Skip to main content

naga/valid/
expression.rs

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#[cfg(test)]
10use alloc::boxed::Box;
11
12#[derive(Clone, Debug, thiserror::Error)]
13#[cfg_attr(test, derive(PartialEq))]
14pub enum ExpressionError {
15    #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")]
16    NotInScope,
17    #[error("Base type {0:?} is not compatible with this expression")]
18    InvalidBaseType(Handle<crate::Expression>),
19    #[error("Accessing with index {0:?} can't be done")]
20    InvalidIndexType(Handle<crate::Expression>),
21    #[error("Accessing {0:?} via a negative index is invalid")]
22    NegativeIndex(Handle<crate::Expression>),
23    #[error("Accessing index {1} is out of {0:?} bounds")]
24    IndexOutOfBounds(Handle<crate::Expression>, u32),
25    #[error("Function argument {0:?} doesn't exist")]
26    FunctionArgumentDoesntExist(u32),
27    #[error("Loading of {0:?} can't be done")]
28    InvalidPointerType(Handle<crate::Expression>),
29    #[error("Array length of {0:?} can't be done")]
30    InvalidArrayType(Handle<crate::Expression>),
31    #[error("Get intersection of {0:?} can't be done")]
32    InvalidRayQueryType(Handle<crate::Expression>),
33    #[error("Hit object {0:?} is not a pointer to a hit object in the function address space")]
34    InvalidHitObjectType(Handle<crate::Expression>),
35    #[error("Splatting {0:?} can't be done")]
36    InvalidSplatType(Handle<crate::Expression>),
37    #[error("Swizzling {0:?} can't be done")]
38    InvalidVectorType(Handle<crate::Expression>),
39    #[error("Swizzle component {0:?} is outside of vector size {1:?}")]
40    InvalidSwizzleComponent(crate::SwizzleComponent, crate::VectorSize),
41    #[error(transparent)]
42    Compose(#[from] super::ComposeError),
43    #[error("Cannot construct zero value of {0:?} because it is not a constructible type")]
44    InvalidZeroValue(Handle<crate::Type>),
45    #[error(transparent)]
46    IndexableLength(#[from] IndexableLengthError),
47    #[error("Operation {0:?} can't work with {1:?}")]
48    InvalidUnaryOperandType(crate::UnaryOperator, Handle<crate::Expression>),
49    #[error(
50        "Operation {:?} can't work with {:?} (of type {:?}) and {:?} (of type {:?})",
51        op,
52        lhs_expr,
53        lhs_type,
54        rhs_expr,
55        rhs_type
56    )]
57    InvalidBinaryOperandTypes {
58        op: crate::BinaryOperator,
59        lhs_expr: Handle<crate::Expression>,
60        lhs_type: crate::TypeInner,
61        rhs_expr: Handle<crate::Expression>,
62        rhs_type: crate::TypeInner,
63    },
64    #[error("Expected selection argument types to match, but reject value of type {reject:?} does not match accept value of value {accept:?}")]
65    SelectValuesTypeMismatch {
66        accept: crate::TypeInner,
67        reject: crate::TypeInner,
68    },
69    #[error("Expected selection condition to be a boolean value, got {actual:?}")]
70    SelectConditionNotABool { actual: crate::TypeInner },
71    #[error("Relational argument {0:?} is not a boolean vector")]
72    InvalidBooleanVector(Handle<crate::Expression>),
73    #[error("Relational argument {0:?} is not a float")]
74    InvalidFloatArgument(Handle<crate::Expression>),
75    #[error("Type resolution failed")]
76    Type(#[from] ResolveError),
77    #[error("Not a global variable")]
78    ExpectedGlobalVariable,
79    #[error("Not a global variable or a function argument")]
80    ExpectedGlobalOrArgument,
81    #[error("Needs to be an binding array instead of {0:?}")]
82    ExpectedBindingArrayType(Handle<crate::Type>),
83    #[error("Needs to be an image instead of {0:?}")]
84    ExpectedImageType(Handle<crate::Type>),
85    #[error("Needs to be an image instead of {0:?}")]
86    ExpectedSamplerType(Handle<crate::Type>),
87    #[error("Unable to operate on image class {0:?}")]
88    InvalidImageClass(crate::ImageClass),
89    #[error("Image atomics are not supported for storage format {0:?}")]
90    InvalidImageFormat(crate::StorageFormat),
91    #[error("Image atomics require atomic storage access, {0:?} is insufficient")]
92    InvalidImageStorageAccess(crate::StorageAccess),
93    #[error("Derivatives can only be taken from scalar and vector floats")]
94    InvalidDerivative,
95    #[error("Image array index parameter is misplaced")]
96    InvalidImageArrayIndex,
97    #[error("Cannot textureLoad from a specific multisample sample on a non-multisampled image.")]
98    InvalidImageSampleSelector,
99    #[error("Cannot textureLoad from a multisampled image without specifying a sample.")]
100    MissingImageSampleSelector,
101    #[error("Cannot textureLoad with a specific mip level on a non-mipmapped image.")]
102    InvalidImageLevelSelector,
103    #[error("Cannot textureLoad from a mipmapped image without specifying a level.")]
104    MissingImageLevelSelector,
105    #[error("Image array index type of {0:?} is not an integer scalar")]
106    InvalidImageArrayIndexType(Handle<crate::Expression>),
107    #[error("Image sample or level-of-detail index's type of {0:?} is not an integer scalar")]
108    InvalidImageOtherIndexType(Handle<crate::Expression>),
109    #[error("Image coordinate type of {1:?} does not match dimension {0:?}")]
110    InvalidImageCoordinateType(crate::ImageDimension, Handle<crate::Expression>),
111    #[error("Comparison sampling mismatch: image has class {image:?}, but the sampler is comparison={sampler}, and the reference was provided={has_ref}")]
112    ComparisonSamplingMismatch {
113        image: crate::ImageClass,
114        sampler: bool,
115        has_ref: bool,
116    },
117    #[error("Sample offset must be a const-expression")]
118    InvalidSampleOffsetExprType,
119    #[error("Sample offset constant {1:?} doesn't match the image dimension {0:?}")]
120    InvalidSampleOffset(crate::ImageDimension, Handle<crate::Expression>),
121    #[error("Depth reference {0:?} is not a scalar float")]
122    InvalidDepthReference(Handle<crate::Expression>),
123    #[error("Depth sample level can only be Auto or Zero")]
124    InvalidDepthSampleLevel,
125    #[error("Gather level can only be Zero")]
126    InvalidGatherLevel,
127    #[error("Gather component {0:?} doesn't exist in the image")]
128    InvalidGatherComponent(crate::SwizzleComponent),
129    #[error("Gather can't be done for image dimension {0:?}")]
130    InvalidGatherDimension(crate::ImageDimension),
131    #[error("Sample level (exact) type {0:?} has an invalid type")]
132    InvalidSampleLevelExactType(Handle<crate::Expression>),
133    #[error("Sample level (bias) type {0:?} is not a scalar float")]
134    InvalidSampleLevelBiasType(Handle<crate::Expression>),
135    #[error("Bias can't be done for image dimension {0:?}")]
136    InvalidSampleLevelBiasDimension(crate::ImageDimension),
137    #[error("Sample level (gradient) of {1:?} doesn't match the image dimension {0:?}")]
138    InvalidSampleLevelGradientType(crate::ImageDimension, Handle<crate::Expression>),
139    #[error("Clamping sample coordinate to edge is not supported with {0}")]
140    InvalidSampleClampCoordinateToEdge(alloc::string::String),
141    #[error("Unable to cast")]
142    InvalidCastArgument,
143    #[error("Unable to bitcast the argument to {0:?}")]
144    InvalidBitcast(Handle<crate::Type>),
145    #[error("Invalid argument count for {0:?}")]
146    WrongArgumentCount(crate::MathFunction),
147    #[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")]
148    InvalidArgumentType(crate::MathFunction, u32, Handle<crate::Expression>),
149    #[error(
150        "workgroupUniformLoad result type can't be {0:?}. It can only be a constructible type."
151    )]
152    InvalidWorkGroupUniformLoadResultType(Handle<crate::Type>),
153    #[error("Shader requires capability {0:?}")]
154    MissingCapabilities(super::Capabilities),
155    #[error(transparent)]
156    Literal(#[from] LiteralError),
157    #[error("{0:?} is not supported for Width {2} {1:?} arguments yet, see https://github.com/gfx-rs/wgpu/issues/5276")]
158    UnsupportedWidth(crate::MathFunction, crate::ScalarKind, crate::Bytes),
159    #[error("Invalid operand for cooperative op")]
160    InvalidCooperativeOperand(Handle<crate::Expression>),
161    #[error("Shift amount exceeds the bit width of {lhs_type:?}")]
162    ShiftAmountTooLarge {
163        lhs_type: crate::TypeInner,
164        rhs_expr: Handle<crate::Expression>,
165    },
166    #[error("Division by zero")]
167    DivideByZero,
168}
169
170#[derive(Clone, Debug, thiserror::Error)]
171#[cfg_attr(test, derive(PartialEq))]
172pub enum ConstExpressionError {
173    #[error("The expression is not a constant or override expression")]
174    NonConstOrOverride,
175    #[error("The expression is not a fully evaluated constant expression")]
176    NonFullyEvaluatedConst,
177    #[error(transparent)]
178    Compose(#[from] super::ComposeError),
179    #[error("Splatting {0:?} can't be done")]
180    InvalidSplatType(Handle<crate::Expression>),
181    #[error("Type resolution failed")]
182    Type(#[from] ResolveError),
183    #[error(transparent)]
184    Literal(#[from] LiteralError),
185    #[error(transparent)]
186    Width(#[from] super::r#type::WidthError),
187}
188
189#[derive(Clone, Debug, thiserror::Error)]
190#[cfg_attr(test, derive(PartialEq))]
191pub enum LiteralError {
192    #[error("Float literal is NaN")]
193    NaN,
194    #[error("Float literal is infinite")]
195    Infinity,
196    #[error(transparent)]
197    Width(#[from] super::r#type::WidthError),
198}
199
200struct ExpressionTypeResolver<'a> {
201    root: Handle<crate::Expression>,
202    types: &'a UniqueArena<crate::Type>,
203    info: &'a FunctionInfo,
204}
205
206impl core::ops::Index<Handle<crate::Expression>> for ExpressionTypeResolver<'_> {
207    type Output = crate::TypeInner;
208
209    #[allow(clippy::panic)]
210    fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
211        if handle < self.root {
212            self.info[handle].ty.inner_with(self.types)
213        } else {
214            // `Validator::validate_module_handles` should have caught this.
215            panic!(
216                "Depends on {:?}, which has not been processed yet",
217                self.root
218            )
219        }
220    }
221}
222
223impl super::Validator {
224    pub(super) fn validate_const_expression(
225        &self,
226        handle: Handle<crate::Expression>,
227        gctx: crate::proc::GlobalCtx,
228        mod_info: &ModuleInfo,
229        global_expr_kind: &crate::proc::ExpressionKindTracker,
230    ) -> Result<(), ConstExpressionError> {
231        use crate::Expression as E;
232
233        if !global_expr_kind.is_const_or_override(handle) {
234            return Err(ConstExpressionError::NonConstOrOverride);
235        }
236
237        match gctx.global_expressions[handle] {
238            E::Literal(literal) => {
239                self.validate_literal(literal)?;
240            }
241            E::Constant(_) | E::ZeroValue(_) => {}
242            E::Compose { ref components, ty } => {
243                validate_compose(
244                    ty,
245                    gctx,
246                    components.iter().map(|&handle| mod_info[handle].clone()),
247                )?;
248            }
249            E::Splat { value, .. } => match *mod_info[value].inner_with(gctx.types) {
250                crate::TypeInner::Scalar { .. } => {}
251                _ => return Err(ConstExpressionError::InvalidSplatType(value)),
252            },
253            _ if global_expr_kind.is_const(handle) || self.overrides_resolved => {
254                return Err(ConstExpressionError::NonFullyEvaluatedConst)
255            }
256            // the constant evaluator will report errors about override-expressions
257            _ => {}
258        }
259
260        Ok(())
261    }
262
263    /// Return an error if a constant shift amount in `right` exceeds the bit
264    /// width of `left_ty`.
265    ///
266    /// This function promises to return an error in cases where (1) the
267    /// expression is well-typed, (2) `left_ty` is a concrete integer, and
268    /// (3) the shift will overflow. It does not return an error in cases where
269    /// the expression is not well-typed (e.g. vector dimension mismatch),
270    /// because those will be rejected elsewhere.
271    fn validate_constant_shift_amounts(
272        left_ty: &crate::TypeInner,
273        right: Handle<crate::Expression>,
274        module: &crate::Module,
275        function: &crate::Function,
276    ) -> Result<(), ExpressionError> {
277        fn is_overflowing_shift(
278            left_ty: &crate::TypeInner,
279            right: Handle<crate::Expression>,
280            module: &crate::Module,
281            function: &crate::Function,
282        ) -> bool {
283            let Some((vec_size, scalar)) = left_ty.vector_size_and_scalar() else {
284                return false;
285            };
286            if !matches!(
287                scalar.kind,
288                crate::ScalarKind::Sint | crate::ScalarKind::Uint
289            ) {
290                return false;
291            }
292            let lhs_bits = u32::from(8 * scalar.width);
293            if vec_size.is_none() {
294                let shift_amount = module
295                    .to_ctx()
296                    .get_const_val_from::<u32, _>(right, &function.expressions);
297                shift_amount.ok().is_some_and(|s| s >= lhs_bits)
298            } else {
299                match function.expressions[right] {
300                    crate::Expression::ZeroValue(_) => false, // zero shift does not overflow
301                    crate::Expression::Splat { value, .. } => module
302                        .to_ctx()
303                        .get_const_val_from::<u32, _>(value, &function.expressions)
304                        .ok()
305                        .is_some_and(|s| s >= lhs_bits),
306                    crate::Expression::Compose {
307                        ty: _,
308                        ref components,
309                    } => components.iter().any(|comp| {
310                        module
311                            .to_ctx()
312                            .get_const_val_from::<u32, _>(*comp, &function.expressions)
313                            .ok()
314                            .is_some_and(|s| s >= lhs_bits)
315                    }),
316                    _ => false,
317                }
318            }
319        }
320
321        if is_overflowing_shift(left_ty, right, module, function) {
322            Err(ExpressionError::ShiftAmountTooLarge {
323                lhs_type: left_ty.clone(),
324                rhs_expr: right,
325            })
326        } else {
327            Ok(())
328        }
329    }
330
331    /// Return an error if a constant divisor in `right` evaluates to zero for
332    /// an integer division or remainder operation.
333    ///
334    /// This function promises to return an error in cases where (1) the
335    /// expression is well-typed, (2) `left_ty` is a concrete integer or a
336    /// vector, and (3) `right` is a const-expression that evaluates to zero.
337    /// It does not return an error in cases where the expression is not
338    /// well-typed (e.g. vector dimension mismatch), because those will be
339    /// rejected elsewhere.
340    fn validate_constant_divisor(
341        left_ty: &crate::TypeInner,
342        right: Handle<crate::Expression>,
343        module: &crate::Module,
344        function: &crate::Function,
345    ) -> Result<(), ExpressionError> {
346        fn contains_zero(
347            handle: Handle<crate::Expression>,
348            expressions: &crate::Arena<crate::Expression>,
349            module: &crate::Module,
350        ) -> bool {
351            match expressions[handle] {
352                crate::Expression::Literal(_) | crate::Expression::ZeroValue(_) => module
353                    .to_ctx()
354                    .get_const_val_from::<u32, _>(handle, expressions)
355                    .ok()
356                    .is_some_and(|v| v == 0),
357                crate::Expression::Splat { value, .. } => contains_zero(value, expressions, module),
358                crate::Expression::Compose { ref components, .. } => components
359                    .iter()
360                    .any(|&comp| contains_zero(comp, expressions, module)),
361                crate::Expression::Constant(c) => {
362                    contains_zero(module.constants[c].init, &module.global_expressions, module)
363                }
364                _ => false,
365            }
366        }
367
368        let Some((_, scalar)) = left_ty.vector_size_and_scalar() else {
369            return Ok(());
370        };
371        if !matches!(
372            scalar.kind,
373            crate::ScalarKind::Sint | crate::ScalarKind::Uint
374        ) {
375            return Ok(());
376        }
377
378        if contains_zero(right, &function.expressions, module) {
379            Err(ExpressionError::DivideByZero)
380        } else {
381            Ok(())
382        }
383    }
384
385    #[allow(clippy::too_many_arguments)]
386    pub(super) fn validate_expression(
387        &self,
388        root: Handle<crate::Expression>,
389        expression: &crate::Expression,
390        function: &crate::Function,
391        module: &crate::Module,
392        info: &FunctionInfo,
393        mod_info: &ModuleInfo,
394        expr_kind: &crate::proc::ExpressionKindTracker,
395    ) -> Result<ShaderStages, ExpressionError> {
396        use crate::{Expression as E, Scalar as Sc, ScalarKind as Sk, TypeInner as Ti};
397
398        let resolver = ExpressionTypeResolver {
399            root,
400            types: &module.types,
401            info,
402        };
403
404        let stages = match *expression {
405            E::Access { base, index } => {
406                let base_type = &resolver[base];
407                match *base_type {
408                    Ti::Matrix { .. }
409                    | Ti::Vector { .. }
410                    | Ti::Array { .. }
411                    | Ti::Pointer { .. }
412                    | Ti::ValuePointer { size: Some(_), .. }
413                    | Ti::BindingArray { .. } => {}
414                    ref other => {
415                        log::debug!("Indexing of {other:?}");
416                        return Err(ExpressionError::InvalidBaseType(base));
417                    }
418                };
419                match resolver[index] {
420                    //TODO: only allow one of these
421                    Ti::Scalar(Sc {
422                        kind: Sk::Sint | Sk::Uint,
423                        ..
424                    }) => {}
425                    ref other => {
426                        log::debug!("Indexing by {other:?}");
427                        return Err(ExpressionError::InvalidIndexType(index));
428                    }
429                }
430
431                // If index is const we can do check for non-negative index
432                match module
433                    .to_ctx()
434                    .get_const_val_from(index, &function.expressions)
435                {
436                    Ok(value) => {
437                        let length = if self.overrides_resolved {
438                            base_type.indexable_length_resolved(module)
439                        } else {
440                            base_type.indexable_length_pending(module)
441                        }?;
442                        // If we know both the length and the index, we can do the
443                        // bounds check now.
444                        if let crate::proc::IndexableLength::Known(known_length) = length {
445                            if value >= known_length {
446                                return Err(ExpressionError::IndexOutOfBounds(base, value));
447                            }
448                        }
449                    }
450                    Err(crate::proc::ConstValueError::Negative) => {
451                        return Err(ExpressionError::NegativeIndex(base))
452                    }
453                    Err(crate::proc::ConstValueError::NonConst) => {}
454                    Err(crate::proc::ConstValueError::InvalidType) => {
455                        return Err(ExpressionError::InvalidIndexType(index))
456                    }
457                }
458
459                ShaderStages::all()
460            }
461            E::AccessIndex { base, index } => {
462                fn resolve_index_limit(
463                    module: &crate::Module,
464                    top: Handle<crate::Expression>,
465                    ty: &crate::TypeInner,
466                    top_level: bool,
467                ) -> Result<u32, ExpressionError> {
468                    let limit = match *ty {
469                        Ti::Vector { size, .. }
470                        | Ti::ValuePointer {
471                            size: Some(size), ..
472                        } => size as u32,
473                        Ti::Matrix { columns, .. } => columns as u32,
474                        Ti::Array {
475                            size: crate::ArraySize::Constant(len),
476                            ..
477                        } => len.get(),
478                        Ti::Array { .. } | Ti::BindingArray { .. } => u32::MAX, // can't statically know, but need run-time checks
479                        Ti::Pointer { base, .. } if top_level => {
480                            resolve_index_limit(module, top, &module.types[base].inner, false)?
481                        }
482                        Ti::Struct { ref members, .. } => members.len() as u32,
483                        ref other => {
484                            log::debug!("Indexing of {other:?}");
485                            return Err(ExpressionError::InvalidBaseType(top));
486                        }
487                    };
488                    Ok(limit)
489                }
490
491                let limit = resolve_index_limit(module, base, &resolver[base], true)?;
492                if index >= limit {
493                    return Err(ExpressionError::IndexOutOfBounds(base, index));
494                }
495                ShaderStages::all()
496            }
497            E::Splat { size: _, value } => match resolver[value] {
498                Ti::Scalar { .. } => ShaderStages::all(),
499                ref other => {
500                    log::debug!("Splat scalar type {other:?}");
501                    return Err(ExpressionError::InvalidSplatType(value));
502                }
503            },
504            E::Swizzle {
505                size,
506                vector,
507                pattern,
508            } => {
509                let vec_size = match resolver[vector] {
510                    Ti::Vector { size: vec_size, .. } => vec_size,
511                    ref other => {
512                        log::debug!("Swizzle vector type {other:?}");
513                        return Err(ExpressionError::InvalidVectorType(vector));
514                    }
515                };
516                for &sc in pattern[..size as usize].iter() {
517                    if sc as u8 >= vec_size as u8 {
518                        return Err(ExpressionError::InvalidSwizzleComponent(sc, vec_size));
519                    }
520                }
521                ShaderStages::all()
522            }
523            E::Literal(literal) => {
524                self.validate_literal(literal)?;
525                ShaderStages::all()
526            }
527            E::Constant(_) | E::Override(_) => ShaderStages::all(),
528            E::ZeroValue(ty) => {
529                if !mod_info[ty].contains(TypeFlags::CONSTRUCTIBLE) {
530                    return Err(ExpressionError::InvalidZeroValue(ty));
531                }
532                // Opaque handle types cannot be constructed, even though their
533                // `CONSTRUCTIBLE` flag lets them be declared as locals.
534                if matches!(
535                    module.types[ty].inner,
536                    crate::TypeInner::RayQuery { .. } | crate::TypeInner::HitObject
537                ) {
538                    return Err(ExpressionError::InvalidZeroValue(ty));
539                }
540                ShaderStages::all()
541            }
542            E::Compose { ref components, ty } => {
543                validate_compose(
544                    ty,
545                    module.to_ctx(),
546                    components.iter().map(|&handle| info[handle].ty.clone()),
547                )?;
548                ShaderStages::all()
549            }
550            E::FunctionArgument(index) => {
551                if index >= function.arguments.len() as u32 {
552                    return Err(ExpressionError::FunctionArgumentDoesntExist(index));
553                }
554                ShaderStages::all()
555            }
556            E::GlobalVariable(_handle) => ShaderStages::all(),
557            E::LocalVariable(_handle) => ShaderStages::all(),
558            E::Load { pointer } => {
559                match resolver[pointer] {
560                    Ti::Pointer { base, .. }
561                        if self.types[base.index()]
562                            .flags
563                            .contains(TypeFlags::SIZED | TypeFlags::DATA)
564                            && !matches!(module.types[base].inner, Ti::HitObject) => {}
565                    Ti::ValuePointer { .. } => {}
566                    ref other => {
567                        log::debug!("Loading {other:?}");
568                        return Err(ExpressionError::InvalidPointerType(pointer));
569                    }
570                }
571                ShaderStages::all()
572            }
573            E::ImageSample {
574                image,
575                sampler,
576                gather,
577                coordinate,
578                array_index,
579                offset,
580                level,
581                depth_ref,
582                clamp_to_edge,
583            } => {
584                // check the validity of expressions
585                let image_ty = Self::global_var_ty(module, function, image)?;
586                let sampler_ty = Self::global_var_ty(module, function, sampler)?;
587
588                let comparison = match module.types[sampler_ty].inner {
589                    Ti::Sampler { comparison } => comparison,
590                    _ => return Err(ExpressionError::ExpectedSamplerType(sampler_ty)),
591                };
592
593                let (class, dim) = match module.types[image_ty].inner {
594                    Ti::Image {
595                        class,
596                        arrayed,
597                        dim,
598                    } => {
599                        // check the array property
600                        if arrayed != array_index.is_some() {
601                            return Err(ExpressionError::InvalidImageArrayIndex);
602                        }
603                        if let Some(expr) = array_index {
604                            match resolver[expr] {
605                                Ti::Scalar(Sc {
606                                    kind: Sk::Sint | Sk::Uint,
607                                    ..
608                                }) => {}
609                                _ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)),
610                            }
611                        }
612                        (class, dim)
613                    }
614                    _ => return Err(ExpressionError::ExpectedImageType(image_ty)),
615                };
616
617                // check sampling and comparison properties
618                let image_depth = match class {
619                    crate::ImageClass::Sampled {
620                        kind: crate::ScalarKind::Float,
621                        multi: false,
622                    } => false,
623                    crate::ImageClass::Sampled {
624                        kind: crate::ScalarKind::Uint | crate::ScalarKind::Sint,
625                        multi: false,
626                    } if gather.is_some() => false,
627                    crate::ImageClass::External => false,
628                    crate::ImageClass::Depth { multi: false } => true,
629                    _ => return Err(ExpressionError::InvalidImageClass(class)),
630                };
631                if comparison != depth_ref.is_some() || (comparison && !image_depth) {
632                    return Err(ExpressionError::ComparisonSamplingMismatch {
633                        image: class,
634                        sampler: comparison,
635                        has_ref: depth_ref.is_some(),
636                    });
637                }
638
639                // check texture coordinates type
640                let num_components = match dim {
641                    crate::ImageDimension::D1 => 1,
642                    crate::ImageDimension::D2 => 2,
643                    crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3,
644                };
645                match resolver[coordinate] {
646                    Ti::Scalar(Sc {
647                        kind: Sk::Float, ..
648                    }) if num_components == 1 => {}
649                    Ti::Vector {
650                        size,
651                        scalar:
652                            Sc {
653                                kind: Sk::Float, ..
654                            },
655                    } if size as u32 == num_components => {}
656                    _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)),
657                }
658
659                // check constant offset
660                if let Some(const_expr) = offset {
661                    if !expr_kind.is_const(const_expr) {
662                        return Err(ExpressionError::InvalidSampleOffsetExprType);
663                    }
664
665                    match resolver[const_expr] {
666                        Ti::Scalar(Sc { kind: Sk::Sint, .. }) if num_components == 1 => {}
667                        Ti::Vector {
668                            size,
669                            scalar: Sc { kind: Sk::Sint, .. },
670                        } if size as u32 == num_components => {}
671                        _ => {
672                            return Err(ExpressionError::InvalidSampleOffset(dim, const_expr));
673                        }
674                    }
675                }
676
677                // check depth reference type
678                if let Some(expr) = depth_ref {
679                    match resolver[expr] {
680                        Ti::Scalar(Sc {
681                            kind: Sk::Float, ..
682                        }) => {}
683                        _ => return Err(ExpressionError::InvalidDepthReference(expr)),
684                    }
685                    match level {
686                        crate::SampleLevel::Auto | crate::SampleLevel::Zero => {}
687                        _ => return Err(ExpressionError::InvalidDepthSampleLevel),
688                    }
689                }
690
691                if let Some(component) = gather {
692                    match dim {
693                        crate::ImageDimension::D2 | crate::ImageDimension::Cube => {}
694                        crate::ImageDimension::D1 | crate::ImageDimension::D3 => {
695                            return Err(ExpressionError::InvalidGatherDimension(dim))
696                        }
697                    };
698                    let max_component = match class {
699                        crate::ImageClass::Depth { .. } => crate::SwizzleComponent::X,
700                        _ => crate::SwizzleComponent::W,
701                    };
702                    if component > max_component {
703                        return Err(ExpressionError::InvalidGatherComponent(component));
704                    }
705                    match level {
706                        crate::SampleLevel::Zero => {}
707                        _ => return Err(ExpressionError::InvalidGatherLevel),
708                    }
709                }
710
711                // Clamping coordinate to edge is only supported with 2d non-arrayed, sampled images
712                // when sampling from level Zero without any offset, gather, or depth comparison.
713                if clamp_to_edge {
714                    if !matches!(
715                        class,
716                        crate::ImageClass::Sampled {
717                            kind: crate::ScalarKind::Float,
718                            multi: false
719                        } | crate::ImageClass::External
720                    ) {
721                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
722                            alloc::format!("image class `{class:?}`"),
723                        ));
724                    }
725                    if dim != crate::ImageDimension::D2 {
726                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
727                            alloc::format!("image dimension `{dim:?}`"),
728                        ));
729                    }
730                    if gather.is_some() {
731                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
732                            "gather".into(),
733                        ));
734                    }
735                    if array_index.is_some() {
736                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
737                            "array index".into(),
738                        ));
739                    }
740                    if offset.is_some() {
741                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
742                            "offset".into(),
743                        ));
744                    }
745                    if level != crate::SampleLevel::Zero {
746                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
747                            "non-zero level".into(),
748                        ));
749                    }
750                    if depth_ref.is_some() {
751                        return Err(ExpressionError::InvalidSampleClampCoordinateToEdge(
752                            "depth comparison".into(),
753                        ));
754                    }
755                }
756
757                // External textures can only be sampled using clamp_to_edge.
758                if matches!(class, crate::ImageClass::External) && !clamp_to_edge {
759                    return Err(ExpressionError::InvalidImageClass(class));
760                }
761
762                // check level properties
763                match level {
764                    crate::SampleLevel::Auto => ShaderStages::FRAGMENT,
765                    crate::SampleLevel::Zero => ShaderStages::all(),
766                    crate::SampleLevel::Exact(expr) => {
767                        match class {
768                            crate::ImageClass::Depth { .. } => match resolver[expr] {
769                                Ti::Scalar(Sc {
770                                    kind: Sk::Sint | Sk::Uint,
771                                    ..
772                                }) => {}
773                                _ => {
774                                    return Err(ExpressionError::InvalidSampleLevelExactType(expr))
775                                }
776                            },
777                            _ => match resolver[expr] {
778                                Ti::Scalar(Sc {
779                                    kind: Sk::Float, ..
780                                }) => {}
781                                _ => {
782                                    return Err(ExpressionError::InvalidSampleLevelExactType(expr))
783                                }
784                            },
785                        }
786                        ShaderStages::all()
787                    }
788                    crate::SampleLevel::Bias(expr) => {
789                        match resolver[expr] {
790                            Ti::Scalar(Sc {
791                                kind: Sk::Float, ..
792                            }) => {}
793                            _ => return Err(ExpressionError::InvalidSampleLevelBiasType(expr)),
794                        }
795                        match class {
796                            crate::ImageClass::Sampled {
797                                kind: Sk::Float,
798                                multi: false,
799                            } => {
800                                if dim == crate::ImageDimension::D1 {
801                                    return Err(ExpressionError::InvalidSampleLevelBiasDimension(
802                                        dim,
803                                    ));
804                                }
805                            }
806                            _ => return Err(ExpressionError::InvalidImageClass(class)),
807                        }
808                        ShaderStages::FRAGMENT
809                    }
810                    crate::SampleLevel::Gradient { x, y } => {
811                        match resolver[x] {
812                            Ti::Scalar(Sc {
813                                kind: Sk::Float, ..
814                            }) if num_components == 1 => {}
815                            Ti::Vector {
816                                size,
817                                scalar:
818                                    Sc {
819                                        kind: Sk::Float, ..
820                                    },
821                            } if size as u32 == num_components => {}
822                            _ => {
823                                return Err(ExpressionError::InvalidSampleLevelGradientType(dim, x))
824                            }
825                        }
826                        match resolver[y] {
827                            Ti::Scalar(Sc {
828                                kind: Sk::Float, ..
829                            }) if num_components == 1 => {}
830                            Ti::Vector {
831                                size,
832                                scalar:
833                                    Sc {
834                                        kind: Sk::Float, ..
835                                    },
836                            } if size as u32 == num_components => {}
837                            _ => {
838                                return Err(ExpressionError::InvalidSampleLevelGradientType(dim, y))
839                            }
840                        }
841                        ShaderStages::all()
842                    }
843                }
844            }
845            E::ImageLoad {
846                image,
847                coordinate,
848                array_index,
849                sample,
850                level,
851            } => {
852                let ty = Self::global_var_ty(module, function, image)?;
853                let Ti::Image {
854                    class,
855                    arrayed,
856                    dim,
857                } = module.types[ty].inner
858                else {
859                    return Err(ExpressionError::ExpectedImageType(ty));
860                };
861
862                match resolver[coordinate].image_storage_coordinates() {
863                    Some(coord_dim) if coord_dim == dim => {}
864                    _ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)),
865                };
866                if arrayed != array_index.is_some() {
867                    return Err(ExpressionError::InvalidImageArrayIndex);
868                }
869                if let Some(expr) = array_index {
870                    if !matches!(resolver[expr], Ti::Scalar(Sc::I32 | Sc::U32)) {
871                        return Err(ExpressionError::InvalidImageArrayIndexType(expr));
872                    }
873                }
874
875                match (sample, class.is_multisampled()) {
876                    (None, false) => {}
877                    (Some(sample), true) => {
878                        if !matches!(resolver[sample], Ti::Scalar(Sc::I32 | Sc::U32)) {
879                            return Err(ExpressionError::InvalidImageOtherIndexType(sample));
880                        }
881                    }
882                    (Some(_), false) => {
883                        return Err(ExpressionError::InvalidImageSampleSelector);
884                    }
885                    (None, true) => {
886                        return Err(ExpressionError::MissingImageSampleSelector);
887                    }
888                }
889
890                match (level, class.is_mipmapped()) {
891                    (None, false) => {}
892                    (Some(level), true) => match resolver[level] {
893                        Ti::Scalar(Sc {
894                            kind: Sk::Sint | Sk::Uint,
895                            width: _,
896                        }) => {}
897                        _ => return Err(ExpressionError::InvalidImageArrayIndexType(level)),
898                    },
899                    (Some(_), false) => {
900                        return Err(ExpressionError::InvalidImageLevelSelector);
901                    }
902                    (None, true) => {
903                        return Err(ExpressionError::MissingImageLevelSelector);
904                    }
905                }
906                ShaderStages::all()
907            }
908            E::ImageQuery { image, query } => {
909                let ty = Self::global_var_ty(module, function, image)?;
910                match module.types[ty].inner {
911                    Ti::Image { class, arrayed, .. } => {
912                        let good = match query {
913                            crate::ImageQuery::NumLayers => arrayed,
914                            crate::ImageQuery::Size { level: None } => true,
915                            crate::ImageQuery::Size { level: Some(level) } => {
916                                match resolver[level] {
917                                    Ti::Scalar(Sc::I32 | Sc::U32) => {}
918                                    _ => {
919                                        return Err(ExpressionError::InvalidImageOtherIndexType(
920                                            level,
921                                        ))
922                                    }
923                                }
924                                class.is_mipmapped()
925                            }
926                            crate::ImageQuery::NumLevels => class.is_mipmapped(),
927                            crate::ImageQuery::NumSamples => class.is_multisampled(),
928                        };
929                        if !good {
930                            return Err(ExpressionError::InvalidImageClass(class));
931                        }
932                    }
933                    _ => return Err(ExpressionError::ExpectedImageType(ty)),
934                }
935                ShaderStages::all()
936            }
937            E::Unary { op, expr } => {
938                use crate::UnaryOperator as Uo;
939                let Some((_, scalar)) = resolver[expr].vector_size_and_scalar() else {
940                    return Err(ExpressionError::InvalidUnaryOperandType(op, expr));
941                };
942                match (op, scalar.kind) {
943                    (Uo::Negate, Sk::Float | Sk::Sint) => {}
944                    (Uo::LogicalNot, Sk::Bool) => {}
945                    (Uo::BitwiseNot, Sk::Sint | Sk::Uint) => {}
946                    _ => return Err(ExpressionError::InvalidUnaryOperandType(op, expr)),
947                }
948                ShaderStages::all()
949            }
950            E::Binary { op, left, right } => {
951                use crate::BinaryOperator as Bo;
952                let left_inner = &resolver[left];
953                let right_inner = &resolver[right];
954                let good = match op {
955                    Bo::Add | Bo::Subtract => match *left_inner {
956                        Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
957                            Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
958                            Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => false,
959                        },
960                        Ti::Matrix { .. } | Ti::CooperativeMatrix { .. } => {
961                            left_inner == right_inner
962                        }
963                        _ => false,
964                    },
965                    Bo::Divide | Bo::Modulo => match *left_inner {
966                        Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
967                            Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
968                            Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => false,
969                        },
970                        _ => false,
971                    },
972                    Bo::Multiply => {
973                        let kind_allowed = match left_inner.scalar_kind() {
974                            Some(Sk::Uint | Sk::Sint | Sk::Float) => true,
975                            Some(Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat) | None => false,
976                        };
977                        let types_match = match (left_inner, right_inner) {
978                            // Straight scalar and mixed scalar/vector.
979                            (&Ti::Scalar(scalar1), &Ti::Scalar(scalar2))
980                            | (
981                                &Ti::Vector {
982                                    scalar: scalar1, ..
983                                },
984                                &Ti::Scalar(scalar2),
985                            )
986                            | (
987                                &Ti::Scalar(scalar1),
988                                &Ti::Vector {
989                                    scalar: scalar2, ..
990                                },
991                            ) => scalar1 == scalar2,
992                            // Scalar * matrix.
993                            (
994                                &Ti::Scalar(Sc {
995                                    kind: Sk::Float, ..
996                                }),
997                                &Ti::Matrix { .. },
998                            )
999                            | (
1000                                &Ti::Matrix { .. },
1001                                &Ti::Scalar(Sc {
1002                                    kind: Sk::Float, ..
1003                                }),
1004                            ) => true,
1005                            // Vector * vector.
1006                            (
1007                                &Ti::Vector {
1008                                    size: size1,
1009                                    scalar: scalar1,
1010                                },
1011                                &Ti::Vector {
1012                                    size: size2,
1013                                    scalar: scalar2,
1014                                },
1015                            ) => scalar1 == scalar2 && size1 == size2,
1016                            // Matrix * vector.
1017                            (
1018                                &Ti::Matrix { columns, .. },
1019                                &Ti::Vector {
1020                                    size,
1021                                    scalar:
1022                                        Sc {
1023                                            kind: Sk::Float, ..
1024                                        },
1025                                },
1026                            ) => columns == size,
1027                            // Vector * matrix.
1028                            (
1029                                &Ti::Vector {
1030                                    size,
1031                                    scalar:
1032                                        Sc {
1033                                            kind: Sk::Float, ..
1034                                        },
1035                                },
1036                                &Ti::Matrix { rows, .. },
1037                            ) => size == rows,
1038                            // Matrix * matrix.
1039                            (&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => {
1040                                columns == rows
1041                            }
1042                            // Scalar * coop matrix.
1043                            (&Ti::Scalar(s1), &Ti::CooperativeMatrix { scalar: s2, .. })
1044                            | (&Ti::CooperativeMatrix { scalar: s1, .. }, &Ti::Scalar(s2)) => {
1045                                s1 == s2
1046                            }
1047                            _ => false,
1048                        };
1049                        let left_width = left_inner.scalar_width().unwrap_or(0);
1050                        let right_width = right_inner.scalar_width().unwrap_or(0);
1051                        kind_allowed && types_match && left_width == right_width
1052                    }
1053                    Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner,
1054                    Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => {
1055                        match *left_inner {
1056                            Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
1057                                Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
1058                                Sk::Bool | Sk::AbstractInt | Sk::AbstractFloat => false,
1059                            },
1060                            ref other => {
1061                                log::debug!("Op {op:?} left type {other:?}");
1062                                false
1063                            }
1064                        }
1065                    }
1066                    Bo::LogicalAnd | Bo::LogicalOr => match *left_inner {
1067                        Ti::Scalar(Sc { kind: Sk::Bool, .. })
1068                        | Ti::Vector {
1069                            scalar: Sc { kind: Sk::Bool, .. },
1070                            ..
1071                        } => left_inner == right_inner,
1072                        ref other => {
1073                            log::debug!("Op {op:?} left type {other:?}");
1074                            false
1075                        }
1076                    },
1077                    Bo::And | Bo::InclusiveOr => match *left_inner {
1078                        Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
1079                            Sk::Bool | Sk::Sint | Sk::Uint => left_inner == right_inner,
1080                            Sk::Float | Sk::AbstractInt | Sk::AbstractFloat => false,
1081                        },
1082                        ref other => {
1083                            log::debug!("Op {op:?} left type {other:?}");
1084                            false
1085                        }
1086                    },
1087                    Bo::ExclusiveOr => match *left_inner {
1088                        Ti::Scalar(scalar) | Ti::Vector { scalar, .. } => match scalar.kind {
1089                            Sk::Sint | Sk::Uint => left_inner == right_inner,
1090                            Sk::Bool | Sk::Float | Sk::AbstractInt | Sk::AbstractFloat => false,
1091                        },
1092                        ref other => {
1093                            log::debug!("Op {op:?} left type {other:?}");
1094                            false
1095                        }
1096                    },
1097                    Bo::ShiftLeft | Bo::ShiftRight => {
1098                        let (base_size, base_scalar) = match *left_inner {
1099                            Ti::Scalar(scalar) => (Ok(None), scalar),
1100                            Ti::Vector { size, scalar } => (Ok(Some(size)), scalar),
1101                            ref other => {
1102                                log::debug!("Op {op:?} base type {other:?}");
1103                                (Err(()), Sc::BOOL)
1104                            }
1105                        };
1106                        let shift_size = match *right_inner {
1107                            Ti::Scalar(Sc { kind: Sk::Uint, .. }) => Ok(None),
1108                            Ti::Vector {
1109                                size,
1110                                scalar: Sc { kind: Sk::Uint, .. },
1111                            } => Ok(Some(size)),
1112                            ref other => {
1113                                log::debug!("Op {op:?} shift type {other:?}");
1114                                Err(())
1115                            }
1116                        };
1117                        match base_scalar.kind {
1118                            Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size,
1119                            Sk::Float | Sk::AbstractInt | Sk::AbstractFloat | Sk::Bool => false,
1120                        }
1121                    }
1122                };
1123                if !good {
1124                    log::debug!(
1125                        "Left: {:?} of type {:?}",
1126                        function.expressions[left],
1127                        left_inner
1128                    );
1129                    log::debug!(
1130                        "Right: {:?} of type {:?}",
1131                        function.expressions[right],
1132                        right_inner
1133                    );
1134                    return Err(ExpressionError::InvalidBinaryOperandTypes {
1135                        op,
1136                        lhs_expr: left,
1137                        lhs_type: left_inner.clone(),
1138                        rhs_expr: right,
1139                        rhs_type: right_inner.clone(),
1140                    });
1141                }
1142                // For shift operations, check if the constant shift amount exceeds the bit width
1143                if matches!(op, Bo::ShiftLeft | Bo::ShiftRight) {
1144                    Self::validate_constant_shift_amounts(left_inner, right, module, function)?;
1145                }
1146                // For integer division or remainder, check if the constant divisor is zero
1147                if matches!(op, Bo::Divide | Bo::Modulo) {
1148                    Self::validate_constant_divisor(left_inner, right, module, function)?;
1149                }
1150                ShaderStages::all()
1151            }
1152            E::Select {
1153                condition,
1154                accept,
1155                reject,
1156            } => {
1157                let accept_inner = &resolver[accept];
1158                let reject_inner = &resolver[reject];
1159                let condition_ty = &resolver[condition];
1160                let condition_good = match *condition_ty {
1161                    Ti::Scalar(Sc {
1162                        kind: Sk::Bool,
1163                        width: _,
1164                    }) => {
1165                        // When `condition` is a single boolean, `accept` and
1166                        // `reject` can be vectors or scalars.
1167                        match *accept_inner {
1168                            Ti::Scalar { .. } | Ti::Vector { .. } => true,
1169                            _ => false,
1170                        }
1171                    }
1172                    Ti::Vector {
1173                        size,
1174                        scalar:
1175                            Sc {
1176                                kind: Sk::Bool,
1177                                width: _,
1178                            },
1179                    } => match *accept_inner {
1180                        Ti::Vector {
1181                            size: other_size, ..
1182                        } => size == other_size,
1183                        _ => false,
1184                    },
1185                    _ => false,
1186                };
1187                if accept_inner != reject_inner {
1188                    return Err(ExpressionError::SelectValuesTypeMismatch {
1189                        accept: accept_inner.clone(),
1190                        reject: reject_inner.clone(),
1191                    });
1192                }
1193                if !condition_good {
1194                    return Err(ExpressionError::SelectConditionNotABool {
1195                        actual: condition_ty.clone(),
1196                    });
1197                }
1198                ShaderStages::all()
1199            }
1200            E::Derivative { expr, .. } => {
1201                let Some((_, scalar)) = resolver[expr].vector_size_and_scalar() else {
1202                    return Err(ExpressionError::InvalidDerivative);
1203                };
1204                if scalar.kind != Sk::Float || scalar.width < 4 {
1205                    // Derivatives are not supported for `f16`, although support may be added
1206                    // in the future, see https://github.com/gpuweb/gpuweb/issues/5482.
1207                    return Err(ExpressionError::InvalidDerivative);
1208                }
1209                ShaderStages::FRAGMENT
1210            }
1211            E::Relational { fun, argument } => {
1212                use crate::RelationalFunction as Rf;
1213                let argument_inner = &resolver[argument];
1214                match fun {
1215                    Rf::All | Rf::Any => match *argument_inner {
1216                        Ti::Vector {
1217                            scalar: Sc { kind: Sk::Bool, .. },
1218                            ..
1219                        } => {}
1220                        ref other => {
1221                            log::debug!("All/Any of type {other:?}");
1222                            return Err(ExpressionError::InvalidBooleanVector(argument));
1223                        }
1224                    },
1225                    Rf::IsNan | Rf::IsInf => match *argument_inner {
1226                        Ti::Scalar(scalar) | Ti::Vector { scalar, .. }
1227                            if scalar.kind == Sk::Float => {}
1228                        ref other => {
1229                            log::debug!("Float test of type {other:?}");
1230                            return Err(ExpressionError::InvalidFloatArgument(argument));
1231                        }
1232                    },
1233                }
1234                ShaderStages::all()
1235            }
1236            E::Math {
1237                fun,
1238                arg,
1239                arg1,
1240                arg2,
1241                arg3,
1242            } => {
1243                if matches!(
1244                    fun,
1245                    crate::MathFunction::QuantizeToF16
1246                        | crate::MathFunction::Pack2x16float
1247                        | crate::MathFunction::Unpack2x16float
1248                ) && !self
1249                    .capabilities
1250                    .contains(crate::valid::Capabilities::SHADER_FLOAT16_IN_FLOAT32)
1251                {
1252                    return Err(ExpressionError::MissingCapabilities(
1253                        crate::valid::Capabilities::SHADER_FLOAT16_IN_FLOAT32,
1254                    ));
1255                }
1256
1257                let actuals: &[_] = match (arg1, arg2, arg3) {
1258                    (None, None, None) => &[arg],
1259                    (Some(arg1), None, None) => &[arg, arg1],
1260                    (Some(arg1), Some(arg2), None) => &[arg, arg1, arg2],
1261                    (Some(arg1), Some(arg2), Some(arg3)) => &[arg, arg1, arg2, arg3],
1262                    _ => return Err(ExpressionError::WrongArgumentCount(fun)),
1263                };
1264
1265                let resolve = |arg| &resolver[arg];
1266                let actual_types: &[_] = match *actuals {
1267                    [arg0] => &[resolve(arg0)],
1268                    [arg0, arg1] => &[resolve(arg0), resolve(arg1)],
1269                    [arg0, arg1, arg2] => &[resolve(arg0), resolve(arg1), resolve(arg2)],
1270                    [arg0, arg1, arg2, arg3] => {
1271                        &[resolve(arg0), resolve(arg1), resolve(arg2), resolve(arg3)]
1272                    }
1273                    _ => unreachable!(),
1274                };
1275
1276                // Start with the set of all overloads available for `fun`.
1277                let mut overloads = fun.overloads();
1278                log::debug!(
1279                    "initial overloads for {:?}: {:#?}",
1280                    fun,
1281                    overloads.for_debug(&module.types)
1282                );
1283
1284                // If any argument is not a constant expression, then no
1285                // overloads that accept abstract values should be considered.
1286                // `OverloadSet::concrete_only` is supposed to help impose this
1287                // restriction. However, no `MathFunction` accepts a mix of
1288                // abstract and concrete arguments, so we don't need to worry
1289                // about that here.
1290
1291                for (i, (&expr, &ty)) in actuals.iter().zip(actual_types).enumerate() {
1292                    // Remove overloads that cannot accept an `i`'th
1293                    // argument arguments of type `ty`.
1294                    overloads = overloads.arg(i, ty, &module.types);
1295                    log::debug!(
1296                        "overloads after arg {i}: {:#?}",
1297                        overloads.for_debug(&module.types)
1298                    );
1299
1300                    if overloads.is_empty() {
1301                        log::debug!("all overloads eliminated");
1302                        return Err(ExpressionError::InvalidArgumentType(fun, i as u32, expr));
1303                    }
1304                }
1305
1306                if actuals.len() < overloads.min_arguments() {
1307                    return Err(ExpressionError::WrongArgumentCount(fun));
1308                }
1309
1310                ShaderStages::all()
1311            }
1312            E::As { expr, target } => {
1313                match resolver[expr] {
1314                    Ti::Scalar(_) | Ti::Vector { .. } => {}
1315                    Ti::Matrix { .. } if target.kind == Sk::Float => {}
1316                    _ => return Err(ExpressionError::InvalidCastArgument),
1317                }
1318                if self.check_width(target).is_err() {
1319                    return Err(ExpressionError::InvalidCastArgument);
1320                }
1321                ShaderStages::all()
1322            }
1323            E::Bitcast { expr, ty } => {
1324                let is_bit_pattern = |scalar: Sc| {
1325                    matches!(scalar.kind, Sk::Sint | Sk::Uint | Sk::Float)
1326                        && self.check_width(scalar).is_ok()
1327                };
1328                let byte_size = |inner: &Ti| match *inner {
1329                    Ti::Scalar(scalar) if is_bit_pattern(scalar) => Some(scalar.width as u32),
1330                    Ti::Vector { size, scalar } if is_bit_pattern(scalar) => {
1331                        Some(size as u32 * scalar.width as u32)
1332                    }
1333                    _ => None,
1334                };
1335                match (
1336                    byte_size(&resolver[expr]),
1337                    byte_size(&module.types[ty].inner),
1338                ) {
1339                    (Some(source), Some(target)) if source == target => {}
1340                    _ => return Err(ExpressionError::InvalidBitcast(ty)),
1341                }
1342                ShaderStages::all()
1343            }
1344            E::CallResult(function) => mod_info.functions[function.index()].available_stages,
1345            E::AtomicResult { .. } => {
1346                // These expressions are validated when we check the `Atomic` statement
1347                // that refers to them, because we have all the information we need at
1348                // that point. The checks driven by `Validator::needs_visit` ensure
1349                // that this expression is indeed visited by one `Atomic` statement.
1350                ShaderStages::all()
1351            }
1352            E::WorkGroupUniformLoadResult { ty } => {
1353                if self.types[ty.index()]
1354                    .flags
1355                    // Sized | Constructible is exactly the types currently supported by
1356                    // WorkGroupUniformLoad
1357                    .contains(TypeFlags::SIZED | TypeFlags::CONSTRUCTIBLE)
1358                {
1359                    ShaderStages::COMPUTE_LIKE
1360                } else {
1361                    return Err(ExpressionError::InvalidWorkGroupUniformLoadResultType(ty));
1362                }
1363            }
1364            E::ArrayLength(expr) => match resolver[expr] {
1365                Ti::Pointer { base, .. } => {
1366                    let base_ty = &resolver.types[base];
1367                    if let Ti::Array {
1368                        size: crate::ArraySize::Dynamic,
1369                        ..
1370                    } = base_ty.inner
1371                    {
1372                        ShaderStages::all()
1373                    } else {
1374                        return Err(ExpressionError::InvalidArrayType(expr));
1375                    }
1376                }
1377                ref other => {
1378                    log::debug!("Array length of {other:?}");
1379                    return Err(ExpressionError::InvalidArrayType(expr));
1380                }
1381            },
1382            E::RayQueryProceedResult => ShaderStages::all(),
1383            E::RayQueryGetIntersection {
1384                query,
1385                committed: _,
1386            } => match resolver[query] {
1387                Ti::Pointer {
1388                    base,
1389                    space: crate::AddressSpace::Function,
1390                } => match resolver.types[base].inner {
1391                    Ti::RayQuery { .. } => ShaderStages::all(),
1392                    ref other => {
1393                        log::debug!("Intersection result of a pointer to {other:?}");
1394                        return Err(ExpressionError::InvalidRayQueryType(query));
1395                    }
1396                },
1397                ref other => {
1398                    log::debug!("Intersection result of {other:?}");
1399                    return Err(ExpressionError::InvalidRayQueryType(query));
1400                }
1401            },
1402            E::HitObjectQuery {
1403                hit_object,
1404                query: _,
1405            } => match resolver[hit_object] {
1406                Ti::Pointer {
1407                    base,
1408                    space: crate::AddressSpace::Function,
1409                } => match resolver.types[base].inner {
1410                    Ti::HitObject => {
1411                        ShaderStages::RAY_GENERATION
1412                            | ShaderStages::CLOSEST_HIT
1413                            | ShaderStages::MISS
1414                    }
1415                    ref other => {
1416                        log::debug!("Hit object query of a pointer to {other:?}");
1417                        return Err(ExpressionError::InvalidHitObjectType(hit_object));
1418                    }
1419                },
1420                ref other => {
1421                    log::debug!("Hit object query of {other:?}");
1422                    return Err(ExpressionError::InvalidHitObjectType(hit_object));
1423                }
1424            },
1425            E::RayQueryVertexPositions {
1426                query,
1427                committed: _,
1428            } => match resolver[query] {
1429                Ti::Pointer {
1430                    base,
1431                    space: crate::AddressSpace::Function,
1432                } => match resolver.types[base].inner {
1433                    Ti::RayQuery {
1434                        vertex_return: true,
1435                    } => ShaderStages::all(),
1436                    ref other => {
1437                        log::debug!("Intersection result of a pointer to {other:?}");
1438                        return Err(ExpressionError::InvalidRayQueryType(query));
1439                    }
1440                },
1441                ref other => {
1442                    log::debug!("Intersection result of {other:?}");
1443                    return Err(ExpressionError::InvalidRayQueryType(query));
1444                }
1445            },
1446            E::SubgroupBallotResult | E::SubgroupOperationResult { .. } => self.subgroup_stages,
1447            E::CooperativeLoad { ref data, .. } => {
1448                if resolver[data.pointer]
1449                    .pointer_base_type()
1450                    .and_then(|tr| tr.inner_with(&module.types).scalar())
1451                    .is_none()
1452                {
1453                    return Err(ExpressionError::InvalidPointerType(data.pointer));
1454                }
1455                ShaderStages::COMPUTE
1456            }
1457            E::CooperativeMultiplyAdd { a, b, c } => {
1458                let roles = [
1459                    crate::CooperativeRole::A,
1460                    crate::CooperativeRole::B,
1461                    crate::CooperativeRole::C,
1462                ];
1463                for (operand, expected_role) in [a, b, c].into_iter().zip(roles) {
1464                    match resolver[operand] {
1465                        Ti::CooperativeMatrix { role, .. } if role == expected_role => {}
1466                        ref other => {
1467                            log::debug!("{expected_role:?} operand type: {other:?}");
1468                            return Err(ExpressionError::InvalidCooperativeOperand(a));
1469                        }
1470                    }
1471                }
1472                ShaderStages::COMPUTE
1473            }
1474        };
1475        Ok(stages)
1476    }
1477
1478    fn global_var_ty(
1479        module: &crate::Module,
1480        function: &crate::Function,
1481        expr: Handle<crate::Expression>,
1482    ) -> Result<Handle<crate::Type>, ExpressionError> {
1483        use crate::Expression as Ex;
1484
1485        match function.expressions[expr] {
1486            Ex::GlobalVariable(var_handle) => Ok(module.global_variables[var_handle].ty),
1487            Ex::FunctionArgument(i) => Ok(function.arguments[i as usize].ty),
1488            Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => {
1489                match function.expressions[base] {
1490                    Ex::GlobalVariable(var_handle) => {
1491                        let array_ty = module.global_variables[var_handle].ty;
1492
1493                        match module.types[array_ty].inner {
1494                            crate::TypeInner::BindingArray { base, .. } => Ok(base),
1495                            _ => Err(ExpressionError::ExpectedBindingArrayType(array_ty)),
1496                        }
1497                    }
1498                    _ => Err(ExpressionError::ExpectedGlobalVariable),
1499                }
1500            }
1501            _ => Err(ExpressionError::ExpectedGlobalVariable),
1502        }
1503    }
1504
1505    pub fn validate_literal(&self, literal: crate::Literal) -> Result<(), LiteralError> {
1506        let _ = self.check_width(literal.scalar())?;
1507        check_literal_value(literal)?;
1508
1509        Ok(())
1510    }
1511}
1512
1513pub const fn check_literal_value(literal: crate::Literal) -> Result<(), LiteralError> {
1514    let is_nan = match literal {
1515        crate::Literal::F64(v) => v.is_nan(),
1516        crate::Literal::F32(v) => v.is_nan(),
1517        _ => false,
1518    };
1519    if is_nan {
1520        return Err(LiteralError::NaN);
1521    }
1522
1523    let is_infinite = match literal {
1524        crate::Literal::F64(v) => v.is_infinite(),
1525        crate::Literal::F32(v) => v.is_infinite(),
1526        _ => false,
1527    };
1528    if is_infinite {
1529        return Err(LiteralError::Infinity);
1530    }
1531
1532    Ok(())
1533}
1534
1535#[cfg(test)]
1536/// Validate a module containing the given expression, expecting an error.
1537fn validate_with_expression(
1538    expr: crate::Expression,
1539    caps: super::Capabilities,
1540) -> Result<ModuleInfo, Box<crate::span::WithSpan<super::ValidationError>>> {
1541    use crate::span::Span;
1542
1543    let mut function = crate::Function::default();
1544    function.expressions.append(expr, Span::default());
1545    function.body.push(
1546        crate::Statement::Emit(function.expressions.range_from(0)),
1547        Span::default(),
1548    );
1549
1550    let mut module = crate::Module::default();
1551    module.functions.append(function, Span::default());
1552
1553    let mut validator = super::Validator::new(super::ValidationFlags::EXPRESSIONS, caps);
1554
1555    validator.validate(&module)
1556}
1557
1558#[cfg(test)]
1559/// Validate a module containing the given constant expression, expecting an error.
1560fn validate_with_const_expression(
1561    expr: crate::Expression,
1562    caps: super::Capabilities,
1563) -> Result<ModuleInfo, Box<crate::span::WithSpan<super::ValidationError>>> {
1564    use crate::span::Span;
1565
1566    let mut module = crate::Module::default();
1567    module.global_expressions.append(expr, Span::default());
1568
1569    let mut validator = super::Validator::new(super::ValidationFlags::CONSTANTS, caps);
1570
1571    validator.validate(&module)
1572}
1573
1574/// Using F64 in a function's expression arena is forbidden.
1575#[test]
1576fn f64_runtime_literals() {
1577    let result = validate_with_expression(
1578        crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1579        super::Capabilities::default(),
1580    );
1581    let error = result.unwrap_err().into_inner();
1582    assert!(matches!(
1583        error,
1584        crate::valid::ValidationError::Function {
1585            source: super::FunctionError::Expression {
1586                source: ExpressionError::Literal(LiteralError::Width(
1587                    super::r#type::WidthError::MissingCapability {
1588                        name: "f64",
1589                        flag: "FLOAT64",
1590                    }
1591                ),),
1592                ..
1593            },
1594            ..
1595        }
1596    ));
1597
1598    let result = validate_with_expression(
1599        crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1600        super::Capabilities::default() | super::Capabilities::FLOAT64,
1601    );
1602    assert!(result.is_ok());
1603}
1604
1605/// Using F64 in a module's constant expression arena is forbidden.
1606#[test]
1607fn f64_const_literals() {
1608    let result = validate_with_const_expression(
1609        crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1610        super::Capabilities::default(),
1611    );
1612    let error = result.unwrap_err().into_inner();
1613    assert!(matches!(
1614        error,
1615        crate::valid::ValidationError::ConstExpression {
1616            source: ConstExpressionError::Literal(LiteralError::Width(
1617                super::r#type::WidthError::MissingCapability {
1618                    name: "f64",
1619                    flag: "FLOAT64",
1620                }
1621            )),
1622            ..
1623        }
1624    ));
1625
1626    let result = validate_with_const_expression(
1627        crate::Expression::Literal(crate::Literal::F64(0.57721_56649)),
1628        super::Capabilities::default() | super::Capabilities::FLOAT64,
1629    );
1630    assert!(result.is_ok());
1631}