Skip to main content

naga/valid/
type.rs

1use alloc::string::String;
2
3use super::Capabilities;
4use crate::{arena::Handle, ir, proc::Alignment};
5
6bitflags::bitflags! {
7    /// Flags associated with [`Type`]s by [`Validator`].
8    ///
9    /// [`Type`]: crate::Type
10    /// [`Validator`]: crate::valid::Validator
11    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
12    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
13    #[repr(transparent)]
14    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
15    pub struct TypeFlags: u8 {
16        /// Can be used for data variables.
17        ///
18        /// This flag is required on types of local variables, function
19        /// arguments, array elements, and struct members.
20        ///
21        /// This includes all types except [`Image`], [`Sampler`],
22        /// and some [`Pointer`] types.
23        ///
24        /// [`Image`]: crate::TypeInner::Image
25        /// [`Sampler`]: crate::TypeInner::Sampler
26        /// [`Pointer`]: crate::TypeInner::Pointer
27        const DATA = 0x1;
28
29        /// The data type has a size known by pipeline creation time.
30        ///
31        /// Unsized types are quite restricted. The only unsized types permitted
32        /// by Naga, other than the non-[`DATA`] types like [`Image`] and
33        /// [`Sampler`], are dynamically-sized [`Array`]s, and [`Struct`]s whose
34        /// last members are such arrays. See the documentation for those types
35        /// for details.
36        ///
37        /// [`DATA`]: TypeFlags::DATA
38        /// [`Image`]: crate::TypeInner::Image
39        /// [`Sampler`]: crate::TypeInner::Sampler
40        /// [`Array`]: crate::TypeInner::Array
41        /// [`Struct`]: crate::TypeInner::Struct
42        const SIZED = 0x2;
43
44        /// The data can be copied around.
45        const COPY = 0x4;
46
47        /// Can be be used in pipeline stage I/O.
48        ///
49        /// Applies to the following:
50        ///   - Types that may be used in a [`Location`] binding (numeric scalars and vectors)
51        ///   - `@blend_src` structs
52        ///
53        /// See [location-attr] and [input-output].
54        ///
55        /// [`Location`]: crate::Binding::Location
56        /// [location-attr]: https://gpuweb.github.io/gpuweb/wgsl/#location-attr
57        /// [input-output]: https://gpuweb.github.io/gpuweb/wgsl/#input-output-locations
58        /// https://gpuweb.github.io/gpuweb/wgsl/#location-attr
59        const IO_SHAREABLE = 0x8;
60
61        /// Can be used for host-shareable structures.
62        const HOST_SHAREABLE = 0x10;
63
64        /// The set of types with a fixed size at shader-creation time (ie. everything
65        /// except arrays sized by an override-expression)
66        const CREATION_RESOLVED = 0x20;
67
68        /// This type can be passed as a function argument.
69        const ARGUMENT = 0x40;
70
71        /// A WGSL [constructible] type.
72        ///
73        /// The constructible types are scalars, vectors, matrices, fixed-size
74        /// arrays of constructible types, and structs whose members are all
75        /// constructible.
76        ///
77        /// [constructible]: https://gpuweb.github.io/gpuweb/wgsl/#constructible
78        const CONSTRUCTIBLE = 0x80;
79    }
80}
81
82#[derive(Clone, Copy, Debug, thiserror::Error)]
83#[cfg_attr(test, derive(PartialEq))]
84pub enum Disalignment {
85    #[error("The array stride {stride} is not a multiple of the required alignment {alignment}")]
86    ArrayStride { stride: u32, alignment: Alignment },
87    #[error("The struct span {span}, is not a multiple of the required alignment {alignment}")]
88    StructSpan { span: u32, alignment: Alignment },
89    #[error("The struct member[{index}] offset {offset} is not a multiple of the required alignment {alignment}")]
90    MemberOffset {
91        index: u32,
92        offset: u32,
93        alignment: Alignment,
94    },
95    #[error("The struct member[{index}] offset {offset} must be at least {expected}")]
96    MemberOffsetAfterStruct {
97        index: u32,
98        offset: u32,
99        expected: u32,
100    },
101    #[error("The struct member[{index}] is not statically sized")]
102    UnsizedMember { index: u32 },
103    #[error("The type is not host-shareable")]
104    NonHostShareable,
105}
106
107#[derive(Clone, Debug, thiserror::Error)]
108#[cfg_attr(test, derive(PartialEq))]
109pub enum TypeError {
110    #[error("Capability {0:?} is required")]
111    MissingCapability(Capabilities),
112    #[error("The {0:?} scalar width {1} is not supported for an atomic")]
113    InvalidAtomicWidth(crate::ScalarKind, crate::Bytes),
114    #[error("Invalid type for pointer target {0:?}")]
115    InvalidPointerBase(Handle<crate::Type>),
116    #[error("Unsized types like {base:?} must be in the `Storage` address space, not `{space:?}`")]
117    InvalidPointerToUnsized {
118        base: Handle<crate::Type>,
119        space: crate::AddressSpace,
120    },
121    #[error("Expected data type, found {0:?}")]
122    InvalidData(Handle<crate::Type>),
123    #[error("Base type {0:?} for the array is invalid")]
124    InvalidArrayBaseType(Handle<crate::Type>),
125    #[error("Matrix elements must always be floating-point types")]
126    MatrixElementNotFloat,
127    #[error("The constant {0:?} is specialized, and cannot be used as an array size")]
128    UnsupportedSpecializedArrayLength(Handle<crate::Constant>),
129    #[error("{} of dimensionality {dim:?} and class {class:?} are not supported", if *.arrayed {"Arrayed images"} else {"Images"})]
130    UnsupportedImageType {
131        dim: crate::ImageDimension,
132        arrayed: bool,
133        class: crate::ImageClass,
134    },
135    #[error("Array stride {stride} does not match the expected {expected}")]
136    InvalidArrayStride { stride: u32, expected: u32 },
137    #[error("Field '{0}' can't be dynamically-sized, has type {1:?}")]
138    InvalidDynamicArray(String, Handle<crate::Type>),
139    #[error("The base handle {0:?} has to be a struct")]
140    BindingArrayBaseTypeNotStruct(Handle<crate::Type>),
141    #[error("Binding arrays of external textures are not yet supported")]
142    BindingArrayBaseExternalTextures,
143    #[error("Structure member[{index}] at {offset} overlaps the previous member")]
144    MemberOverlap { index: u32, offset: u32 },
145    #[error(
146        "Structure member[{index}] at {offset} and size {size} crosses the structure boundary of size {span}"
147    )]
148    MemberOutOfBounds {
149        index: u32,
150        offset: u32,
151        size: u32,
152        span: u32,
153    },
154    #[error("Structure types must have at least one member")]
155    EmptyStruct,
156    #[error("Invalid `@blend_src` structure: {0}")]
157    InvalidBlendSrc(super::VaryingError),
158    #[error(transparent)]
159    WidthError(#[from] WidthError),
160    #[error(
161        "The base handle {0:?} has an override-expression that didn't get resolved to a constant"
162    )]
163    UnresolvedOverride(Handle<crate::Type>),
164    #[error("Override-sized array type {0:?} does not have a positive size")]
165    InvalidArraySize(Handle<crate::Type>),
166}
167
168#[derive(Clone, Debug, thiserror::Error)]
169#[cfg_attr(test, derive(PartialEq))]
170pub enum WidthError {
171    #[error("The {0:?} scalar width {1} is not supported")]
172    Invalid(crate::ScalarKind, crate::Bytes),
173    #[error("Using `{name}` values requires the `naga::valid::Capabilities::{flag}` flag")]
174    MissingCapability {
175        name: &'static str,
176        flag: &'static str,
177    },
178
179    #[error("Abstract types may only appear in constant expressions")]
180    Abstract,
181}
182
183#[derive(Clone, Debug, thiserror::Error)]
184#[cfg_attr(test, derive(PartialEq))]
185pub enum ImmediateError {
186    #[error("The scalar type {0:?} is not supported in immediates")]
187    InvalidScalar(crate::Scalar),
188    #[error("Arrays are not supported in the immediate address space")]
189    InvalidArray,
190}
191
192// Only makes sense if `flags.contains(HOST_SHAREABLE)`
193type LayoutCompatibility = Result<Alignment, (Handle<crate::Type>, Disalignment)>;
194type ImmediateCompatibility = Result<(), ImmediateError>;
195
196fn check_member_layout(
197    accum: &mut LayoutCompatibility,
198    member: &crate::StructMember,
199    member_index: u32,
200    member_layout: LayoutCompatibility,
201    parent_handle: Handle<crate::Type>,
202) {
203    *accum = match (*accum, member_layout) {
204        (Ok(cur_alignment), Ok(alignment)) => {
205            if alignment.is_aligned(member.offset) {
206                Ok(cur_alignment.max(alignment))
207            } else {
208                Err((
209                    parent_handle,
210                    Disalignment::MemberOffset {
211                        index: member_index,
212                        offset: member.offset,
213                        alignment,
214                    },
215                ))
216            }
217        }
218        (Err(e), _) | (_, Err(e)) => Err(e),
219    };
220}
221
222/// Determine whether a pointer in `space` can be passed as an argument.
223///
224/// If a pointer in `space` is permitted to be passed as an argument to a
225/// user-defined function, return `TypeFlags::ARGUMENT`. Otherwise, return
226/// `TypeFlags::empty()`.
227///
228/// Pointers passed as arguments to user-defined functions must be in the
229/// `Function` or `Private` address space.
230const fn ptr_space_argument_flag(space: crate::AddressSpace) -> TypeFlags {
231    use crate::AddressSpace as As;
232    match space {
233        As::Function | As::Private | As::RayPayload | As::IncomingRayPayload => TypeFlags::ARGUMENT,
234        As::Uniform
235        | As::Storage { .. }
236        | As::Handle
237        | As::Immediate
238        | As::WorkGroup
239        | As::TaskPayload => TypeFlags::empty(),
240    }
241}
242
243#[derive(Clone, Debug)]
244pub(super) struct TypeInfo {
245    pub flags: TypeFlags,
246    pub uniform_layout: LayoutCompatibility,
247    pub storage_layout: LayoutCompatibility,
248    pub immediates_compatibility: ImmediateCompatibility,
249}
250
251impl TypeInfo {
252    const fn dummy() -> Self {
253        TypeInfo {
254            flags: TypeFlags::empty(),
255            uniform_layout: Ok(Alignment::ONE),
256            storage_layout: Ok(Alignment::ONE),
257            immediates_compatibility: Ok(()),
258        }
259    }
260
261    const fn new(flags: TypeFlags, alignment: Alignment) -> Self {
262        TypeInfo {
263            flags,
264            uniform_layout: Ok(alignment),
265            storage_layout: Ok(alignment),
266            immediates_compatibility: Ok(()),
267        }
268    }
269}
270
271impl super::Validator {
272    const fn require_type_capability(&self, capability: Capabilities) -> Result<(), TypeError> {
273        if self.capabilities.contains(capability) {
274            Ok(())
275        } else {
276            Err(TypeError::MissingCapability(capability))
277        }
278    }
279
280    /// Check whether `scalar` is a permitted scalar width.
281    ///
282    /// If `scalar` is not a width allowed by the selected [`Capabilities`],
283    /// return an error explaining why.
284    ///
285    /// If `scalar` is allowed, return a [`ImmediateCompatibility`] result
286    /// that says whether `scalar` is allowed specifically in immediates.
287    ///
288    /// [`Capabilities`]: crate::valid::Capabilities
289    pub(super) const fn check_width(
290        &self,
291        scalar: crate::Scalar,
292    ) -> Result<ImmediateCompatibility, WidthError> {
293        let mut immediates_compatibility = Ok(());
294        let good = match scalar.kind {
295            crate::ScalarKind::Bool => scalar.width == crate::BOOL_WIDTH,
296            crate::ScalarKind::Float => match scalar.width {
297                8 => {
298                    if !self.capabilities.contains(Capabilities::FLOAT64) {
299                        return Err(WidthError::MissingCapability {
300                            name: "f64",
301                            flag: "FLOAT64",
302                        });
303                    }
304                    true
305                }
306                2 => {
307                    if !self.capabilities.contains(Capabilities::SHADER_FLOAT16) {
308                        return Err(WidthError::MissingCapability {
309                            name: "f16",
310                            flag: "FLOAT16",
311                        });
312                    }
313
314                    true
315                }
316                _ => scalar.width == 4,
317            },
318            crate::ScalarKind::Sint => {
319                if scalar.width == 2 {
320                    if !self.capabilities.contains(Capabilities::SHADER_INT16) {
321                        return Err(WidthError::MissingCapability {
322                            name: "i16",
323                            flag: "SHADER_INT16",
324                        });
325                    }
326
327                    immediates_compatibility = Err(ImmediateError::InvalidScalar(scalar));
328
329                    true
330                } else if scalar.width == 8 {
331                    if !self.capabilities.contains(Capabilities::SHADER_INT64) {
332                        return Err(WidthError::MissingCapability {
333                            name: "i64",
334                            flag: "SHADER_INT64",
335                        });
336                    }
337                    true
338                } else {
339                    scalar.width == 4
340                }
341            }
342            crate::ScalarKind::Uint => {
343                if scalar.width == 2 {
344                    if !self.capabilities.contains(Capabilities::SHADER_INT16) {
345                        return Err(WidthError::MissingCapability {
346                            name: "u16",
347                            flag: "SHADER_INT16",
348                        });
349                    }
350
351                    immediates_compatibility = Err(ImmediateError::InvalidScalar(scalar));
352
353                    true
354                } else if scalar.width == 8 {
355                    if !self.capabilities.contains(Capabilities::SHADER_INT64) {
356                        return Err(WidthError::MissingCapability {
357                            name: "u64",
358                            flag: "SHADER_INT64",
359                        });
360                    }
361                    true
362                } else {
363                    scalar.width == 4
364                }
365            }
366            crate::ScalarKind::AbstractInt | crate::ScalarKind::AbstractFloat => {
367                return Err(WidthError::Abstract);
368            }
369        };
370        if good {
371            Ok(immediates_compatibility)
372        } else {
373            Err(WidthError::Invalid(scalar.kind, scalar.width))
374        }
375    }
376
377    pub(super) fn reset_types(&mut self, size: usize) {
378        self.types.clear();
379        self.types.resize(size, TypeInfo::dummy());
380        self.layouter.clear();
381    }
382
383    pub(super) fn validate_type(
384        &self,
385        handle: Handle<crate::Type>,
386        gctx: crate::proc::GlobalCtx,
387    ) -> Result<TypeInfo, TypeError> {
388        use crate::TypeInner as Ti;
389        Ok(match gctx.types[handle].inner {
390            Ti::Scalar(scalar) => {
391                let immediates_compatibility = self.check_width(scalar)?;
392                let shareable = if scalar.kind.is_numeric() {
393                    TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE
394                } else {
395                    TypeFlags::empty()
396                };
397                let mut type_info = TypeInfo::new(
398                    TypeFlags::DATA
399                        | TypeFlags::SIZED
400                        | TypeFlags::COPY
401                        | TypeFlags::ARGUMENT
402                        | TypeFlags::CONSTRUCTIBLE
403                        | TypeFlags::CREATION_RESOLVED
404                        | shareable,
405                    Alignment::from_width(scalar.width),
406                );
407                type_info.immediates_compatibility = immediates_compatibility;
408                type_info
409            }
410            Ti::Vector { size, scalar } => {
411                let immediates_compatibility = self.check_width(scalar)?;
412                let shareable = if scalar.kind.is_numeric() {
413                    TypeFlags::IO_SHAREABLE | TypeFlags::HOST_SHAREABLE
414                } else {
415                    TypeFlags::empty()
416                };
417                let mut type_info = TypeInfo::new(
418                    TypeFlags::DATA
419                        | TypeFlags::SIZED
420                        | TypeFlags::COPY
421                        | TypeFlags::ARGUMENT
422                        | TypeFlags::CONSTRUCTIBLE
423                        | TypeFlags::CREATION_RESOLVED
424                        | shareable,
425                    Alignment::from(size) * Alignment::from_width(scalar.width),
426                );
427                type_info.immediates_compatibility = immediates_compatibility;
428                type_info
429            }
430            Ti::Matrix {
431                columns: _,
432                rows,
433                scalar,
434            } => {
435                if scalar.kind != crate::ScalarKind::Float {
436                    return Err(TypeError::MatrixElementNotFloat);
437                }
438                let immediates_compatibility = self.check_width(scalar)?;
439                let mut type_info = TypeInfo::new(
440                    TypeFlags::DATA
441                        | TypeFlags::SIZED
442                        | TypeFlags::COPY
443                        | TypeFlags::HOST_SHAREABLE
444                        | TypeFlags::ARGUMENT
445                        | TypeFlags::CONSTRUCTIBLE
446                        | TypeFlags::CREATION_RESOLVED,
447                    Alignment::from(rows) * Alignment::from_width(scalar.width),
448                );
449                type_info.immediates_compatibility = immediates_compatibility;
450                type_info
451            }
452            Ti::CooperativeMatrix {
453                columns: _,
454                rows: _,
455                scalar,
456                role: _,
457            } => {
458                self.require_type_capability(Capabilities::COOPERATIVE_MATRIX)?;
459                // Allow f16 (width 2) and f32 (width 4) for cooperative matrices
460                if scalar.kind != crate::ScalarKind::Float
461                    || (scalar.width != 2 && scalar.width != 4)
462                {
463                    return Err(TypeError::MatrixElementNotFloat);
464                }
465                TypeInfo::new(
466                    TypeFlags::DATA
467                        | TypeFlags::SIZED
468                        | TypeFlags::COPY
469                        | TypeFlags::HOST_SHAREABLE
470                        | TypeFlags::ARGUMENT
471                        | TypeFlags::CONSTRUCTIBLE
472                        | TypeFlags::CREATION_RESOLVED,
473                    Alignment::from_width(scalar.width),
474                )
475            }
476            Ti::Atomic(scalar) => {
477                match scalar {
478                    crate::Scalar {
479                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
480                        width: 4,
481                    } => {}
482                    crate::Scalar {
483                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
484                        width: 8,
485                    } => {
486                        if !self.capabilities.intersects(
487                            Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
488                                | Capabilities::SHADER_INT64_ATOMIC_MIN_MAX,
489                        ) {
490                            return Err(TypeError::MissingCapability(
491                                Capabilities::SHADER_INT64_ATOMIC_ALL_OPS,
492                            ));
493                        }
494                    }
495                    crate::Scalar::F32 => {
496                        if !self
497                            .capabilities
498                            .contains(Capabilities::SHADER_FLOAT32_ATOMIC)
499                        {
500                            return Err(TypeError::MissingCapability(
501                                Capabilities::SHADER_FLOAT32_ATOMIC,
502                            ));
503                        }
504                    }
505                    _ => return Err(TypeError::InvalidAtomicWidth(scalar.kind, scalar.width)),
506                };
507                TypeInfo::new(
508                    TypeFlags::DATA
509                        | TypeFlags::SIZED
510                        | TypeFlags::HOST_SHAREABLE
511                        | TypeFlags::CREATION_RESOLVED,
512                    Alignment::from_width(scalar.width),
513                )
514            }
515            Ti::Pointer { base, space } => {
516                use crate::AddressSpace as As;
517
518                let base_info = &self.types[base.index()];
519                if !base_info.flags.contains(TypeFlags::DATA) {
520                    return Err(TypeError::InvalidPointerBase(base));
521                }
522
523                // Runtime-sized values can only live in the `Storage` address
524                // space, so it's useless to have a pointer to such a type in
525                // any other space.
526                //
527                // Detecting this problem here prevents the definition of
528                // functions like:
529                //
530                //     fn f(p: ptr<workgroup, UnsizedType>) -> ... { ... }
531                //
532                // which would otherwise be permitted, but uncallable. (They
533                // may also present difficulties in code generation).
534                if !base_info.flags.contains(TypeFlags::SIZED) {
535                    match space {
536                        As::Storage { .. } => {}
537                        _ => {
538                            return Err(TypeError::InvalidPointerToUnsized { base, space });
539                        }
540                    }
541                }
542
543                // `Validator::validate_function` actually checks the address
544                // space of pointer arguments explicitly before checking the
545                // `ARGUMENT` flag, to give better error messages. But it seems
546                // best to set `ARGUMENT` accurately anyway.
547                let argument_flag = ptr_space_argument_flag(space);
548
549                // Pointers cannot be stored in variables, structure members, or
550                // array elements, so we do not mark them as `DATA`.
551                TypeInfo::new(
552                    argument_flag
553                        | TypeFlags::SIZED
554                        | TypeFlags::COPY
555                        | TypeFlags::CREATION_RESOLVED,
556                    Alignment::ONE,
557                )
558            }
559            Ti::ValuePointer {
560                size: _,
561                scalar,
562                space,
563            } => {
564                // ValuePointer should be treated the same way as the equivalent
565                // Pointer / Scalar / Vector combination, so each step in those
566                // variants' match arms should have a counterpart here.
567                //
568                // However, some cases are trivial: All our implicit base types
569                // are DATA and SIZED, so we can never return
570                // `InvalidPointerBase` or `InvalidPointerToUnsized`.
571                let _ = self.check_width(scalar)?;
572
573                // `Validator::validate_function` actually checks the address
574                // space of pointer arguments explicitly before checking the
575                // `ARGUMENT` flag, to give better error messages. But it seems
576                // best to set `ARGUMENT` accurately anyway.
577                let argument_flag = ptr_space_argument_flag(space);
578
579                // Pointers cannot be stored in variables, structure members, or
580                // array elements, so we do not mark them as `DATA`.
581                TypeInfo::new(
582                    argument_flag
583                        | TypeFlags::SIZED
584                        | TypeFlags::COPY
585                        | TypeFlags::CREATION_RESOLVED,
586                    Alignment::ONE,
587                )
588            }
589            Ti::Array { base, size, stride } => {
590                let base_info = &self.types[base.index()];
591                if !base_info
592                    .flags
593                    .contains(TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::CREATION_RESOLVED)
594                    || matches!(gctx.types[base].inner, Ti::HitObject)
595                {
596                    return Err(TypeError::InvalidArrayBaseType(base));
597                }
598
599                if self.overrides_resolved {
600                    // This check only makes sense for override-sized arrays.
601                    // `ArraySize::Constant` holds a `NonZeroU32`.
602                    if let crate::ArraySize::Pending(_) = size {
603                        size.resolve(gctx)
604                            .map_err(|_| TypeError::InvalidArraySize(handle))?;
605                    }
606                }
607
608                let base_layout = self.layouter[base];
609                let general_alignment = base_layout.alignment;
610                let uniform_layout = match base_info.uniform_layout {
611                    Ok(base_alignment) => {
612                        let alignment = base_alignment
613                            .max(general_alignment)
614                            .max(Alignment::MIN_UNIFORM);
615                        if alignment.is_aligned(stride) {
616                            Ok(alignment)
617                        } else {
618                            Err((handle, Disalignment::ArrayStride { stride, alignment }))
619                        }
620                    }
621                    Err(e) => Err(e),
622                };
623                let storage_layout = match base_info.storage_layout {
624                    Ok(base_alignment) => {
625                        let alignment = base_alignment.max(general_alignment);
626                        if alignment.is_aligned(stride) {
627                            Ok(alignment)
628                        } else {
629                            Err((handle, Disalignment::ArrayStride { stride, alignment }))
630                        }
631                    }
632                    Err(e) => Err(e),
633                };
634
635                let type_info_mask = match size {
636                    crate::ArraySize::Constant(_) => {
637                        TypeFlags::DATA
638                            | TypeFlags::SIZED
639                            | TypeFlags::COPY
640                            | TypeFlags::HOST_SHAREABLE
641                            | TypeFlags::ARGUMENT
642                            | TypeFlags::CONSTRUCTIBLE
643                            | TypeFlags::CREATION_RESOLVED
644                    }
645                    crate::ArraySize::Pending(_) => {
646                        TypeFlags::DATA
647                            | TypeFlags::SIZED
648                            | TypeFlags::COPY
649                            | TypeFlags::HOST_SHAREABLE
650                            | TypeFlags::ARGUMENT
651                    }
652                    crate::ArraySize::Dynamic => {
653                        // Non-SIZED types may only appear as the last element of a structure.
654                        // This is enforced by checks for SIZED-ness for all compound types,
655                        // and a special case for structs.
656                        TypeFlags::DATA
657                            | TypeFlags::COPY
658                            | TypeFlags::HOST_SHAREABLE
659                            | TypeFlags::CREATION_RESOLVED
660                    }
661                };
662
663                TypeInfo {
664                    flags: base_info.flags & type_info_mask,
665                    uniform_layout,
666                    storage_layout,
667                    immediates_compatibility: Err(ImmediateError::InvalidArray),
668                }
669            }
670            Ti::Struct { ref members, span } => {
671                if members.is_empty() {
672                    return Err(TypeError::EmptyStruct);
673                }
674
675                let mut blend_src_types = [None, None];
676                let mut non_blend_src_location = None;
677
678                let mut ti = TypeInfo::new(
679                    TypeFlags::DATA
680                        | TypeFlags::SIZED
681                        | TypeFlags::COPY
682                        | TypeFlags::HOST_SHAREABLE
683                        | TypeFlags::ARGUMENT
684                        | TypeFlags::CONSTRUCTIBLE
685                        | TypeFlags::CREATION_RESOLVED,
686                    Alignment::ONE,
687                );
688                ti.uniform_layout = Ok(Alignment::MIN_UNIFORM);
689
690                let mut min_offset = 0;
691                let mut prev_struct_data: Option<(u32, u32)> = None;
692
693                for (i, member) in members.iter().enumerate() {
694                    let base_info = &self.types[member.ty.index()];
695                    if !base_info
696                        .flags
697                        .contains(TypeFlags::DATA | TypeFlags::CREATION_RESOLVED)
698                        || matches!(gctx.types[member.ty].inner, Ti::HitObject)
699                    {
700                        return Err(TypeError::InvalidData(member.ty));
701                    }
702                    if !base_info.flags.contains(TypeFlags::HOST_SHAREABLE) {
703                        if ti.uniform_layout.is_ok() {
704                            ti.uniform_layout = Err((member.ty, Disalignment::NonHostShareable));
705                        }
706                        if ti.storage_layout.is_ok() {
707                            ti.storage_layout = Err((member.ty, Disalignment::NonHostShareable));
708                        }
709                    }
710                    ti.flags &= base_info.flags;
711
712                    match member.binding {
713                        Some(ir::Binding::Location {
714                            location,
715                            blend_src: Some(blend_src),
716                            ..
717                        }) => {
718                            // `blend_src` is only valid if dual source blending was explicitly enabled,
719                            // see https://www.w3.org/TR/WGSL/#extension-dual_source_blending
720                            if !self
721                                .capabilities
722                                .contains(Capabilities::DUAL_SOURCE_BLENDING)
723                            {
724                                return Err(TypeError::MissingCapability(
725                                    Capabilities::DUAL_SOURCE_BLENDING,
726                                ));
727                            }
728                            if !(location == 0 && (blend_src == 0 || blend_src == 1)) {
729                                return Err(TypeError::InvalidBlendSrc(
730                                    super::VaryingError::InvalidBlendSrcIndex {
731                                        location,
732                                        blend_src,
733                                    },
734                                ));
735                            }
736                            if blend_src_types[blend_src as usize]
737                                .replace(member.ty)
738                                .is_some()
739                            {
740                                // @blend_src(i) appeared multiple times
741                                return Err(TypeError::InvalidBlendSrc(
742                                    super::VaryingError::BindingCollisionBlendSrc { blend_src },
743                                ));
744                            }
745                        }
746                        Some(ir::Binding::Location {
747                            location,
748                            blend_src: None,
749                            ..
750                        }) => non_blend_src_location = Some(location),
751                        _ => {}
752                    }
753
754                    if member.offset < min_offset {
755                        // HACK: this could be nicer. We want to allow some structures
756                        // to not bother with offsets/alignments if they are never
757                        // used for host sharing.
758                        if member.offset == 0 {
759                            ti.flags.set(TypeFlags::HOST_SHAREABLE, false);
760                        } else {
761                            return Err(TypeError::MemberOverlap {
762                                index: i as u32,
763                                offset: member.offset,
764                            });
765                        }
766                    }
767
768                    let base_size = gctx.types[member.ty].inner.size(gctx);
769                    min_offset = member.offset + base_size;
770                    if min_offset > span {
771                        return Err(TypeError::MemberOutOfBounds {
772                            index: i as u32,
773                            offset: member.offset,
774                            size: base_size,
775                            span,
776                        });
777                    }
778
779                    check_member_layout(
780                        &mut ti.uniform_layout,
781                        member,
782                        i as u32,
783                        base_info.uniform_layout,
784                        handle,
785                    );
786                    check_member_layout(
787                        &mut ti.storage_layout,
788                        member,
789                        i as u32,
790                        base_info.storage_layout,
791                        handle,
792                    );
793                    if base_info.immediates_compatibility.is_err() {
794                        ti.immediates_compatibility = base_info.immediates_compatibility.clone();
795                    }
796
797                    // Validate rule: If a structure member itself has a structure type S,
798                    // then the number of bytes between the start of that member and
799                    // the start of any following member must be at least roundUp(16, SizeOf(S)).
800                    if let Some((span, offset)) = prev_struct_data {
801                        let diff = member.offset - offset;
802                        let min = Alignment::MIN_UNIFORM.round_up(span);
803                        if diff < min {
804                            ti.uniform_layout = Err((
805                                handle,
806                                Disalignment::MemberOffsetAfterStruct {
807                                    index: i as u32,
808                                    offset: member.offset,
809                                    expected: offset + min,
810                                },
811                            ));
812                        }
813                    };
814
815                    prev_struct_data = match gctx.types[member.ty].inner {
816                        crate::TypeInner::Struct { span, .. } => Some((span, member.offset)),
817                        _ => None,
818                    };
819
820                    // The last field may be an unsized array.
821                    if !base_info.flags.contains(TypeFlags::SIZED) {
822                        let is_array = match gctx.types[member.ty].inner {
823                            crate::TypeInner::Array { .. } => true,
824                            _ => false,
825                        };
826                        if !is_array || i + 1 != members.len() {
827                            let name = member.name.clone().unwrap_or_default();
828                            return Err(TypeError::InvalidDynamicArray(name, member.ty));
829                        }
830                        if ti.uniform_layout.is_ok() {
831                            ti.uniform_layout =
832                                Err((handle, Disalignment::UnsizedMember { index: i as u32 }));
833                        }
834                    }
835                }
836
837                match blend_src_types {
838                    [None, None] => {}
839                    [Some(ty0), Some(ty1)] => {
840                        if let Some(location) = non_blend_src_location {
841                            // If `@blend_src` members are present, then `@location`
842                            // may only be used for those members.
843                            return Err(TypeError::InvalidBlendSrc(
844                                super::VaryingError::InvalidBlendSrcWithOtherBindings { location },
845                            ));
846                        }
847                        let ty0_inner = &gctx.types[ty0].inner;
848                        let ty1_inner = &gctx.types[ty1].inner;
849                        // The two blend sources must have the same type...
850                        if !ty0_inner.non_struct_equivalent(ty1_inner, gctx.types) {
851                            return Err(TypeError::InvalidBlendSrc(
852                                super::VaryingError::BlendSrcOutputTypeMismatch {
853                                    blend_src_0_type: ty0,
854                                    blend_src_1_type: ty1,
855                                },
856                            ));
857                        }
858                        // ... and that type must be I/O-shareable.
859                        if !self.types[ty0.index()]
860                            .flags
861                            .contains(TypeFlags::IO_SHAREABLE)
862                        {
863                            return Err(TypeError::InvalidBlendSrc(
864                                super::VaryingError::NotIOShareableType(ty0),
865                            ));
866                        }
867
868                        // `@blend_src` is the only case where we classify a struct as
869                        // I/O-shareable. (In the case of a struct with `@location` bindings, we
870                        // process the members individually in interface validation, and do not
871                        // classify the struct as I/O-shareable.)
872                        ti.flags |= TypeFlags::IO_SHAREABLE;
873                    }
874                    [None, Some(_)] | [Some(_), None] => {
875                        // Only one of the blend sources was specified.
876                        return Err(TypeError::InvalidBlendSrc(
877                            super::VaryingError::IncompleteBlendSrcUsage {
878                                present_blend_src: blend_src_types
879                                    .iter()
880                                    .position(|src| src.is_some())
881                                    .unwrap()
882                                    as u32,
883                            },
884                        ));
885                    }
886                }
887
888                let alignment = self.layouter[handle].alignment;
889                if !alignment.is_aligned(span) {
890                    ti.uniform_layout = Err((handle, Disalignment::StructSpan { span, alignment }));
891                    ti.storage_layout = Err((handle, Disalignment::StructSpan { span, alignment }));
892                }
893
894                ti
895            }
896            Ti::Image {
897                dim,
898                arrayed,
899                class,
900            } => {
901                if arrayed && matches!(dim, crate::ImageDimension::D3) {
902                    return Err(TypeError::UnsupportedImageType {
903                        dim,
904                        arrayed,
905                        class,
906                    });
907                }
908                if arrayed && matches!(dim, crate::ImageDimension::Cube) {
909                    self.require_type_capability(Capabilities::CUBE_ARRAY_TEXTURES)?;
910                }
911                if matches!(class, crate::ImageClass::External) {
912                    if dim != crate::ImageDimension::D2 || arrayed {
913                        return Err(TypeError::UnsupportedImageType {
914                            dim,
915                            arrayed,
916                            class,
917                        });
918                    }
919                    self.require_type_capability(Capabilities::TEXTURE_EXTERNAL)?;
920                }
921                TypeInfo::new(
922                    TypeFlags::ARGUMENT | TypeFlags::CREATION_RESOLVED,
923                    Alignment::ONE,
924                )
925            }
926            Ti::Sampler { .. } => TypeInfo::new(
927                TypeFlags::ARGUMENT | TypeFlags::CREATION_RESOLVED,
928                Alignment::ONE,
929            ),
930            Ti::AccelerationStructure { vertex_return } => {
931                self.require_type_capability(Capabilities::RAY_TRACING_PIPELINE)
932                    .or_else(|_| self.require_type_capability(Capabilities::RAY_QUERY))?;
933                if vertex_return {
934                    self.require_type_capability(Capabilities::RAY_HIT_VERTEX_POSITION)?;
935                }
936                TypeInfo::new(
937                    TypeFlags::ARGUMENT | TypeFlags::CREATION_RESOLVED,
938                    Alignment::ONE,
939                )
940            }
941            Ti::RayQuery { vertex_return } => {
942                self.require_type_capability(Capabilities::RAY_QUERY)?;
943                if vertex_return {
944                    self.require_type_capability(Capabilities::RAY_HIT_VERTEX_POSITION)?;
945                }
946                TypeInfo::new(
947                    TypeFlags::DATA
948                        | TypeFlags::CONSTRUCTIBLE
949                        | TypeFlags::SIZED
950                        | TypeFlags::CREATION_RESOLVED,
951                    Alignment::ONE,
952                )
953            }
954            Ti::HitObject => {
955                self.require_type_capability(Capabilities::RAY_TRACING_INVOCATION_REORDER)?;
956                TypeInfo::new(
957                    TypeFlags::DATA
958                        | TypeFlags::CONSTRUCTIBLE
959                        | TypeFlags::SIZED
960                        | TypeFlags::CREATION_RESOLVED,
961                    Alignment::ONE,
962                )
963            }
964            Ti::BindingArray { base, size } => {
965                let type_info_mask = match size {
966                    crate::ArraySize::Constant(_) => {
967                        TypeFlags::SIZED | TypeFlags::HOST_SHAREABLE | TypeFlags::CREATION_RESOLVED
968                    }
969                    crate::ArraySize::Pending(_) => TypeFlags::SIZED | TypeFlags::HOST_SHAREABLE,
970                    crate::ArraySize::Dynamic => {
971                        // Final type is non-sized
972                        TypeFlags::HOST_SHAREABLE | TypeFlags::CREATION_RESOLVED
973                    }
974                };
975                let base_info = &self.types[base.index()];
976
977                if base_info.flags.contains(TypeFlags::DATA) {
978                    // Currently Naga only supports binding arrays of structs for non-handle types.
979                    // `validate_global_var` relies on ray queries (which are `DATA`) being rejected here
980                    match gctx.types[base].inner {
981                        crate::TypeInner::Struct { .. } => {}
982                        _ => return Err(TypeError::BindingArrayBaseTypeNotStruct(base)),
983                    };
984                }
985                if gctx.types[base].inner.is_external_image() {
986                    // Binding arrays of external textures are not yet supported.
987                    // See <https://github.com/gfx-rs/wgpu/issues/8027>. Note that
988                    // `validate_global_var` relies on this error being raised here.
989                    return Err(TypeError::BindingArrayBaseExternalTextures);
990                }
991
992                if !base_info.flags.contains(TypeFlags::CREATION_RESOLVED) {
993                    return Err(TypeError::InvalidData(base));
994                }
995
996                TypeInfo::new(base_info.flags & type_info_mask, Alignment::ONE)
997            }
998        })
999    }
1000}