Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 20:53:56 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions
File diff suppressed because one or more lines are too long
+955
View File
@@ -0,0 +1,955 @@
# Change Log
For changelogs after v0.14, see [the wgpu changelog](../CHANGELOG.md).
## v0.14 (2023-10-25)
#### GENERAL
- Add support for const-expressions. ([#2309](https://github.com/gfx-rs/naga/pull/2309)) **@teoxoy**, **@jimblandy**
- Add support for the `rgb10a2uint` storage format. ([#2525](https://github.com/gfx-rs/naga/pull/2525)) **@teoxoy**
- Implement module compaction for snapshot testing and the CLI. ([#2472](https://github.com/gfx-rs/naga/pull/2472)) **@jimblandy**
- Fix validation and GLSL parsing of `ldexp`. ([#2449](https://github.com/gfx-rs/naga/pull/2449)) **@fornwall**
- Add support for dual source blending. ([#2427](https://github.com/gfx-rs/naga/pull/2427)) **@freqmod**
- Bump `indexmap` to v2. ([#2426](https://github.com/gfx-rs/naga/pull/2426)) **@daxpedda**
- Bump MSRV to 1.65. ([#2420](https://github.com/gfx-rs/naga/pull/2420)) **@jimblandy**
#### API
- Split `UnaryOperator::Not` into `UnaryOperator::LogicalNot` & `UnaryOperator::BitwiseNot`. ([#2554](https://github.com/gfx-rs/naga/pull/2554)) **@teoxoy**
- Remove `IsFinite` & `IsNormal` relational functions. ([#2532](https://github.com/gfx-rs/naga/pull/2532)) **@teoxoy**
- Derive `PartialEq` on `Expression`. ([#2417](https://github.com/gfx-rs/naga/pull/2417)) **@robtfm**
- Use `FastIndexMap` for `SpecialTypes::predeclared_types`. ([#2495](https://github.com/gfx-rs/naga/pull/2495)) **@jimblandy**
#### CLI
- Change `--generate-debug-symbols` from an `option` to a `switch`. ([#2472](https://github.com/gfx-rs/naga/pull/2472)) **@jimblandy**
- Add support for `.{vert,frag,comp}.glsl` files. ([#2462](https://github.com/gfx-rs/naga/pull/2462)) **@eliemichel**
#### VALIDATOR
- Require `Capabilities::FLOAT64` for 64-bit floating-point literals. ([#2567](https://github.com/gfx-rs/naga/pull/2567)) **@jimblandy**
- Add `Capabilities::CUBE_ARRAY_TEXTURES`. ([#2530](https://github.com/gfx-rs/naga/pull/2530)) **@teoxoy**
- Disallow passing pointers to variables in the workgroup address space to functions. ([#2507](https://github.com/gfx-rs/naga/pull/2507)) **@teoxoy**
- Avoid OOM with large sparse resource bindings. ([#2561](https://github.com/gfx-rs/naga/pull/2561)) **@teoxoy**
- Require that `Function` and `Private` variables be `CONSTRUCTIBLE`. ([#2545](https://github.com/gfx-rs/naga/pull/2545)) **@jimblandy**
- Disallow floating-point NaNs and infinities. ([#2508](https://github.com/gfx-rs/naga/pull/2508)) **@teoxoy**
- Temporarily disable uniformity analysis for the fragment stage. ([#2515](https://github.com/gfx-rs/naga/pull/2515)) **@teoxoy**
- Validate that `textureSampleBias` is only used in the fragment stage. ([#2515](https://github.com/gfx-rs/naga/pull/2515)) **@teoxoy**
- Validate variable initializer for address spaces. ([#2513](https://github.com/gfx-rs/naga/pull/2513)) **@teoxoy**
- Prevent using multiple push constant variables in one entry point. ([#2484](https://github.com/gfx-rs/naga/pull/2484)) **@andriyDev**
- Validate `binding_array` variable address space. ([#2422](https://github.com/gfx-rs/naga/pull/2422)) **@teoxoy**
- Validate storage buffer access. ([#2415](https://github.com/gfx-rs/naga/pull/2415)) **@teoxoy**
#### WGSL-IN
- Fix expected min arg count of `textureLoad`. ([#2584](https://github.com/gfx-rs/naga/pull/2584)) **@teoxoy**
- Turn `Error::Other` into `Error::Internal`, to help devs. ([#2574](https://github.com/gfx-rs/naga/pull/2574)) **@jimblandy**
- Fix OOB typifier indexing. ([#2570](https://github.com/gfx-rs/naga/pull/2570)) **@teoxoy**
- Add support for the `bgra8unorm` storage format. ([#2542](https://github.com/gfx-rs/naga/pull/2542) & [#2550](https://github.com/gfx-rs/naga/pull/2550)) **@nical**
- Remove the `outerProduct` built-in function. ([#2535](https://github.com/gfx-rs/naga/pull/2535)) **@teoxoy**
- Add support for `i32` overload of the `sign` built-in function. ([#2463](https://github.com/gfx-rs/naga/pull/2463)) **@fornwall**
- Properly implement `modf` and `frexp`. ([#2454](https://github.com/gfx-rs/naga/pull/2454)) **@fornwall**
- Add support for scalar overloads of `all` & `any` built-in functions. ([#2445](https://github.com/gfx-rs/naga/pull/2445)) **@fornwall**
- Don't splat the left hand operand of a binary operation if it's not a scalar. ([#2444](https://github.com/gfx-rs/naga/pull/2444)) **@fornwall**
- Avoid splatting all binary operator expressions. ([#2440](https://github.com/gfx-rs/naga/pull/2440)) **@fornwall**
- Error on repeated or missing `@workgroup_size()`. ([#2435](https://github.com/gfx-rs/naga/pull/2435)) **@fornwall**
- Error on repeated attributes. ([#2428](https://github.com/gfx-rs/naga/pull/2428)) **@fornwall**
- Fix error message for invalid `texture{Load,Store}()` on arrayed textures. ([#2432](https://github.com/gfx-rs/naga/pull/2432)) **@fornwall**
#### SPV-IN
- Disable `Modf` & `Frexp` and translate `ModfStruct` & `FrexpStruct` to their IR equivalents. ([#2527](https://github.com/gfx-rs/naga/pull/2527)) **@teoxoy**
- Don't advertise support for `Capability::ImageMSArray` & `Capability::InterpolationFunction`. ([#2529](https://github.com/gfx-rs/naga/pull/2529)) **@teoxoy**
- Fix `OpImageQueries` to allow Uints. ([#2404](https://github.com/gfx-rs/naga/pull/2404)) **@evahop**
#### GLSL-IN
- Disable `modf` & `frexp`. ([#2527](https://github.com/gfx-rs/naga/pull/2527)) **@teoxoy**
#### SPV-OUT
- Require `ClipDistance` & `CullDistance` capabilities if necessary. ([#2528](https://github.com/gfx-rs/naga/pull/2528)) **@teoxoy**
- Change `naga::back::spv::DebugInfo::file_name` to a `&Path`. ([#2501](https://github.com/gfx-rs/naga/pull/2501)) **@jimblandy**
- Always give structs with runtime arrays a `Block` decoration. ([#2455](https://github.com/gfx-rs/naga/pull/2455)) **@TheoDulka**
- Decorate the result of the `OpLoad` with `NonUniform` (not the access chain) when loading images/samplers (resources in the Handle address space). ([#2422](https://github.com/gfx-rs/naga/pull/2422)) **@teoxoy**
- Cache `OpConstantNull`. ([#2414](https://github.com/gfx-rs/naga/pull/2414)) **@evahop**
#### MSL-OUT
- Add and fix minimum Metal version checks for optional functionality. ([#2486](https://github.com/gfx-rs/naga/pull/2486)) **@teoxoy**
- Make varyings' struct members unique. ([#2521](https://github.com/gfx-rs/naga/pull/2521)) **@evahop**
- Add experimental vertex pulling transform flag. ([#5254](https://github.com/gfx-rs/wgpu/pull/5254)) **@bradwerth**
- Fixup some generated MSL for vertex buffer unpack functions. ([#5829](https://github.com/gfx-rs/wgpu/pull/5829)) **@bradwerth**
- Make vertex pulling transform on by default. ([#5773](https://github.com/gfx-rs/wgpu/pull/5773)) **@bradwerth**
#### GLSL-OUT
- Cull functions that should not be available for a given stage. ([#2531](https://github.com/gfx-rs/naga/pull/2531)) **@teoxoy**
- Rename identifiers containing double underscores. ([#2510](https://github.com/gfx-rs/naga/pull/2510)) **@evahop**
- Polyfill `frexp`. ([#2504](https://github.com/gfx-rs/naga/pull/2504)) **@evahop**
- Add built-in functions to keywords. ([#2410](https://github.com/gfx-rs/naga/pull/2410)) **@fornwall**
#### WGSL-OUT
- Generate correct code for bit complement on integers. ([#2548](https://github.com/gfx-rs/naga/pull/2548)) **@jimblandy**
- Don't include type parameter in splat expressions. ([#2469](https://github.com/gfx-rs/naga/pull/2469)) **@jimblandy**
## v0.13 (2023-07-21)
#### GENERAL
- Move from `make` to `cargo xtask` workflows. ([#2297](https://github.com/gfx-rs/naga/pull/2297)) **@ErichDonGubler**
- Omit non referenced expressions from output. ([#2378](https://github.com/gfx-rs/naga/pull/2378)) **@teoxoy**
- Bump `bitflags` to v2. ([#2358](https://github.com/gfx-rs/naga/pull/2358)) **@daxpedda**
- Implement `workgroupUniformLoad`. ([#2201](https://github.com/gfx-rs/naga/pull/2201)) **@DJMcNab**
#### API
- Expose early depth test field. ([#2393](https://github.com/gfx-rs/naga/pull/2393)) **@Joeoc2001**
- Split image bounds check policy. ([#2265](https://github.com/gfx-rs/naga/pull/2265)) **@teoxoy**
- Change type of constant sized arrays to `NonZeroU32`. ([#2337](https://github.com/gfx-rs/naga/pull/2337)) **@teoxoy**
- Introduce `GlobalCtx`. ([#2335](https://github.com/gfx-rs/naga/pull/2335)) **@teoxoy**
- Introduce `Expression::Literal`. ([#2333](https://github.com/gfx-rs/naga/pull/2333)) **@teoxoy**
- Introduce `Expression::ZeroValue`. ([#2332](https://github.com/gfx-rs/naga/pull/2332)) **@teoxoy**
- Add support for const-expressions (only at the API level, functionality is still WIP). ([#2266](https://github.com/gfx-rs/naga/pull/2266)) **@teoxoy**, **@jimblandy**
#### DOCS
- Document which expressions are in scope for a `break_if` expression. ([#2326](https://github.com/gfx-rs/naga/pull/2326)) **@jimblandy**
#### VALIDATOR
- Don't `use std::opsIndex`, used only when `"validate"` is on. ([#2383](https://github.com/gfx-rs/naga/pull/2383)) **@jimblandy**
- Remove unneeded `ConstantError::Unresolved{Component,Size}`. ([#2330](https://github.com/gfx-rs/naga/pull/2330)) **@ErichDonGubler**
- Remove `TypeError::UnresolvedBase`. ([#2308](https://github.com/gfx-rs/naga/pull/2308)) **@ErichDonGubler**
#### WGSL-IN
- Error on param redefinition. ([#2342](https://github.com/gfx-rs/naga/pull/2342)) **@SparkyPotato**
#### SPV-IN
- Improve documentation for SPIR-V control flow parsing. ([#2324](https://github.com/gfx-rs/naga/pull/2324)) **@jimblandy**
- Obey the `is_depth` field of `OpTypeImage`. ([#2341](https://github.com/gfx-rs/naga/pull/2341)) **@expenses**
- Convert conditional backedges to `break if`. ([#2290](https://github.com/gfx-rs/naga/pull/2290)) **@eddyb**
#### GLSL-IN
- Support commas in structure definitions. ([#2400](https://github.com/gfx-rs/naga/pull/2400)) **@fornwall**
#### SPV-OUT
- Add debug info. ([#2379](https://github.com/gfx-rs/naga/pull/2379)) **@wicast**
- Use `IndexSet` instead of `HashSet` for iterated sets (capabilities/extensions). ([#2389](https://github.com/gfx-rs/naga/pull/2389)) **@eddyb**
- Support array bindings of buffers. ([#2282](https://github.com/gfx-rs/naga/pull/2282)) **@kvark**
#### MSL-OUT
- Rename `allow_point_size` to `allow_and_force_point_size`. ([#2280](https://github.com/gfx-rs/naga/pull/2280)) **@teoxoy**
- Initialize arrays inline. ([#2331](https://github.com/gfx-rs/naga/pull/2331)) **@teoxoy**
#### HLSL-OUT
- Implement Pack/Unpack for HLSL. ([#2353](https://github.com/gfx-rs/naga/pull/2353)) **@Elabajaba**
- Complete HLSL reserved symbols. ([#2367](https://github.com/gfx-rs/naga/pull/2367)) **@teoxoy**
- Handle case insensitive FXC keywords. ([#2347](https://github.com/gfx-rs/naga/pull/2347)) **@PJB3005**
- Fix return type for firstbitlow/high. ([#2315](https://github.com/gfx-rs/naga/pull/2315)) **@evahop**
#### GLSL-OUT
- `textureSize` level must be a signed integer. ([#2397](https://github.com/gfx-rs/naga/pull/2397)) **@nical**
- Fix functions with array return type. ([#2382](https://github.com/gfx-rs/naga/pull/2382)) **@Gordon-F**
#### WGSL-OUT
- Output `@interpolate(flat)` attribute for integer locations. ([#2318](https://github.com/gfx-rs/naga/pull/2318)) **@expenses**
## v0.12.3 (2023-07-09)
#### WGSL-OUT
- (Backport) Output `@interpolate(flat)` attribute for integer locations. ([#2318](https://github.com/gfx-rs/naga/pull/2318)) **@expenses**
## v0.12.2 (2023-05-30)
#### SPV-OUT
- (Backport) Support array bindings of buffers. ([#2282](https://github.com/gfx-rs/naga/pull/2282)) **@kvark**
## v0.12.1 (2023-05-18)
#### SPV-IN
- (Backport) Convert conditional backedges to `break if`. ([#2290](https://github.com/gfx-rs/naga/pull/2290)) **@eddyb**
## v0.12 (2023-04-19)
#### GENERAL
- Allow `array_index` to be unsigned. ([#2298](https://github.com/gfx-rs/naga/pull/2298)) **@daxpedda**
- Add ray query support. ([#2256](https://github.com/gfx-rs/naga/pull/2256)) **@kvark**
- Add partial derivative builtins. ([#2277](https://github.com/gfx-rs/naga/pull/2277)) **@evahop**
- Skip `gl_PerVertex` unused builtins in the SPIR-V frontend. ([#2272](https://github.com/gfx-rs/naga/pull/2272)) **@teoxoy**
- Differentiate between `i32` and `u32` in switch statement cases. ([#2269](https://github.com/gfx-rs/naga/pull/2269)) **@evahop**
- Fix zero initialization of workgroup memory. ([#2259](https://github.com/gfx-rs/naga/pull/2259)) **@teoxoy**
- Add `countTrailingZeros`. ([#2243](https://github.com/gfx-rs/naga/pull/2243)) **@gents83**
- Fix texture built-ins where u32 was expected. ([#2245](https://github.com/gfx-rs/naga/pull/2245)) **@evahop**
- Add `countLeadingZeros`. ([#2226](https://github.com/gfx-rs/naga/pull/2226)) **@evahop**
- [glsl/hlsl-out] Write sizes of arrays behind pointers in function arguments. ([#2250](https://github.com/gfx-rs/naga/pull/2250)) **@pluiedev**
#### VALIDATOR
- Validate vertex stage returns the position built-in. ([#2264](https://github.com/gfx-rs/naga/pull/2264)) **@teoxoy**
- Enforce discard is only used in the fragment stage. ([#2262](https://github.com/gfx-rs/naga/pull/2262)) **@Uriopass**
- Add `Capabilities::MULTISAMPLED_SHADING`. ([#2255](https://github.com/gfx-rs/naga/pull/2255)) **@teoxoy**
- Add `Capabilities::EARLY_DEPTH_TEST`. ([#2255](https://github.com/gfx-rs/naga/pull/2255)) **@teoxoy**
- Add `Capabilities::MULTIVIEW`. ([#2255](https://github.com/gfx-rs/naga/pull/2255)) **@teoxoy**
- Improve forward declaration validation. ([#2232](https://github.com/gfx-rs/naga/pull/2232)) **@JCapucho**
#### WGSL-IN
- Use `alias` instead of `type` for type aliases. ([#2299](https://github.com/gfx-rs/naga/pull/2299)) **@FL33TW00D**
- Add predeclared vector and matrix type aliases. ([#2251](https://github.com/gfx-rs/naga/pull/2251)) **@evahop**
- Improve invalid assignment diagnostic. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato**
- Expect semicolons wherever required. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato**
- Fix panic on invalid zero array size. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato**
- Check for leading `{` while parsing a block. ([#2233](https://github.com/gfx-rs/naga/pull/2233)) **@SparkyPotato**
#### SPV-IN
- Don't apply interpolation to fragment shaders outputs. ([#2239](https://github.com/gfx-rs/naga/pull/2239)) **@JCapucho**
#### GLSL-IN
- Add switch implicit type conversion. ([#2273](https://github.com/gfx-rs/naga/pull/2273)) **@evahop**
- Document some fields of `naga::front::glsl::context::Context`. ([#2244](https://github.com/gfx-rs/naga/pull/2244)) **@jimblandy**
- Perform output parameters implicit casts. ([#2063](https://github.com/gfx-rs/naga/pull/2063)) **@JCapucho**
- Add `not` vector relational builtin. ([#2227](https://github.com/gfx-rs/naga/pull/2227)) **@JCapucho**
- Add double overloads for relational vector builtins. ([#2227](https://github.com/gfx-rs/naga/pull/2227)) **@JCapucho**
- Add bool overloads for relational vector builtins. ([#2227](https://github.com/gfx-rs/naga/pull/2227)) **@JCapucho**
#### SPV-OUT
- Fix invalid spirv being generated from integer dot products. ([#2291](https://github.com/gfx-rs/naga/pull/2291)) **@PyryM**
- Fix adding illegal decorators on fragment outputs. ([#2286](https://github.com/gfx-rs/naga/pull/2286)) **@Wumpf**
- Fix `countLeadingZeros` impl. ([#2258](https://github.com/gfx-rs/naga/pull/2258)) **@teoxoy**
- Cache constant composites. ([#2257](https://github.com/gfx-rs/naga/pull/2257)) **@evahop**
- Support SPIR-V version 1.4. ([#2230](https://github.com/gfx-rs/naga/pull/2230)) **@kvark**
#### MSL-OUT
- Replace `per_stage_map` with `per_entry_point_map` ([#2237](https://github.com/gfx-rs/naga/pull/2237)) **@armansito**
- Update `firstLeadingBit` for signed integers ([#2235](https://github.com/gfx-rs/naga/pull/2235)) **@evahop**
#### HLSL-OUT
- Use `Interlocked<op>` intrinsic for atomic integers (#2294) ([#2294](https://github.com/gfx-rs/naga/pull/2294)) **@ErichDonGubler**
- Document storage access generation. ([#2295](https://github.com/gfx-rs/naga/pull/2295)) **@jimblandy**
- Emit constructor functions for arrays. ([#2281](https://github.com/gfx-rs/naga/pull/2281)) **@ErichDonGubler**
- Clear `named_expressions` inserted by duplicated blocks. ([#2116](https://github.com/gfx-rs/naga/pull/2116)) **@teoxoy**
#### GLSL-OUT
- Skip `invariant` for `gl_FragCoord` on WebGL2. ([#2254](https://github.com/gfx-rs/naga/pull/2254)) **@grovesNL**
- Inject default `gl_PointSize = 1.0` in vertex shaders if `FORCE_POINT_SIZE` option was set. ([#2223](https://github.com/gfx-rs/naga/pull/2223)) **@REASY**
## v0.11.1 (2023-05-18)
#### SPV-IN
- (Backport) Convert conditional backedges to `break if`. ([#2290](https://github.com/gfx-rs/naga/pull/2290)) **@eddyb**
## v0.11 (2023-01-25)
- Move to the Rust 2021 edition ([#2085](https://github.com/gfx-rs/naga/pull/2085)) **@ErichDonGubler**
- Bump MSRV to 1.63 ([#2129](https://github.com/gfx-rs/naga/pull/2129)) **@teoxoy**
#### API
- Add handle validation pass to `Validator` ([#2090](https://github.com/gfx-rs/naga/pull/2090)) **@ErichDonGubler**
- Add `Range::new_from_bounds` ([#2148](https://github.com/gfx-rs/naga/pull/2148)) **@robtfm**
#### DOCS
- Fix docs for `Emit` statements ([#2208](https://github.com/gfx-rs/naga/pull/2208)) **@jimblandy**
- Fix invalid `<...>` URLs with code spans ([#2176](https://github.com/gfx-rs/naga/pull/2176)) **@ErichDonGubler**
- Explain how case clauses with multiple selectors are supported ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
- Document `EarlyDepthTest` and `ConservativeDepth` syntax ([#2132](https://github.com/gfx-rs/naga/pull/2132)) **@coreh**
#### VALIDATOR
- Allow `u32` coordinates for `textureStore`/`textureLoad` ([#2172](https://github.com/gfx-rs/naga/pull/2172)) **@PENGUINLIONG**
- Fix array being flagged as constructible when its base isn't ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy**
- Add `type_flags` to `ModuleInfo` ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy**
- Remove overly restrictive array stride check ([#2215](https://github.com/gfx-rs/naga/pull/2215)) **@fintelia**
- Let the uniformity analysis trust the handle validation pass ([#2200](https://github.com/gfx-rs/naga/pull/2200)) **@jimblandy**
- Fix warnings when building tests without validation ([#2177](https://github.com/gfx-rs/naga/pull/2177)) **@jimblandy**
- Add `ValidationFlags::BINDINGS` ([#2156](https://github.com/gfx-rs/naga/pull/2156)) **@kvark**
- Fix `textureGather` on `texture_2d<u32/i32>` ([#2138](https://github.com/gfx-rs/naga/pull/2138)) **@JMS55**
#### ALL (FRONTENDS/BACKENDS)
- Support 16-bit unorm/snorm formats ([#2210](https://github.com/gfx-rs/naga/pull/2210)) **@fintelia**
- Support `gl_PointCoord` ([#2180](https://github.com/gfx-rs/naga/pull/2180)) **@Neo-Zhixing**
#### ALL BACKENDS
- Add support for zero-initializing workgroup memory ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy**
#### WGSL-IN
- Implement module-level scoping ([#2075](https://github.com/gfx-rs/naga/pull/2075)) **@SparkyPotato**
- Remove `isFinite` and `isNormal` ([#2218](https://github.com/gfx-rs/naga/pull/2218)) **@evahop**
- Update inverse hyperbolic built-ins ([#2218](https://github.com/gfx-rs/naga/pull/2218)) **@evahop**
- Add `refract` built-in ([#2218](https://github.com/gfx-rs/naga/pull/2218)) **@evahop**
- Update reserved keywords ([#2130](https://github.com/gfx-rs/naga/pull/2130)) **@teoxoy**
- Remove non-32bit integers ([#2146](https://github.com/gfx-rs/naga/pull/2146)) **@teoxoy**
- Remove `workgroup_size` builtin ([#2147](https://github.com/gfx-rs/naga/pull/2147)) **@teoxoy**
- Remove fallthrough statement ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
#### SPV-IN
- Support binding arrays ([#2199](https://github.com/gfx-rs/naga/pull/2199)) **@Patryk27**
#### GLSL-IN
- Fix position propagation in lowering ([#2079](https://github.com/gfx-rs/naga/pull/2079)) **@JCapucho**
- Update initializer list type when parsing ([#2066](https://github.com/gfx-rs/naga/pull/2066)) **@JCapucho**
- Parenthesize unary negations to avoid `--` ([#2087](https://github.com/gfx-rs/naga/pull/2087)) **@ErichDonGubler**
#### SPV-OUT
- Add support for `atomicCompareExchangeWeak` ([#2165](https://github.com/gfx-rs/naga/pull/2165)) **@aweinstock314**
- Omit extra switch case blocks where possible ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
- Fix switch cases after default not being output ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
#### MSL-OUT
- Don't panic on missing bindings ([#2175](https://github.com/gfx-rs/naga/pull/2175)) **@kvark**
- Omit extra switch case blocks where possible ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
- Fix `textureGather` compatibility on macOS 10.13 ([#2104](https://github.com/gfx-rs/naga/pull/2104)) **@xiaopengli89**
- Fix incorrect atomic bounds check on metal back-end ([#2099](https://github.com/gfx-rs/naga/pull/2099)) **@raphlinus**
- Parenthesize unary negations to avoid `--` ([#2087](https://github.com/gfx-rs/naga/pull/2087)) **@ErichDonGubler**
#### HLSL-OUT
- Simplify `write_default_init` ([#2111](https://github.com/gfx-rs/naga/pull/2111)) **@teoxoy**
- Omit extra switch case blocks where possible ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
- Properly implement bitcast ([#2097](https://github.com/gfx-rs/naga/pull/2097)) **@cwfitzgerald**
- Fix storage access chain through a matrix ([#2097](https://github.com/gfx-rs/naga/pull/2097)) **@cwfitzgerald**
- Workaround FXC Bug in Matrix Indexing ([#2096](https://github.com/gfx-rs/naga/pull/2096)) **@cwfitzgerald**
- Parenthesize unary negations to avoid `--` ([#2087](https://github.com/gfx-rs/naga/pull/2087)) **@ErichDonGubler**
#### GLSL-OUT
- Introduce a flag to include unused items ([#2205](https://github.com/gfx-rs/naga/pull/2205)) **@robtfm**
- Use `fma` polyfill for versions below gles 320 ([#2197](https://github.com/gfx-rs/naga/pull/2197)) **@teoxoy**
- Emit reflection info for non-struct uniforms ([#2189](https://github.com/gfx-rs/naga/pull/2189)) **@Rainb0wCodes**
- Introduce a new block for switch cases ([#2126](https://github.com/gfx-rs/naga/pull/2126)) **@teoxoy**
#### WGSL-OUT
- Write correct scalar kind when `width != 4` ([#1514](https://github.com/gfx-rs/naga/pull/1514)) **@fintelia**
## v0.10.1 (2023-06-21)
SPV-OUT
- Backport #2389 (Use `IndexSet` instead of `HashSet` for iterated sets (capabilities/extensions)) by @eddyb, @jimblandy in https://github.com/gfx-rs/naga/pull/2391
SPV-IN
- Backport #2290 (Convert conditional backedges to `break if`) by @eddyb in https://github.com/gfx-rs/naga/pull/2387
## v0.10 (2022-10-05)
- Make termcolor dependency optional by @AldaronLau in https://github.com/gfx-rs/naga/pull/2014
- Fix clippy lints for 1.63 by @JCapucho in https://github.com/gfx-rs/naga/pull/2026
- Saturate by @evahop in https://github.com/gfx-rs/naga/pull/2025
- Use `Option::as_deref` as appropriate. by @jimblandy in https://github.com/gfx-rs/naga/pull/2040
- Explicitly enable std for indexmap by @maxammann in https://github.com/gfx-rs/naga/pull/2062
- Fix compiler warning by @Gordon-F in https://github.com/gfx-rs/naga/pull/2074
API
- Implement `Clone` for `Module` by @daxpedda in https://github.com/gfx-rs/naga/pull/2013
- Remove the glsl-validate feature by @JCapucho in https://github.com/gfx-rs/naga/pull/2045
DOCS
- Document arithmetic binary operation type rules. by @jimblandy in https://github.com/gfx-rs/naga/pull/2051
VALIDATOR
- Add `emit_to_{stderr,string}` helpers to validation error by @nolanderc in https://github.com/gfx-rs/naga/pull/2012
- Check regular functions don't have bindings by @JCapucho in https://github.com/gfx-rs/naga/pull/2050
WGSL-IN
- Update reserved WGSL keywords by @norepimorphism in https://github.com/gfx-rs/naga/pull/2009
- Implement lexical scopes by @JCapucho in https://github.com/gfx-rs/naga/pull/2024
- Rename `Scope` to `Rule`, since we now have lexical scope. by @jimblandy in https://github.com/gfx-rs/naga/pull/2042
- Splat on compound assignments by @JCapucho in https://github.com/gfx-rs/naga/pull/2049
- Fix bad span in assignment lhs error by @JCapucho in https://github.com/gfx-rs/naga/pull/2054
- Fix inclusion of trivia in spans by @SparkyPotato in https://github.com/gfx-rs/naga/pull/2055
- Improve assignment diagnostics by @SparkyPotato in https://github.com/gfx-rs/naga/pull/2056
- Break up long string, reformat rest of file. by @jimblandy in https://github.com/gfx-rs/naga/pull/2057
- Fix line endings on wgsl reserved words list. by @jimblandy in https://github.com/gfx-rs/naga/pull/2059
GLSL-IN
- Add support for .length() by @SpaceCat-Chan in https://github.com/gfx-rs/naga/pull/2017
- Fix missing stores for local declarations by @adeline-sparks in https://github.com/gfx-rs/naga/pull/2029
- Migrate to `SymbolTable` by @JCapucho in https://github.com/gfx-rs/naga/pull/2044
- Update initializer list type when parsing by @JCapucho in https://github.com/gfx-rs/naga/pull/2066
SPV-OUT
- Don't decorate varyings with interpolation modes at pipeline start/end by @nical in https://github.com/gfx-rs/naga/pull/2038
- Decorate integer builtins as Flat in the spirv writer by @nical in https://github.com/gfx-rs/naga/pull/2035
- Properly combine the fixes for #2035 and #2038. by @jimblandy in https://github.com/gfx-rs/naga/pull/2041
- Don't emit no-op `OpBitCast` instructions. by @jimblandy in https://github.com/gfx-rs/naga/pull/2043
HLSL-OUT
- Use the namer to sanitise entrypoint input/output struct names by @expenses in https://github.com/gfx-rs/naga/pull/2001
- Handle Unpack2x16float in hlsl by @expenses in https://github.com/gfx-rs/naga/pull/2002
- Add support for push constants by @JCapucho in https://github.com/gfx-rs/naga/pull/2005
DOT-OUT
- Improvements by @JCapucho in https://github.com/gfx-rs/naga/pull/1987
## v0.9 (2022-06-30)
- Fix minimal-versions of dependencies ([#1840](https://github.com/gfx-rs/naga/pull/1840)) **@teoxoy**
- Update MSRV to 1.56 ([#1838](https://github.com/gfx-rs/naga/pull/1838)) **@teoxoy**
API
- Rename `TypeFlags` `INTERFACE`/`HOST_SHARED` to `IO_SHARED`/`HOST_SHAREABLE` ([#1872](https://github.com/gfx-rs/naga/pull/1872)) **@jimblandy**
- Expose more error information ([#1827](https://github.com/gfx-rs/naga/pull/1827), [#1937](https://github.com/gfx-rs/naga/pull/1937)) **@jakobhellermann** **@nical** **@jimblandy**
- Do not unconditionally make error output colorful ([#1707](https://github.com/gfx-rs/naga/pull/1707)) **@rhysd**
- Rename `StorageClass` to `AddressSpace` ([#1699](https://github.com/gfx-rs/naga/pull/1699)) **@kvark**
- Add a way to emit errors to a path ([#1640](https://github.com/gfx-rs/naga/pull/1640)) **@laptou**
CLI
- Add `bincode` representation ([#1729](https://github.com/gfx-rs/naga/pull/1729)) **@kvark**
- Include file path in WGSL parse error ([#1708](https://github.com/gfx-rs/naga/pull/1708)) **@rhysd**
- Add `--version` flag ([#1706](https://github.com/gfx-rs/naga/pull/1706)) **@rhysd**
- Support reading input from stdin via `--stdin-file-path` ([#1701](https://github.com/gfx-rs/naga/pull/1701)) **@rhysd**
- Use `panic = "abort"` ([#1597](https://github.com/gfx-rs/naga/pull/1597)) **@jrmuizel**
DOCS
- Standardize some docs ([#1660](https://github.com/gfx-rs/naga/pull/1660)) **@NoelTautges**
- Document `TypeInner::BindingArray` ([#1859](https://github.com/gfx-rs/naga/pull/1859)) **@jimblandy**
- Clarify accepted types for `Expression::AccessIndex` ([#1862](https://github.com/gfx-rs/naga/pull/1862)) **@NoelTautges**
- Document `proc::layouter` ([#1693](https://github.com/gfx-rs/naga/pull/1693)) **@jimblandy**
- Document Naga's promises around validation and panics ([#1828](https://github.com/gfx-rs/naga/pull/1828)) **@jimblandy**
- `FunctionInfo` doc fixes ([#1726](https://github.com/gfx-rs/naga/pull/1726)) **@jimblandy**
VALIDATOR
- Forbid returning pointers and atomics from functions ([#911](https://github.com/gfx-rs/naga/pull/911)) **@jimblandy**
- Let validation check for more unsupported builtins ([#1962](https://github.com/gfx-rs/naga/pull/1962)) **@jimblandy**
- Fix `Capabilities::SAMPLER_NON_UNIFORM_INDEXING` bitflag ([#1915](https://github.com/gfx-rs/naga/pull/1915)) **@cwfitzgerald**
- Properly check that user-defined IO uses IO-shareable types ([#912](https://github.com/gfx-rs/naga/pull/912)) **@jimblandy**
- Validate `ValuePointer` exactly like a `Pointer` to a `Scalar` ([#1875](https://github.com/gfx-rs/naga/pull/1875)) **@jimblandy**
- Reject empty structs ([#1826](https://github.com/gfx-rs/naga/pull/1826)) **@jimblandy**
- Validate uniform address space layout constraints ([#1812](https://github.com/gfx-rs/naga/pull/1812)) **@teoxoy**
- Improve `AddressSpace` related error messages ([#1710](https://github.com/gfx-rs/naga/pull/1710)) **@kvark**
WGSL-IN
Main breaking changes
- Commas to separate struct members (comma after last member is optional)
- `struct S { a: f32; b: i32; }` -> `struct S { a: f32, b: i32 }`
- Attribute syntax
- `[[binding(0), group(0)]]` -> `@binding(0) @group(0)`
- Entry point stage attributes
- `@stage(vertex)` -> `@vertex`
- `@stage(fragment)` -> `@fragment`
- `@stage(compute)` -> `@compute`
- Function renames
- `smoothStep` -> `smoothstep`
- `findLsb` -> `firstTrailingBit`
- `findMsb` -> `firstLeadingBit`
Specification Changes (relevant changes have also been applied to the WGSL backend)
- Add support for `break if` ([#1993](https://github.com/gfx-rs/naga/pull/1993)) **@JCapucho**
- Update number literal format ([#1863](https://github.com/gfx-rs/naga/pull/1863)) **@teoxoy**
- Allow non-ascii characters in identifiers ([#1849](https://github.com/gfx-rs/naga/pull/1849)) **@teoxoy**
- Update reserved keywords ([#1847](https://github.com/gfx-rs/naga/pull/1847), [#1870](https://github.com/gfx-rs/naga/pull/1870), [#1905](https://github.com/gfx-rs/naga/pull/1905)) **@teoxoy** **@Gordon-F**
- Update entry point stage attributes ([#1833](https://github.com/gfx-rs/naga/pull/1833)) **@Gordon-F**
- Make colon in case optional ([#1801](https://github.com/gfx-rs/naga/pull/1801)) **@Gordon-F**
- Rename `smoothStep` to `smoothstep` ([#1800](https://github.com/gfx-rs/naga/pull/1800)) **@Gordon-F**
- Make semicolon after struct declaration optional ([#1791](https://github.com/gfx-rs/naga/pull/1791)) **@stshine**
- Use commas to separate struct members instead of semicolons ([#1773](https://github.com/gfx-rs/naga/pull/1773)) **@Gordon-F**
- Rename `findLsb`/`findMsb` to `firstTrailingBit`/`firstLeadingBit` ([#1735](https://github.com/gfx-rs/naga/pull/1735)) **@kvark**
- Make parenthesis optional for `if` and `switch` statements ([#1725](https://github.com/gfx-rs/naga/pull/1725)) **@Gordon-F**
- Declare attributes with `@attrib` instead of `[[attrib]]` ([#1676](https://github.com/gfx-rs/naga/pull/1676)) **@kvark**
- Allow non-structure buffer types ([#1682](https://github.com/gfx-rs/naga/pull/1682)) **@kvark**
- Remove `stride` attribute ([#1681](https://github.com/gfx-rs/naga/pull/1681)) **@kvark**
Improvements
- Implement complete validation for size and align attributes ([#1979](https://github.com/gfx-rs/naga/pull/1979)) **@teoxoy**
- Implement `firstTrailingBit`/`firstLeadingBit` u32 overloads ([#1865](https://github.com/gfx-rs/naga/pull/1865)) **@teoxoy**
- Add error for non-floating-point matrix ([#1917](https://github.com/gfx-rs/naga/pull/1917)) **@grovesNL**
- Implement partial vector & matrix identity constructors ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy**
- Implement phony assignment ([#1866](https://github.com/gfx-rs/naga/pull/1866), [#1869](https://github.com/gfx-rs/naga/pull/1869)) **@teoxoy**
- Fix being able to match `~=` as LogicalOperation ([#1849](https://github.com/gfx-rs/naga/pull/1849)) **@teoxoy**
- Implement Binding Arrays ([#1845](https://github.com/gfx-rs/naga/pull/1845)) **@cwfitzgerald**
- Implement unary vector operators ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy**
- Implement zero value constructors and constructors that infer their type from their parameters ([#1790](https://github.com/gfx-rs/naga/pull/1790)) **@teoxoy**
- Implement invariant attribute ([#1789](https://github.com/gfx-rs/naga/pull/1789), [#1822](https://github.com/gfx-rs/naga/pull/1822)) **@teoxoy** **@jimblandy**
- Implement increment and decrement statements ([#1788](https://github.com/gfx-rs/naga/pull/1788), [#1912](https://github.com/gfx-rs/naga/pull/1912)) **@teoxoy**
- Implement `while` loop ([#1787](https://github.com/gfx-rs/naga/pull/1787)) **@teoxoy**
- Fix array size on globals ([#1717](https://github.com/gfx-rs/naga/pull/1717)) **@jimblandy**
- Implement integer vector overloads for `dot` function ([#1689](https://github.com/gfx-rs/naga/pull/1689)) **@francesco-cattoglio**
- Implement block comments ([#1675](https://github.com/gfx-rs/naga/pull/1675)) **@kocsis1david**
- Implement assignment binary operators ([#1662](https://github.com/gfx-rs/naga/pull/1662)) **@kvark**
- Implement `radians`/`degrees` builtin functions ([#1627](https://github.com/gfx-rs/naga/pull/1627)) **@encounter**
- Implement `findLsb`/`findMsb` builtin functions ([#1473](https://github.com/gfx-rs/naga/pull/1473)) **@fintelia**
- Implement `textureGather`/`textureGatherCompare` builtin functions ([#1596](https://github.com/gfx-rs/naga/pull/1596)) **@kvark**
SPV-IN
- Implement `OpBitReverse` and `OpBitCount` ([#1954](https://github.com/gfx-rs/naga/pull/1954)) **@JCapucho**
- Add `MultiView` to `SUPPORTED_CAPABILITIES` ([#1934](https://github.com/gfx-rs/naga/pull/1934)) **@expenses**
- Translate `OpSMod` and `OpFMod` correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867), [#1995](https://github.com/gfx-rs/naga/pull/1995)) **@teoxoy** **@JCapucho**
- Error on unsupported `MatrixStride` ([#1805](https://github.com/gfx-rs/naga/pull/1805)) **@teoxoy**
- Align array stride for undecorated arrays ([#1724](https://github.com/gfx-rs/naga/pull/1724)) **@JCapucho**
GLSL-IN
- Don't allow empty last case in switch ([#1981](https://github.com/gfx-rs/naga/pull/1981)) **@JCapucho**
- Fix last case fallthrough and empty switch ([#1981](https://github.com/gfx-rs/naga/pull/1981)) **@JCapucho**
- Splat inputs for smoothstep if needed ([#1976](https://github.com/gfx-rs/naga/pull/1976)) **@JCapucho**
- Fix parameter not changing to depth ([#1967](https://github.com/gfx-rs/naga/pull/1967)) **@JCapucho**
- Fix matrix multiplication check ([#1953](https://github.com/gfx-rs/naga/pull/1953)) **@JCapucho**
- Fix panic (stop emitter in conditional) ([#1952](https://github.com/gfx-rs/naga/pull/1952)) **@JCapucho**
- Translate `mod` fn correctly ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy**
- Make the ternary operator behave as an if ([#1877](https://github.com/gfx-rs/naga/pull/1877)) **@JCapucho**
- Add support for `clamp` function ([#1502](https://github.com/gfx-rs/naga/pull/1502)) **@sjinno**
- Better errors for bad constant expression ([#1501](https://github.com/gfx-rs/naga/pull/1501)) **@sjinno**
- Error on a `matCx2` used with the `std140` layout ([#1806](https://github.com/gfx-rs/naga/pull/1806)) **@teoxoy**
- Allow nested accesses in lhs positions ([#1794](https://github.com/gfx-rs/naga/pull/1794)) **@JCapucho**
- Use forced conversions for vector/matrix constructors ([#1796](https://github.com/gfx-rs/naga/pull/1796)) **@JCapucho**
- Add support for `barrier` function ([#1793](https://github.com/gfx-rs/naga/pull/1793)) **@fintelia**
- Fix panic (resume expression emit after `imageStore`) ([#1795](https://github.com/gfx-rs/naga/pull/1795)) **@JCapucho**
- Allow multiple array specifiers ([#1780](https://github.com/gfx-rs/naga/pull/1780)) **@JCapucho**
- Fix memory qualifiers being inverted ([#1779](https://github.com/gfx-rs/naga/pull/1779)) **@JCapucho**
- Support arrays as input/output types ([#1759](https://github.com/gfx-rs/naga/pull/1759)) **@JCapucho**
- Fix freestanding constructor parsing ([#1758](https://github.com/gfx-rs/naga/pull/1758)) **@JCapucho**
- Fix matrix - scalar operations ([#1757](https://github.com/gfx-rs/naga/pull/1757)) **@JCapucho**
- Fix matrix - matrix division ([#1757](https://github.com/gfx-rs/naga/pull/1757)) **@JCapucho**
- Fix matrix comparisons ([#1757](https://github.com/gfx-rs/naga/pull/1757)) **@JCapucho**
- Add support for `texelFetchOffset` ([#1746](https://github.com/gfx-rs/naga/pull/1746)) **@JCapucho**
- Inject `sampler2DMSArray` builtins on use ([#1737](https://github.com/gfx-rs/naga/pull/1737)) **@JCapucho**
- Inject `samplerCubeArray` builtins on use ([#1736](https://github.com/gfx-rs/naga/pull/1736)) **@JCapucho**
- Add support for image builtin functions ([#1723](https://github.com/gfx-rs/naga/pull/1723)) **@JCapucho**
- Add support for image declarations ([#1723](https://github.com/gfx-rs/naga/pull/1723)) **@JCapucho**
- Texture builtins fixes ([#1719](https://github.com/gfx-rs/naga/pull/1719)) **@JCapucho**
- Type qualifiers rework ([#1713](https://github.com/gfx-rs/naga/pull/1713)) **@JCapucho**
- `texelFetch` accept multisampled textures ([#1715](https://github.com/gfx-rs/naga/pull/1715)) **@JCapucho**
- Fix panic when culling nested block ([#1714](https://github.com/gfx-rs/naga/pull/1714)) **@JCapucho**
- Fix composite constructors ([#1631](https://github.com/gfx-rs/naga/pull/1631)) **@JCapucho**
- Fix using swizzle as out arguments ([#1632](https://github.com/gfx-rs/naga/pull/1632)) **@JCapucho**
SPV-OUT
- Implement `reverseBits` and `countOneBits` ([#1897](https://github.com/gfx-rs/naga/pull/1897)) **@hasali19**
- Use `OpCopyObject` for matrix identity casts ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy**
- Use `OpCopyObject` for bool - bool conversion due to `OpBitcast` not being feasible for booleans ([#1916](https://github.com/gfx-rs/naga/pull/1916)) **@teoxoy**
- Zero init variables in function and private address spaces ([#1871](https://github.com/gfx-rs/naga/pull/1871)) **@teoxoy**
- Use `SRem` instead of `SMod` ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy**
- Add support for integer vector - scalar multiplication ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy**
- Add support for matrix addition and subtraction ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy**
- Emit required decorations on wrapper struct types ([#1815](https://github.com/gfx-rs/naga/pull/1815)) **@jimblandy**
- Decorate array and struct type layouts unconditionally ([#1815](https://github.com/gfx-rs/naga/pull/1815)) **@jimblandy**
- Fix wrong `MatrixStride` for `matCx2` and `mat2xR` ([#1781](https://github.com/gfx-rs/naga/pull/1781)) **@teoxoy**
- Use `OpImageQuerySize` for MS images ([#1742](https://github.com/gfx-rs/naga/pull/1742)) **@JCapucho**
MSL-OUT
- Insert padding initialization for global constants ([#1988](https://github.com/gfx-rs/naga/pull/1988)) **@teoxoy**
- Don't rely on cached expressions ([#1975](https://github.com/gfx-rs/naga/pull/1975)) **@JCapucho**
- Fix pointers to private or workgroup address spaces possibly being read only ([#1901](https://github.com/gfx-rs/naga/pull/1901)) **@teoxoy**
- Zero init variables in function address space ([#1871](https://github.com/gfx-rs/naga/pull/1871)) **@teoxoy**
- Make binding arrays play nice with bounds checks ([#1855](https://github.com/gfx-rs/naga/pull/1855)) **@cwfitzgerald**
- Permit `invariant` qualifier on vertex shader outputs ([#1821](https://github.com/gfx-rs/naga/pull/1821)) **@jimblandy**
- Fix packed `vec3` stores ([#1816](https://github.com/gfx-rs/naga/pull/1816)) **@teoxoy**
- Actually test push constants to be used ([#1767](https://github.com/gfx-rs/naga/pull/1767)) **@kvark**
- Properly rename entry point arguments for struct members ([#1766](https://github.com/gfx-rs/naga/pull/1766)) **@jimblandy**
- Qualify read-only storage with const ([#1763](https://github.com/gfx-rs/naga/pull/1763)) **@kvark**
- Fix not unary operator for integer scalars ([#1760](https://github.com/gfx-rs/naga/pull/1760)) **@vincentisambart**
- Add bounds checks for `ImageLoad` and `ImageStore` ([#1730](https://github.com/gfx-rs/naga/pull/1730)) **@jimblandy**
- Fix resource bindings for non-structures ([#1718](https://github.com/gfx-rs/naga/pull/1718)) **@kvark**
- Always check whether _buffer_sizes arg is needed ([#1717](https://github.com/gfx-rs/naga/pull/1717)) **@jimblandy**
- WGSL storage address space should always correspond to MSL device address space ([#1711](https://github.com/gfx-rs/naga/pull/1711)) **@wtholliday**
- Mitigation for MSL atomic bounds check ([#1703](https://github.com/gfx-rs/naga/pull/1703)) **@glalonde**
HLSL-OUT
- More `matCx2` fixes (#1989) ([#1989](https://github.com/gfx-rs/naga/pull/1989)) **@teoxoy**
- Fix fallthrough in switch statements ([#1920](https://github.com/gfx-rs/naga/pull/1920)) **@teoxoy**
- Fix missing break statements ([#1919](https://github.com/gfx-rs/naga/pull/1919)) **@teoxoy**
- Fix `countOneBits` and `reverseBits` for signed integers ([#1928](https://github.com/gfx-rs/naga/pull/1928)) **@hasali19**
- Fix array constructor return type ([#1914](https://github.com/gfx-rs/naga/pull/1914)) **@teoxoy**
- Fix hlsl output for writes to scalar/vector storage buffer ([#1903](https://github.com/gfx-rs/naga/pull/1903)) **@hasali19**
- Use `fmod` instead of `%` ([#1867](https://github.com/gfx-rs/naga/pull/1867)) **@teoxoy**
- Use wrapped constructors when loading from storage address space ([#1893](https://github.com/gfx-rs/naga/pull/1893)) **@teoxoy**
- Zero init struct constructor ([#1890](https://github.com/gfx-rs/naga/pull/1890)) **@teoxoy**
- Flesh out matrix handling documentation ([#1850](https://github.com/gfx-rs/naga/pull/1850)) **@jimblandy**
- Emit `row_major` qualifier on matrix uniform globals ([#1846](https://github.com/gfx-rs/naga/pull/1846)) **@jimblandy**
- Fix bool splat ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy**
- Add more padding when necessary ([#1814](https://github.com/gfx-rs/naga/pull/1814)) **@teoxoy**
- Support multidimensional arrays ([#1814](https://github.com/gfx-rs/naga/pull/1814)) **@teoxoy**
- Don't output interpolation modifier if it's the default ([#1809](https://github.com/gfx-rs/naga/pull/1809)) **@NoelTautges**
- Fix `matCx2` translation for uniform buffers ([#1802](https://github.com/gfx-rs/naga/pull/1802)) **@teoxoy**
- Fix modifiers not being written in the vertex output and fragment input structs ([#1789](https://github.com/gfx-rs/naga/pull/1789)) **@teoxoy**
- Fix matrix not being declared as transposed ([#1784](https://github.com/gfx-rs/naga/pull/1784)) **@teoxoy**
- Insert padding between struct members ([#1786](https://github.com/gfx-rs/naga/pull/1786)) **@teoxoy**
- Fix not unary operator for integer scalars ([#1760](https://github.com/gfx-rs/naga/pull/1760)) **@vincentisambart**
GLSL-OUT
- Fix vector bitcasts (#1966) ([#1966](https://github.com/gfx-rs/naga/pull/1966)) **@expenses**
- Perform casts in int only math functions ([#1978](https://github.com/gfx-rs/naga/pull/1978)) **@JCapucho**
- Don't rely on cached expressions ([#1975](https://github.com/gfx-rs/naga/pull/1975)) **@JCapucho**
- Fix type error for `countOneBits` implementation ([#1897](https://github.com/gfx-rs/naga/pull/1897)) **@hasali19**
- Fix storage format for `Rgba8Unorm` ([#1955](https://github.com/gfx-rs/naga/pull/1955)) **@JCapucho**
- Implement bounds checks for `ImageLoad` ([#1889](https://github.com/gfx-rs/naga/pull/1889)) **@JCapucho**
- Fix feature search in expressions ([#1887](https://github.com/gfx-rs/naga/pull/1887)) **@JCapucho**
- Emit globals of any type ([#1823](https://github.com/gfx-rs/naga/pull/1823)) **@jimblandy**
- Add support for boolean vector `~`, `|` and `&` ops ([#1820](https://github.com/gfx-rs/naga/pull/1820)) **@teoxoy**
- Fix array function arguments ([#1814](https://github.com/gfx-rs/naga/pull/1814)) **@teoxoy**
- Write constant sized array type for uniform ([#1768](https://github.com/gfx-rs/naga/pull/1768)) **@hatoo**
- Texture function fixes ([#1742](https://github.com/gfx-rs/naga/pull/1742)) **@JCapucho**
- Push constants use anonymous uniforms ([#1683](https://github.com/gfx-rs/naga/pull/1683)) **@JCapucho**
- Add support for push constant emulation ([#1672](https://github.com/gfx-rs/naga/pull/1672)) **@JCapucho**
- Skip unsized types if unused ([#1649](https://github.com/gfx-rs/naga/pull/1649)) **@kvark**
- Write struct and array initializers ([#1644](https://github.com/gfx-rs/naga/pull/1644)) **@JCapucho**
## v0.8.5 (2022-01-25)
MSL-OUT
- Make VS-output positions invariant on even more systems ([#1697](https://github.com/gfx-rs/naga/pull/1697)) **@cwfitzgerald**
- Improve support for point primitives ([#1696](https://github.com/gfx-rs/naga/pull/1696)) **@kvark**
## v0.8.4 (2022-01-24)
MSL-OUT
- Make VS-output positions invariant if possible ([#1687](https://github.com/gfx-rs/naga/pull/1687)) **@kvark**
GLSL-OUT
- Fix `floatBitsToUint` spelling ([#1688](https://github.com/gfx-rs/naga/pull/1688)) **@cwfitzgerald**
- Call proper memory barrier functions ([#1680](https://github.com/gfx-rs/naga/pull/1680)) **@francesco-cattoglio**
## v0.8.3 (2022-01-20)
- Don't pin `indexmap` version ([#1666](https://github.com/gfx-rs/naga/pull/1666)) **@a1phyr**
MSL-OUT
- Fix support for point primitives ([#1674](https://github.com/gfx-rs/naga/pull/1674)) **@kvark**
GLSL-OUT
- Fix sampler association ([#1671](https://github.com/gfx-rs/naga/pull/1671)) **@JCapucho**
## v0.8.2 (2022-01-11)
VALIDATOR
- Check structure resource types ([#1639](https://github.com/gfx-rs/naga/pull/1639)) **@kvark**
WGSL-IN
- Improve type mismatch errors ([#1658](https://github.com/gfx-rs/naga/pull/1658)) **@Gordon-F**
SPV-IN
- Implement more sign agnostic operations ([#1651](https://github.com/gfx-rs/naga/pull/1651), [#1650](https://github.com/gfx-rs/naga/pull/1650)) **@JCapucho**
SPV-OUT
- Fix modulo operator (use `OpFRem` instead of `OpFMod`) ([#1653](https://github.com/gfx-rs/naga/pull/1653)) **@JCapucho**
MSL-OUT
- Fix `texture1d` accesses ([#1647](https://github.com/gfx-rs/naga/pull/1647)) **@jimblandy**
- Fix data packing functions ([#1637](https://github.com/gfx-rs/naga/pull/1637)) **@phoekz**
## v0.8.1 (2021-12-29)
API
- Make `WithSpan` cloneable ([#1620](https://github.com/gfx-rs/naga/pull/1620)) **@jakobhellermann**
MSL-OUT
- Fix packed vec access ([#1634](https://github.com/gfx-rs/naga/pull/1634)) **@kvark**
- Fix packed float support ([#1630](https://github.com/gfx-rs/naga/pull/1630)) **@kvark**
HLSL-OUT
- Support arrays of matrices ([#1629](https://github.com/gfx-rs/naga/pull/1629)) **@kvark**
- Use `mad` instead of `fma` function ([#1580](https://github.com/gfx-rs/naga/pull/1580)) **@parasyte**
GLSL-OUT
- Fix conflicting names for globals ([#1616](https://github.com/gfx-rs/naga/pull/1616)) **@Gordon-F**
- Fix `fma` function ([#1580](https://github.com/gfx-rs/naga/pull/1580)) **@parasyte**
## v0.8 (2021-12-18)
- development release for wgpu-0.12
- lots of fixes in all parts
- validator:
- now gated by `validate` feature
- nicely detailed error messages with spans
- API:
- image gather operations
- WGSL-in:
- remove `[[block]]` attribute
- `elseif` is removed in favor of `else if`
- MSL-out:
- full out-of-bounds checking
## v0.7.3 (2021-12-14)
- API:
- `view_index` builtin
- GLSL-out:
- reflect textures without samplers
- SPV-out:
- fix incorrect pack/unpack
## v0.7.2 (2021-12-01)
- validator:
- check stores for proper pointer class
- HLSL-out:
- fix stores into `mat3`
- respect array strides
- SPV-out:
- fix multi-word constants
- WGSL-in:
- permit names starting with underscores
- SPV-in:
- cull unused builtins
- support empty debug labels
- GLSL-in:
- don't panic on invalid integer operations
## v0.7.1 (2021-10-12)
- implement casts from and to booleans in the backends
## v0.7 (2021-10-07)
- development release for wgpu-0.11
- API:
- bit extraction and packing functions
- hyperbolic trigonometry functions
- validation is gated by a cargo feature
- `view_index` builtin
- separate bounds checking policies for locals/buffers/textures
- IR:
- types and constants are guaranteed to be unique
- WGSL-in:
- new hex literal parser
- updated list of reserved words
- rewritten logic for resolving references and pointers
- `switch` can use unsigned selectors
- GLSL-in:
- better support for texture sampling
- better logic for auto-splatting scalars
- GLSL-out:
- fixed storage buffer layout
- fix module operator
- HLSL-out:
- fixed texture queries
- SPV-in:
- control flow handling is rewritten from scratch
- SPV-out:
- fully covered out-of-bounds checking
- option to emit point size
- option to clamp output depth
## v0.6.3 (2021-09-08)
- Reduced heap allocations when generating WGSL, HLSL, and GLSL
- WGSL-in:
- support module-scope `let` type inference
- SPV-in:
- fix depth sampling with projection
- HLSL-out:
- fix local struct construction
- GLSL-out:
- fix `select()` order
- SPV-out:
- allow working around Adreno issue with `OpName`
## v0.6.2 (2021-09-01)
- SPV-out fixes:
- requested capabilities for 1D and cube images, storage formats
- handling `break` and `continue` in a `switch` statement
- avoid generating duplicate `OpTypeImage` types
- HLSL-out fixes:
- fix output struct member names
- MSL-out fixes:
- fix packing of fields in interface structs
- GLSL-out fixes:
- fix non-fallthrough `switch` cases
- GLSL-in fixes:
- avoid infinite loop on invalid statements
## v0.6.1 (2021-08-24)
- HLSL-out fixes:
- array arguments
- pointers to array arguments
- switch statement
- rewritten interface matching
- SPV-in fixes:
- array storage texture stores
- tracking sampling across function parameters
- updated petgraph dependencies
- MSL-out:
- gradient sampling
- GLSL-out:
- modulo operator on floats
## v0.6 (2021-08-18)
- development release for wgpu-0.10
- API:
- atomic types and functions
- storage access is moved from global variables to the storage class and storage texture type
- new built-ins: `primitive_index` and `num_workgroups`
- support for multi-sampled depth images
- WGSL:
- `select()` order of true/false is swapped
- HLSL backend is vastly improved and now usable
- GLSL frontend is heavily reworked
## v0.5 (2021-06-18)
- development release for wgpu-0.9
- API:
- barriers
- dynamic indexing of matrices and arrays is only allowed on variables
- validator now accepts a list of IR capabilities to allow
- improved documentation
- Infrastructure:
- much richer test suite, focused around consuming or emitting WGSL
- lazy testing on large shader corpuses
- the binary is moved to a sub-crate "naga-cli"
- Frontends:
- GLSL frontend:
- rewritten from scratch and effectively revived, no longer depends on `pomelo`
- only supports 440/450/460 versions for now
- has optional support for codespan messages
- SPIRV frontend has improved CFG resolution (still with issues unresolved)
- WGSL got better error messages, workgroup memory support
- Backends:
- general: better expression naming and emitting
- new HLSL backend (in progress)
- MSL:
- support `ArraySize` expression
- better texture sampling instructions
- GLSL:
- multisampling on GLES
- WGSL is vastly improved and now usable
## v0.4.2 (2021-05-28)
- SPIR-V frontend:
- fix image stores
- fix matrix stride check
- SPIR-V backend:
- fix auto-deriving the capabilities
- GLSL backend:
- support sample interpolation
- write out swizzled vector accesses
## v0.4.1 (2021-05-14)
- numerous additions and improvements to SPIR-V frontend:
- int8, in16, int64
- null constant initializers for structs and matrices
- `OpArrayLength`, `OpCopyMemory`, `OpInBoundsAccessChain`, `OpLogicalXxxEqual`
- outer product
- fix struct size alignment
- initialize built-ins with default values
- fix read-only decorations on struct members
- fix struct size alignment in WGSL
- fix `fwidth` in WGSL
- fix scalars arrays in GLSL backend
## v0.4 (2021-04-29)
- development release for wgpu-0.8
- API:
- expressions are explicitly emitted with `Statement::Emit`
- entry points have inputs in arguments and outputs in the result type
- `input`/`output` storage classes are gone, but `push_constant` is added
- `Interpolation` is moved into `Binding::Location` variant
- real pointer semantics with required `Expression::Load`
- `TypeInner::ValuePointer` is added
- image query expressions are added
- new `Statement::ImageStore`
- all function calls are `Statement::Call`
- `GlobalUse` is moved out into processing
- `Header` is removed
- entry points are an array instead of a map
- new `Swizzle` and `Splat` expressions
- interpolation qualifiers are extended and required
- struct member layout is based on the byte offsets
- Infrastructure:
- control flow uniformity analysis
- texture-sampler combination gathering
- `CallGraph` processor is moved out into `glsl` backend
- `Interface` is removed, instead the analysis produces `ModuleInfo` with all the derived info
- validation of statement tree, expressions, and constants
- code linting is more strict for matches
- new GraphViz `dot` backend for pretty visualization of the IR
- Metal support for inlined samplers
- `convert` example is transformed into the default binary target named `naga`
- lots of frontend and backend fixes
## v0.3.2 (2021-02-15)
- fix logical expression types
- fix _FragDepth_ semantics
- spv-in:
- derive block status of structures
- spv-out:
- add lots of missing math functions
- implement discard
## v0.3.1 (2021-01-31)
- wgsl:
- support constant array sizes
- spv-out:
- fix block decorations on nested structures
- fix fixed-size arrays
- fix matrix decorations inside structures
- implement read-only decorations
## v0.3 (2021-01-30)
- development release for wgpu-0.7
- API:
- math functions
- type casts
- updated storage classes
- updated image sub-types
- image sampling/loading options
- storage images
- interpolation qualifiers
- early and conservative depth
- Processors:
- name manager
- automatic layout
- termination analysis
- validation of types, constants, variables, and entry points
## v0.2 (2020-08-17)
- development release for wgpu-0.6
## v0.1 (2020-02-26)
- initial release
+178
View File
@@ -0,0 +1,178 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.76"
name = "naga"
version = "24.0.0"
authors = ["gfx-rs developers"]
build = "build.rs"
exclude = [
"bin/**/*",
"tests/**/*",
"Cargo.lock",
"target/**/*",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Shader translator and validator. Part of the wgpu project"
readme = "README.md"
keywords = [
"shader",
"SPIR-V",
"GLSL",
"MSL",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/gfx-rs/wgpu/tree/trunk/naga"
resolver = "2"
[package.metadata.docs.rs]
all-features = true
[lib]
name = "naga"
path = "src/lib.rs"
[dependencies.arbitrary]
version = "1.4"
features = ["derive"]
optional = true
[dependencies.arrayvec]
version = "0.7"
[dependencies.bit-set]
version = "0.8"
[dependencies.bitflags]
version = "2.7"
[dependencies.codespan-reporting]
version = "0.11.0"
[dependencies.hexf-parse]
version = "0.2.1"
optional = true
[dependencies.indexmap]
version = "2"
[dependencies.log]
version = "0.4"
[dependencies.petgraph]
version = "0.7"
optional = true
[dependencies.pp-rs]
version = "0.2.1"
optional = true
[dependencies.rustc-hash]
version = "1"
[dependencies.serde]
version = "1.0.217"
features = [
"default",
"derive",
]
optional = true
[dependencies.spirv]
version = "0.3"
optional = true
[dependencies.strum]
version = "0.26.0"
features = ["derive"]
[dependencies.termcolor]
version = "1.4.1"
[dependencies.thiserror]
version = "2"
[dependencies.unicode-xid]
version = "0.2.6"
optional = true
[dev-dependencies.diff]
version = "0.1"
[dev-dependencies.env_logger]
version = "0.11"
[dev-dependencies.itertools]
version = "0.13.0"
[dev-dependencies.ron]
version = "0.8.0"
[dev-dependencies.rspirv]
version = "0.11"
[dev-dependencies.serde]
version = "1"
features = [
"default",
"derive",
]
default-features = false
[dev-dependencies.spirv]
version = "0.3"
features = ["deserialize"]
[build-dependencies.cfg_aliases]
version = "0.2.1"
[features]
arbitrary = [
"dep:arbitrary",
"bitflags/arbitrary",
"indexmap/arbitrary",
]
compact = []
default = []
deserialize = [
"dep:serde",
"bitflags/serde",
"indexmap/serde",
]
dot-out = []
glsl-in = ["dep:pp-rs"]
glsl-out = []
hlsl-out = []
hlsl-out-if-target-windows = []
msl-out = []
msl-out-if-target-apple = []
serialize = [
"dep:serde",
"bitflags/serde",
"indexmap/serde",
]
spv-in = [
"dep:petgraph",
"dep:spirv",
]
spv-out = ["dep:spirv"]
wgsl-in = [
"dep:hexf-parse",
"dep:unicode-xid",
"compact",
]
wgsl-out = []
+86
View File
@@ -0,0 +1,86 @@
# Naga
[![Matrix](https://img.shields.io/badge/Matrix-%23naga%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#naga:matrix.org)
[![Crates.io](https://img.shields.io/crates/v/naga.svg?label=naga)](https://crates.io/crates/naga)
[![Docs.rs](https://docs.rs/naga/badge.svg)](https://docs.rs/naga)
[![Build Status](https://github.com/gfx-rs/naga/workflows/pipeline/badge.svg)](https://github.com/gfx-rs/naga/actions)
![MSRV](https://img.shields.io/badge/rustc-1.76+-blue.svg)
[![codecov.io](https://codecov.io/gh/gfx-rs/naga/branch/master/graph/badge.svg?token=9VOKYO8BM2)](https://codecov.io/gh/gfx-rs/naga)
The shader translation library for the needs of [wgpu](https://github.com/gfx-rs/wgpu).
## Supported end-points
Front-end | Status | Feature | Notes |
--------------- | ------------------ | ------- | ----- |
SPIR-V (binary) | :white_check_mark: | spv-in | |
WGSL | :white_check_mark: | wgsl-in | Fully validated |
GLSL | :ok: | glsl-in | GLSL 440+ and Vulkan semantics only |
Back-end | Status | Feature | Notes |
--------------- | ------------------ | -------- | ----- |
SPIR-V | :white_check_mark: | spv-out | |
WGSL | :ok: | wgsl-out | |
Metal | :white_check_mark: | msl-out | |
HLSL | :white_check_mark: | hlsl-out | Shader Model 5.0+ (DirectX 11+) |
GLSL | :ok: | glsl-out | GLSL 330+ and GLSL ES 300+ |
AIR | | | |
DXIL/DXIR | | | |
DXBC | | | |
DOT (GraphViz) | :ok: | dot-out | Not a shading language |
:white_check_mark: = Primary support — :ok: = Secondary support — :construction: = Unsupported, but support in progress
## Conversion tool
Naga can be used as a CLI, which allows testing the conversion of different code paths.
First, install `naga-cli` from crates.io or directly from GitHub.
```bash
# release version
cargo install naga-cli
# development version
cargo install naga-cli --git https://github.com/gfx-rs/wgpu.git
```
Then, you can run `naga` command.
```bash
naga my_shader.wgsl # validate only
naga my_shader.spv my_shader.txt # dump the IR module into a file
naga my_shader.spv my_shader.metal --flow-dir flow-dir # convert the SPV to Metal, also dump the SPIR-V flow graph to `flow-dir`
naga my_shader.wgsl my_shader.vert --profile es310 # convert the WGSL to GLSL vertex stage under ES 3.20 profile
```
As naga includes a default binary target, you can also use `cargo run` without installation. This is useful when you develop naga itself or investigate the behavior of naga at a specific commit (e.g. [wgpu](https://github.com/gfx-rs/wgpu) might pin a different version of naga than the `HEAD` of this repository).
```bash
cargo run my_shader.wgsl
```
## Development workflow
The main instrument aiding the development is the good old `cargo test --all-features --workspace`,
which will run the unit tests and also update all the snapshots. You'll see these
changes in git before committing the code.
If working on a particular front-end or back-end, it may be convenient to
enable the relevant features in `Cargo.toml`, e.g.
```toml
default = ["spv-out"] #TEMP!
```
This allows IDE basic checks to report errors there unless your IDE is sufficiently configurable already.
Finally, when changes to the snapshots are made, we should verify that the produced shaders
are indeed valid for the target platforms they are compiled for:
```bash
cargo xtask validate spv # for Vulkan shaders, requires SPIRV-Tools installed
cargo xtask validate msl # for Metal shaders, requires XCode command-line tools installed
cargo xtask validate glsl # for OpenGL shaders, requires GLSLang installed
cargo xtask validate dot # for dot files, requires GraphViz installed
cargo xtask validate wgsl # for WGSL shaders
cargo xtask validate hlsl dxc # for HLSL shaders via DXC
cargo xtask validate hlsl fxc # for HLSL shaders via FXC
```
+10
View File
@@ -0,0 +1,10 @@
fn main() {
cfg_aliases::cfg_aliases! {
dot_out: { feature = "dot-out" },
glsl_out: { feature = "glsl-out" },
hlsl_out: { any(feature = "hlsl-out", all(target_os = "windows", feature = "hlsl-out-if-target-windows")) },
msl_out: { any(feature = "msl-out", all(target_vendor = "apple", feature = "msl-out-if-target-apple")) },
spv_out: { feature = "spv-out" },
wgsl_out: { feature = "wgsl-out" },
}
}
+126
View File
@@ -0,0 +1,126 @@
//! Well-typed indices into [`Arena`]s and [`UniqueArena`]s.
//!
//! This module defines [`Handle`] and related types.
//!
//! [`Arena`]: super::Arena
//! [`UniqueArena`]: super::UniqueArena
use std::{cmp::Ordering, fmt, hash, marker::PhantomData};
/// An unique index in the arena array that a handle points to.
/// The "non-max" part ensures that an `Option<Handle<T>>` has
/// the same size and representation as `Handle<T>`.
pub type Index = crate::non_max_u32::NonMaxU32;
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)]
#[error("Handle {index} of {kind} is either not present, or inaccessible yet")]
pub struct BadHandle {
pub kind: &'static str,
pub index: usize,
}
impl BadHandle {
pub fn new<T>(handle: Handle<T>) -> Self {
Self {
kind: std::any::type_name::<T>(),
index: handle.index(),
}
}
}
/// A strongly typed reference to an arena item.
///
/// A `Handle` value can be used as an index into an [`Arena`] or [`UniqueArena`].
///
/// [`Arena`]: super::Arena
/// [`UniqueArena`]: super::UniqueArena
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(
any(feature = "serialize", feature = "deserialize"),
serde(transparent)
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Handle<T> {
index: Index,
#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))]
marker: PhantomData<T>,
}
impl<T> Clone for Handle<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Handle<T> {}
impl<T> PartialEq for Handle<T> {
fn eq(&self, other: &Self) -> bool {
self.index == other.index
}
}
impl<T> Eq for Handle<T> {}
impl<T> PartialOrd for Handle<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for Handle<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.index.cmp(&other.index)
}
}
impl<T> fmt::Debug for Handle<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "[{}]", self.index)
}
}
impl<T> hash::Hash for Handle<T> {
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
self.index.hash(hasher)
}
}
impl<T> Handle<T> {
pub(crate) const fn new(index: Index) -> Self {
Handle {
index,
marker: PhantomData,
}
}
/// Returns the index of this handle.
pub const fn index(self) -> usize {
self.index.get() as usize
}
/// Convert a `usize` index into a `Handle<T>`.
pub(super) fn from_usize(index: usize) -> Self {
let handle_index = u32::try_from(index)
.ok()
.and_then(Index::new)
.expect("Failed to insert into arena. Handle overflows");
Handle::new(handle_index)
}
/// Convert a `usize` index into a `Handle<T>`, without range checks.
pub(super) const unsafe fn from_usize_unchecked(index: usize) -> Self {
Handle::new(Index::new_unchecked(index as u32))
}
/// Write this handle's index to `formatter`, preceded by `prefix`.
pub fn write_prefixed(
&self,
formatter: &mut fmt::Formatter,
prefix: &'static str,
) -> fmt::Result {
formatter.write_str(prefix)?;
<usize as fmt::Display>::fmt(&self.index(), formatter)
}
}
+110
View File
@@ -0,0 +1,110 @@
//! The [`HandleSet`] type and associated definitions.
use crate::arena::{Arena, Handle, UniqueArena};
/// A set of `Handle<T>` values.
#[derive(Debug)]
pub struct HandleSet<T> {
/// Bound on indexes of handles stored in this set.
len: usize,
/// `members[i]` is true if the handle with index `i` is a member.
members: bit_set::BitSet,
/// This type is indexed by values of type `T`.
as_keys: std::marker::PhantomData<T>,
}
impl<T> HandleSet<T> {
/// Return a new, empty `HandleSet`.
pub fn new() -> Self {
Self {
len: 0,
members: bit_set::BitSet::new(),
as_keys: std::marker::PhantomData,
}
}
pub fn is_empty(&self) -> bool {
self.members.is_empty()
}
/// Return a new, empty `HandleSet`, sized to hold handles from `arena`.
pub fn for_arena(arena: &impl ArenaType<T>) -> Self {
let len = arena.len();
Self {
len,
members: bit_set::BitSet::with_capacity(len),
as_keys: std::marker::PhantomData,
}
}
/// Remove all members from `self`.
pub fn clear(&mut self) {
self.members.clear();
}
/// Remove all members from `self`, and reserve space to hold handles from `arena`.
pub fn clear_for_arena(&mut self, arena: &impl ArenaType<T>) {
self.members.clear();
self.members.reserve_len(arena.len());
}
/// Return an iterator over all handles that could be made members
/// of this set.
pub fn all_possible(&self) -> impl Iterator<Item = Handle<T>> {
super::Range::full_range_from_size(self.len)
}
/// Add `handle` to the set.
///
/// Return `true` if `handle` was not already present in the set.
pub fn insert(&mut self, handle: Handle<T>) -> bool {
self.members.insert(handle.index())
}
/// Remove `handle` from the set.
///
/// Returns `true` if `handle` was present in the set.
pub fn remove(&mut self, handle: Handle<T>) -> bool {
self.members.remove(handle.index())
}
/// Add handles from `iter` to the set.
pub fn insert_iter(&mut self, iter: impl IntoIterator<Item = Handle<T>>) {
for handle in iter {
self.insert(handle);
}
}
pub fn contains(&self, handle: Handle<T>) -> bool {
self.members.contains(handle.index())
}
/// Return an iterator over all handles in `self`.
pub fn iter(&self) -> impl '_ + Iterator<Item = Handle<T>> {
self.members.iter().map(Handle::from_usize)
}
}
impl<T> Default for HandleSet<T> {
fn default() -> Self {
Self::new()
}
}
pub trait ArenaType<T> {
fn len(&self) -> usize;
}
impl<T> ArenaType<T> for Arena<T> {
fn len(&self) -> usize {
self.len()
}
}
impl<T: std::hash::Hash + Eq> ArenaType<T> for UniqueArena<T> {
fn len(&self) -> usize {
self.len()
}
}
+105
View File
@@ -0,0 +1,105 @@
//! The [`HandleVec`] type and associated definitions.
use super::handle::Handle;
use std::marker::PhantomData;
use std::ops;
/// A [`Vec`] indexed by [`Handle`]s.
///
/// A `HandleVec<T, U>` is a [`Vec<U>`] indexed by values of type `Handle<T>`,
/// rather than `usize`.
///
/// Rather than a `push` method, `HandleVec` has an [`insert`] method, analogous
/// to [`HashMap::insert`], that requires you to provide the handle at which the
/// new value should appear. However, since `HandleVec` only supports insertion
/// at the end, the given handle's index must be equal to the the `HandleVec`'s
/// current length; otherwise, the insertion will panic.
///
/// [`insert`]: HandleVec::insert
/// [`HashMap::insert`]: std::collections::HashMap::insert
#[derive(Debug)]
pub(crate) struct HandleVec<T, U> {
inner: Vec<U>,
as_keys: PhantomData<T>,
}
impl<T, U> Default for HandleVec<T, U> {
fn default() -> Self {
Self {
inner: vec![],
as_keys: PhantomData,
}
}
}
#[allow(dead_code)]
impl<T, U> HandleVec<T, U> {
pub(crate) const fn new() -> Self {
Self {
inner: vec![],
as_keys: PhantomData,
}
}
pub(crate) fn with_capacity(capacity: usize) -> Self {
Self {
inner: Vec::with_capacity(capacity),
as_keys: PhantomData,
}
}
pub(crate) fn len(&self) -> usize {
self.inner.len()
}
/// Insert a mapping from `handle` to `value`.
///
/// Unlike a [`HashMap`], a `HandleVec` can only have new entries inserted at
/// the end, like [`Vec::push`]. So the index of `handle` must equal
/// [`self.len()`].
///
/// [`HashMap`]: std::collections::HashMap
/// [`self.len()`]: HandleVec::len
pub(crate) fn insert(&mut self, handle: Handle<T>, value: U) {
assert_eq!(handle.index(), self.inner.len());
self.inner.push(value);
}
pub(crate) fn get(&self, handle: Handle<T>) -> Option<&U> {
self.inner.get(handle.index())
}
pub(crate) fn clear(&mut self) {
self.inner.clear()
}
pub(crate) fn resize(&mut self, len: usize, fill: U)
where
U: Clone,
{
self.inner.resize(len, fill);
}
pub(crate) fn iter(&self) -> impl Iterator<Item = &U> {
self.inner.iter()
}
pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = &mut U> {
self.inner.iter_mut()
}
}
impl<T, U> ops::Index<Handle<T>> for HandleVec<T, U> {
type Output = U;
fn index(&self, handle: Handle<T>) -> &Self::Output {
&self.inner[handle.index()]
}
}
impl<T, U> ops::IndexMut<Handle<T>> for HandleVec<T, U> {
fn index_mut(&mut self, handle: Handle<T>) -> &mut Self::Output {
&mut self.inner[handle.index()]
}
}
+329
View File
@@ -0,0 +1,329 @@
/*! The [`Arena`], [`UniqueArena`], and [`Handle`] types.
To improve translator performance and reduce memory usage, most structures are
stored in an [`Arena`]. An `Arena<T>` stores a series of `T` values, indexed by
[`Handle<T>`](Handle) values, which are just wrappers around integer indexes.
For example, a `Function`'s expressions are stored in an `Arena<Expression>`,
and compound expressions refer to their sub-expressions via `Handle<Expression>`
values. (When examining the serialized form of a `Module`, note that the first
element of an `Arena` has an index of 1, not 0.)
A [`UniqueArena`] is just like an `Arena`, except that it stores only a single
instance of each value. The value type must implement `Eq` and `Hash`. Like an
`Arena`, inserting a value into a `UniqueArena` returns a `Handle` which can be
used to efficiently access the value, without a hash lookup. Inserting a value
multiple times returns the same `Handle`.
If the `span` feature is enabled, both `Arena` and `UniqueArena` can associate a
source code span with each element.
[`Handle<T>`]: Handle
*/
mod handle;
mod handle_set;
mod handlevec;
mod range;
mod unique_arena;
pub use handle::{BadHandle, Handle};
pub(crate) use handle_set::HandleSet;
pub(crate) use handlevec::HandleVec;
pub use range::{BadRangeError, Range};
pub use unique_arena::UniqueArena;
use crate::Span;
use handle::Index;
use std::{fmt, ops};
/// An arena holding some kind of component (e.g., type, constant,
/// instruction, etc.) that can be referenced.
///
/// Adding new items to the arena produces a strongly-typed [`Handle`].
/// The arena can be indexed using the given handle to obtain
/// a reference to the stored item.
#[derive(Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "serialize", serde(transparent))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(test, derive(PartialEq))]
pub struct Arena<T> {
/// Values of this arena.
data: Vec<T>,
#[cfg_attr(feature = "serialize", serde(skip))]
span_info: Vec<Span>,
}
impl<T> Default for Arena<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: fmt::Debug> fmt::Debug for Arena<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<T> Arena<T> {
/// Create a new arena with no initial capacity allocated.
pub const fn new() -> Self {
Arena {
data: Vec::new(),
span_info: Vec::new(),
}
}
/// Extracts the inner vector.
#[allow(clippy::missing_const_for_fn)] // ignore due to requirement of #![feature(const_precise_live_drops)]
pub fn into_inner(self) -> Vec<T> {
self.data
}
/// Returns the current number of items stored in this arena.
pub fn len(&self) -> usize {
self.data.len()
}
/// Returns `true` if the arena contains no elements.
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Returns an iterator over the items stored in this arena, returning both
/// the item's handle and a reference to it.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Handle<T>, &T)> {
self.data
.iter()
.enumerate()
.map(|(i, v)| unsafe { (Handle::from_usize_unchecked(i), v) })
}
/// Drains the arena, returning an iterator over the items stored.
pub fn drain(&mut self) -> impl DoubleEndedIterator<Item = (Handle<T>, T, Span)> {
let arena = std::mem::take(self);
arena
.data
.into_iter()
.zip(arena.span_info)
.enumerate()
.map(|(i, (v, span))| unsafe { (Handle::from_usize_unchecked(i), v, span) })
}
/// Returns a iterator over the items stored in this arena,
/// returning both the item's handle and a mutable reference to it.
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = (Handle<T>, &mut T)> {
self.data
.iter_mut()
.enumerate()
.map(|(i, v)| unsafe { (Handle::from_usize_unchecked(i), v) })
}
/// Adds a new value to the arena, returning a typed handle.
pub fn append(&mut self, value: T, span: Span) -> Handle<T> {
let index = self.data.len();
self.data.push(value);
self.span_info.push(span);
Handle::from_usize(index)
}
/// Fetch a handle to an existing type.
pub fn fetch_if<F: Fn(&T) -> bool>(&self, fun: F) -> Option<Handle<T>> {
self.data
.iter()
.position(fun)
.map(|index| unsafe { Handle::from_usize_unchecked(index) })
}
/// Adds a value with a custom check for uniqueness:
/// returns a handle pointing to
/// an existing element if the check succeeds, or adds a new
/// element otherwise.
pub fn fetch_if_or_append<F: Fn(&T, &T) -> bool>(
&mut self,
value: T,
span: Span,
fun: F,
) -> Handle<T> {
if let Some(index) = self.data.iter().position(|d| fun(d, &value)) {
unsafe { Handle::from_usize_unchecked(index) }
} else {
self.append(value, span)
}
}
/// Adds a value with a check for uniqueness, where the check is plain comparison.
pub fn fetch_or_append(&mut self, value: T, span: Span) -> Handle<T>
where
T: PartialEq,
{
self.fetch_if_or_append(value, span, T::eq)
}
pub fn try_get(&self, handle: Handle<T>) -> Result<&T, BadHandle> {
self.data
.get(handle.index())
.ok_or_else(|| BadHandle::new(handle))
}
/// Get a mutable reference to an element in the arena.
pub fn get_mut(&mut self, handle: Handle<T>) -> &mut T {
self.data.get_mut(handle.index()).unwrap()
}
/// Get the range of handles from a particular number of elements to the end.
pub fn range_from(&self, old_length: usize) -> Range<T> {
let range = old_length as u32..self.data.len() as u32;
Range::from_index_range(range, self)
}
/// Clears the arena keeping all allocations
pub fn clear(&mut self) {
self.data.clear()
}
pub fn get_span(&self, handle: Handle<T>) -> Span {
*self
.span_info
.get(handle.index())
.unwrap_or(&Span::default())
}
/// Assert that `handle` is valid for this arena.
pub fn check_contains_handle(&self, handle: Handle<T>) -> Result<(), BadHandle> {
if handle.index() < self.data.len() {
Ok(())
} else {
Err(BadHandle::new(handle))
}
}
/// Assert that `range` is valid for this arena.
pub fn check_contains_range(&self, range: &Range<T>) -> Result<(), BadRangeError> {
// Since `range.inner` is a `Range<u32>`, we only need to check that the
// start precedes the end, and that the end is in range.
if range.inner.start > range.inner.end {
return Err(BadRangeError::new(range.clone()));
}
// Empty ranges are tolerated: they can be produced by compaction.
if range.inner.start == range.inner.end {
return Ok(());
}
let last_handle = Handle::new(Index::new(range.inner.end - 1).unwrap());
if self.check_contains_handle(last_handle).is_err() {
return Err(BadRangeError::new(range.clone()));
}
Ok(())
}
#[cfg(feature = "compact")]
pub(crate) fn retain_mut<P>(&mut self, mut predicate: P)
where
P: FnMut(Handle<T>, &mut T) -> bool,
{
let mut index = 0;
let mut retained = 0;
self.data.retain_mut(|elt| {
let handle = Handle::from_usize(index);
let keep = predicate(handle, elt);
// Since `predicate` needs mutable access to each element,
// we can't feasibly call it twice, so we have to compact
// spans by hand in parallel as part of this iteration.
if keep {
self.span_info[retained] = self.span_info[index];
retained += 1;
}
index += 1;
keep
});
self.span_info.truncate(retained);
}
}
#[cfg(feature = "deserialize")]
impl<'de, T> serde::Deserialize<'de> for Arena<T>
where
T: serde::Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let data = Vec::deserialize(deserializer)?;
let span_info = std::iter::repeat(Span::default())
.take(data.len())
.collect();
Ok(Self { data, span_info })
}
}
impl<T> ops::Index<Handle<T>> for Arena<T> {
type Output = T;
fn index(&self, handle: Handle<T>) -> &T {
&self.data[handle.index()]
}
}
impl<T> ops::IndexMut<Handle<T>> for Arena<T> {
fn index_mut(&mut self, handle: Handle<T>) -> &mut T {
&mut self.data[handle.index()]
}
}
impl<T> ops::Index<Range<T>> for Arena<T> {
type Output = [T];
fn index(&self, range: Range<T>) -> &[T] {
&self.data[range.inner.start as usize..range.inner.end as usize]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn append_non_unique() {
let mut arena: Arena<u8> = Arena::new();
let t1 = arena.append(0, Default::default());
let t2 = arena.append(0, Default::default());
assert!(t1 != t2);
assert!(arena[t1] == arena[t2]);
}
#[test]
fn append_unique() {
let mut arena: Arena<u8> = Arena::new();
let t1 = arena.append(0, Default::default());
let t2 = arena.append(1, Default::default());
assert!(t1 != t2);
assert!(arena[t1] != arena[t2]);
}
#[test]
fn fetch_or_append_non_unique() {
let mut arena: Arena<u8> = Arena::new();
let t1 = arena.fetch_or_append(0, Default::default());
let t2 = arena.fetch_or_append(0, Default::default());
assert!(t1 == t2);
assert!(arena[t1] == arena[t2])
}
#[test]
fn fetch_or_append_unique() {
let mut arena: Arena<u8> = Arena::new();
let t1 = arena.fetch_or_append(0, Default::default());
let t2 = arena.fetch_or_append(1, Default::default());
assert!(t1 != t2);
assert!(arena[t1] != arena[t2]);
}
}
+139
View File
@@ -0,0 +1,139 @@
//! Well-typed ranges of [`Arena`]s.
//!
//! This module defines the [`Range`] type, representing a contiguous range of
//! entries in an [`Arena`].
//!
//! [`Arena`]: super::Arena
use super::{
handle::{Handle, Index},
Arena,
};
use std::{fmt, marker::PhantomData, ops};
/// A strongly typed range of handles.
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(
any(feature = "serialize", feature = "deserialize"),
serde(transparent)
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(test, derive(PartialEq))]
pub struct Range<T> {
pub(super) inner: ops::Range<u32>,
#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))]
marker: PhantomData<T>,
}
impl<T> Range<T> {
pub(crate) const fn erase_type(self) -> Range<()> {
let Self { inner, marker: _ } = self;
Range {
inner,
marker: PhantomData,
}
}
}
// NOTE: Keep this diagnostic in sync with that of [`BadHandle`].
#[derive(Clone, Debug, thiserror::Error)]
#[cfg_attr(test, derive(PartialEq))]
#[error("Handle range {range:?} of {kind} is either not present, or inaccessible yet")]
pub struct BadRangeError {
// This error is used for many `Handle` types, but there's no point in making this generic, so
// we just flatten them all to `Handle<()>` here.
kind: &'static str,
range: Range<()>,
}
impl BadRangeError {
pub fn new<T>(range: Range<T>) -> Self {
Self {
kind: std::any::type_name::<T>(),
range: range.erase_type(),
}
}
}
impl<T> Clone for Range<T> {
fn clone(&self) -> Self {
Range {
inner: self.inner.clone(),
marker: self.marker,
}
}
}
impl<T> fmt::Debug for Range<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "[{}..{}]", self.inner.start, self.inner.end)
}
}
impl<T> Iterator for Range<T> {
type Item = Handle<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.inner.start < self.inner.end {
let next = self.inner.start;
self.inner.start += 1;
Some(Handle::new(Index::new(next).unwrap()))
} else {
None
}
}
}
impl<T> Range<T> {
/// Return a range enclosing handles `first` through `last`, inclusive.
pub fn new_from_bounds(first: Handle<T>, last: Handle<T>) -> Self {
Self {
inner: (first.index() as u32)..(last.index() as u32 + 1),
marker: Default::default(),
}
}
/// Return a range covering all handles with indices from `0` to `size`.
pub(super) fn full_range_from_size(size: usize) -> Self {
Self {
inner: 0..size as u32,
marker: Default::default(),
}
}
/// return the first and last handles included in `self`.
///
/// If `self` is an empty range, there are no handles included, so
/// return `None`.
pub fn first_and_last(&self) -> Option<(Handle<T>, Handle<T>)> {
if self.inner.start < self.inner.end {
Some((
// `Range::new_from_bounds` expects a start- and end-inclusive
// range, but `self.inner` is an end-exclusive range.
Handle::new(Index::new(self.inner.start).unwrap()),
Handle::new(Index::new(self.inner.end - 1).unwrap()),
))
} else {
None
}
}
/// Return the index range covered by `self`.
pub fn index_range(&self) -> ops::Range<u32> {
self.inner.clone()
}
/// Construct a `Range` that covers the indices in `inner`.
pub fn from_index_range(inner: ops::Range<u32>, arena: &Arena<T>) -> Self {
// Since `inner` is a `Range<u32>`, we only need to check that
// the start and end are well-ordered, and that the end fits
// within `arena`.
assert!(inner.start <= inner.end);
assert!(inner.end as usize <= arena.len());
Self {
inner,
marker: Default::default(),
}
}
}
+262
View File
@@ -0,0 +1,262 @@
//! The [`UniqueArena`] type and supporting definitions.
use crate::{FastIndexSet, Span};
use super::handle::{BadHandle, Handle, Index};
use std::{fmt, hash, ops};
/// An arena whose elements are guaranteed to be unique.
///
/// A `UniqueArena` holds a set of unique values of type `T`, each with an
/// associated [`Span`]. Inserting a value returns a `Handle<T>`, which can be
/// used to index the `UniqueArena` and obtain shared access to the `T` element.
/// Access via a `Handle` is an array lookup - no hash lookup is necessary.
///
/// The element type must implement `Eq` and `Hash`. Insertions of equivalent
/// elements, according to `Eq`, all return the same `Handle`.
///
/// Once inserted, elements may not be mutated.
///
/// `UniqueArena` is similar to [`Arena`]: If `Arena` is vector-like,
/// `UniqueArena` is `HashSet`-like.
///
/// [`Arena`]: super::Arena
#[derive(Clone)]
pub struct UniqueArena<T> {
set: FastIndexSet<T>,
/// Spans for the elements, indexed by handle.
///
/// The length of this vector is always equal to `set.len()`. `FastIndexSet`
/// promises that its elements "are indexed in a compact range, without
/// holes in the range 0..set.len()", so we can always use the indices
/// returned by insertion as indices into this vector.
span_info: Vec<Span>,
}
impl<T> UniqueArena<T> {
/// Create a new arena with no initial capacity allocated.
pub fn new() -> Self {
UniqueArena {
set: FastIndexSet::default(),
span_info: Vec::new(),
}
}
/// Return the current number of items stored in this arena.
pub fn len(&self) -> usize {
self.set.len()
}
/// Return `true` if the arena contains no elements.
pub fn is_empty(&self) -> bool {
self.set.is_empty()
}
/// Clears the arena, keeping all allocations.
pub fn clear(&mut self) {
self.set.clear();
self.span_info.clear();
}
/// Return the span associated with `handle`.
///
/// If a value has been inserted multiple times, the span returned is the
/// one provided with the first insertion.
pub fn get_span(&self, handle: Handle<T>) -> Span {
*self
.span_info
.get(handle.index())
.unwrap_or(&Span::default())
}
#[cfg(feature = "compact")]
pub(crate) fn drain_all(&mut self) -> UniqueArenaDrain<T> {
UniqueArenaDrain {
inner_elts: self.set.drain(..),
inner_spans: self.span_info.drain(..),
index: Index::new(0).unwrap(),
}
}
}
#[cfg(feature = "compact")]
pub struct UniqueArenaDrain<'a, T> {
inner_elts: indexmap::set::Drain<'a, T>,
inner_spans: std::vec::Drain<'a, Span>,
index: Index,
}
#[cfg(feature = "compact")]
impl<T> Iterator for UniqueArenaDrain<'_, T> {
type Item = (Handle<T>, T, Span);
fn next(&mut self) -> Option<Self::Item> {
match self.inner_elts.next() {
Some(elt) => {
let handle = Handle::new(self.index);
self.index = self.index.checked_add(1).unwrap();
let span = self.inner_spans.next().unwrap();
Some((handle, elt, span))
}
None => None,
}
}
}
impl<T: Eq + hash::Hash> UniqueArena<T> {
/// Returns an iterator over the items stored in this arena, returning both
/// the item's handle and a reference to it.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Handle<T>, &T)> {
self.set.iter().enumerate().map(|(i, v)| {
let index = unsafe { Index::new_unchecked(i as u32) };
(Handle::new(index), v)
})
}
/// Insert a new value into the arena.
///
/// Return a [`Handle<T>`], which can be used to index this arena to get a
/// shared reference to the element.
///
/// If this arena already contains an element that is `Eq` to `value`,
/// return a `Handle` to the existing element, and drop `value`.
///
/// If `value` is inserted into the arena, associate `span` with
/// it. An element's span can be retrieved with the [`get_span`]
/// method.
///
/// [`Handle<T>`]: Handle
/// [`get_span`]: UniqueArena::get_span
pub fn insert(&mut self, value: T, span: Span) -> Handle<T> {
let (index, added) = self.set.insert_full(value);
if added {
debug_assert!(index == self.span_info.len());
self.span_info.push(span);
}
debug_assert!(self.set.len() == self.span_info.len());
Handle::from_usize(index)
}
/// Replace an old value with a new value.
///
/// # Panics
///
/// - if the old value is not in the arena
/// - if the new value already exists in the arena
pub fn replace(&mut self, old: Handle<T>, new: T) {
let (index, added) = self.set.insert_full(new);
assert!(added && index == self.set.len() - 1);
self.set.swap_remove_index(old.index()).unwrap();
}
/// Return this arena's handle for `value`, if present.
///
/// If this arena already contains an element equal to `value`,
/// return its handle. Otherwise, return `None`.
pub fn get(&self, value: &T) -> Option<Handle<T>> {
self.set
.get_index_of(value)
.map(|index| unsafe { Handle::from_usize_unchecked(index) })
}
/// Return this arena's value at `handle`, if that is a valid handle.
pub fn get_handle(&self, handle: Handle<T>) -> Result<&T, BadHandle> {
self.set
.get_index(handle.index())
.ok_or_else(|| BadHandle::new(handle))
}
/// Assert that `handle` is valid for this arena.
pub fn check_contains_handle(&self, handle: Handle<T>) -> Result<(), BadHandle> {
if handle.index() < self.set.len() {
Ok(())
} else {
Err(BadHandle::new(handle))
}
}
}
impl<T> Default for UniqueArena<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: fmt::Debug + Eq + hash::Hash> fmt::Debug for UniqueArena<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<T> ops::Index<Handle<T>> for UniqueArena<T> {
type Output = T;
fn index(&self, handle: Handle<T>) -> &T {
&self.set[handle.index()]
}
}
#[cfg(feature = "serialize")]
impl<T> serde::Serialize for UniqueArena<T>
where
T: Eq + hash::Hash + serde::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.set.serialize(serializer)
}
}
#[cfg(feature = "deserialize")]
impl<'de, T> serde::Deserialize<'de> for UniqueArena<T>
where
T: Eq + hash::Hash + serde::Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let set = FastIndexSet::deserialize(deserializer)?;
let span_info = std::iter::repeat(Span::default()).take(set.len()).collect();
Ok(Self { set, span_info })
}
}
//Note: largely borrowed from `HashSet` implementation
#[cfg(feature = "arbitrary")]
impl<'a, T> arbitrary::Arbitrary<'a> for UniqueArena<T>
where
T: Eq + hash::Hash + arbitrary::Arbitrary<'a>,
{
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let mut arena = Self::default();
for elem in u.arbitrary_iter()? {
arena.set.insert(elem?);
arena.span_info.push(Span::UNDEFINED);
}
Ok(arena)
}
fn arbitrary_take_rest(u: arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let mut arena = Self::default();
for elem in u.arbitrary_take_rest_iter()? {
arena.set.insert(elem?);
arena.span_info.push(Span::UNDEFINED);
}
Ok(arena)
}
#[inline]
fn size_hint(depth: usize) -> (usize, Option<usize>) {
let depth_hint = <usize as arbitrary::Arbitrary>::size_hint(depth);
arbitrary::size_hint::and(depth_hint, (0, None))
}
}
+311
View File
@@ -0,0 +1,311 @@
//! Workarounds for platform bugs and limitations in switches and loops.
//!
//! In these docs, we use CamelCase links for Naga IR concepts, and ordinary
//! `code` formatting for HLSL or GLSL concepts.
//!
//! ## Avoiding `continue` within `switch`
//!
//! As described in <https://github.com/gfx-rs/wgpu/issues/4485>, the FXC HLSL
//! compiler doesn't allow `continue` statements within `switch` statements, but
//! Naga IR does. We work around this by introducing synthetic boolean local
//! variables and branches.
//!
//! Specifically:
//!
//! - We generate code for [`Continue`] statements within [`SwitchCase`]s that
//! sets an introduced `bool` local to `true` and does a `break`, jumping to
//! immediately after the generated `switch`.
//!
//! - When generating code for a [`Switch`] statement, we conservatively assume
//! it might contain such a [`Continue`] statement, so:
//!
//! - If it's the outermost such [`Switch`] within a [`Loop`], we declare the
//! `bool` local ahead of the switch, initialized to `false`. Immediately
//! after the `switch`, we check the local and do a `continue` if it's set.
//!
//! - If the [`Switch`] is nested within other [`Switch`]es, then after the
//! generated `switch`, we check the local (which we know was declared
//! before the surrounding `switch`) and do a `break` if it's set.
//!
//! - As an optimization, we only generate the check of the local if a
//! [`Continue`] statement is encountered within the [`Switch`]. This may
//! help drivers more easily identify that the `bool` is unused.
//!
//! So while we "weaken" the [`Continue`] statement by rendering it as a `break`
//! statement, we also place checks immediately at the locations to which those
//! `break` statements will jump, until we can be sure we've reached the
//! intended target of the original [`Continue`].
//!
//! In the case of nested [`Loop`] and [`Switch`] statements, there may be
//! multiple introduced `bool` locals in scope, but there's no problem knowing
//! which one to operate on. At any point, there is at most one [`Loop`]
//! statement that could be targeted by a [`Continue`] statement, so the correct
//! `bool` local to set and test is always the one introduced for the innermost
//! enclosing [`Loop`]'s outermost [`Switch`].
//!
//! # Avoiding single body `switch` statements
//!
//! As described in <https://github.com/gfx-rs/wgpu/issues/4514>, some language
//! front ends miscompile `switch` statements where all cases branch to the same
//! body. Our HLSL and GLSL backends render [`Switch`] statements with a single
//! [`SwitchCase`] as `do {} while(false);` loops.
//!
//! However, this rewriting introduces a new loop that could "capture"
//! `continue` statements in its body. To avoid doing so, we apply the
//! [`Continue`]-to-`break` transformation described above.
//!
//! [`Continue`]: crate::Statement::Continue
//! [`Loop`]: crate::Statement::Loop
//! [`Switch`]: crate::Statement::Switch
//! [`SwitchCase`]: crate::SwitchCase
use crate::proc::Namer;
use std::rc::Rc;
/// A summary of the code surrounding a statement.
enum Nesting {
/// Currently nested in at least one [`Loop`] statement.
///
/// [`Continue`] should apply to the innermost loop.
///
/// When this entry is on the top of the stack:
///
/// * When entering an inner [`Loop`] statement, push a [`Loop`][nl] state
/// onto the stack.
///
/// * When entering a nested [`Switch`] statement, push a [`Switch`][ns]
/// state onto the stack with a new variable name. Before the generated
/// `switch`, introduce a `bool` local with that name, initialized to
/// `false`.
///
/// When exiting the [`Loop`] for which this entry was pushed, pop it from
/// the stack.
///
/// [`Continue`]: crate::Statement::Continue
/// [`Loop`]: crate::Statement::Loop
/// [`Switch`]: crate::Statement::Switch
/// [ns]: Nesting::Switch
/// [nl]: Nesting::Loop
Loop,
/// Currently nested in at least one [`Switch`] that may need to forward
/// [`Continue`]s.
///
/// This includes [`Switch`]es rendered as `do {} while(false)` loops, but
/// doesn't need to include regular [`Switch`]es in backends that can
/// support `continue` within switches.
///
/// [`Continue`] should be forwarded to the innermost surrounding [`Loop`].
///
/// When this entry is on the top of the stack:
///
/// * When entering a nested [`Loop`], push a [`Loop`][nl] state onto the
/// stack.
///
/// * When entering a nested [`Switch`], push a [`Switch`][ns] state onto
/// the stack with a clone of the introduced `bool` variable's name.
///
/// * When encountering a [`Continue`] statement, render it as code to set
/// the introduced `bool` local (whose name is held in [`variable`]) to
/// `true`, and then `break`. Set [`continue_encountered`] to `true` to
/// record that the [`Switch`] contains a [`Continue`].
///
/// * When exiting this [`Switch`], pop its entry from the stack. If
/// [`continue_encountered`] is set, then we have rendered [`Continue`]
/// statements as `break` statements that jump to this point. Generate
/// code to check `variable`, and if it is `true`:
///
/// * If there is another [`Switch`][ns] left on top of the stack, set
/// its `continue_encountered` flag, and generate a `break`. (Both
/// [`Switch`][ns]es are within the same [`Loop`] and share the same
/// introduced variable, so there's no need to set another flag to
/// continue to exit the `switch`es.)
///
/// * Otherwise, `continue`.
///
/// When we exit the [`Switch`] for which this entry was pushed, pop it.
///
/// [`Continue`]: crate::Statement::Continue
/// [`Loop`]: crate::Statement::Loop
/// [`Switch`]: crate::Statement::Switch
/// [`variable`]: Nesting::Switch::variable
/// [`continue_encountered`]: Nesting::Switch::continue_encountered
/// [ns]: Nesting::Switch
/// [nl]: Nesting::Loop
Switch {
variable: Rc<String>,
/// Set if we've generated code for a [`Continue`] statement with this
/// entry on the top of the stack.
///
/// If this is still clear when we finish rendering the [`Switch`], then
/// we know we don't need to generate branch forwarding code. Omitting
/// that may make it easier for drivers to tell that the `bool` we
/// introduced ahead of the [`Switch`] is actually unused.
///
/// [`Continue`]: crate::Statement::Continue
/// [`Switch`]: crate::Statement::Switch
continue_encountered: bool,
},
}
/// A micro-IR for code a backend should generate after a [`Switch`].
///
/// [`Switch`]: crate::Statement::Switch
pub(super) enum ExitControlFlow {
None,
/// Emit `if (continue_variable) { continue; }`
Continue {
variable: Rc<String>,
},
/// Emit `if (continue_variable) { break; }`
///
/// Used after a [`Switch`] to exit from an enclosing [`Switch`].
///
/// After the enclosing switch, its associated check will consult this same
/// variable, see that it is set, and exit early.
///
/// [`Switch`]: crate::Statement::Switch
Break {
variable: Rc<String>,
},
}
/// Utility for tracking nesting of loops and switches to orchestrate forwarding
/// of continue statements inside of a switch to the enclosing loop.
///
/// See [module docs](self) for why we need this.
#[derive(Default)]
pub(super) struct ContinueCtx {
stack: Vec<Nesting>,
}
impl ContinueCtx {
/// Resets internal state.
///
/// Use this to reuse memory between writing sessions.
pub fn clear(&mut self) {
self.stack.clear();
}
/// Updates internal state to record entering a [`Loop`] statement.
///
/// [`Loop`]: crate::Statement::Loop
pub fn enter_loop(&mut self) {
self.stack.push(Nesting::Loop);
}
/// Updates internal state to record exiting a [`Loop`] statement.
///
/// [`Loop`]: crate::Statement::Loop
pub fn exit_loop(&mut self) {
if !matches!(self.stack.pop(), Some(Nesting::Loop)) {
unreachable!("ContinueCtx stack out of sync");
}
}
/// Updates internal state to record entering a [`Switch`] statement.
///
/// Return `Some(variable)` if this [`Switch`] is nested within a [`Loop`],
/// and the caller should introcue a new `bool` local variable named
/// `variable` above the `switch`, for forwarding [`Continue`] statements.
///
/// `variable` is guaranteed not to conflict with any names used by the
/// program itself.
///
/// [`Continue`]: crate::Statement::Continue
/// [`Loop`]: crate::Statement::Loop
/// [`Switch`]: crate::Statement::Switch
pub fn enter_switch(&mut self, namer: &mut Namer) -> Option<Rc<String>> {
match self.stack.last() {
// If the stack is empty, we are not in loop, so we don't need to
// forward continue statements within this `Switch`. We can leave
// the stack empty.
None => None,
Some(&Nesting::Loop { .. }) => {
let variable = Rc::new(namer.call("should_continue"));
self.stack.push(Nesting::Switch {
variable: Rc::clone(&variable),
continue_encountered: false,
});
Some(variable)
}
Some(&Nesting::Switch { ref variable, .. }) => {
self.stack.push(Nesting::Switch {
variable: Rc::clone(variable),
continue_encountered: false,
});
// We have already declared the variable before some enclosing
// `Switch`.
None
}
}
}
/// Update internal state to record leaving a [`Switch`] statement.
///
/// Return an [`ExitControlFlow`] value indicating what code should be
/// introduced after the generated `switch` to forward continues.
///
/// [`Switch`]: crate::Statement::Switch
pub fn exit_switch(&mut self) -> ExitControlFlow {
match self.stack.pop() {
// This doesn't indicate a problem: we don't start pushing entries
// for `Switch` statements unless we have an enclosing `Loop`.
None => ExitControlFlow::None,
Some(Nesting::Loop { .. }) => {
unreachable!("Unexpected loop state when exiting switch");
}
Some(Nesting::Switch {
variable,
continue_encountered: inner_continue,
}) => {
if !inner_continue {
// No `Continue` statement was encountered, so we didn't
// introduce any `break`s jumping to this point.
ExitControlFlow::None
} else if let Some(&mut Nesting::Switch {
continue_encountered: ref mut outer_continue,
..
}) = self.stack.last_mut()
{
// This is nested in another `Switch`. Propagate upwards
// that there is a continue statement present.
*outer_continue = true;
ExitControlFlow::Break { variable }
} else {
ExitControlFlow::Continue { variable }
}
}
}
}
/// Determine what to generate for a [`Continue`] statement.
///
/// If we can generate an ordinary `continue` statement, return `None`.
///
/// Otherwise, we're enclosed by a [`Switch`] that is itself enclosed by a
/// [`Loop`]. Return `Some(variable)` to indicate that the [`Continue`]
/// should be rendered as setting `variable` to `true`, and then doing a
/// `break`.
///
/// This also notes that we've encountered a [`Continue`] statement, so that
/// we can generate the right code to forward the branch following the
/// enclosing `switch`.
///
/// [`Continue`]: crate::Statement::Continue
/// [`Loop`]: crate::Statement::Loop
/// [`Switch`]: crate::Statement::Switch
pub fn continue_encountered(&mut self) -> Option<&str> {
if let Some(&mut Nesting::Switch {
ref variable,
ref mut continue_encountered,
}) = self.stack.last_mut()
{
*continue_encountered = true;
Some(variable)
} else {
None
}
}
}
+834
View File
@@ -0,0 +1,834 @@
/*!
Backend for [DOT][dot] (Graphviz).
This backend writes a graph in the DOT language, for the ease
of IR inspection and debugging.
[dot]: https://graphviz.org/doc/info/lang.html
*/
use crate::{
arena::Handle,
valid::{FunctionInfo, ModuleInfo},
};
use std::{
borrow::Cow,
fmt::{Error as FmtError, Write as _},
};
/// Configuration options for the dot backend
#[derive(Clone, Default)]
pub struct Options {
/// Only emit function bodies
pub cfg_only: bool,
}
/// Identifier used to address a graph node
type NodeId = usize;
/// Stores the target nodes for control flow statements
#[derive(Default, Clone, Copy)]
struct Targets {
/// The node, if some, where continue operations will land
continue_target: Option<usize>,
/// The node, if some, where break operations will land
break_target: Option<usize>,
}
/// Stores information about the graph of statements
#[derive(Default)]
struct StatementGraph {
/// List of node names
nodes: Vec<&'static str>,
/// List of edges of the control flow, the items are defined as
/// (from, to, label)
flow: Vec<(NodeId, NodeId, &'static str)>,
/// List of implicit edges of the control flow, used for jump
/// operations such as continue or break, the items are defined as
/// (from, to, label, color_id)
jumps: Vec<(NodeId, NodeId, &'static str, usize)>,
/// List of dependency relationships between a statement node and
/// expressions
dependencies: Vec<(NodeId, Handle<crate::Expression>, &'static str)>,
/// List of expression emitted by statement node
emits: Vec<(NodeId, Handle<crate::Expression>)>,
/// List of function call by statement node
calls: Vec<(NodeId, Handle<crate::Function>)>,
}
impl StatementGraph {
/// Adds a new block to the statement graph, returning the first and last node, respectively
fn add(&mut self, block: &[crate::Statement], targets: Targets) -> (NodeId, NodeId) {
use crate::Statement as S;
// The first node of the block isn't a statement but a virtual node
let root = self.nodes.len();
self.nodes.push(if root == 0 { "Root" } else { "Node" });
// Track the last placed node, this will be returned to the caller and
// will also be used to generate the control flow edges
let mut last_node = root;
for statement in block {
// Reserve a new node for the current statement and link it to the
// node of the previous statement
let id = self.nodes.len();
self.flow.push((last_node, id, ""));
self.nodes.push(""); // reserve space
// Track the node identifier for the merge node, the merge node is
// the last node of a statement, normally this is the node itself,
// but for control flow statements such as `if`s and `switch`s this
// is a virtual node where all branches merge back.
let mut merge_id = id;
self.nodes[id] = match *statement {
S::Emit(ref range) => {
for handle in range.clone() {
self.emits.push((id, handle));
}
"Emit"
}
S::Kill => "Kill", //TODO: link to the beginning
S::Break => {
// Try to link to the break target, otherwise produce
// a broken connection
if let Some(target) = targets.break_target {
self.jumps.push((id, target, "Break", 5))
} else {
self.jumps.push((id, root, "Broken", 7))
}
"Break"
}
S::Continue => {
// Try to link to the continue target, otherwise produce
// a broken connection
if let Some(target) = targets.continue_target {
self.jumps.push((id, target, "Continue", 5))
} else {
self.jumps.push((id, root, "Broken", 7))
}
"Continue"
}
S::Barrier(_flags) => "Barrier",
S::Block(ref b) => {
let (other, last) = self.add(b, targets);
self.flow.push((id, other, ""));
// All following nodes should connect to the end of the block
// statement so change the merge id to it.
merge_id = last;
"Block"
}
S::If {
condition,
ref accept,
ref reject,
} => {
self.dependencies.push((id, condition, "condition"));
let (accept_id, accept_last) = self.add(accept, targets);
self.flow.push((id, accept_id, "accept"));
let (reject_id, reject_last) = self.add(reject, targets);
self.flow.push((id, reject_id, "reject"));
// Create a merge node, link the branches to it and set it
// as the merge node to make the next statement node link to it
merge_id = self.nodes.len();
self.nodes.push("Merge");
self.flow.push((accept_last, merge_id, ""));
self.flow.push((reject_last, merge_id, ""));
"If"
}
S::Switch {
selector,
ref cases,
} => {
self.dependencies.push((id, selector, "selector"));
// Create a merge node and set it as the merge node to make
// the next statement node link to it
merge_id = self.nodes.len();
self.nodes.push("Merge");
// Create a new targets structure and set the break target
// to the merge node
let mut targets = targets;
targets.break_target = Some(merge_id);
for case in cases {
let (case_id, case_last) = self.add(&case.body, targets);
let label = match case.value {
crate::SwitchValue::Default => "default",
_ => "case",
};
self.flow.push((id, case_id, label));
// Link the last node of the branch to the merge node
self.flow.push((case_last, merge_id, ""));
}
"Switch"
}
S::Loop {
ref body,
ref continuing,
break_if,
} => {
// Create a new targets structure and set the break target
// to the merge node, this must happen before generating the
// continuing block since it can break.
let mut targets = targets;
targets.break_target = Some(id);
let (continuing_id, continuing_last) = self.add(continuing, targets);
// Set the the continue target to the beginning
// of the newly generated continuing block
targets.continue_target = Some(continuing_id);
let (body_id, body_last) = self.add(body, targets);
self.flow.push((id, body_id, "body"));
// Link the last node of the body to the continuing block
self.flow.push((body_last, continuing_id, "continuing"));
// Link the last node of the continuing block back to the
// beginning of the loop body
self.flow.push((continuing_last, body_id, "continuing"));
if let Some(expr) = break_if {
self.dependencies.push((continuing_id, expr, "break if"));
}
"Loop"
}
S::Return { value } => {
if let Some(expr) = value {
self.dependencies.push((id, expr, "value"));
}
"Return"
}
S::Store { pointer, value } => {
self.dependencies.push((id, value, "value"));
self.emits.push((id, pointer));
"Store"
}
S::ImageStore {
image,
coordinate,
array_index,
value,
} => {
self.dependencies.push((id, image, "image"));
self.dependencies.push((id, coordinate, "coordinate"));
if let Some(expr) = array_index {
self.dependencies.push((id, expr, "array_index"));
}
self.dependencies.push((id, value, "value"));
"ImageStore"
}
S::Call {
function,
ref arguments,
result,
} => {
for &arg in arguments {
self.dependencies.push((id, arg, "arg"));
}
if let Some(expr) = result {
self.emits.push((id, expr));
}
self.calls.push((id, function));
"Call"
}
S::Atomic {
pointer,
ref fun,
value,
result,
} => {
if let Some(result) = result {
self.emits.push((id, result));
}
self.dependencies.push((id, pointer, "pointer"));
self.dependencies.push((id, value, "value"));
if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
self.dependencies.push((id, cmp, "cmp"));
}
"Atomic"
}
S::ImageAtomic {
image,
coordinate,
array_index,
fun: _,
value,
} => {
self.dependencies.push((id, image, "image"));
self.dependencies.push((id, coordinate, "coordinate"));
if let Some(expr) = array_index {
self.dependencies.push((id, expr, "array_index"));
}
self.dependencies.push((id, value, "value"));
"ImageAtomic"
}
S::WorkGroupUniformLoad { pointer, result } => {
self.emits.push((id, result));
self.dependencies.push((id, pointer, "pointer"));
"WorkGroupUniformLoad"
}
S::RayQuery { query, ref fun } => {
self.dependencies.push((id, query, "query"));
match *fun {
crate::RayQueryFunction::Initialize {
acceleration_structure,
descriptor,
} => {
self.dependencies.push((
id,
acceleration_structure,
"acceleration_structure",
));
self.dependencies.push((id, descriptor, "descriptor"));
"RayQueryInitialize"
}
crate::RayQueryFunction::Proceed { result } => {
self.emits.push((id, result));
"RayQueryProceed"
}
crate::RayQueryFunction::Terminate => "RayQueryTerminate",
}
}
S::SubgroupBallot { result, predicate } => {
if let Some(predicate) = predicate {
self.dependencies.push((id, predicate, "predicate"));
}
self.emits.push((id, result));
"SubgroupBallot"
}
S::SubgroupCollectiveOperation {
op,
collective_op,
argument,
result,
} => {
self.dependencies.push((id, argument, "arg"));
self.emits.push((id, result));
match (collective_op, op) {
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
"SubgroupAll"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
"SubgroupAny"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
"SubgroupAdd"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
"SubgroupMul"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
"SubgroupMax"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
"SubgroupMin"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
"SubgroupAnd"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
"SubgroupOr"
}
(crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
"SubgroupXor"
}
(
crate::CollectiveOperation::ExclusiveScan,
crate::SubgroupOperation::Add,
) => "SubgroupExclusiveAdd",
(
crate::CollectiveOperation::ExclusiveScan,
crate::SubgroupOperation::Mul,
) => "SubgroupExclusiveMul",
(
crate::CollectiveOperation::InclusiveScan,
crate::SubgroupOperation::Add,
) => "SubgroupInclusiveAdd",
(
crate::CollectiveOperation::InclusiveScan,
crate::SubgroupOperation::Mul,
) => "SubgroupInclusiveMul",
_ => unimplemented!(),
}
}
S::SubgroupGather {
mode,
argument,
result,
} => {
match mode {
crate::GatherMode::BroadcastFirst => {}
crate::GatherMode::Broadcast(index)
| crate::GatherMode::Shuffle(index)
| crate::GatherMode::ShuffleDown(index)
| crate::GatherMode::ShuffleUp(index)
| crate::GatherMode::ShuffleXor(index) => {
self.dependencies.push((id, index, "index"))
}
}
self.dependencies.push((id, argument, "arg"));
self.emits.push((id, result));
match mode {
crate::GatherMode::BroadcastFirst => "SubgroupBroadcastFirst",
crate::GatherMode::Broadcast(_) => "SubgroupBroadcast",
crate::GatherMode::Shuffle(_) => "SubgroupShuffle",
crate::GatherMode::ShuffleDown(_) => "SubgroupShuffleDown",
crate::GatherMode::ShuffleUp(_) => "SubgroupShuffleUp",
crate::GatherMode::ShuffleXor(_) => "SubgroupShuffleXor",
}
}
};
// Set the last node to the merge node
last_node = merge_id;
}
(root, last_node)
}
}
fn name(option: &Option<String>) -> &str {
option.as_deref().unwrap_or_default()
}
/// set39 color scheme from <https://graphviz.org/doc/info/colors.html>
const COLORS: &[&str] = &[
"white", // pattern starts at 1
"#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5",
"#d9d9d9",
];
struct Prefixed<T>(Handle<T>);
impl std::fmt::Display for Prefixed<crate::Expression> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_prefixed(f, "e")
}
}
impl std::fmt::Display for Prefixed<crate::LocalVariable> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_prefixed(f, "l")
}
}
impl std::fmt::Display for Prefixed<crate::GlobalVariable> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_prefixed(f, "g")
}
}
impl std::fmt::Display for Prefixed<crate::Function> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_prefixed(f, "f")
}
}
fn write_fun(
output: &mut String,
prefix: String,
fun: &crate::Function,
info: Option<&FunctionInfo>,
options: &Options,
) -> Result<(), FmtError> {
writeln!(output, "\t\tnode [ style=filled ]")?;
if !options.cfg_only {
for (handle, var) in fun.local_variables.iter() {
writeln!(
output,
"\t\t{}_{} [ shape=hexagon label=\"{:?} '{}'\" ]",
prefix,
Prefixed(handle),
handle,
name(&var.name),
)?;
}
write_function_expressions(output, &prefix, fun, info)?;
}
let mut sg = StatementGraph::default();
sg.add(&fun.body, Targets::default());
for (index, label) in sg.nodes.into_iter().enumerate() {
writeln!(
output,
"\t\t{prefix}_s{index} [ shape=square label=\"{label}\" ]",
)?;
}
for (from, to, label) in sg.flow {
writeln!(
output,
"\t\t{prefix}_s{from} -> {prefix}_s{to} [ arrowhead=tee label=\"{label}\" ]",
)?;
}
for (from, to, label, color_id) in sg.jumps {
writeln!(
output,
"\t\t{}_s{} -> {}_s{} [ arrowhead=tee style=dashed color=\"{}\" label=\"{}\" ]",
prefix, from, prefix, to, COLORS[color_id], label,
)?;
}
if !options.cfg_only {
for (to, expr, label) in sg.dependencies {
writeln!(
output,
"\t\t{}_{} -> {}_s{} [ label=\"{}\" ]",
prefix,
Prefixed(expr),
prefix,
to,
label,
)?;
}
for (from, to) in sg.emits {
writeln!(
output,
"\t\t{}_s{} -> {}_{} [ style=dotted ]",
prefix,
from,
prefix,
Prefixed(to),
)?;
}
}
assert!(sg.calls.is_empty());
for (from, function) in sg.calls {
writeln!(
output,
"\t\t{}_s{} -> {}_s0",
prefix,
from,
Prefixed(function),
)?;
}
Ok(())
}
fn write_function_expressions(
output: &mut String,
prefix: &str,
fun: &crate::Function,
info: Option<&FunctionInfo>,
) -> Result<(), FmtError> {
enum Payload<'a> {
Arguments(&'a [Handle<crate::Expression>]),
Local(Handle<crate::LocalVariable>),
Global(Handle<crate::GlobalVariable>),
}
let mut edges = crate::FastHashMap::<&str, _>::default();
let mut payload = None;
for (handle, expression) in fun.expressions.iter() {
use crate::Expression as E;
let (label, color_id) = match *expression {
E::Literal(_) => ("Literal".into(), 2),
E::Constant(_) => ("Constant".into(), 2),
E::Override(_) => ("Override".into(), 2),
E::ZeroValue(_) => ("ZeroValue".into(), 2),
E::Compose { ref components, .. } => {
payload = Some(Payload::Arguments(components));
("Compose".into(), 3)
}
E::Access { base, index } => {
edges.insert("base", base);
edges.insert("index", index);
("Access".into(), 1)
}
E::AccessIndex { base, index } => {
edges.insert("base", base);
(format!("AccessIndex[{index}]").into(), 1)
}
E::Splat { size, value } => {
edges.insert("value", value);
(format!("Splat{size:?}").into(), 3)
}
E::Swizzle {
size,
vector,
pattern,
} => {
edges.insert("vector", vector);
(format!("Swizzle{:?}", &pattern[..size as usize]).into(), 3)
}
E::FunctionArgument(index) => (format!("Argument[{index}]").into(), 1),
E::GlobalVariable(h) => {
payload = Some(Payload::Global(h));
("Global".into(), 2)
}
E::LocalVariable(h) => {
payload = Some(Payload::Local(h));
("Local".into(), 1)
}
E::Load { pointer } => {
edges.insert("pointer", pointer);
("Load".into(), 4)
}
E::ImageSample {
image,
sampler,
gather,
coordinate,
array_index,
offset: _,
level,
depth_ref,
} => {
edges.insert("image", image);
edges.insert("sampler", sampler);
edges.insert("coordinate", coordinate);
if let Some(expr) = array_index {
edges.insert("array_index", expr);
}
match level {
crate::SampleLevel::Auto => {}
crate::SampleLevel::Zero => {}
crate::SampleLevel::Exact(expr) => {
edges.insert("level", expr);
}
crate::SampleLevel::Bias(expr) => {
edges.insert("bias", expr);
}
crate::SampleLevel::Gradient { x, y } => {
edges.insert("grad_x", x);
edges.insert("grad_y", y);
}
}
if let Some(expr) = depth_ref {
edges.insert("depth_ref", expr);
}
let string = match gather {
Some(component) => Cow::Owned(format!("ImageGather{component:?}")),
_ => Cow::Borrowed("ImageSample"),
};
(string, 5)
}
E::ImageLoad {
image,
coordinate,
array_index,
sample,
level,
} => {
edges.insert("image", image);
edges.insert("coordinate", coordinate);
if let Some(expr) = array_index {
edges.insert("array_index", expr);
}
if let Some(sample) = sample {
edges.insert("sample", sample);
}
if let Some(level) = level {
edges.insert("level", level);
}
("ImageLoad".into(), 5)
}
E::ImageQuery { image, query } => {
edges.insert("image", image);
let args = match query {
crate::ImageQuery::Size { level } => {
if let Some(expr) = level {
edges.insert("level", expr);
}
Cow::from("ImageSize")
}
_ => Cow::Owned(format!("{query:?}")),
};
(args, 7)
}
E::Unary { op, expr } => {
edges.insert("expr", expr);
(format!("{op:?}").into(), 6)
}
E::Binary { op, left, right } => {
edges.insert("left", left);
edges.insert("right", right);
(format!("{op:?}").into(), 6)
}
E::Select {
condition,
accept,
reject,
} => {
edges.insert("condition", condition);
edges.insert("accept", accept);
edges.insert("reject", reject);
("Select".into(), 3)
}
E::Derivative { axis, ctrl, expr } => {
edges.insert("", expr);
(format!("d{axis:?}{ctrl:?}").into(), 8)
}
E::Relational { fun, argument } => {
edges.insert("arg", argument);
(format!("{fun:?}").into(), 6)
}
E::Math {
fun,
arg,
arg1,
arg2,
arg3,
} => {
edges.insert("arg", arg);
if let Some(expr) = arg1 {
edges.insert("arg1", expr);
}
if let Some(expr) = arg2 {
edges.insert("arg2", expr);
}
if let Some(expr) = arg3 {
edges.insert("arg3", expr);
}
(format!("{fun:?}").into(), 7)
}
E::As {
kind,
expr,
convert,
} => {
edges.insert("", expr);
let string = match convert {
Some(width) => format!("Convert<{kind:?},{width}>"),
None => format!("Bitcast<{kind:?}>"),
};
(string.into(), 3)
}
E::CallResult(_function) => ("CallResult".into(), 4),
E::AtomicResult { .. } => ("AtomicResult".into(), 4),
E::WorkGroupUniformLoadResult { .. } => ("WorkGroupUniformLoadResult".into(), 4),
E::ArrayLength(expr) => {
edges.insert("", expr);
("ArrayLength".into(), 7)
}
E::RayQueryProceedResult => ("rayQueryProceedResult".into(), 4),
E::RayQueryGetIntersection { query, committed } => {
edges.insert("", query);
let ty = if committed { "Committed" } else { "Candidate" };
(format!("rayQueryGet{ty}Intersection").into(), 4)
}
E::SubgroupBallotResult => ("SubgroupBallotResult".into(), 4),
E::SubgroupOperationResult { .. } => ("SubgroupOperationResult".into(), 4),
};
// give uniform expressions an outline
let color_attr = match info {
Some(info) if info[handle].uniformity.non_uniform_result.is_none() => "fillcolor",
_ => "color",
};
writeln!(
output,
"\t\t{}_{} [ {}=\"{}\" label=\"{:?} {}\" ]",
prefix,
Prefixed(handle),
color_attr,
COLORS[color_id],
handle,
label,
)?;
for (key, edge) in edges.drain() {
writeln!(
output,
"\t\t{}_{} -> {}_{} [ label=\"{}\" ]",
prefix,
Prefixed(edge),
prefix,
Prefixed(handle),
key,
)?;
}
match payload.take() {
Some(Payload::Arguments(list)) => {
write!(output, "\t\t{{")?;
for &comp in list {
write!(output, " {}_{}", prefix, Prefixed(comp))?;
}
writeln!(output, " }} -> {}_{}", prefix, Prefixed(handle))?;
}
Some(Payload::Local(h)) => {
writeln!(
output,
"\t\t{}_{} -> {}_{}",
prefix,
Prefixed(h),
prefix,
Prefixed(handle),
)?;
}
Some(Payload::Global(h)) => {
writeln!(
output,
"\t\t{} -> {}_{} [fillcolor=gray]",
Prefixed(h),
prefix,
Prefixed(handle),
)?;
}
None => {}
}
}
Ok(())
}
/// Write shader module to a [`String`].
pub fn write(
module: &crate::Module,
mod_info: Option<&ModuleInfo>,
options: Options,
) -> Result<String, FmtError> {
use std::fmt::Write as _;
let mut output = String::new();
output += "digraph Module {\n";
if !options.cfg_only {
writeln!(output, "\tsubgraph cluster_globals {{")?;
writeln!(output, "\t\tlabel=\"Globals\"")?;
for (handle, var) in module.global_variables.iter() {
writeln!(
output,
"\t\t{} [ shape=hexagon label=\"{:?} {:?}/'{}'\" ]",
Prefixed(handle),
handle,
var.space,
name(&var.name),
)?;
}
writeln!(output, "\t}}")?;
}
for (handle, fun) in module.functions.iter() {
let prefix = Prefixed(handle).to_string();
writeln!(output, "\tsubgraph cluster_{prefix} {{")?;
writeln!(
output,
"\t\tlabel=\"Function{:?}/'{}'\"",
handle,
name(&fun.name)
)?;
let info = mod_info.map(|a| &a[handle]);
write_fun(&mut output, prefix, fun, info, &options)?;
writeln!(output, "\t}}")?;
}
for (ep_index, ep) in module.entry_points.iter().enumerate() {
let prefix = format!("ep{ep_index}");
writeln!(output, "\tsubgraph cluster_{prefix} {{")?;
writeln!(output, "\t\tlabel=\"{:?}/'{}'\"", ep.stage, ep.name)?;
let info = mod_info.map(|a| a.get_entry_point(ep_index));
write_fun(&mut output, prefix, &ep.function, info, &options)?;
writeln!(output, "\t}}")?;
}
output += "}\n";
Ok(output)
}
+622
View File
@@ -0,0 +1,622 @@
use super::{BackendResult, Error, Version, Writer};
use crate::{
back::glsl::{Options, WriterFlags},
AddressSpace, Binding, Expression, Handle, ImageClass, ImageDimension, Interpolation,
SampleLevel, Sampling, Scalar, ScalarKind, ShaderStage, StorageFormat, Type, TypeInner,
};
use std::fmt::Write;
bitflags::bitflags! {
/// Structure used to encode additions to GLSL that aren't supported by all versions.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Features: u32 {
/// Buffer address space support.
const BUFFER_STORAGE = 1;
const ARRAY_OF_ARRAYS = 1 << 1;
/// 8 byte floats.
const DOUBLE_TYPE = 1 << 2;
/// More image formats.
const FULL_IMAGE_FORMATS = 1 << 3;
const MULTISAMPLED_TEXTURES = 1 << 4;
const MULTISAMPLED_TEXTURE_ARRAYS = 1 << 5;
const CUBE_TEXTURES_ARRAY = 1 << 6;
const COMPUTE_SHADER = 1 << 7;
/// Image load and early depth tests.
const IMAGE_LOAD_STORE = 1 << 8;
const CONSERVATIVE_DEPTH = 1 << 9;
/// Interpolation and auxiliary qualifiers.
///
/// Perspective, Flat, and Centroid are available in all GLSL versions we support.
const NOPERSPECTIVE_QUALIFIER = 1 << 11;
const SAMPLE_QUALIFIER = 1 << 12;
const CLIP_DISTANCE = 1 << 13;
const CULL_DISTANCE = 1 << 14;
/// Sample ID.
const SAMPLE_VARIABLES = 1 << 15;
/// Arrays with a dynamic length.
const DYNAMIC_ARRAY_SIZE = 1 << 16;
const MULTI_VIEW = 1 << 17;
/// Texture samples query
const TEXTURE_SAMPLES = 1 << 18;
/// Texture levels query
const TEXTURE_LEVELS = 1 << 19;
/// Image size query
const IMAGE_SIZE = 1 << 20;
/// Dual source blending
const DUAL_SOURCE_BLENDING = 1 << 21;
/// Instance index
///
/// We can always support this, either through the language or a polyfill
const INSTANCE_INDEX = 1 << 22;
/// Sample specific LODs of cube / array shadow textures
const TEXTURE_SHADOW_LOD = 1 << 23;
/// Subgroup operations
const SUBGROUP_OPERATIONS = 1 << 24;
/// Image atomics
const TEXTURE_ATOMICS = 1 << 25;
}
}
/// Helper structure used to store the required [`Features`] needed to output a
/// [`Module`](crate::Module)
///
/// Provides helper methods to check for availability and writing required extensions
pub struct FeaturesManager(Features);
impl FeaturesManager {
/// Creates a new [`FeaturesManager`] instance
pub const fn new() -> Self {
Self(Features::empty())
}
/// Adds to the list of required [`Features`]
pub fn request(&mut self, features: Features) {
self.0 |= features
}
/// Checks if the list of features [`Features`] contains the specified [`Features`]
pub fn contains(&mut self, features: Features) -> bool {
self.0.contains(features)
}
/// Checks that all required [`Features`] are available for the specified
/// [`Version`] otherwise returns an [`Error::MissingFeatures`].
pub fn check_availability(&self, version: Version) -> BackendResult {
// Will store all the features that are unavailable
let mut missing = Features::empty();
// Helper macro to check for feature availability
macro_rules! check_feature {
// Used when only core glsl supports the feature
($feature:ident, $core:literal) => {
if self.0.contains(Features::$feature)
&& (version < Version::Desktop($core) || version.is_es())
{
missing |= Features::$feature;
}
};
// Used when both core and es support the feature
($feature:ident, $core:literal, $es:literal) => {
if self.0.contains(Features::$feature)
&& (version < Version::Desktop($core) || version < Version::new_gles($es))
{
missing |= Features::$feature;
}
};
}
check_feature!(COMPUTE_SHADER, 420, 310);
check_feature!(BUFFER_STORAGE, 400, 310);
check_feature!(DOUBLE_TYPE, 150);
check_feature!(CUBE_TEXTURES_ARRAY, 130, 310);
check_feature!(MULTISAMPLED_TEXTURES, 150, 300);
check_feature!(MULTISAMPLED_TEXTURE_ARRAYS, 150, 310);
check_feature!(ARRAY_OF_ARRAYS, 120, 310);
check_feature!(IMAGE_LOAD_STORE, 130, 310);
check_feature!(CONSERVATIVE_DEPTH, 130, 300);
check_feature!(NOPERSPECTIVE_QUALIFIER, 130);
check_feature!(SAMPLE_QUALIFIER, 400, 320);
check_feature!(CLIP_DISTANCE, 130, 300 /* with extension */);
check_feature!(CULL_DISTANCE, 450, 300 /* with extension */);
check_feature!(SAMPLE_VARIABLES, 400, 300);
check_feature!(DYNAMIC_ARRAY_SIZE, 430, 310);
check_feature!(DUAL_SOURCE_BLENDING, 330, 300 /* with extension */);
check_feature!(SUBGROUP_OPERATIONS, 430, 310);
check_feature!(TEXTURE_ATOMICS, 420, 310);
match version {
Version::Embedded { is_webgl: true, .. } => check_feature!(MULTI_VIEW, 140, 300),
_ => check_feature!(MULTI_VIEW, 140, 310),
};
// Only available on glsl core, this means that opengl es can't query the number
// of samples nor levels in a image and neither do bound checks on the sample nor
// the level argument of texelFecth
check_feature!(TEXTURE_SAMPLES, 150);
check_feature!(TEXTURE_LEVELS, 130);
check_feature!(IMAGE_SIZE, 430, 310);
check_feature!(TEXTURE_SHADOW_LOD, 200, 300);
// Return an error if there are missing features
if missing.is_empty() {
Ok(())
} else {
Err(Error::MissingFeatures(missing))
}
}
/// Helper method used to write all needed extensions
///
/// # Notes
/// This won't check for feature availability so it might output extensions that aren't even
/// supported.[`check_availability`](Self::check_availability) will check feature availability
pub fn write(&self, options: &Options, mut out: impl Write) -> BackendResult {
if self.0.contains(Features::COMPUTE_SHADER) && !options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_compute_shader.txt
writeln!(out, "#extension GL_ARB_compute_shader : require")?;
}
if self.0.contains(Features::BUFFER_STORAGE) && !options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_storage_buffer_object.txt
writeln!(
out,
"#extension GL_ARB_shader_storage_buffer_object : require"
)?;
}
if self.0.contains(Features::DOUBLE_TYPE) && options.version < Version::Desktop(400) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_fp64.txt
writeln!(out, "#extension GL_ARB_gpu_shader_fp64 : require")?;
}
if self.0.contains(Features::CUBE_TEXTURES_ARRAY) {
if options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_cube_map_array.txt
writeln!(out, "#extension GL_EXT_texture_cube_map_array : require")?;
} else if options.version < Version::Desktop(400) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_cube_map_array.txt
writeln!(out, "#extension GL_ARB_texture_cube_map_array : require")?;
}
}
if self.0.contains(Features::MULTISAMPLED_TEXTURE_ARRAYS) && options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/OES/OES_texture_storage_multisample_2d_array.txt
writeln!(
out,
"#extension GL_OES_texture_storage_multisample_2d_array : require"
)?;
}
if self.0.contains(Features::ARRAY_OF_ARRAYS) && options.version < Version::Desktop(430) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_arrays_of_arrays.txt
writeln!(out, "#extension ARB_arrays_of_arrays : require")?;
}
if self.0.contains(Features::IMAGE_LOAD_STORE) {
if self.0.contains(Features::FULL_IMAGE_FORMATS) && options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/NV/NV_image_formats.txt
writeln!(out, "#extension GL_NV_image_formats : require")?;
}
if options.version < Version::Desktop(420) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_image_load_store.txt
writeln!(out, "#extension GL_ARB_shader_image_load_store : require")?;
}
}
if self.0.contains(Features::CONSERVATIVE_DEPTH) {
if options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_conservative_depth.txt
writeln!(out, "#extension GL_EXT_conservative_depth : require")?;
}
if options.version < Version::Desktop(420) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt
writeln!(out, "#extension GL_ARB_conservative_depth : require")?;
}
}
if (self.0.contains(Features::CLIP_DISTANCE) || self.0.contains(Features::CULL_DISTANCE))
&& options.version.is_es()
{
// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_clip_cull_distance.txt
writeln!(out, "#extension GL_EXT_clip_cull_distance : require")?;
}
if self.0.contains(Features::SAMPLE_VARIABLES) && options.version.is_es() {
// https://www.khronos.org/registry/OpenGL/extensions/OES/OES_sample_variables.txt
writeln!(out, "#extension GL_OES_sample_variables : require")?;
}
if self.0.contains(Features::MULTI_VIEW) {
if let Version::Embedded { is_webgl: true, .. } = options.version {
// https://www.khronos.org/registry/OpenGL/extensions/OVR/OVR_multiview2.txt
writeln!(out, "#extension GL_OVR_multiview2 : require")?;
} else {
// https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_multiview.txt
writeln!(out, "#extension GL_EXT_multiview : require")?;
}
}
if self.0.contains(Features::TEXTURE_SAMPLES) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_texture_image_samples.txt
writeln!(
out,
"#extension GL_ARB_shader_texture_image_samples : require"
)?;
}
if self.0.contains(Features::TEXTURE_LEVELS) && options.version < Version::Desktop(430) {
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_query_levels.txt
writeln!(out, "#extension GL_ARB_texture_query_levels : require")?;
}
if self.0.contains(Features::DUAL_SOURCE_BLENDING) && options.version.is_es() {
// https://registry.khronos.org/OpenGL/extensions/EXT/EXT_blend_func_extended.txt
writeln!(out, "#extension GL_EXT_blend_func_extended : require")?;
}
if self.0.contains(Features::INSTANCE_INDEX) {
if options.writer_flags.contains(WriterFlags::DRAW_PARAMETERS) {
// https://registry.khronos.org/OpenGL/extensions/ARB/ARB_shader_draw_parameters.txt
writeln!(out, "#extension GL_ARB_shader_draw_parameters : require")?;
}
}
if self.0.contains(Features::TEXTURE_SHADOW_LOD) {
// https://registry.khronos.org/OpenGL/extensions/EXT/EXT_texture_shadow_lod.txt
writeln!(out, "#extension GL_EXT_texture_shadow_lod : require")?;
}
if self.0.contains(Features::SUBGROUP_OPERATIONS) {
// https://registry.khronos.org/OpenGL/extensions/KHR/KHR_shader_subgroup.txt
writeln!(out, "#extension GL_KHR_shader_subgroup_basic : require")?;
writeln!(out, "#extension GL_KHR_shader_subgroup_vote : require")?;
writeln!(
out,
"#extension GL_KHR_shader_subgroup_arithmetic : require"
)?;
writeln!(out, "#extension GL_KHR_shader_subgroup_ballot : require")?;
writeln!(out, "#extension GL_KHR_shader_subgroup_shuffle : require")?;
writeln!(
out,
"#extension GL_KHR_shader_subgroup_shuffle_relative : require"
)?;
}
if self.0.contains(Features::TEXTURE_ATOMICS) {
// https://www.khronos.org/registry/OpenGL/extensions/OES/OES_shader_image_atomic.txt
writeln!(out, "#extension GL_OES_shader_image_atomic : require")?;
}
Ok(())
}
}
impl<W> Writer<'_, W> {
/// Helper method that searches the module for all the needed [`Features`]
///
/// # Errors
/// If the version doesn't support any of the needed [`Features`] a
/// [`Error::MissingFeatures`] will be returned
pub(super) fn collect_required_features(&mut self) -> BackendResult {
let ep_info = self.info.get_entry_point(self.entry_point_idx as usize);
if let Some(depth_test) = self.entry_point.early_depth_test {
// If IMAGE_LOAD_STORE is supported for this version of GLSL
if self.options.version.supports_early_depth_test() {
self.features.request(Features::IMAGE_LOAD_STORE);
}
if depth_test.conservative.is_some() {
self.features.request(Features::CONSERVATIVE_DEPTH);
}
}
for arg in self.entry_point.function.arguments.iter() {
self.varying_required_features(arg.binding.as_ref(), arg.ty);
}
if let Some(ref result) = self.entry_point.function.result {
self.varying_required_features(result.binding.as_ref(), result.ty);
}
if let ShaderStage::Compute = self.entry_point.stage {
self.features.request(Features::COMPUTE_SHADER)
}
if self.multiview.is_some() {
self.features.request(Features::MULTI_VIEW);
}
for (ty_handle, ty) in self.module.types.iter() {
match ty.inner {
TypeInner::Scalar(scalar)
| TypeInner::Vector { scalar, .. }
| TypeInner::Matrix { scalar, .. } => self.scalar_required_features(scalar),
TypeInner::Array { base, size, .. } => {
if let TypeInner::Array { .. } = self.module.types[base].inner {
self.features.request(Features::ARRAY_OF_ARRAYS)
}
// If the array is dynamically sized
if size == crate::ArraySize::Dynamic {
let mut is_used = false;
// Check if this type is used in a global that is needed by the current entrypoint
for (global_handle, global) in self.module.global_variables.iter() {
// Skip unused globals
if ep_info[global_handle].is_empty() {
continue;
}
// If this array is the type of a global, then this array is used
if global.ty == ty_handle {
is_used = true;
break;
}
// If the type of this global is a struct
if let TypeInner::Struct { ref members, .. } =
self.module.types[global.ty].inner
{
// Check the last element of the struct to see if it's type uses
// this array
if let Some(last) = members.last() {
if last.ty == ty_handle {
is_used = true;
break;
}
}
}
}
// If this dynamically size array is used, we need dynamic array size support
if is_used {
self.features.request(Features::DYNAMIC_ARRAY_SIZE);
}
}
}
TypeInner::Image {
dim,
arrayed,
class,
} => {
if arrayed && dim == ImageDimension::Cube {
self.features.request(Features::CUBE_TEXTURES_ARRAY)
}
match class {
ImageClass::Sampled { multi: true, .. }
| ImageClass::Depth { multi: true } => {
self.features.request(Features::MULTISAMPLED_TEXTURES);
if arrayed {
self.features.request(Features::MULTISAMPLED_TEXTURE_ARRAYS);
}
}
ImageClass::Storage { format, .. } => match format {
StorageFormat::R8Unorm
| StorageFormat::R8Snorm
| StorageFormat::R8Uint
| StorageFormat::R8Sint
| StorageFormat::R16Uint
| StorageFormat::R16Sint
| StorageFormat::R16Float
| StorageFormat::Rg8Unorm
| StorageFormat::Rg8Snorm
| StorageFormat::Rg8Uint
| StorageFormat::Rg8Sint
| StorageFormat::Rg16Uint
| StorageFormat::Rg16Sint
| StorageFormat::Rg16Float
| StorageFormat::Rgb10a2Uint
| StorageFormat::Rgb10a2Unorm
| StorageFormat::Rg11b10Ufloat
| StorageFormat::R64Uint
| StorageFormat::Rg32Uint
| StorageFormat::Rg32Sint
| StorageFormat::Rg32Float => {
self.features.request(Features::FULL_IMAGE_FORMATS)
}
_ => {}
},
ImageClass::Sampled { multi: false, .. }
| ImageClass::Depth { multi: false } => {}
}
}
_ => {}
}
}
let mut push_constant_used = false;
for (handle, global) in self.module.global_variables.iter() {
if ep_info[handle].is_empty() {
continue;
}
match global.space {
AddressSpace::WorkGroup => self.features.request(Features::COMPUTE_SHADER),
AddressSpace::Storage { .. } => self.features.request(Features::BUFFER_STORAGE),
AddressSpace::PushConstant => {
if push_constant_used {
return Err(Error::MultiplePushConstants);
}
push_constant_used = true;
}
_ => {}
}
}
// We will need to pass some of the members to a closure, so we need
// to separate them otherwise the borrow checker will complain, this
// shouldn't be needed in rust 2021
let &mut Self {
module,
info,
ref mut features,
entry_point,
entry_point_idx,
ref policies,
..
} = self;
// Loop through all expressions in both functions and the entry point
// to check for needed features
for (expressions, info) in module
.functions
.iter()
.map(|(h, f)| (&f.expressions, &info[h]))
.chain(std::iter::once((
&entry_point.function.expressions,
info.get_entry_point(entry_point_idx as usize),
)))
{
for (_, expr) in expressions.iter() {
match *expr {
// Check for queries that need aditonal features
Expression::ImageQuery {
image,
query,
..
} => match query {
// Storage images use `imageSize` which is only available
// in glsl > 420
//
// layers queries are also implemented as size queries
crate::ImageQuery::Size { .. } | crate::ImageQuery::NumLayers => {
if let TypeInner::Image {
class: ImageClass::Storage { .. }, ..
} = *info[image].ty.inner_with(&module.types) {
features.request(Features::IMAGE_SIZE)
}
},
crate::ImageQuery::NumLevels => features.request(Features::TEXTURE_LEVELS),
crate::ImageQuery::NumSamples => features.request(Features::TEXTURE_SAMPLES),
}
,
// Check for image loads that needs bound checking on the sample
// or level argument since this requires a feature
Expression::ImageLoad {
sample, level, ..
} => {
if policies.image_load != crate::proc::BoundsCheckPolicy::Unchecked {
if sample.is_some() {
features.request(Features::TEXTURE_SAMPLES)
}
if level.is_some() {
features.request(Features::TEXTURE_LEVELS)
}
}
}
Expression::ImageSample { image, level, offset, .. } => {
if let TypeInner::Image {
dim,
arrayed,
class: ImageClass::Depth { .. },
} = *info[image].ty.inner_with(&module.types) {
let lod = matches!(level, SampleLevel::Zero | SampleLevel::Exact(_));
let bias = matches!(level, SampleLevel::Bias(_));
let auto = matches!(level, SampleLevel::Auto);
let cube = dim == ImageDimension::Cube;
let array2d = dim == ImageDimension::D2 && arrayed;
let gles = self.options.version.is_es();
// We have a workaround of using `textureGrad` instead of `textureLod` if the LOD is zero,
// so we don't *need* this extension for those cases.
// But if we're explicitly allowed to use the extension (`WriterFlags::TEXTURE_SHADOW_LOD`),
// we always use it instead of the workaround.
let grad_workaround_applicable = (array2d || (cube && !arrayed)) && level == SampleLevel::Zero;
let prefer_grad_workaround = grad_workaround_applicable && !self.options.writer_flags.contains(WriterFlags::TEXTURE_SHADOW_LOD);
let mut ext_used = false;
// float texture(sampler2DArrayShadow sampler, vec4 P [, float bias])
// float texture(samplerCubeArrayShadow sampler, vec4 P, float compare [, float bias])
ext_used |= (array2d || cube && arrayed) && bias;
// The non `bias` version of this was standardized in GL 4.3, but never in GLES.
// float textureOffset(sampler2DArrayShadow sampler, vec4 P, ivec2 offset [, float bias])
ext_used |= array2d && (bias || (gles && auto)) && offset.is_some();
// float textureLod(sampler2DArrayShadow sampler, vec4 P, float lod)
// float textureLodOffset(sampler2DArrayShadow sampler, vec4 P, float lod, ivec2 offset)
// float textureLod(samplerCubeShadow sampler, vec4 P, float lod)
// float textureLod(samplerCubeArrayShadow sampler, vec4 P, float compare, float lod)
ext_used |= (cube || array2d) && lod && !prefer_grad_workaround;
if ext_used {
features.request(Features::TEXTURE_SHADOW_LOD);
}
}
}
Expression::SubgroupBallotResult |
Expression::SubgroupOperationResult { .. } => {
features.request(Features::SUBGROUP_OPERATIONS)
}
_ => {}
}
}
}
for blocks in module
.functions
.iter()
.map(|(_, f)| &f.body)
.chain(std::iter::once(&entry_point.function.body))
{
for (stmt, _) in blocks.span_iter() {
match *stmt {
crate::Statement::ImageAtomic { .. } => {
features.request(Features::TEXTURE_ATOMICS)
}
_ => {}
}
}
}
self.features.check_availability(self.options.version)
}
/// Helper method that checks the [`Features`] needed by a scalar
fn scalar_required_features(&mut self, scalar: Scalar) {
if scalar.kind == ScalarKind::Float && scalar.width == 8 {
self.features.request(Features::DOUBLE_TYPE);
}
}
fn varying_required_features(&mut self, binding: Option<&Binding>, ty: Handle<Type>) {
if let TypeInner::Struct { ref members, .. } = self.module.types[ty].inner {
for member in members {
self.varying_required_features(member.binding.as_ref(), member.ty);
}
} else if let Some(binding) = binding {
match *binding {
Binding::BuiltIn(built_in) => match built_in {
crate::BuiltIn::ClipDistance => self.features.request(Features::CLIP_DISTANCE),
crate::BuiltIn::CullDistance => self.features.request(Features::CULL_DISTANCE),
crate::BuiltIn::SampleIndex => {
self.features.request(Features::SAMPLE_VARIABLES)
}
crate::BuiltIn::ViewIndex => self.features.request(Features::MULTI_VIEW),
crate::BuiltIn::InstanceIndex | crate::BuiltIn::DrawID => {
self.features.request(Features::INSTANCE_INDEX)
}
_ => {}
},
Binding::Location {
location: _,
interpolation,
sampling,
second_blend_source,
} => {
if interpolation == Some(Interpolation::Linear) {
self.features.request(Features::NOPERSPECTIVE_QUALIFIER);
}
if sampling == Some(Sampling::Sample) {
self.features.request(Features::SAMPLE_QUALIFIER);
}
if second_blend_source {
self.features.request(Features::DUAL_SOURCE_BLENDING);
}
}
}
}
}
}
+492
View File
@@ -0,0 +1,492 @@
pub const RESERVED_KEYWORDS: &[&str] = &[
//
// GLSL 4.6 keywords, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L2004-L2322
// GLSL ES 3.2 keywords, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/es/3.2/GLSL_ES_Specification_3.20.html#L2166-L2478
//
// Note: The GLSL ES 3.2 keywords are the same as GLSL 4.6 keywords with some residing in the reserved section.
// The only exception are the missing Vulkan keywords which I think is an oversight (see https://github.com/KhronosGroup/OpenGL-Registry/issues/585).
//
"const",
"uniform",
"buffer",
"shared",
"attribute",
"varying",
"coherent",
"volatile",
"restrict",
"readonly",
"writeonly",
"atomic_uint",
"layout",
"centroid",
"flat",
"smooth",
"noperspective",
"patch",
"sample",
"invariant",
"precise",
"break",
"continue",
"do",
"for",
"while",
"switch",
"case",
"default",
"if",
"else",
"subroutine",
"in",
"out",
"inout",
"int",
"void",
"bool",
"true",
"false",
"float",
"double",
"discard",
"return",
"vec2",
"vec3",
"vec4",
"ivec2",
"ivec3",
"ivec4",
"bvec2",
"bvec3",
"bvec4",
"uint",
"uvec2",
"uvec3",
"uvec4",
"dvec2",
"dvec3",
"dvec4",
"mat2",
"mat3",
"mat4",
"mat2x2",
"mat2x3",
"mat2x4",
"mat3x2",
"mat3x3",
"mat3x4",
"mat4x2",
"mat4x3",
"mat4x4",
"dmat2",
"dmat3",
"dmat4",
"dmat2x2",
"dmat2x3",
"dmat2x4",
"dmat3x2",
"dmat3x3",
"dmat3x4",
"dmat4x2",
"dmat4x3",
"dmat4x4",
"lowp",
"mediump",
"highp",
"precision",
"sampler1D",
"sampler1DShadow",
"sampler1DArray",
"sampler1DArrayShadow",
"isampler1D",
"isampler1DArray",
"usampler1D",
"usampler1DArray",
"sampler2D",
"sampler2DShadow",
"sampler2DArray",
"sampler2DArrayShadow",
"isampler2D",
"isampler2DArray",
"usampler2D",
"usampler2DArray",
"sampler2DRect",
"sampler2DRectShadow",
"isampler2DRect",
"usampler2DRect",
"sampler2DMS",
"isampler2DMS",
"usampler2DMS",
"sampler2DMSArray",
"isampler2DMSArray",
"usampler2DMSArray",
"sampler3D",
"isampler3D",
"usampler3D",
"samplerCube",
"samplerCubeShadow",
"isamplerCube",
"usamplerCube",
"samplerCubeArray",
"samplerCubeArrayShadow",
"isamplerCubeArray",
"usamplerCubeArray",
"samplerBuffer",
"isamplerBuffer",
"usamplerBuffer",
"image1D",
"iimage1D",
"uimage1D",
"image1DArray",
"iimage1DArray",
"uimage1DArray",
"image2D",
"iimage2D",
"uimage2D",
"image2DArray",
"iimage2DArray",
"uimage2DArray",
"image2DRect",
"iimage2DRect",
"uimage2DRect",
"image2DMS",
"iimage2DMS",
"uimage2DMS",
"image2DMSArray",
"iimage2DMSArray",
"uimage2DMSArray",
"image3D",
"iimage3D",
"uimage3D",
"imageCube",
"iimageCube",
"uimageCube",
"imageCubeArray",
"iimageCubeArray",
"uimageCubeArray",
"imageBuffer",
"iimageBuffer",
"uimageBuffer",
"struct",
// Vulkan keywords
"texture1D",
"texture1DArray",
"itexture1D",
"itexture1DArray",
"utexture1D",
"utexture1DArray",
"texture2D",
"texture2DArray",
"itexture2D",
"itexture2DArray",
"utexture2D",
"utexture2DArray",
"texture2DRect",
"itexture2DRect",
"utexture2DRect",
"texture2DMS",
"itexture2DMS",
"utexture2DMS",
"texture2DMSArray",
"itexture2DMSArray",
"utexture2DMSArray",
"texture3D",
"itexture3D",
"utexture3D",
"textureCube",
"itextureCube",
"utextureCube",
"textureCubeArray",
"itextureCubeArray",
"utextureCubeArray",
"textureBuffer",
"itextureBuffer",
"utextureBuffer",
"sampler",
"samplerShadow",
"subpassInput",
"isubpassInput",
"usubpassInput",
"subpassInputMS",
"isubpassInputMS",
"usubpassInputMS",
// Reserved keywords
"common",
"partition",
"active",
"asm",
"class",
"union",
"enum",
"typedef",
"template",
"this",
"resource",
"goto",
"inline",
"noinline",
"public",
"static",
"extern",
"external",
"interface",
"long",
"short",
"half",
"fixed",
"unsigned",
"superp",
"input",
"output",
"hvec2",
"hvec3",
"hvec4",
"fvec2",
"fvec3",
"fvec4",
"filter",
"sizeof",
"cast",
"namespace",
"using",
"sampler3DRect",
// Reserved keywords that were unreserved in GLSL 4.2
"image1DArrayShadow",
"image1DShadow",
"image2DArrayShadow",
"image2DShadow",
// Reserved keywords that were unreserved in GLSL 4.4
"packed",
"row_major",
//
// GLSL 4.6 Built-In Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13314
//
// Angle and Trigonometry Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13469-L13561C5
"radians",
"degrees",
"sin",
"cos",
"tan",
"asin",
"acos",
"atan",
"sinh",
"cosh",
"tanh",
"asinh",
"acosh",
"atanh",
// Exponential Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13569-L13620
"pow",
"exp",
"log",
"exp2",
"log2",
"sqrt",
"inversesqrt",
// Common Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13628-L13908
"abs",
"sign",
"floor",
"trunc",
"round",
"roundEven",
"ceil",
"fract",
"mod",
"modf",
"min",
"max",
"clamp",
"mix",
"step",
"smoothstep",
"isnan",
"isinf",
"floatBitsToInt",
"floatBitsToUint",
"intBitsToFloat",
"uintBitsToFloat",
"fma",
"frexp",
"ldexp",
// Floating-Point Pack and Unpack Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L13916-L14007
"packUnorm2x16",
"packSnorm2x16",
"packUnorm4x8",
"packSnorm4x8",
"unpackUnorm2x16",
"unpackSnorm2x16",
"unpackUnorm4x8",
"unpackSnorm4x8",
"packHalf2x16",
"unpackHalf2x16",
"packDouble2x32",
"unpackDouble2x32",
// Geometric Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14014-L14121
"length",
"distance",
"dot",
"cross",
"normalize",
"ftransform",
"faceforward",
"reflect",
"refract",
// Matrix Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14151-L14215
"matrixCompMult",
"outerProduct",
"transpose",
"determinant",
"inverse",
// Vector Relational Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14259-L14322
"lessThan",
"lessThanEqual",
"greaterThan",
"greaterThanEqual",
"equal",
"notEqual",
"any",
"all",
"not",
// Integer Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14335-L14432
"uaddCarry",
"usubBorrow",
"umulExtended",
"imulExtended",
"bitfieldExtract",
"bitfieldInsert",
"bitfieldReverse",
"bitCount",
"findLSB",
"findMSB",
// Texture Query Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14645-L14732
"textureSize",
"textureQueryLod",
"textureQueryLevels",
"textureSamples",
// Texel Lookup Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L14736-L14997
"texture",
"textureProj",
"textureLod",
"textureOffset",
"texelFetch",
"texelFetchOffset",
"textureProjOffset",
"textureLodOffset",
"textureProjLod",
"textureProjLodOffset",
"textureGrad",
"textureGradOffset",
"textureProjGrad",
"textureProjGradOffset",
// Texture Gather Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15077-L15154
"textureGather",
"textureGatherOffset",
"textureGatherOffsets",
// Compatibility Profile Texture Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15161-L15220
"texture1D",
"texture1DProj",
"texture1DLod",
"texture1DProjLod",
"texture2D",
"texture2DProj",
"texture2DLod",
"texture2DProjLod",
"texture3D",
"texture3DProj",
"texture3DLod",
"texture3DProjLod",
"textureCube",
"textureCubeLod",
"shadow1D",
"shadow2D",
"shadow1DProj",
"shadow2DProj",
"shadow1DLod",
"shadow2DLod",
"shadow1DProjLod",
"shadow2DProjLod",
// Atomic Counter Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15241-L15531
"atomicCounterIncrement",
"atomicCounterDecrement",
"atomicCounter",
"atomicCounterAdd",
"atomicCounterSubtract",
"atomicCounterMin",
"atomicCounterMax",
"atomicCounterAnd",
"atomicCounterOr",
"atomicCounterXor",
"atomicCounterExchange",
"atomicCounterCompSwap",
// Atomic Memory Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15563-L15624
"atomicAdd",
"atomicMin",
"atomicMax",
"atomicAnd",
"atomicOr",
"atomicXor",
"atomicExchange",
"atomicCompSwap",
// Image Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15763-L15878
"imageSize",
"imageSamples",
"imageLoad",
"imageStore",
"imageAtomicAdd",
"imageAtomicMin",
"imageAtomicMax",
"imageAtomicAnd",
"imageAtomicOr",
"imageAtomicXor",
"imageAtomicExchange",
"imageAtomicCompSwap",
// Geometry Shader Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L15886-L15932
"EmitStreamVertex",
"EndStreamPrimitive",
"EmitVertex",
"EndPrimitive",
// Fragment Processing Functions, Derivative Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16041-L16114
"dFdx",
"dFdy",
"dFdxFine",
"dFdyFine",
"dFdxCoarse",
"dFdyCoarse",
"fwidth",
"fwidthFine",
"fwidthCoarse",
// Fragment Processing Functions, Interpolation Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16150-L16198
"interpolateAtCentroid",
"interpolateAtSample",
"interpolateAtOffset",
// Noise Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16214-L16243
"noise1",
"noise2",
"noise3",
"noise4",
// Shader Invocation Control Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16255-L16276
"barrier",
// Shader Memory Control Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16336-L16382
"memoryBarrier",
"memoryBarrierAtomicCounter",
"memoryBarrierBuffer",
"memoryBarrierShared",
"memoryBarrierImage",
"groupMemoryBarrier",
// Subpass-Input Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16451-L16470
"subpassLoad",
// Shader Invocation Group Functions, from https://github.com/KhronosGroup/OpenGL-Registry/blob/d00e11dc1a1ffba581d633f21f70202051248d5c/specs/gl/GLSLangSpec.4.60.html#L16483-L16511
"anyInvocation",
"allInvocations",
"allInvocationsEqual",
//
// entry point name (should not be shadowed)
//
"main",
// Naga utilities:
super::MODF_FUNCTION,
super::FREXP_FUNCTION,
super::FIRST_INSTANCE_BINDING,
];
+4983
View File
File diff suppressed because it is too large Load Diff
+228
View File
@@ -0,0 +1,228 @@
use std::borrow::Cow;
use crate::proc::Alignment;
use super::Error;
impl crate::ScalarKind {
pub(super) fn to_hlsl_cast(self) -> &'static str {
match self {
Self::Float => "asfloat",
Self::Sint => "asint",
Self::Uint => "asuint",
Self::Bool | Self::AbstractInt | Self::AbstractFloat => unreachable!(),
}
}
}
impl crate::Scalar {
/// Helper function that returns scalar related strings
///
/// <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-scalar>
pub(super) const fn to_hlsl_str(self) -> Result<&'static str, Error> {
match self.kind {
crate::ScalarKind::Sint => match self.width {
4 => Ok("int"),
8 => Ok("int64_t"),
_ => Err(Error::UnsupportedScalar(self)),
},
crate::ScalarKind::Uint => match self.width {
4 => Ok("uint"),
8 => Ok("uint64_t"),
_ => Err(Error::UnsupportedScalar(self)),
},
crate::ScalarKind::Float => match self.width {
2 => Ok("half"),
4 => Ok("float"),
8 => Ok("double"),
_ => Err(Error::UnsupportedScalar(self)),
},
crate::ScalarKind::Bool => Ok("bool"),
crate::ScalarKind::AbstractInt | crate::ScalarKind::AbstractFloat => {
Err(Error::UnsupportedScalar(self))
}
}
}
}
impl crate::TypeInner {
pub(super) const fn is_matrix(&self) -> bool {
match *self {
Self::Matrix { .. } => true,
_ => false,
}
}
pub(super) fn size_hlsl(&self, gctx: crate::proc::GlobalCtx) -> u32 {
match *self {
Self::Matrix {
columns,
rows,
scalar,
} => {
let stride = Alignment::from(rows) * scalar.width as u32;
let last_row_size = rows as u32 * scalar.width as u32;
((columns as u32 - 1) * stride) + last_row_size
}
Self::Array { base, size, stride } => {
let count = match size {
crate::ArraySize::Constant(size) => size.get(),
// A dynamically-sized array has to have at least one element
crate::ArraySize::Pending(_) => unreachable!(),
crate::ArraySize::Dynamic => 1,
};
let last_el_size = gctx.types[base].inner.size_hlsl(gctx);
((count - 1) * stride) + last_el_size
}
_ => self.size(gctx),
}
}
/// Used to generate the name of the wrapped type constructor
pub(super) fn hlsl_type_id<'a>(
base: crate::Handle<crate::Type>,
gctx: crate::proc::GlobalCtx,
names: &'a crate::FastHashMap<crate::proc::NameKey, String>,
) -> Result<Cow<'a, str>, Error> {
Ok(match gctx.types[base].inner {
crate::TypeInner::Scalar(scalar) => Cow::Borrowed(scalar.to_hlsl_str()?),
crate::TypeInner::Vector { size, scalar } => Cow::Owned(format!(
"{}{}",
scalar.to_hlsl_str()?,
crate::back::vector_size_str(size)
)),
crate::TypeInner::Matrix {
columns,
rows,
scalar,
} => Cow::Owned(format!(
"{}{}x{}",
scalar.to_hlsl_str()?,
crate::back::vector_size_str(columns),
crate::back::vector_size_str(rows),
)),
crate::TypeInner::Array {
base,
size: crate::ArraySize::Constant(size),
..
} => Cow::Owned(format!(
"array{size}_{}_",
Self::hlsl_type_id(base, gctx, names)?
)),
crate::TypeInner::Struct { .. } => {
Cow::Borrowed(&names[&crate::proc::NameKey::Type(base)])
}
_ => unreachable!(),
})
}
}
impl crate::StorageFormat {
pub(super) const fn to_hlsl_str(self) -> &'static str {
match self {
Self::R16Float | Self::R32Float => "float",
Self::R8Unorm | Self::R16Unorm => "unorm float",
Self::R8Snorm | Self::R16Snorm => "snorm float",
Self::R8Uint | Self::R16Uint | Self::R32Uint => "uint",
Self::R8Sint | Self::R16Sint | Self::R32Sint => "int",
Self::R64Uint => "uint64_t",
Self::Rg16Float | Self::Rg32Float => "float2",
Self::Rg8Unorm | Self::Rg16Unorm => "unorm float2",
Self::Rg8Snorm | Self::Rg16Snorm => "snorm float2",
Self::Rg8Sint | Self::Rg16Sint | Self::Rg32Uint => "int2",
Self::Rg8Uint | Self::Rg16Uint | Self::Rg32Sint => "uint2",
Self::Rg11b10Ufloat => "float3",
Self::Rgba16Float | Self::Rgba32Float => "float4",
Self::Rgba8Unorm | Self::Bgra8Unorm | Self::Rgba16Unorm | Self::Rgb10a2Unorm => {
"unorm float4"
}
Self::Rgba8Snorm | Self::Rgba16Snorm => "snorm float4",
Self::Rgba8Uint | Self::Rgba16Uint | Self::Rgba32Uint | Self::Rgb10a2Uint => "uint4",
Self::Rgba8Sint | Self::Rgba16Sint | Self::Rgba32Sint => "int4",
}
}
}
impl crate::BuiltIn {
pub(super) fn to_hlsl_str(self) -> Result<&'static str, Error> {
Ok(match self {
Self::Position { .. } => "SV_Position",
// vertex
Self::ClipDistance => "SV_ClipDistance",
Self::CullDistance => "SV_CullDistance",
Self::InstanceIndex => "SV_InstanceID",
Self::VertexIndex => "SV_VertexID",
// fragment
Self::FragDepth => "SV_Depth",
Self::FrontFacing => "SV_IsFrontFace",
Self::PrimitiveIndex => "SV_PrimitiveID",
Self::SampleIndex => "SV_SampleIndex",
Self::SampleMask => "SV_Coverage",
// compute
Self::GlobalInvocationId => "SV_DispatchThreadID",
Self::LocalInvocationId => "SV_GroupThreadID",
Self::LocalInvocationIndex => "SV_GroupIndex",
Self::WorkGroupId => "SV_GroupID",
// The specific semantic we use here doesn't matter, because references
// to this field will get replaced with references to `SPECIAL_CBUF_VAR`
// in `Writer::write_expr`.
Self::NumWorkGroups => "SV_GroupID",
// These builtins map to functions
Self::SubgroupSize
| Self::SubgroupInvocationId
| Self::NumSubgroups
| Self::SubgroupId => unreachable!(),
Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => {
return Err(Error::Unimplemented(format!("builtin {self:?}")))
}
Self::PointSize | Self::ViewIndex | Self::PointCoord | Self::DrawID => {
return Err(Error::Custom(format!("Unsupported builtin {self:?}")))
}
})
}
}
impl crate::Interpolation {
/// Return the string corresponding to the HLSL interpolation qualifier.
pub(super) const fn to_hlsl_str(self) -> Option<&'static str> {
match self {
// Would be "linear", but it's the default interpolation in SM4 and up
// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-struct#interpolation-modifiers-introduced-in-shader-model-4
Self::Perspective => None,
Self::Linear => Some("noperspective"),
Self::Flat => Some("nointerpolation"),
}
}
}
impl crate::Sampling {
/// Return the HLSL auxiliary qualifier for the given sampling value.
pub(super) const fn to_hlsl_str(self) -> Option<&'static str> {
match self {
Self::Center | Self::First | Self::Either => None,
Self::Centroid => Some("centroid"),
Self::Sample => Some("sample"),
}
}
}
impl crate::AtomicFunction {
/// Return the HLSL suffix for the `InterlockedXxx` method.
pub(super) const fn to_hlsl_suffix(self) -> &'static str {
match self {
Self::Add | Self::Subtract => "Add",
Self::And => "And",
Self::InclusiveOr => "Or",
Self::ExclusiveOr => "Xor",
Self::Min => "Min",
Self::Max => "Max",
Self::Exchange { compare: None } => "Exchange",
Self::Exchange { .. } => "", //TODO
}
}
}
+1399
View File
File diff suppressed because it is too large Load Diff
+907
View File
@@ -0,0 +1,907 @@
// When compiling with FXC without strict mode, these keywords are actually case insensitive.
// If you compile with strict mode and specify a different casing like "Pass" instead in an identifier, FXC will give this error:
// "error X3086: alternate cases for 'pass' are deprecated in strict mode"
// This behavior is not documented anywhere, but as far as I can tell this is the full list.
pub const RESERVED_CASE_INSENSITIVE: &[&str] = &[
"asm",
"decl",
"pass",
"technique",
"Texture1D",
"Texture2D",
"Texture3D",
"TextureCube",
];
pub const RESERVED: &[&str] = &[
// FXC keywords, from https://github.com/MicrosoftDocs/win32/blob/c885cb0c63b0e9be80c6a0e6512473ac6f4e771e/desktop-src/direct3dhlsl/dx-graphics-hlsl-appendix-keywords.md?plain=1#L99-L118
"AppendStructuredBuffer",
"asm",
"asm_fragment",
"BlendState",
"bool",
"break",
"Buffer",
"ByteAddressBuffer",
"case",
"cbuffer",
"centroid",
"class",
"column_major",
"compile",
"compile_fragment",
"CompileShader",
"const",
"continue",
"ComputeShader",
"ConsumeStructuredBuffer",
"default",
"DepthStencilState",
"DepthStencilView",
"discard",
"do",
"double",
"DomainShader",
"dword",
"else",
"export",
"extern",
"false",
"float",
"for",
"fxgroup",
"GeometryShader",
"groupshared",
"half",
"Hullshader",
"if",
"in",
"inline",
"inout",
"InputPatch",
"int",
"interface",
"line",
"lineadj",
"linear",
"LineStream",
"matrix",
"min16float",
"min10float",
"min16int",
"min12int",
"min16uint",
"namespace",
"nointerpolation",
"noperspective",
"NULL",
"out",
"OutputPatch",
"packoffset",
"pass",
"pixelfragment",
"PixelShader",
"point",
"PointStream",
"precise",
"RasterizerState",
"RenderTargetView",
"return",
"register",
"row_major",
"RWBuffer",
"RWByteAddressBuffer",
"RWStructuredBuffer",
"RWTexture1D",
"RWTexture1DArray",
"RWTexture2D",
"RWTexture2DArray",
"RWTexture3D",
"sample",
"sampler",
"SamplerState",
"SamplerComparisonState",
"shared",
"snorm",
"stateblock",
"stateblock_state",
"static",
"string",
"struct",
"switch",
"StructuredBuffer",
"tbuffer",
"technique",
"technique10",
"technique11",
"texture",
"Texture1D",
"Texture1DArray",
"Texture2D",
"Texture2DArray",
"Texture2DMS",
"Texture2DMSArray",
"Texture3D",
"TextureCube",
"TextureCubeArray",
"true",
"typedef",
"triangle",
"triangleadj",
"TriangleStream",
"uint",
"uniform",
"unorm",
"unsigned",
"vector",
"vertexfragment",
"VertexShader",
"void",
"volatile",
"while",
// FXC reserved keywords, from https://github.com/MicrosoftDocs/win32/blob/c885cb0c63b0e9be80c6a0e6512473ac6f4e771e/desktop-src/direct3dhlsl/dx-graphics-hlsl-appendix-reserved-words.md?plain=1#L19-L38
"auto",
"case",
"catch",
"char",
"class",
"const_cast",
"default",
"delete",
"dynamic_cast",
"enum",
"explicit",
"friend",
"goto",
"long",
"mutable",
"new",
"operator",
"private",
"protected",
"public",
"reinterpret_cast",
"short",
"signed",
"sizeof",
"static_cast",
"template",
"this",
"throw",
"try",
"typename",
"union",
"unsigned",
"using",
"virtual",
// FXC intrinsics, from https://github.com/MicrosoftDocs/win32/blob/1682b99e203708f6f5eda972d966e30f3c1588de/desktop-src/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions.md?plain=1#L26-L165
"abort",
"abs",
"acos",
"all",
"AllMemoryBarrier",
"AllMemoryBarrierWithGroupSync",
"any",
"asdouble",
"asfloat",
"asin",
"asint",
"asuint",
"atan",
"atan2",
"ceil",
"CheckAccessFullyMapped",
"clamp",
"clip",
"cos",
"cosh",
"countbits",
"cross",
"D3DCOLORtoUBYTE4",
"ddx",
"ddx_coarse",
"ddx_fine",
"ddy",
"ddy_coarse",
"ddy_fine",
"degrees",
"determinant",
"DeviceMemoryBarrier",
"DeviceMemoryBarrierWithGroupSync",
"distance",
"dot",
"dst",
"errorf",
"EvaluateAttributeCentroid",
"EvaluateAttributeAtSample",
"EvaluateAttributeSnapped",
"exp",
"exp2",
"f16tof32",
"f32tof16",
"faceforward",
"firstbithigh",
"firstbitlow",
"floor",
"fma",
"fmod",
"frac",
"frexp",
"fwidth",
"GetRenderTargetSampleCount",
"GetRenderTargetSamplePosition",
"GroupMemoryBarrier",
"GroupMemoryBarrierWithGroupSync",
"InterlockedAdd",
"InterlockedAnd",
"InterlockedCompareExchange",
"InterlockedCompareStore",
"InterlockedExchange",
"InterlockedMax",
"InterlockedMin",
"InterlockedOr",
"InterlockedXor",
"isfinite",
"isinf",
"isnan",
"ldexp",
"length",
"lerp",
"lit",
"log",
"log10",
"log2",
"mad",
"max",
"min",
"modf",
"msad4",
"mul",
"noise",
"normalize",
"pow",
"printf",
"Process2DQuadTessFactorsAvg",
"Process2DQuadTessFactorsMax",
"Process2DQuadTessFactorsMin",
"ProcessIsolineTessFactors",
"ProcessQuadTessFactorsAvg",
"ProcessQuadTessFactorsMax",
"ProcessQuadTessFactorsMin",
"ProcessTriTessFactorsAvg",
"ProcessTriTessFactorsMax",
"ProcessTriTessFactorsMin",
"radians",
"rcp",
"reflect",
"refract",
"reversebits",
"round",
"rsqrt",
"saturate",
"sign",
"sin",
"sincos",
"sinh",
"smoothstep",
"sqrt",
"step",
"tan",
"tanh",
"tex1D",
"tex1Dbias",
"tex1Dgrad",
"tex1Dlod",
"tex1Dproj",
"tex2D",
"tex2Dbias",
"tex2Dgrad",
"tex2Dlod",
"tex2Dproj",
"tex3D",
"tex3Dbias",
"tex3Dgrad",
"tex3Dlod",
"tex3Dproj",
"texCUBE",
"texCUBEbias",
"texCUBEgrad",
"texCUBElod",
"texCUBEproj",
"transpose",
"trunc",
// DXC (reserved) keywords, from https://github.com/microsoft/DirectXShaderCompiler/blob/d5d478470d3020a438d3cb810b8d3fe0992e6709/tools/clang/include/clang/Basic/TokenKinds.def#L222-L648
// with the KEYALL, KEYCXX, BOOLSUPPORT, WCHARSUPPORT, KEYHLSL options enabled (see https://github.com/microsoft/DirectXShaderCompiler/blob/d5d478470d3020a438d3cb810b8d3fe0992e6709/tools/clang/lib/Frontend/CompilerInvocation.cpp#L1199)
"auto",
"break",
"case",
"char",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extern",
"float",
"for",
"goto",
"if",
"inline",
"int",
"long",
"register",
"return",
"short",
"signed",
"sizeof",
"static",
"struct",
"switch",
"typedef",
"union",
"unsigned",
"void",
"volatile",
"while",
"_Alignas",
"_Alignof",
"_Atomic",
"_Complex",
"_Generic",
"_Imaginary",
"_Noreturn",
"_Static_assert",
"_Thread_local",
"__func__",
"__objc_yes",
"__objc_no",
"asm",
"bool",
"catch",
"class",
"const_cast",
"delete",
"dynamic_cast",
"explicit",
"export",
"false",
"friend",
"mutable",
"namespace",
"new",
"operator",
"private",
"protected",
"public",
"reinterpret_cast",
"static_cast",
"template",
"this",
"throw",
"true",
"try",
"typename",
"typeid",
"using",
"virtual",
"wchar_t",
"_Decimal32",
"_Decimal64",
"_Decimal128",
"__null",
"__alignof",
"__attribute",
"__builtin_choose_expr",
"__builtin_offsetof",
"__builtin_va_arg",
"__extension__",
"__imag",
"__int128",
"__label__",
"__real",
"__thread",
"__FUNCTION__",
"__PRETTY_FUNCTION__",
"__is_nothrow_assignable",
"__is_constructible",
"__is_nothrow_constructible",
"__has_nothrow_assign",
"__has_nothrow_move_assign",
"__has_nothrow_copy",
"__has_nothrow_constructor",
"__has_trivial_assign",
"__has_trivial_move_assign",
"__has_trivial_copy",
"__has_trivial_constructor",
"__has_trivial_move_constructor",
"__has_trivial_destructor",
"__has_virtual_destructor",
"__is_abstract",
"__is_base_of",
"__is_class",
"__is_convertible_to",
"__is_empty",
"__is_enum",
"__is_final",
"__is_literal",
"__is_literal_type",
"__is_pod",
"__is_polymorphic",
"__is_trivial",
"__is_union",
"__is_trivially_constructible",
"__is_trivially_copyable",
"__is_trivially_assignable",
"__underlying_type",
"__is_lvalue_expr",
"__is_rvalue_expr",
"__is_arithmetic",
"__is_floating_point",
"__is_integral",
"__is_complete_type",
"__is_void",
"__is_array",
"__is_function",
"__is_reference",
"__is_lvalue_reference",
"__is_rvalue_reference",
"__is_fundamental",
"__is_object",
"__is_scalar",
"__is_compound",
"__is_pointer",
"__is_member_object_pointer",
"__is_member_function_pointer",
"__is_member_pointer",
"__is_const",
"__is_volatile",
"__is_standard_layout",
"__is_signed",
"__is_unsigned",
"__is_same",
"__is_convertible",
"__array_rank",
"__array_extent",
"__private_extern__",
"__module_private__",
"__declspec",
"__cdecl",
"__stdcall",
"__fastcall",
"__thiscall",
"__vectorcall",
"cbuffer",
"tbuffer",
"packoffset",
"linear",
"centroid",
"nointerpolation",
"noperspective",
"sample",
"column_major",
"row_major",
"in",
"out",
"inout",
"uniform",
"precise",
"center",
"shared",
"groupshared",
"discard",
"snorm",
"unorm",
"point",
"line",
"lineadj",
"triangle",
"triangleadj",
"globallycoherent",
"interface",
"sampler_state",
"technique",
"indices",
"vertices",
"primitives",
"payload",
"Technique",
"technique10",
"technique11",
"__builtin_omp_required_simd_align",
"__pascal",
"__fp16",
"__alignof__",
"__asm",
"__asm__",
"__attribute__",
"__complex",
"__complex__",
"__const",
"__const__",
"__decltype",
"__imag__",
"__inline",
"__inline__",
"__nullptr",
"__real__",
"__restrict",
"__restrict__",
"__signed",
"__signed__",
"__typeof",
"__typeof__",
"__volatile",
"__volatile__",
"_Nonnull",
"_Nullable",
"_Null_unspecified",
"__builtin_convertvector",
"__char16_t",
"__char32_t",
// DXC intrinsics, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/utils/hct/gen_intrin_main.txt#L86-L376
"D3DCOLORtoUBYTE4",
"GetRenderTargetSampleCount",
"GetRenderTargetSamplePosition",
"abort",
"abs",
"acos",
"all",
"AllMemoryBarrier",
"AllMemoryBarrierWithGroupSync",
"any",
"asdouble",
"asfloat",
"asfloat16",
"asint16",
"asin",
"asint",
"asuint",
"asuint16",
"atan",
"atan2",
"ceil",
"clamp",
"clip",
"cos",
"cosh",
"countbits",
"cross",
"ddx",
"ddx_coarse",
"ddx_fine",
"ddy",
"ddy_coarse",
"ddy_fine",
"degrees",
"determinant",
"DeviceMemoryBarrier",
"DeviceMemoryBarrierWithGroupSync",
"distance",
"dot",
"dst",
"EvaluateAttributeAtSample",
"EvaluateAttributeCentroid",
"EvaluateAttributeSnapped",
"GetAttributeAtVertex",
"exp",
"exp2",
"f16tof32",
"f32tof16",
"faceforward",
"firstbithigh",
"firstbitlow",
"floor",
"fma",
"fmod",
"frac",
"frexp",
"fwidth",
"GroupMemoryBarrier",
"GroupMemoryBarrierWithGroupSync",
"InterlockedAdd",
"InterlockedMin",
"InterlockedMax",
"InterlockedAnd",
"InterlockedOr",
"InterlockedXor",
"InterlockedCompareStore",
"InterlockedExchange",
"InterlockedCompareExchange",
"InterlockedCompareStoreFloatBitwise",
"InterlockedCompareExchangeFloatBitwise",
"isfinite",
"isinf",
"isnan",
"ldexp",
"length",
"lerp",
"lit",
"log",
"log10",
"log2",
"mad",
"max",
"min",
"modf",
"msad4",
"mul",
"normalize",
"pow",
"printf",
"Process2DQuadTessFactorsAvg",
"Process2DQuadTessFactorsMax",
"Process2DQuadTessFactorsMin",
"ProcessIsolineTessFactors",
"ProcessQuadTessFactorsAvg",
"ProcessQuadTessFactorsMax",
"ProcessQuadTessFactorsMin",
"ProcessTriTessFactorsAvg",
"ProcessTriTessFactorsMax",
"ProcessTriTessFactorsMin",
"radians",
"rcp",
"reflect",
"refract",
"reversebits",
"round",
"rsqrt",
"saturate",
"sign",
"sin",
"sincos",
"sinh",
"smoothstep",
"source_mark",
"sqrt",
"step",
"tan",
"tanh",
"tex1D",
"tex1Dbias",
"tex1Dgrad",
"tex1Dlod",
"tex1Dproj",
"tex2D",
"tex2Dbias",
"tex2Dgrad",
"tex2Dlod",
"tex2Dproj",
"tex3D",
"tex3Dbias",
"tex3Dgrad",
"tex3Dlod",
"tex3Dproj",
"texCUBE",
"texCUBEbias",
"texCUBEgrad",
"texCUBElod",
"texCUBEproj",
"transpose",
"trunc",
"CheckAccessFullyMapped",
"AddUint64",
"NonUniformResourceIndex",
"WaveIsFirstLane",
"WaveGetLaneIndex",
"WaveGetLaneCount",
"WaveActiveAnyTrue",
"WaveActiveAllTrue",
"WaveActiveAllEqual",
"WaveActiveBallot",
"WaveReadLaneAt",
"WaveReadLaneFirst",
"WaveActiveCountBits",
"WaveActiveSum",
"WaveActiveProduct",
"WaveActiveBitAnd",
"WaveActiveBitOr",
"WaveActiveBitXor",
"WaveActiveMin",
"WaveActiveMax",
"WavePrefixCountBits",
"WavePrefixSum",
"WavePrefixProduct",
"WaveMatch",
"WaveMultiPrefixBitAnd",
"WaveMultiPrefixBitOr",
"WaveMultiPrefixBitXor",
"WaveMultiPrefixCountBits",
"WaveMultiPrefixProduct",
"WaveMultiPrefixSum",
"QuadReadLaneAt",
"QuadReadAcrossX",
"QuadReadAcrossY",
"QuadReadAcrossDiagonal",
"QuadAny",
"QuadAll",
"TraceRay",
"ReportHit",
"CallShader",
"IgnoreHit",
"AcceptHitAndEndSearch",
"DispatchRaysIndex",
"DispatchRaysDimensions",
"WorldRayOrigin",
"WorldRayDirection",
"ObjectRayOrigin",
"ObjectRayDirection",
"RayTMin",
"RayTCurrent",
"PrimitiveIndex",
"InstanceID",
"InstanceIndex",
"GeometryIndex",
"HitKind",
"RayFlags",
"ObjectToWorld",
"WorldToObject",
"ObjectToWorld3x4",
"WorldToObject3x4",
"ObjectToWorld4x3",
"WorldToObject4x3",
"dot4add_u8packed",
"dot4add_i8packed",
"dot2add",
"unpack_s8s16",
"unpack_u8u16",
"unpack_s8s32",
"unpack_u8u32",
"pack_s8",
"pack_u8",
"pack_clamp_s8",
"pack_clamp_u8",
"SetMeshOutputCounts",
"DispatchMesh",
"IsHelperLane",
"AllocateRayQuery",
"CreateResourceFromHeap",
"and",
"or",
"select",
// DXC resource and other types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/HlslTypes.cpp#L441-#L572
"InputPatch",
"OutputPatch",
"PointStream",
"LineStream",
"TriangleStream",
"Texture1D",
"RWTexture1D",
"Texture2D",
"RWTexture2D",
"Texture2DMS",
"RWTexture2DMS",
"Texture3D",
"RWTexture3D",
"TextureCube",
"RWTextureCube",
"Texture1DArray",
"RWTexture1DArray",
"Texture2DArray",
"RWTexture2DArray",
"Texture2DMSArray",
"RWTexture2DMSArray",
"TextureCubeArray",
"RWTextureCubeArray",
"FeedbackTexture2D",
"FeedbackTexture2DArray",
"RasterizerOrderedTexture1D",
"RasterizerOrderedTexture2D",
"RasterizerOrderedTexture3D",
"RasterizerOrderedTexture1DArray",
"RasterizerOrderedTexture2DArray",
"RasterizerOrderedBuffer",
"RasterizerOrderedByteAddressBuffer",
"RasterizerOrderedStructuredBuffer",
"ByteAddressBuffer",
"RWByteAddressBuffer",
"StructuredBuffer",
"RWStructuredBuffer",
"AppendStructuredBuffer",
"ConsumeStructuredBuffer",
"Buffer",
"RWBuffer",
"SamplerState",
"SamplerComparisonState",
"ConstantBuffer",
"TextureBuffer",
"RaytracingAccelerationStructure",
// DXC templated types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp
// look for `BuiltinTypeDeclBuilder`
"matrix",
"vector",
"TextureBuffer",
"ConstantBuffer",
"RayQuery",
"RayDesc",
// Naga utilities
super::writer::MODF_FUNCTION,
super::writer::FREXP_FUNCTION,
super::writer::EXTRACT_BITS_FUNCTION,
super::writer::INSERT_BITS_FUNCTION,
];
// DXC scalar types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp#L48-L254
// + vector and matrix shorthands
pub const TYPES: &[&str] = &{
const L: usize = 23 * (1 + 4 + 4 * 4);
let mut res = [""; L];
let mut c = 0;
/// For each scalar type, it will additionally generate vector and matrix shorthands
macro_rules! generate {
([$($roots:literal),*], $x:tt) => {
$(
generate!(@inner push $roots);
generate!(@inner $roots, $x);
)*
};
(@inner $root:literal, [$($x:literal),*]) => {
generate!(@inner vector $root, $($x)*);
generate!(@inner matrix $root, $($x)*);
};
(@inner vector $root:literal, $($x:literal)*) => {
$(
generate!(@inner push concat!($root, $x));
)*
};
(@inner matrix $root:literal, $($x:literal)*) => {
// Duplicate the list
generate!(@inner matrix $root, $($x)*; $($x)*);
};
// The head/tail recursion: pick the first element of the first list and recursively do it for the tail.
(@inner matrix $root:literal, $head:literal $($tail:literal)*; $($x:literal)*) => {
$(
generate!(@inner push concat!($root, $head, "x", $x));
)*
generate!(@inner matrix $root, $($tail)*; $($x)*);
};
// The end of iteration: we exhausted the list
(@inner matrix $root:literal, ; $($x:literal)*) => {};
(@inner push $v:expr) => {
res[c] = $v;
c += 1;
};
}
generate!(
[
"bool",
"int",
"uint",
"dword",
"half",
"float",
"double",
"min10float",
"min16float",
"min12int",
"min16int",
"min16uint",
"int16_t",
"int32_t",
"int64_t",
"uint16_t",
"uint32_t",
"uint64_t",
"float16_t",
"float32_t",
"float64_t",
"int8_t4_packed",
"uint8_t4_packed"
],
["1", "2", "3", "4"]
);
debug_assert!(c == L);
res
};
+358
View File
@@ -0,0 +1,358 @@
/*!
Backend for [HLSL][hlsl] (High-Level Shading Language).
# Supported shader model versions:
- 5.0
- 5.1
- 6.0
# Layout of values in `uniform` buffers
WGSL's ["Internal Layout of Values"][ilov] rules specify how each WGSL
type should be stored in `uniform` and `storage` buffers. The HLSL we
generate must access values in that form, even when it is not what
HLSL would use normally.
The rules described here only apply to WGSL `uniform` variables. WGSL
`storage` buffers are translated as HLSL `ByteAddressBuffers`, for
which we generate `Load` and `Store` method calls with explicit byte
offsets. WGSL pipeline inputs must be scalars or vectors; they cannot
be matrices, which is where the interesting problems arise.
## Row- and column-major ordering for matrices
WGSL specifies that matrices in uniform buffers are stored in
column-major order. This matches HLSL's default, so one might expect
things to be straightforward. Unfortunately, WGSL and HLSL disagree on
what indexing a matrix means: in WGSL, `m[i]` retrieves the `i`'th
*column* of `m`, whereas in HLSL it retrieves the `i`'th *row*. We
want to avoid translating `m[i]` into some complicated reassembly of a
vector from individually fetched components, so this is a problem.
However, with a bit of trickery, it is possible to use HLSL's `m[i]`
as the translation of WGSL's `m[i]`:
- We declare all matrices in uniform buffers in HLSL with the
`row_major` qualifier, and transpose the row and column counts: a
WGSL `mat3x4<f32>`, say, becomes an HLSL `row_major float3x4`. (Note
that WGSL and HLSL type names put the row and column in reverse
order.) Since the HLSL type is the transpose of how WebGPU directs
the user to store the data, HLSL will load all matrices transposed.
- Since matrices are transposed, an HLSL indexing expression retrieves
the "columns" of the intended WGSL value, as desired.
- For vector-matrix multiplication, since `mul(transpose(m), v)` is
equivalent to `mul(v, m)` (note the reversal of the arguments), and
`mul(v, transpose(m))` is equivalent to `mul(m, v)`, we can
translate WGSL `m * v` and `v * m` to HLSL by simply reversing the
arguments to `mul`.
## Padding in two-row matrices
An HLSL `row_major floatKx2` matrix has padding between its rows that
the WGSL `matKx2<f32>` matrix it represents does not. HLSL stores all
matrix rows [aligned on 16-byte boundaries][16bb], whereas WGSL says
that the columns of a `matKx2<f32>` need only be [aligned as required
for `vec2<f32>`][ilov], which is [eight-byte alignment][8bb].
To compensate for this, any time a `matKx2<f32>` appears in a WGSL
`uniform` variable, whether directly as the variable's type or as part
of a struct/array, we actually emit `K` separate `float2` members, and
assemble/disassemble the matrix from its columns (in WGSL; rows in
HLSL) upon load and store.
For example, the following WGSL struct type:
```ignore
struct Baz {
m: mat3x2<f32>,
}
```
is rendered as the HLSL struct type:
```ignore
struct Baz {
float2 m_0; float2 m_1; float2 m_2;
};
```
The `wrapped_struct_matrix` functions in `help.rs` generate HLSL
helper functions to access such members, converting between the stored
form and the HLSL matrix types appropriately. For example, for reading
the member `m` of the `Baz` struct above, we emit:
```ignore
float3x2 GetMatmOnBaz(Baz obj) {
return float3x2(obj.m_0, obj.m_1, obj.m_2);
}
```
We also emit an analogous `Set` function, as well as functions for
accessing individual columns by dynamic index.
[hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl
[ilov]: https://gpuweb.github.io/gpuweb/wgsl/#internal-value-layout
[16bb]: https://github.com/microsoft/DirectXShaderCompiler/wiki/Buffer-Packing#constant-buffer-packing
[8bb]: https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
*/
mod conv;
mod help;
mod keywords;
mod ray;
mod storage;
mod writer;
use std::fmt::Error as FmtError;
use thiserror::Error;
use crate::{back, proc};
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct BindTarget {
pub space: u8,
pub register: u32,
/// If the binding is an unsized binding array, this overrides the size.
pub binding_array_size: Option<u32>,
}
// Using `BTreeMap` instead of `HashMap` so that we can hash itself.
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, BindTarget>;
/// A HLSL shader model version.
#[allow(non_snake_case, non_camel_case_types)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum ShaderModel {
V5_0,
V5_1,
V6_0,
V6_1,
V6_2,
V6_3,
V6_4,
V6_5,
V6_6,
V6_7,
}
impl ShaderModel {
pub const fn to_str(self) -> &'static str {
match self {
Self::V5_0 => "5_0",
Self::V5_1 => "5_1",
Self::V6_0 => "6_0",
Self::V6_1 => "6_1",
Self::V6_2 => "6_2",
Self::V6_3 => "6_3",
Self::V6_4 => "6_4",
Self::V6_5 => "6_5",
Self::V6_6 => "6_6",
Self::V6_7 => "6_7",
}
}
}
impl crate::ShaderStage {
pub const fn to_hlsl_str(self) -> &'static str {
match self {
Self::Vertex => "vs",
Self::Fragment => "ps",
Self::Compute => "cs",
}
}
}
impl crate::ImageDimension {
const fn to_hlsl_str(self) -> &'static str {
match self {
Self::D1 => "1D",
Self::D2 => "2D",
Self::D3 => "3D",
Self::Cube => "Cube",
}
}
}
/// Shorthand result used internally by the backend
type BackendResult = Result<(), Error>;
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum EntryPointError {
#[error("mapping of {0:?} is missing")]
MissingBinding(crate::ResourceBinding),
}
/// Configuration used in the [`Writer`].
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(feature = "deserialize", serde(default))]
pub struct Options {
/// The hlsl shader model to be used
pub shader_model: ShaderModel,
/// Map of resources association to binding locations.
pub binding_map: BindingMap,
/// Don't panic on missing bindings, instead generate any HLSL.
pub fake_missing_bindings: bool,
/// Add special constants to `SV_VertexIndex` and `SV_InstanceIndex`,
/// to make them work like in Vulkan/Metal, with help of the host.
pub special_constants_binding: Option<BindTarget>,
/// Bind target of the push constant buffer
pub push_constants_target: Option<BindTarget>,
/// Should workgroup variables be zero initialized (by polyfilling)?
pub zero_initialize_workgroup_memory: bool,
/// Should we restrict indexing of vectors, matrices and arrays?
pub restrict_indexing: bool,
}
impl Default for Options {
fn default() -> Self {
Options {
shader_model: ShaderModel::V5_1,
binding_map: BindingMap::default(),
fake_missing_bindings: true,
special_constants_binding: None,
push_constants_target: None,
zero_initialize_workgroup_memory: true,
restrict_indexing: true,
}
}
}
impl Options {
fn resolve_resource_binding(
&self,
res_binding: &crate::ResourceBinding,
) -> Result<BindTarget, EntryPointError> {
match self.binding_map.get(res_binding) {
Some(target) => Ok(target.clone()),
None if self.fake_missing_bindings => Ok(BindTarget {
space: res_binding.group as u8,
register: res_binding.binding,
binding_array_size: None,
}),
None => Err(EntryPointError::MissingBinding(res_binding.clone())),
}
}
}
/// Reflection info for entry point names.
#[derive(Default)]
pub struct ReflectionInfo {
/// Mapping of the entry point names.
///
/// Each item in the array corresponds to an entry point index. The real entry point name may be different if one of the
/// reserved words are used.
///
/// Note: Some entry points may fail translation because of missing bindings.
pub entry_point_names: Vec<Result<String, EntryPointError>>,
}
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
IoError(#[from] FmtError),
#[error("A scalar with an unsupported width was requested: {0:?}")]
UnsupportedScalar(crate::Scalar),
#[error("{0}")]
Unimplemented(String), // TODO: Error used only during development
#[error("{0}")]
Custom(String),
#[error("overrides should not be present at this stage")]
Override,
}
#[derive(Default)]
struct Wrapped {
zero_values: crate::FastHashSet<help::WrappedZeroValue>,
array_lengths: crate::FastHashSet<help::WrappedArrayLength>,
image_queries: crate::FastHashSet<help::WrappedImageQuery>,
constructors: crate::FastHashSet<help::WrappedConstructor>,
struct_matrix_access: crate::FastHashSet<help::WrappedStructMatrixAccess>,
mat_cx2s: crate::FastHashSet<help::WrappedMatCx2>,
math: crate::FastHashSet<help::WrappedMath>,
}
impl Wrapped {
fn clear(&mut self) {
self.array_lengths.clear();
self.image_queries.clear();
self.constructors.clear();
self.struct_matrix_access.clear();
self.mat_cx2s.clear();
self.math.clear();
}
}
/// A fragment entry point to be considered when generating HLSL for the output interface of vertex
/// entry points.
///
/// This is provided as an optional parameter to [`Writer::write`].
///
/// If this is provided, vertex outputs will be removed if they are not inputs of this fragment
/// entry point. This is necessary for generating correct HLSL when some of the vertex shader
/// outputs are not consumed by the fragment shader.
pub struct FragmentEntryPoint<'a> {
module: &'a crate::Module,
func: &'a crate::Function,
}
impl<'a> FragmentEntryPoint<'a> {
/// Returns `None` if the entry point with the provided name can't be found or isn't a fragment
/// entry point.
pub fn new(module: &'a crate::Module, ep_name: &'a str) -> Option<Self> {
module
.entry_points
.iter()
.find(|ep| ep.name == ep_name)
.filter(|ep| ep.stage == crate::ShaderStage::Fragment)
.map(|ep| Self {
module,
func: &ep.function,
})
}
}
pub struct Writer<'a, W> {
out: W,
names: crate::FastHashMap<proc::NameKey, String>,
namer: proc::Namer,
/// HLSL backend options
options: &'a Options,
/// Information about entry point arguments and result types.
entry_point_io: Vec<writer::EntryPointInterface>,
/// Set of expressions that have associated temporary variables
named_expressions: crate::NamedExpressions,
wrapped: Wrapped,
written_committed_intersection: bool,
written_candidate_intersection: bool,
continue_ctx: back::continue_forward::ContinueCtx,
/// A reference to some part of a global variable, lowered to a series of
/// byte offset calculations.
///
/// See the [`storage`] module for background on why we need this.
///
/// Each [`SubAccess`] in the vector is a lowering of some [`Access`] or
/// [`AccessIndex`] expression to the level of byte strides and offsets. See
/// [`SubAccess`] for details.
///
/// This field is a member of [`Writer`] solely to allow re-use of
/// the `Vec`'s dynamic allocation. The value is no longer needed
/// once HLSL for the access has been generated.
///
/// [`Storage`]: crate::AddressSpace::Storage
/// [`SubAccess`]: storage::SubAccess
/// [`Access`]: crate::Expression::Access
/// [`AccessIndex`]: crate::Expression::AccessIndex
temp_access_chain: Vec<storage::SubAccess>,
need_bake_expressions: back::NeedBakeExpressions,
}
+163
View File
@@ -0,0 +1,163 @@
use crate::back::hlsl::BackendResult;
use crate::{RayQueryIntersection, TypeInner};
use std::fmt::Write;
impl<W: Write> super::Writer<'_, W> {
// constructs hlsl RayDesc from wgsl RayDesc
pub(super) fn write_ray_desc_from_ray_desc_constructor_function(
&mut self,
module: &crate::Module,
) -> BackendResult {
write!(self.out, "RayDesc RayDescFromRayDesc_(")?;
self.write_type(module, module.special_types.ray_desc.unwrap())?;
writeln!(self.out, " arg0) {{")?;
writeln!(self.out, " RayDesc ret = (RayDesc)0;")?;
writeln!(self.out, " ret.Origin = arg0.origin;")?;
writeln!(self.out, " ret.TMin = arg0.tmin;")?;
writeln!(self.out, " ret.Direction = arg0.dir;")?;
writeln!(self.out, " ret.TMax = arg0.tmax;")?;
writeln!(self.out, " return ret;")?;
writeln!(self.out, "}}")?;
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_committed_intersection_function(
&mut self,
module: &crate::Module,
) -> BackendResult {
self.write_type(module, module.special_types.ray_intersection.unwrap())?;
write!(self.out, " GetCommittedIntersection(")?;
self.write_value_type(module, &TypeInner::RayQuery)?;
writeln!(self.out, " rq) {{")?;
write!(self.out, " ")?;
self.write_type(module, module.special_types.ray_intersection.unwrap())?;
write!(self.out, " ret = (")?;
self.write_type(module, module.special_types.ray_intersection.unwrap())?;
writeln!(self.out, ")0;")?;
writeln!(self.out, " ret.kind = rq.CommittedStatus();")?;
writeln!(
self.out,
" if( rq.CommittedStatus() == COMMITTED_NOTHING) {{}} else {{"
)?;
writeln!(self.out, " ret.t = rq.CommittedRayT();")?;
writeln!(
self.out,
" ret.instance_custom_index = rq.CommittedInstanceID();"
)?;
writeln!(
self.out,
" ret.instance_id = rq.CommittedInstanceIndex();"
)?;
writeln!(
self.out,
" ret.sbt_record_offset = rq.CommittedInstanceContributionToHitGroupIndex();"
)?;
writeln!(
self.out,
" ret.geometry_index = rq.CommittedGeometryIndex();"
)?;
writeln!(
self.out,
" ret.primitive_index = rq.CommittedPrimitiveIndex();"
)?;
writeln!(
self.out,
" if( rq.CommittedStatus() == COMMITTED_TRIANGLE_HIT ) {{"
)?;
writeln!(
self.out,
" ret.barycentrics = rq.CommittedTriangleBarycentrics();"
)?;
writeln!(
self.out,
" ret.front_face = rq.CommittedTriangleFrontFace();"
)?;
writeln!(self.out, " }}")?;
writeln!(
self.out,
" ret.object_to_world = rq.CommittedObjectToWorld4x3();"
)?;
writeln!(
self.out,
" ret.world_to_object = rq.CommittedWorldToObject4x3();"
)?;
writeln!(self.out, " }}")?;
writeln!(self.out, " return ret;")?;
writeln!(self.out, "}}")?;
writeln!(self.out)?;
Ok(())
}
pub(super) fn write_candidate_intersection_function(
&mut self,
module: &crate::Module,
) -> BackendResult {
self.write_type(module, module.special_types.ray_intersection.unwrap())?;
write!(self.out, " GetCandidateIntersection(")?;
self.write_value_type(module, &TypeInner::RayQuery)?;
writeln!(self.out, " rq) {{")?;
write!(self.out, " ")?;
self.write_type(module, module.special_types.ray_intersection.unwrap())?;
write!(self.out, " ret = (")?;
self.write_type(module, module.special_types.ray_intersection.unwrap())?;
writeln!(self.out, ")0;")?;
writeln!(self.out, " CANDIDATE_TYPE kind = rq.CandidateType();")?;
writeln!(
self.out,
" if (kind == CANDIDATE_NON_OPAQUE_TRIANGLE) {{"
)?;
writeln!(
self.out,
" ret.kind = {};",
RayQueryIntersection::Triangle as u32
)?;
writeln!(self.out, " ret.t = rq.CandidateTriangleRayT();")?;
writeln!(
self.out,
" ret.barycentrics = rq.CandidateTriangleBarycentrics();"
)?;
writeln!(
self.out,
" ret.front_face = rq.CandidateTriangleFrontFace();"
)?;
writeln!(self.out, " }} else {{")?;
writeln!(
self.out,
" ret.kind = {};",
RayQueryIntersection::Aabb as u32
)?;
writeln!(self.out, " }}")?;
writeln!(
self.out,
" ret.instance_custom_index = rq.CandidateInstanceID();"
)?;
writeln!(
self.out,
" ret.instance_id = rq.CandidateInstanceIndex();"
)?;
writeln!(
self.out,
" ret.sbt_record_offset = rq.CandidateInstanceContributionToHitGroupIndex();"
)?;
writeln!(
self.out,
" ret.geometry_index = rq.CandidateGeometryIndex();"
)?;
writeln!(
self.out,
" ret.primitive_index = rq.CandidatePrimitiveIndex();"
)?;
writeln!(
self.out,
" ret.object_to_world = rq.CandidateObjectToWorld4x3();"
)?;
writeln!(
self.out,
" ret.world_to_object = rq.CandidateWorldToObject4x3();"
)?;
writeln!(self.out, " return ret;")?;
writeln!(self.out, "}}")?;
writeln!(self.out)?;
Ok(())
}
}
+542
View File
@@ -0,0 +1,542 @@
/*!
Generating accesses to [`ByteAddressBuffer`] contents.
Naga IR globals in the [`Storage`] address space are rendered as
[`ByteAddressBuffer`]s or [`RWByteAddressBuffer`]s in HLSL. These
buffers don't have HLSL types (structs, arrays, etc.); instead, they
are just raw blocks of bytes, with methods to load and store values of
specific types at particular byte offsets. This means that Naga must
translate chains of [`Access`] and [`AccessIndex`] expressions into
HLSL expressions that compute byte offsets into the buffer.
To generate code for a [`Storage`] access:
- Call [`Writer::fill_access_chain`] on the expression referring to
the value. This populates [`Writer::temp_access_chain`] with the
appropriate byte offset calculations, as a vector of [`SubAccess`]
values.
- Call [`Writer::write_storage_address`] to emit an HLSL expression
for a given slice of [`SubAccess`] values.
Naga IR expressions can operate on composite values of any type, but
[`ByteAddressBuffer`] and [`RWByteAddressBuffer`] have only a fixed
set of `Load` and `Store` methods, to access one through four
consecutive 32-bit values. To synthesize a Naga access, you can
initialize [`temp_access_chain`] to refer to the composite, and then
temporarily push and pop additional steps on
[`Writer::temp_access_chain`] to generate accesses to the individual
elements/members.
The [`temp_access_chain`] field is a member of [`Writer`] solely to
allow re-use of the `Vec`'s dynamic allocation. Its value is no longer
needed once HLSL for the access has been generated.
Note about DXC and Load/Store functions:
DXC's HLSL has a generic [`Load` and `Store`] function for [`ByteAddressBuffer`] and
[`RWByteAddressBuffer`]. This is not available in FXC's HLSL, so we use
it only for types that are only available in DXC. Notably 64 and 16 bit types.
FXC's HLSL has functions Load, Load2, Load3, and Load4 and Store, Store2, Store3, Store4.
This loads/stores a vector of length 1, 2, 3, or 4. We use that for 32bit types, bitcasting to the
correct type if necessary.
[`Storage`]: crate::AddressSpace::Storage
[`ByteAddressBuffer`]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-byteaddressbuffer
[`RWByteAddressBuffer`]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer
[`Access`]: crate::Expression::Access
[`AccessIndex`]: crate::Expression::AccessIndex
[`Writer::fill_access_chain`]: super::Writer::fill_access_chain
[`Writer::write_storage_address`]: super::Writer::write_storage_address
[`Writer::temp_access_chain`]: super::Writer::temp_access_chain
[`temp_access_chain`]: super::Writer::temp_access_chain
[`Writer`]: super::Writer
[`Load` and `Store`]: https://github.com/microsoft/DirectXShaderCompiler/wiki/ByteAddressBuffer-Load-Store-Additions
*/
use super::{super::FunctionCtx, BackendResult, Error};
use crate::{
proc::{Alignment, NameKey, TypeResolution},
Handle,
};
use std::{fmt, mem};
const STORE_TEMP_NAME: &str = "_value";
/// One step in accessing a [`Storage`] global's component or element.
///
/// [`Writer::temp_access_chain`] holds a series of these structures,
/// describing how to compute the byte offset of a particular element
/// or member of some global variable in the [`Storage`] address
/// space.
///
/// [`Writer::temp_access_chain`]: super::Writer::temp_access_chain
/// [`Storage`]: crate::AddressSpace::Storage
#[derive(Debug)]
pub(super) enum SubAccess {
/// Add the given byte offset. This is used for struct members, or
/// known components of a vector or matrix. In all those cases,
/// the byte offset is a compile-time constant.
Offset(u32),
/// Scale `value` by `stride`, and add that to the current byte
/// offset. This is used to compute the offset of an array element
/// whose index is computed at runtime.
Index {
value: Handle<crate::Expression>,
stride: u32,
},
}
pub(super) enum StoreValue {
Expression(Handle<crate::Expression>),
TempIndex {
depth: usize,
index: u32,
ty: TypeResolution,
},
TempAccess {
depth: usize,
base: Handle<crate::Type>,
member_index: u32,
},
}
impl<W: fmt::Write> super::Writer<'_, W> {
pub(super) fn write_storage_address(
&mut self,
module: &crate::Module,
chain: &[SubAccess],
func_ctx: &FunctionCtx,
) -> BackendResult {
if chain.is_empty() {
write!(self.out, "0")?;
}
for (i, access) in chain.iter().enumerate() {
if i != 0 {
write!(self.out, "+")?;
}
match *access {
SubAccess::Offset(offset) => {
write!(self.out, "{offset}")?;
}
SubAccess::Index { value, stride } => {
self.write_expr(module, value, func_ctx)?;
write!(self.out, "*{stride}")?;
}
}
}
Ok(())
}
fn write_storage_load_sequence<I: Iterator<Item = (TypeResolution, u32)>>(
&mut self,
module: &crate::Module,
var_handle: Handle<crate::GlobalVariable>,
sequence: I,
func_ctx: &FunctionCtx,
) -> BackendResult {
for (i, (ty_resolution, offset)) in sequence.enumerate() {
// add the index temporarily
self.temp_access_chain.push(SubAccess::Offset(offset));
if i != 0 {
write!(self.out, ", ")?;
};
self.write_storage_load(module, var_handle, ty_resolution, func_ctx)?;
self.temp_access_chain.pop();
}
Ok(())
}
/// Emit code to access a [`Storage`] global's component.
///
/// Emit HLSL to access the component of `var_handle`, a global
/// variable in the [`Storage`] address space, whose type is
/// `result_ty` and whose location within the global is given by
/// [`self.temp_access_chain`]. See the [`storage`] module's
/// documentation for background.
///
/// [`Storage`]: crate::AddressSpace::Storage
/// [`self.temp_access_chain`]: super::Writer::temp_access_chain
pub(super) fn write_storage_load(
&mut self,
module: &crate::Module,
var_handle: Handle<crate::GlobalVariable>,
result_ty: TypeResolution,
func_ctx: &FunctionCtx,
) -> BackendResult {
match *result_ty.inner_with(&module.types) {
crate::TypeInner::Scalar(scalar) => {
// working around the borrow checker in `self.write_expr`
let chain = mem::take(&mut self.temp_access_chain);
let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
// See note about DXC and Load/Store in the module's documentation.
if scalar.width == 4 {
let cast = scalar.kind.to_hlsl_cast();
write!(self.out, "{cast}({var_name}.Load(")?;
} else {
let ty = scalar.to_hlsl_str()?;
write!(self.out, "{var_name}.Load<{ty}>(")?;
};
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ")")?;
if scalar.width == 4 {
write!(self.out, ")")?;
}
self.temp_access_chain = chain;
}
crate::TypeInner::Vector { size, scalar } => {
// working around the borrow checker in `self.write_expr`
let chain = mem::take(&mut self.temp_access_chain);
let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
let size = size as u8;
// See note about DXC and Load/Store in the module's documentation.
if scalar.width == 4 {
let cast = scalar.kind.to_hlsl_cast();
write!(self.out, "{cast}({var_name}.Load{size}(")?;
} else {
let ty = scalar.to_hlsl_str()?;
write!(self.out, "{var_name}.Load<{ty}{size}>(")?;
};
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ")")?;
if scalar.width == 4 {
write!(self.out, ")")?;
}
self.temp_access_chain = chain;
}
crate::TypeInner::Matrix {
columns,
rows,
scalar,
} => {
write!(
self.out,
"{}{}x{}(",
scalar.to_hlsl_str()?,
columns as u8,
rows as u8,
)?;
// Note: Matrices containing vec3s, due to padding, act like they contain vec4s.
let row_stride = Alignment::from(rows) * scalar.width as u32;
let iter = (0..columns as u32).map(|i| {
let ty_inner = crate::TypeInner::Vector { size: rows, scalar };
(TypeResolution::Value(ty_inner), i * row_stride)
});
self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?;
write!(self.out, ")")?;
}
crate::TypeInner::Array {
base,
size: crate::ArraySize::Constant(size),
stride,
} => {
let constructor = super::help::WrappedConstructor {
ty: result_ty.handle().unwrap(),
};
self.write_wrapped_constructor_function_name(module, constructor)?;
write!(self.out, "(")?;
let iter = (0..size.get()).map(|i| (TypeResolution::Handle(base), stride * i));
self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?;
write!(self.out, ")")?;
}
crate::TypeInner::Struct { ref members, .. } => {
let constructor = super::help::WrappedConstructor {
ty: result_ty.handle().unwrap(),
};
self.write_wrapped_constructor_function_name(module, constructor)?;
write!(self.out, "(")?;
let iter = members
.iter()
.map(|m| (TypeResolution::Handle(m.ty), m.offset));
self.write_storage_load_sequence(module, var_handle, iter, func_ctx)?;
write!(self.out, ")")?;
}
_ => unreachable!(),
}
Ok(())
}
fn write_store_value(
&mut self,
module: &crate::Module,
value: &StoreValue,
func_ctx: &FunctionCtx,
) -> BackendResult {
match *value {
StoreValue::Expression(expr) => self.write_expr(module, expr, func_ctx)?,
StoreValue::TempIndex {
depth,
index,
ty: _,
} => write!(self.out, "{STORE_TEMP_NAME}{depth}[{index}]")?,
StoreValue::TempAccess {
depth,
base,
member_index,
} => {
let name = &self.names[&NameKey::StructMember(base, member_index)];
write!(self.out, "{STORE_TEMP_NAME}{depth}.{name}")?
}
}
Ok(())
}
/// Helper function to write down the Store operation on a `ByteAddressBuffer`.
pub(super) fn write_storage_store(
&mut self,
module: &crate::Module,
var_handle: Handle<crate::GlobalVariable>,
value: StoreValue,
func_ctx: &FunctionCtx,
level: crate::back::Level,
) -> BackendResult {
let temp_resolution;
let ty_resolution = match value {
StoreValue::Expression(expr) => &func_ctx.info[expr].ty,
StoreValue::TempIndex {
depth: _,
index: _,
ref ty,
} => ty,
StoreValue::TempAccess {
depth: _,
base,
member_index,
} => {
let ty_handle = match module.types[base].inner {
crate::TypeInner::Struct { ref members, .. } => {
members[member_index as usize].ty
}
_ => unreachable!(),
};
temp_resolution = TypeResolution::Handle(ty_handle);
&temp_resolution
}
};
match *ty_resolution.inner_with(&module.types) {
crate::TypeInner::Scalar(scalar) => {
// working around the borrow checker in `self.write_expr`
let chain = mem::take(&mut self.temp_access_chain);
let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
// See note about DXC and Load/Store in the module's documentation.
if scalar.width == 4 {
write!(self.out, "{level}{var_name}.Store(")?;
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ", asuint(")?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, "));")?;
} else {
write!(self.out, "{level}{var_name}.Store(")?;
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ", ")?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, ");")?;
}
self.temp_access_chain = chain;
}
crate::TypeInner::Vector { size, scalar } => {
// working around the borrow checker in `self.write_expr`
let chain = mem::take(&mut self.temp_access_chain);
let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
// See note about DXC and Load/Store in the module's documentation.
if scalar.width == 4 {
write!(self.out, "{}{}.Store{}(", level, var_name, size as u8)?;
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ", asuint(")?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, "));")?;
} else {
write!(self.out, "{level}{var_name}.Store(")?;
self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ", ")?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, ");")?;
}
self.temp_access_chain = chain;
}
crate::TypeInner::Matrix {
columns,
rows,
scalar,
} => {
// first, assign the value to a temporary
writeln!(self.out, "{level}{{")?;
let depth = level.0 + 1;
write!(
self.out,
"{}{}{}x{} {}{} = ",
level.next(),
scalar.to_hlsl_str()?,
columns as u8,
rows as u8,
STORE_TEMP_NAME,
depth,
)?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, ";")?;
// Note: Matrices containing vec3s, due to padding, act like they contain vec4s.
let row_stride = Alignment::from(rows) * scalar.width as u32;
// then iterate the stores
for i in 0..columns as u32 {
self.temp_access_chain
.push(SubAccess::Offset(i * row_stride));
let ty_inner = crate::TypeInner::Vector { size: rows, scalar };
let sv = StoreValue::TempIndex {
depth,
index: i,
ty: TypeResolution::Value(ty_inner),
};
self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?;
self.temp_access_chain.pop();
}
// done
writeln!(self.out, "{level}}}")?;
}
crate::TypeInner::Array {
base,
size: crate::ArraySize::Constant(size),
stride,
} => {
// first, assign the value to a temporary
writeln!(self.out, "{level}{{")?;
write!(self.out, "{}", level.next())?;
self.write_value_type(module, &module.types[base].inner)?;
let depth = level.next().0;
write!(self.out, " {STORE_TEMP_NAME}{depth}")?;
self.write_array_size(module, base, crate::ArraySize::Constant(size))?;
write!(self.out, " = ")?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, ";")?;
// then iterate the stores
for i in 0..size.get() {
self.temp_access_chain.push(SubAccess::Offset(i * stride));
let sv = StoreValue::TempIndex {
depth,
index: i,
ty: TypeResolution::Handle(base),
};
self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?;
self.temp_access_chain.pop();
}
// done
writeln!(self.out, "{level}}}")?;
}
crate::TypeInner::Struct { ref members, .. } => {
// first, assign the value to a temporary
writeln!(self.out, "{level}{{")?;
let depth = level.next().0;
let struct_ty = ty_resolution.handle().unwrap();
let struct_name = &self.names[&NameKey::Type(struct_ty)];
write!(
self.out,
"{}{} {}{} = ",
level.next(),
struct_name,
STORE_TEMP_NAME,
depth
)?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, ";")?;
// then iterate the stores
for (i, member) in members.iter().enumerate() {
self.temp_access_chain
.push(SubAccess::Offset(member.offset));
let sv = StoreValue::TempAccess {
depth,
base: struct_ty,
member_index: i as u32,
};
self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?;
self.temp_access_chain.pop();
}
// done
writeln!(self.out, "{level}}}")?;
}
_ => unreachable!(),
}
Ok(())
}
/// Set [`temp_access_chain`] to compute the byte offset of `cur_expr`.
///
/// The `cur_expr` expression must be a reference to a global
/// variable in the [`Storage`] address space, or a chain of
/// [`Access`] and [`AccessIndex`] expressions referring to some
/// component of such a global.
///
/// [`temp_access_chain`]: super::Writer::temp_access_chain
/// [`Storage`]: crate::AddressSpace::Storage
/// [`Access`]: crate::Expression::Access
/// [`AccessIndex`]: crate::Expression::AccessIndex
pub(super) fn fill_access_chain(
&mut self,
module: &crate::Module,
mut cur_expr: Handle<crate::Expression>,
func_ctx: &FunctionCtx,
) -> Result<Handle<crate::GlobalVariable>, Error> {
enum AccessIndex {
Expression(Handle<crate::Expression>),
Constant(u32),
}
enum Parent<'a> {
Array { stride: u32 },
Struct(&'a [crate::StructMember]),
}
self.temp_access_chain.clear();
loop {
let (next_expr, access_index) = match func_ctx.expressions[cur_expr] {
crate::Expression::GlobalVariable(handle) => return Ok(handle),
crate::Expression::Access { base, index } => (base, AccessIndex::Expression(index)),
crate::Expression::AccessIndex { base, index } => {
(base, AccessIndex::Constant(index))
}
ref other => {
return Err(Error::Unimplemented(format!("Pointer access of {other:?}")))
}
};
let parent = match *func_ctx.resolve_type(next_expr, &module.types) {
crate::TypeInner::Pointer { base, .. } => match module.types[base].inner {
crate::TypeInner::Struct { ref members, .. } => Parent::Struct(members),
crate::TypeInner::Array { stride, .. } => Parent::Array { stride },
crate::TypeInner::Vector { scalar, .. } => Parent::Array {
stride: scalar.width as u32,
},
crate::TypeInner::Matrix { rows, scalar, .. } => Parent::Array {
// The stride between matrices is the count of rows as this is how
// long each column is.
stride: Alignment::from(rows) * scalar.width as u32,
},
_ => unreachable!(),
},
crate::TypeInner::ValuePointer { scalar, .. } => Parent::Array {
stride: scalar.width as u32,
},
_ => unreachable!(),
};
let sub = match (parent, access_index) {
(Parent::Array { stride }, AccessIndex::Expression(value)) => {
SubAccess::Index { value, stride }
}
(Parent::Array { stride }, AccessIndex::Constant(index)) => {
SubAccess::Offset(stride * index)
}
(Parent::Struct(members), AccessIndex::Constant(index)) => {
SubAccess::Offset(members[index as usize].offset)
}
(Parent::Struct(_), AccessIndex::Expression(_)) => unreachable!(),
};
self.temp_access_chain.push(sub);
cur_expr = next_expr;
}
}
}
File diff suppressed because it is too large Load Diff
+317
View File
@@ -0,0 +1,317 @@
/*!
Backend functions that export shader [`Module`](super::Module)s into binary and text formats.
*/
#![allow(dead_code)] // can be dead if none of the enabled backends need it
use crate::proc::ExpressionKindTracker;
#[cfg(dot_out)]
pub mod dot;
#[cfg(glsl_out)]
pub mod glsl;
#[cfg(hlsl_out)]
pub mod hlsl;
#[cfg(msl_out)]
pub mod msl;
#[cfg(spv_out)]
pub mod spv;
#[cfg(wgsl_out)]
pub mod wgsl;
#[cfg(any(hlsl_out, msl_out, spv_out, glsl_out))]
pub mod pipeline_constants;
#[cfg(any(hlsl_out, glsl_out))]
mod continue_forward;
/// Names of vector components.
pub const COMPONENTS: &[char] = &['x', 'y', 'z', 'w'];
/// Indent for backends.
pub const INDENT: &str = " ";
/// Expressions that need baking.
pub type NeedBakeExpressions = crate::FastHashSet<crate::Handle<crate::Expression>>;
/// A type for displaying expression handles as baking identifiers.
///
/// Given an [`Expression`] [`Handle`] `h`, `Baked(h)` implements
/// [`std::fmt::Display`], showing the handle's index prefixed by
/// `_e`.
///
/// [`Expression`]: crate::Expression
/// [`Handle`]: crate::Handle
struct Baked(crate::Handle<crate::Expression>);
impl std::fmt::Display for Baked {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_prefixed(f, "_e")
}
}
/// Specifies the values of pipeline-overridable constants in the shader module.
///
/// If an `@id` attribute was specified on the declaration,
/// the key must be the pipeline constant ID as a decimal ASCII number; if not,
/// the key must be the constant's identifier name.
///
/// The value may represent any of WGSL's concrete scalar types.
pub type PipelineConstants = std::collections::HashMap<String, f64>;
/// Indentation level.
#[derive(Clone, Copy)]
pub struct Level(pub usize);
impl Level {
const fn next(&self) -> Self {
Level(self.0 + 1)
}
}
impl std::fmt::Display for Level {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
(0..self.0).try_for_each(|_| formatter.write_str(INDENT))
}
}
/// Whether we're generating an entry point or a regular function.
///
/// Backend languages often require different code for a [`Function`]
/// depending on whether it represents an [`EntryPoint`] or not.
/// Backends can pass common code one of these values to select the
/// right behavior.
///
/// These values also carry enough information to find the `Function`
/// in the [`Module`]: the `Handle` for a regular function, or the
/// index into [`Module::entry_points`] for an entry point.
///
/// [`Function`]: crate::Function
/// [`EntryPoint`]: crate::EntryPoint
/// [`Module`]: crate::Module
/// [`Module::entry_points`]: crate::Module::entry_points
pub enum FunctionType {
/// A regular function.
Function(crate::Handle<crate::Function>),
/// An [`EntryPoint`], and its index in [`Module::entry_points`].
///
/// [`EntryPoint`]: crate::EntryPoint
/// [`Module::entry_points`]: crate::Module::entry_points
EntryPoint(crate::proc::EntryPointIndex),
}
impl FunctionType {
/// Returns true if the function is an entry point for a compute shader.
pub fn is_compute_entry_point(&self, module: &crate::Module) -> bool {
match *self {
FunctionType::EntryPoint(index) => {
module.entry_points[index as usize].stage == crate::ShaderStage::Compute
}
FunctionType::Function(_) => false,
}
}
}
/// Helper structure that stores data needed when writing the function
pub struct FunctionCtx<'a> {
/// The current function being written
pub ty: FunctionType,
/// Analysis about the function
pub info: &'a crate::valid::FunctionInfo,
/// The expression arena of the current function being written
pub expressions: &'a crate::Arena<crate::Expression>,
/// Map of expressions that have associated variable names
pub named_expressions: &'a crate::NamedExpressions,
/// For constness checks
pub expr_kind_tracker: ExpressionKindTracker,
}
impl FunctionCtx<'_> {
/// Helper method that resolves a type of a given expression.
pub fn resolve_type<'a>(
&'a self,
handle: crate::Handle<crate::Expression>,
types: &'a crate::UniqueArena<crate::Type>,
) -> &'a crate::TypeInner {
self.info[handle].ty.inner_with(types)
}
/// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function
pub const fn name_key(
&self,
local: crate::Handle<crate::LocalVariable>,
) -> crate::proc::NameKey {
match self.ty {
FunctionType::Function(handle) => crate::proc::NameKey::FunctionLocal(handle, local),
FunctionType::EntryPoint(idx) => crate::proc::NameKey::EntryPointLocal(idx, local),
}
}
/// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a function argument.
///
/// # Panics
/// - If the function arguments are less or equal to `arg`
pub const fn argument_key(&self, arg: u32) -> crate::proc::NameKey {
match self.ty {
FunctionType::Function(handle) => crate::proc::NameKey::FunctionArgument(handle, arg),
FunctionType::EntryPoint(ep_index) => {
crate::proc::NameKey::EntryPointArgument(ep_index, arg)
}
}
}
/// Returns true if the given expression points to a fixed-function pipeline input.
pub fn is_fixed_function_input(
&self,
mut expression: crate::Handle<crate::Expression>,
module: &crate::Module,
) -> Option<crate::BuiltIn> {
let ep_function = match self.ty {
FunctionType::Function(_) => return None,
FunctionType::EntryPoint(ep_index) => &module.entry_points[ep_index as usize].function,
};
let mut built_in = None;
loop {
match self.expressions[expression] {
crate::Expression::FunctionArgument(arg_index) => {
return match ep_function.arguments[arg_index as usize].binding {
Some(crate::Binding::BuiltIn(bi)) => Some(bi),
_ => built_in,
};
}
crate::Expression::AccessIndex { base, index } => {
match *self.resolve_type(base, &module.types) {
crate::TypeInner::Struct { ref members, .. } => {
if let Some(crate::Binding::BuiltIn(bi)) =
members[index as usize].binding
{
built_in = Some(bi);
}
}
_ => return None,
}
expression = base;
}
_ => return None,
}
}
}
}
impl crate::Expression {
/// Returns the ref count, upon reaching which this expression
/// should be considered for baking.
///
/// Note: we have to cache any expressions that depend on the control flow,
/// or otherwise they may be moved into a non-uniform control flow, accidentally.
/// See the [module-level documentation][emit] for details.
///
/// [emit]: index.html#expression-evaluation-time
pub const fn bake_ref_count(&self) -> usize {
match *self {
// accesses are never cached, only loads are
crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => usize::MAX,
// sampling may use the control flow, and image ops look better by themselves
crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1,
// derivatives use the control flow
crate::Expression::Derivative { .. } => 1,
// TODO: We need a better fix for named `Load` expressions
// More info - https://github.com/gfx-rs/naga/pull/914
// And https://github.com/gfx-rs/naga/issues/910
crate::Expression::Load { .. } => 1,
// cache expressions that are referenced multiple times
_ => 2,
}
}
}
/// Helper function that returns the string corresponding to the [`BinaryOperator`](crate::BinaryOperator)
pub const fn binary_operation_str(op: crate::BinaryOperator) -> &'static str {
use crate::BinaryOperator as Bo;
match op {
Bo::Add => "+",
Bo::Subtract => "-",
Bo::Multiply => "*",
Bo::Divide => "/",
Bo::Modulo => "%",
Bo::Equal => "==",
Bo::NotEqual => "!=",
Bo::Less => "<",
Bo::LessEqual => "<=",
Bo::Greater => ">",
Bo::GreaterEqual => ">=",
Bo::And => "&",
Bo::ExclusiveOr => "^",
Bo::InclusiveOr => "|",
Bo::LogicalAnd => "&&",
Bo::LogicalOr => "||",
Bo::ShiftLeft => "<<",
Bo::ShiftRight => ">>",
}
}
/// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize)
const fn vector_size_str(size: crate::VectorSize) -> &'static str {
match size {
crate::VectorSize::Bi => "2",
crate::VectorSize::Tri => "3",
crate::VectorSize::Quad => "4",
}
}
impl crate::TypeInner {
/// Returns true if this is a handle to a type rather than the type directly.
pub const fn is_handle(&self) -> bool {
match *self {
crate::TypeInner::Image { .. }
| crate::TypeInner::Sampler { .. }
| crate::TypeInner::AccelerationStructure { .. } => true,
_ => false,
}
}
}
impl crate::Statement {
/// Returns true if the statement directly terminates the current block.
///
/// Used to decide whether case blocks require a explicit `break`.
pub const fn is_terminator(&self) -> bool {
match *self {
crate::Statement::Break
| crate::Statement::Continue
| crate::Statement::Return { .. }
| crate::Statement::Kill => true,
_ => false,
}
}
}
bitflags::bitflags! {
/// Ray flags, for a [`RayDesc`]'s `flags` field.
///
/// Note that these exactly correspond to the SPIR-V "Ray Flags" mask, and
/// the SPIR-V backend passes them directly through to the
/// [`OpRayQueryInitializeKHR`][op] instruction. (We have to choose something, so
/// we might as well make one back end's life easier.)
///
/// [`RayDesc`]: crate::Module::generate_ray_desc_type
/// [op]: https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpRayQueryInitializeKHR
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct RayFlag: u32 {
const OPAQUE = 0x01;
const NO_OPAQUE = 0x02;
const TERMINATE_ON_FIRST_HIT = 0x04;
const SKIP_CLOSEST_HIT_SHADER = 0x08;
const CULL_BACK_FACING = 0x10;
const CULL_FRONT_FACING = 0x20;
const CULL_OPAQUE = 0x40;
const CULL_NO_OPAQUE = 0x80;
const SKIP_TRIANGLES = 0x100;
const SKIP_AABBS = 0x200;
}
}
/// The intersection test to use for ray queries.
#[repr(u32)]
pub enum RayIntersectionType {
Triangle = 1,
BoundingBox = 4,
}
+345
View File
@@ -0,0 +1,345 @@
// MSLS - Metal Shading Language Specification:
// https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
//
// C++ - Standard for Programming Language C++ (N4431)
// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4431.pdf
pub const RESERVED: &[&str] = &[
// Undocumented
"assert", // found in https://github.com/gfx-rs/wgpu/issues/5347
// Standard for Programming Language C++ (N4431): 2.5 Alternative tokens
"and",
"bitor",
"or",
"xor",
"compl",
"bitand",
"and_eq",
"or_eq",
"xor_eq",
"not",
"not_eq",
// Standard for Programming Language C++ (N4431): 2.11 Keywords
"alignas",
"alignof",
"asm",
"auto",
"bool",
"break",
"case",
"catch",
"char",
"char16_t",
"char32_t",
"class",
"const",
"constexpr",
"const_cast",
"continue",
"decltype",
"default",
"delete",
"do",
"double",
"dynamic_cast",
"else",
"enum",
"explicit",
"export",
"extern",
"false",
"float",
"for",
"friend",
"goto",
"if",
"inline",
"int",
"long",
"mutable",
"namespace",
"new",
"noexcept",
"nullptr",
"operator",
"private",
"protected",
"public",
"register",
"reinterpret_cast",
"return",
"short",
"signed",
"sizeof",
"static",
"static_assert",
"static_cast",
"struct",
"switch",
"template",
"this",
"thread_local",
"throw",
"true",
"try",
"typedef",
"typeid",
"typename",
"union",
"unsigned",
"using",
"virtual",
"void",
"volatile",
"wchar_t",
"while",
// Metal Shading Language Specification: 1.4.4 Restrictions
"main",
// Metal Shading Language Specification: 2.1 Scalar Data Types
"int8_t",
"uchar",
"uint8_t",
"int16_t",
"ushort",
"uint16_t",
"int32_t",
"uint",
"uint32_t",
"int64_t",
"uint64_t",
"half",
"bfloat",
"size_t",
"ptrdiff_t",
// Metal Shading Language Specification: 2.2 Vector Data Types
"bool2",
"bool3",
"bool4",
"char2",
"char3",
"char4",
"short2",
"short3",
"short4",
"int2",
"int3",
"int4",
"long2",
"long3",
"long4",
"uchar2",
"uchar3",
"uchar4",
"ushort2",
"ushort3",
"ushort4",
"uint2",
"uint3",
"uint4",
"ulong2",
"ulong3",
"ulong4",
"half2",
"half3",
"half4",
"bfloat2",
"bfloat3",
"bfloat4",
"float2",
"float3",
"float4",
"vec",
// Metal Shading Language Specification: 2.2.3 Packed Vector Types
"packed_bool2",
"packed_bool3",
"packed_bool4",
"packed_char2",
"packed_char3",
"packed_char4",
"packed_short2",
"packed_short3",
"packed_short4",
"packed_int2",
"packed_int3",
"packed_int4",
"packed_uchar2",
"packed_uchar3",
"packed_uchar4",
"packed_ushort2",
"packed_ushort3",
"packed_ushort4",
"packed_uint2",
"packed_uint3",
"packed_uint4",
"packed_half2",
"packed_half3",
"packed_half4",
"packed_bfloat2",
"packed_bfloat3",
"packed_bfloat4",
"packed_float2",
"packed_float3",
"packed_float4",
"packed_long2",
"packed_long3",
"packed_long4",
"packed_vec",
// Metal Shading Language Specification: 2.3 Matrix Data Types
"half2x2",
"half2x3",
"half2x4",
"half3x2",
"half3x3",
"half3x4",
"half4x2",
"half4x3",
"half4x4",
"float2x2",
"float2x3",
"float2x4",
"float3x2",
"float3x3",
"float3x4",
"float4x2",
"float4x3",
"float4x4",
"matrix",
// Metal Shading Language Specification: 2.6 Atomic Data Types
"atomic",
"atomic_int",
"atomic_uint",
"atomic_bool",
"atomic_ulong",
"atomic_float",
// Metal Shading Language Specification: 2.20 Type Conversions and Re-interpreting Data
"as_type",
// Metal Shading Language Specification: 4 Address Spaces
"device",
"constant",
"thread",
"threadgroup",
"threadgroup_imageblock",
"ray_data",
"object_data",
// Metal Shading Language Specification: 5.1 Functions
"vertex",
"fragment",
"kernel",
// Metal Shading Language Specification: 6.1 Namespace and Header Files
"metal",
// C99 / C++ extension:
"restrict",
// Metal reserved types in <metal_types>:
"llong",
"ullong",
"quad",
"complex",
"imaginary",
// Constants in <metal_types>:
"CHAR_BIT",
"SCHAR_MAX",
"SCHAR_MIN",
"UCHAR_MAX",
"CHAR_MAX",
"CHAR_MIN",
"USHRT_MAX",
"SHRT_MAX",
"SHRT_MIN",
"UINT_MAX",
"INT_MAX",
"INT_MIN",
"ULONG_MAX",
"LONG_MAX",
"LONG_MIN",
"ULLONG_MAX",
"LLONG_MAX",
"LLONG_MIN",
"FLT_DIG",
"FLT_MANT_DIG",
"FLT_MAX_10_EXP",
"FLT_MAX_EXP",
"FLT_MIN_10_EXP",
"FLT_MIN_EXP",
"FLT_RADIX",
"FLT_MAX",
"FLT_MIN",
"FLT_EPSILON",
"FLT_DECIMAL_DIG",
"FP_ILOGB0",
"FP_ILOGB0",
"FP_ILOGBNAN",
"FP_ILOGBNAN",
"MAXFLOAT",
"HUGE_VALF",
"INFINITY",
"NAN",
"M_E_F",
"M_LOG2E_F",
"M_LOG10E_F",
"M_LN2_F",
"M_LN10_F",
"M_PI_F",
"M_PI_2_F",
"M_PI_4_F",
"M_1_PI_F",
"M_2_PI_F",
"M_2_SQRTPI_F",
"M_SQRT2_F",
"M_SQRT1_2_F",
"HALF_DIG",
"HALF_MANT_DIG",
"HALF_MAX_10_EXP",
"HALF_MAX_EXP",
"HALF_MIN_10_EXP",
"HALF_MIN_EXP",
"HALF_RADIX",
"HALF_MAX",
"HALF_MIN",
"HALF_EPSILON",
"HALF_DECIMAL_DIG",
"MAXHALF",
"HUGE_VALH",
"M_E_H",
"M_LOG2E_H",
"M_LOG10E_H",
"M_LN2_H",
"M_LN10_H",
"M_PI_H",
"M_PI_2_H",
"M_PI_4_H",
"M_1_PI_H",
"M_2_PI_H",
"M_2_SQRTPI_H",
"M_SQRT2_H",
"M_SQRT1_2_H",
"DBL_DIG",
"DBL_MANT_DIG",
"DBL_MAX_10_EXP",
"DBL_MAX_EXP",
"DBL_MIN_10_EXP",
"DBL_MIN_EXP",
"DBL_RADIX",
"DBL_MAX",
"DBL_MIN",
"DBL_EPSILON",
"DBL_DECIMAL_DIG",
"MAXDOUBLE",
"HUGE_VAL",
"M_E",
"M_LOG2E",
"M_LOG10E",
"M_LN2",
"M_LN10",
"M_PI",
"M_PI_2",
"M_PI_4",
"M_1_PI",
"M_2_PI",
"M_2_SQRTPI",
"M_SQRT2",
"M_SQRT1_2",
// Naga utilities
"DefaultConstructible",
super::writer::FREXP_FUNCTION,
super::writer::MODF_FUNCTION,
super::writer::ARGUMENT_BUFFER_WRAPPER_STRUCT,
];
+700
View File
@@ -0,0 +1,700 @@
/*!
Backend for [MSL][msl] (Metal Shading Language).
This backend does not support the [`SHADER_INT64_ATOMIC_ALL_OPS`][all-atom]
capability.
## Binding model
Metal's bindings are flat per resource. Since there isn't an obvious mapping
from SPIR-V's descriptor sets, we require a separate mapping provided in the options.
This mapping may have one or more resource end points for each descriptor set + index
pair.
## Entry points
Even though MSL and our IR appear to be similar in that the entry points in both can
accept arguments and return values, the restrictions are different.
MSL allows the varyings to be either in separate arguments, or inside a single
`[[stage_in]]` struct. We gather input varyings and form this artificial structure.
We also add all the (non-Private) globals into the arguments.
At the beginning of the entry point, we assign the local constants and re-compose
the arguments as they are declared on IR side, so that the rest of the logic can
pretend that MSL doesn't have all the restrictions it has.
For the result type, if it's a structure, we re-compose it with a temporary value
holding the result.
[msl]: https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
[all-atom]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
*/
use crate::{arena::Handle, proc::index, valid::ModuleInfo};
use std::fmt::{Error as FmtError, Write};
mod keywords;
pub mod sampler;
mod writer;
pub use writer::Writer;
pub type Slot = u8;
pub type InlineSamplerIndex = u8;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum BindSamplerTarget {
Resource(Slot),
Inline(InlineSamplerIndex),
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))]
pub struct BindTarget {
pub buffer: Option<Slot>,
pub texture: Option<Slot>,
pub sampler: Option<BindSamplerTarget>,
pub mutable: bool,
}
// Using `BTreeMap` instead of `HashMap` so that we can hash itself.
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, BindTarget>;
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))]
pub struct EntryPointResources {
pub resources: BindingMap,
pub push_constant_buffer: Option<Slot>,
/// The slot of a buffer that contains an array of `u32`,
/// one for the size of each bound buffer that contains a runtime array,
/// in order of [`crate::GlobalVariable`] declarations.
pub sizes_buffer: Option<Slot>,
}
pub type EntryPointResourceMap = std::collections::BTreeMap<String, EntryPointResources>;
enum ResolvedBinding {
BuiltIn(crate::BuiltIn),
Attribute(u32),
Color {
location: u32,
second_blend_source: bool,
},
User {
prefix: &'static str,
index: u32,
interpolation: Option<ResolvedInterpolation>,
},
Resource(BindTarget),
}
#[derive(Copy, Clone)]
enum ResolvedInterpolation {
CenterPerspective,
CenterNoPerspective,
CentroidPerspective,
CentroidNoPerspective,
SamplePerspective,
SampleNoPerspective,
Flat,
}
// Note: some of these should be removed in favor of proper IR validation.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Format(#[from] FmtError),
#[error("bind target {0:?} is empty")]
UnimplementedBindTarget(BindTarget),
#[error("composing of {0:?} is not implemented yet")]
UnsupportedCompose(Handle<crate::Type>),
#[error("operation {0:?} is not implemented yet")]
UnsupportedBinaryOp(crate::BinaryOperator),
#[error("standard function '{0}' is not implemented yet")]
UnsupportedCall(String),
#[error("feature '{0}' is not implemented yet")]
FeatureNotImplemented(String),
#[error("internal naga error: module should not have validated: {0}")]
GenericValidation(String),
#[error("BuiltIn {0:?} is not supported")]
UnsupportedBuiltIn(crate::BuiltIn),
#[error("capability {0:?} is not supported")]
CapabilityNotSupported(crate::valid::Capabilities),
#[error("attribute '{0}' is not supported for target MSL version")]
UnsupportedAttribute(String),
#[error("function '{0}' is not supported for target MSL version")]
UnsupportedFunction(String),
#[error("can not use writeable storage buffers in fragment stage prior to MSL 1.2")]
UnsupportedWriteableStorageBuffer,
#[error("can not use writeable storage textures in {0:?} stage prior to MSL 1.2")]
UnsupportedWriteableStorageTexture(crate::ShaderStage),
#[error("can not use read-write storage textures prior to MSL 1.2")]
UnsupportedRWStorageTexture,
#[error("array of '{0}' is not supported for target MSL version")]
UnsupportedArrayOf(String),
#[error("array of type '{0:?}' is not supported")]
UnsupportedArrayOfType(Handle<crate::Type>),
#[error("ray tracing is not supported prior to MSL 2.3")]
UnsupportedRayTracing,
#[error("overrides should not be present at this stage")]
Override,
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum EntryPointError {
#[error("global '{0}' doesn't have a binding")]
MissingBinding(String),
#[error("mapping of {0:?} is missing")]
MissingBindTarget(crate::ResourceBinding),
#[error("mapping for push constants is missing")]
MissingPushConstants,
#[error("mapping for sizes buffer is missing")]
MissingSizesBuffer,
}
/// Points in the MSL code where we might emit a pipeline input or output.
///
/// Note that, even though vertex shaders' outputs are always fragment
/// shaders' inputs, we still need to distinguish `VertexOutput` and
/// `FragmentInput`, since there are certain differences in the way
/// [`ResolvedBinding`s] are represented on either side.
///
/// [`ResolvedBinding`s]: ResolvedBinding
#[derive(Clone, Copy, Debug)]
enum LocationMode {
/// Input to the vertex shader.
VertexInput,
/// Output from the vertex shader.
VertexOutput,
/// Input to the fragment shader.
FragmentInput,
/// Output from the fragment shader.
FragmentOutput,
/// Compute shader input or output.
Uniform,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(feature = "deserialize", serde(default))]
pub struct Options {
/// (Major, Minor) target version of the Metal Shading Language.
pub lang_version: (u8, u8),
/// Map of entry-point resources, indexed by entry point function name, to slots.
pub per_entry_point_map: EntryPointResourceMap,
/// Samplers to be inlined into the code.
pub inline_samplers: Vec<sampler::InlineSampler>,
/// Make it possible to link different stages via SPIRV-Cross.
pub spirv_cross_compatibility: bool,
/// Don't panic on missing bindings, instead generate invalid MSL.
pub fake_missing_bindings: bool,
/// Bounds checking policies.
pub bounds_check_policies: index::BoundsCheckPolicies,
/// Should workgroup variables be zero initialized (by polyfilling)?
pub zero_initialize_workgroup_memory: bool,
/// If set, loops will have code injected into them, forcing the compiler
/// to think the number of iterations is bounded.
pub force_loop_bounding: bool,
}
impl Default for Options {
fn default() -> Self {
Options {
lang_version: (1, 0),
per_entry_point_map: EntryPointResourceMap::default(),
inline_samplers: Vec::new(),
spirv_cross_compatibility: false,
fake_missing_bindings: true,
bounds_check_policies: index::BoundsCheckPolicies::default(),
zero_initialize_workgroup_memory: true,
force_loop_bounding: true,
}
}
}
/// Corresponds to [WebGPU `GPUVertexFormat`](
/// https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexformat).
#[repr(u32)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum VertexFormat {
/// One unsigned byte (u8). `u32` in shaders.
Uint8 = 0,
/// Two unsigned bytes (u8). `vec2<u32>` in shaders.
Uint8x2 = 1,
/// Four unsigned bytes (u8). `vec4<u32>` in shaders.
Uint8x4 = 2,
/// One signed byte (i8). `i32` in shaders.
Sint8 = 3,
/// Two signed bytes (i8). `vec2<i32>` in shaders.
Sint8x2 = 4,
/// Four signed bytes (i8). `vec4<i32>` in shaders.
Sint8x4 = 5,
/// One unsigned byte (u8). [0, 255] converted to float [0, 1] `f32` in shaders.
Unorm8 = 6,
/// Two unsigned bytes (u8). [0, 255] converted to float [0, 1] `vec2<f32>` in shaders.
Unorm8x2 = 7,
/// Four unsigned bytes (u8). [0, 255] converted to float [0, 1] `vec4<f32>` in shaders.
Unorm8x4 = 8,
/// One signed byte (i8). [-127, 127] converted to float [-1, 1] `f32` in shaders.
Snorm8 = 9,
/// Two signed bytes (i8). [-127, 127] converted to float [-1, 1] `vec2<f32>` in shaders.
Snorm8x2 = 10,
/// Four signed bytes (i8). [-127, 127] converted to float [-1, 1] `vec4<f32>` in shaders.
Snorm8x4 = 11,
/// One unsigned short (u16). `u32` in shaders.
Uint16 = 12,
/// Two unsigned shorts (u16). `vec2<u32>` in shaders.
Uint16x2 = 13,
/// Four unsigned shorts (u16). `vec4<u32>` in shaders.
Uint16x4 = 14,
/// One signed short (u16). `i32` in shaders.
Sint16 = 15,
/// Two signed shorts (i16). `vec2<i32>` in shaders.
Sint16x2 = 16,
/// Four signed shorts (i16). `vec4<i32>` in shaders.
Sint16x4 = 17,
/// One unsigned short (u16). [0, 65535] converted to float [0, 1] `f32` in shaders.
Unorm16 = 18,
/// Two unsigned shorts (u16). [0, 65535] converted to float [0, 1] `vec2<f32>` in shaders.
Unorm16x2 = 19,
/// Four unsigned shorts (u16). [0, 65535] converted to float [0, 1] `vec4<f32>` in shaders.
Unorm16x4 = 20,
/// One signed short (i16). [-32767, 32767] converted to float [-1, 1] `f32` in shaders.
Snorm16 = 21,
/// Two signed shorts (i16). [-32767, 32767] converted to float [-1, 1] `vec2<f32>` in shaders.
Snorm16x2 = 22,
/// Four signed shorts (i16). [-32767, 32767] converted to float [-1, 1] `vec4<f32>` in shaders.
Snorm16x4 = 23,
/// One half-precision float (no Rust equiv). `f32` in shaders.
Float16 = 24,
/// Two half-precision floats (no Rust equiv). `vec2<f32>` in shaders.
Float16x2 = 25,
/// Four half-precision floats (no Rust equiv). `vec4<f32>` in shaders.
Float16x4 = 26,
/// One single-precision float (f32). `f32` in shaders.
Float32 = 27,
/// Two single-precision floats (f32). `vec2<f32>` in shaders.
Float32x2 = 28,
/// Three single-precision floats (f32). `vec3<f32>` in shaders.
Float32x3 = 29,
/// Four single-precision floats (f32). `vec4<f32>` in shaders.
Float32x4 = 30,
/// One unsigned int (u32). `u32` in shaders.
Uint32 = 31,
/// Two unsigned ints (u32). `vec2<u32>` in shaders.
Uint32x2 = 32,
/// Three unsigned ints (u32). `vec3<u32>` in shaders.
Uint32x3 = 33,
/// Four unsigned ints (u32). `vec4<u32>` in shaders.
Uint32x4 = 34,
/// One signed int (i32). `i32` in shaders.
Sint32 = 35,
/// Two signed ints (i32). `vec2<i32>` in shaders.
Sint32x2 = 36,
/// Three signed ints (i32). `vec3<i32>` in shaders.
Sint32x3 = 37,
/// Four signed ints (i32). `vec4<i32>` in shaders.
Sint32x4 = 38,
/// Three unsigned 10-bit integers and one 2-bit integer, packed into a 32-bit integer (u32). [0, 1024] converted to float [0, 1] `vec4<f32>` in shaders.
#[cfg_attr(
any(feature = "serialize", feature = "deserialize"),
serde(rename = "unorm10-10-10-2")
)]
Unorm10_10_10_2 = 43,
/// Four unsigned 8-bit integers, packed into a 32-bit integer (u32). [0, 255] converted to float [0, 1] `vec4<f32>` in shaders.
#[cfg_attr(
any(feature = "serialize", feature = "deserialize"),
serde(rename = "unorm8x4-bgra")
)]
Unorm8x4Bgra = 44,
}
/// A mapping of vertex buffers and their attributes to shader
/// locations.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct AttributeMapping {
/// Shader location associated with this attribute
pub shader_location: u32,
/// Offset in bytes from start of vertex buffer structure
pub offset: u32,
/// Format code to help us unpack the attribute into the type
/// used by the shader. Codes correspond to a 0-based index of
/// <https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexformat>.
/// The conversion process is described by
/// <https://gpuweb.github.io/gpuweb/#vertex-processing>.
pub format: VertexFormat,
}
/// A description of a vertex buffer with all the information we
/// need to address the attributes within it.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct VertexBufferMapping {
/// Shader location associated with this buffer
pub id: u32,
/// Size of the structure in bytes
pub stride: u32,
/// True if the buffer is indexed by vertex, false if indexed
/// by instance.
pub indexed_by_vertex: bool,
/// Vec of the attributes within the structure
pub attributes: Vec<AttributeMapping>,
}
/// A subset of options that are meant to be changed per pipeline.
#[derive(Debug, Default, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(feature = "deserialize", serde(default))]
pub struct PipelineOptions {
/// Allow `BuiltIn::PointSize` and inject it if doesn't exist.
///
/// Metal doesn't like this for non-point primitive topologies and requires it for
/// point primitive topologies.
///
/// Enable this for vertex shaders with point primitive topologies.
pub allow_and_force_point_size: bool,
/// If set, when generating the Metal vertex shader, transform it
/// to receive the vertex buffers, lengths, and vertex id as args,
/// and bounds-check the vertex id and use the index into the
/// vertex buffers to access attributes, rather than using Metal's
/// [[stage-in]] assembled attribute data. This is true by default,
/// but remains configurable for use by tests via deserialization
/// of this struct. There is no user-facing way to set this value.
pub vertex_pulling_transform: bool,
/// vertex_buffer_mappings are used during shader translation to
/// support vertex pulling.
pub vertex_buffer_mappings: Vec<VertexBufferMapping>,
}
impl Options {
fn resolve_local_binding(
&self,
binding: &crate::Binding,
mode: LocationMode,
) -> Result<ResolvedBinding, Error> {
match *binding {
crate::Binding::BuiltIn(mut built_in) => {
match built_in {
crate::BuiltIn::Position { ref mut invariant } => {
if *invariant && self.lang_version < (2, 1) {
return Err(Error::UnsupportedAttribute("invariant".to_string()));
}
// The 'invariant' attribute may only appear on vertex
// shader outputs, not fragment shader inputs.
if !matches!(mode, LocationMode::VertexOutput) {
*invariant = false;
}
}
crate::BuiltIn::BaseInstance if self.lang_version < (1, 2) => {
return Err(Error::UnsupportedAttribute("base_instance".to_string()));
}
crate::BuiltIn::InstanceIndex if self.lang_version < (1, 2) => {
return Err(Error::UnsupportedAttribute("instance_id".to_string()));
}
// macOS: Since Metal 2.2
// iOS: Since Metal 2.3 (check depends on https://github.com/gfx-rs/naga/issues/2164)
crate::BuiltIn::PrimitiveIndex if self.lang_version < (2, 2) => {
return Err(Error::UnsupportedAttribute("primitive_id".to_string()));
}
_ => {}
}
Ok(ResolvedBinding::BuiltIn(built_in))
}
crate::Binding::Location {
location,
interpolation,
sampling,
second_blend_source,
} => match mode {
LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)),
LocationMode::FragmentOutput => {
if second_blend_source && self.lang_version < (1, 2) {
return Err(Error::UnsupportedAttribute(
"second_blend_source".to_string(),
));
}
Ok(ResolvedBinding::Color {
location,
second_blend_source,
})
}
LocationMode::VertexOutput | LocationMode::FragmentInput => {
Ok(ResolvedBinding::User {
prefix: if self.spirv_cross_compatibility {
"locn"
} else {
"loc"
},
index: location,
interpolation: {
// unwrap: The verifier ensures that vertex shader outputs and fragment
// shader inputs always have fully specified interpolation, and that
// sampling is `None` only for Flat interpolation.
let interpolation = interpolation.unwrap();
let sampling = sampling.unwrap_or(crate::Sampling::Center);
Some(ResolvedInterpolation::from_binding(interpolation, sampling))
},
})
}
LocationMode::Uniform => Err(Error::GenericValidation(format!(
"Unexpected Binding::Location({location}) for the Uniform mode"
))),
},
}
}
fn get_entry_point_resources(&self, ep: &crate::EntryPoint) -> Option<&EntryPointResources> {
self.per_entry_point_map.get(&ep.name)
}
fn get_resource_binding_target(
&self,
ep: &crate::EntryPoint,
res_binding: &crate::ResourceBinding,
) -> Option<&BindTarget> {
self.get_entry_point_resources(ep)
.and_then(|res| res.resources.get(res_binding))
}
fn resolve_resource_binding(
&self,
ep: &crate::EntryPoint,
res_binding: &crate::ResourceBinding,
) -> Result<ResolvedBinding, EntryPointError> {
let target = self.get_resource_binding_target(ep, res_binding);
match target {
Some(target) => Ok(ResolvedBinding::Resource(target.clone())),
None if self.fake_missing_bindings => Ok(ResolvedBinding::User {
prefix: "fake",
index: 0,
interpolation: None,
}),
None => Err(EntryPointError::MissingBindTarget(res_binding.clone())),
}
}
fn resolve_push_constants(
&self,
ep: &crate::EntryPoint,
) -> Result<ResolvedBinding, EntryPointError> {
let slot = self
.get_entry_point_resources(ep)
.and_then(|res| res.push_constant_buffer);
match slot {
Some(slot) => Ok(ResolvedBinding::Resource(BindTarget {
buffer: Some(slot),
..Default::default()
})),
None if self.fake_missing_bindings => Ok(ResolvedBinding::User {
prefix: "fake",
index: 0,
interpolation: None,
}),
None => Err(EntryPointError::MissingPushConstants),
}
}
fn resolve_sizes_buffer(
&self,
ep: &crate::EntryPoint,
) -> Result<ResolvedBinding, EntryPointError> {
let slot = self
.get_entry_point_resources(ep)
.and_then(|res| res.sizes_buffer);
match slot {
Some(slot) => Ok(ResolvedBinding::Resource(BindTarget {
buffer: Some(slot),
..Default::default()
})),
None if self.fake_missing_bindings => Ok(ResolvedBinding::User {
prefix: "fake",
index: 0,
interpolation: None,
}),
None => Err(EntryPointError::MissingSizesBuffer),
}
}
}
impl ResolvedBinding {
fn as_inline_sampler<'a>(&self, options: &'a Options) -> Option<&'a sampler::InlineSampler> {
match *self {
Self::Resource(BindTarget {
sampler: Some(BindSamplerTarget::Inline(index)),
..
}) => Some(&options.inline_samplers[index as usize]),
_ => None,
}
}
const fn as_bind_target(&self) -> Option<&BindTarget> {
match *self {
Self::Resource(ref target) => Some(target),
_ => None,
}
}
fn try_fmt<W: Write>(&self, out: &mut W) -> Result<(), Error> {
write!(out, " [[")?;
match *self {
Self::BuiltIn(built_in) => {
use crate::BuiltIn as Bi;
let name = match built_in {
Bi::Position { invariant: false } => "position",
Bi::Position { invariant: true } => "position, invariant",
// vertex
Bi::BaseInstance => "base_instance",
Bi::BaseVertex => "base_vertex",
Bi::ClipDistance => "clip_distance",
Bi::InstanceIndex => "instance_id",
Bi::PointSize => "point_size",
Bi::VertexIndex => "vertex_id",
// fragment
Bi::FragDepth => "depth(any)",
Bi::PointCoord => "point_coord",
Bi::FrontFacing => "front_facing",
Bi::PrimitiveIndex => "primitive_id",
Bi::SampleIndex => "sample_id",
Bi::SampleMask => "sample_mask",
// compute
Bi::GlobalInvocationId => "thread_position_in_grid",
Bi::LocalInvocationId => "thread_position_in_threadgroup",
Bi::LocalInvocationIndex => "thread_index_in_threadgroup",
Bi::WorkGroupId => "threadgroup_position_in_grid",
Bi::WorkGroupSize => "dispatch_threads_per_threadgroup",
Bi::NumWorkGroups => "threadgroups_per_grid",
// subgroup
Bi::NumSubgroups => "simdgroups_per_threadgroup",
Bi::SubgroupId => "simdgroup_index_in_threadgroup",
Bi::SubgroupSize => "threads_per_simdgroup",
Bi::SubgroupInvocationId => "thread_index_in_simdgroup",
Bi::CullDistance | Bi::ViewIndex | Bi::DrawID => {
return Err(Error::UnsupportedBuiltIn(built_in))
}
};
write!(out, "{name}")?;
}
Self::Attribute(index) => write!(out, "attribute({index})")?,
Self::Color {
location,
second_blend_source,
} => {
if second_blend_source {
write!(out, "color({location}) index(1)")?
} else {
write!(out, "color({location})")?
}
}
Self::User {
prefix,
index,
interpolation,
} => {
write!(out, "user({prefix}{index})")?;
if let Some(interpolation) = interpolation {
write!(out, ", ")?;
interpolation.try_fmt(out)?;
}
}
Self::Resource(ref target) => {
if let Some(id) = target.buffer {
write!(out, "buffer({id})")?;
} else if let Some(id) = target.texture {
write!(out, "texture({id})")?;
} else if let Some(BindSamplerTarget::Resource(id)) = target.sampler {
write!(out, "sampler({id})")?;
} else {
return Err(Error::UnimplementedBindTarget(target.clone()));
}
}
}
write!(out, "]]")?;
Ok(())
}
}
impl ResolvedInterpolation {
const fn from_binding(interpolation: crate::Interpolation, sampling: crate::Sampling) -> Self {
use crate::Interpolation as I;
use crate::Sampling as S;
match (interpolation, sampling) {
(I::Perspective, S::Center) => Self::CenterPerspective,
(I::Perspective, S::Centroid) => Self::CentroidPerspective,
(I::Perspective, S::Sample) => Self::SamplePerspective,
(I::Linear, S::Center) => Self::CenterNoPerspective,
(I::Linear, S::Centroid) => Self::CentroidNoPerspective,
(I::Linear, S::Sample) => Self::SampleNoPerspective,
(I::Flat, _) => Self::Flat,
_ => unreachable!(),
}
}
fn try_fmt<W: Write>(self, out: &mut W) -> Result<(), Error> {
let identifier = match self {
Self::CenterPerspective => "center_perspective",
Self::CenterNoPerspective => "center_no_perspective",
Self::CentroidPerspective => "centroid_perspective",
Self::CentroidNoPerspective => "centroid_no_perspective",
Self::SamplePerspective => "sample_perspective",
Self::SampleNoPerspective => "sample_no_perspective",
Self::Flat => "flat",
};
out.write_str(identifier)?;
Ok(())
}
}
/// Information about a translated module that is required
/// for the use of the result.
pub struct TranslationInfo {
/// Mapping of the entry point names. Each item in the array
/// corresponds to an entry point index.
///
///Note: Some entry points may fail translation because of missing bindings.
pub entry_point_names: Vec<Result<String, EntryPointError>>,
}
pub fn write_string(
module: &crate::Module,
info: &ModuleInfo,
options: &Options,
pipeline_options: &PipelineOptions,
) -> Result<(String, TranslationInfo), Error> {
let mut w = Writer::new(String::new());
let info = w.write(module, info, options, pipeline_options)?;
Ok((w.finish(), info))
}
#[test]
fn test_error_size() {
use std::mem::size_of;
assert_eq!(size_of::<Error>(), 32);
}
+176
View File
@@ -0,0 +1,176 @@
#[cfg(feature = "deserialize")]
use serde::Deserialize;
#[cfg(feature = "serialize")]
use serde::Serialize;
use std::{num::NonZeroU32, ops::Range};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum Coord {
Normalized,
Pixel,
}
impl Default for Coord {
fn default() -> Self {
Self::Normalized
}
}
impl Coord {
pub const fn as_str(&self) -> &'static str {
match *self {
Self::Normalized => "normalized",
Self::Pixel => "pixel",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum Address {
Repeat,
MirroredRepeat,
ClampToEdge,
ClampToZero,
ClampToBorder,
}
impl Default for Address {
fn default() -> Self {
Self::ClampToEdge
}
}
impl Address {
pub const fn as_str(&self) -> &'static str {
match *self {
Self::Repeat => "repeat",
Self::MirroredRepeat => "mirrored_repeat",
Self::ClampToEdge => "clamp_to_edge",
Self::ClampToZero => "clamp_to_zero",
Self::ClampToBorder => "clamp_to_border",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum BorderColor {
TransparentBlack,
OpaqueBlack,
OpaqueWhite,
}
impl Default for BorderColor {
fn default() -> Self {
Self::TransparentBlack
}
}
impl BorderColor {
pub const fn as_str(&self) -> &'static str {
match *self {
Self::TransparentBlack => "transparent_black",
Self::OpaqueBlack => "opaque_black",
Self::OpaqueWhite => "opaque_white",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum Filter {
Nearest,
Linear,
}
impl Filter {
pub const fn as_str(&self) -> &'static str {
match *self {
Self::Nearest => "nearest",
Self::Linear => "linear",
}
}
}
impl Default for Filter {
fn default() -> Self {
Self::Nearest
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum CompareFunc {
Never,
Less,
LessEqual,
Greater,
GreaterEqual,
Equal,
NotEqual,
Always,
}
impl Default for CompareFunc {
fn default() -> Self {
Self::Never
}
}
impl CompareFunc {
pub const fn as_str(&self) -> &'static str {
match *self {
Self::Never => "never",
Self::Less => "less",
Self::LessEqual => "less_equal",
Self::Greater => "greater",
Self::GreaterEqual => "greater_equal",
Self::Equal => "equal",
Self::NotEqual => "not_equal",
Self::Always => "always",
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub struct InlineSampler {
pub coord: Coord,
pub address: [Address; 3],
pub border_color: BorderColor,
pub mag_filter: Filter,
pub min_filter: Filter,
pub mip_filter: Option<Filter>,
pub lod_clamp: Option<Range<f32>>,
pub max_anisotropy: Option<NonZeroU32>,
pub compare_func: CompareFunc,
}
impl Eq for InlineSampler {}
#[allow(renamed_and_removed_lints)]
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for InlineSampler {
fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
self.coord.hash(hasher);
self.address.hash(hasher);
self.border_color.hash(hasher);
self.mag_filter.hash(hasher);
self.min_filter.hash(hasher);
self.mip_filter.hash(hasher);
self.lod_clamp
.as_ref()
.map(|range| (range.start.to_bits(), range.end.to_bits()))
.hash(hasher);
self.max_anisotropy.hash(hasher);
self.compare_func.hash(hasher);
}
}
+6352
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+3058
View File
File diff suppressed because it is too large Load Diff
+149
View File
@@ -0,0 +1,149 @@
use crate::{Handle, UniqueArena};
use spirv::Word;
pub(super) fn bytes_to_words(bytes: &[u8]) -> Vec<Word> {
bytes
.chunks(4)
.map(|chars| chars.iter().rev().fold(0u32, |u, c| (u << 8) | *c as u32))
.collect()
}
pub(super) fn string_to_words(input: &str) -> Vec<Word> {
let bytes = input.as_bytes();
str_bytes_to_words(bytes)
}
pub(super) fn str_bytes_to_words(bytes: &[u8]) -> Vec<Word> {
let mut words = bytes_to_words(bytes);
if bytes.len() % 4 == 0 {
// nul-termination
words.push(0x0u32);
}
words
}
/// split a string into chunks and keep utf8 valid
#[allow(unstable_name_collisions)]
pub(super) fn string_to_byte_chunks(input: &str, limit: usize) -> Vec<&[u8]> {
let mut offset: usize = 0;
let mut start: usize = 0;
let mut words = vec![];
while offset < input.len() {
offset = input.floor_char_boundary(offset + limit);
words.push(input[start..offset].as_bytes());
start = offset;
}
words
}
pub(super) const fn map_storage_class(space: crate::AddressSpace) -> spirv::StorageClass {
match space {
crate::AddressSpace::Handle => spirv::StorageClass::UniformConstant,
crate::AddressSpace::Function => spirv::StorageClass::Function,
crate::AddressSpace::Private => spirv::StorageClass::Private,
crate::AddressSpace::Storage { .. } => spirv::StorageClass::StorageBuffer,
crate::AddressSpace::Uniform => spirv::StorageClass::Uniform,
crate::AddressSpace::WorkGroup => spirv::StorageClass::Workgroup,
crate::AddressSpace::PushConstant => spirv::StorageClass::PushConstant,
}
}
pub(super) fn contains_builtin(
binding: Option<&crate::Binding>,
ty: Handle<crate::Type>,
arena: &UniqueArena<crate::Type>,
built_in: crate::BuiltIn,
) -> bool {
if let Some(&crate::Binding::BuiltIn(bi)) = binding {
bi == built_in
} else if let crate::TypeInner::Struct { ref members, .. } = arena[ty].inner {
members
.iter()
.any(|member| contains_builtin(member.binding.as_ref(), member.ty, arena, built_in))
} else {
false // unreachable
}
}
impl crate::AddressSpace {
pub(super) const fn to_spirv_semantics_and_scope(
self,
) -> (spirv::MemorySemantics, spirv::Scope) {
match self {
Self::Storage { .. } => (spirv::MemorySemantics::UNIFORM_MEMORY, spirv::Scope::Device),
Self::WorkGroup => (
spirv::MemorySemantics::WORKGROUP_MEMORY,
spirv::Scope::Workgroup,
),
_ => (spirv::MemorySemantics::empty(), spirv::Scope::Invocation),
}
}
}
/// Return true if the global requires a type decorated with `Block`.
///
/// See [`back::spv::GlobalVariable`] for details.
///
/// [`back::spv::GlobalVariable`]: super::GlobalVariable
pub fn global_needs_wrapper(ir_module: &crate::Module, var: &crate::GlobalVariable) -> bool {
match var.space {
crate::AddressSpace::Uniform
| crate::AddressSpace::Storage { .. }
| crate::AddressSpace::PushConstant => {}
_ => return false,
};
match ir_module.types[var.ty].inner {
crate::TypeInner::Struct {
ref members,
span: _,
} => match members.last() {
Some(member) => match ir_module.types[member.ty].inner {
// Structs with dynamically sized arrays can't be copied and can't be wrapped.
crate::TypeInner::Array {
size: crate::ArraySize::Dynamic,
..
} => false,
_ => true,
},
None => false,
},
crate::TypeInner::BindingArray { .. } => false,
// if it's not a structure or a binding array, let's wrap it to be able to put "Block"
_ => true,
}
}
///HACK: this is taken from std unstable, remove it when std's floor_char_boundary is stable
trait U8Internal {
fn is_utf8_char_boundary(&self) -> bool;
}
impl U8Internal for u8 {
fn is_utf8_char_boundary(&self) -> bool {
// This is bit magic equivalent to: b < 128 || b >= 192
(*self as i8) >= -0x40
}
}
trait StrUnstable {
fn floor_char_boundary(&self, index: usize) -> usize;
}
impl StrUnstable for str {
fn floor_char_boundary(&self, index: usize) -> usize {
if index >= self.len() {
self.len()
} else {
let lower_bound = index.saturating_sub(3);
let new_index = self.as_bytes()[lower_bound..=index]
.iter()
.rposition(|b| b.is_utf8_char_boundary());
// SAFETY: we know that the character boundary will be within four bytes
unsafe { lower_bound + new_index.unwrap_unchecked() }
}
}
}
+1305
View File
File diff suppressed because it is too large Load Diff
+601
View File
@@ -0,0 +1,601 @@
/*!
Bounds-checking for SPIR-V output.
*/
use super::{
helpers::{global_needs_wrapper, map_storage_class},
selection::Selection,
Block, BlockContext, Error, IdGenerator, Instruction, Word,
};
use crate::{
arena::Handle,
proc::{index::GuardedIndex, BoundsCheckPolicy},
};
/// The results of performing a bounds check.
///
/// On success, [`write_bounds_check`](BlockContext::write_bounds_check)
/// returns a value of this type. The caller can assume that the right
/// policy has been applied, and simply do what the variant says.
#[derive(Debug)]
pub(super) enum BoundsCheckResult {
/// The index is statically known and in bounds, with the given value.
KnownInBounds(u32),
/// The given instruction computes the index to be used.
///
/// When [`BoundsCheckPolicy::Restrict`] is in force, this is a
/// clamped version of the index the user supplied.
///
/// When [`BoundsCheckPolicy::Unchecked`] is in force, this is
/// simply the index the user supplied. This variant indicates
/// that we couldn't prove statically that the index was in
/// bounds; otherwise we would have returned [`KnownInBounds`].
///
/// [`KnownInBounds`]: BoundsCheckResult::KnownInBounds
Computed(Word),
/// The given instruction computes a boolean condition which is true
/// if the index is in bounds.
///
/// This is returned when [`BoundsCheckPolicy::ReadZeroSkipWrite`]
/// is in force.
Conditional {
/// The access should only be permitted if this value is true.
condition_id: Word,
/// The access should use this index value.
index_id: Word,
},
}
/// A value that we either know at translation time, or need to compute at runtime.
#[derive(Copy, Clone)]
pub(super) enum MaybeKnown<T> {
/// The value is known at shader translation time.
Known(T),
/// The value is computed by the instruction with the given id.
Computed(Word),
}
impl BlockContext<'_> {
/// Emit code to compute the length of a run-time array.
///
/// Given `array`, an expression referring a runtime-sized array, return the
/// instruction id for the array's length.
///
/// Runtime-sized arrays may only appear in the values of global
/// variables, which must have one of the following Naga types:
///
/// 1. A runtime-sized array.
/// 2. A struct whose last member is a runtime-sized array.
/// 3. A binding array of 2.
///
/// Thus, the expression `array` has the form of:
///
/// - An optional [`AccessIndex`], for case 2, applied to...
/// - An optional [`Access`] or [`AccessIndex`], for case 3, applied to...
/// - A [`GlobalVariable`].
///
/// The generated SPIR-V takes into account wrapped globals; see
/// [`back::spv::GlobalVariable`] for details.
///
/// [`GlobalVariable`]: crate::Expression::GlobalVariable
/// [`AccessIndex`]: crate::Expression::AccessIndex
/// [`Access`]: crate::Expression::Access
/// [`base`]: crate::Expression::Access::base
/// [`back::spv::GlobalVariable`]: super::GlobalVariable
pub(super) fn write_runtime_array_length(
&mut self,
array: Handle<crate::Expression>,
block: &mut Block,
) -> Result<Word, Error> {
// The index into the binding array, if any.
let binding_array_index_id: Option<Word>;
// The handle to the Naga IR global we're referring to.
let global_handle: Handle<crate::GlobalVariable>;
// At the Naga type level, if the runtime-sized array is the final member of a
// struct, this is that member's index.
//
// This does not cover wrappers: if this backend wrapped the Naga global's
// type in a synthetic SPIR-V struct (see `global_needs_wrapper`), this is
// `None`.
let opt_last_member_index: Option<u32>;
// Inspect `array` and decide whether we have a binding array and/or an
// enclosing struct.
match self.ir_function.expressions[array] {
crate::Expression::AccessIndex { base, index } => {
match self.ir_function.expressions[base] {
crate::Expression::AccessIndex {
base: base_outer,
index: index_outer,
} => match self.ir_function.expressions[base_outer] {
// An `AccessIndex` of an `AccessIndex` must be a
// binding array holding structs whose last members are
// runtime-sized arrays.
crate::Expression::GlobalVariable(handle) => {
let index_id = self.get_index_constant(index_outer);
binding_array_index_id = Some(index_id);
global_handle = handle;
opt_last_member_index = Some(index);
}
_ => {
return Err(Error::Validation(
"array length expression: AccessIndex(AccessIndex(Global))",
))
}
},
crate::Expression::Access {
base: base_outer,
index: index_outer,
} => match self.ir_function.expressions[base_outer] {
// Similarly, an `AccessIndex` of an `Access` must be a
// binding array holding structs whose last members are
// runtime-sized arrays.
crate::Expression::GlobalVariable(handle) => {
let index_id = self.cached[index_outer];
binding_array_index_id = Some(index_id);
global_handle = handle;
opt_last_member_index = Some(index);
}
_ => {
return Err(Error::Validation(
"array length expression: AccessIndex(Access(Global))",
))
}
},
crate::Expression::GlobalVariable(handle) => {
// An outer `AccessIndex` applied directly to a
// `GlobalVariable`. Since binding arrays can only contain
// structs, this must be referring to the last member of a
// struct that is a runtime-sized array.
binding_array_index_id = None;
global_handle = handle;
opt_last_member_index = Some(index);
}
_ => {
return Err(Error::Validation(
"array length expression: AccessIndex(<unexpected>)",
))
}
}
}
crate::Expression::GlobalVariable(handle) => {
// A direct reference to a global variable. This must hold the
// runtime-sized array directly.
binding_array_index_id = None;
global_handle = handle;
opt_last_member_index = None;
}
_ => return Err(Error::Validation("array length expression case-4")),
};
// The verifier should have checked this, but make sure the inspection above
// agrees with the type about whether a binding array is involved.
//
// Eventually we do want to support `binding_array<array<T>>`. This check
// ensures that whoever relaxes the validator will get an error message from
// us, not just bogus SPIR-V.
let global = &self.ir_module.global_variables[global_handle];
match (
&self.ir_module.types[global.ty].inner,
binding_array_index_id,
) {
(&crate::TypeInner::BindingArray { .. }, Some(_)) => {}
(_, None) => {}
_ => {
return Err(Error::Validation(
"array length expression: bad binding array inference",
))
}
}
// SPIR-V allows runtime-sized arrays to appear only as the last member of a
// struct. Determine this member's index.
let gvar = self.writer.global_variables[global_handle].clone();
let global = &self.ir_module.global_variables[global_handle];
let needs_wrapper = global_needs_wrapper(self.ir_module, global);
let (last_member_index, gvar_id) = match (opt_last_member_index, needs_wrapper) {
(Some(index), false) => {
// At the Naga type level, the runtime-sized array appears as the
// final member of a struct, whose index is `index`. We didn't need to
// wrap this, since the Naga type meets SPIR-V's requirements already.
(index, gvar.access_id)
}
(None, true) => {
// At the Naga type level, the runtime-sized array does not appear
// within a struct. We wrapped this in an OpTypeStruct with nothing
// else in it, so the index is zero. OpArrayLength wants the pointer
// to the wrapper struct, so use `gvar.var_id`.
(0, gvar.var_id)
}
_ => {
return Err(Error::Validation(
"array length expression: bad SPIR-V wrapper struct inference",
));
}
};
let structure_id = match binding_array_index_id {
// We are indexing inside a binding array, generate the access op.
Some(index_id) => {
let element_type_id = match self.ir_module.types[global.ty].inner {
crate::TypeInner::BindingArray { base, size: _ } => {
let class = map_storage_class(global.space);
self.get_pointer_id(base, class)
}
_ => return Err(Error::Validation("array length expression case-5")),
};
let structure_id = self.gen_id();
block.body.push(Instruction::access_chain(
element_type_id,
structure_id,
gvar_id,
&[index_id],
));
structure_id
}
None => gvar_id,
};
let length_id = self.gen_id();
block.body.push(Instruction::array_length(
self.writer.get_uint_type_id(),
length_id,
structure_id,
last_member_index,
));
Ok(length_id)
}
/// Compute the length of a subscriptable value.
///
/// Given `sequence`, an expression referring to some indexable type, return
/// its length. The result may either be computed by SPIR-V instructions, or
/// known at shader translation time.
///
/// `sequence` may be a `Vector`, `Matrix`, or `Array`, a `Pointer` to any
/// of those, or a `ValuePointer`. An array may be fixed-size, dynamically
/// sized, or use a specializable constant as its length.
fn write_sequence_length(
&mut self,
sequence: Handle<crate::Expression>,
block: &mut Block,
) -> Result<MaybeKnown<u32>, Error> {
let sequence_ty = self.fun_info[sequence].ty.inner_with(&self.ir_module.types);
match sequence_ty.indexable_length(self.ir_module) {
Ok(crate::proc::IndexableLength::Known(known_length)) => {
Ok(MaybeKnown::Known(known_length))
}
Ok(crate::proc::IndexableLength::Pending) => {
unreachable!()
}
Ok(crate::proc::IndexableLength::Dynamic) => {
let length_id = self.write_runtime_array_length(sequence, block)?;
Ok(MaybeKnown::Computed(length_id))
}
Err(err) => {
log::error!("Sequence length for {:?} failed: {}", sequence, err);
Err(Error::Validation("indexable length"))
}
}
}
/// Compute the maximum valid index of a subscriptable value.
///
/// Given `sequence`, an expression referring to some indexable type, return
/// its maximum valid index - one less than its length. The result may
/// either be computed, or known at shader translation time.
///
/// `sequence` may be a `Vector`, `Matrix`, or `Array`, a `Pointer` to any
/// of those, or a `ValuePointer`. An array may be fixed-size, dynamically
/// sized, or use a specializable constant as its length.
fn write_sequence_max_index(
&mut self,
sequence: Handle<crate::Expression>,
block: &mut Block,
) -> Result<MaybeKnown<u32>, Error> {
match self.write_sequence_length(sequence, block)? {
MaybeKnown::Known(known_length) => {
// We should have thrown out all attempts to subscript zero-length
// sequences during validation, so the following subtraction should never
// underflow.
assert!(known_length > 0);
// Compute the max index from the length now.
Ok(MaybeKnown::Known(known_length - 1))
}
MaybeKnown::Computed(length_id) => {
// Emit code to compute the max index from the length.
let const_one_id = self.get_index_constant(1);
let max_index_id = self.gen_id();
block.body.push(Instruction::binary(
spirv::Op::ISub,
self.writer.get_uint_type_id(),
max_index_id,
length_id,
const_one_id,
));
Ok(MaybeKnown::Computed(max_index_id))
}
}
}
/// Restrict an index to be in range for a vector, matrix, or array.
///
/// This is used to implement `BoundsCheckPolicy::Restrict`. An in-bounds
/// index is left unchanged. An out-of-bounds index is replaced with some
/// arbitrary in-bounds index. Note,this is not necessarily clamping; for
/// example, negative indices might be changed to refer to the last element
/// of the sequence, not the first, as clamping would do.
///
/// Either return the restricted index value, if known, or add instructions
/// to `block` to compute it, and return the id of the result. See the
/// documentation for `BoundsCheckResult` for details.
///
/// The `sequence` expression may be a `Vector`, `Matrix`, or `Array`, a
/// `Pointer` to any of those, or a `ValuePointer`. An array may be
/// fixed-size, dynamically sized, or use a specializable constant as its
/// length.
pub(super) fn write_restricted_index(
&mut self,
sequence: Handle<crate::Expression>,
index: GuardedIndex,
block: &mut Block,
) -> Result<BoundsCheckResult, Error> {
let max_index = self.write_sequence_max_index(sequence, block)?;
// If both are known, we can compute the index to be used
// right now.
if let (GuardedIndex::Known(index), MaybeKnown::Known(max_index)) = (index, max_index) {
let restricted = std::cmp::min(index, max_index);
return Ok(BoundsCheckResult::KnownInBounds(restricted));
}
let index_id = match index {
GuardedIndex::Known(value) => self.get_index_constant(value),
GuardedIndex::Expression(expr) => self.cached[expr],
};
let max_index_id = match max_index {
MaybeKnown::Known(value) => self.get_index_constant(value),
MaybeKnown::Computed(id) => id,
};
// One or the other of the index or length is dynamic, so emit code for
// BoundsCheckPolicy::Restrict.
let restricted_index_id = self.gen_id();
block.body.push(Instruction::ext_inst(
self.writer.gl450_ext_inst_id,
spirv::GLOp::UMin,
self.writer.get_uint_type_id(),
restricted_index_id,
&[index_id, max_index_id],
));
Ok(BoundsCheckResult::Computed(restricted_index_id))
}
/// Write an index bounds comparison to `block`, if needed.
///
/// This is used to implement [`BoundsCheckPolicy::ReadZeroSkipWrite`].
///
/// If we're able to determine statically that `index` is in bounds for
/// `sequence`, return `KnownInBounds(value)`, where `value` is the actual
/// value of the index. (In principle, one could know that the index is in
/// bounds without knowing its specific value, but in our simple-minded
/// situation, we always know it.)
///
/// If instead we must generate code to perform the comparison at run time,
/// return `Conditional(comparison_id)`, where `comparison_id` is an
/// instruction producing a boolean value that is true if `index` is in
/// bounds for `sequence`.
///
/// The `sequence` expression may be a `Vector`, `Matrix`, or `Array`, a
/// `Pointer` to any of those, or a `ValuePointer`. An array may be
/// fixed-size, dynamically sized, or use a specializable constant as its
/// length.
fn write_index_comparison(
&mut self,
sequence: Handle<crate::Expression>,
index: GuardedIndex,
block: &mut Block,
) -> Result<BoundsCheckResult, Error> {
let length = self.write_sequence_length(sequence, block)?;
// If both are known, we can decide whether the index is in
// bounds right now.
if let (GuardedIndex::Known(index), MaybeKnown::Known(length)) = (index, length) {
if index < length {
return Ok(BoundsCheckResult::KnownInBounds(index));
}
// In theory, when `index` is bad, we could return a new
// `KnownOutOfBounds` variant here. But it's simpler just to fall
// through and let the bounds check take place. The shader is broken
// anyway, so it doesn't make sense to invest in emitting the ideal
// code for it.
}
let index_id = match index {
GuardedIndex::Known(value) => self.get_index_constant(value),
GuardedIndex::Expression(expr) => self.cached[expr],
};
let length_id = match length {
MaybeKnown::Known(value) => self.get_index_constant(value),
MaybeKnown::Computed(id) => id,
};
// Compare the index against the length.
let condition_id = self.gen_id();
block.body.push(Instruction::binary(
spirv::Op::ULessThan,
self.writer.get_bool_type_id(),
condition_id,
index_id,
length_id,
));
// Indicate that we did generate the check.
Ok(BoundsCheckResult::Conditional {
condition_id,
index_id,
})
}
/// Emit a conditional load for `BoundsCheckPolicy::ReadZeroSkipWrite`.
///
/// Generate code to load a value of `result_type` if `condition` is true,
/// and generate a null value of that type if it is false. Call `emit_load`
/// to emit the instructions to perform the load. Return the id of the
/// merged value of the two branches.
pub(super) fn write_conditional_indexed_load<F>(
&mut self,
result_type: Word,
condition: Word,
block: &mut Block,
emit_load: F,
) -> Word
where
F: FnOnce(&mut IdGenerator, &mut Block) -> Word,
{
// For the out-of-bounds case, we produce a zero value.
let null_id = self.writer.get_constant_null(result_type);
let mut selection = Selection::start(block, result_type);
// As it turns out, we don't actually need a full 'if-then-else'
// structure for this: SPIR-V constants are declared up front, so the
// 'else' block would have no instructions. Instead we emit something
// like this:
//
// result = zero;
// if in_bounds {
// result = do the load;
// }
// use result;
// Continue only if the index was in bounds. Otherwise, branch to the
// merge block.
selection.if_true(self, condition, null_id);
// The in-bounds path. Perform the access and the load.
let loaded_value = emit_load(&mut self.writer.id_gen, selection.block());
selection.finish(self, loaded_value)
}
/// Emit code for bounds checks for an array, vector, or matrix access.
///
/// This tries to handle all the critical steps for bounds checks:
///
/// - First, select the appropriate bounds check policy for `base`,
/// depending on its address space.
///
/// - Next, analyze `index` to see if its value is known at
/// compile time, in which case we can decide statically whether
/// the index is in bounds.
///
/// - If the index's value is not known at compile time, emit code to:
///
/// - restrict its value (for [`BoundsCheckPolicy::Restrict`]), or
///
/// - check whether it's in bounds (for
/// [`BoundsCheckPolicy::ReadZeroSkipWrite`]).
///
/// Return a [`BoundsCheckResult`] indicating how the index should be
/// consumed. See that type's documentation for details.
pub(super) fn write_bounds_check(
&mut self,
base: Handle<crate::Expression>,
mut index: GuardedIndex,
block: &mut Block,
) -> Result<BoundsCheckResult, Error> {
// If the value of `index` is known at compile time, find it now.
index.try_resolve_to_constant(&self.ir_function.expressions, self.ir_module);
let policy = self.writer.bounds_check_policies.choose_policy(
base,
&self.ir_module.types,
self.fun_info,
);
Ok(match policy {
BoundsCheckPolicy::Restrict => self.write_restricted_index(base, index, block)?,
BoundsCheckPolicy::ReadZeroSkipWrite => {
self.write_index_comparison(base, index, block)?
}
BoundsCheckPolicy::Unchecked => match index {
GuardedIndex::Known(value) => BoundsCheckResult::KnownInBounds(value),
GuardedIndex::Expression(expr) => BoundsCheckResult::Computed(self.cached[expr]),
},
})
}
/// Emit code to subscript a vector by value with a computed index.
///
/// Return the id of the element value.
pub(super) fn write_vector_access(
&mut self,
expr_handle: Handle<crate::Expression>,
base: Handle<crate::Expression>,
index: Handle<crate::Expression>,
block: &mut Block,
) -> Result<Word, Error> {
let result_type_id = self.get_expression_type_id(&self.fun_info[expr_handle].ty);
let base_id = self.cached[base];
let index = GuardedIndex::Expression(index);
let result_id = match self.write_bounds_check(base, index, block)? {
BoundsCheckResult::KnownInBounds(known_index) => {
let result_id = self.gen_id();
block.body.push(Instruction::composite_extract(
result_type_id,
result_id,
base_id,
&[known_index],
));
result_id
}
BoundsCheckResult::Computed(computed_index_id) => {
let result_id = self.gen_id();
block.body.push(Instruction::vector_extract_dynamic(
result_type_id,
result_id,
base_id,
computed_index_id,
));
result_id
}
BoundsCheckResult::Conditional {
condition_id,
index_id,
} => {
// Run-time bounds checks were required. Emit
// conditional load.
self.write_conditional_indexed_load(
result_type_id,
condition_id,
block,
|id_gen, block| {
// The in-bounds path. Generate the access.
let element_id = id_gen.next();
block.body.push(Instruction::vector_extract_dynamic(
result_type_id,
element_id,
base_id,
index_id,
));
element_id
},
)
}
};
Ok(result_id)
}
}
File diff suppressed because it is too large Load Diff
+210
View File
@@ -0,0 +1,210 @@
use super::{Instruction, LogicalLayout, PhysicalLayout};
use spirv::{Op, Word, MAGIC_NUMBER};
use std::iter;
// https://github.com/KhronosGroup/SPIRV-Headers/pull/195
const GENERATOR: Word = 28;
impl PhysicalLayout {
pub(super) const fn new(version: Word) -> Self {
PhysicalLayout {
magic_number: MAGIC_NUMBER,
version,
generator: GENERATOR,
bound: 0,
instruction_schema: 0x0u32,
}
}
pub(super) fn in_words(&self, sink: &mut impl Extend<Word>) {
sink.extend(iter::once(self.magic_number));
sink.extend(iter::once(self.version));
sink.extend(iter::once(self.generator));
sink.extend(iter::once(self.bound));
sink.extend(iter::once(self.instruction_schema));
}
}
impl super::recyclable::Recyclable for PhysicalLayout {
fn recycle(self) -> Self {
PhysicalLayout {
magic_number: self.magic_number,
version: self.version,
generator: self.generator,
instruction_schema: self.instruction_schema,
bound: 0,
}
}
}
impl LogicalLayout {
pub(super) fn in_words(&self, sink: &mut impl Extend<Word>) {
sink.extend(self.capabilities.iter().cloned());
sink.extend(self.extensions.iter().cloned());
sink.extend(self.ext_inst_imports.iter().cloned());
sink.extend(self.memory_model.iter().cloned());
sink.extend(self.entry_points.iter().cloned());
sink.extend(self.execution_modes.iter().cloned());
sink.extend(self.debugs.iter().cloned());
sink.extend(self.annotations.iter().cloned());
sink.extend(self.declarations.iter().cloned());
sink.extend(self.function_declarations.iter().cloned());
sink.extend(self.function_definitions.iter().cloned());
}
}
impl super::recyclable::Recyclable for LogicalLayout {
fn recycle(self) -> Self {
Self {
capabilities: self.capabilities.recycle(),
extensions: self.extensions.recycle(),
ext_inst_imports: self.ext_inst_imports.recycle(),
memory_model: self.memory_model.recycle(),
entry_points: self.entry_points.recycle(),
execution_modes: self.execution_modes.recycle(),
debugs: self.debugs.recycle(),
annotations: self.annotations.recycle(),
declarations: self.declarations.recycle(),
function_declarations: self.function_declarations.recycle(),
function_definitions: self.function_definitions.recycle(),
}
}
}
impl Instruction {
pub(super) const fn new(op: Op) -> Self {
Instruction {
op,
wc: 1, // Always start at 1 for the first word (OP + WC),
type_id: None,
result_id: None,
operands: vec![],
}
}
#[allow(clippy::panic)]
pub(super) fn set_type(&mut self, id: Word) {
assert!(self.type_id.is_none(), "Type can only be set once");
self.type_id = Some(id);
self.wc += 1;
}
#[allow(clippy::panic)]
pub(super) fn set_result(&mut self, id: Word) {
assert!(self.result_id.is_none(), "Result can only be set once");
self.result_id = Some(id);
self.wc += 1;
}
pub(super) fn add_operand(&mut self, operand: Word) {
self.operands.push(operand);
self.wc += 1;
}
pub(super) fn add_operands(&mut self, operands: Vec<Word>) {
for operand in operands.into_iter() {
self.add_operand(operand)
}
}
pub(super) fn to_words(&self, sink: &mut impl Extend<Word>) {
sink.extend(Some(self.wc << 16 | self.op as u32));
sink.extend(self.type_id);
sink.extend(self.result_id);
sink.extend(self.operands.iter().cloned());
}
}
impl Instruction {
#[cfg(test)]
fn validate(&self, words: &[Word]) {
let mut inst_index = 0;
let (wc, op) = ((words[inst_index] >> 16) as u16, words[inst_index] as u16);
inst_index += 1;
assert_eq!(wc, words.len() as u16);
assert_eq!(op, self.op as u16);
if self.type_id.is_some() {
assert_eq!(words[inst_index], self.type_id.unwrap());
inst_index += 1;
}
if self.result_id.is_some() {
assert_eq!(words[inst_index], self.result_id.unwrap());
inst_index += 1;
}
for (op_index, i) in (inst_index..wc as usize).enumerate() {
assert_eq!(words[i], self.operands[op_index]);
}
}
}
#[test]
fn test_physical_layout_in_words() {
let bound = 5;
let version = 0x10203;
let mut output = vec![];
let mut layout = PhysicalLayout::new(version);
layout.bound = bound;
layout.in_words(&mut output);
assert_eq!(&output, &[MAGIC_NUMBER, version, GENERATOR, bound, 0,]);
}
#[test]
fn test_logical_layout_in_words() {
let mut output = vec![];
let mut layout = LogicalLayout::default();
let layout_vectors = 11;
let mut instructions = Vec::with_capacity(layout_vectors);
let vector_names = &[
"Capabilities",
"Extensions",
"External Instruction Imports",
"Memory Model",
"Entry Points",
"Execution Modes",
"Debugs",
"Annotations",
"Declarations",
"Function Declarations",
"Function Definitions",
];
for (i, _) in vector_names.iter().enumerate().take(layout_vectors) {
let mut dummy_instruction = Instruction::new(Op::Constant);
dummy_instruction.set_type((i + 1) as u32);
dummy_instruction.set_result((i + 2) as u32);
dummy_instruction.add_operand((i + 3) as u32);
dummy_instruction.add_operands(super::helpers::string_to_words(
format!("This is the vector: {}", vector_names[i]).as_str(),
));
instructions.push(dummy_instruction);
}
instructions[0].to_words(&mut layout.capabilities);
instructions[1].to_words(&mut layout.extensions);
instructions[2].to_words(&mut layout.ext_inst_imports);
instructions[3].to_words(&mut layout.memory_model);
instructions[4].to_words(&mut layout.entry_points);
instructions[5].to_words(&mut layout.execution_modes);
instructions[6].to_words(&mut layout.debugs);
instructions[7].to_words(&mut layout.annotations);
instructions[8].to_words(&mut layout.declarations);
instructions[9].to_words(&mut layout.function_declarations);
instructions[10].to_words(&mut layout.function_definitions);
layout.in_words(&mut output);
let mut index: usize = 0;
for instruction in instructions {
let wc = instruction.wc as usize;
instruction.validate(&output[index..index + wc]);
index += wc;
}
}
+900
View File
@@ -0,0 +1,900 @@
/*!
Backend for [SPIR-V][spv] (Standard Portable Intermediate Representation).
[spv]: https://www.khronos.org/registry/SPIR-V/
*/
mod block;
mod helpers;
mod image;
mod index;
mod instructions;
mod layout;
mod ray;
mod recyclable;
mod selection;
mod subgroup;
mod writer;
pub use spirv::{Capability, SourceLanguage};
use crate::arena::{Handle, HandleVec};
use crate::proc::{BoundsCheckPolicies, TypeResolution};
use spirv::Word;
use std::ops;
use thiserror::Error;
#[derive(Clone)]
struct PhysicalLayout {
magic_number: Word,
version: Word,
generator: Word,
bound: Word,
instruction_schema: Word,
}
#[derive(Default)]
struct LogicalLayout {
capabilities: Vec<Word>,
extensions: Vec<Word>,
ext_inst_imports: Vec<Word>,
memory_model: Vec<Word>,
entry_points: Vec<Word>,
execution_modes: Vec<Word>,
debugs: Vec<Word>,
annotations: Vec<Word>,
declarations: Vec<Word>,
function_declarations: Vec<Word>,
function_definitions: Vec<Word>,
}
struct Instruction {
op: spirv::Op,
wc: u32,
type_id: Option<Word>,
result_id: Option<Word>,
operands: Vec<Word>,
}
const BITS_PER_BYTE: crate::Bytes = 8;
#[derive(Clone, Debug, Error)]
pub enum Error {
#[error("The requested entry point couldn't be found")]
EntryPointNotFound,
#[error("target SPIRV-{0}.{1} is not supported")]
UnsupportedVersion(u8, u8),
#[error("using {0} requires at least one of the capabilities {1:?}, but none are available")]
MissingCapabilities(&'static str, Vec<Capability>),
#[error("unimplemented {0}")]
FeatureNotImplemented(&'static str),
#[error("module is not validated properly: {0}")]
Validation(&'static str),
#[error("overrides should not be present at this stage")]
Override,
}
#[derive(Default)]
struct IdGenerator(Word);
impl IdGenerator {
fn next(&mut self) -> Word {
self.0 += 1;
self.0
}
}
#[derive(Debug, Clone)]
pub struct DebugInfo<'a> {
pub source_code: &'a str,
pub file_name: &'a std::path::Path,
pub language: SourceLanguage,
}
/// A SPIR-V block to which we are still adding instructions.
///
/// A `Block` represents a SPIR-V block that does not yet have a termination
/// instruction like `OpBranch` or `OpReturn`.
///
/// The `OpLabel` that starts the block is implicit. It will be emitted based on
/// `label_id` when we write the block to a `LogicalLayout`.
///
/// To terminate a `Block`, pass the block and the termination instruction to
/// `Function::consume`. This takes ownership of the `Block` and transforms it
/// into a `TerminatedBlock`.
struct Block {
label_id: Word,
body: Vec<Instruction>,
}
/// A SPIR-V block that ends with a termination instruction.
struct TerminatedBlock {
label_id: Word,
body: Vec<Instruction>,
}
impl Block {
const fn new(label_id: Word) -> Self {
Block {
label_id,
body: Vec::new(),
}
}
}
struct LocalVariable {
id: Word,
instruction: Instruction,
}
struct ResultMember {
id: Word,
type_id: Word,
built_in: Option<crate::BuiltIn>,
}
struct EntryPointContext {
argument_ids: Vec<Word>,
results: Vec<ResultMember>,
}
#[derive(Default)]
struct Function {
signature: Option<Instruction>,
parameters: Vec<FunctionArgument>,
variables: crate::FastHashMap<Handle<crate::LocalVariable>, LocalVariable>,
/// A map taking an expression that yields a composite value (array, matrix)
/// to the temporary variables we have spilled it to, if any. Spilling
/// allows us to render an arbitrary chain of [`Access`] and [`AccessIndex`]
/// expressions as an `OpAccessChain` and an `OpLoad` (plus bounds checks).
/// This supports dynamic indexing of by-value arrays and matrices, which
/// SPIR-V does not.
///
/// [`Access`]: crate::Expression::Access
/// [`AccessIndex`]: crate::Expression::AccessIndex
spilled_composites: crate::FastIndexMap<Handle<crate::Expression>, LocalVariable>,
/// A set of expressions that are either in [`spilled_composites`] or refer
/// to some component/element of such.
///
/// [`spilled_composites`]: Function::spilled_composites
spilled_accesses: crate::arena::HandleSet<crate::Expression>,
/// A map taking each expression to the number of [`Access`] and
/// [`AccessIndex`] expressions that uses it as a base value. If an
/// expression has no entry, its count is zero: it is never used as a
/// [`Access`] or [`AccessIndex`] base.
///
/// We use this, together with [`ExpressionInfo::ref_count`], to recognize
/// the tips of chains of [`Access`] and [`AccessIndex`] expressions that
/// access spilled values --- expressions in [`spilled_composites`]. We
/// defer generating code for the chain until we reach its tip, so we can
/// handle it with a single instruction.
///
/// [`Access`]: crate::Expression::Access
/// [`AccessIndex`]: crate::Expression::AccessIndex
/// [`ExpressionInfo::ref_count`]: crate::valid::ExpressionInfo
/// [`spilled_composites`]: Function::spilled_composites
access_uses: crate::FastHashMap<Handle<crate::Expression>, usize>,
blocks: Vec<TerminatedBlock>,
entry_point_context: Option<EntryPointContext>,
}
impl Function {
fn consume(&mut self, mut block: Block, termination: Instruction) {
block.body.push(termination);
self.blocks.push(TerminatedBlock {
label_id: block.label_id,
body: block.body,
})
}
fn parameter_id(&self, index: u32) -> Word {
match self.entry_point_context {
Some(ref context) => context.argument_ids[index as usize],
None => self.parameters[index as usize]
.instruction
.result_id
.unwrap(),
}
}
}
/// Characteristics of a SPIR-V `OpTypeImage` type.
///
/// SPIR-V requires non-composite types to be unique, including images. Since we
/// use `LocalType` for this deduplication, it's essential that `LocalImageType`
/// be equal whenever the corresponding `OpTypeImage`s would be. To reduce the
/// likelihood of mistakes, we use fields that correspond exactly to the
/// operands of an `OpTypeImage` instruction, using the actual SPIR-V types
/// where practical.
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
struct LocalImageType {
sampled_type: crate::Scalar,
dim: spirv::Dim,
flags: ImageTypeFlags,
image_format: spirv::ImageFormat,
}
bitflags::bitflags! {
/// Flags corresponding to the boolean(-ish) parameters to OpTypeImage.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ImageTypeFlags: u8 {
const DEPTH = 0x1;
const ARRAYED = 0x2;
const MULTISAMPLED = 0x4;
const SAMPLED = 0x8;
}
}
impl LocalImageType {
/// Construct a `LocalImageType` from the fields of a `TypeInner::Image`.
fn from_inner(dim: crate::ImageDimension, arrayed: bool, class: crate::ImageClass) -> Self {
let make_flags = |multi: bool, other: ImageTypeFlags| -> ImageTypeFlags {
let mut flags = other;
flags.set(ImageTypeFlags::ARRAYED, arrayed);
flags.set(ImageTypeFlags::MULTISAMPLED, multi);
flags
};
let dim = spirv::Dim::from(dim);
match class {
crate::ImageClass::Sampled { kind, multi } => LocalImageType {
sampled_type: crate::Scalar { kind, width: 4 },
dim,
flags: make_flags(multi, ImageTypeFlags::SAMPLED),
image_format: spirv::ImageFormat::Unknown,
},
crate::ImageClass::Depth { multi } => LocalImageType {
sampled_type: crate::Scalar {
kind: crate::ScalarKind::Float,
width: 4,
},
dim,
flags: make_flags(multi, ImageTypeFlags::DEPTH | ImageTypeFlags::SAMPLED),
image_format: spirv::ImageFormat::Unknown,
},
crate::ImageClass::Storage { format, access: _ } => LocalImageType {
sampled_type: format.into(),
dim,
flags: make_flags(false, ImageTypeFlags::empty()),
image_format: format.into(),
},
}
}
}
/// A numeric type, for use in [`LocalType`].
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum NumericType {
Scalar(crate::Scalar),
Vector {
size: crate::VectorSize,
scalar: crate::Scalar,
},
Matrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
scalar: crate::Scalar,
},
}
impl NumericType {
const fn from_inner(inner: &crate::TypeInner) -> Option<Self> {
match *inner {
crate::TypeInner::Scalar(scalar) | crate::TypeInner::Atomic(scalar) => {
Some(NumericType::Scalar(scalar))
}
crate::TypeInner::Vector { size, scalar } => Some(NumericType::Vector { size, scalar }),
crate::TypeInner::Matrix {
columns,
rows,
scalar,
} => Some(NumericType::Matrix {
columns,
rows,
scalar,
}),
_ => None,
}
}
}
/// A SPIR-V type constructed during code generation.
///
/// This is the variant of [`LookupType`] used to represent types that might not
/// be available in the arena. Variants are present here for one of two reasons:
///
/// - They represent types synthesized during code generation, as explained
/// in the documentation for [`LookupType`].
///
/// - They represent types for which SPIR-V forbids duplicate `OpType...`
/// instructions, requiring deduplication.
///
/// This is not a complete copy of [`TypeInner`]: for example, SPIR-V generation
/// never synthesizes new struct types, so `LocalType` has nothing for that.
///
/// Each `LocalType` variant should be handled identically to its analogous
/// `TypeInner` variant. You can use the [`LocalType::from_inner`] function to
/// help with this, by converting everything possible to a `LocalType` before
/// inspecting it.
///
/// ## `LocalType` equality and SPIR-V `OpType` uniqueness
///
/// The definition of `Eq` on `LocalType` is carefully chosen to help us follow
/// certain SPIR-V rules. SPIR-V §2.8 requires some classes of `OpType...`
/// instructions to be unique; for example, you can't have two `OpTypeInt 32 1`
/// instructions in the same module. All 32-bit signed integers must use the
/// same type id.
///
/// All SPIR-V types that must be unique can be represented as a `LocalType`,
/// and two `LocalType`s are always `Eq` if SPIR-V would require them to use the
/// same `OpType...` instruction. This lets us avoid duplicates by recording the
/// ids of the type instructions we've already generated in a hash table,
/// [`Writer::lookup_type`], keyed by `LocalType`.
///
/// As another example, [`LocalImageType`], stored in the `LocalType::Image`
/// variant, is designed to help us deduplicate `OpTypeImage` instructions. See
/// its documentation for details.
///
/// `LocalType` also includes variants like `Pointer` that do not need to be
/// unique - but it is harmless to avoid the duplication.
///
/// As it always must, the `Hash` implementation respects the `Eq` relation.
///
/// [`TypeInner`]: crate::TypeInner
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum LocalType {
/// A numeric type.
Numeric(NumericType),
LocalPointer {
base: NumericType,
class: spirv::StorageClass,
},
Pointer {
base: Handle<crate::Type>,
class: spirv::StorageClass,
},
Image(LocalImageType),
SampledImage {
image_type_id: Word,
},
Sampler,
/// Equivalent to a [`LocalType::Pointer`] whose `base` is a Naga IR [`BindingArray`]. SPIR-V
/// permits duplicated `OpTypePointer` ids, so it's fine to have two different [`LocalType`]
/// representations for pointer types.
///
/// [`BindingArray`]: crate::TypeInner::BindingArray
PointerToBindingArray {
base: Handle<crate::Type>,
size: u32,
space: crate::AddressSpace,
},
BindingArray {
base: Handle<crate::Type>,
size: u32,
},
AccelerationStructure,
RayQuery,
}
/// A type encountered during SPIR-V generation.
///
/// In the process of writing SPIR-V, we need to synthesize various types for
/// intermediate results and such: pointer types, vector/matrix component types,
/// or even booleans, which usually appear in SPIR-V code even when they're not
/// used by the module source.
///
/// However, we can't use `crate::Type` or `crate::TypeInner` for these, as the
/// type arena may not contain what we need (it only contains types used
/// directly by other parts of the IR), and the IR module is immutable, so we
/// can't add anything to it.
///
/// So for local use in the SPIR-V writer, we use this type, which holds either
/// a handle into the arena, or a [`LocalType`] containing something synthesized
/// locally.
///
/// This is very similar to the [`proc::TypeResolution`] enum, with `LocalType`
/// playing the role of `TypeInner`. However, `LocalType` also has other
/// properties needed for SPIR-V generation; see the description of
/// [`LocalType`] for details.
///
/// [`proc::TypeResolution`]: crate::proc::TypeResolution
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum LookupType {
Handle(Handle<crate::Type>),
Local(LocalType),
}
impl From<LocalType> for LookupType {
fn from(local: LocalType) -> Self {
Self::Local(local)
}
}
#[derive(Debug, PartialEq, Clone, Hash, Eq)]
struct LookupFunctionType {
parameter_type_ids: Vec<Word>,
return_type_id: Word,
}
impl LocalType {
fn from_inner(inner: &crate::TypeInner) -> Option<Self> {
Some(match *inner {
crate::TypeInner::Scalar(_)
| crate::TypeInner::Atomic(_)
| crate::TypeInner::Vector { .. }
| crate::TypeInner::Matrix { .. } => {
// We expect `NumericType::from_inner` to handle all
// these cases, so unwrap.
LocalType::Numeric(NumericType::from_inner(inner).unwrap())
}
crate::TypeInner::Pointer { base, space } => LocalType::Pointer {
base,
class: helpers::map_storage_class(space),
},
crate::TypeInner::ValuePointer {
size: Some(size),
scalar,
space,
} => LocalType::LocalPointer {
base: NumericType::Vector { size, scalar },
class: helpers::map_storage_class(space),
},
crate::TypeInner::ValuePointer {
size: None,
scalar,
space,
} => LocalType::LocalPointer {
base: NumericType::Scalar(scalar),
class: helpers::map_storage_class(space),
},
crate::TypeInner::Image {
dim,
arrayed,
class,
} => LocalType::Image(LocalImageType::from_inner(dim, arrayed, class)),
crate::TypeInner::Sampler { comparison: _ } => LocalType::Sampler,
crate::TypeInner::AccelerationStructure => LocalType::AccelerationStructure,
crate::TypeInner::RayQuery => LocalType::RayQuery,
crate::TypeInner::Array { .. }
| crate::TypeInner::Struct { .. }
| crate::TypeInner::BindingArray { .. } => return None,
})
}
}
#[derive(Debug)]
enum Dimension {
Scalar,
Vector,
Matrix,
}
/// A map from evaluated [`Expression`](crate::Expression)s to their SPIR-V ids.
///
/// When we emit code to evaluate a given `Expression`, we record the
/// SPIR-V id of its value here, under its `Handle<Expression>` index.
///
/// A `CachedExpressions` value can be indexed by a `Handle<Expression>` value.
///
/// [emit]: index.html#expression-evaluation-time-and-scope
#[derive(Default)]
struct CachedExpressions {
ids: HandleVec<crate::Expression, Word>,
}
impl CachedExpressions {
fn reset(&mut self, length: usize) {
self.ids.clear();
self.ids.resize(length, 0);
}
}
impl ops::Index<Handle<crate::Expression>> for CachedExpressions {
type Output = Word;
fn index(&self, h: Handle<crate::Expression>) -> &Word {
let id = &self.ids[h];
if *id == 0 {
unreachable!("Expression {:?} is not cached!", h);
}
id
}
}
impl ops::IndexMut<Handle<crate::Expression>> for CachedExpressions {
fn index_mut(&mut self, h: Handle<crate::Expression>) -> &mut Word {
let id = &mut self.ids[h];
if *id != 0 {
unreachable!("Expression {:?} is already cached!", h);
}
id
}
}
impl recyclable::Recyclable for CachedExpressions {
fn recycle(self) -> Self {
CachedExpressions {
ids: self.ids.recycle(),
}
}
}
#[derive(Eq, Hash, PartialEq)]
enum CachedConstant {
Literal(crate::proc::HashableLiteral),
Composite {
ty: LookupType,
constituent_ids: Vec<Word>,
},
ZeroValue(Word),
}
/// The SPIR-V representation of a [`crate::GlobalVariable`].
///
/// In the Vulkan spec 1.3.296, the section [Descriptor Set Interface][dsi] says:
///
/// > Variables identified with the `Uniform` storage class are used to access
/// > transparent buffer backed resources. Such variables *must* be:
/// >
/// > - typed as `OpTypeStruct`, or an array of this type,
/// >
/// > - identified with a `Block` or `BufferBlock` decoration, and
/// >
/// > - laid out explicitly using the `Offset`, `ArrayStride`, and `MatrixStride`
/// > decorations as specified in "Offset and Stride Assignment".
///
/// This is followed by identical language for the `StorageBuffer`,
/// except that a `BufferBlock` decoration is not allowed.
///
/// When we encounter a global variable in the [`Storage`] or [`Uniform`]
/// address spaces whose type is not already [`Struct`], this backend implicitly
/// wraps the global variable in a struct: we generate a SPIR-V global variable
/// holding an `OpTypeStruct` with a single member, whose type is what the Naga
/// global's type would suggest, decorated as required above.
///
/// The [`helpers::global_needs_wrapper`] function determines whether a given
/// [`crate::GlobalVariable`] needs to be wrapped.
///
/// [dsi]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-resources-descset
/// [`Storage`]: crate::AddressSpace::Storage
/// [`Uniform`]: crate::AddressSpace::Uniform
/// [`Struct`]: crate::TypeInner::Struct
#[derive(Clone)]
struct GlobalVariable {
/// The SPIR-V id of the `OpVariable` that declares the global.
///
/// If this global has been implicitly wrapped in an `OpTypeStruct`, this id
/// refers to the wrapper, not the original Naga value it contains. If you
/// need the Naga value, use [`access_id`] instead of this field.
///
/// If this global is not implicitly wrapped, this is the same as
/// [`access_id`].
///
/// This is used to compute the `access_id` pointer in function prologues,
/// and used for `ArrayLength` expressions, which need to pass the wrapper
/// struct.
///
/// [`access_id`]: GlobalVariable::access_id
var_id: Word,
/// The loaded value of a `AddressSpace::Handle` global variable.
///
/// If the current function uses this global variable, this is the id of an
/// `OpLoad` instruction in the function's prologue that loads its value.
/// (This value is assigned as we write the prologue code of each function.)
/// It is then used for all operations on the global, such as `OpImageSample`.
handle_id: Word,
/// The SPIR-V id of a pointer to this variable's Naga IR value.
///
/// If the current function uses this global variable, and it has been
/// implicitly wrapped in an `OpTypeStruct`, this is the id of an
/// `OpAccessChain` instruction in the function's prologue that refers to
/// the wrapped value inside the struct. (This value is assigned as we write
/// the prologue code of each function.) If you need the wrapper struct
/// itself, use [`var_id`] instead of this field.
///
/// If this global is not implicitly wrapped, this is the same as
/// [`var_id`].
///
/// [`var_id`]: GlobalVariable::var_id
access_id: Word,
}
impl GlobalVariable {
const fn dummy() -> Self {
Self {
var_id: 0,
handle_id: 0,
access_id: 0,
}
}
const fn new(id: Word) -> Self {
Self {
var_id: id,
handle_id: 0,
access_id: 0,
}
}
/// Prepare `self` for use within a single function.
fn reset_for_function(&mut self) {
self.handle_id = 0;
self.access_id = 0;
}
}
struct FunctionArgument {
/// Actual instruction of the argument.
instruction: Instruction,
handle_id: Word,
}
/// Tracks the expressions for which the backend emits the following instructions:
/// - OpConstantTrue
/// - OpConstantFalse
/// - OpConstant
/// - OpConstantComposite
/// - OpConstantNull
struct ExpressionConstnessTracker {
inner: crate::arena::HandleSet<crate::Expression>,
}
impl ExpressionConstnessTracker {
fn from_arena(arena: &crate::Arena<crate::Expression>) -> Self {
let mut inner = crate::arena::HandleSet::for_arena(arena);
for (handle, expr) in arena.iter() {
let insert = match *expr {
crate::Expression::Literal(_)
| crate::Expression::ZeroValue(_)
| crate::Expression::Constant(_) => true,
crate::Expression::Compose { ref components, .. } => {
components.iter().all(|&h| inner.contains(h))
}
crate::Expression::Splat { value, .. } => inner.contains(value),
_ => false,
};
if insert {
inner.insert(handle);
}
}
Self { inner }
}
fn is_const(&self, value: Handle<crate::Expression>) -> bool {
self.inner.contains(value)
}
}
/// General information needed to emit SPIR-V for Naga statements.
struct BlockContext<'w> {
/// The writer handling the module to which this code belongs.
writer: &'w mut Writer,
/// The [`Module`](crate::Module) for which we're generating code.
ir_module: &'w crate::Module,
/// The [`Function`](crate::Function) for which we're generating code.
ir_function: &'w crate::Function,
/// Information module validation produced about
/// [`ir_function`](BlockContext::ir_function).
fun_info: &'w crate::valid::FunctionInfo,
/// The [`spv::Function`](Function) to which we are contributing SPIR-V instructions.
function: &'w mut Function,
/// SPIR-V ids for expressions we've evaluated.
cached: CachedExpressions,
/// The `Writer`'s temporary vector, for convenience.
temp_list: Vec<Word>,
/// Tracks the constness of `Expression`s residing in `self.ir_function.expressions`
expression_constness: ExpressionConstnessTracker,
}
impl BlockContext<'_> {
fn gen_id(&mut self) -> Word {
self.writer.id_gen.next()
}
fn get_type_id(&mut self, lookup_type: LookupType) -> Word {
self.writer.get_type_id(lookup_type)
}
fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word {
self.writer.get_expression_type_id(tr)
}
fn get_index_constant(&mut self, index: Word) -> Word {
self.writer.get_constant_scalar(crate::Literal::U32(index))
}
fn get_scope_constant(&mut self, scope: Word) -> Word {
self.writer
.get_constant_scalar(crate::Literal::I32(scope as _))
}
fn get_pointer_id(&mut self, handle: Handle<crate::Type>, class: spirv::StorageClass) -> Word {
self.writer.get_pointer_id(handle, class)
}
}
pub struct Writer {
physical_layout: PhysicalLayout,
logical_layout: LogicalLayout,
id_gen: IdGenerator,
/// The set of capabilities modules are permitted to use.
///
/// This is initialized from `Options::capabilities`.
capabilities_available: Option<crate::FastHashSet<Capability>>,
/// The set of capabilities used by this module.
///
/// If `capabilities_available` is `Some`, then this is always a subset of
/// that.
capabilities_used: crate::FastIndexSet<Capability>,
/// The set of spirv extensions used.
extensions_used: crate::FastIndexSet<&'static str>,
debugs: Vec<Instruction>,
annotations: Vec<Instruction>,
flags: WriterFlags,
bounds_check_policies: BoundsCheckPolicies,
zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode,
void_type: Word,
//TODO: convert most of these into vectors, addressable by handle indices
lookup_type: crate::FastHashMap<LookupType, Word>,
lookup_function: crate::FastHashMap<Handle<crate::Function>, Word>,
lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
/// Indexed by const-expression handle indexes
constant_ids: HandleVec<crate::Expression, Word>,
cached_constants: crate::FastHashMap<CachedConstant, Word>,
global_variables: HandleVec<crate::GlobalVariable, GlobalVariable>,
binding_map: BindingMap,
// Cached expressions are only meaningful within a BlockContext, but we
// retain the table here between functions to save heap allocations.
saved_cached: CachedExpressions,
gl450_ext_inst_id: Word,
// Just a temporary list of SPIR-V ids
temp_list: Vec<Word>,
}
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WriterFlags: u32 {
/// Include debug labels for everything.
const DEBUG = 0x1;
/// Flip Y coordinate of [`BuiltIn::Position`] output.
///
/// [`BuiltIn::Position`]: crate::BuiltIn::Position
const ADJUST_COORDINATE_SPACE = 0x2;
/// Emit [`OpName`][op] for input/output locations.
///
/// Contrary to spec, some drivers treat it as semantic, not allowing
/// any conflicts.
///
/// [op]: https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpName
const LABEL_VARYINGS = 0x4;
/// Emit [`PointSize`] output builtin to vertex shaders, which is
/// required for drawing with `PointList` topology.
///
/// [`PointSize`]: crate::BuiltIn::PointSize
const FORCE_POINT_SIZE = 0x8;
/// Clamp [`BuiltIn::FragDepth`] output between 0 and 1.
///
/// [`BuiltIn::FragDepth`]: crate::BuiltIn::FragDepth
const CLAMP_FRAG_DEPTH = 0x10;
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct BindingInfo {
/// If the binding is an unsized binding array, this overrides the size.
pub binding_array_size: Option<u32>,
}
// Using `BTreeMap` instead of `HashMap` so that we can hash itself.
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, BindingInfo>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ZeroInitializeWorkgroupMemoryMode {
/// Via `VK_KHR_zero_initialize_workgroup_memory` or Vulkan 1.3
Native,
/// Via assignments + barrier
Polyfill,
None,
}
#[derive(Debug, Clone)]
pub struct Options<'a> {
/// (Major, Minor) target version of the SPIR-V.
pub lang_version: (u8, u8),
/// Configuration flags for the writer.
pub flags: WriterFlags,
/// Map of resources to information about the binding.
pub binding_map: BindingMap,
/// If given, the set of capabilities modules are allowed to use. Code that
/// requires capabilities beyond these is rejected with an error.
///
/// If this is `None`, all capabilities are permitted.
pub capabilities: Option<crate::FastHashSet<Capability>>,
/// How should generate code handle array, vector, matrix, or image texel
/// indices that are out of range?
pub bounds_check_policies: BoundsCheckPolicies,
/// Dictates the way workgroup variables should be zero initialized
pub zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode,
pub debug_info: Option<DebugInfo<'a>>,
}
impl Default for Options<'_> {
fn default() -> Self {
let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE
| WriterFlags::LABEL_VARYINGS
| WriterFlags::CLAMP_FRAG_DEPTH;
if cfg!(debug_assertions) {
flags |= WriterFlags::DEBUG;
}
Options {
lang_version: (1, 0),
flags,
binding_map: BindingMap::default(),
capabilities: None,
bounds_check_policies: BoundsCheckPolicies::default(),
zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode::Polyfill,
debug_info: None,
}
}
}
// A subset of options meant to be changed per pipeline.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct PipelineOptions {
/// The stage of the entry point.
pub shader_stage: crate::ShaderStage,
/// The name of the entry point.
///
/// If no entry point that matches is found while creating a [`Writer`], a error will be thrown.
pub entry_point: String,
}
pub fn write_vec(
module: &crate::Module,
info: &crate::valid::ModuleInfo,
options: &Options,
pipeline_options: Option<&PipelineOptions>,
) -> Result<Vec<u32>, Error> {
let mut words: Vec<u32> = Vec::new();
let mut w = Writer::new(options)?;
w.write(
module,
info,
pipeline_options,
&options.debug_info,
&mut words,
)?;
Ok(words)
}
+291
View File
@@ -0,0 +1,291 @@
/*!
Generating SPIR-V for ray query operations.
*/
use super::{Block, BlockContext, Instruction, LocalType, LookupType, NumericType};
use crate::arena::Handle;
impl BlockContext<'_> {
pub(super) fn write_ray_query_function(
&mut self,
query: Handle<crate::Expression>,
function: &crate::RayQueryFunction,
block: &mut Block,
) {
let query_id = self.cached[query];
match *function {
crate::RayQueryFunction::Initialize {
acceleration_structure,
descriptor,
} => {
//Note: composite extract indices and types must match `generate_ray_desc_type`
let desc_id = self.cached[descriptor];
let acc_struct_id = self.get_handle_id(acceleration_structure);
let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
NumericType::Scalar(crate::Scalar::U32),
)));
let ray_flags_id = self.gen_id();
block.body.push(Instruction::composite_extract(
flag_type_id,
ray_flags_id,
desc_id,
&[0],
));
let cull_mask_id = self.gen_id();
block.body.push(Instruction::composite_extract(
flag_type_id,
cull_mask_id,
desc_id,
&[1],
));
let scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
NumericType::Scalar(crate::Scalar::F32),
)));
let tmin_id = self.gen_id();
block.body.push(Instruction::composite_extract(
scalar_type_id,
tmin_id,
desc_id,
&[2],
));
let tmax_id = self.gen_id();
block.body.push(Instruction::composite_extract(
scalar_type_id,
tmax_id,
desc_id,
&[3],
));
let vector_type_id =
self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Vector {
size: crate::VectorSize::Tri,
scalar: crate::Scalar::F32,
})));
let ray_origin_id = self.gen_id();
block.body.push(Instruction::composite_extract(
vector_type_id,
ray_origin_id,
desc_id,
&[4],
));
let ray_dir_id = self.gen_id();
block.body.push(Instruction::composite_extract(
vector_type_id,
ray_dir_id,
desc_id,
&[5],
));
block.body.push(Instruction::ray_query_initialize(
query_id,
acc_struct_id,
ray_flags_id,
cull_mask_id,
ray_origin_id,
tmin_id,
ray_dir_id,
tmax_id,
));
}
crate::RayQueryFunction::Proceed { result } => {
let id = self.gen_id();
self.cached[result] = id;
let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty);
block
.body
.push(Instruction::ray_query_proceed(result_type_id, id, query_id));
}
crate::RayQueryFunction::Terminate => {}
}
}
pub(super) fn write_ray_query_get_intersection(
&mut self,
query: Handle<crate::Expression>,
block: &mut Block,
is_committed: bool,
) -> spirv::Word {
let query_id = self.cached[query];
let intersection_id =
self.writer
.get_constant_scalar(crate::Literal::U32(if is_committed {
spirv::RayQueryIntersection::RayQueryCommittedIntersectionKHR
} else {
spirv::RayQueryIntersection::RayQueryCandidateIntersectionKHR
} as _));
let flag_type_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
NumericType::Scalar(crate::Scalar::U32),
)));
let raw_kind_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionTypeKHR,
flag_type_id,
raw_kind_id,
query_id,
intersection_id,
));
let kind_id = if is_committed {
// Nothing to do: the IR value matches `spirv::RayQueryCommittedIntersectionType`
raw_kind_id
} else {
// Remap from the candidate kind to IR
let condition_id = self.gen_id();
let committed_triangle_kind_id = self.writer.get_constant_scalar(crate::Literal::U32(
spirv::RayQueryCandidateIntersectionType::RayQueryCandidateIntersectionTriangleKHR
as _,
));
block.body.push(Instruction::binary(
spirv::Op::IEqual,
self.writer.get_bool_type_id(),
condition_id,
raw_kind_id,
committed_triangle_kind_id,
));
let kind_id = self.gen_id();
block.body.push(Instruction::select(
flag_type_id,
kind_id,
condition_id,
self.writer.get_constant_scalar(crate::Literal::U32(
crate::RayQueryIntersection::Triangle as _,
)),
self.writer.get_constant_scalar(crate::Literal::U32(
crate::RayQueryIntersection::Aabb as _,
)),
));
kind_id
};
let instance_custom_index_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionInstanceCustomIndexKHR,
flag_type_id,
instance_custom_index_id,
query_id,
intersection_id,
));
let instance_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionInstanceIdKHR,
flag_type_id,
instance_id,
query_id,
intersection_id,
));
let sbt_record_offset_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR,
flag_type_id,
sbt_record_offset_id,
query_id,
intersection_id,
));
let geometry_index_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionGeometryIndexKHR,
flag_type_id,
geometry_index_id,
query_id,
intersection_id,
));
let primitive_index_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionPrimitiveIndexKHR,
flag_type_id,
primitive_index_id,
query_id,
intersection_id,
));
let scalar_type_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
NumericType::Scalar(crate::Scalar::F32),
)));
let t_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionTKHR,
scalar_type_id,
t_id,
query_id,
intersection_id,
));
let barycentrics_type_id =
self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Vector {
size: crate::VectorSize::Bi,
scalar: crate::Scalar::F32,
})));
let barycentrics_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionBarycentricsKHR,
barycentrics_type_id,
barycentrics_id,
query_id,
intersection_id,
));
let bool_type_id = self.get_type_id(LookupType::Local(LocalType::Numeric(
NumericType::Scalar(crate::Scalar::BOOL),
)));
let front_face_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionFrontFaceKHR,
bool_type_id,
front_face_id,
query_id,
intersection_id,
));
//Note: there is also `OpRayQueryGetIntersectionCandidateAABBOpaqueKHR`,
// but it's not a property of an intersection.
let transform_type_id =
self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Tri,
scalar: crate::Scalar::F32,
})));
let object_to_world_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionObjectToWorldKHR,
transform_type_id,
object_to_world_id,
query_id,
intersection_id,
));
let world_to_object_id = self.gen_id();
block.body.push(Instruction::ray_query_get_intersection(
spirv::Op::RayQueryGetIntersectionWorldToObjectKHR,
transform_type_id,
world_to_object_id,
query_id,
intersection_id,
));
let id = self.gen_id();
let intersection_type_id = self.get_type_id(LookupType::Handle(
self.ir_module.special_types.ray_intersection.unwrap(),
));
//Note: the arguments must match `generate_ray_intersection_type` layout
block.body.push(Instruction::composite_construct(
intersection_type_id,
id,
&[
kind_id,
t_id,
instance_custom_index_id,
instance_id,
sbt_record_offset_id,
geometry_index_id,
primitive_index_id,
barycentrics_id,
front_face_id,
object_to_world_id,
world_to_object_id,
],
));
id
}
}
+74
View File
@@ -0,0 +1,74 @@
/*!
Reusing collections' previous allocations.
*/
/// A value that can be reset to its initial state, retaining its current allocations.
///
/// Naga attempts to lower the cost of SPIR-V generation by allowing clients to
/// reuse the same `Writer` for multiple Module translations. Reusing a `Writer`
/// means that the `Vec`s, `HashMap`s, and other heap-allocated structures the
/// `Writer` uses internally begin the translation with heap-allocated buffers
/// ready to use.
///
/// But this approach introduces the risk of `Writer` state leaking from one
/// module to the next. When a developer adds fields to `Writer` or its internal
/// types, they must remember to reset their contents between modules.
///
/// One trick to ensure that every field has been accounted for is to use Rust's
/// struct literal syntax to construct a new, reset value. If a developer adds a
/// field, but neglects to update the reset code, the compiler will complain
/// that a field is missing from the literal. This trait's `recycle` method
/// takes `self` by value, and returns `Self` by value, encouraging the use of
/// struct literal expressions in its implementation.
pub trait Recyclable {
/// Clear `self`, retaining its current memory allocations.
///
/// Shrink the buffer if it's currently much larger than was actually used.
/// This prevents a module with exceptionally large allocations from causing
/// the `Writer` to retain more memory than it needs indefinitely.
fn recycle(self) -> Self;
}
// Stock values for various collections.
impl<T> Recyclable for Vec<T> {
fn recycle(mut self) -> Self {
self.clear();
self
}
}
impl<K, V, S: Clone> Recyclable for std::collections::HashMap<K, V, S> {
fn recycle(mut self) -> Self {
self.clear();
self
}
}
impl<K, S: Clone> Recyclable for std::collections::HashSet<K, S> {
fn recycle(mut self) -> Self {
self.clear();
self
}
}
impl<K, S: Clone> Recyclable for indexmap::IndexSet<K, S> {
fn recycle(mut self) -> Self {
self.clear();
self
}
}
impl<K: Ord, V> Recyclable for std::collections::BTreeMap<K, V> {
fn recycle(mut self) -> Self {
self.clear();
self
}
}
impl<K, V> Recyclable for crate::arena::HandleVec<K, V> {
fn recycle(mut self) -> Self {
self.clear();
self
}
}
+257
View File
@@ -0,0 +1,257 @@
/*!
Generate SPIR-V conditional structures.
Builders for `if` structures with `and`s.
The types in this module track the information needed to emit SPIR-V code
for complex conditional structures, like those whose conditions involve
short-circuiting 'and' and 'or' structures. These track labels and can emit
`OpPhi` instructions to merge values produced along different paths.
This currently only supports exactly the forms Naga uses, so it doesn't
support `or` or `else`, and only supports zero or one merged values.
Naga needs to emit code roughly like this:
```ignore
value = DEFAULT;
if COND1 && COND2 {
value = THEN_VALUE;
}
// use value
```
Assuming `ctx` and `block` are a mutable references to a [`BlockContext`]
and the current [`Block`], and `merge_type` is the SPIR-V type for the
merged value `value`, we can build SPIR-V for the code above like so:
```ignore
let cond = Selection::start(block, merge_type);
// ... compute `cond1` ...
cond.if_true(ctx, cond1, DEFAULT);
// ... compute `cond2` ...
cond.if_true(ctx, cond2, DEFAULT);
// ... compute THEN_VALUE
let merged_value = cond.finish(ctx, THEN_VALUE);
```
After this, `merged_value` is either `DEFAULT` or `THEN_VALUE`, depending on
the path by which the merged block was reached.
This takes care of writing all branch instructions, including an
`OpSelectionMerge` annotation in the header block; starting new blocks and
assigning them labels; and emitting the `OpPhi` that gathers together the
right sources for the merged values, for every path through the selection
construct.
When there is no merged value to produce, you can pass `()` for `merge_type`
and the merge values. In this case no `OpPhi` instructions are produced, and
the `finish` method returns `()`.
To enforce proper nesting, a `Selection` takes ownership of the `&mut Block`
pointer for the duration of its lifetime. To obtain the block for generating
code in the selection's body, call the `Selection::block` method.
*/
use super::{Block, BlockContext, Instruction};
use spirv::Word;
/// A private struct recording what we know about the selection construct so far.
pub(super) struct Selection<'b, M: MergeTuple> {
/// The block pointer we're emitting code into.
block: &'b mut Block,
/// The label of the selection construct's merge block, or `None` if we
/// haven't yet written the `OpSelectionMerge` merge instruction.
merge_label: Option<Word>,
/// A set of `(VALUES, PARENT)` pairs, used to build `OpPhi` instructions in
/// the merge block. Each `PARENT` is the label of a predecessor block of
/// the merge block. The corresponding `VALUES` holds the ids of the values
/// that `PARENT` contributes to the merged values.
///
/// We emit all branches to the merge block, so we know all its
/// predecessors. And we refuse to emit a branch unless we're given the
/// values the branching block contributes to the merge, so we always have
/// everything we need to emit the correct phis, by construction.
values: Vec<(M, Word)>,
/// The types of the values in each element of `values`.
merge_types: M,
}
impl<'b, M: MergeTuple> Selection<'b, M> {
/// Start a new selection construct.
///
/// The `block` argument indicates the selection's header block.
///
/// The `merge_types` argument should be a `Word` or tuple of `Word`s, each
/// value being the SPIR-V result type id of an `OpPhi` instruction that
/// will be written to the selection's merge block when this selection's
/// [`finish`] method is called. This argument may also be `()`, for
/// selections that produce no values.
///
/// (This function writes no code to `block` itself; it simply constructs a
/// fresh `Selection`.)
///
/// [`finish`]: Selection::finish
pub(super) fn start(block: &'b mut Block, merge_types: M) -> Self {
Selection {
block,
merge_label: None,
values: vec![],
merge_types,
}
}
pub(super) fn block(&mut self) -> &mut Block {
self.block
}
/// Branch to a successor block if `cond` is true, otherwise merge.
///
/// If `cond` is false, branch to the merge block, using `values` as the
/// merged values. Otherwise, proceed to a new block.
///
/// The `values` argument must be the same shape as the `merge_types`
/// argument passed to `Selection::start`.
pub(super) fn if_true(&mut self, ctx: &mut BlockContext, cond: Word, values: M) {
self.values.push((values, self.block.label_id));
let merge_label = self.make_merge_label(ctx);
let next_label = ctx.gen_id();
ctx.function.consume(
std::mem::replace(self.block, Block::new(next_label)),
Instruction::branch_conditional(cond, next_label, merge_label),
);
}
/// Emit an unconditional branch to the merge block, and compute merged
/// values.
///
/// Use `final_values` as the merged values contributed by the current
/// block, and transition to the merge block, emitting `OpPhi` instructions
/// to produce the merged values. This must be the same shape as the
/// `merge_types` argument passed to [`Selection::start`].
///
/// Return the SPIR-V ids of the merged values. This value has the same
/// shape as the `merge_types` argument passed to `Selection::start`.
pub(super) fn finish(self, ctx: &mut BlockContext, final_values: M) -> M {
match self {
Selection {
merge_label: None, ..
} => {
// We didn't actually emit any branches, so `self.values` must
// be empty, and `final_values` are the only sources we have for
// the merged values. Easy peasy.
final_values
}
Selection {
block,
merge_label: Some(merge_label),
mut values,
merge_types,
} => {
// Emit the final branch and transition to the merge block.
values.push((final_values, block.label_id));
ctx.function.consume(
std::mem::replace(block, Block::new(merge_label)),
Instruction::branch(merge_label),
);
// Now that we're in the merge block, build the phi instructions.
merge_types.write_phis(ctx, block, &values)
}
}
}
/// Return the id of the merge block, writing a merge instruction if needed.
fn make_merge_label(&mut self, ctx: &mut BlockContext) -> Word {
match self.merge_label {
None => {
let merge_label = ctx.gen_id();
self.block.body.push(Instruction::selection_merge(
merge_label,
spirv::SelectionControl::NONE,
));
self.merge_label = Some(merge_label);
merge_label
}
Some(merge_label) => merge_label,
}
}
}
/// A trait to help `Selection` manage any number of merged values.
///
/// Some selection constructs, like a `ReadZeroSkipWrite` bounds check on a
/// [`Load`] expression, produce a single merged value. Others produce no merged
/// value, like a bounds check on a [`Store`] statement.
///
/// To let `Selection` work nicely with both cases, we let the merge type
/// argument passed to [`Selection::start`] be any type that implements this
/// `MergeTuple` trait. `MergeTuple` is then implemented for `()`, `Word`,
/// `(Word, Word)`, and so on.
///
/// A `MergeTuple` type can represent either a bunch of SPIR-V types or values;
/// the `merge_types` argument to `Selection::start` are type ids, whereas the
/// `values` arguments to the [`if_true`] and [`finish`] methods are value ids.
/// The set of merged value returned by `finish` is a tuple of value ids.
///
/// In fact, since Naga only uses zero- and single-valued selection constructs
/// at present, we only implement `MergeTuple` for `()` and `Word`. But if you
/// add more cases, feel free to add more implementations. Once const generics
/// are available, we could have a single implementation of `MergeTuple` for all
/// lengths of arrays, and be done with it.
///
/// [`Load`]: crate::Expression::Load
/// [`Store`]: crate::Statement::Store
/// [`if_true`]: Selection::if_true
/// [`finish`]: Selection::finish
pub(super) trait MergeTuple: Sized {
/// Write OpPhi instructions for the given set of predecessors.
///
/// The `predecessors` vector should be a vector of `(LABEL, VALUES)` pairs,
/// where each `VALUES` holds the values contributed by the branch from
/// `LABEL`, which should be one of the current block's predecessors.
fn write_phis(
self,
ctx: &mut BlockContext,
block: &mut Block,
predecessors: &[(Self, Word)],
) -> Self;
}
/// Selections that produce a single merged value.
///
/// For example, `ImageLoad` with `BoundsCheckPolicy::ReadZeroSkipWrite` either
/// returns a texel value or zeros.
impl MergeTuple for Word {
fn write_phis(
self,
ctx: &mut BlockContext,
block: &mut Block,
predecessors: &[(Word, Word)],
) -> Word {
let merged_value = ctx.gen_id();
block
.body
.push(Instruction::phi(self, merged_value, predecessors));
merged_value
}
}
/// Selections that produce no merged values.
///
/// For example, `ImageStore` under `BoundsCheckPolicy::ReadZeroSkipWrite`
/// either does the store or skips it, but in neither case does it produce a
/// value.
impl MergeTuple for () {
/// No phis need to be generated.
fn write_phis(self, _: &mut BlockContext, _: &mut Block, _: &[((), Word)]) {}
}
+209
View File
@@ -0,0 +1,209 @@
use super::{Block, BlockContext, Error, Instruction, NumericType};
use crate::{
arena::Handle,
back::spv::{LocalType, LookupType},
TypeInner,
};
impl BlockContext<'_> {
pub(super) fn write_subgroup_ballot(
&mut self,
predicate: &Option<Handle<crate::Expression>>,
result: Handle<crate::Expression>,
block: &mut Block,
) -> Result<(), Error> {
self.writer.require_any(
"GroupNonUniformBallot",
&[spirv::Capability::GroupNonUniformBallot],
)?;
let vec4_u32_type_id =
self.get_type_id(LookupType::Local(LocalType::Numeric(NumericType::Vector {
size: crate::VectorSize::Quad,
scalar: crate::Scalar::U32,
})));
let exec_scope_id = self.get_index_constant(spirv::Scope::Subgroup as u32);
let predicate = if let Some(predicate) = *predicate {
self.cached[predicate]
} else {
self.writer.get_constant_scalar(crate::Literal::Bool(true))
};
let id = self.gen_id();
block.body.push(Instruction::group_non_uniform_ballot(
vec4_u32_type_id,
id,
exec_scope_id,
predicate,
));
self.cached[result] = id;
Ok(())
}
pub(super) fn write_subgroup_operation(
&mut self,
op: &crate::SubgroupOperation,
collective_op: &crate::CollectiveOperation,
argument: Handle<crate::Expression>,
result: Handle<crate::Expression>,
block: &mut Block,
) -> Result<(), Error> {
use crate::SubgroupOperation as sg;
match *op {
sg::All | sg::Any => {
self.writer.require_any(
"GroupNonUniformVote",
&[spirv::Capability::GroupNonUniformVote],
)?;
}
_ => {
self.writer.require_any(
"GroupNonUniformArithmetic",
&[spirv::Capability::GroupNonUniformArithmetic],
)?;
}
}
let id = self.gen_id();
let result_ty = &self.fun_info[result].ty;
let result_type_id = self.get_expression_type_id(result_ty);
let result_ty_inner = result_ty.inner_with(&self.ir_module.types);
let (is_scalar, scalar) = match *result_ty_inner {
TypeInner::Scalar(kind) => (true, kind),
TypeInner::Vector { scalar: kind, .. } => (false, kind),
_ => unimplemented!(),
};
use crate::ScalarKind as sk;
let spirv_op = match (scalar.kind, *op) {
(sk::Bool, sg::All) if is_scalar => spirv::Op::GroupNonUniformAll,
(sk::Bool, sg::Any) if is_scalar => spirv::Op::GroupNonUniformAny,
(_, sg::All | sg::Any) => unimplemented!(),
(sk::Sint | sk::Uint, sg::Add) => spirv::Op::GroupNonUniformIAdd,
(sk::Float, sg::Add) => spirv::Op::GroupNonUniformFAdd,
(sk::Sint | sk::Uint, sg::Mul) => spirv::Op::GroupNonUniformIMul,
(sk::Float, sg::Mul) => spirv::Op::GroupNonUniformFMul,
(sk::Sint, sg::Max) => spirv::Op::GroupNonUniformSMax,
(sk::Uint, sg::Max) => spirv::Op::GroupNonUniformUMax,
(sk::Float, sg::Max) => spirv::Op::GroupNonUniformFMax,
(sk::Sint, sg::Min) => spirv::Op::GroupNonUniformSMin,
(sk::Uint, sg::Min) => spirv::Op::GroupNonUniformUMin,
(sk::Float, sg::Min) => spirv::Op::GroupNonUniformFMin,
(_, sg::Add | sg::Mul | sg::Min | sg::Max) => unimplemented!(),
(sk::Sint | sk::Uint, sg::And) => spirv::Op::GroupNonUniformBitwiseAnd,
(sk::Sint | sk::Uint, sg::Or) => spirv::Op::GroupNonUniformBitwiseOr,
(sk::Sint | sk::Uint, sg::Xor) => spirv::Op::GroupNonUniformBitwiseXor,
(sk::Bool, sg::And) => spirv::Op::GroupNonUniformLogicalAnd,
(sk::Bool, sg::Or) => spirv::Op::GroupNonUniformLogicalOr,
(sk::Bool, sg::Xor) => spirv::Op::GroupNonUniformLogicalXor,
(_, sg::And | sg::Or | sg::Xor) => unimplemented!(),
};
let exec_scope_id = self.get_index_constant(spirv::Scope::Subgroup as u32);
use crate::CollectiveOperation as c;
let group_op = match *op {
sg::All | sg::Any => None,
_ => Some(match *collective_op {
c::Reduce => spirv::GroupOperation::Reduce,
c::InclusiveScan => spirv::GroupOperation::InclusiveScan,
c::ExclusiveScan => spirv::GroupOperation::ExclusiveScan,
}),
};
let arg_id = self.cached[argument];
block.body.push(Instruction::group_non_uniform_arithmetic(
spirv_op,
result_type_id,
id,
exec_scope_id,
group_op,
arg_id,
));
self.cached[result] = id;
Ok(())
}
pub(super) fn write_subgroup_gather(
&mut self,
mode: &crate::GatherMode,
argument: Handle<crate::Expression>,
result: Handle<crate::Expression>,
block: &mut Block,
) -> Result<(), Error> {
self.writer.require_any(
"GroupNonUniformBallot",
&[spirv::Capability::GroupNonUniformBallot],
)?;
match *mode {
crate::GatherMode::BroadcastFirst => {
self.writer.require_any(
"GroupNonUniformBallot",
&[spirv::Capability::GroupNonUniformBallot],
)?;
}
crate::GatherMode::Shuffle(_)
| crate::GatherMode::ShuffleXor(_)
| crate::GatherMode::Broadcast(_) => {
self.writer.require_any(
"GroupNonUniformShuffle",
&[spirv::Capability::GroupNonUniformShuffle],
)?;
}
crate::GatherMode::ShuffleDown(_) | crate::GatherMode::ShuffleUp(_) => {
self.writer.require_any(
"GroupNonUniformShuffleRelative",
&[spirv::Capability::GroupNonUniformShuffleRelative],
)?;
}
}
let id = self.gen_id();
let result_ty = &self.fun_info[result].ty;
let result_type_id = self.get_expression_type_id(result_ty);
let exec_scope_id = self.get_index_constant(spirv::Scope::Subgroup as u32);
let arg_id = self.cached[argument];
match *mode {
crate::GatherMode::BroadcastFirst => {
block
.body
.push(Instruction::group_non_uniform_broadcast_first(
result_type_id,
id,
exec_scope_id,
arg_id,
));
}
crate::GatherMode::Broadcast(index)
| crate::GatherMode::Shuffle(index)
| crate::GatherMode::ShuffleDown(index)
| crate::GatherMode::ShuffleUp(index)
| crate::GatherMode::ShuffleXor(index) => {
let index_id = self.cached[index];
let op = match *mode {
crate::GatherMode::BroadcastFirst => unreachable!(),
// Use shuffle to emit broadcast to allow the index to
// be dynamically uniform on Vulkan 1.1. The argument to
// OpGroupNonUniformBroadcast must be a constant pre SPIR-V
// 1.5 (vulkan 1.2)
crate::GatherMode::Broadcast(_) => spirv::Op::GroupNonUniformShuffle,
crate::GatherMode::Shuffle(_) => spirv::Op::GroupNonUniformShuffle,
crate::GatherMode::ShuffleDown(_) => spirv::Op::GroupNonUniformShuffleDown,
crate::GatherMode::ShuffleUp(_) => spirv::Op::GroupNonUniformShuffleUp,
crate::GatherMode::ShuffleXor(_) => spirv::Op::GroupNonUniformShuffleXor,
};
block.body.push(Instruction::group_non_uniform_gather(
op,
result_type_id,
id,
exec_scope_id,
arg_id,
index_id,
));
}
}
self.cached[result] = id;
Ok(())
}
}
+2121
View File
File diff suppressed because it is too large Load Diff
+53
View File
@@ -0,0 +1,53 @@
/*!
Backend for [WGSL][wgsl] (WebGPU Shading Language).
[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html
*/
mod polyfill;
mod writer;
use thiserror::Error;
pub use writer::{Writer, WriterFlags};
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
FmtError(#[from] std::fmt::Error),
#[error("{0}")]
Custom(String),
#[error("{0}")]
Unimplemented(String), // TODO: Error used only during development
#[error("Unsupported math function: {0:?}")]
UnsupportedMathFunction(crate::MathFunction),
#[error("Unsupported relational function: {0:?}")]
UnsupportedRelationalFunction(crate::RelationalFunction),
}
pub fn write_string(
module: &crate::Module,
info: &crate::valid::ModuleInfo,
flags: WriterFlags,
) -> Result<String, Error> {
let mut w = Writer::new(String::new(), flags);
w.write(module, info)?;
let output = w.finish();
Ok(output)
}
impl crate::AtomicFunction {
const fn to_wgsl(self) -> &'static str {
match self {
Self::Add => "Add",
Self::Subtract => "Sub",
Self::And => "And",
Self::InclusiveOr => "Or",
Self::ExclusiveOr => "Xor",
Self::Min => "Min",
Self::Max => "Max",
Self::Exchange { compare: None } => "Exchange",
Self::Exchange { .. } => "CompareExchangeWeak",
}
}
}
@@ -0,0 +1,10 @@
fn _naga_inverse_2x2_f16(m: mat2x2<f16>) -> mat2x2<f16> {
var adj: mat2x2<f16>;
adj[0][0] = m[1][1];
adj[0][1] = -m[0][1];
adj[1][0] = -m[1][0];
adj[1][1] = m[0][0];
let det: f16 = m[0][0] * m[1][1] - m[1][0] * m[0][1];
return adj * (1 / det);
}
@@ -0,0 +1,10 @@
fn _naga_inverse_2x2_f32(m: mat2x2<f32>) -> mat2x2<f32> {
var adj: mat2x2<f32>;
adj[0][0] = m[1][1];
adj[0][1] = -m[0][1];
adj[1][0] = -m[1][0];
adj[1][1] = m[0][0];
let det: f32 = m[0][0] * m[1][1] - m[1][0] * m[0][1];
return adj * (1 / det);
}
@@ -0,0 +1,19 @@
fn _naga_inverse_3x3_f16(m: mat3x3<f16>) -> mat3x3<f16> {
var adj: mat3x3<f16>;
adj[0][0] = (m[1][1] * m[2][2] - m[2][1] * m[1][2]);
adj[1][0] = - (m[1][0] * m[2][2] - m[2][0] * m[1][2]);
adj[2][0] = (m[1][0] * m[2][1] - m[2][0] * m[1][1]);
adj[0][1] = - (m[0][1] * m[2][2] - m[2][1] * m[0][2]);
adj[1][1] = (m[0][0] * m[2][2] - m[2][0] * m[0][2]);
adj[2][1] = - (m[0][0] * m[2][1] - m[2][0] * m[0][1]);
adj[0][2] = (m[0][1] * m[1][2] - m[1][1] * m[0][2]);
adj[1][2] = - (m[0][0] * m[1][2] - m[1][0] * m[0][2]);
adj[2][2] = (m[0][0] * m[1][1] - m[1][0] * m[0][1]);
let det: f16 = (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]));
return adj * (1 / det);
}
@@ -0,0 +1,19 @@
fn _naga_inverse_3x3_f32(m: mat3x3<f32>) -> mat3x3<f32> {
var adj: mat3x3<f32>;
adj[0][0] = (m[1][1] * m[2][2] - m[2][1] * m[1][2]);
adj[1][0] = - (m[1][0] * m[2][2] - m[2][0] * m[1][2]);
adj[2][0] = (m[1][0] * m[2][1] - m[2][0] * m[1][1]);
adj[0][1] = - (m[0][1] * m[2][2] - m[2][1] * m[0][2]);
adj[1][1] = (m[0][0] * m[2][2] - m[2][0] * m[0][2]);
adj[2][1] = - (m[0][0] * m[2][1] - m[2][0] * m[0][1]);
adj[0][2] = (m[0][1] * m[1][2] - m[1][1] * m[0][2]);
adj[1][2] = - (m[0][0] * m[1][2] - m[1][0] * m[0][2]);
adj[2][2] = (m[0][0] * m[1][1] - m[1][0] * m[0][1]);
let det: f32 = (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]));
return adj * (1 / det);
}
@@ -0,0 +1,43 @@
fn _naga_inverse_4x4_f16(m: mat4x4<f16>) -> mat4x4<f16> {
let sub_factor00: f16 = m[2][2] * m[3][3] - m[3][2] * m[2][3];
let sub_factor01: f16 = m[2][1] * m[3][3] - m[3][1] * m[2][3];
let sub_factor02: f16 = m[2][1] * m[3][2] - m[3][1] * m[2][2];
let sub_factor03: f16 = m[2][0] * m[3][3] - m[3][0] * m[2][3];
let sub_factor04: f16 = m[2][0] * m[3][2] - m[3][0] * m[2][2];
let sub_factor05: f16 = m[2][0] * m[3][1] - m[3][0] * m[2][1];
let sub_factor06: f16 = m[1][2] * m[3][3] - m[3][2] * m[1][3];
let sub_factor07: f16 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
let sub_factor08: f16 = m[1][1] * m[3][2] - m[3][1] * m[1][2];
let sub_factor09: f16 = m[1][0] * m[3][3] - m[3][0] * m[1][3];
let sub_factor10: f16 = m[1][0] * m[3][2] - m[3][0] * m[1][2];
let sub_factor11: f16 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
let sub_factor12: f16 = m[1][0] * m[3][1] - m[3][0] * m[1][1];
let sub_factor13: f16 = m[1][2] * m[2][3] - m[2][2] * m[1][3];
let sub_factor14: f16 = m[1][1] * m[2][3] - m[2][1] * m[1][3];
let sub_factor15: f16 = m[1][1] * m[2][2] - m[2][1] * m[1][2];
let sub_factor16: f16 = m[1][0] * m[2][3] - m[2][0] * m[1][3];
let sub_factor17: f16 = m[1][0] * m[2][2] - m[2][0] * m[1][2];
let sub_factor18: f16 = m[1][0] * m[2][1] - m[2][0] * m[1][1];
var adj: mat4x4<f16>;
adj[0][0] = (m[1][1] * sub_factor00 - m[1][2] * sub_factor01 + m[1][3] * sub_factor02);
adj[1][0] = - (m[1][0] * sub_factor00 - m[1][2] * sub_factor03 + m[1][3] * sub_factor04);
adj[2][0] = (m[1][0] * sub_factor01 - m[1][1] * sub_factor03 + m[1][3] * sub_factor05);
adj[3][0] = - (m[1][0] * sub_factor02 - m[1][1] * sub_factor04 + m[1][2] * sub_factor05);
adj[0][1] = - (m[0][1] * sub_factor00 - m[0][2] * sub_factor01 + m[0][3] * sub_factor02);
adj[1][1] = (m[0][0] * sub_factor00 - m[0][2] * sub_factor03 + m[0][3] * sub_factor04);
adj[2][1] = - (m[0][0] * sub_factor01 - m[0][1] * sub_factor03 + m[0][3] * sub_factor05);
adj[3][1] = (m[0][0] * sub_factor02 - m[0][1] * sub_factor04 + m[0][2] * sub_factor05);
adj[0][2] = (m[0][1] * sub_factor06 - m[0][2] * sub_factor07 + m[0][3] * sub_factor08);
adj[1][2] = - (m[0][0] * sub_factor06 - m[0][2] * sub_factor09 + m[0][3] * sub_factor10);
adj[2][2] = (m[0][0] * sub_factor11 - m[0][1] * sub_factor09 + m[0][3] * sub_factor12);
adj[3][2] = - (m[0][0] * sub_factor08 - m[0][1] * sub_factor10 + m[0][2] * sub_factor12);
adj[0][3] = - (m[0][1] * sub_factor13 - m[0][2] * sub_factor14 + m[0][3] * sub_factor15);
adj[1][3] = (m[0][0] * sub_factor13 - m[0][2] * sub_factor16 + m[0][3] * sub_factor17);
adj[2][3] = - (m[0][0] * sub_factor14 - m[0][1] * sub_factor16 + m[0][3] * sub_factor18);
adj[3][3] = (m[0][0] * sub_factor15 - m[0][1] * sub_factor17 + m[0][2] * sub_factor18);
let det = (m[0][0] * adj[0][0] + m[0][1] * adj[1][0] + m[0][2] * adj[2][0] + m[0][3] * adj[3][0]);
return adj * (1 / det);
}
@@ -0,0 +1,43 @@
fn _naga_inverse_4x4_f32(m: mat4x4<f32>) -> mat4x4<f32> {
let sub_factor00: f32 = m[2][2] * m[3][3] - m[3][2] * m[2][3];
let sub_factor01: f32 = m[2][1] * m[3][3] - m[3][1] * m[2][3];
let sub_factor02: f32 = m[2][1] * m[3][2] - m[3][1] * m[2][2];
let sub_factor03: f32 = m[2][0] * m[3][3] - m[3][0] * m[2][3];
let sub_factor04: f32 = m[2][0] * m[3][2] - m[3][0] * m[2][2];
let sub_factor05: f32 = m[2][0] * m[3][1] - m[3][0] * m[2][1];
let sub_factor06: f32 = m[1][2] * m[3][3] - m[3][2] * m[1][3];
let sub_factor07: f32 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
let sub_factor08: f32 = m[1][1] * m[3][2] - m[3][1] * m[1][2];
let sub_factor09: f32 = m[1][0] * m[3][3] - m[3][0] * m[1][3];
let sub_factor10: f32 = m[1][0] * m[3][2] - m[3][0] * m[1][2];
let sub_factor11: f32 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
let sub_factor12: f32 = m[1][0] * m[3][1] - m[3][0] * m[1][1];
let sub_factor13: f32 = m[1][2] * m[2][3] - m[2][2] * m[1][3];
let sub_factor14: f32 = m[1][1] * m[2][3] - m[2][1] * m[1][3];
let sub_factor15: f32 = m[1][1] * m[2][2] - m[2][1] * m[1][2];
let sub_factor16: f32 = m[1][0] * m[2][3] - m[2][0] * m[1][3];
let sub_factor17: f32 = m[1][0] * m[2][2] - m[2][0] * m[1][2];
let sub_factor18: f32 = m[1][0] * m[2][1] - m[2][0] * m[1][1];
var adj: mat4x4<f32>;
adj[0][0] = (m[1][1] * sub_factor00 - m[1][2] * sub_factor01 + m[1][3] * sub_factor02);
adj[1][0] = - (m[1][0] * sub_factor00 - m[1][2] * sub_factor03 + m[1][3] * sub_factor04);
adj[2][0] = (m[1][0] * sub_factor01 - m[1][1] * sub_factor03 + m[1][3] * sub_factor05);
adj[3][0] = - (m[1][0] * sub_factor02 - m[1][1] * sub_factor04 + m[1][2] * sub_factor05);
adj[0][1] = - (m[0][1] * sub_factor00 - m[0][2] * sub_factor01 + m[0][3] * sub_factor02);
adj[1][1] = (m[0][0] * sub_factor00 - m[0][2] * sub_factor03 + m[0][3] * sub_factor04);
adj[2][1] = - (m[0][0] * sub_factor01 - m[0][1] * sub_factor03 + m[0][3] * sub_factor05);
adj[3][1] = (m[0][0] * sub_factor02 - m[0][1] * sub_factor04 + m[0][2] * sub_factor05);
adj[0][2] = (m[0][1] * sub_factor06 - m[0][2] * sub_factor07 + m[0][3] * sub_factor08);
adj[1][2] = - (m[0][0] * sub_factor06 - m[0][2] * sub_factor09 + m[0][3] * sub_factor10);
adj[2][2] = (m[0][0] * sub_factor11 - m[0][1] * sub_factor09 + m[0][3] * sub_factor12);
adj[3][2] = - (m[0][0] * sub_factor08 - m[0][1] * sub_factor10 + m[0][2] * sub_factor12);
adj[0][3] = - (m[0][1] * sub_factor13 - m[0][2] * sub_factor14 + m[0][3] * sub_factor15);
adj[1][3] = (m[0][0] * sub_factor13 - m[0][2] * sub_factor16 + m[0][3] * sub_factor17);
adj[2][3] = - (m[0][0] * sub_factor14 - m[0][1] * sub_factor16 + m[0][3] * sub_factor18);
adj[3][3] = (m[0][0] * sub_factor15 - m[0][1] * sub_factor17 + m[0][2] * sub_factor18);
let det = (m[0][0] * adj[0][0] + m[0][1] * adj[1][0] + m[0][2] * adj[2][0] + m[0][3] * adj[3][0]);
return adj * (1 / det);
}
+66
View File
@@ -0,0 +1,66 @@
use crate::{ScalarKind, TypeInner, VectorSize};
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct InversePolyfill {
pub fun_name: &'static str,
pub source: &'static str,
}
impl InversePolyfill {
pub fn find_overload(ty: &TypeInner) -> Option<InversePolyfill> {
let &TypeInner::Matrix {
columns,
rows,
scalar,
} = ty
else {
return None;
};
if columns != rows || scalar.kind != ScalarKind::Float {
return None;
};
Self::polyfill_overload(columns, scalar.width)
}
const fn polyfill_overload(
dimension: VectorSize,
width: crate::Bytes,
) -> Option<InversePolyfill> {
const INVERSE_2X2_F32: &str = include_str!("inverse/inverse_2x2_f32.wgsl");
const INVERSE_3X3_F32: &str = include_str!("inverse/inverse_3x3_f32.wgsl");
const INVERSE_4X4_F32: &str = include_str!("inverse/inverse_4x4_f32.wgsl");
const INVERSE_2X2_F16: &str = include_str!("inverse/inverse_2x2_f16.wgsl");
const INVERSE_3X3_F16: &str = include_str!("inverse/inverse_3x3_f16.wgsl");
const INVERSE_4X4_F16: &str = include_str!("inverse/inverse_4x4_f16.wgsl");
match (dimension, width) {
(VectorSize::Bi, 4) => Some(InversePolyfill {
fun_name: "_naga_inverse_2x2_f32",
source: INVERSE_2X2_F32,
}),
(VectorSize::Tri, 4) => Some(InversePolyfill {
fun_name: "_naga_inverse_3x3_f32",
source: INVERSE_3X3_F32,
}),
(VectorSize::Quad, 4) => Some(InversePolyfill {
fun_name: "_naga_inverse_4x4_f32",
source: INVERSE_4X4_F32,
}),
(VectorSize::Bi, 2) => Some(InversePolyfill {
fun_name: "_naga_inverse_2x2_f16",
source: INVERSE_2X2_F16,
}),
(VectorSize::Tri, 2) => Some(InversePolyfill {
fun_name: "_naga_inverse_3x3_f16",
source: INVERSE_3X3_F16,
}),
(VectorSize::Quad, 2) => Some(InversePolyfill {
fun_name: "_naga_inverse_4x4_f16",
source: INVERSE_4X4_F16,
}),
_ => None,
}
}
}
File diff suppressed because it is too large Load Diff
+129
View File
@@ -0,0 +1,129 @@
use crate::{Span, Statement};
use std::ops::{Deref, DerefMut, RangeBounds};
/// A code block is a vector of statements, with maybe a vector of spans.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "serialize", serde(transparent))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Block {
body: Vec<Statement>,
#[cfg_attr(feature = "serialize", serde(skip))]
span_info: Vec<Span>,
}
impl Block {
pub const fn new() -> Self {
Self {
body: Vec::new(),
span_info: Vec::new(),
}
}
pub fn from_vec(body: Vec<Statement>) -> Self {
let span_info = std::iter::repeat(Span::default())
.take(body.len())
.collect();
Self { body, span_info }
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
body: Vec::with_capacity(capacity),
span_info: Vec::with_capacity(capacity),
}
}
#[allow(unused_variables)]
pub fn push(&mut self, end: Statement, span: Span) {
self.body.push(end);
self.span_info.push(span);
}
pub fn extend(&mut self, item: Option<(Statement, Span)>) {
if let Some((end, span)) = item {
self.push(end, span)
}
}
pub fn extend_block(&mut self, other: Self) {
self.span_info.extend(other.span_info);
self.body.extend(other.body);
}
pub fn append(&mut self, other: &mut Self) {
self.span_info.append(&mut other.span_info);
self.body.append(&mut other.body);
}
pub fn cull<R: RangeBounds<usize> + Clone>(&mut self, range: R) {
self.span_info.drain(range.clone());
self.body.drain(range);
}
pub fn splice<R: RangeBounds<usize> + Clone>(&mut self, range: R, other: Self) {
self.span_info.splice(range.clone(), other.span_info);
self.body.splice(range, other.body);
}
pub fn span_into_iter(self) -> impl Iterator<Item = (Statement, Span)> {
let Block { body, span_info } = self;
body.into_iter().zip(span_info)
}
pub fn span_iter(&self) -> impl Iterator<Item = (&Statement, &Span)> {
let span_iter = self.span_info.iter();
self.body.iter().zip(span_iter)
}
pub fn span_iter_mut(&mut self) -> impl Iterator<Item = (&mut Statement, Option<&mut Span>)> {
let span_iter = self.span_info.iter_mut().map(Some);
self.body.iter_mut().zip(span_iter)
}
pub fn is_empty(&self) -> bool {
self.body.is_empty()
}
pub fn len(&self) -> usize {
self.body.len()
}
}
impl Deref for Block {
type Target = [Statement];
fn deref(&self) -> &[Statement] {
&self.body
}
}
impl DerefMut for Block {
fn deref_mut(&mut self) -> &mut [Statement] {
&mut self.body
}
}
impl<'a> IntoIterator for &'a Block {
type Item = &'a Statement;
type IntoIter = std::slice::Iter<'a, Statement>;
fn into_iter(self) -> std::slice::Iter<'a, Statement> {
self.iter()
}
}
#[cfg(feature = "deserialize")]
impl<'de> serde::Deserialize<'de> for Block {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Self::from_vec(Vec::deserialize(deserializer)?))
}
}
impl From<Vec<Statement>> for Block {
fn from(body: Vec<Statement>) -> Self {
Self::from_vec(body)
}
}
+3
View File
@@ -0,0 +1,3 @@
//! Code common to the front and backends for specific languages.
pub mod wgsl;
+69
View File
@@ -0,0 +1,69 @@
//! Code shared between the WGSL front and back ends.
use std::fmt::{self, Display, Formatter};
use crate::diagnostic_filter::{
FilterableTriggeringRule, Severity, StandardFilterableTriggeringRule,
};
impl Severity {
const ERROR: &'static str = "error";
const WARNING: &'static str = "warning";
const INFO: &'static str = "info";
const OFF: &'static str = "off";
/// Convert from a sentinel word in WGSL into its associated [`Severity`], if possible.
pub fn from_wgsl_ident(s: &str) -> Option<Self> {
Some(match s {
Self::ERROR => Self::Error,
Self::WARNING => Self::Warning,
Self::INFO => Self::Info,
Self::OFF => Self::Off,
_ => return None,
})
}
}
struct DisplayFilterableTriggeringRule<'a>(&'a FilterableTriggeringRule);
impl Display for DisplayFilterableTriggeringRule<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let &Self(inner) = self;
match *inner {
FilterableTriggeringRule::Standard(rule) => write!(f, "{}", rule.to_wgsl_ident()),
FilterableTriggeringRule::Unknown(ref rule) => write!(f, "{rule}"),
FilterableTriggeringRule::User(ref rules) => {
let &[ref seg1, ref seg2] = rules.as_ref();
write!(f, "{seg1}.{seg2}")
}
}
}
}
impl FilterableTriggeringRule {
/// [`Display`] this rule's identifiers in WGSL.
pub const fn display_wgsl_ident(&self) -> impl Display + '_ {
DisplayFilterableTriggeringRule(self)
}
}
impl StandardFilterableTriggeringRule {
const DERIVATIVE_UNIFORMITY: &'static str = "derivative_uniformity";
/// Convert from a sentinel word in WGSL into its associated
/// [`StandardFilterableTriggeringRule`], if possible.
pub fn from_wgsl_ident(s: &str) -> Option<Self> {
Some(match s {
Self::DERIVATIVE_UNIFORMITY => Self::DerivativeUniformity,
_ => return None,
})
}
/// Maps this [`StandardFilterableTriggeringRule`] into the sentinel word associated with it in
/// WGSL.
pub const fn to_wgsl_ident(self) -> &'static str {
match self {
Self::DerivativeUniformity => Self::DERIVATIVE_UNIFORMITY,
}
}
}
+427
View File
@@ -0,0 +1,427 @@
use super::{HandleMap, HandleSet, ModuleMap};
use crate::arena::{Arena, Handle};
pub struct ExpressionTracer<'tracer> {
pub constants: &'tracer Arena<crate::Constant>,
/// The arena in which we are currently tracing expressions.
pub expressions: &'tracer Arena<crate::Expression>,
/// The used map for `types`.
pub types_used: &'tracer mut HandleSet<crate::Type>,
/// The used map for `constants`.
pub constants_used: &'tracer mut HandleSet<crate::Constant>,
/// The used set for `arena`.
///
/// This points to whatever arena holds the expressions we are
/// currently tracing: either a function's expression arena, or
/// the module's constant expression arena.
pub expressions_used: &'tracer mut HandleSet<crate::Expression>,
/// The used set for the module's `global_expressions` arena.
///
/// If `None`, we are already tracing the constant expressions,
/// and `expressions_used` already refers to their handle set.
pub global_expressions_used: Option<&'tracer mut HandleSet<crate::Expression>>,
}
impl ExpressionTracer<'_> {
/// Propagate usage through `self.expressions`, starting with `self.expressions_used`.
///
/// Treat `self.expressions_used` as the initial set of "known
/// live" expressions, and follow through to identify all
/// transitively used expressions.
///
/// Mark types, constants, and constant expressions used directly
/// by `self.expressions` as used. Items used indirectly are not
/// marked.
///
/// [fe]: crate::Function::expressions
/// [ce]: crate::Module::global_expressions
pub fn trace_expressions(&mut self) {
log::trace!(
"entering trace_expression of {}",
if self.global_expressions_used.is_some() {
"function expressions"
} else {
"const expressions"
}
);
// We don't need recursion or a work list. Because an
// expression may only refer to other expressions that precede
// it in the arena, it suffices to make a single pass over the
// arena from back to front, marking the referents of used
// expressions as used themselves.
for (handle, expr) in self.expressions.iter().rev() {
// If this expression isn't used, it doesn't matter what it uses.
if !self.expressions_used.contains(handle) {
continue;
}
log::trace!("tracing new expression {:?}", expr);
use crate::Expression as Ex;
match *expr {
// Expressions that do not contain handles that need to be traced.
Ex::Literal(_)
| Ex::FunctionArgument(_)
| Ex::GlobalVariable(_)
| Ex::LocalVariable(_)
| Ex::CallResult(_)
| Ex::SubgroupBallotResult
| Ex::RayQueryProceedResult => {}
Ex::Constant(handle) => {
self.constants_used.insert(handle);
// Constants and expressions are mutually recursive, which
// complicates our nice one-pass algorithm. However, since
// constants don't refer to each other, we can get around
// this by looking *through* each constant and marking its
// initializer as used. Since `expr` refers to the constant,
// and the constant refers to the initializer, it must
// precede `expr` in the arena.
let init = self.constants[handle].init;
match self.global_expressions_used {
Some(ref mut used) => used.insert(init),
None => self.expressions_used.insert(init),
};
}
Ex::Override(_) => {
// All overrides are considered used by definition. We mark
// their types and initialization expressions as used in
// `compact::compact`, so we have no more work to do here.
}
Ex::ZeroValue(ty) => {
self.types_used.insert(ty);
}
Ex::Compose { ty, ref components } => {
self.types_used.insert(ty);
self.expressions_used
.insert_iter(components.iter().cloned());
}
Ex::Access { base, index } => self.expressions_used.insert_iter([base, index]),
Ex::AccessIndex { base, index: _ } => {
self.expressions_used.insert(base);
}
Ex::Splat { size: _, value } => {
self.expressions_used.insert(value);
}
Ex::Swizzle {
size: _,
vector,
pattern: _,
} => {
self.expressions_used.insert(vector);
}
Ex::Load { pointer } => {
self.expressions_used.insert(pointer);
}
Ex::ImageSample {
image,
sampler,
gather: _,
coordinate,
array_index,
offset,
ref level,
depth_ref,
} => {
self.expressions_used
.insert_iter([image, sampler, coordinate]);
self.expressions_used.insert_iter(array_index);
match self.global_expressions_used {
Some(ref mut used) => used.insert_iter(offset),
None => self.expressions_used.insert_iter(offset),
}
use crate::SampleLevel as Sl;
match *level {
Sl::Auto | Sl::Zero => {}
Sl::Exact(expr) | Sl::Bias(expr) => {
self.expressions_used.insert(expr);
}
Sl::Gradient { x, y } => self.expressions_used.insert_iter([x, y]),
}
self.expressions_used.insert_iter(depth_ref);
}
Ex::ImageLoad {
image,
coordinate,
array_index,
sample,
level,
} => {
self.expressions_used.insert(image);
self.expressions_used.insert(coordinate);
self.expressions_used.insert_iter(array_index);
self.expressions_used.insert_iter(sample);
self.expressions_used.insert_iter(level);
}
Ex::ImageQuery { image, ref query } => {
self.expressions_used.insert(image);
use crate::ImageQuery as Iq;
match *query {
Iq::Size { level } => self.expressions_used.insert_iter(level),
Iq::NumLevels | Iq::NumLayers | Iq::NumSamples => {}
}
}
Ex::Unary { op: _, expr } => {
self.expressions_used.insert(expr);
}
Ex::Binary { op: _, left, right } => {
self.expressions_used.insert_iter([left, right]);
}
Ex::Select {
condition,
accept,
reject,
} => self
.expressions_used
.insert_iter([condition, accept, reject]),
Ex::Derivative {
axis: _,
ctrl: _,
expr,
} => {
self.expressions_used.insert(expr);
}
Ex::Relational { fun: _, argument } => {
self.expressions_used.insert(argument);
}
Ex::Math {
fun: _,
arg,
arg1,
arg2,
arg3,
} => {
self.expressions_used.insert(arg);
self.expressions_used.insert_iter(arg1);
self.expressions_used.insert_iter(arg2);
self.expressions_used.insert_iter(arg3);
}
Ex::As {
expr,
kind: _,
convert: _,
} => {
self.expressions_used.insert(expr);
}
Ex::ArrayLength(expr) => {
self.expressions_used.insert(expr);
}
Ex::AtomicResult { ty, comparison: _ }
| Ex::WorkGroupUniformLoadResult { ty }
| Ex::SubgroupOperationResult { ty } => {
self.types_used.insert(ty);
}
Ex::RayQueryGetIntersection {
query,
committed: _,
} => {
self.expressions_used.insert(query);
}
}
}
}
}
impl ModuleMap {
/// Fix up all handles in `expr`.
///
/// Use the expression handle remappings in `operand_map`, and all
/// other mappings from `self`.
pub fn adjust_expression(
&self,
expr: &mut crate::Expression,
operand_map: &HandleMap<crate::Expression>,
) {
let adjust = |expr: &mut Handle<crate::Expression>| {
operand_map.adjust(expr);
};
use crate::Expression as Ex;
match *expr {
// Expressions that do not contain handles that need to be adjusted.
Ex::Literal(_)
| Ex::FunctionArgument(_)
| Ex::GlobalVariable(_)
| Ex::LocalVariable(_)
| Ex::CallResult(_)
| Ex::SubgroupBallotResult
| Ex::RayQueryProceedResult => {}
// All overrides are retained, so their handles never change.
Ex::Override(_) => {}
// Expressions that contain handles that need to be adjusted.
Ex::Constant(ref mut constant) => self.constants.adjust(constant),
Ex::ZeroValue(ref mut ty) => self.types.adjust(ty),
Ex::Compose {
ref mut ty,
ref mut components,
} => {
self.types.adjust(ty);
for component in components {
adjust(component);
}
}
Ex::Access {
ref mut base,
ref mut index,
} => {
adjust(base);
adjust(index);
}
Ex::AccessIndex {
ref mut base,
index: _,
} => adjust(base),
Ex::Splat {
size: _,
ref mut value,
} => adjust(value),
Ex::Swizzle {
size: _,
ref mut vector,
pattern: _,
} => adjust(vector),
Ex::Load { ref mut pointer } => adjust(pointer),
Ex::ImageSample {
ref mut image,
ref mut sampler,
gather: _,
ref mut coordinate,
ref mut array_index,
ref mut offset,
ref mut level,
ref mut depth_ref,
} => {
adjust(image);
adjust(sampler);
adjust(coordinate);
operand_map.adjust_option(array_index);
if let Some(ref mut offset) = *offset {
self.global_expressions.adjust(offset);
}
self.adjust_sample_level(level, operand_map);
operand_map.adjust_option(depth_ref);
}
Ex::ImageLoad {
ref mut image,
ref mut coordinate,
ref mut array_index,
ref mut sample,
ref mut level,
} => {
adjust(image);
adjust(coordinate);
operand_map.adjust_option(array_index);
operand_map.adjust_option(sample);
operand_map.adjust_option(level);
}
Ex::ImageQuery {
ref mut image,
ref mut query,
} => {
adjust(image);
self.adjust_image_query(query, operand_map);
}
Ex::Unary {
op: _,
ref mut expr,
} => adjust(expr),
Ex::Binary {
op: _,
ref mut left,
ref mut right,
} => {
adjust(left);
adjust(right);
}
Ex::Select {
ref mut condition,
ref mut accept,
ref mut reject,
} => {
adjust(condition);
adjust(accept);
adjust(reject);
}
Ex::Derivative {
axis: _,
ctrl: _,
ref mut expr,
} => adjust(expr),
Ex::Relational {
fun: _,
ref mut argument,
} => adjust(argument),
Ex::Math {
fun: _,
ref mut arg,
ref mut arg1,
ref mut arg2,
ref mut arg3,
} => {
adjust(arg);
operand_map.adjust_option(arg1);
operand_map.adjust_option(arg2);
operand_map.adjust_option(arg3);
}
Ex::As {
ref mut expr,
kind: _,
convert: _,
} => adjust(expr),
Ex::AtomicResult {
ref mut ty,
comparison: _,
} => self.types.adjust(ty),
Ex::WorkGroupUniformLoadResult { ref mut ty } => self.types.adjust(ty),
Ex::SubgroupOperationResult { ref mut ty } => self.types.adjust(ty),
Ex::ArrayLength(ref mut expr) => adjust(expr),
Ex::RayQueryGetIntersection {
ref mut query,
committed: _,
} => adjust(query),
}
}
fn adjust_sample_level(
&self,
level: &mut crate::SampleLevel,
operand_map: &HandleMap<crate::Expression>,
) {
let adjust = |expr: &mut Handle<crate::Expression>| operand_map.adjust(expr);
use crate::SampleLevel as Sl;
match *level {
Sl::Auto | Sl::Zero => {}
Sl::Exact(ref mut expr) => adjust(expr),
Sl::Bias(ref mut expr) => adjust(expr),
Sl::Gradient {
ref mut x,
ref mut y,
} => {
adjust(x);
adjust(y);
}
}
}
fn adjust_image_query(
&self,
query: &mut crate::ImageQuery,
operand_map: &HandleMap<crate::Expression>,
) {
use crate::ImageQuery as Iq;
match *query {
Iq::Size { ref mut level } => operand_map.adjust_option(level),
Iq::NumLevels | Iq::NumLayers | Iq::NumSamples => {}
}
}
}
+106
View File
@@ -0,0 +1,106 @@
use super::arena::HandleSet;
use super::{FunctionMap, ModuleMap};
pub struct FunctionTracer<'a> {
pub function: &'a crate::Function,
pub constants: &'a crate::Arena<crate::Constant>,
pub types_used: &'a mut HandleSet<crate::Type>,
pub constants_used: &'a mut HandleSet<crate::Constant>,
pub global_expressions_used: &'a mut HandleSet<crate::Expression>,
/// Function-local expressions used.
pub expressions_used: HandleSet<crate::Expression>,
}
impl FunctionTracer<'_> {
pub fn trace(&mut self) {
for argument in self.function.arguments.iter() {
self.types_used.insert(argument.ty);
}
if let Some(ref result) = self.function.result {
self.types_used.insert(result.ty);
}
for (_, local) in self.function.local_variables.iter() {
self.types_used.insert(local.ty);
if let Some(init) = local.init {
self.expressions_used.insert(init);
}
}
// Treat named expressions as alive, for the sake of our test suite,
// which uses `let blah = expr;` to exercise lots of things.
for (&value, _name) in &self.function.named_expressions {
self.expressions_used.insert(value);
}
self.trace_block(&self.function.body);
// Given that `trace_block` has marked the expressions used
// directly by statements, walk the arena to find all
// expressions used, directly or indirectly.
self.as_expression().trace_expressions();
}
fn as_expression(&mut self) -> super::expressions::ExpressionTracer {
super::expressions::ExpressionTracer {
constants: self.constants,
expressions: &self.function.expressions,
types_used: self.types_used,
constants_used: self.constants_used,
expressions_used: &mut self.expressions_used,
global_expressions_used: Some(&mut self.global_expressions_used),
}
}
}
impl FunctionMap {
pub fn compact(
&self,
function: &mut crate::Function,
module_map: &ModuleMap,
reuse: &mut crate::NamedExpressions,
) {
assert!(reuse.is_empty());
for argument in function.arguments.iter_mut() {
module_map.types.adjust(&mut argument.ty);
}
if let Some(ref mut result) = function.result {
module_map.types.adjust(&mut result.ty);
}
for (_, local) in function.local_variables.iter_mut() {
log::trace!("adjusting local variable {:?}", local.name);
module_map.types.adjust(&mut local.ty);
if let Some(ref mut init) = local.init {
self.expressions.adjust(init);
}
}
// Drop unused expressions, reusing existing storage.
function.expressions.retain_mut(|handle, expr| {
if self.expressions.used(handle) {
module_map.adjust_expression(expr, &self.expressions);
true
} else {
false
}
});
// Adjust named expressions.
for (mut handle, name) in function.named_expressions.drain(..) {
self.expressions.adjust(&mut handle);
reuse.insert(handle, name);
}
std::mem::swap(&mut function.named_expressions, reuse);
assert!(reuse.is_empty());
// Adjust statements.
self.adjust_body(function);
}
}
+106
View File
@@ -0,0 +1,106 @@
use crate::arena::{Arena, Handle, HandleSet, Range};
type Index = crate::non_max_u32::NonMaxU32;
/// A map from old handle indices to new, compressed handle indices.
pub struct HandleMap<T> {
/// The indices assigned to handles in the compacted module.
///
/// If `new_index[i]` is `Some(n)`, then `n` is the `Index` of the
/// compacted `Handle` corresponding to the pre-compacted `Handle`
/// whose index is `i`.
new_index: Vec<Option<Index>>,
/// This type is indexed by values of type `T`.
as_keys: std::marker::PhantomData<T>,
}
impl<T: 'static> HandleMap<T> {
pub fn from_set(set: HandleSet<T>) -> Self {
let mut next_index = Index::new(0).unwrap();
Self {
new_index: set
.all_possible()
.map(|handle| {
if set.contains(handle) {
// This handle will be retained in the compacted version,
// so assign it a new index.
let this = next_index;
next_index = next_index.checked_add(1).unwrap();
Some(this)
} else {
// This handle will be omitted in the compacted version.
None
}
})
.collect(),
as_keys: std::marker::PhantomData,
}
}
/// Return true if `old` is used in the compacted module.
pub fn used(&self, old: Handle<T>) -> bool {
self.new_index[old.index()].is_some()
}
/// Return the counterpart to `old` in the compacted module.
///
/// If we thought `old` wouldn't be used in the compacted module, return
/// `None`.
pub fn try_adjust(&self, old: Handle<T>) -> Option<Handle<T>> {
log::trace!(
"adjusting {} handle [{}] -> [{:?}]",
std::any::type_name::<T>(),
old.index(),
self.new_index[old.index()]
);
self.new_index[old.index()].map(Handle::new)
}
/// Return the counterpart to `old` in the compacted module.
///
/// If we thought `old` wouldn't be used in the compacted module, panic.
pub fn adjust(&self, handle: &mut Handle<T>) {
*handle = self.try_adjust(*handle).unwrap();
}
/// Like `adjust`, but for optional handles.
pub fn adjust_option(&self, handle: &mut Option<Handle<T>>) {
if let Some(ref mut handle) = *handle {
self.adjust(handle);
}
}
/// Shrink `range` to include only used handles.
///
/// Fortunately, compaction doesn't arbitrarily scramble the expressions
/// in the arena, but instead preserves the order of the elements while
/// squeezing out unused ones. That means that a contiguous range in the
/// pre-compacted arena always maps to a contiguous range in the
/// post-compacted arena. So we just need to adjust the endpoints.
///
/// Compaction may have eliminated the endpoints themselves.
///
/// Use `compacted_arena` to bounds-check the result.
pub fn adjust_range(&self, range: &mut Range<T>, compacted_arena: &Arena<T>) {
let mut index_range = range.index_range();
let compacted;
if let Some(first) = index_range.find_map(|i| self.new_index[i as usize]) {
// The first call to `find_map` mutated `index_range` to hold the
// remainder of original range, which is exactly the range we need
// to search for the new last handle.
if let Some(last) = index_range.rev().find_map(|i| self.new_index[i as usize]) {
// Build an end-exclusive range, given the two included indices
// `first` and `last`.
compacted = first.get()..last.get() + 1;
} else {
// The range contains only a single live handle, which
// we identified with the first `find_map` call.
compacted = first.get()..first.get() + 1;
}
} else {
compacted = 0..0;
};
*range = Range::from_index_range(compacted, compacted_arena);
}
}
+354
View File
@@ -0,0 +1,354 @@
mod expressions;
mod functions;
mod handle_set_map;
mod statements;
mod types;
use crate::arena::HandleSet;
use crate::{arena, compact::functions::FunctionTracer};
use handle_set_map::HandleMap;
/// Remove unused types, expressions, and constants from `module`.
///
/// Assuming that all globals, named constants, special types,
/// functions and entry points in `module` are used, determine which
/// types, constants, and expressions (both function-local and global
/// constant expressions) are actually used, and remove the rest,
/// adjusting all handles as necessary. The result should be a module
/// functionally identical to the original.
///
/// This may be useful to apply to modules generated in the snapshot
/// tests. Our backends often generate temporary names based on handle
/// indices, which means that adding or removing unused arena entries
/// can affect the output even though they have no semantic effect.
/// Such meaningless changes add noise to snapshot diffs, making
/// accurate patch review difficult. Compacting the modules before
/// generating snapshots makes the output independent of unused arena
/// entries.
///
/// # Panics
///
/// If `module` has not passed validation, this may panic.
pub fn compact(module: &mut crate::Module) {
let mut module_tracer = ModuleTracer::new(module);
// We treat all globals as used by definition.
log::trace!("tracing global variables");
{
for (_, global) in module.global_variables.iter() {
log::trace!("tracing global {:?}", global.name);
module_tracer.types_used.insert(global.ty);
if let Some(init) = global.init {
module_tracer.global_expressions_used.insert(init);
}
}
}
// We treat all special types as used by definition.
module_tracer.trace_special_types(&module.special_types);
// We treat all named constants as used by definition.
for (handle, constant) in module.constants.iter() {
if constant.name.is_some() {
module_tracer.constants_used.insert(handle);
module_tracer.global_expressions_used.insert(constant.init);
}
}
// We treat all overrides as used by definition.
for (_, override_) in module.overrides.iter() {
module_tracer.types_used.insert(override_.ty);
if let Some(init) = override_.init {
module_tracer.global_expressions_used.insert(init);
}
}
for (_, ty) in module.types.iter() {
if let crate::TypeInner::Array {
size: crate::ArraySize::Pending(crate::PendingArraySize::Expression(size_expr)),
..
} = ty.inner
{
module_tracer.global_expressions_used.insert(size_expr);
}
}
// We assume that all functions are used.
//
// Observe which types, constant expressions, constants, and
// expressions each function uses, and produce maps for each
// function from pre-compaction to post-compaction expression
// handles.
log::trace!("tracing functions");
let function_maps: Vec<FunctionMap> = module
.functions
.iter()
.map(|(_, f)| {
log::trace!("tracing function {:?}", f.name);
let mut function_tracer = module_tracer.as_function(f);
function_tracer.trace();
FunctionMap::from(function_tracer)
})
.collect();
// Similarly, observe what each entry point actually uses.
log::trace!("tracing entry points");
let entry_point_maps: Vec<FunctionMap> = module
.entry_points
.iter()
.map(|e| {
log::trace!("tracing entry point {:?}", e.function.name);
if let Some(sizes) = e.workgroup_size_overrides {
for size in sizes.iter().filter_map(|x| *x) {
module_tracer.global_expressions_used.insert(size);
}
}
let mut used = module_tracer.as_function(&e.function);
used.trace();
FunctionMap::from(used)
})
.collect();
// Given that the above steps have marked all the constant
// expressions used directly by globals, constants, functions, and
// entry points, walk the constant expression arena to find all
// constant expressions used, directly or indirectly.
module_tracer.as_const_expression().trace_expressions();
// Constants' initializers are taken care of already, because
// expression tracing sees through constants. But we still need to
// note type usage.
for (handle, constant) in module.constants.iter() {
if module_tracer.constants_used.contains(handle) {
module_tracer.types_used.insert(constant.ty);
}
}
// Treat all named types as used.
for (handle, ty) in module.types.iter() {
log::trace!("tracing type {:?}, name {:?}", handle, ty.name);
if ty.name.is_some() {
module_tracer.types_used.insert(handle);
}
}
// Propagate usage through types.
module_tracer.as_type().trace_types();
// Now that we know what is used and what is never touched,
// produce maps from the `Handle`s that appear in `module` now to
// the corresponding `Handle`s that will refer to the same items
// in the compacted module.
let module_map = ModuleMap::from(module_tracer);
// Drop unused types from the type arena.
//
// `FastIndexSet`s don't have an underlying Vec<T> that we can
// steal, compact in place, and then rebuild the `FastIndexSet`
// from. So we have to rebuild the type arena from scratch.
log::trace!("compacting types");
let mut new_types = arena::UniqueArena::new();
for (old_handle, mut ty, span) in module.types.drain_all() {
if let Some(expected_new_handle) = module_map.types.try_adjust(old_handle) {
module_map.adjust_type(&mut ty);
let actual_new_handle = new_types.insert(ty, span);
assert_eq!(actual_new_handle, expected_new_handle);
}
}
module.types = new_types;
log::trace!("adjusting special types");
module_map.adjust_special_types(&mut module.special_types);
// Drop unused constant expressions, reusing existing storage.
log::trace!("adjusting constant expressions");
module.global_expressions.retain_mut(|handle, expr| {
if module_map.global_expressions.used(handle) {
module_map.adjust_expression(expr, &module_map.global_expressions);
true
} else {
false
}
});
// Drop unused constants in place, reusing existing storage.
log::trace!("adjusting constants");
module.constants.retain_mut(|handle, constant| {
if module_map.constants.used(handle) {
module_map.types.adjust(&mut constant.ty);
module_map.global_expressions.adjust(&mut constant.init);
true
} else {
false
}
});
// Adjust override types and initializers.
log::trace!("adjusting overrides");
for (_, override_) in module.overrides.iter_mut() {
module_map.types.adjust(&mut override_.ty);
if let Some(init) = override_.init.as_mut() {
module_map.global_expressions.adjust(init);
}
}
// Adjust workgroup_size_overrides
log::trace!("adjusting workgroup_size_overrides");
for e in module.entry_points.iter_mut() {
if let Some(sizes) = e.workgroup_size_overrides.as_mut() {
for size in sizes.iter_mut() {
if let Some(expr) = size.as_mut() {
module_map.global_expressions.adjust(expr);
}
}
}
}
// Adjust global variables' types and initializers.
log::trace!("adjusting global variables");
for (_, global) in module.global_variables.iter_mut() {
log::trace!("adjusting global {:?}", global.name);
module_map.types.adjust(&mut global.ty);
if let Some(ref mut init) = global.init {
module_map.global_expressions.adjust(init);
}
}
// Temporary storage to help us reuse allocations of existing
// named expression tables.
let mut reused_named_expressions = crate::NamedExpressions::default();
// Compact each function.
for ((_, function), map) in module.functions.iter_mut().zip(function_maps.iter()) {
log::trace!("compacting function {:?}", function.name);
map.compact(function, &module_map, &mut reused_named_expressions);
}
// Compact each entry point.
for (entry, map) in module.entry_points.iter_mut().zip(entry_point_maps.iter()) {
log::trace!("compacting entry point {:?}", entry.function.name);
map.compact(
&mut entry.function,
&module_map,
&mut reused_named_expressions,
);
}
}
struct ModuleTracer<'module> {
module: &'module crate::Module,
types_used: HandleSet<crate::Type>,
constants_used: HandleSet<crate::Constant>,
global_expressions_used: HandleSet<crate::Expression>,
}
impl<'module> ModuleTracer<'module> {
fn new(module: &'module crate::Module) -> Self {
Self {
module,
types_used: HandleSet::for_arena(&module.types),
constants_used: HandleSet::for_arena(&module.constants),
global_expressions_used: HandleSet::for_arena(&module.global_expressions),
}
}
fn trace_special_types(&mut self, special_types: &crate::SpecialTypes) {
let crate::SpecialTypes {
ref ray_desc,
ref ray_intersection,
ref predeclared_types,
} = *special_types;
if let Some(ray_desc) = *ray_desc {
self.types_used.insert(ray_desc);
}
if let Some(ray_intersection) = *ray_intersection {
self.types_used.insert(ray_intersection);
}
for (_, &handle) in predeclared_types {
self.types_used.insert(handle);
}
}
fn as_type(&mut self) -> types::TypeTracer {
types::TypeTracer {
types: &self.module.types,
types_used: &mut self.types_used,
}
}
fn as_const_expression(&mut self) -> expressions::ExpressionTracer {
expressions::ExpressionTracer {
expressions: &self.module.global_expressions,
constants: &self.module.constants,
types_used: &mut self.types_used,
constants_used: &mut self.constants_used,
expressions_used: &mut self.global_expressions_used,
global_expressions_used: None,
}
}
pub fn as_function<'tracer>(
&'tracer mut self,
function: &'tracer crate::Function,
) -> FunctionTracer<'tracer> {
FunctionTracer {
function,
constants: &self.module.constants,
types_used: &mut self.types_used,
constants_used: &mut self.constants_used,
global_expressions_used: &mut self.global_expressions_used,
expressions_used: HandleSet::for_arena(&function.expressions),
}
}
}
struct ModuleMap {
types: HandleMap<crate::Type>,
constants: HandleMap<crate::Constant>,
global_expressions: HandleMap<crate::Expression>,
}
impl From<ModuleTracer<'_>> for ModuleMap {
fn from(used: ModuleTracer) -> Self {
ModuleMap {
types: HandleMap::from_set(used.types_used),
constants: HandleMap::from_set(used.constants_used),
global_expressions: HandleMap::from_set(used.global_expressions_used),
}
}
}
impl ModuleMap {
fn adjust_special_types(&self, special: &mut crate::SpecialTypes) {
let crate::SpecialTypes {
ref mut ray_desc,
ref mut ray_intersection,
ref mut predeclared_types,
} = *special;
if let Some(ref mut ray_desc) = *ray_desc {
self.types.adjust(ray_desc);
}
if let Some(ref mut ray_intersection) = *ray_intersection {
self.types.adjust(ray_intersection);
}
for handle in predeclared_types.values_mut() {
self.types.adjust(handle);
}
}
}
struct FunctionMap {
expressions: HandleMap<crate::Expression>,
}
impl From<FunctionTracer<'_>> for FunctionMap {
fn from(used: FunctionTracer) -> Self {
FunctionMap {
expressions: HandleMap::from_set(used.expressions_used),
}
}
}
+399
View File
@@ -0,0 +1,399 @@
use super::functions::FunctionTracer;
use super::FunctionMap;
use crate::arena::Handle;
impl FunctionTracer<'_> {
pub fn trace_block(&mut self, block: &[crate::Statement]) {
let mut worklist: Vec<&[crate::Statement]> = vec![block];
while let Some(last) = worklist.pop() {
for stmt in last {
use crate::Statement as St;
match *stmt {
St::Emit(ref _range) => {
// If we come across a statement that actually uses an
// expression in this range, it'll get traced from
// there. But since evaluating expressions has no
// effect, we don't need to assume that everything
// emitted is live.
}
St::Block(ref block) => worklist.push(block),
St::If {
condition,
ref accept,
ref reject,
} => {
self.expressions_used.insert(condition);
worklist.push(accept);
worklist.push(reject);
}
St::Switch {
selector,
ref cases,
} => {
self.expressions_used.insert(selector);
for case in cases {
worklist.push(&case.body);
}
}
St::Loop {
ref body,
ref continuing,
break_if,
} => {
if let Some(break_if) = break_if {
self.expressions_used.insert(break_if);
}
worklist.push(body);
worklist.push(continuing);
}
St::Return { value: Some(value) } => {
self.expressions_used.insert(value);
}
St::Store { pointer, value } => {
self.expressions_used.insert(pointer);
self.expressions_used.insert(value);
}
St::ImageStore {
image,
coordinate,
array_index,
value,
} => {
self.expressions_used.insert(image);
self.expressions_used.insert(coordinate);
if let Some(array_index) = array_index {
self.expressions_used.insert(array_index);
}
self.expressions_used.insert(value);
}
St::Atomic {
pointer,
ref fun,
value,
result,
} => {
self.expressions_used.insert(pointer);
self.trace_atomic_function(fun);
self.expressions_used.insert(value);
if let Some(result) = result {
self.expressions_used.insert(result);
}
}
St::ImageAtomic {
image,
coordinate,
array_index,
fun: _,
value,
} => {
self.expressions_used.insert(image);
self.expressions_used.insert(coordinate);
if let Some(array_index) = array_index {
self.expressions_used.insert(array_index);
}
self.expressions_used.insert(value);
}
St::WorkGroupUniformLoad { pointer, result } => {
self.expressions_used.insert(pointer);
self.expressions_used.insert(result);
}
St::Call {
function: _,
ref arguments,
result,
} => {
for expr in arguments {
self.expressions_used.insert(*expr);
}
if let Some(result) = result {
self.expressions_used.insert(result);
}
}
St::RayQuery { query, ref fun } => {
self.expressions_used.insert(query);
self.trace_ray_query_function(fun);
}
St::SubgroupBallot { result, predicate } => {
if let Some(predicate) = predicate {
self.expressions_used.insert(predicate);
}
self.expressions_used.insert(result);
}
St::SubgroupCollectiveOperation {
op: _,
collective_op: _,
argument,
result,
} => {
self.expressions_used.insert(argument);
self.expressions_used.insert(result);
}
St::SubgroupGather {
mode,
argument,
result,
} => {
match mode {
crate::GatherMode::BroadcastFirst => {}
crate::GatherMode::Broadcast(index)
| crate::GatherMode::Shuffle(index)
| crate::GatherMode::ShuffleDown(index)
| crate::GatherMode::ShuffleUp(index)
| crate::GatherMode::ShuffleXor(index) => {
self.expressions_used.insert(index);
}
}
self.expressions_used.insert(argument);
self.expressions_used.insert(result);
}
// Trivial statements.
St::Break
| St::Continue
| St::Kill
| St::Barrier(_)
| St::Return { value: None } => {}
}
}
}
}
fn trace_atomic_function(&mut self, fun: &crate::AtomicFunction) {
use crate::AtomicFunction as Af;
match *fun {
Af::Exchange {
compare: Some(expr),
} => {
self.expressions_used.insert(expr);
}
Af::Exchange { compare: None }
| Af::Add
| Af::Subtract
| Af::And
| Af::ExclusiveOr
| Af::InclusiveOr
| Af::Min
| Af::Max => {}
}
}
fn trace_ray_query_function(&mut self, fun: &crate::RayQueryFunction) {
use crate::RayQueryFunction as Qf;
match *fun {
Qf::Initialize {
acceleration_structure,
descriptor,
} => {
self.expressions_used.insert(acceleration_structure);
self.expressions_used.insert(descriptor);
}
Qf::Proceed { result } => {
self.expressions_used.insert(result);
}
Qf::Terminate => {}
}
}
}
impl FunctionMap {
pub fn adjust_body(&self, function: &mut crate::Function) {
let block = &mut function.body;
let mut worklist: Vec<&mut [crate::Statement]> = vec![block];
let adjust = |handle: &mut Handle<crate::Expression>| {
self.expressions.adjust(handle);
};
while let Some(last) = worklist.pop() {
for stmt in last {
use crate::Statement as St;
match *stmt {
St::Emit(ref mut range) => {
self.expressions.adjust_range(range, &function.expressions);
}
St::Block(ref mut block) => worklist.push(block),
St::If {
ref mut condition,
ref mut accept,
ref mut reject,
} => {
adjust(condition);
worklist.push(accept);
worklist.push(reject);
}
St::Switch {
ref mut selector,
ref mut cases,
} => {
adjust(selector);
for case in cases {
worklist.push(&mut case.body);
}
}
St::Loop {
ref mut body,
ref mut continuing,
ref mut break_if,
} => {
if let Some(ref mut break_if) = *break_if {
adjust(break_if);
}
worklist.push(body);
worklist.push(continuing);
}
St::Return {
value: Some(ref mut value),
} => adjust(value),
St::Store {
ref mut pointer,
ref mut value,
} => {
adjust(pointer);
adjust(value);
}
St::ImageStore {
ref mut image,
ref mut coordinate,
ref mut array_index,
ref mut value,
} => {
adjust(image);
adjust(coordinate);
if let Some(ref mut array_index) = *array_index {
adjust(array_index);
}
adjust(value);
}
St::Atomic {
ref mut pointer,
ref mut fun,
ref mut value,
ref mut result,
} => {
adjust(pointer);
self.adjust_atomic_function(fun);
adjust(value);
if let Some(ref mut result) = *result {
adjust(result);
}
}
St::ImageAtomic {
ref mut image,
ref mut coordinate,
ref mut array_index,
fun: _,
ref mut value,
} => {
adjust(image);
adjust(coordinate);
if let Some(ref mut array_index) = *array_index {
adjust(array_index);
}
adjust(value);
}
St::WorkGroupUniformLoad {
ref mut pointer,
ref mut result,
} => {
adjust(pointer);
adjust(result);
}
St::Call {
function: _,
ref mut arguments,
ref mut result,
} => {
for expr in arguments {
adjust(expr);
}
if let Some(ref mut result) = *result {
adjust(result);
}
}
St::RayQuery {
ref mut query,
ref mut fun,
} => {
adjust(query);
self.adjust_ray_query_function(fun);
}
St::SubgroupBallot {
ref mut result,
ref mut predicate,
} => {
if let Some(ref mut predicate) = *predicate {
adjust(predicate);
}
adjust(result);
}
St::SubgroupCollectiveOperation {
op: _,
collective_op: _,
ref mut argument,
ref mut result,
} => {
adjust(argument);
adjust(result);
}
St::SubgroupGather {
ref mut mode,
ref mut argument,
ref mut result,
} => {
match *mode {
crate::GatherMode::BroadcastFirst => {}
crate::GatherMode::Broadcast(ref mut index)
| crate::GatherMode::Shuffle(ref mut index)
| crate::GatherMode::ShuffleDown(ref mut index)
| crate::GatherMode::ShuffleUp(ref mut index)
| crate::GatherMode::ShuffleXor(ref mut index) => adjust(index),
}
adjust(argument);
adjust(result);
}
// Trivial statements.
St::Break
| St::Continue
| St::Kill
| St::Barrier(_)
| St::Return { value: None } => {}
}
}
}
}
fn adjust_atomic_function(&self, fun: &mut crate::AtomicFunction) {
use crate::AtomicFunction as Af;
match *fun {
Af::Exchange {
compare: Some(ref mut expr),
} => {
self.expressions.adjust(expr);
}
Af::Exchange { compare: None }
| Af::Add
| Af::Subtract
| Af::And
| Af::ExclusiveOr
| Af::InclusiveOr
| Af::Min
| Af::Max => {}
}
}
fn adjust_ray_query_function(&self, fun: &mut crate::RayQueryFunction) {
use crate::RayQueryFunction as Qf;
match *fun {
Qf::Initialize {
ref mut acceleration_structure,
ref mut descriptor,
} => {
self.expressions.adjust(acceleration_structure);
self.expressions.adjust(descriptor);
}
Qf::Proceed { ref mut result } => {
self.expressions.adjust(result);
}
Qf::Terminate => {}
}
}
}
+112
View File
@@ -0,0 +1,112 @@
use super::{HandleSet, ModuleMap};
use crate::{Handle, UniqueArena};
pub struct TypeTracer<'a> {
pub types: &'a UniqueArena<crate::Type>,
pub types_used: &'a mut HandleSet<crate::Type>,
}
impl TypeTracer<'_> {
/// Propagate usage through `self.types`, starting with `self.types_used`.
///
/// Treat `self.types_used` as the initial set of "known
/// live" types, and follow through to identify all
/// transitively used types.
pub fn trace_types(&mut self) {
// We don't need recursion or a work list. Because an
// expression may only refer to other expressions that precede
// it in the arena, it suffices to make a single pass over the
// arena from back to front, marking the referents of used
// expressions as used themselves.
for (handle, ty) in self.types.iter().rev() {
// If this type isn't used, it doesn't matter what it uses.
if !self.types_used.contains(handle) {
continue;
}
use crate::TypeInner as Ti;
match ty.inner {
// Types that do not contain handles.
Ti::Scalar { .. }
| Ti::Vector { .. }
| Ti::Matrix { .. }
| Ti::Atomic { .. }
| Ti::ValuePointer { .. }
| Ti::Image { .. }
| Ti::Sampler { .. }
| Ti::AccelerationStructure
| Ti::RayQuery => {}
// Types that do contain handles.
Ti::Pointer { base, space: _ }
| Ti::Array {
base,
size: _,
stride: _,
}
| Ti::BindingArray { base, size: _ } => {
self.types_used.insert(base);
}
Ti::Struct {
ref members,
span: _,
} => {
self.types_used.insert_iter(members.iter().map(|m| m.ty));
}
}
}
}
}
impl ModuleMap {
pub fn adjust_type(&self, ty: &mut crate::Type) {
let adjust = |ty: &mut Handle<crate::Type>| self.types.adjust(ty);
use crate::TypeInner as Ti;
match ty.inner {
// Types that do not contain handles.
Ti::Scalar(_)
| Ti::Vector { .. }
| Ti::Matrix { .. }
| Ti::Atomic(_)
| Ti::ValuePointer { .. }
| Ti::Image { .. }
| Ti::Sampler { .. }
| Ti::AccelerationStructure
| Ti::RayQuery => {}
// Types that do contain handles.
Ti::Pointer {
ref mut base,
space: _,
} => adjust(base),
Ti::Array {
ref mut base,
ref mut size,
stride: _,
} => {
adjust(base);
if let crate::ArraySize::Pending(crate::PendingArraySize::Expression(
ref mut size_expr,
)) = *size
{
self.global_expressions.adjust(size_expr);
}
}
Ti::Struct {
ref mut members,
span: _,
} => {
for member in members {
self.types.adjust(&mut member.ty);
}
}
Ti::BindingArray {
ref mut base,
size: _,
} => {
adjust(base);
}
};
}
}
+271
View File
@@ -0,0 +1,271 @@
//! [`DiagnosticFilter`]s and supporting functionality.
#[cfg(feature = "wgsl-in")]
use crate::Span;
use crate::{Arena, Handle};
#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;
#[cfg(feature = "wgsl-in")]
use indexmap::IndexMap;
#[cfg(feature = "deserialize")]
use serde::Deserialize;
#[cfg(feature = "serialize")]
use serde::Serialize;
/// A severity set on a [`DiagnosticFilter`].
///
/// <https://www.w3.org/TR/WGSL/#diagnostic-severity>
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub enum Severity {
Off,
Info,
Warning,
Error,
}
impl Severity {
/// Checks whether this severity is [`Self::Error`].
///
/// Naga does not yet support diagnostic items at lesser severities than
/// [`Severity::Error`]. When this is implemented, this method should be deleted, and the
/// severity should be used directly for reporting diagnostics.
pub(crate) fn report_diag<E>(
self,
err: E,
log_handler: impl FnOnce(E, log::Level),
) -> Result<(), E> {
let log_level = match self {
Severity::Off => return Ok(()),
// NOTE: These severities are not yet reported.
Severity::Info => log::Level::Info,
Severity::Warning => log::Level::Warn,
Severity::Error => return Err(err),
};
log_handler(err, log_level);
Ok(())
}
}
/// A filterable triggering rule in a [`DiagnosticFilter`].
///
/// <https://www.w3.org/TR/WGSL/#filterable-triggering-rules>
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub enum FilterableTriggeringRule {
Standard(StandardFilterableTriggeringRule),
Unknown(Box<str>),
User(Box<[Box<str>; 2]>),
}
/// A filterable triggering rule in a [`DiagnosticFilter`].
///
/// <https://www.w3.org/TR/WGSL/#filterable-triggering-rules>
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub enum StandardFilterableTriggeringRule {
DerivativeUniformity,
}
impl StandardFilterableTriggeringRule {
/// The default severity associated with this triggering rule.
///
/// See <https://www.w3.org/TR/WGSL/#filterable-triggering-rules> for a table of default
/// severities.
pub(crate) const fn default_severity(self) -> Severity {
match self {
Self::DerivativeUniformity => Severity::Error,
}
}
}
/// A filtering rule that modifies how diagnostics are emitted for shaders.
///
/// <https://www.w3.org/TR/WGSL/#diagnostic-filter>
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub struct DiagnosticFilter {
pub new_severity: Severity,
pub triggering_rule: FilterableTriggeringRule,
}
/// Determines whether [`DiagnosticFilterMap::add`] should consider full duplicates a conflict.
///
/// In WGSL, directive position does not consider this case a conflict, while attribute position
/// does.
#[cfg(feature = "wgsl-in")]
pub(crate) enum ShouldConflictOnFullDuplicate {
/// Use this for attributes in WGSL.
Yes,
/// Use this for directives in WGSL.
No,
}
/// A map from diagnostic filters to their severity and span.
///
/// Front ends can use this to collect the set of filters applied to a
/// particular language construct, and detect duplicate/conflicting filters.
///
/// For example, WGSL has global diagnostic filters that apply to the entire
/// module, and diagnostic range filter attributes that apply to a specific
/// function, statement, or other smaller construct. The set of filters applied
/// to any given construct must not conflict, but they can be overridden by
/// filters on other constructs nested within it. A front end can use a
/// `DiagnosticFilterMap` to collect the filters applied to a single construct,
/// using the [`add`] method's error checking to forbid conflicts.
///
/// For each filter it contains, a `DiagnosticFilterMap` records the requested
/// severity, and the source span of the filter itself.
///
/// [`add`]: DiagnosticFilterMap::add
#[derive(Clone, Debug, Default)]
#[cfg(feature = "wgsl-in")]
pub(crate) struct DiagnosticFilterMap(IndexMap<FilterableTriggeringRule, (Severity, Span)>);
#[cfg(feature = "wgsl-in")]
impl DiagnosticFilterMap {
pub(crate) fn new() -> Self {
Self::default()
}
/// Add the given `diagnostic_filter` parsed at the given `span` to this map.
pub(crate) fn add(
&mut self,
diagnostic_filter: DiagnosticFilter,
span: Span,
should_conflict_on_full_duplicate: ShouldConflictOnFullDuplicate,
) -> Result<(), ConflictingDiagnosticRuleError> {
use indexmap::map::Entry;
let &mut Self(ref mut diagnostic_filters) = self;
let DiagnosticFilter {
new_severity,
triggering_rule,
} = diagnostic_filter;
match diagnostic_filters.entry(triggering_rule.clone()) {
Entry::Vacant(entry) => {
entry.insert((new_severity, span));
}
Entry::Occupied(entry) => {
let &(first_severity, first_span) = entry.get();
let should_conflict_on_full_duplicate = match should_conflict_on_full_duplicate {
ShouldConflictOnFullDuplicate::Yes => true,
ShouldConflictOnFullDuplicate::No => false,
};
if first_severity != new_severity || should_conflict_on_full_duplicate {
return Err(ConflictingDiagnosticRuleError {
triggering_rule_spans: [first_span, span],
});
}
}
}
Ok(())
}
/// Were any rules specified?
pub(crate) fn is_empty(&self) -> bool {
let &Self(ref map) = self;
map.is_empty()
}
/// Returns the spans of all contained rules.
pub(crate) fn spans(&self) -> impl Iterator<Item = Span> + '_ {
let &Self(ref map) = self;
map.iter().map(|(_, &(_, span))| span)
}
}
#[cfg(feature = "wgsl-in")]
impl IntoIterator for DiagnosticFilterMap {
type Item = (FilterableTriggeringRule, (Severity, Span));
type IntoIter = indexmap::map::IntoIter<FilterableTriggeringRule, (Severity, Span)>;
fn into_iter(self) -> Self::IntoIter {
let Self(this) = self;
this.into_iter()
}
}
/// An error returned by [`DiagnosticFilterMap::add`] when it encounters conflicting rules.
#[cfg(feature = "wgsl-in")]
#[derive(Clone, Debug)]
pub(crate) struct ConflictingDiagnosticRuleError {
pub triggering_rule_spans: [Span; 2],
}
/// Represents a single parent-linking node in a tree of [`DiagnosticFilter`]s backed by a
/// [`crate::Arena`].
///
/// A single element of a _tree_ of diagnostic filter rules stored in
/// [`crate::Module::diagnostic_filters`]. When nodes are built by a front-end, module-applicable
/// filter rules are chained together in runs based on parse site. For instance, given the
/// following:
///
/// - Module-applicable rules `a` and `b`.
/// - Rules `c` and `d`, applicable to an entry point called `c_and_d_func`.
/// - Rule `e`, applicable to an entry point called `e_func`.
///
/// The tree would be represented as follows:
///
/// ```text
/// a <- b
/// ^
/// |- c <- d
/// |
/// \- e
/// ```
///
/// ...where:
///
/// - `d` is the first leaf consulted by validation in `c_and_d_func`.
/// - `e` is the first leaf consulted by validation in `e_func`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub struct DiagnosticFilterNode {
pub inner: DiagnosticFilter,
pub parent: Option<Handle<DiagnosticFilterNode>>,
}
impl DiagnosticFilterNode {
/// Finds the most specific filter rule applicable to `triggering_rule` from the chain of
/// diagnostic filter rules in `arena`, starting with `node`, and returns its severity. If none
/// is found, return the value of [`StandardFilterableTriggeringRule::default_severity`].
///
/// When `triggering_rule` is not applicable to this node, its parent is consulted recursively.
pub(crate) fn search(
node: Option<Handle<Self>>,
arena: &Arena<Self>,
triggering_rule: StandardFilterableTriggeringRule,
) -> Severity {
let mut next = node;
while let Some(handle) = next {
let node = &arena[handle];
let &Self { ref inner, parent } = node;
let &DiagnosticFilter {
triggering_rule: ref rule,
new_severity,
} = inner;
if rule == &FilterableTriggeringRule::Standard(triggering_rule) {
return new_severity;
}
next = parent;
}
triggering_rule.default_severity()
}
}
+60
View File
@@ -0,0 +1,60 @@
use std::{error::Error, fmt};
#[derive(Clone, Debug)]
pub struct ShaderError<E> {
/// The source code of the shader.
pub source: String,
pub label: Option<String>,
pub inner: Box<E>,
}
#[cfg(feature = "wgsl-in")]
impl fmt::Display for ShaderError<crate::front::wgsl::ParseError> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let label = self.label.as_deref().unwrap_or_default();
let string = self.inner.emit_to_string(&self.source);
write!(f, "\nShader '{label}' parsing {string}")
}
}
#[cfg(feature = "glsl-in")]
impl fmt::Display for ShaderError<crate::front::glsl::ParseErrors> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let label = self.label.as_deref().unwrap_or_default();
let string = self.inner.emit_to_string(&self.source);
write!(f, "\nShader '{label}' parsing {string}")
}
}
#[cfg(feature = "spv-in")]
impl fmt::Display for ShaderError<crate::front::spv::Error> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let label = self.label.as_deref().unwrap_or_default();
let string = self.inner.emit_to_string(&self.source);
write!(f, "\nShader '{label}' parsing {string}")
}
}
impl fmt::Display for ShaderError<crate::WithSpan<crate::valid::ValidationError>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use codespan_reporting::{files::SimpleFile, term};
let label = self.label.as_deref().unwrap_or_default();
let files = SimpleFile::new(label, &self.source);
let config = term::Config::default();
let mut writer = termcolor::NoColor::new(Vec::new());
term::emit(&mut writer, &config, &files, &self.inner.diagnostic())
.expect("cannot write error");
write!(
f,
"\nShader validation {}",
String::from_utf8_lossy(&writer.into_inner())
)
}
}
impl<E> Error for ShaderError<E>
where
ShaderError<E>: fmt::Display,
E: Error + 'static,
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.inner)
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Upgrade the types of scalars observed to be accessed as atomics to [`Atomic`] types.
//!
//! In SPIR-V, atomic operations can be applied to any scalar value, but in Naga
//! IR atomic operations can only be applied to values of type [`Atomic`]. Naga
//! IR's restriction matches Metal Shading Language and WGSL, so we don't want
//! to relax that. Instead, when the SPIR-V front end observes a value being
//! accessed using atomic instructions, it promotes the value's type from
//! [`Scalar`] to [`Atomic`]. This module implements `Module::upgrade_atomics`,
//! the function that makes that change.
//!
//! Atomics can only appear in global variables in the [`Storage`] and
//! [`Workgroup`] address spaces. These variables can either have `Atomic` types
//! themselves, or be [`Array`]s of such, or be [`Struct`]s containing such.
//! So we only need to change the types of globals and struct fields.
//!
//! Naga IR [`Load`] expressions and [`Store`] statements can operate directly
//! on [`Atomic`] values, retrieving and depositing ordinary [`Scalar`] values,
//! so changing the types doesn't have much effect on the code that operates on
//! those values.
//!
//! Future work:
//!
//! - The GLSL front end could use this transformation as well.
//!
//! [`Atomic`]: TypeInner::Atomic
//! [`Scalar`]: TypeInner::Scalar
//! [`Storage`]: crate::AddressSpace::Storage
//! [`WorkGroup`]: crate::AddressSpace::WorkGroup
//! [`Array`]: TypeInner::Array
//! [`Struct`]: TypeInner::Struct
//! [`Load`]: crate::Expression::Load
//! [`Store`]: crate::Statement::Store
use std::sync::{atomic::AtomicUsize, Arc};
use crate::{GlobalVariable, Handle, Module, Type, TypeInner};
#[derive(Clone, Debug, thiserror::Error)]
pub enum Error {
#[error("encountered an unsupported expression")]
Unsupported,
#[error("unexpected end of struct field access indices")]
UnexpectedEndOfIndices,
#[error("encountered unsupported global initializer in an atomic variable")]
GlobalInitUnsupported,
#[error("expected to find a global variable")]
GlobalVariableMissing,
#[error("atomic compare exchange requires a scalar base type")]
CompareExchangeNonScalarBaseType,
}
#[derive(Clone, Default)]
struct Padding(Arc<AtomicUsize>);
impl std::fmt::Display for Padding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for _ in 0..self.0.load(std::sync::atomic::Ordering::Relaxed) {
f.write_str(" ")?;
}
Ok(())
}
}
impl Drop for Padding {
fn drop(&mut self) {
let _ = self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
impl Padding {
fn trace(&self, msg: impl std::fmt::Display, t: impl std::fmt::Debug) {
format!("{msg} {t:#?}")
.split('\n')
.for_each(|ln| log::trace!("{self}{ln}"));
}
fn debug(&self, msg: impl std::fmt::Display, t: impl std::fmt::Debug) {
format!("{msg} {t:#?}")
.split('\n')
.for_each(|ln| log::debug!("{self}{ln}"));
}
fn inc_padding(&self) -> Padding {
let _ = self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.clone()
}
}
#[derive(Debug, Default)]
pub struct Upgrades {
/// Global variables that we've accessed using atomic operations.
///
/// This includes globals with composite types (arrays, structs) where we've
/// only accessed some components (elements, fields) atomically.
globals: crate::arena::HandleSet<GlobalVariable>,
/// Struct fields that we've accessed using atomic operations.
///
/// Each key refers to some [`Struct`] type, and each value is a set of
/// the indices of the fields in that struct that have been accessed
/// atomically.
///
/// This includes fields with composite types (arrays, structs)
/// of which we've only accessed some components (elements, fields)
/// atomically.
///
/// [`Struct`]: crate::TypeInner::Struct
fields: crate::FastHashMap<Handle<Type>, bit_set::BitSet>,
}
impl Upgrades {
pub fn insert_global(&mut self, global: Handle<GlobalVariable>) {
self.globals.insert(global);
}
pub fn insert_field(&mut self, struct_type: Handle<Type>, field: usize) {
self.fields.entry(struct_type).or_default().insert(field);
}
pub fn is_empty(&self) -> bool {
self.globals.is_empty()
}
}
struct UpgradeState<'a> {
padding: Padding,
module: &'a mut Module,
/// A map from old types to their upgraded versions.
///
/// This ensures we never try to rebuild a type more than once.
upgraded_types: crate::FastHashMap<Handle<Type>, Handle<Type>>,
}
impl UpgradeState<'_> {
fn inc_padding(&self) -> Padding {
self.padding.inc_padding()
}
/// Get a type equivalent to `ty`, but with [`Scalar`] leaves upgraded to [`Atomic`] scalars.
///
/// If such a type already exists in `self.module.types`, return its handle.
/// Otherwise, construct a new one and return that handle.
///
/// If `ty` is a [`Pointer`], [`Array`], [`BindingArray`], recurse into the
/// type and upgrade its leaf types.
///
/// If `ty` is a [`Struct`], recurse into it and upgrade only those fields
/// whose indices appear in `field_indices`.
///
/// The existing type is not affected.
///
/// [`Scalar`]: crate::TypeInner::Scalar
/// [`Atomic`]: crate::TypeInner::Atomic
/// [`Pointer`]: crate::TypeInner::Pointer
/// [`Array`]: crate::TypeInner::Array
/// [`Struct`]: crate::TypeInner::Struct
/// [`BindingArray`]: crate::TypeInner::BindingArray
fn upgrade_type(
&mut self,
ty: Handle<Type>,
upgrades: &Upgrades,
) -> Result<Handle<Type>, Error> {
let padding = self.inc_padding();
padding.trace("visiting type: ", ty);
// If we've already upgraded this type, return the handle we produced at
// the time.
if let Some(&new) = self.upgraded_types.get(&ty) {
return Ok(new);
}
let inner = match self.module.types[ty].inner {
TypeInner::Scalar(scalar) => {
log::trace!("{padding}hit the scalar leaf, replacing with an atomic");
TypeInner::Atomic(scalar)
}
TypeInner::Pointer { base, space } => TypeInner::Pointer {
base: self.upgrade_type(base, upgrades)?,
space,
},
TypeInner::Array { base, size, stride } => TypeInner::Array {
base: self.upgrade_type(base, upgrades)?,
size,
stride,
},
TypeInner::Struct { ref members, span } => {
// If no field or subfield of this struct was ever accessed
// atomically, no change is needed. We should never have arrived here.
let Some(fields) = upgrades.fields.get(&ty) else {
unreachable!("global or field incorrectly flagged as atomically accessed");
};
let mut new_members = members.clone();
for field in fields {
new_members[field].ty = self.upgrade_type(new_members[field].ty, upgrades)?;
}
TypeInner::Struct {
members: new_members,
span,
}
}
TypeInner::BindingArray { base, size } => TypeInner::BindingArray {
base: self.upgrade_type(base, upgrades)?,
size,
},
_ => return Ok(ty),
};
// At this point, we have a `TypeInner` that is the upgraded version of
// `ty`. Find a suitable `Type` for this, creating a new one if
// necessary, and return its handle.
let r#type = &self.module.types[ty];
let span = self.module.types.get_span(ty);
let new_type = Type {
name: r#type.name.clone(),
inner,
};
padding.debug("ty: ", ty);
padding.debug("from: ", r#type);
padding.debug("to: ", &new_type);
let new_handle = self.module.types.insert(new_type, span);
self.upgraded_types.insert(ty, new_handle);
Ok(new_handle)
}
fn upgrade_all(&mut self, upgrades: &Upgrades) -> Result<(), Error> {
for handle in upgrades.globals.iter() {
let padding = self.inc_padding();
let global = &self.module.global_variables[handle];
padding.trace("visiting global variable: ", handle);
padding.trace("var: ", global);
if global.init.is_some() {
return Err(Error::GlobalInitUnsupported);
}
let var_ty = global.ty;
let new_ty = self.upgrade_type(var_ty, upgrades)?;
if new_ty != var_ty {
padding.debug("upgrading global variable: ", handle);
padding.debug("from ty: ", var_ty);
padding.debug("to ty: ", new_ty);
self.module.global_variables[handle].ty = new_ty;
}
}
Ok(())
}
}
impl Module {
/// Upgrade `global_var_handles` to have [`Atomic`] leaf types.
///
/// [`Atomic`]: TypeInner::Atomic
pub(crate) fn upgrade_atomics(&mut self, upgrades: &Upgrades) -> Result<(), Error> {
let mut state = UpgradeState {
padding: Default::default(),
module: self,
upgraded_types: crate::FastHashMap::with_capacity_and_hasher(
upgrades.fields.len(),
Default::default(),
),
};
state.upgrade_all(upgrades)?;
Ok(())
}
}
+386
View File
@@ -0,0 +1,386 @@
use std::{borrow::Cow, fmt};
use super::{builtins::MacroCall, Span};
use crate::{
AddressSpace, BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle,
Interpolation, Literal, Sampling, StorageAccess, Type, UnaryOperator,
};
#[derive(Debug, Clone, Copy)]
pub enum GlobalLookupKind {
Variable(Handle<GlobalVariable>),
Constant(Handle<Constant>, Handle<Type>),
BlockSelect(Handle<GlobalVariable>, u32),
}
#[derive(Debug, Clone, Copy)]
pub struct GlobalLookup {
pub kind: GlobalLookupKind,
pub entry_arg: Option<usize>,
pub mutable: bool,
}
#[derive(Debug, Clone)]
pub struct ParameterInfo {
pub qualifier: ParameterQualifier,
/// Whether the parameter should be treated as a depth image instead of a
/// sampled image.
pub depth: bool,
}
/// How the function is implemented
#[derive(Clone, Copy)]
pub enum FunctionKind {
/// The function is user defined
Call(Handle<Function>),
/// The function is a builtin
Macro(MacroCall),
}
impl fmt::Debug for FunctionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Call(_) => write!(f, "Call"),
Self::Macro(_) => write!(f, "Macro"),
}
}
}
#[derive(Debug)]
pub struct Overload {
/// Normalized function parameters, modifiers are not applied
pub parameters: Vec<Handle<Type>>,
pub parameters_info: Vec<ParameterInfo>,
/// How the function is implemented
pub kind: FunctionKind,
/// Whether this function was already defined or is just a prototype
pub defined: bool,
/// Whether this overload is the one provided by the language or has
/// been redeclared by the user (builtins only)
pub internal: bool,
/// Whether or not this function returns void (nothing)
pub void: bool,
}
bitflags::bitflags! {
/// Tracks the variations of the builtin already generated, this is needed because some
/// builtins overloads can't be generated unless explicitly used, since they might cause
/// unneeded capabilities to be requested
#[derive(Default)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BuiltinVariations: u32 {
/// Request the standard overloads
const STANDARD = 1 << 0;
/// Request overloads that use the double type
const DOUBLE = 1 << 1;
/// Request overloads that use `samplerCubeArray(Shadow)`
const CUBE_TEXTURES_ARRAY = 1 << 2;
/// Request overloads that use `sampler2DMSArray`
const D2_MULTI_TEXTURES_ARRAY = 1 << 3;
}
}
#[derive(Debug, Default)]
pub struct FunctionDeclaration {
pub overloads: Vec<Overload>,
/// Tracks the builtin overload variations that were already generated
pub variations: BuiltinVariations,
}
#[derive(Debug)]
pub struct EntryArg {
pub name: Option<String>,
pub binding: Binding,
pub handle: Handle<GlobalVariable>,
pub storage: StorageQualifier,
}
#[derive(Debug, Clone)]
pub struct VariableReference {
pub expr: Handle<Expression>,
/// Whether the variable is of a pointer type (and needs loading) or not
pub load: bool,
/// Whether the value of the variable can be changed or not
pub mutable: bool,
pub constant: Option<(Handle<Constant>, Handle<Type>)>,
pub entry_arg: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct HirExpr {
pub kind: HirExprKind,
pub meta: Span,
}
#[derive(Debug, Clone)]
pub enum HirExprKind {
Access {
base: Handle<HirExpr>,
index: Handle<HirExpr>,
},
Select {
base: Handle<HirExpr>,
field: String,
},
Literal(Literal),
Binary {
left: Handle<HirExpr>,
op: BinaryOperator,
right: Handle<HirExpr>,
},
Unary {
op: UnaryOperator,
expr: Handle<HirExpr>,
},
Variable(VariableReference),
Call(FunctionCall),
/// Represents the ternary operator in glsl (`:?`)
Conditional {
/// The expression that will decide which branch to take, must evaluate to a boolean
condition: Handle<HirExpr>,
/// The expression that will be evaluated if [`condition`] returns `true`
///
/// [`condition`]: Self::Conditional::condition
accept: Handle<HirExpr>,
/// The expression that will be evaluated if [`condition`] returns `false`
///
/// [`condition`]: Self::Conditional::condition
reject: Handle<HirExpr>,
},
Assign {
tgt: Handle<HirExpr>,
value: Handle<HirExpr>,
},
/// A prefix/postfix operator like `++`
PrePostfix {
/// The operation to be performed
op: BinaryOperator,
/// Whether this is a postfix or a prefix
postfix: bool,
/// The target expression
expr: Handle<HirExpr>,
},
/// A method call like `what.something(a, b, c)`
Method {
/// expression the method call applies to (`what` in the example)
expr: Handle<HirExpr>,
/// the method name (`something` in the example)
name: String,
/// the arguments to the method (`a`, `b`, and `c` in the example)
args: Vec<Handle<HirExpr>>,
},
}
#[derive(Debug, Hash, PartialEq, Eq)]
pub enum QualifierKey<'a> {
String(Cow<'a, str>),
/// Used for `std140` and `std430` layout qualifiers
Layout,
/// Used for image formats
Format,
}
#[derive(Debug)]
pub enum QualifierValue {
None,
Uint(u32),
Layout(StructLayout),
Format(crate::StorageFormat),
}
#[derive(Debug, Default)]
pub struct TypeQualifiers<'a> {
pub span: Span,
pub storage: (StorageQualifier, Span),
pub invariant: Option<Span>,
pub interpolation: Option<(Interpolation, Span)>,
pub precision: Option<(Precision, Span)>,
pub sampling: Option<(Sampling, Span)>,
/// Memory qualifiers used in the declaration to set the storage access to be used
/// in declarations that support it (storage images and buffers)
pub storage_access: Option<(StorageAccess, Span)>,
pub layout_qualifiers: crate::FastHashMap<QualifierKey<'a>, (QualifierValue, Span)>,
}
impl<'a> TypeQualifiers<'a> {
/// Appends `errors` with errors for all unused qualifiers
pub fn unused_errors(&self, errors: &mut Vec<super::Error>) {
if let Some(meta) = self.invariant {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError(
"Invariant qualifier can only be used in in/out variables".into(),
),
meta,
});
}
if let Some((_, meta)) = self.interpolation {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError(
"Interpolation qualifiers can only be used in in/out variables".into(),
),
meta,
});
}
if let Some((_, meta)) = self.sampling {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError(
"Sampling qualifiers can only be used in in/out variables".into(),
),
meta,
});
}
if let Some((_, meta)) = self.storage_access {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError(
"Memory qualifiers can only be used in storage variables".into(),
),
meta,
});
}
for &(_, meta) in self.layout_qualifiers.values() {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError("Unexpected qualifier".into()),
meta,
});
}
}
/// Removes the layout qualifier with `name`, if it exists and adds an error if it isn't
/// a [`QualifierValue::Uint`]
pub fn uint_layout_qualifier(
&mut self,
name: &'a str,
errors: &mut Vec<super::Error>,
) -> Option<u32> {
match self
.layout_qualifiers
.remove(&QualifierKey::String(name.into()))
{
Some((QualifierValue::Uint(v), _)) => Some(v),
Some((_, meta)) => {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError("Qualifier expects a uint value".into()),
meta,
});
// Return a dummy value instead of `None` to differentiate from
// the qualifier not existing, since some parts might require the
// qualifier to exist and throwing another error that it doesn't
// exist would be unhelpful
Some(0)
}
_ => None,
}
}
/// Removes the layout qualifier with `name`, if it exists and adds an error if it isn't
/// a [`QualifierValue::None`]
pub fn none_layout_qualifier(&mut self, name: &'a str, errors: &mut Vec<super::Error>) -> bool {
match self
.layout_qualifiers
.remove(&QualifierKey::String(name.into()))
{
Some((QualifierValue::None, _)) => true,
Some((_, meta)) => {
errors.push(super::Error {
kind: super::ErrorKind::SemanticError(
"Qualifier doesn't expect a value".into(),
),
meta,
});
// Return a `true` to since the qualifier is defined and adding
// another error for it not being defined would be unhelpful
true
}
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub enum FunctionCallKind {
TypeConstructor(Handle<Type>),
Function(String),
}
#[derive(Debug, Clone)]
pub struct FunctionCall {
pub kind: FunctionCallKind,
pub args: Vec<Handle<HirExpr>>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StorageQualifier {
AddressSpace(AddressSpace),
Input,
Output,
Const,
}
impl Default for StorageQualifier {
fn default() -> Self {
StorageQualifier::AddressSpace(AddressSpace::Function)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructLayout {
Std140,
Std430,
}
// TODO: Encode precision hints in the IR
/// A precision hint used in GLSL declarations.
///
/// Precision hints can be used to either speed up shader execution or control
/// the precision of arithmetic operations.
///
/// To use a precision hint simply add it before the type in the declaration.
/// ```glsl
/// mediump float a;
/// ```
///
/// The default when no precision is declared is `highp` which means that all
/// operations operate with the type defined width.
///
/// For `mediump` and `lowp` operations follow the spir-v
/// [`RelaxedPrecision`][RelaxedPrecision] decoration semantics.
///
/// [RelaxedPrecision]: https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#_a_id_relaxedprecisionsection_a_relaxed_precision
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum Precision {
/// `lowp` precision
Low,
/// `mediump` precision
Medium,
/// `highp` precision
High,
}
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum ParameterQualifier {
In,
Out,
InOut,
Const,
}
impl ParameterQualifier {
/// Returns true if the argument should be passed as a lhs expression
pub const fn is_lhs(&self) -> bool {
match *self {
ParameterQualifier::Out | ParameterQualifier::InOut => true,
_ => false,
}
}
}
/// The GLSL profile used by a shader.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Profile {
/// The `core` profile, default when no profile is specified.
Core,
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+199
View File
@@ -0,0 +1,199 @@
use super::token::TokenValue;
use crate::SourceLocation;
use crate::{proc::ConstantEvaluatorError, Span};
use codespan_reporting::diagnostic::{Diagnostic, Label};
use codespan_reporting::files::SimpleFile;
use codespan_reporting::term;
use pp_rs::token::PreprocessorError;
use std::borrow::Cow;
use termcolor::{NoColor, WriteColor};
use thiserror::Error;
fn join_with_comma(list: &[ExpectedToken]) -> String {
let mut string = "".to_string();
for (i, val) in list.iter().enumerate() {
string.push_str(&val.to_string());
match i {
i if i == list.len() - 1 => {}
i if i == list.len() - 2 => string.push_str(" or "),
_ => string.push_str(", "),
}
}
string
}
/// One of the expected tokens returned in [`InvalidToken`](ErrorKind::InvalidToken).
#[derive(Clone, Debug, PartialEq)]
pub enum ExpectedToken {
/// A specific token was expected.
Token(TokenValue),
/// A type was expected.
TypeName,
/// An identifier was expected.
Identifier,
/// An integer literal was expected.
IntLiteral,
/// A float literal was expected.
FloatLiteral,
/// A boolean literal was expected.
BoolLiteral,
/// The end of file was expected.
Eof,
}
impl From<TokenValue> for ExpectedToken {
fn from(token: TokenValue) -> Self {
ExpectedToken::Token(token)
}
}
impl std::fmt::Display for ExpectedToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
ExpectedToken::Token(ref token) => write!(f, "{token:?}"),
ExpectedToken::TypeName => write!(f, "a type"),
ExpectedToken::Identifier => write!(f, "identifier"),
ExpectedToken::IntLiteral => write!(f, "integer literal"),
ExpectedToken::FloatLiteral => write!(f, "float literal"),
ExpectedToken::BoolLiteral => write!(f, "bool literal"),
ExpectedToken::Eof => write!(f, "end of file"),
}
}
}
/// Information about the cause of an error.
#[derive(Clone, Debug, Error)]
#[cfg_attr(test, derive(PartialEq))]
pub enum ErrorKind {
/// Whilst parsing as encountered an unexpected EOF.
#[error("Unexpected end of file")]
EndOfFile,
/// The shader specified an unsupported or invalid profile.
#[error("Invalid profile: {0}")]
InvalidProfile(String),
/// The shader requested an unsupported or invalid version.
#[error("Invalid version: {0}")]
InvalidVersion(u64),
/// Whilst parsing an unexpected token was encountered.
///
/// A list of expected tokens is also returned.
#[error("Expected {expected_tokens}, found {found_token:?}", found_token = .0, expected_tokens = join_with_comma(.1))]
InvalidToken(TokenValue, Vec<ExpectedToken>),
/// A specific feature is not yet implemented.
///
/// To help prioritize work please open an issue in the github issue tracker
/// if none exist already or react to the already existing one.
#[error("Not implemented: {0}")]
NotImplemented(&'static str),
/// A reference to a variable that wasn't declared was used.
#[error("Unknown variable: {0}")]
UnknownVariable(String),
/// A reference to a type that wasn't declared was used.
#[error("Unknown type: {0}")]
UnknownType(String),
/// A reference to a non existent member of a type was made.
#[error("Unknown field: {0}")]
UnknownField(String),
/// An unknown layout qualifier was used.
///
/// If the qualifier does exist please open an issue in the github issue tracker
/// if none exist already or react to the already existing one to help
/// prioritize work.
#[error("Unknown layout qualifier: {0}")]
UnknownLayoutQualifier(String),
/// Unsupported matrix of the form matCx2
///
/// Our IR expects matrices of the form matCx2 to have a stride of 8 however
/// matrices in the std140 layout have a stride of at least 16
#[error("unsupported matrix of the form matCx2 in std140 block layout")]
UnsupportedMatrixTypeInStd140,
/// A variable with the same name already exists in the current scope.
#[error("Variable already declared: {0}")]
VariableAlreadyDeclared(String),
/// A semantic error was detected in the shader.
#[error("{0}")]
SemanticError(Cow<'static, str>),
/// An error was returned by the preprocessor.
#[error("{0:?}")]
PreprocessorError(PreprocessorError),
/// The parser entered an illegal state and exited
///
/// This obviously is a bug and as such should be reported in the github issue tracker
#[error("Internal error: {0}")]
InternalError(&'static str),
}
impl From<ConstantEvaluatorError> for ErrorKind {
fn from(err: ConstantEvaluatorError) -> Self {
ErrorKind::SemanticError(err.to_string().into())
}
}
/// Error returned during shader parsing.
#[derive(Clone, Debug, Error)]
#[error("{kind}")]
#[cfg_attr(test, derive(PartialEq))]
pub struct Error {
/// Holds the information about the error itself.
pub kind: ErrorKind,
/// Holds information about the range of the source code where the error happened.
pub meta: Span,
}
impl Error {
/// Returns a [`SourceLocation`] for the error message.
pub fn location(&self, source: &str) -> Option<SourceLocation> {
Some(self.meta.location(source))
}
}
/// A collection of errors returned during shader parsing.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct ParseErrors {
pub errors: Vec<Error>,
}
impl ParseErrors {
pub fn emit_to_writer(&self, writer: &mut impl WriteColor, source: &str) {
self.emit_to_writer_with_path(writer, source, "glsl");
}
pub fn emit_to_writer_with_path(&self, writer: &mut impl WriteColor, source: &str, path: &str) {
let path = path.to_string();
let files = SimpleFile::new(path, source);
let config = term::Config::default();
for err in &self.errors {
let mut diagnostic = Diagnostic::error().with_message(err.kind.to_string());
if let Some(range) = err.meta.to_range() {
diagnostic = diagnostic.with_labels(vec![Label::primary((), range)]);
}
term::emit(writer, &config, &files, &diagnostic).expect("cannot write error");
}
}
pub fn emit_to_string(&self, source: &str) -> String {
let mut writer = NoColor::new(Vec::new());
self.emit_to_writer(&mut writer, source);
String::from_utf8(writer.into_inner()).unwrap()
}
}
impl std::fmt::Display for ParseErrors {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.errors.iter().try_for_each(|e| write!(f, "{e:?}"))
}
}
impl std::error::Error for ParseErrors {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl From<Vec<Error>> for ParseErrors {
fn from(errors: Vec<Error>) -> Self {
Self { errors }
}
}
File diff suppressed because it is too large Load Diff
+301
View File
@@ -0,0 +1,301 @@
use super::{
ast::Precision,
token::{Directive, DirectiveKind, Token, TokenValue},
types::parse_type,
};
use crate::{FastHashMap, Span, StorageAccess};
use pp_rs::{
pp::Preprocessor,
token::{PreprocessorError, Punct, TokenValue as PPTokenValue},
};
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct LexerResult {
pub kind: LexerResultKind,
pub meta: Span,
}
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum LexerResultKind {
Token(Token),
Directive(Directive),
Error(PreprocessorError),
}
pub struct Lexer<'a> {
pp: Preprocessor<'a>,
}
impl<'a> Lexer<'a> {
pub fn new(input: &'a str, defines: &'a FastHashMap<String, String>) -> Self {
let mut pp = Preprocessor::new(input);
for (define, value) in defines {
pp.add_define(define, value).unwrap(); //TODO: handle error
}
Lexer { pp }
}
}
impl Iterator for Lexer<'_> {
type Item = LexerResult;
fn next(&mut self) -> Option<Self::Item> {
let pp_token = match self.pp.next()? {
Ok(t) => t,
Err((err, loc)) => {
return Some(LexerResult {
kind: LexerResultKind::Error(err),
meta: loc.into(),
});
}
};
let meta = pp_token.location.into();
let value = match pp_token.value {
PPTokenValue::Extension(extension) => {
return Some(LexerResult {
kind: LexerResultKind::Directive(Directive {
kind: DirectiveKind::Extension,
tokens: extension.tokens,
}),
meta,
})
}
PPTokenValue::Float(float) => TokenValue::FloatConstant(float),
PPTokenValue::Ident(ident) => {
match ident.as_str() {
// Qualifiers
"layout" => TokenValue::Layout,
"in" => TokenValue::In,
"out" => TokenValue::Out,
"uniform" => TokenValue::Uniform,
"buffer" => TokenValue::Buffer,
"shared" => TokenValue::Shared,
"invariant" => TokenValue::Invariant,
"flat" => TokenValue::Interpolation(crate::Interpolation::Flat),
"noperspective" => TokenValue::Interpolation(crate::Interpolation::Linear),
"smooth" => TokenValue::Interpolation(crate::Interpolation::Perspective),
"centroid" => TokenValue::Sampling(crate::Sampling::Centroid),
"sample" => TokenValue::Sampling(crate::Sampling::Sample),
"const" => TokenValue::Const,
"inout" => TokenValue::InOut,
"precision" => TokenValue::Precision,
"highp" => TokenValue::PrecisionQualifier(Precision::High),
"mediump" => TokenValue::PrecisionQualifier(Precision::Medium),
"lowp" => TokenValue::PrecisionQualifier(Precision::Low),
"restrict" => TokenValue::Restrict,
"readonly" => TokenValue::MemoryQualifier(StorageAccess::LOAD),
"writeonly" => TokenValue::MemoryQualifier(StorageAccess::STORE),
// values
"true" => TokenValue::BoolConstant(true),
"false" => TokenValue::BoolConstant(false),
// jump statements
"continue" => TokenValue::Continue,
"break" => TokenValue::Break,
"return" => TokenValue::Return,
"discard" => TokenValue::Discard,
// selection statements
"if" => TokenValue::If,
"else" => TokenValue::Else,
"switch" => TokenValue::Switch,
"case" => TokenValue::Case,
"default" => TokenValue::Default,
// iteration statements
"while" => TokenValue::While,
"do" => TokenValue::Do,
"for" => TokenValue::For,
// types
"void" => TokenValue::Void,
"struct" => TokenValue::Struct,
word => match parse_type(word) {
Some(t) => TokenValue::TypeName(t),
None => TokenValue::Identifier(String::from(word)),
},
}
}
PPTokenValue::Integer(integer) => TokenValue::IntConstant(integer),
PPTokenValue::Punct(punct) => match punct {
// Compound assignments
Punct::AddAssign => TokenValue::AddAssign,
Punct::SubAssign => TokenValue::SubAssign,
Punct::MulAssign => TokenValue::MulAssign,
Punct::DivAssign => TokenValue::DivAssign,
Punct::ModAssign => TokenValue::ModAssign,
Punct::LeftShiftAssign => TokenValue::LeftShiftAssign,
Punct::RightShiftAssign => TokenValue::RightShiftAssign,
Punct::AndAssign => TokenValue::AndAssign,
Punct::XorAssign => TokenValue::XorAssign,
Punct::OrAssign => TokenValue::OrAssign,
// Two character punctuation
Punct::Increment => TokenValue::Increment,
Punct::Decrement => TokenValue::Decrement,
Punct::LogicalAnd => TokenValue::LogicalAnd,
Punct::LogicalOr => TokenValue::LogicalOr,
Punct::LogicalXor => TokenValue::LogicalXor,
Punct::LessEqual => TokenValue::LessEqual,
Punct::GreaterEqual => TokenValue::GreaterEqual,
Punct::EqualEqual => TokenValue::Equal,
Punct::NotEqual => TokenValue::NotEqual,
Punct::LeftShift => TokenValue::LeftShift,
Punct::RightShift => TokenValue::RightShift,
// Parenthesis or similar
Punct::LeftBrace => TokenValue::LeftBrace,
Punct::RightBrace => TokenValue::RightBrace,
Punct::LeftParen => TokenValue::LeftParen,
Punct::RightParen => TokenValue::RightParen,
Punct::LeftBracket => TokenValue::LeftBracket,
Punct::RightBracket => TokenValue::RightBracket,
// Other one character punctuation
Punct::LeftAngle => TokenValue::LeftAngle,
Punct::RightAngle => TokenValue::RightAngle,
Punct::Semicolon => TokenValue::Semicolon,
Punct::Comma => TokenValue::Comma,
Punct::Colon => TokenValue::Colon,
Punct::Dot => TokenValue::Dot,
Punct::Equal => TokenValue::Assign,
Punct::Bang => TokenValue::Bang,
Punct::Minus => TokenValue::Dash,
Punct::Tilde => TokenValue::Tilde,
Punct::Plus => TokenValue::Plus,
Punct::Star => TokenValue::Star,
Punct::Slash => TokenValue::Slash,
Punct::Percent => TokenValue::Percent,
Punct::Pipe => TokenValue::VerticalBar,
Punct::Caret => TokenValue::Caret,
Punct::Ampersand => TokenValue::Ampersand,
Punct::Question => TokenValue::Question,
},
PPTokenValue::Pragma(pragma) => {
return Some(LexerResult {
kind: LexerResultKind::Directive(Directive {
kind: DirectiveKind::Pragma,
tokens: pragma.tokens,
}),
meta,
})
}
PPTokenValue::Version(version) => {
return Some(LexerResult {
kind: LexerResultKind::Directive(Directive {
kind: DirectiveKind::Version {
is_first_directive: version.is_first_directive,
},
tokens: version.tokens,
}),
meta,
})
}
};
Some(LexerResult {
kind: LexerResultKind::Token(Token { value, meta }),
meta,
})
}
}
#[cfg(test)]
mod tests {
use pp_rs::token::{Integer, Location, Token as PPToken, TokenValue as PPTokenValue};
use super::{
super::token::{Directive, DirectiveKind, Token, TokenValue},
Lexer, LexerResult, LexerResultKind,
};
use crate::Span;
#[test]
fn lex_tokens() {
let defines = crate::FastHashMap::default();
// line comments
let mut lex = Lexer::new("#version 450\nvoid main () {}", &defines);
let mut location = Location::default();
location.start = 9;
location.end = 12;
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Directive(Directive {
kind: DirectiveKind::Version {
is_first_directive: true
},
tokens: vec![PPToken {
value: PPTokenValue::Integer(Integer {
signed: true,
value: 450,
width: 32
}),
location
}]
}),
meta: Span::new(1, 8)
}
);
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Token(Token {
value: TokenValue::Void,
meta: Span::new(13, 17)
}),
meta: Span::new(13, 17)
}
);
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Token(Token {
value: TokenValue::Identifier("main".into()),
meta: Span::new(18, 22)
}),
meta: Span::new(18, 22)
}
);
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Token(Token {
value: TokenValue::LeftParen,
meta: Span::new(23, 24)
}),
meta: Span::new(23, 24)
}
);
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Token(Token {
value: TokenValue::RightParen,
meta: Span::new(24, 25)
}),
meta: Span::new(24, 25)
}
);
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Token(Token {
value: TokenValue::LeftBrace,
meta: Span::new(26, 27)
}),
meta: Span::new(26, 27)
}
);
assert_eq!(
lex.next().unwrap(),
LexerResult {
kind: LexerResultKind::Token(Token {
value: TokenValue::RightBrace,
meta: Span::new(27, 28)
}),
meta: Span::new(27, 28)
}
);
assert_eq!(lex.next(), None);
}
}
+232
View File
@@ -0,0 +1,232 @@
/*!
Frontend for [GLSL][glsl] (OpenGL Shading Language).
To begin, take a look at the documentation for the [`Frontend`].
# Supported versions
## Vulkan
- 440 (partial)
- 450
- 460
[glsl]: https://www.khronos.org/registry/OpenGL/index_gl.php
*/
pub use ast::{Precision, Profile};
pub use error::{Error, ErrorKind, ExpectedToken, ParseErrors};
pub use token::TokenValue;
use crate::{proc::Layouter, FastHashMap, FastHashSet, Handle, Module, ShaderStage, Span, Type};
use ast::{EntryArg, FunctionDeclaration, GlobalLookup};
use parser::ParsingContext;
mod ast;
mod builtins;
mod context;
mod error;
mod functions;
mod lex;
mod offset;
mod parser;
#[cfg(test)]
mod parser_tests;
mod token;
mod types;
mod variables;
type Result<T> = std::result::Result<T, Error>;
/// Per-shader options passed to [`parse`](Frontend::parse).
///
/// The [`From`] trait is implemented for [`ShaderStage`] to provide a quick way
/// to create an `Options` instance.
///
/// ```rust
/// # use naga::ShaderStage;
/// # use naga::front::glsl::Options;
/// Options::from(ShaderStage::Vertex);
/// ```
#[derive(Debug)]
pub struct Options {
/// The shader stage in the pipeline.
pub stage: ShaderStage,
/// Preprocessor definitions to be used, akin to having
/// ```glsl
/// #define key value
/// ```
/// for each key value pair in the map.
pub defines: FastHashMap<String, String>,
}
impl From<ShaderStage> for Options {
fn from(stage: ShaderStage) -> Self {
Options {
stage,
defines: FastHashMap::default(),
}
}
}
/// Additional information about the GLSL shader.
///
/// Stores additional information about the GLSL shader which might not be
/// stored in the shader [`Module`].
#[derive(Debug)]
pub struct ShaderMetadata {
/// The GLSL version specified in the shader through the use of the
/// `#version` preprocessor directive.
pub version: u16,
/// The GLSL profile specified in the shader through the use of the
/// `#version` preprocessor directive.
pub profile: Profile,
/// The shader stage in the pipeline, passed to the [`parse`](Frontend::parse)
/// method via the [`Options`] struct.
pub stage: ShaderStage,
/// The workgroup size for compute shaders, defaults to `[1; 3]` for
/// compute shaders and `[0; 3]` for non compute shaders.
pub workgroup_size: [u32; 3],
/// Whether or not early fragment tests where requested by the shader.
/// Defaults to `false`.
pub early_fragment_tests: bool,
/// The shader can request extensions via the
/// `#extension` preprocessor directive, in the directive a behavior
/// parameter is used to control whether the extension should be disabled,
/// warn on usage, enabled if possible or required.
///
/// This field only stores extensions which were required or requested to
/// be enabled if possible and they are supported.
pub extensions: FastHashSet<String>,
}
impl ShaderMetadata {
fn reset(&mut self, stage: ShaderStage) {
self.version = 0;
self.profile = Profile::Core;
self.stage = stage;
self.workgroup_size = [u32::from(stage == ShaderStage::Compute); 3];
self.early_fragment_tests = false;
self.extensions.clear();
}
}
impl Default for ShaderMetadata {
fn default() -> Self {
ShaderMetadata {
version: 0,
profile: Profile::Core,
stage: ShaderStage::Vertex,
workgroup_size: [0; 3],
early_fragment_tests: false,
extensions: FastHashSet::default(),
}
}
}
/// The `Frontend` is the central structure of the GLSL frontend.
///
/// To instantiate a new `Frontend` the [`Default`] trait is used, so a
/// call to the associated function [`Frontend::default`](Frontend::default) will
/// return a new `Frontend` instance.
///
/// To parse a shader simply call the [`parse`](Frontend::parse) method with a
/// [`Options`] struct and a [`&str`](str) holding the glsl code.
///
/// The `Frontend` also provides the [`metadata`](Frontend::metadata) to get some
/// further information about the previously parsed shader, like version and
/// extensions used (see the documentation for
/// [`ShaderMetadata`] to see all the returned information)
///
/// # Example usage
/// ```rust
/// use naga::ShaderStage;
/// use naga::front::glsl::{Frontend, Options};
///
/// let glsl = r#"
/// #version 450 core
///
/// void main() {}
/// "#;
///
/// let mut frontend = Frontend::default();
/// let options = Options::from(ShaderStage::Vertex);
/// frontend.parse(&options, glsl);
/// ```
///
/// # Reusability
///
/// If there's a need to parse more than one shader reusing the same `Frontend`
/// instance may be beneficial since internal allocations will be reused.
///
/// Calling the [`parse`](Frontend::parse) method multiple times will reset the
/// `Frontend` so no extra care is needed when reusing.
#[derive(Debug, Default)]
pub struct Frontend {
meta: ShaderMetadata,
lookup_function: FastHashMap<String, FunctionDeclaration>,
lookup_type: FastHashMap<String, Handle<Type>>,
global_variables: Vec<(String, GlobalLookup)>,
entry_args: Vec<EntryArg>,
layouter: Layouter,
errors: Vec<Error>,
}
impl Frontend {
fn reset(&mut self, stage: ShaderStage) {
self.meta.reset(stage);
self.lookup_function.clear();
self.lookup_type.clear();
self.global_variables.clear();
self.entry_args.clear();
self.layouter.clear();
}
/// Parses a shader either outputting a shader [`Module`] or a list of
/// [`Error`]s.
///
/// Multiple calls using the same `Frontend` and different shaders are supported.
pub fn parse(
&mut self,
options: &Options,
source: &str,
) -> std::result::Result<Module, ParseErrors> {
self.reset(options.stage);
let lexer = lex::Lexer::new(source, &options.defines);
let mut ctx = ParsingContext::new(lexer);
match ctx.parse(self) {
Ok(module) => {
if self.errors.is_empty() {
Ok(module)
} else {
Err(std::mem::take(&mut self.errors).into())
}
}
Err(e) => {
self.errors.push(e);
Err(std::mem::take(&mut self.errors).into())
}
}
}
/// Returns additional information about the parsed shader which might not
/// be stored in the [`Module`], see the documentation for
/// [`ShaderMetadata`] for more information about the returned data.
///
/// # Notes
///
/// Following an unsuccessful parsing the state of the returned information
/// is undefined, it might contain only partial information about the
/// current shader, the previous shader or both.
pub const fn metadata(&self) -> &ShaderMetadata {
&self.meta
}
}
+174
View File
@@ -0,0 +1,174 @@
/*!
Module responsible for calculating the offset and span for types.
There exists two types of layouts std140 and std430 (there's technically
two more layouts, shared and packed. Shared is not supported by spirv. Packed is
implementation dependent and for now it's just implemented as an alias to
std140).
The OpenGl spec (the layout rules are defined by the OpenGl spec in section
7.6.2.2 as opposed to the GLSL spec) uses the term basic machine units which are
equivalent to bytes.
*/
use super::{
ast::StructLayout,
error::{Error, ErrorKind},
Span,
};
use crate::{proc::Alignment, Handle, Scalar, Type, TypeInner, UniqueArena};
/// Struct with information needed for defining a struct member.
///
/// Returned by [`calculate_offset`].
#[derive(Debug)]
pub struct TypeAlignSpan {
/// The handle to the type, this might be the same handle passed to
/// [`calculate_offset`] or a new such a new array type with a different
/// stride set.
pub ty: Handle<Type>,
/// The alignment required by the type.
pub align: Alignment,
/// The size of the type.
pub span: u32,
}
/// Returns the type, alignment and span of a struct member according to a [`StructLayout`].
///
/// The functions returns a [`TypeAlignSpan`] which has a `ty` member this
/// should be used as the struct member type because for example arrays may have
/// to change the stride and as such need to have a different type.
pub fn calculate_offset(
mut ty: Handle<Type>,
meta: Span,
layout: StructLayout,
types: &mut UniqueArena<Type>,
errors: &mut Vec<Error>,
) -> TypeAlignSpan {
// When using the std430 storage layout, shader storage blocks will be laid out in buffer storage
// identically to uniform and shader storage blocks using the std140 layout, except
// that the base alignment and stride of arrays of scalars and vectors in rule 4 and of
// structures in rule 9 are not rounded up a multiple of the base alignment of a vec4.
let (align, span) = match types[ty].inner {
// 1. If the member is a scalar consuming N basic machine units,
// the base alignment is N.
TypeInner::Scalar(Scalar { width, .. }) => (Alignment::from_width(width), width as u32),
// 2. If the member is a two- or four-component vector with components
// consuming N basic machine units, the base alignment is 2N or 4N, respectively.
// 3. If the member is a three-component vector with components consuming N
// basic machine units, the base alignment is 4N.
TypeInner::Vector {
size,
scalar: Scalar { width, .. },
} => (
Alignment::from(size) * Alignment::from_width(width),
size as u32 * width as u32,
),
// 4. If the member is an array of scalars or vectors, the base alignment and array
// stride are set to match the base alignment of a single array element, according
// to rules (1), (2), and (3), and rounded up to the base alignment of a vec4.
// TODO: Matrices array
TypeInner::Array { base, size, .. } => {
let info = calculate_offset(base, meta, layout, types, errors);
let name = types[ty].name.clone();
// See comment at the beginning of the function
let (align, stride) = if StructLayout::Std430 == layout {
(info.align, info.align.round_up(info.span))
} else {
let align = info.align.max(Alignment::MIN_UNIFORM);
(align, align.round_up(info.span))
};
let span = match size {
crate::ArraySize::Constant(size) => size.get() * stride,
crate::ArraySize::Pending(_) => unreachable!(),
crate::ArraySize::Dynamic => stride,
};
let ty_span = types.get_span(ty);
ty = types.insert(
Type {
name,
inner: TypeInner::Array {
base: info.ty,
size,
stride,
},
},
ty_span,
);
(align, span)
}
// 5. If the member is a column-major matrix with C columns and R rows, the
// matrix is stored identically to an array of C column vectors with R
// components each, according to rule (4)
// TODO: Row major matrices
TypeInner::Matrix {
columns,
rows,
scalar,
} => {
let mut align = Alignment::from(rows) * Alignment::from_width(scalar.width);
// See comment at the beginning of the function
if StructLayout::Std430 != layout {
align = align.max(Alignment::MIN_UNIFORM);
}
// See comment on the error kind
if StructLayout::Std140 == layout && rows == crate::VectorSize::Bi {
errors.push(Error {
kind: ErrorKind::UnsupportedMatrixTypeInStd140,
meta,
});
}
(align, align * columns as u32)
}
TypeInner::Struct { ref members, .. } => {
let mut span = 0;
let mut align = Alignment::ONE;
let mut members = members.clone();
let name = types[ty].name.clone();
for member in members.iter_mut() {
let info = calculate_offset(member.ty, meta, layout, types, errors);
let member_alignment = info.align;
span = member_alignment.round_up(span);
align = member_alignment.max(align);
member.ty = info.ty;
member.offset = span;
span += info.span;
}
span = align.round_up(span);
let ty_span = types.get_span(ty);
ty = types.insert(
Type {
name,
inner: TypeInner::Struct { members, span },
},
ty_span,
);
(align, span)
}
_ => {
errors.push(Error {
kind: ErrorKind::SemanticError("Invalid struct member type".into()),
meta,
});
(Alignment::ONE, 0)
}
};
TypeAlignSpan { ty, align, span }
}
+442
View File
@@ -0,0 +1,442 @@
use super::{
ast::{FunctionKind, Profile, TypeQualifiers},
context::{Context, ExprPos},
error::ExpectedToken,
error::{Error, ErrorKind},
lex::{Lexer, LexerResultKind},
token::{Directive, DirectiveKind},
token::{Token, TokenValue},
variables::{GlobalOrConstant, VarDeclaration},
Frontend, Result,
};
use crate::{arena::Handle, proc::U32EvalError, Expression, Module, Span, Type};
use pp_rs::token::{PreprocessorError, Token as PPToken, TokenValue as PPTokenValue};
use std::iter::Peekable;
mod declarations;
mod expressions;
mod functions;
mod types;
pub struct ParsingContext<'source> {
lexer: Peekable<Lexer<'source>>,
/// Used to store tokens already consumed by the parser but that need to be backtracked
backtracked_token: Option<Token>,
last_meta: Span,
}
impl<'source> ParsingContext<'source> {
pub fn new(lexer: Lexer<'source>) -> Self {
ParsingContext {
lexer: lexer.peekable(),
backtracked_token: None,
last_meta: Span::default(),
}
}
/// Helper method for backtracking from a consumed token
///
/// This method should always be used instead of assigning to `backtracked_token` since
/// it validates that backtracking hasn't occurred more than one time in a row
///
/// # Panics
/// - If the parser already backtracked without bumping in between
pub fn backtrack(&mut self, token: Token) -> Result<()> {
// This should never happen
if let Some(ref prev_token) = self.backtracked_token {
return Err(Error {
kind: ErrorKind::InternalError("The parser tried to backtrack twice in a row"),
meta: prev_token.meta,
});
}
self.backtracked_token = Some(token);
Ok(())
}
pub fn expect_ident(&mut self, frontend: &mut Frontend) -> Result<(String, Span)> {
let token = self.bump(frontend)?;
match token.value {
TokenValue::Identifier(name) => Ok((name, token.meta)),
_ => Err(Error {
kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]),
meta: token.meta,
}),
}
}
pub fn expect(&mut self, frontend: &mut Frontend, value: TokenValue) -> Result<Token> {
let token = self.bump(frontend)?;
if token.value != value {
Err(Error {
kind: ErrorKind::InvalidToken(token.value, vec![value.into()]),
meta: token.meta,
})
} else {
Ok(token)
}
}
pub fn next(&mut self, frontend: &mut Frontend) -> Option<Token> {
loop {
if let Some(token) = self.backtracked_token.take() {
self.last_meta = token.meta;
break Some(token);
}
let res = self.lexer.next()?;
match res.kind {
LexerResultKind::Token(token) => {
self.last_meta = token.meta;
break Some(token);
}
LexerResultKind::Directive(directive) => {
frontend.handle_directive(directive, res.meta)
}
LexerResultKind::Error(error) => frontend.errors.push(Error {
kind: ErrorKind::PreprocessorError(error),
meta: res.meta,
}),
}
}
}
pub fn bump(&mut self, frontend: &mut Frontend) -> Result<Token> {
self.next(frontend).ok_or(Error {
kind: ErrorKind::EndOfFile,
meta: self.last_meta,
})
}
/// Returns None on the end of the file rather than an error like other methods
pub fn bump_if(&mut self, frontend: &mut Frontend, value: TokenValue) -> Option<Token> {
if self.peek(frontend).filter(|t| t.value == value).is_some() {
self.bump(frontend).ok()
} else {
None
}
}
pub fn peek(&mut self, frontend: &mut Frontend) -> Option<&Token> {
loop {
if let Some(ref token) = self.backtracked_token {
break Some(token);
}
match self.lexer.peek()?.kind {
LexerResultKind::Token(_) => {
let res = self.lexer.peek()?;
match res.kind {
LexerResultKind::Token(ref token) => break Some(token),
_ => unreachable!(),
}
}
LexerResultKind::Error(_) | LexerResultKind::Directive(_) => {
let res = self.lexer.next()?;
match res.kind {
LexerResultKind::Directive(directive) => {
frontend.handle_directive(directive, res.meta)
}
LexerResultKind::Error(error) => frontend.errors.push(Error {
kind: ErrorKind::PreprocessorError(error),
meta: res.meta,
}),
LexerResultKind::Token(_) => unreachable!(),
}
}
}
}
}
pub fn expect_peek(&mut self, frontend: &mut Frontend) -> Result<&Token> {
let meta = self.last_meta;
self.peek(frontend).ok_or(Error {
kind: ErrorKind::EndOfFile,
meta,
})
}
pub fn parse(&mut self, frontend: &mut Frontend) -> Result<Module> {
let mut module = Module::default();
let mut global_expression_kind_tracker = crate::proc::ExpressionKindTracker::new();
// Body and expression arena for global initialization
let mut ctx = Context::new(
frontend,
&mut module,
false,
&mut global_expression_kind_tracker,
)?;
while self.peek(frontend).is_some() {
self.parse_external_declaration(frontend, &mut ctx)?;
}
// Add an `EntryPoint` to `parser.module` for `main`, if a
// suitable overload exists. Error out if we can't find one.
if let Some(declaration) = frontend.lookup_function.get("main") {
for decl in declaration.overloads.iter() {
if let FunctionKind::Call(handle) = decl.kind {
if decl.defined && decl.parameters.is_empty() {
frontend.add_entry_point(handle, ctx)?;
return Ok(module);
}
}
}
}
Err(Error {
kind: ErrorKind::SemanticError("Missing entry point".into()),
meta: Span::default(),
})
}
fn parse_uint_constant(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
) -> Result<(u32, Span)> {
let (const_expr, meta) = self.parse_constant_expression(
frontend,
ctx.module,
ctx.global_expression_kind_tracker,
)?;
let res = ctx.module.to_ctx().eval_expr_to_u32(const_expr);
let int = match res {
Ok(value) => Ok(value),
Err(U32EvalError::Negative) => Err(Error {
kind: ErrorKind::SemanticError("int constant overflows".into()),
meta,
}),
Err(U32EvalError::NonConst) => Err(Error {
kind: ErrorKind::SemanticError("Expected a uint constant".into()),
meta,
}),
}?;
Ok((int, meta))
}
fn parse_constant_expression(
&mut self,
frontend: &mut Frontend,
module: &mut Module,
global_expression_kind_tracker: &mut crate::proc::ExpressionKindTracker,
) -> Result<(Handle<Expression>, Span)> {
let mut ctx = Context::new(frontend, module, true, global_expression_kind_tracker)?;
let mut stmt_ctx = ctx.stmt_ctx();
let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, None)?;
let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs)?;
Ok((root, meta))
}
}
impl Frontend {
fn handle_directive(&mut self, directive: Directive, meta: Span) {
let mut tokens = directive.tokens.into_iter();
match directive.kind {
DirectiveKind::Version { is_first_directive } => {
if !is_first_directive {
self.errors.push(Error {
kind: ErrorKind::SemanticError(
"#version must occur first in shader".into(),
),
meta,
})
}
match tokens.next() {
Some(PPToken {
value: PPTokenValue::Integer(int),
location,
}) => match int.value {
440 | 450 | 460 => self.meta.version = int.value as u16,
_ => self.errors.push(Error {
kind: ErrorKind::InvalidVersion(int.value),
meta: location.into(),
}),
},
Some(PPToken { value, location }) => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
}),
None => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedNewLine),
meta,
}),
};
match tokens.next() {
Some(PPToken {
value: PPTokenValue::Ident(name),
location,
}) => match name.as_str() {
"core" => self.meta.profile = Profile::Core,
_ => self.errors.push(Error {
kind: ErrorKind::InvalidProfile(name),
meta: location.into(),
}),
},
Some(PPToken { value, location }) => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
}),
None => {}
};
if let Some(PPToken { value, location }) = tokens.next() {
self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
})
}
}
DirectiveKind::Extension => {
// TODO: Proper extension handling
// - Checking for extension support in the compiler
// - Handle behaviors such as warn
// - Handle the all extension
let name = match tokens.next() {
Some(PPToken {
value: PPTokenValue::Ident(name),
..
}) => Some(name),
Some(PPToken { value, location }) => {
self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
});
None
}
None => {
self.errors.push(Error {
kind: ErrorKind::PreprocessorError(
PreprocessorError::UnexpectedNewLine,
),
meta,
});
None
}
};
match tokens.next() {
Some(PPToken {
value: PPTokenValue::Punct(pp_rs::token::Punct::Colon),
..
}) => {}
Some(PPToken { value, location }) => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
}),
None => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedNewLine),
meta,
}),
};
match tokens.next() {
Some(PPToken {
value: PPTokenValue::Ident(behavior),
location,
}) => match behavior.as_str() {
"require" | "enable" | "warn" | "disable" => {
if let Some(name) = name {
self.meta.extensions.insert(name);
}
}
_ => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
PPTokenValue::Ident(behavior),
)),
meta: location.into(),
}),
},
Some(PPToken { value, location }) => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
}),
None => self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedNewLine),
meta,
}),
}
if let Some(PPToken { value, location }) = tokens.next() {
self.errors.push(Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedToken(
value,
)),
meta: location.into(),
})
}
}
DirectiveKind::Pragma => {
// TODO: handle some common pragmas?
}
}
}
}
pub struct DeclarationContext<'ctx, 'qualifiers, 'a> {
qualifiers: TypeQualifiers<'qualifiers>,
/// Indicates a global declaration
external: bool,
is_inside_loop: bool,
ctx: &'ctx mut Context<'a>,
}
impl DeclarationContext<'_, '_, '_> {
fn add_var(
&mut self,
frontend: &mut Frontend,
ty: Handle<Type>,
name: String,
init: Option<Handle<Expression>>,
meta: Span,
) -> Result<Handle<Expression>> {
let decl = VarDeclaration {
qualifiers: &mut self.qualifiers,
ty,
name: Some(name),
init,
meta,
};
match self.external {
true => {
let global = frontend.add_global_var(self.ctx, decl)?;
let expr = match global {
GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle),
GlobalOrConstant::Constant(handle) => Expression::Constant(handle),
};
Ok(self.ctx.add_expression(expr, meta)?)
}
false => frontend.add_local_var(self.ctx, decl),
}
}
}
+682
View File
@@ -0,0 +1,682 @@
use crate::{
front::glsl::{
ast::{
GlobalLookup, GlobalLookupKind, Precision, QualifierKey, QualifierValue,
StorageQualifier, StructLayout, TypeQualifiers,
},
context::{Context, ExprPos},
error::ExpectedToken,
offset,
token::{Token, TokenValue},
types::scalar_components,
variables::{GlobalOrConstant, VarDeclaration},
Error, ErrorKind, Frontend, Span,
},
proc::Alignment,
AddressSpace, Expression, FunctionResult, Handle, Scalar, ScalarKind, Statement, StructMember,
Type, TypeInner,
};
use super::{DeclarationContext, ParsingContext, Result};
/// Helper method used to retrieve the child type of `ty` at
/// index `i`.
///
/// # Note
///
/// Does not check if the index is valid and returns the same type
/// when indexing out-of-bounds a struct or indexing a non indexable
/// type.
fn element_or_member_type(
ty: Handle<Type>,
i: usize,
types: &mut crate::UniqueArena<Type>,
) -> Handle<Type> {
match types[ty].inner {
// The child type of a vector is a scalar of the same kind and width
TypeInner::Vector { scalar, .. } => types.insert(
Type {
name: None,
inner: TypeInner::Scalar(scalar),
},
Default::default(),
),
// The child type of a matrix is a vector of floats with the same
// width and the size of the matrix rows.
TypeInner::Matrix { rows, scalar, .. } => types.insert(
Type {
name: None,
inner: TypeInner::Vector { size: rows, scalar },
},
Default::default(),
),
// The child type of an array is the base type of the array
TypeInner::Array { base, .. } => base,
// The child type of a struct at index `i` is the type of it's
// member at that same index.
//
// In case the index is out of bounds the same type is returned
TypeInner::Struct { ref members, .. } => {
members.get(i).map(|member| member.ty).unwrap_or(ty)
}
// The type isn't indexable, the same type is returned
_ => ty,
}
}
impl ParsingContext<'_> {
pub fn parse_external_declaration(
&mut self,
frontend: &mut Frontend,
global_ctx: &mut Context,
) -> Result<()> {
if self
.parse_declaration(frontend, global_ctx, true, false)?
.is_none()
{
let token = self.bump(frontend)?;
match token.value {
TokenValue::Semicolon if frontend.meta.version == 460 => Ok(()),
_ => {
let expected = match frontend.meta.version {
460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof],
_ => vec![ExpectedToken::Eof],
};
Err(Error {
kind: ErrorKind::InvalidToken(token.value, expected),
meta: token.meta,
})
}
}
} else {
Ok(())
}
}
pub fn parse_initializer(
&mut self,
frontend: &mut Frontend,
ty: Handle<Type>,
ctx: &mut Context,
) -> Result<(Handle<Expression>, Span)> {
// initializer:
// assignment_expression
// LEFT_BRACE initializer_list RIGHT_BRACE
// LEFT_BRACE initializer_list COMMA RIGHT_BRACE
//
// initializer_list:
// initializer
// initializer_list COMMA initializer
if let Some(Token { mut meta, .. }) = self.bump_if(frontend, TokenValue::LeftBrace) {
// initializer_list
let mut components = Vec::new();
loop {
// The type expected to be parsed inside the initializer list
let new_ty = element_or_member_type(ty, components.len(), &mut ctx.module.types);
components.push(self.parse_initializer(frontend, new_ty, ctx)?.0);
let token = self.bump(frontend)?;
match token.value {
TokenValue::Comma => {
if let Some(Token { meta: end_meta, .. }) =
self.bump_if(frontend, TokenValue::RightBrace)
{
meta.subsume(end_meta);
break;
}
}
TokenValue::RightBrace => {
meta.subsume(token.meta);
break;
}
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![TokenValue::Comma.into(), TokenValue::RightBrace.into()],
),
meta: token.meta,
})
}
}
}
Ok((
ctx.add_expression(Expression::Compose { ty, components }, meta)?,
meta,
))
} else {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_assignment(frontend, ctx, &mut stmt)?;
let (mut init, init_meta) = ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?;
let scalar_components = scalar_components(&ctx.module.types[ty].inner);
if let Some(scalar) = scalar_components {
ctx.implicit_conversion(&mut init, init_meta, scalar)?;
}
Ok((init, init_meta))
}
}
// Note: caller preparsed the type and qualifiers
// Note: caller skips this if the fallthrough token is not expected to be consumed here so this
// produced Error::InvalidToken if it isn't consumed
pub fn parse_init_declarator_list(
&mut self,
frontend: &mut Frontend,
mut ty: Handle<Type>,
ctx: &mut DeclarationContext,
) -> Result<()> {
// init_declarator_list:
// single_declaration
// init_declarator_list COMMA IDENTIFIER
// init_declarator_list COMMA IDENTIFIER array_specifier
// init_declarator_list COMMA IDENTIFIER array_specifier EQUAL initializer
// init_declarator_list COMMA IDENTIFIER EQUAL initializer
//
// single_declaration:
// fully_specified_type
// fully_specified_type IDENTIFIER
// fully_specified_type IDENTIFIER array_specifier
// fully_specified_type IDENTIFIER array_specifier EQUAL initializer
// fully_specified_type IDENTIFIER EQUAL initializer
// Consume any leading comma, e.g. this is valid: `float, a=1;`
if self
.peek(frontend)
.is_some_and(|t| t.value == TokenValue::Comma)
{
self.next(frontend);
}
loop {
let token = self.bump(frontend)?;
let name = match token.value {
TokenValue::Semicolon => break,
TokenValue::Identifier(name) => name,
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()],
),
meta: token.meta,
})
}
};
let mut meta = token.meta;
// array_specifier
// array_specifier EQUAL initializer
// EQUAL initializer
// parse an array specifier if it exists
// NOTE: unlike other parse methods this one doesn't expect an array specifier and
// returns Ok(None) rather than an error if there is not one
self.parse_array_specifier(frontend, ctx.ctx, &mut meta, &mut ty)?;
let is_global_const =
ctx.qualifiers.storage.0 == StorageQualifier::Const && ctx.external;
let init = self
.bump_if(frontend, TokenValue::Assign)
.map::<Result<_>, _>(|_| {
let prev_const = ctx.ctx.is_const;
ctx.ctx.is_const = is_global_const;
let (mut expr, init_meta) = self.parse_initializer(frontend, ty, ctx.ctx)?;
let scalar_components = scalar_components(&ctx.ctx.module.types[ty].inner);
if let Some(scalar) = scalar_components {
ctx.ctx.implicit_conversion(&mut expr, init_meta, scalar)?;
}
ctx.ctx.is_const = prev_const;
meta.subsume(init_meta);
Ok(expr)
})
.transpose()?;
let decl_initializer;
let late_initializer;
if is_global_const {
decl_initializer = init;
late_initializer = None;
} else if ctx.external {
decl_initializer =
init.and_then(|expr| ctx.ctx.lift_up_const_expression(expr).ok());
late_initializer = None;
} else if let Some(init) = init {
if ctx.is_inside_loop || !ctx.ctx.local_expression_kind_tracker.is_const(init) {
decl_initializer = None;
late_initializer = Some(init);
} else {
decl_initializer = Some(init);
late_initializer = None;
}
} else {
decl_initializer = None;
late_initializer = None;
};
let pointer = ctx.add_var(frontend, ty, name, decl_initializer, meta)?;
if let Some(value) = late_initializer {
ctx.ctx.emit_restart();
ctx.ctx.body.push(Statement::Store { pointer, value }, meta);
}
let token = self.bump(frontend)?;
match token.value {
TokenValue::Semicolon => break,
TokenValue::Comma => {}
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![TokenValue::Comma.into(), TokenValue::Semicolon.into()],
),
meta: token.meta,
})
}
}
}
Ok(())
}
/// `external` whether or not we are in a global or local context
pub fn parse_declaration(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
external: bool,
is_inside_loop: bool,
) -> Result<Option<Span>> {
//declaration:
// function_prototype SEMICOLON
//
// init_declarator_list SEMICOLON
// PRECISION precision_qualifier type_specifier SEMICOLON
//
// type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE SEMICOLON
// type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER SEMICOLON
// type_qualifier IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE IDENTIFIER array_specifier SEMICOLON
// type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON
// type_qualifier IDENTIFIER identifier_list SEMICOLON
if self.peek_type_qualifier(frontend) || self.peek_type_name(frontend) {
let mut qualifiers = self.parse_type_qualifiers(frontend, ctx)?;
if self.peek_type_name(frontend) {
// This branch handles variables and function prototypes and if
// external is true also function definitions
let (ty, mut meta) = self.parse_type(frontend, ctx)?;
let token = self.bump(frontend)?;
let token_fallthrough = match token.value {
TokenValue::Identifier(name) => match self.expect_peek(frontend)?.value {
TokenValue::LeftParen => {
// This branch handles function definition and prototypes
self.bump(frontend)?;
let result = ty.map(|ty| FunctionResult { ty, binding: None });
let mut context = Context::new(
frontend,
ctx.module,
false,
ctx.global_expression_kind_tracker,
)?;
self.parse_function_args(frontend, &mut context)?;
let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta;
meta.subsume(end_meta);
let token = self.bump(frontend)?;
return match token.value {
TokenValue::Semicolon => {
// This branch handles function prototypes
frontend.add_prototype(context, name, result, meta);
Ok(Some(meta))
}
TokenValue::LeftBrace if external => {
// This branch handles function definitions
// as you can see by the guard this branch
// only happens if external is also true
// parse the body
self.parse_compound_statement(
token.meta,
frontend,
&mut context,
&mut None,
false,
)?;
frontend.add_function(context, name, result, meta);
Ok(Some(meta))
}
_ if external => Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![
TokenValue::LeftBrace.into(),
TokenValue::Semicolon.into(),
],
),
meta: token.meta,
}),
_ => Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![TokenValue::Semicolon.into()],
),
meta: token.meta,
}),
};
}
// Pass the token to the init_declarator_list parser
_ => Token {
value: TokenValue::Identifier(name),
meta: token.meta,
},
},
// Pass the token to the init_declarator_list parser
_ => token,
};
// If program execution has reached here then this will be a
// init_declarator_list
// token_fallthrough will have a token that was already bumped
if let Some(ty) = ty {
let mut ctx = DeclarationContext {
qualifiers,
external,
is_inside_loop,
ctx,
};
self.backtrack(token_fallthrough)?;
self.parse_init_declarator_list(frontend, ty, &mut ctx)?;
} else {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError("Declaration cannot have void type".into()),
meta,
})
}
Ok(Some(meta))
} else {
// This branch handles struct definitions and modifiers like
// ```glsl
// layout(early_fragment_tests);
// ```
let token = self.bump(frontend)?;
match token.value {
TokenValue::Identifier(ty_name) => {
if self.bump_if(frontend, TokenValue::LeftBrace).is_some() {
self.parse_block_declaration(
frontend,
ctx,
&mut qualifiers,
ty_name,
token.meta,
)
.map(Some)
} else {
if qualifiers.invariant.take().is_some() {
frontend.make_variable_invariant(ctx, &ty_name, token.meta)?;
qualifiers.unused_errors(&mut frontend.errors);
self.expect(frontend, TokenValue::Semicolon)?;
return Ok(Some(qualifiers.span));
}
//TODO: declaration
// type_qualifier IDENTIFIER SEMICOLON
// type_qualifier IDENTIFIER identifier_list SEMICOLON
Err(Error {
kind: ErrorKind::NotImplemented("variable qualifier"),
meta: token.meta,
})
}
}
TokenValue::Semicolon => {
if let Some(value) =
qualifiers.uint_layout_qualifier("local_size_x", &mut frontend.errors)
{
frontend.meta.workgroup_size[0] = value;
}
if let Some(value) =
qualifiers.uint_layout_qualifier("local_size_y", &mut frontend.errors)
{
frontend.meta.workgroup_size[1] = value;
}
if let Some(value) =
qualifiers.uint_layout_qualifier("local_size_z", &mut frontend.errors)
{
frontend.meta.workgroup_size[2] = value;
}
frontend.meta.early_fragment_tests |= qualifiers
.none_layout_qualifier("early_fragment_tests", &mut frontend.errors);
qualifiers.unused_errors(&mut frontend.errors);
Ok(Some(qualifiers.span))
}
_ => Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()],
),
meta: token.meta,
}),
}
}
} else {
match self.peek(frontend).map(|t| &t.value) {
Some(&TokenValue::Precision) => {
// PRECISION precision_qualifier type_specifier SEMICOLON
self.bump(frontend)?;
let token = self.bump(frontend)?;
let _ = match token.value {
TokenValue::PrecisionQualifier(p) => p,
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![
TokenValue::PrecisionQualifier(Precision::High).into(),
TokenValue::PrecisionQualifier(Precision::Medium).into(),
TokenValue::PrecisionQualifier(Precision::Low).into(),
],
),
meta: token.meta,
})
}
};
let (ty, meta) = self.parse_type_non_void(frontend, ctx)?;
match ctx.module.types[ty].inner {
TypeInner::Scalar(Scalar {
kind: ScalarKind::Float | ScalarKind::Sint,
..
}) => {}
_ => frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Precision statement can only work on floats and ints".into(),
),
meta,
}),
}
self.expect(frontend, TokenValue::Semicolon)?;
Ok(Some(meta))
}
_ => Ok(None),
}
}
}
pub fn parse_block_declaration(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
qualifiers: &mut TypeQualifiers,
ty_name: String,
mut meta: Span,
) -> Result<Span> {
let layout = match qualifiers.layout_qualifiers.remove(&QualifierKey::Layout) {
Some((QualifierValue::Layout(l), _)) => l,
None => {
if let StorageQualifier::AddressSpace(AddressSpace::Storage { .. }) =
qualifiers.storage.0
{
StructLayout::Std430
} else {
StructLayout::Std140
}
}
_ => unreachable!(),
};
let mut members = Vec::new();
let span = self.parse_struct_declaration_list(frontend, ctx, &mut members, layout)?;
self.expect(frontend, TokenValue::RightBrace)?;
let mut ty = ctx.module.types.insert(
Type {
name: Some(ty_name),
inner: TypeInner::Struct {
members: members.clone(),
span,
},
},
Default::default(),
);
let token = self.bump(frontend)?;
let name = match token.value {
TokenValue::Semicolon => None,
TokenValue::Identifier(name) => {
self.parse_array_specifier(frontend, ctx, &mut meta, &mut ty)?;
self.expect(frontend, TokenValue::Semicolon)?;
Some(name)
}
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![ExpectedToken::Identifier, TokenValue::Semicolon.into()],
),
meta: token.meta,
})
}
};
let global = frontend.add_global_var(
ctx,
VarDeclaration {
qualifiers,
ty,
name,
init: None,
meta,
},
)?;
for (i, k, ty) in members.into_iter().enumerate().filter_map(|(i, m)| {
let ty = m.ty;
m.name.map(|s| (i as u32, s, ty))
}) {
let lookup = GlobalLookup {
kind: match global {
GlobalOrConstant::Global(handle) => GlobalLookupKind::BlockSelect(handle, i),
GlobalOrConstant::Constant(handle) => GlobalLookupKind::Constant(handle, ty),
},
entry_arg: None,
mutable: true,
};
ctx.add_global(&k, lookup)?;
frontend.global_variables.push((k, lookup));
}
Ok(meta)
}
// TODO: Accept layout arguments
pub fn parse_struct_declaration_list(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
members: &mut Vec<StructMember>,
layout: StructLayout,
) -> Result<u32> {
let mut span = 0;
let mut align = Alignment::ONE;
loop {
// TODO: type_qualifier
let (base_ty, mut meta) = self.parse_type_non_void(frontend, ctx)?;
loop {
let (name, name_meta) = self.expect_ident(frontend)?;
let mut ty = base_ty;
self.parse_array_specifier(frontend, ctx, &mut meta, &mut ty)?;
meta.subsume(name_meta);
let info = offset::calculate_offset(
ty,
meta,
layout,
&mut ctx.module.types,
&mut frontend.errors,
);
let member_alignment = info.align;
span = member_alignment.round_up(span);
align = member_alignment.max(align);
members.push(StructMember {
name: Some(name),
ty: info.ty,
binding: None,
offset: span,
});
span += info.span;
if self.bump_if(frontend, TokenValue::Comma).is_none() {
break;
}
}
self.expect(frontend, TokenValue::Semicolon)?;
if let TokenValue::RightBrace = self.expect_peek(frontend)?.value {
break;
}
}
span = align.round_up(span);
Ok(span)
}
}
+548
View File
@@ -0,0 +1,548 @@
use std::num::NonZeroU32;
use crate::{
front::glsl::{
ast::{FunctionCall, FunctionCallKind, HirExpr, HirExprKind},
context::{Context, StmtContext},
error::{ErrorKind, ExpectedToken},
parser::ParsingContext,
token::{Token, TokenValue},
Error, Frontend, Result, Span,
},
ArraySize, BinaryOperator, Handle, Literal, Type, TypeInner, UnaryOperator,
};
impl ParsingContext<'_> {
pub fn parse_primary(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
) -> Result<Handle<HirExpr>> {
let mut token = self.bump(frontend)?;
let literal = match token.value {
TokenValue::IntConstant(int) => {
if int.width != 32 {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError("Unsupported non-32bit integer".into()),
meta: token.meta,
});
}
if int.signed {
Literal::I32(int.value as i32)
} else {
Literal::U32(int.value as u32)
}
}
TokenValue::FloatConstant(float) => {
if float.width != 32 {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
concat!(
"Unsupported floating-point value ",
"(expected single-precision floating-point number)"
)
.into(),
),
meta: token.meta,
});
}
Literal::F32(float.value)
}
TokenValue::BoolConstant(value) => Literal::Bool(value),
TokenValue::LeftParen => {
let expr = self.parse_expression(frontend, ctx, stmt)?;
let meta = self.expect(frontend, TokenValue::RightParen)?.meta;
token.meta.subsume(meta);
return Ok(expr);
}
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![
TokenValue::LeftParen.into(),
ExpectedToken::IntLiteral,
ExpectedToken::FloatLiteral,
ExpectedToken::BoolLiteral,
],
),
meta: token.meta,
});
}
};
Ok(stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Literal(literal),
meta: token.meta,
},
Default::default(),
))
}
pub fn parse_function_call_args(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
meta: &mut Span,
) -> Result<Vec<Handle<HirExpr>>> {
let mut args = Vec::new();
if let Some(token) = self.bump_if(frontend, TokenValue::RightParen) {
meta.subsume(token.meta);
} else {
loop {
args.push(self.parse_assignment(frontend, ctx, stmt)?);
let token = self.bump(frontend)?;
match token.value {
TokenValue::Comma => {}
TokenValue::RightParen => {
meta.subsume(token.meta);
break;
}
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![TokenValue::Comma.into(), TokenValue::RightParen.into()],
),
meta: token.meta,
});
}
}
}
}
Ok(args)
}
pub fn parse_postfix(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
) -> Result<Handle<HirExpr>> {
let mut base = if self.peek_type_name(frontend) {
let (mut handle, mut meta) = self.parse_type_non_void(frontend, ctx)?;
self.expect(frontend, TokenValue::LeftParen)?;
let args = self.parse_function_call_args(frontend, ctx, stmt, &mut meta)?;
if let TypeInner::Array {
size: ArraySize::Dynamic,
stride,
base,
} = ctx.module.types[handle].inner
{
let span = ctx.module.types.get_span(handle);
let size = u32::try_from(args.len())
.ok()
.and_then(NonZeroU32::new)
.ok_or(Error {
kind: ErrorKind::SemanticError(
"There must be at least one argument".into(),
),
meta,
})?;
handle = ctx.module.types.insert(
Type {
name: None,
inner: TypeInner::Array {
stride,
base,
size: ArraySize::Constant(size),
},
},
span,
)
}
stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Call(FunctionCall {
kind: FunctionCallKind::TypeConstructor(handle),
args,
}),
meta,
},
Default::default(),
)
} else if let TokenValue::Identifier(_) = self.expect_peek(frontend)?.value {
let (name, mut meta) = self.expect_ident(frontend)?;
let expr = if self.bump_if(frontend, TokenValue::LeftParen).is_some() {
let args = self.parse_function_call_args(frontend, ctx, stmt, &mut meta)?;
let kind = match frontend.lookup_type.get(&name) {
Some(ty) => FunctionCallKind::TypeConstructor(*ty),
None => FunctionCallKind::Function(name),
};
HirExpr {
kind: HirExprKind::Call(FunctionCall { kind, args }),
meta,
}
} else {
let var = match frontend.lookup_variable(ctx, &name, meta)? {
Some(var) => var,
None => {
return Err(Error {
kind: ErrorKind::UnknownVariable(name),
meta,
})
}
};
HirExpr {
kind: HirExprKind::Variable(var),
meta,
}
};
stmt.hir_exprs.append(expr, Default::default())
} else {
self.parse_primary(frontend, ctx, stmt)?
};
while let TokenValue::LeftBracket
| TokenValue::Dot
| TokenValue::Increment
| TokenValue::Decrement = self.expect_peek(frontend)?.value
{
let Token { value, mut meta } = self.bump(frontend)?;
match value {
TokenValue::LeftBracket => {
let index = self.parse_expression(frontend, ctx, stmt)?;
let end_meta = self.expect(frontend, TokenValue::RightBracket)?.meta;
meta.subsume(end_meta);
base = stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Access { base, index },
meta,
},
Default::default(),
)
}
TokenValue::Dot => {
let (field, end_meta) = self.expect_ident(frontend)?;
if self.bump_if(frontend, TokenValue::LeftParen).is_some() {
let args = self.parse_function_call_args(frontend, ctx, stmt, &mut meta)?;
base = stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Method {
expr: base,
name: field,
args,
},
meta,
},
Default::default(),
);
continue;
}
meta.subsume(end_meta);
base = stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Select { base, field },
meta,
},
Default::default(),
)
}
TokenValue::Increment | TokenValue::Decrement => {
base = stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::PrePostfix {
op: match value {
TokenValue::Increment => BinaryOperator::Add,
_ => BinaryOperator::Subtract,
},
postfix: true,
expr: base,
},
meta,
},
Default::default(),
)
}
_ => unreachable!(),
}
}
Ok(base)
}
pub fn parse_unary(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
) -> Result<Handle<HirExpr>> {
Ok(match self.expect_peek(frontend)?.value {
TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => {
let Token { value, mut meta } = self.bump(frontend)?;
let expr = self.parse_unary(frontend, ctx, stmt)?;
let end_meta = stmt.hir_exprs[expr].meta;
let kind = match value {
TokenValue::Dash => HirExprKind::Unary {
op: UnaryOperator::Negate,
expr,
},
TokenValue::Bang => HirExprKind::Unary {
op: UnaryOperator::LogicalNot,
expr,
},
TokenValue::Tilde => HirExprKind::Unary {
op: UnaryOperator::BitwiseNot,
expr,
},
_ => return Ok(expr),
};
meta.subsume(end_meta);
stmt.hir_exprs
.append(HirExpr { kind, meta }, Default::default())
}
TokenValue::Increment | TokenValue::Decrement => {
let Token { value, meta } = self.bump(frontend)?;
let expr = self.parse_unary(frontend, ctx, stmt)?;
stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::PrePostfix {
op: match value {
TokenValue::Increment => BinaryOperator::Add,
_ => BinaryOperator::Subtract,
},
postfix: false,
expr,
},
meta,
},
Default::default(),
)
}
_ => self.parse_postfix(frontend, ctx, stmt)?,
})
}
pub fn parse_binary(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
passthrough: Option<Handle<HirExpr>>,
min_bp: u8,
) -> Result<Handle<HirExpr>> {
let mut left = passthrough
.ok_or(ErrorKind::EndOfFile /* Dummy error */)
.or_else(|_| self.parse_unary(frontend, ctx, stmt))?;
let mut meta = stmt.hir_exprs[left].meta;
while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(frontend)?.value) {
if l_bp < min_bp {
break;
}
let Token { value, .. } = self.bump(frontend)?;
let right = self.parse_binary(frontend, ctx, stmt, None, r_bp)?;
let end_meta = stmt.hir_exprs[right].meta;
meta.subsume(end_meta);
left = stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Binary {
left,
op: match value {
TokenValue::LogicalOr => BinaryOperator::LogicalOr,
TokenValue::LogicalXor => BinaryOperator::NotEqual,
TokenValue::LogicalAnd => BinaryOperator::LogicalAnd,
TokenValue::VerticalBar => BinaryOperator::InclusiveOr,
TokenValue::Caret => BinaryOperator::ExclusiveOr,
TokenValue::Ampersand => BinaryOperator::And,
TokenValue::Equal => BinaryOperator::Equal,
TokenValue::NotEqual => BinaryOperator::NotEqual,
TokenValue::GreaterEqual => BinaryOperator::GreaterEqual,
TokenValue::LessEqual => BinaryOperator::LessEqual,
TokenValue::LeftAngle => BinaryOperator::Less,
TokenValue::RightAngle => BinaryOperator::Greater,
TokenValue::LeftShift => BinaryOperator::ShiftLeft,
TokenValue::RightShift => BinaryOperator::ShiftRight,
TokenValue::Plus => BinaryOperator::Add,
TokenValue::Dash => BinaryOperator::Subtract,
TokenValue::Star => BinaryOperator::Multiply,
TokenValue::Slash => BinaryOperator::Divide,
TokenValue::Percent => BinaryOperator::Modulo,
_ => unreachable!(),
},
right,
},
meta,
},
Default::default(),
)
}
Ok(left)
}
pub fn parse_conditional(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
passthrough: Option<Handle<HirExpr>>,
) -> Result<Handle<HirExpr>> {
let mut condition = self.parse_binary(frontend, ctx, stmt, passthrough, 0)?;
let mut meta = stmt.hir_exprs[condition].meta;
if self.bump_if(frontend, TokenValue::Question).is_some() {
let accept = self.parse_expression(frontend, ctx, stmt)?;
self.expect(frontend, TokenValue::Colon)?;
let reject = self.parse_assignment(frontend, ctx, stmt)?;
let end_meta = stmt.hir_exprs[reject].meta;
meta.subsume(end_meta);
condition = stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Conditional {
condition,
accept,
reject,
},
meta,
},
Default::default(),
)
}
Ok(condition)
}
pub fn parse_assignment(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
) -> Result<Handle<HirExpr>> {
let tgt = self.parse_unary(frontend, ctx, stmt)?;
let mut meta = stmt.hir_exprs[tgt].meta;
Ok(match self.expect_peek(frontend)?.value {
TokenValue::Assign => {
self.bump(frontend)?;
let value = self.parse_assignment(frontend, ctx, stmt)?;
let end_meta = stmt.hir_exprs[value].meta;
meta.subsume(end_meta);
stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Assign { tgt, value },
meta,
},
Default::default(),
)
}
TokenValue::OrAssign
| TokenValue::AndAssign
| TokenValue::AddAssign
| TokenValue::DivAssign
| TokenValue::ModAssign
| TokenValue::SubAssign
| TokenValue::MulAssign
| TokenValue::LeftShiftAssign
| TokenValue::RightShiftAssign
| TokenValue::XorAssign => {
let token = self.bump(frontend)?;
let right = self.parse_assignment(frontend, ctx, stmt)?;
let end_meta = stmt.hir_exprs[right].meta;
meta.subsume(end_meta);
let value = stmt.hir_exprs.append(
HirExpr {
meta,
kind: HirExprKind::Binary {
left: tgt,
op: match token.value {
TokenValue::OrAssign => BinaryOperator::InclusiveOr,
TokenValue::AndAssign => BinaryOperator::And,
TokenValue::AddAssign => BinaryOperator::Add,
TokenValue::DivAssign => BinaryOperator::Divide,
TokenValue::ModAssign => BinaryOperator::Modulo,
TokenValue::SubAssign => BinaryOperator::Subtract,
TokenValue::MulAssign => BinaryOperator::Multiply,
TokenValue::LeftShiftAssign => BinaryOperator::ShiftLeft,
TokenValue::RightShiftAssign => BinaryOperator::ShiftRight,
TokenValue::XorAssign => BinaryOperator::ExclusiveOr,
_ => unreachable!(),
},
right,
},
},
Default::default(),
);
stmt.hir_exprs.append(
HirExpr {
kind: HirExprKind::Assign { tgt, value },
meta,
},
Default::default(),
)
}
_ => self.parse_conditional(frontend, ctx, stmt, Some(tgt))?,
})
}
pub fn parse_expression(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
stmt: &mut StmtContext,
) -> Result<Handle<HirExpr>> {
let mut expr = self.parse_assignment(frontend, ctx, stmt)?;
while let TokenValue::Comma = self.expect_peek(frontend)?.value {
self.bump(frontend)?;
expr = self.parse_assignment(frontend, ctx, stmt)?;
}
Ok(expr)
}
}
const fn binding_power(value: &TokenValue) -> Option<(u8, u8)> {
Some(match *value {
TokenValue::LogicalOr => (1, 2),
TokenValue::LogicalXor => (3, 4),
TokenValue::LogicalAnd => (5, 6),
TokenValue::VerticalBar => (7, 8),
TokenValue::Caret => (9, 10),
TokenValue::Ampersand => (11, 12),
TokenValue::Equal | TokenValue::NotEqual => (13, 14),
TokenValue::GreaterEqual
| TokenValue::LessEqual
| TokenValue::LeftAngle
| TokenValue::RightAngle => (15, 16),
TokenValue::LeftShift | TokenValue::RightShift => (17, 18),
TokenValue::Plus | TokenValue::Dash => (19, 20),
TokenValue::Star | TokenValue::Slash | TokenValue::Percent => (21, 22),
_ => return None,
})
}
+659
View File
@@ -0,0 +1,659 @@
use crate::front::glsl::context::ExprPos;
use crate::front::glsl::Span;
use crate::Literal;
use crate::{
front::glsl::{
ast::ParameterQualifier,
context::Context,
parser::ParsingContext,
token::{Token, TokenValue},
variables::VarDeclaration,
Error, ErrorKind, Frontend, Result,
},
Block, Expression, Statement, SwitchCase, UnaryOperator,
};
impl ParsingContext<'_> {
pub fn peek_parameter_qualifier(&mut self, frontend: &mut Frontend) -> bool {
self.peek(frontend).is_some_and(|t| match t.value {
TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true,
_ => false,
})
}
/// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In`
pub fn parse_parameter_qualifier(&mut self, frontend: &mut Frontend) -> ParameterQualifier {
if self.peek_parameter_qualifier(frontend) {
match self.bump(frontend).unwrap().value {
TokenValue::In => ParameterQualifier::In,
TokenValue::Out => ParameterQualifier::Out,
TokenValue::InOut => ParameterQualifier::InOut,
TokenValue::Const => ParameterQualifier::Const,
_ => unreachable!(),
}
} else {
ParameterQualifier::In
}
}
pub fn parse_statement(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
terminator: &mut Option<usize>,
is_inside_loop: bool,
) -> Result<Option<Span>> {
// Type qualifiers always identify a declaration statement
if self.peek_type_qualifier(frontend) {
return self.parse_declaration(frontend, ctx, false, is_inside_loop);
}
// Type names can identify either declaration statements or type constructors
// depending on whether the token following the type name is a `(` (LeftParen)
if self.peek_type_name(frontend) {
// Start by consuming the type name so that we can peek the token after it
let token = self.bump(frontend)?;
// Peek the next token and check if it's a `(` (LeftParen) if so the statement
// is a constructor, otherwise it's a declaration. We need to do the check
// beforehand and not in the if since we will backtrack before the if
let declaration = TokenValue::LeftParen != self.expect_peek(frontend)?.value;
self.backtrack(token)?;
if declaration {
return self.parse_declaration(frontend, ctx, false, is_inside_loop);
}
}
let new_break = || {
let mut block = Block::new();
block.push(Statement::Break, Span::default());
block
};
let &Token {
ref value,
mut meta,
} = self.expect_peek(frontend)?;
let meta_rest = match *value {
TokenValue::Continue => {
let meta = self.bump(frontend)?.meta;
ctx.body.push(Statement::Continue, meta);
terminator.get_or_insert(ctx.body.len());
self.expect(frontend, TokenValue::Semicolon)?.meta
}
TokenValue::Break => {
let meta = self.bump(frontend)?.meta;
ctx.body.push(Statement::Break, meta);
terminator.get_or_insert(ctx.body.len());
self.expect(frontend, TokenValue::Semicolon)?.meta
}
TokenValue::Return => {
self.bump(frontend)?;
let (value, meta) = match self.expect_peek(frontend)?.value {
TokenValue::Semicolon => (None, self.bump(frontend)?.meta),
_ => {
// TODO: Implicit conversions
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(frontend, ctx, &mut stmt)?;
self.expect(frontend, TokenValue::Semicolon)?;
let (handle, meta) =
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?;
(Some(handle), meta)
}
};
ctx.emit_restart();
ctx.body.push(Statement::Return { value }, meta);
terminator.get_or_insert(ctx.body.len());
meta
}
TokenValue::Discard => {
let meta = self.bump(frontend)?.meta;
ctx.body.push(Statement::Kill, meta);
terminator.get_or_insert(ctx.body.len());
self.expect(frontend, TokenValue::Semicolon)?.meta
}
TokenValue::If => {
let mut meta = self.bump(frontend)?.meta;
self.expect(frontend, TokenValue::LeftParen)?;
let condition = {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(frontend, ctx, &mut stmt)?;
let (handle, more_meta) =
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?;
meta.subsume(more_meta);
handle
};
self.expect(frontend, TokenValue::RightParen)?;
let accept = ctx.new_body(|ctx| {
if let Some(more_meta) =
self.parse_statement(frontend, ctx, &mut None, is_inside_loop)?
{
meta.subsume(more_meta);
}
Ok(())
})?;
let reject = ctx.new_body(|ctx| {
if self.bump_if(frontend, TokenValue::Else).is_some() {
if let Some(more_meta) =
self.parse_statement(frontend, ctx, &mut None, is_inside_loop)?
{
meta.subsume(more_meta);
}
}
Ok(())
})?;
ctx.body.push(
Statement::If {
condition,
accept,
reject,
},
meta,
);
meta
}
TokenValue::Switch => {
let mut meta = self.bump(frontend)?.meta;
let end_meta;
self.expect(frontend, TokenValue::LeftParen)?;
let (selector, uint) = {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(frontend, ctx, &mut stmt)?;
let (root, meta) = ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs)?;
let uint = ctx.resolve_type(root, meta)?.scalar_kind()
== Some(crate::ScalarKind::Uint);
(root, uint)
};
self.expect(frontend, TokenValue::RightParen)?;
ctx.emit_restart();
let mut cases = Vec::new();
// Track if any default case is present in the switch statement.
let mut default_present = false;
self.expect(frontend, TokenValue::LeftBrace)?;
loop {
let value = match self.expect_peek(frontend)?.value {
TokenValue::Case => {
self.bump(frontend)?;
let (const_expr, meta) = self.parse_constant_expression(
frontend,
ctx.module,
ctx.global_expression_kind_tracker,
)?;
match ctx.module.global_expressions[const_expr] {
Expression::Literal(Literal::I32(value)) => match uint {
// This unchecked cast isn't good, but since
// we only reach this code when the selector
// is unsigned but the case label is signed,
// verification will reject the module
// anyway (which also matches GLSL's rules).
true => crate::SwitchValue::U32(value as u32),
false => crate::SwitchValue::I32(value),
},
Expression::Literal(Literal::U32(value)) => {
crate::SwitchValue::U32(value)
}
_ => {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Case values can only be integers".into(),
),
meta,
});
crate::SwitchValue::I32(0)
}
}
}
TokenValue::Default => {
self.bump(frontend)?;
default_present = true;
crate::SwitchValue::Default
}
TokenValue::RightBrace => {
end_meta = self.bump(frontend)?.meta;
break;
}
_ => {
let Token { value, meta } = self.bump(frontend)?;
return Err(Error {
kind: ErrorKind::InvalidToken(
value,
vec![
TokenValue::Case.into(),
TokenValue::Default.into(),
TokenValue::RightBrace.into(),
],
),
meta,
});
}
};
self.expect(frontend, TokenValue::Colon)?;
let mut fall_through = true;
let body = ctx.new_body(|ctx| {
let mut case_terminator = None;
loop {
match self.expect_peek(frontend)?.value {
TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => {
break
}
_ => {
self.parse_statement(
frontend,
ctx,
&mut case_terminator,
is_inside_loop,
)?;
}
}
}
if let Some(mut idx) = case_terminator {
if let Statement::Break = ctx.body[idx - 1] {
fall_through = false;
idx -= 1;
}
ctx.body.cull(idx..)
}
Ok(())
})?;
cases.push(SwitchCase {
value,
body,
fall_through,
})
}
meta.subsume(end_meta);
// NOTE: do not unwrap here since a switch statement isn't required
// to have any cases.
if let Some(case) = cases.last_mut() {
// GLSL requires that the last case not be empty, so we check
// that here and produce an error otherwise (fall_through must
// also be checked because `break`s count as statements but
// they aren't added to the body)
if case.body.is_empty() && case.fall_through {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"last case/default label must be followed by statements".into(),
),
meta,
})
}
// GLSL allows the last case to not have any `break` statement,
// this would mark it as fall through but naga's IR requires that
// the last case must not be fall through, so we mark need to mark
// the last case as not fall through always.
case.fall_through = false;
}
// Add an empty default case in case non was present, this is needed because
// naga's IR requires that all switch statements must have a default case but
// GLSL doesn't require that, so we might need to add an empty default case.
if !default_present {
cases.push(SwitchCase {
value: crate::SwitchValue::Default,
body: Block::new(),
fall_through: false,
})
}
ctx.body.push(Statement::Switch { selector, cases }, meta);
meta
}
TokenValue::While => {
let mut meta = self.bump(frontend)?.meta;
let loop_body = ctx.new_body(|ctx| {
let mut stmt = ctx.stmt_ctx();
self.expect(frontend, TokenValue::LeftParen)?;
let root = self.parse_expression(frontend, ctx, &mut stmt)?;
meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta);
let (expr, expr_meta) = ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?;
let condition = ctx.add_expression(
Expression::Unary {
op: UnaryOperator::LogicalNot,
expr,
},
expr_meta,
)?;
ctx.emit_restart();
ctx.body.push(
Statement::If {
condition,
accept: new_break(),
reject: Block::new(),
},
Span::default(),
);
meta.subsume(expr_meta);
if let Some(body_meta) = self.parse_statement(frontend, ctx, &mut None, true)? {
meta.subsume(body_meta);
}
Ok(())
})?;
ctx.body.push(
Statement::Loop {
body: loop_body,
continuing: Block::new(),
break_if: None,
},
meta,
);
meta
}
TokenValue::Do => {
let mut meta = self.bump(frontend)?.meta;
let loop_body = ctx.new_body(|ctx| {
let mut terminator = None;
self.parse_statement(frontend, ctx, &mut terminator, true)?;
let mut stmt = ctx.stmt_ctx();
self.expect(frontend, TokenValue::While)?;
self.expect(frontend, TokenValue::LeftParen)?;
let root = self.parse_expression(frontend, ctx, &mut stmt)?;
let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta;
meta.subsume(end_meta);
let (expr, expr_meta) = ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?;
let condition = ctx.add_expression(
Expression::Unary {
op: UnaryOperator::LogicalNot,
expr,
},
expr_meta,
)?;
ctx.emit_restart();
ctx.body.push(
Statement::If {
condition,
accept: new_break(),
reject: Block::new(),
},
Span::default(),
);
if let Some(idx) = terminator {
ctx.body.cull(idx..)
}
Ok(())
})?;
ctx.body.push(
Statement::Loop {
body: loop_body,
continuing: Block::new(),
break_if: None,
},
meta,
);
meta
}
TokenValue::For => {
let mut meta = self.bump(frontend)?.meta;
ctx.symbol_table.push_scope();
self.expect(frontend, TokenValue::LeftParen)?;
if self.bump_if(frontend, TokenValue::Semicolon).is_none() {
if self.peek_type_name(frontend) || self.peek_type_qualifier(frontend) {
self.parse_declaration(frontend, ctx, false, is_inside_loop)?;
} else {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(frontend, ctx, &mut stmt)?;
ctx.lower(stmt, frontend, expr, ExprPos::Rhs)?;
self.expect(frontend, TokenValue::Semicolon)?;
}
}
let loop_body = ctx.new_body(|ctx| {
if self.bump_if(frontend, TokenValue::Semicolon).is_none() {
let (expr, expr_meta) = if self.peek_type_name(frontend)
|| self.peek_type_qualifier(frontend)
{
let mut qualifiers = self.parse_type_qualifiers(frontend, ctx)?;
let (ty, mut meta) = self.parse_type_non_void(frontend, ctx)?;
let name = self.expect_ident(frontend)?.0;
self.expect(frontend, TokenValue::Assign)?;
let (value, end_meta) = self.parse_initializer(frontend, ty, ctx)?;
meta.subsume(end_meta);
let decl = VarDeclaration {
qualifiers: &mut qualifiers,
ty,
name: Some(name),
init: None,
meta,
};
let pointer = frontend.add_local_var(ctx, decl)?;
ctx.emit_restart();
ctx.body.push(Statement::Store { pointer, value }, meta);
(value, end_meta)
} else {
let mut stmt = ctx.stmt_ctx();
let root = self.parse_expression(frontend, ctx, &mut stmt)?;
ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs)?
};
let condition = ctx.add_expression(
Expression::Unary {
op: UnaryOperator::LogicalNot,
expr,
},
expr_meta,
)?;
ctx.emit_restart();
ctx.body.push(
Statement::If {
condition,
accept: new_break(),
reject: Block::new(),
},
Span::default(),
);
self.expect(frontend, TokenValue::Semicolon)?;
}
Ok(())
})?;
let continuing = ctx.new_body(|ctx| {
match self.expect_peek(frontend)?.value {
TokenValue::RightParen => {}
_ => {
let mut stmt = ctx.stmt_ctx();
let rest = self.parse_expression(frontend, ctx, &mut stmt)?;
ctx.lower(stmt, frontend, rest, ExprPos::Rhs)?;
}
}
Ok(())
})?;
meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta);
let loop_body = ctx.with_body(loop_body, |ctx| {
if let Some(stmt_meta) = self.parse_statement(frontend, ctx, &mut None, true)? {
meta.subsume(stmt_meta);
}
Ok(())
})?;
ctx.body.push(
Statement::Loop {
body: loop_body,
continuing,
break_if: None,
},
meta,
);
ctx.symbol_table.pop_scope();
meta
}
TokenValue::LeftBrace => {
let mut meta = self.bump(frontend)?.meta;
let mut block_terminator = None;
let block = ctx.new_body(|ctx| {
let block_meta = self.parse_compound_statement(
meta,
frontend,
ctx,
&mut block_terminator,
is_inside_loop,
)?;
meta.subsume(block_meta);
Ok(())
})?;
ctx.body.push(Statement::Block(block), meta);
if block_terminator.is_some() {
terminator.get_or_insert(ctx.body.len());
}
meta
}
TokenValue::Semicolon => self.bump(frontend)?.meta,
_ => {
// Attempt to force expression parsing for remainder of the
// tokens. Unknown or invalid tokens will be caught there and
// turned into an error.
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(frontend, ctx, &mut stmt)?;
ctx.lower(stmt, frontend, expr, ExprPos::Rhs)?;
self.expect(frontend, TokenValue::Semicolon)?.meta
}
};
meta.subsume(meta_rest);
Ok(Some(meta))
}
pub fn parse_compound_statement(
&mut self,
mut meta: Span,
frontend: &mut Frontend,
ctx: &mut Context,
terminator: &mut Option<usize>,
is_inside_loop: bool,
) -> Result<Span> {
ctx.symbol_table.push_scope();
loop {
if let Some(Token {
meta: brace_meta, ..
}) = self.bump_if(frontend, TokenValue::RightBrace)
{
meta.subsume(brace_meta);
break;
}
let stmt = self.parse_statement(frontend, ctx, terminator, is_inside_loop)?;
if let Some(stmt_meta) = stmt {
meta.subsume(stmt_meta);
}
}
if let Some(idx) = *terminator {
ctx.body.cull(idx..)
}
ctx.symbol_table.pop_scope();
Ok(meta)
}
pub fn parse_function_args(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
) -> Result<()> {
if self.bump_if(frontend, TokenValue::Void).is_some() {
return Ok(());
}
loop {
if self.peek_type_name(frontend) || self.peek_parameter_qualifier(frontend) {
let qualifier = self.parse_parameter_qualifier(frontend);
let mut ty = self.parse_type_non_void(frontend, ctx)?.0;
match self.expect_peek(frontend)?.value {
TokenValue::Comma => {
self.bump(frontend)?;
ctx.add_function_arg(None, ty, qualifier)?;
continue;
}
TokenValue::Identifier(_) => {
let mut name = self.expect_ident(frontend)?;
self.parse_array_specifier(frontend, ctx, &mut name.1, &mut ty)?;
ctx.add_function_arg(Some(name), ty, qualifier)?;
if self.bump_if(frontend, TokenValue::Comma).is_some() {
continue;
}
break;
}
_ => break,
}
}
break;
}
Ok(())
}
}
+446
View File
@@ -0,0 +1,446 @@
use std::num::NonZeroU32;
use crate::{
front::glsl::{
ast::{QualifierKey, QualifierValue, StorageQualifier, StructLayout, TypeQualifiers},
context::Context,
error::ExpectedToken,
parser::ParsingContext,
token::{Token, TokenValue},
Error, ErrorKind, Frontend, Result,
},
AddressSpace, ArraySize, Handle, Span, Type, TypeInner,
};
impl ParsingContext<'_> {
/// Parses an optional array_specifier returning whether or not it's present
/// and modifying the type handle if it exists
pub fn parse_array_specifier(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
span: &mut Span,
ty: &mut Handle<Type>,
) -> Result<()> {
while self.parse_array_specifier_single(frontend, ctx, span, ty)? {}
Ok(())
}
/// Implementation of [`Self::parse_array_specifier`] for a single array_specifier
fn parse_array_specifier_single(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
span: &mut Span,
ty: &mut Handle<Type>,
) -> Result<bool> {
if self.bump_if(frontend, TokenValue::LeftBracket).is_some() {
let size = if let Some(Token { meta, .. }) =
self.bump_if(frontend, TokenValue::RightBracket)
{
span.subsume(meta);
ArraySize::Dynamic
} else {
let (value, constant_span) = self.parse_uint_constant(frontend, ctx)?;
let size = NonZeroU32::new(value).ok_or(Error {
kind: ErrorKind::SemanticError("Array size must be greater than zero".into()),
meta: constant_span,
})?;
let end_span = self.expect(frontend, TokenValue::RightBracket)?.meta;
span.subsume(end_span);
ArraySize::Constant(size)
};
frontend.layouter.update(ctx.module.to_ctx()).unwrap();
let stride = frontend.layouter[*ty].to_stride();
*ty = ctx.module.types.insert(
Type {
name: None,
inner: TypeInner::Array {
base: *ty,
size,
stride,
},
},
*span,
);
Ok(true)
} else {
Ok(false)
}
}
pub fn parse_type(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
) -> Result<(Option<Handle<Type>>, Span)> {
let token = self.bump(frontend)?;
let mut handle = match token.value {
TokenValue::Void => return Ok((None, token.meta)),
TokenValue::TypeName(ty) => ctx.module.types.insert(ty, token.meta),
TokenValue::Struct => {
let mut meta = token.meta;
let ty_name = self.expect_ident(frontend)?.0;
self.expect(frontend, TokenValue::LeftBrace)?;
let mut members = Vec::new();
let span = self.parse_struct_declaration_list(
frontend,
ctx,
&mut members,
StructLayout::Std140,
)?;
let end_meta = self.expect(frontend, TokenValue::RightBrace)?.meta;
meta.subsume(end_meta);
let ty = ctx.module.types.insert(
Type {
name: Some(ty_name.clone()),
inner: TypeInner::Struct { members, span },
},
meta,
);
frontend.lookup_type.insert(ty_name, ty);
ty
}
TokenValue::Identifier(ident) => match frontend.lookup_type.get(&ident) {
Some(ty) => *ty,
None => {
return Err(Error {
kind: ErrorKind::UnknownType(ident),
meta: token.meta,
})
}
},
_ => {
return Err(Error {
kind: ErrorKind::InvalidToken(
token.value,
vec![
TokenValue::Void.into(),
TokenValue::Struct.into(),
ExpectedToken::TypeName,
],
),
meta: token.meta,
});
}
};
let mut span = token.meta;
self.parse_array_specifier(frontend, ctx, &mut span, &mut handle)?;
Ok((Some(handle), span))
}
pub fn parse_type_non_void(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
) -> Result<(Handle<Type>, Span)> {
let (maybe_ty, meta) = self.parse_type(frontend, ctx)?;
let ty = maybe_ty.ok_or_else(|| Error {
kind: ErrorKind::SemanticError("Type can't be void".into()),
meta,
})?;
Ok((ty, meta))
}
pub fn peek_type_qualifier(&mut self, frontend: &mut Frontend) -> bool {
self.peek(frontend).is_some_and(|t| match t.value {
TokenValue::Invariant
| TokenValue::Interpolation(_)
| TokenValue::Sampling(_)
| TokenValue::PrecisionQualifier(_)
| TokenValue::Const
| TokenValue::In
| TokenValue::Out
| TokenValue::Uniform
| TokenValue::Shared
| TokenValue::Buffer
| TokenValue::Restrict
| TokenValue::MemoryQualifier(_)
| TokenValue::Layout => true,
_ => false,
})
}
pub fn parse_type_qualifiers<'a>(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
) -> Result<TypeQualifiers<'a>> {
let mut qualifiers = TypeQualifiers::default();
while self.peek_type_qualifier(frontend) {
let token = self.bump(frontend)?;
// Handle layout qualifiers outside the match since this can push multiple values
if token.value == TokenValue::Layout {
self.parse_layout_qualifier_id_list(frontend, ctx, &mut qualifiers)?;
continue;
}
qualifiers.span.subsume(token.meta);
match token.value {
TokenValue::Invariant => {
if qualifiers.invariant.is_some() {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Cannot use more than one invariant qualifier per declaration"
.into(),
),
meta: token.meta,
})
}
qualifiers.invariant = Some(token.meta);
}
TokenValue::Interpolation(i) => {
if qualifiers.interpolation.is_some() {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Cannot use more than one interpolation qualifier per declaration"
.into(),
),
meta: token.meta,
})
}
qualifiers.interpolation = Some((i, token.meta));
}
TokenValue::Const
| TokenValue::In
| TokenValue::Out
| TokenValue::Uniform
| TokenValue::Shared
| TokenValue::Buffer => {
let storage = match token.value {
TokenValue::Const => StorageQualifier::Const,
TokenValue::In => StorageQualifier::Input,
TokenValue::Out => StorageQualifier::Output,
TokenValue::Uniform => {
StorageQualifier::AddressSpace(AddressSpace::Uniform)
}
TokenValue::Shared => {
StorageQualifier::AddressSpace(AddressSpace::WorkGroup)
}
TokenValue::Buffer => {
StorageQualifier::AddressSpace(AddressSpace::Storage {
access: crate::StorageAccess::LOAD | crate::StorageAccess::STORE,
})
}
_ => unreachable!(),
};
if StorageQualifier::AddressSpace(AddressSpace::Function)
!= qualifiers.storage.0
{
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Cannot use more than one storage qualifier per declaration".into(),
),
meta: token.meta,
});
}
qualifiers.storage = (storage, token.meta);
}
TokenValue::Sampling(s) => {
if qualifiers.sampling.is_some() {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Cannot use more than one sampling qualifier per declaration"
.into(),
),
meta: token.meta,
})
}
qualifiers.sampling = Some((s, token.meta));
}
TokenValue::PrecisionQualifier(p) => {
if qualifiers.precision.is_some() {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"Cannot use more than one precision qualifier per declaration"
.into(),
),
meta: token.meta,
})
}
qualifiers.precision = Some((p, token.meta));
}
TokenValue::MemoryQualifier(access) => {
let load_store = crate::StorageAccess::LOAD | crate::StorageAccess::STORE;
let storage_access = qualifiers
.storage_access
.get_or_insert((load_store, Span::default()));
if !storage_access.0.contains(!access & load_store) {
frontend.errors.push(Error {
kind: ErrorKind::SemanticError(
"The same memory qualifier can only be used once".into(),
),
meta: token.meta,
})
}
storage_access.0 &= access;
storage_access.1.subsume(token.meta);
}
TokenValue::Restrict => continue,
_ => unreachable!(),
};
}
Ok(qualifiers)
}
pub fn parse_layout_qualifier_id_list(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
qualifiers: &mut TypeQualifiers,
) -> Result<()> {
self.expect(frontend, TokenValue::LeftParen)?;
loop {
self.parse_layout_qualifier_id(frontend, ctx, &mut qualifiers.layout_qualifiers)?;
if self.bump_if(frontend, TokenValue::Comma).is_some() {
continue;
}
break;
}
let token = self.expect(frontend, TokenValue::RightParen)?;
qualifiers.span.subsume(token.meta);
Ok(())
}
pub fn parse_layout_qualifier_id(
&mut self,
frontend: &mut Frontend,
ctx: &mut Context,
qualifiers: &mut crate::FastHashMap<QualifierKey, (QualifierValue, Span)>,
) -> Result<()> {
// layout_qualifier_id:
// IDENTIFIER
// IDENTIFIER EQUAL constant_expression
// SHARED
let mut token = self.bump(frontend)?;
match token.value {
TokenValue::Identifier(name) => {
let (key, value) = match name.as_str() {
"std140" => (
QualifierKey::Layout,
QualifierValue::Layout(StructLayout::Std140),
),
"std430" => (
QualifierKey::Layout,
QualifierValue::Layout(StructLayout::Std430),
),
word => {
if let Some(format) = map_image_format(word) {
(QualifierKey::Format, QualifierValue::Format(format))
} else {
let key = QualifierKey::String(name.into());
let value = if self.bump_if(frontend, TokenValue::Assign).is_some() {
let (value, end_meta) =
match self.parse_uint_constant(frontend, ctx) {
Ok(v) => v,
Err(e) => {
frontend.errors.push(e);
(0, Span::default())
}
};
token.meta.subsume(end_meta);
QualifierValue::Uint(value)
} else {
QualifierValue::None
};
(key, value)
}
}
};
qualifiers.insert(key, (value, token.meta));
}
_ => frontend.errors.push(Error {
kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]),
meta: token.meta,
}),
}
Ok(())
}
pub fn peek_type_name(&mut self, frontend: &mut Frontend) -> bool {
self.peek(frontend).is_some_and(|t| match t.value {
TokenValue::TypeName(_) | TokenValue::Void => true,
TokenValue::Struct => true,
TokenValue::Identifier(ref ident) => frontend.lookup_type.contains_key(ident),
_ => false,
})
}
}
fn map_image_format(word: &str) -> Option<crate::StorageFormat> {
use crate::StorageFormat as Sf;
let format = match word {
// float-image-format-qualifier:
"rgba32f" => Sf::Rgba32Float,
"rgba16f" => Sf::Rgba16Float,
"rg32f" => Sf::Rg32Float,
"rg16f" => Sf::Rg16Float,
"r11f_g11f_b10f" => Sf::Rg11b10Ufloat,
"r32f" => Sf::R32Float,
"r16f" => Sf::R16Float,
"rgba16" => Sf::Rgba16Unorm,
"rgb10_a2ui" => Sf::Rgb10a2Uint,
"rgb10_a2" => Sf::Rgb10a2Unorm,
"rgba8" => Sf::Rgba8Unorm,
"rg16" => Sf::Rg16Unorm,
"rg8" => Sf::Rg8Unorm,
"r16" => Sf::R16Unorm,
"r8" => Sf::R8Unorm,
"rgba16_snorm" => Sf::Rgba16Snorm,
"rgba8_snorm" => Sf::Rgba8Snorm,
"rg16_snorm" => Sf::Rg16Snorm,
"rg8_snorm" => Sf::Rg8Snorm,
"r16_snorm" => Sf::R16Snorm,
"r8_snorm" => Sf::R8Snorm,
// int-image-format-qualifier:
"rgba32i" => Sf::Rgba32Sint,
"rgba16i" => Sf::Rgba16Sint,
"rgba8i" => Sf::Rgba8Sint,
"rg32i" => Sf::Rg32Sint,
"rg16i" => Sf::Rg16Sint,
"rg8i" => Sf::Rg8Sint,
"r32i" => Sf::R32Sint,
"r16i" => Sf::R16Sint,
"r8i" => Sf::R8Sint,
// uint-image-format-qualifier:
"rgba32ui" => Sf::Rgba32Uint,
"rgba16ui" => Sf::Rgba16Uint,
"rgba8ui" => Sf::Rgba8Uint,
"r64ui" => Sf::R64Uint,
"rg32ui" => Sf::Rg32Uint,
"rg16ui" => Sf::Rg16Uint,
"rg8ui" => Sf::Rg8Uint,
"r32ui" => Sf::R32Uint,
"r16ui" => Sf::R16Uint,
"r8ui" => Sf::R8Uint,
// TODO: These next ones seem incorrect to me
// "rgb10_a2ui" => Sf::Rgb10a2Unorm,
_ => return None,
};
Some(format)
}
+856
View File
@@ -0,0 +1,856 @@
use super::{
ast::Profile,
error::ExpectedToken,
error::{Error, ErrorKind, ParseErrors},
token::TokenValue,
Frontend, Options, Span,
};
use crate::ShaderStage;
use pp_rs::token::PreprocessorError;
#[test]
fn version() {
let mut frontend = Frontend::default();
// invalid versions
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
"#version 99000\n void main(){}",
)
.err()
.unwrap(),
ParseErrors {
errors: vec![Error {
kind: ErrorKind::InvalidVersion(99000),
meta: Span::new(9, 14)
}],
},
);
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
"#version 449\n void main(){}",
)
.err()
.unwrap(),
ParseErrors {
errors: vec![Error {
kind: ErrorKind::InvalidVersion(449),
meta: Span::new(9, 12)
}]
},
);
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
"#version 450 smart\n void main(){}",
)
.err()
.unwrap(),
ParseErrors {
errors: vec![Error {
kind: ErrorKind::InvalidProfile("smart".into()),
meta: Span::new(13, 18),
}]
},
);
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
"#version 450\nvoid main(){} #version 450",
)
.err()
.unwrap(),
ParseErrors {
errors: vec![
Error {
kind: ErrorKind::PreprocessorError(PreprocessorError::UnexpectedHash,),
meta: Span::new(27, 28),
},
Error {
kind: ErrorKind::InvalidToken(
TokenValue::Identifier("version".into()),
vec![ExpectedToken::Eof]
),
meta: Span::new(28, 35)
}
]
},
);
// valid versions
frontend
.parse(
&Options::from(ShaderStage::Vertex),
" # version 450\nvoid main() {}",
)
.unwrap();
assert_eq!(
(frontend.metadata().version, frontend.metadata().profile),
(450, Profile::Core)
);
frontend
.parse(
&Options::from(ShaderStage::Vertex),
"#version 450\nvoid main() {}",
)
.unwrap();
assert_eq!(
(frontend.metadata().version, frontend.metadata().profile),
(450, Profile::Core)
);
frontend
.parse(
&Options::from(ShaderStage::Vertex),
"#version 450 core\nvoid main(void) {}",
)
.unwrap();
assert_eq!(
(frontend.metadata().version, frontend.metadata().profile),
(450, Profile::Core)
);
}
#[test]
fn control_flow() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
if (true) {
return 1;
} else {
return 2;
}
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
if (true) {
return 1;
}
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
int x;
int y = 3;
switch (5) {
case 2:
x = 2;
case 5:
x = 5;
y = 2;
break;
default:
x = 0;
}
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
int x = 0;
while(x < 5) {
x = x + 1;
}
do {
x = x - 1;
} while(x >= 4)
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
int x = 0;
for(int i = 0; i < 10;) {
x = x + 2;
}
for(;;);
return x;
}
"#,
)
.unwrap();
}
#[test]
fn declarations() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
layout(location = 0) in vec2 v_uv;
layout(location = 0) out vec4 o_color;
layout(set = 1, binding = 1) uniform texture2D tex;
layout(set = 1, binding = 2) uniform sampler tex_sampler;
layout(early_fragment_tests) in;
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
layout(std140, set = 2, binding = 0)
uniform u_locals {
vec3 model_offs;
float load_time;
ivec4 atlas_offs;
};
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
layout(push_constant)
uniform u_locals {
vec3 model_offs;
float load_time;
ivec4 atlas_offs;
};
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
layout(std430, set = 2, binding = 0)
uniform u_locals {
vec3 model_offs;
float load_time;
ivec4 atlas_offs;
};
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
layout(std140, set = 2, binding = 0)
uniform u_locals {
vec3 model_offs;
float load_time;
} block_var;
void main() {
load_time * model_offs;
block_var.load_time * block_var.model_offs;
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
float vector = vec4(1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0);
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
precision highp float;
void main() {}
"#,
)
.unwrap();
}
#[test]
fn textures() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
#version 450
layout(location = 0) in vec2 v_uv;
layout(location = 0) out vec4 o_color;
layout(set = 1, binding = 1) uniform texture2D tex;
layout(set = 1, binding = 2) uniform sampler tex_sampler;
void main() {
o_color = texture(sampler2D(tex, tex_sampler), v_uv);
o_color.a = texture(sampler2D(tex, tex_sampler), v_uv, 2.0).a;
}
"#,
)
.unwrap();
}
#[test]
fn functions() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void test1(float);
void test1(float) {}
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void test2(float a) {}
void test3(float a, float b) {}
void test4(float, float) {}
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
float test(float a) { return a; }
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
float test(vec4 p) {
return p.x;
}
void main() {}
"#,
)
.unwrap();
// Function overloading
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
float test(vec2 p);
float test(vec3 p);
float test(vec4 p);
float test(vec2 p) {
return p.x;
}
float test(vec3 p) {
return p.x;
}
float test(vec4 p) {
return p.x;
}
void main() {}
"#,
)
.unwrap();
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
int test(vec4 p) {
return p.x;
}
float test(vec4 p) {
return p.x;
}
void main() {}
"#,
)
.err()
.unwrap(),
ParseErrors {
errors: vec![Error {
kind: ErrorKind::SemanticError("Function already defined".into()),
meta: Span::new(134, 152),
}]
},
);
println!();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
float callee(uint q) {
return float(q);
}
float caller() {
callee(1u);
}
void main() {}
"#,
)
.unwrap();
// Nested function call
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
layout(set = 0, binding = 1) uniform texture2D t_noise;
layout(set = 0, binding = 2) uniform sampler s_noise;
void main() {
textureLod(sampler2D(t_noise, s_noise), vec2(1.0), 0);
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void fun(vec2 in_parameter, out float out_parameter) {
ivec2 _ = ivec2(in_parameter);
}
void main() {
float a;
fun(vec2(1.0), a);
}
"#,
)
.unwrap();
}
#[test]
fn constants() {
use crate::{Constant, Expression, Type, TypeInner};
let mut frontend = Frontend::default();
let module = frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
const float a = 1.0;
float global = a;
const float b = a;
void main() {}
"#,
)
.unwrap();
let mut types = module.types.iter();
let mut constants = module.constants.iter();
let mut global_expressions = module.global_expressions.iter();
let (ty_handle, ty) = types.next().unwrap();
assert_eq!(
ty,
&Type {
name: None,
inner: TypeInner::Scalar(crate::Scalar::F32)
}
);
let (init_handle, init) = global_expressions.next().unwrap();
assert_eq!(init, &Expression::Literal(crate::Literal::F32(1.0)));
assert_eq!(
constants.next().unwrap().1,
&Constant {
name: Some("a".to_owned()),
ty: ty_handle,
init: init_handle
}
);
assert_eq!(
constants.next().unwrap().1,
&Constant {
name: Some("b".to_owned()),
ty: ty_handle,
init: init_handle
}
);
assert!(constants.next().is_none());
}
#[test]
fn function_overloading() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
float saturate(float v) { return clamp(v, 0.0, 1.0); }
vec2 saturate(vec2 v) { return clamp(v, vec2(0.0), vec2(1.0)); }
vec3 saturate(vec3 v) { return clamp(v, vec3(0.0), vec3(1.0)); }
vec4 saturate(vec4 v) { return clamp(v, vec4(0.0), vec4(1.0)); }
void main() {
float v1 = saturate(1.5);
vec2 v2 = saturate(vec2(0.5, 1.5));
vec3 v3 = saturate(vec3(0.5, 1.5, 2.5));
vec3 v4 = saturate(vec4(0.5, 1.5, 2.5, 3.5));
}
"#,
)
.unwrap();
}
#[test]
fn implicit_conversions() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
mat4 a = mat4(1);
float b = 1u;
float c = 1 + 2.0;
}
"#,
)
.unwrap();
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void test(int a) {}
void test(uint a) {}
void main() {
test(1.0);
}
"#,
)
.err()
.unwrap(),
ParseErrors {
errors: vec![Error {
kind: ErrorKind::SemanticError("Unknown function \'test\'".into()),
meta: Span::new(156, 165),
}]
},
);
assert_eq!(
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void test(float a) {}
void test(uint a) {}
void main() {
test(1);
}
"#,
)
.err()
.unwrap(),
ParseErrors {
errors: vec![Error {
kind: ErrorKind::SemanticError("Ambiguous best function for \'test\'".into()),
meta: Span::new(158, 165),
}]
}
);
}
#[test]
fn structs() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
Test {
vec4 pos;
} xx;
void main() {}
"#,
)
.unwrap_err();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
struct Test {
vec4 pos;
};
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
const int NUM_VECS = 42;
struct Test {
vec4 vecs[NUM_VECS];
};
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
struct Hello {
vec4 test;
} test() {
return Hello( vec4(1.0) );
}
void main() {}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
struct Test {};
void main() {}
"#,
)
.unwrap_err();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
inout struct Test {
vec4 x;
};
void main() {}
"#,
)
.unwrap_err();
}
#[test]
fn swizzles() {
let mut frontend = Frontend::default();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
vec4 v = vec4(1);
v.xyz = vec3(2);
v.x = 5.0;
v.xyz.zxy.yx.xy = vec2(5.0, 1.0);
}
"#,
)
.unwrap();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
vec4 v = vec4(1);
v.xx = vec2(5.0);
}
"#,
)
.unwrap_err();
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
vec3 v = vec3(1);
v.w = 2.0;
}
"#,
)
.unwrap_err();
}
#[test]
fn expressions() {
let mut frontend = Frontend::default();
// Vector indexing
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
float test(int index) {
vec4 v = vec4(1.0, 2.0, 3.0, 4.0);
return v[index] + 1.0;
}
void main() {}
"#,
)
.unwrap();
// Prefix increment/decrement
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
uint index = 0;
--index;
++index;
}
"#,
)
.unwrap();
// Dynamic indexing of array
frontend
.parse(
&Options::from(ShaderStage::Vertex),
r#"
# version 450
void main() {
const vec4 positions[1] = { vec4(0) };
gl_Position = positions[gl_VertexIndex];
}
"#,
)
.unwrap();
}
+137
View File
@@ -0,0 +1,137 @@
pub use pp_rs::token::{Float, Integer, Location, Token as PPToken};
use super::ast::Precision;
use crate::{Interpolation, Sampling, Span, Type};
impl From<Location> for Span {
fn from(loc: Location) -> Self {
Span::new(loc.start, loc.end)
}
}
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Token {
pub value: TokenValue,
pub meta: Span,
}
/// A token passed from the lexing used in the parsing.
///
/// This type is exported since it's returned in the
/// [`InvalidToken`](super::ErrorKind::InvalidToken) error.
#[derive(Clone, Debug, PartialEq)]
pub enum TokenValue {
Identifier(String),
FloatConstant(Float),
IntConstant(Integer),
BoolConstant(bool),
Layout,
In,
Out,
InOut,
Uniform,
Buffer,
Const,
Shared,
Restrict,
/// A `glsl` memory qualifier such as `writeonly`
///
/// The associated [`crate::StorageAccess`] is the access being allowed
/// (for example `writeonly` has an associated value of [`crate::StorageAccess::STORE`])
MemoryQualifier(crate::StorageAccess),
Invariant,
Interpolation(Interpolation),
Sampling(Sampling),
Precision,
PrecisionQualifier(Precision),
Continue,
Break,
Return,
Discard,
If,
Else,
Switch,
Case,
Default,
While,
Do,
For,
Void,
Struct,
TypeName(Type),
Assign,
AddAssign,
SubAssign,
MulAssign,
DivAssign,
ModAssign,
LeftShiftAssign,
RightShiftAssign,
AndAssign,
XorAssign,
OrAssign,
Increment,
Decrement,
LogicalOr,
LogicalAnd,
LogicalXor,
LessEqual,
GreaterEqual,
Equal,
NotEqual,
LeftShift,
RightShift,
LeftBrace,
RightBrace,
LeftParen,
RightParen,
LeftBracket,
RightBracket,
LeftAngle,
RightAngle,
Comma,
Semicolon,
Colon,
Dot,
Bang,
Dash,
Tilde,
Plus,
Star,
Slash,
Percent,
VerticalBar,
Caret,
Ampersand,
Question,
}
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Directive {
pub kind: DirectiveKind,
pub tokens: Vec<PPToken>,
}
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum DirectiveKind {
Version { is_first_directive: bool },
Extension,
Pragma,
}
+365
View File
@@ -0,0 +1,365 @@
use super::{context::Context, Error, ErrorKind, Result, Span};
use crate::{
proc::ResolveContext, Expression, Handle, ImageClass, ImageDimension, Scalar, ScalarKind, Type,
TypeInner, VectorSize,
};
pub fn parse_type(type_name: &str) -> Option<Type> {
match type_name {
"bool" => Some(Type {
name: None,
inner: TypeInner::Scalar(Scalar::BOOL),
}),
"float" => Some(Type {
name: None,
inner: TypeInner::Scalar(Scalar::F32),
}),
"double" => Some(Type {
name: None,
inner: TypeInner::Scalar(Scalar::F64),
}),
"int" => Some(Type {
name: None,
inner: TypeInner::Scalar(Scalar::I32),
}),
"uint" => Some(Type {
name: None,
inner: TypeInner::Scalar(Scalar::U32),
}),
"sampler" | "samplerShadow" => Some(Type {
name: None,
inner: TypeInner::Sampler {
comparison: type_name == "samplerShadow",
},
}),
word => {
fn kind_width_parse(ty: &str) -> Option<Scalar> {
Some(match ty {
"" => Scalar::F32,
"b" => Scalar::BOOL,
"i" => Scalar::I32,
"u" => Scalar::U32,
"d" => Scalar::F64,
_ => return None,
})
}
fn size_parse(n: &str) -> Option<VectorSize> {
Some(match n {
"2" => VectorSize::Bi,
"3" => VectorSize::Tri,
"4" => VectorSize::Quad,
_ => return None,
})
}
let vec_parse = |word: &str| {
let mut iter = word.split("vec");
let kind = iter.next()?;
let size = iter.next()?;
let scalar = kind_width_parse(kind)?;
let size = size_parse(size)?;
Some(Type {
name: None,
inner: TypeInner::Vector { size, scalar },
})
};
let mat_parse = |word: &str| {
let mut iter = word.split("mat");
let kind = iter.next()?;
let size = iter.next()?;
let scalar = kind_width_parse(kind)?;
let (columns, rows) = if let Some(size) = size_parse(size) {
(size, size)
} else {
let mut iter = size.split('x');
match (iter.next()?, iter.next()?, iter.next()) {
(col, row, None) => (size_parse(col)?, size_parse(row)?),
_ => return None,
}
};
Some(Type {
name: None,
inner: TypeInner::Matrix {
columns,
rows,
scalar,
},
})
};
let texture_parse = |word: &str| {
let mut iter = word.split("texture");
let texture_kind = |ty| {
Some(match ty {
"" => ScalarKind::Float,
"i" => ScalarKind::Sint,
"u" => ScalarKind::Uint,
_ => return None,
})
};
let kind = iter.next()?;
let size = iter.next()?;
let kind = texture_kind(kind)?;
let sampled = |multi| ImageClass::Sampled { kind, multi };
let (dim, arrayed, class) = match size {
"1D" => (ImageDimension::D1, false, sampled(false)),
"1DArray" => (ImageDimension::D1, true, sampled(false)),
"2D" => (ImageDimension::D2, false, sampled(false)),
"2DArray" => (ImageDimension::D2, true, sampled(false)),
"2DMS" => (ImageDimension::D2, false, sampled(true)),
"2DMSArray" => (ImageDimension::D2, true, sampled(true)),
"3D" => (ImageDimension::D3, false, sampled(false)),
"Cube" => (ImageDimension::Cube, false, sampled(false)),
"CubeArray" => (ImageDimension::Cube, true, sampled(false)),
_ => return None,
};
Some(Type {
name: None,
inner: TypeInner::Image {
dim,
arrayed,
class,
},
})
};
let image_parse = |word: &str| {
let mut iter = word.split("image");
let texture_kind = |ty| {
Some(match ty {
"" => ScalarKind::Float,
"i" => ScalarKind::Sint,
"u" => ScalarKind::Uint,
_ => return None,
})
};
let kind = iter.next()?;
let size = iter.next()?;
// TODO: Check that the texture format and the kind match
let _ = texture_kind(kind)?;
let class = ImageClass::Storage {
format: crate::StorageFormat::R8Uint,
access: crate::StorageAccess::LOAD | crate::StorageAccess::STORE,
};
// TODO: glsl support multisampled storage images, naga doesn't
let (dim, arrayed) = match size {
"1D" => (ImageDimension::D1, false),
"1DArray" => (ImageDimension::D1, true),
"2D" => (ImageDimension::D2, false),
"2DArray" => (ImageDimension::D2, true),
"3D" => (ImageDimension::D3, false),
// Naga doesn't support cube images and it's usefulness
// is questionable, so they won't be supported for now
// "Cube" => (ImageDimension::Cube, false),
// "CubeArray" => (ImageDimension::Cube, true),
_ => return None,
};
Some(Type {
name: None,
inner: TypeInner::Image {
dim,
arrayed,
class,
},
})
};
vec_parse(word)
.or_else(|| mat_parse(word))
.or_else(|| texture_parse(word))
.or_else(|| image_parse(word))
}
}
}
pub const fn scalar_components(ty: &TypeInner) -> Option<Scalar> {
match *ty {
TypeInner::Scalar(scalar)
| TypeInner::Vector { scalar, .. }
| TypeInner::ValuePointer { scalar, .. }
| TypeInner::Matrix { scalar, .. } => Some(scalar),
_ => None,
}
}
pub const fn type_power(scalar: Scalar) -> Option<u32> {
Some(match scalar.kind {
ScalarKind::Sint => 0,
ScalarKind::Uint => 1,
ScalarKind::Float if scalar.width == 4 => 2,
ScalarKind::Float => 3,
ScalarKind::Bool | ScalarKind::AbstractInt | ScalarKind::AbstractFloat => return None,
})
}
impl Context<'_> {
/// Resolves the types of the expressions until `expr` (inclusive)
///
/// This needs to be done before the [`typifier`] can be queried for
/// the types of the expressions in the range between the last grow and `expr`.
///
/// # Note
///
/// The `resolve_type*` methods (like [`resolve_type`]) automatically
/// grow the [`typifier`] so calling this method is not necessary when using
/// them.
///
/// [`typifier`]: Context::typifier
/// [`resolve_type`]: Self::resolve_type
pub(crate) fn typifier_grow(&mut self, expr: Handle<Expression>, meta: Span) -> Result<()> {
let resolve_ctx = ResolveContext::with_locals(self.module, &self.locals, &self.arguments);
let typifier = if self.is_const {
&mut self.const_typifier
} else {
&mut self.typifier
};
let expressions = if self.is_const {
&self.module.global_expressions
} else {
&self.expressions
};
typifier
.grow(expr, expressions, &resolve_ctx)
.map_err(|error| Error {
kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()),
meta,
})
}
pub(crate) fn get_type(&self, expr: Handle<Expression>) -> &TypeInner {
let typifier = if self.is_const {
&self.const_typifier
} else {
&self.typifier
};
typifier.get(expr, &self.module.types)
}
/// Gets the type for the result of the `expr` expression
///
/// Automatically grows the [`typifier`] to `expr` so calling
/// [`typifier_grow`] is not necessary
///
/// [`typifier`]: Context::typifier
/// [`typifier_grow`]: Self::typifier_grow
pub(crate) fn resolve_type(
&mut self,
expr: Handle<Expression>,
meta: Span,
) -> Result<&TypeInner> {
self.typifier_grow(expr, meta)?;
Ok(self.get_type(expr))
}
/// Gets the type handle for the result of the `expr` expression
///
/// Automatically grows the [`typifier`] to `expr` so calling
/// [`typifier_grow`] is not necessary
///
/// # Note
///
/// Consider using [`resolve_type`] whenever possible
/// since it doesn't require adding each type to the [`types`] arena
/// and it doesn't need to mutably borrow the [`Parser`][Self]
///
/// [`types`]: crate::Module::types
/// [`typifier`]: Context::typifier
/// [`typifier_grow`]: Self::typifier_grow
/// [`resolve_type`]: Self::resolve_type
pub(crate) fn resolve_type_handle(
&mut self,
expr: Handle<Expression>,
meta: Span,
) -> Result<Handle<Type>> {
self.typifier_grow(expr, meta)?;
let typifier = if self.is_const {
&mut self.const_typifier
} else {
&mut self.typifier
};
Ok(typifier.register_type(expr, &mut self.module.types))
}
/// Invalidates the cached type resolution for `expr` forcing a recomputation
pub(crate) fn invalidate_expression(
&mut self,
expr: Handle<Expression>,
meta: Span,
) -> Result<()> {
let resolve_ctx = ResolveContext::with_locals(self.module, &self.locals, &self.arguments);
let typifier = if self.is_const {
&mut self.const_typifier
} else {
&mut self.typifier
};
typifier
.invalidate(expr, &self.expressions, &resolve_ctx)
.map_err(|error| Error {
kind: ErrorKind::SemanticError(format!("Can't resolve type: {error:?}").into()),
meta,
})
}
pub(crate) fn lift_up_const_expression(
&mut self,
expr: Handle<Expression>,
) -> Result<Handle<Expression>> {
let meta = self.expressions.get_span(expr);
let h = match self.expressions[expr] {
ref expr @ (Expression::Literal(_)
| Expression::Constant(_)
| Expression::ZeroValue(_)) => {
self.module.global_expressions.append(expr.clone(), meta)
}
Expression::Compose { ty, ref components } => {
let mut components = components.clone();
for component in &mut components {
*component = self.lift_up_const_expression(*component)?;
}
self.module
.global_expressions
.append(Expression::Compose { ty, components }, meta)
}
Expression::Splat { size, value } => {
let value = self.lift_up_const_expression(value)?;
self.module
.global_expressions
.append(Expression::Splat { size, value }, meta)
}
_ => {
return Err(Error {
kind: ErrorKind::SemanticError("Expression is not const-expression".into()),
meta,
})
}
};
self.global_expression_kind_tracker
.insert(h, crate::proc::ExpressionKind::Const);
Ok(h)
}
}
+649
View File
@@ -0,0 +1,649 @@
use super::{
ast::*,
context::{Context, ExprPos},
error::{Error, ErrorKind},
Frontend, Result, Span,
};
use crate::{
AddressSpace, Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, Interpolation,
LocalVariable, ResourceBinding, Scalar, ScalarKind, ShaderStage, SwizzleComponent, Type,
TypeInner, VectorSize,
};
pub struct VarDeclaration<'a, 'key> {
pub qualifiers: &'a mut TypeQualifiers<'key>,
pub ty: Handle<Type>,
pub name: Option<String>,
pub init: Option<Handle<Expression>>,
pub meta: Span,
}
/// Information about a builtin used in [`add_builtin`](Frontend::add_builtin).
struct BuiltInData {
/// The type of the builtin.
inner: TypeInner,
/// The associated builtin class.
builtin: BuiltIn,
/// Whether the builtin can be written to or not.
mutable: bool,
/// The storage used for the builtin.
storage: StorageQualifier,
}
pub enum GlobalOrConstant {
Global(Handle<GlobalVariable>),
Constant(Handle<Constant>),
}
impl Frontend {
/// Adds a builtin and returns a variable reference to it
fn add_builtin(
&mut self,
ctx: &mut Context,
name: &str,
data: BuiltInData,
meta: Span,
) -> Result<Option<VariableReference>> {
let ty = ctx.module.types.insert(
Type {
name: None,
inner: data.inner,
},
meta,
);
let handle = ctx.module.global_variables.append(
GlobalVariable {
name: Some(name.into()),
space: AddressSpace::Private,
binding: None,
ty,
init: None,
},
meta,
);
let idx = self.entry_args.len();
self.entry_args.push(EntryArg {
name: Some(name.into()),
binding: Binding::BuiltIn(data.builtin),
handle,
storage: data.storage,
});
self.global_variables.push((
name.into(),
GlobalLookup {
kind: GlobalLookupKind::Variable(handle),
entry_arg: Some(idx),
mutable: data.mutable,
},
));
let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta)?;
let var = VariableReference {
expr,
load: true,
mutable: data.mutable,
constant: None,
entry_arg: Some(idx),
};
ctx.symbol_table.add_root(name.into(), var.clone());
Ok(Some(var))
}
pub(crate) fn lookup_variable(
&mut self,
ctx: &mut Context,
name: &str,
meta: Span,
) -> Result<Option<VariableReference>> {
if let Some(var) = ctx.symbol_table.lookup(name).cloned() {
return Ok(Some(var));
}
let data = match name {
"gl_Position" => BuiltInData {
inner: TypeInner::Vector {
size: VectorSize::Quad,
scalar: Scalar::F32,
},
builtin: BuiltIn::Position { invariant: false },
mutable: true,
storage: StorageQualifier::Output,
},
"gl_FragCoord" => BuiltInData {
inner: TypeInner::Vector {
size: VectorSize::Quad,
scalar: Scalar::F32,
},
builtin: BuiltIn::Position { invariant: false },
mutable: false,
storage: StorageQualifier::Input,
},
"gl_PointCoord" => BuiltInData {
inner: TypeInner::Vector {
size: VectorSize::Bi,
scalar: Scalar::F32,
},
builtin: BuiltIn::PointCoord,
mutable: false,
storage: StorageQualifier::Input,
},
"gl_GlobalInvocationID"
| "gl_NumWorkGroups"
| "gl_WorkGroupSize"
| "gl_WorkGroupID"
| "gl_LocalInvocationID" => BuiltInData {
inner: TypeInner::Vector {
size: VectorSize::Tri,
scalar: Scalar::U32,
},
builtin: match name {
"gl_GlobalInvocationID" => BuiltIn::GlobalInvocationId,
"gl_NumWorkGroups" => BuiltIn::NumWorkGroups,
"gl_WorkGroupSize" => BuiltIn::WorkGroupSize,
"gl_WorkGroupID" => BuiltIn::WorkGroupId,
"gl_LocalInvocationID" => BuiltIn::LocalInvocationId,
_ => unreachable!(),
},
mutable: false,
storage: StorageQualifier::Input,
},
"gl_FrontFacing" => BuiltInData {
inner: TypeInner::Scalar(Scalar::BOOL),
builtin: BuiltIn::FrontFacing,
mutable: false,
storage: StorageQualifier::Input,
},
"gl_PointSize" | "gl_FragDepth" => BuiltInData {
inner: TypeInner::Scalar(Scalar::F32),
builtin: match name {
"gl_PointSize" => BuiltIn::PointSize,
"gl_FragDepth" => BuiltIn::FragDepth,
_ => unreachable!(),
},
mutable: true,
storage: StorageQualifier::Output,
},
"gl_ClipDistance" | "gl_CullDistance" => {
let base = ctx.module.types.insert(
Type {
name: None,
inner: TypeInner::Scalar(Scalar::F32),
},
meta,
);
BuiltInData {
inner: TypeInner::Array {
base,
size: crate::ArraySize::Dynamic,
stride: 4,
},
builtin: match name {
"gl_ClipDistance" => BuiltIn::ClipDistance,
"gl_CullDistance" => BuiltIn::CullDistance,
_ => unreachable!(),
},
mutable: self.meta.stage == ShaderStage::Vertex,
storage: StorageQualifier::Output,
}
}
_ => {
let builtin = match name {
"gl_BaseVertex" => BuiltIn::BaseVertex,
"gl_BaseInstance" => BuiltIn::BaseInstance,
"gl_PrimitiveID" => BuiltIn::PrimitiveIndex,
"gl_InstanceIndex" => BuiltIn::InstanceIndex,
"gl_VertexIndex" => BuiltIn::VertexIndex,
"gl_SampleID" => BuiltIn::SampleIndex,
"gl_LocalInvocationIndex" => BuiltIn::LocalInvocationIndex,
"gl_DrawID" => BuiltIn::DrawID,
_ => return Ok(None),
};
BuiltInData {
inner: TypeInner::Scalar(Scalar::U32),
builtin,
mutable: false,
storage: StorageQualifier::Input,
}
}
};
self.add_builtin(ctx, name, data, meta)
}
pub(crate) fn make_variable_invariant(
&mut self,
ctx: &mut Context,
name: &str,
meta: Span,
) -> Result<()> {
if let Some(var) = self.lookup_variable(ctx, name, meta)? {
if let Some(index) = var.entry_arg {
if let Binding::BuiltIn(BuiltIn::Position { ref mut invariant }) =
self.entry_args[index].binding
{
*invariant = true;
}
}
}
Ok(())
}
pub(crate) fn field_selection(
&mut self,
ctx: &mut Context,
pos: ExprPos,
expression: Handle<Expression>,
name: &str,
meta: Span,
) -> Result<Handle<Expression>> {
let (ty, is_pointer) = match *ctx.resolve_type(expression, meta)? {
TypeInner::Pointer { base, .. } => (&ctx.module.types[base].inner, true),
ref ty => (ty, false),
};
match *ty {
TypeInner::Struct { ref members, .. } => {
let index = members
.iter()
.position(|m| m.name == Some(name.into()))
.ok_or_else(|| Error {
kind: ErrorKind::UnknownField(name.into()),
meta,
})?;
let pointer = ctx.add_expression(
Expression::AccessIndex {
base: expression,
index: index as u32,
},
meta,
)?;
Ok(match pos {
ExprPos::Rhs if is_pointer => {
ctx.add_expression(Expression::Load { pointer }, meta)?
}
_ => pointer,
})
}
// swizzles (xyzw, rgba, stpq)
TypeInner::Vector { size, .. } => {
let check_swizzle_components = |comps: &str| {
name.chars()
.map(|c| {
comps
.find(c)
.filter(|i| *i < size as usize)
.map(|i| SwizzleComponent::from_index(i as u32))
})
.collect::<Option<Vec<SwizzleComponent>>>()
};
let components = check_swizzle_components("xyzw")
.or_else(|| check_swizzle_components("rgba"))
.or_else(|| check_swizzle_components("stpq"));
if let Some(components) = components {
if let ExprPos::Lhs = pos {
let not_unique = (1..components.len())
.any(|i| components[i..].contains(&components[i - 1]));
if not_unique {
self.errors.push(Error {
kind: ErrorKind::SemanticError(
format!(
concat!(
"swizzle cannot have duplicate components in ",
"left-hand-side expression for \"{:?}\""
),
name
)
.into(),
),
meta,
})
}
}
let mut pattern = [SwizzleComponent::X; 4];
for (pat, component) in pattern.iter_mut().zip(&components) {
*pat = *component;
}
// flatten nested swizzles (vec.zyx.xy.x => vec.z)
let mut expression = expression;
if let Expression::Swizzle {
size: _,
vector,
pattern: ref src_pattern,
} = ctx[expression]
{
expression = vector;
for pat in &mut pattern {
*pat = src_pattern[pat.index() as usize];
}
}
let size = match components.len() {
// Swizzles with just one component are accesses and not swizzles
1 => {
match pos {
// If the position is in the right hand side and the base
// vector is a pointer, load it, otherwise the swizzle would
// produce a pointer
ExprPos::Rhs if is_pointer => {
expression = ctx.add_expression(
Expression::Load {
pointer: expression,
},
meta,
)?;
}
_ => {}
};
return ctx.add_expression(
Expression::AccessIndex {
base: expression,
index: pattern[0].index(),
},
meta,
);
}
2 => VectorSize::Bi,
3 => VectorSize::Tri,
4 => VectorSize::Quad,
_ => {
self.errors.push(Error {
kind: ErrorKind::SemanticError(
format!("Bad swizzle size for \"{name:?}\"").into(),
),
meta,
});
VectorSize::Quad
}
};
if is_pointer {
// NOTE: for lhs expression, this extra load ends up as an unused expr, because the
// assignment will extract the pointer and use it directly anyway. Unfortunately we
// need it for validation to pass, as swizzles cannot operate on pointer values.
expression = ctx.add_expression(
Expression::Load {
pointer: expression,
},
meta,
)?;
}
Ok(ctx.add_expression(
Expression::Swizzle {
size,
vector: expression,
pattern,
},
meta,
)?)
} else {
Err(Error {
kind: ErrorKind::SemanticError(
format!("Invalid swizzle for vector \"{name}\"").into(),
),
meta,
})
}
}
_ => Err(Error {
kind: ErrorKind::SemanticError(
format!("Can't lookup field on this type \"{name}\"").into(),
),
meta,
}),
}
}
pub(crate) fn add_global_var(
&mut self,
ctx: &mut Context,
VarDeclaration {
qualifiers,
mut ty,
name,
init,
meta,
}: VarDeclaration,
) -> Result<GlobalOrConstant> {
let storage = qualifiers.storage.0;
let (ret, lookup) = match storage {
StorageQualifier::Input | StorageQualifier::Output => {
let input = storage == StorageQualifier::Input;
// TODO: glslang seems to use a counter for variables without
// explicit location (even if that causes collisions)
let location = qualifiers
.uint_layout_qualifier("location", &mut self.errors)
.unwrap_or(0);
let interpolation = qualifiers.interpolation.take().map(|(i, _)| i).or_else(|| {
let kind = ctx.module.types[ty].inner.scalar_kind()?;
Some(match kind {
ScalarKind::Float => Interpolation::Perspective,
_ => Interpolation::Flat,
})
});
let sampling = qualifiers.sampling.take().map(|(s, _)| s);
let handle = ctx.module.global_variables.append(
GlobalVariable {
name: name.clone(),
space: AddressSpace::Private,
binding: None,
ty,
init,
},
meta,
);
let idx = self.entry_args.len();
self.entry_args.push(EntryArg {
name: name.clone(),
binding: Binding::Location {
location,
interpolation,
sampling,
second_blend_source: false,
},
handle,
storage,
});
let lookup = GlobalLookup {
kind: GlobalLookupKind::Variable(handle),
entry_arg: Some(idx),
mutable: !input,
};
(GlobalOrConstant::Global(handle), lookup)
}
StorageQualifier::Const => {
let init = init.ok_or_else(|| Error {
kind: ErrorKind::SemanticError("const values must have an initializer".into()),
meta,
})?;
let constant = Constant {
name: name.clone(),
ty,
init,
};
let handle = ctx.module.constants.append(constant, meta);
let lookup = GlobalLookup {
kind: GlobalLookupKind::Constant(handle, ty),
entry_arg: None,
mutable: false,
};
(GlobalOrConstant::Constant(handle), lookup)
}
StorageQualifier::AddressSpace(mut space) => {
match space {
AddressSpace::Storage { ref mut access } => {
if let Some((allowed_access, _)) = qualifiers.storage_access.take() {
*access = allowed_access;
}
}
AddressSpace::Uniform => match ctx.module.types[ty].inner {
TypeInner::Image {
class,
dim,
arrayed,
} => {
if let crate::ImageClass::Storage {
mut access,
mut format,
} = class
{
if let Some((allowed_access, _)) = qualifiers.storage_access.take()
{
access = allowed_access;
}
match qualifiers.layout_qualifiers.remove(&QualifierKey::Format) {
Some((QualifierValue::Format(f), _)) => format = f,
// TODO: glsl supports images without format qualifier
// if they are `writeonly`
None => self.errors.push(Error {
kind: ErrorKind::SemanticError(
"image types require a format layout qualifier".into(),
),
meta,
}),
_ => unreachable!(),
}
ty = ctx.module.types.insert(
Type {
name: None,
inner: TypeInner::Image {
dim,
arrayed,
class: crate::ImageClass::Storage { format, access },
},
},
meta,
);
}
space = AddressSpace::Handle
}
TypeInner::Sampler { .. } => space = AddressSpace::Handle,
_ => {
if qualifiers.none_layout_qualifier("push_constant", &mut self.errors) {
space = AddressSpace::PushConstant
}
}
},
AddressSpace::Function => space = AddressSpace::Private,
_ => {}
};
let binding = match space {
AddressSpace::Uniform | AddressSpace::Storage { .. } | AddressSpace::Handle => {
let binding = qualifiers.uint_layout_qualifier("binding", &mut self.errors);
if binding.is_none() {
self.errors.push(Error {
kind: ErrorKind::SemanticError(
"uniform/buffer blocks require layout(binding=X)".into(),
),
meta,
});
}
let set = qualifiers.uint_layout_qualifier("set", &mut self.errors);
binding.map(|binding| ResourceBinding {
group: set.unwrap_or(0),
binding,
})
}
_ => None,
};
let handle = ctx.module.global_variables.append(
GlobalVariable {
name: name.clone(),
space,
binding,
ty,
init,
},
meta,
);
let lookup = GlobalLookup {
kind: GlobalLookupKind::Variable(handle),
entry_arg: None,
mutable: true,
};
(GlobalOrConstant::Global(handle), lookup)
}
};
if let Some(name) = name {
ctx.add_global(&name, lookup)?;
self.global_variables.push((name, lookup));
}
qualifiers.unused_errors(&mut self.errors);
Ok(ret)
}
pub(crate) fn add_local_var(
&mut self,
ctx: &mut Context,
decl: VarDeclaration,
) -> Result<Handle<Expression>> {
let storage = decl.qualifiers.storage;
let mutable = match storage.0 {
StorageQualifier::AddressSpace(AddressSpace::Function) => true,
StorageQualifier::Const => false,
_ => {
self.errors.push(Error {
kind: ErrorKind::SemanticError("Locals cannot have a storage qualifier".into()),
meta: storage.1,
});
true
}
};
let handle = ctx.locals.append(
LocalVariable {
name: decl.name.clone(),
ty: decl.ty,
init: decl.init,
},
decl.meta,
);
let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta)?;
if let Some(name) = decl.name {
let maybe_var = ctx.add_local_var(name.clone(), expr, mutable);
if maybe_var.is_some() {
self.errors.push(Error {
kind: ErrorKind::VariableAlreadyDeclared(name),
meta: decl.meta,
})
}
}
decl.qualifiers.unused_errors(&mut self.errors);
Ok(expr)
}
}
+62
View File
@@ -0,0 +1,62 @@
/*!
Interpolation defaults.
*/
impl crate::Binding {
/// Apply the usual default interpolation for `ty` to `binding`.
///
/// This function is a utility front ends may use to satisfy the Naga IR's
/// requirement, meant to ensure that input languages' policies have been
/// applied appropriately, that all I/O `Binding`s from the vertex shader to the
/// fragment shader must have non-`None` `interpolation` values.
///
/// All the shader languages Naga supports have similar rules:
/// perspective-correct, center-sampled interpolation is the default for any
/// binding that can vary, and everything else either defaults to flat, or
/// requires an explicit flat qualifier/attribute/what-have-you.
///
/// If `binding` is not a [`Location`] binding, or if its [`interpolation`] is
/// already set, then make no changes. Otherwise, set `binding`'s interpolation
/// and sampling to reasonable defaults depending on `ty`, the type of the value
/// being interpolated:
///
/// - If `ty` is a floating-point scalar, vector, or matrix type, then
/// default to [`Perspective`] interpolation and [`Center`] sampling.
///
/// - If `ty` is an integral scalar or vector, then default to [`Flat`]
/// interpolation, which has no associated sampling.
///
/// - For any other types, make no change. Such types are not permitted as
/// user-defined IO values, and will probably be flagged by the verifier
///
/// When structs appear in input or output types, each member ought to have its
/// own [`Binding`], so structs are simply covered by the third case.
///
/// [`Binding`]: crate::Binding
/// [`Location`]: crate::Binding::Location
/// [`interpolation`]: crate::Binding::Location::interpolation
/// [`Perspective`]: crate::Interpolation::Perspective
/// [`Flat`]: crate::Interpolation::Flat
/// [`Center`]: crate::Sampling::Center
pub fn apply_default_interpolation(&mut self, ty: &crate::TypeInner) {
if let crate::Binding::Location {
location: _,
interpolation: ref mut interpolation @ None,
ref mut sampling,
second_blend_source: _,
} = *self
{
match ty.scalar_kind() {
Some(crate::ScalarKind::Float) => {
*interpolation = Some(crate::Interpolation::Perspective);
*sampling = Some(crate::Sampling::Center);
}
Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint) => {
*interpolation = Some(crate::Interpolation::Flat);
*sampling = None;
}
Some(_) | None => {}
}
}
}
}
+330
View File
@@ -0,0 +1,330 @@
/*!
Frontend parsers that consume binary and text shaders and load them into [`Module`](super::Module)s.
*/
mod interpolator;
mod type_gen;
#[cfg(feature = "spv-in")]
pub mod atomic_upgrade;
#[cfg(feature = "glsl-in")]
pub mod glsl;
#[cfg(feature = "spv-in")]
pub mod spv;
#[cfg(feature = "wgsl-in")]
pub mod wgsl;
use crate::{
arena::{Arena, Handle, HandleVec, UniqueArena},
proc::{ResolveContext, ResolveError, TypeResolution},
FastHashMap,
};
use std::ops;
/// A table of types for an `Arena<Expression>`.
///
/// A front end can use a `Typifier` to get types for an arena's expressions
/// while it is still contributing expressions to it. At any point, you can call
/// [`typifier.grow(expr, arena, ctx)`], where `expr` is a `Handle<Expression>`
/// referring to something in `arena`, and the `Typifier` will resolve the types
/// of all the expressions up to and including `expr`. Then you can write
/// `typifier[handle]` to get the type of any handle at or before `expr`.
///
/// Note that `Typifier` does *not* build an `Arena<Type>` as a part of its
/// usual operation. Ideally, a module's type arena should only contain types
/// actually needed by `Handle<Type>`s elsewhere in the module — functions,
/// variables, [`Compose`] expressions, other types, and so on — so we don't
/// want every little thing that occurs as the type of some intermediate
/// expression to show up there.
///
/// Instead, `Typifier` accumulates a [`TypeResolution`] for each expression,
/// which refers to the `Arena<Type>` in the [`ResolveContext`] passed to `grow`
/// as needed. [`TypeResolution`] is a lightweight representation for
/// intermediate types like this; see its documentation for details.
///
/// If you do need to register a `Typifier`'s conclusion in an `Arena<Type>`
/// (say, for a [`LocalVariable`] whose type you've inferred), you can use
/// [`register_type`] to do so.
///
/// [`typifier.grow(expr, arena)`]: Typifier::grow
/// [`register_type`]: Typifier::register_type
/// [`Compose`]: crate::Expression::Compose
/// [`LocalVariable`]: crate::LocalVariable
#[derive(Debug, Default)]
pub struct Typifier {
resolutions: HandleVec<crate::Expression, TypeResolution>,
}
impl Typifier {
pub const fn new() -> Self {
Typifier {
resolutions: HandleVec::new(),
}
}
pub fn reset(&mut self) {
self.resolutions.clear()
}
pub fn get<'a>(
&'a self,
expr_handle: Handle<crate::Expression>,
types: &'a UniqueArena<crate::Type>,
) -> &'a crate::TypeInner {
self.resolutions[expr_handle].inner_with(types)
}
/// Add an expression's type to an `Arena<Type>`.
///
/// Add the type of `expr_handle` to `types`, and return a `Handle<Type>`
/// referring to it.
///
/// # Note
///
/// If you just need a [`TypeInner`] for `expr_handle`'s type, consider
/// using `typifier[expression].inner_with(types)` instead. Calling
/// [`TypeResolution::inner_with`] often lets us avoid adding anything to
/// the arena, which can significantly reduce the number of types that end
/// up in the final module.
///
/// [`TypeInner`]: crate::TypeInner
pub fn register_type(
&self,
expr_handle: Handle<crate::Expression>,
types: &mut UniqueArena<crate::Type>,
) -> Handle<crate::Type> {
match self[expr_handle].clone() {
TypeResolution::Handle(handle) => handle,
TypeResolution::Value(inner) => {
types.insert(crate::Type { name: None, inner }, crate::Span::UNDEFINED)
}
}
}
/// Grow this typifier until it contains a type for `expr_handle`.
pub fn grow(
&mut self,
expr_handle: Handle<crate::Expression>,
expressions: &Arena<crate::Expression>,
ctx: &ResolveContext,
) -> Result<(), ResolveError> {
if self.resolutions.len() <= expr_handle.index() {
for (eh, expr) in expressions.iter().skip(self.resolutions.len()) {
//Note: the closure can't `Err` by construction
let resolution = ctx.resolve(expr, |h| Ok(&self.resolutions[h]))?;
log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution);
self.resolutions.insert(eh, resolution);
}
}
Ok(())
}
/// Recompute the type resolution for `expr_handle`.
///
/// If the type of `expr_handle` hasn't yet been calculated, call
/// [`grow`](Self::grow) to ensure it is covered.
///
/// In either case, when this returns, `self[expr_handle]` should be an
/// updated type resolution for `expr_handle`.
pub fn invalidate(
&mut self,
expr_handle: Handle<crate::Expression>,
expressions: &Arena<crate::Expression>,
ctx: &ResolveContext,
) -> Result<(), ResolveError> {
if self.resolutions.len() <= expr_handle.index() {
self.grow(expr_handle, expressions, ctx)
} else {
let expr = &expressions[expr_handle];
//Note: the closure can't `Err` by construction
let resolution = ctx.resolve(expr, |h| Ok(&self.resolutions[h]))?;
self.resolutions[expr_handle] = resolution;
Ok(())
}
}
}
impl ops::Index<Handle<crate::Expression>> for Typifier {
type Output = TypeResolution;
fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
&self.resolutions[handle]
}
}
/// Type representing a lexical scope, associating a name to a single variable
///
/// The scope is generic over the variable representation and name representation
/// in order to allow larger flexibility on the frontends on how they might
/// represent them.
type Scope<Name, Var> = FastHashMap<Name, Var>;
/// Structure responsible for managing variable lookups and keeping track of
/// lexical scopes
///
/// The symbol table is generic over the variable representation and its name
/// to allow larger flexibility on the frontends on how they might represent them.
///
/// ```
/// use naga::front::SymbolTable;
///
/// // Create a new symbol table with `u32`s representing the variable
/// let mut symbol_table: SymbolTable<&str, u32> = SymbolTable::default();
///
/// // Add two variables named `var1` and `var2` with 0 and 2 respectively
/// symbol_table.add("var1", 0);
/// symbol_table.add("var2", 2);
///
/// // Check that `var1` exists and is `0`
/// assert_eq!(symbol_table.lookup("var1"), Some(&0));
///
/// // Push a new scope and add a variable to it named `var1` shadowing the
/// // variable of our previous scope
/// symbol_table.push_scope();
/// symbol_table.add("var1", 1);
///
/// // Check that `var1` now points to the new value of `1` and `var2` still
/// // exists with its value of `2`
/// assert_eq!(symbol_table.lookup("var1"), Some(&1));
/// assert_eq!(symbol_table.lookup("var2"), Some(&2));
///
/// // Pop the scope
/// symbol_table.pop_scope();
///
/// // Check that `var1` now refers to our initial variable with value `0`
/// assert_eq!(symbol_table.lookup("var1"), Some(&0));
/// ```
///
/// Scopes are ordered as a LIFO stack so a variable defined in a later scope
/// with the same name as another variable defined in a earlier scope will take
/// precedence in the lookup. Scopes can be added with [`push_scope`] and
/// removed with [`pop_scope`].
///
/// A root scope is added when the symbol table is created and must always be
/// present. Trying to pop it will result in a panic.
///
/// Variables can be added with [`add`] and looked up with [`lookup`]. Adding a
/// variable will do so in the currently active scope and as mentioned
/// previously a lookup will search from the current scope to the root scope.
///
/// [`push_scope`]: Self::push_scope
/// [`pop_scope`]: Self::push_scope
/// [`add`]: Self::add
/// [`lookup`]: Self::lookup
pub struct SymbolTable<Name, Var> {
/// Stack of lexical scopes. Not all scopes are active; see [`cursor`].
///
/// [`cursor`]: Self::cursor
scopes: Vec<Scope<Name, Var>>,
/// Limit of the [`scopes`] stack (exclusive). By using a separate value for
/// the stack length instead of `Vec`'s own internal length, the scopes can
/// be reused to cache memory allocations.
///
/// [`scopes`]: Self::scopes
cursor: usize,
}
impl<Name, Var> SymbolTable<Name, Var> {
/// Adds a new lexical scope.
///
/// All variables declared after this point will be added to this scope
/// until another scope is pushed or [`pop_scope`] is called, causing this
/// scope to be removed along with all variables added to it.
///
/// [`pop_scope`]: Self::pop_scope
pub fn push_scope(&mut self) {
// If the cursor is equal to the scope's stack length then we need to
// push another empty scope. Otherwise we can reuse the already existing
// scope.
if self.scopes.len() == self.cursor {
self.scopes.push(FastHashMap::default())
} else {
self.scopes[self.cursor].clear();
}
self.cursor += 1;
}
/// Removes the current lexical scope and all its variables
///
/// # PANICS
/// - If the current lexical scope is the root scope
pub fn pop_scope(&mut self) {
// Despite the method title, the variables are only deleted when the
// scope is reused. This is because while a clear is inevitable if the
// scope needs to be reused, there are cases where the scope might be
// popped and not reused, i.e. if another scope with the same nesting
// level is never pushed again.
assert!(self.cursor != 1, "Tried to pop the root scope");
self.cursor -= 1;
}
}
impl<Name, Var> SymbolTable<Name, Var>
where
Name: std::hash::Hash + Eq,
{
/// Perform a lookup for a variable named `name`.
///
/// As stated in the struct level documentation the lookup will proceed from
/// the current scope to the root scope, returning `Some` when a variable is
/// found or `None` if there doesn't exist a variable with `name` in any
/// scope.
pub fn lookup<Q>(&self, name: &Q) -> Option<&Var>
where
Name: std::borrow::Borrow<Q>,
Q: std::hash::Hash + Eq + ?Sized,
{
// Iterate backwards through the scopes and try to find the variable
for scope in self.scopes[..self.cursor].iter().rev() {
if let Some(var) = scope.get(name) {
return Some(var);
}
}
None
}
/// Adds a new variable to the current scope.
///
/// Returns the previous variable with the same name in this scope if it
/// exists, so that the frontend might handle it in case variable shadowing
/// is disallowed.
pub fn add(&mut self, name: Name, var: Var) -> Option<Var> {
self.scopes[self.cursor - 1].insert(name, var)
}
/// Adds a new variable to the root scope.
///
/// This is used in GLSL for builtins which aren't known in advance and only
/// when used for the first time, so there must be a way to add those
/// declarations to the root unconditionally from the current scope.
///
/// Returns the previous variable with the same name in the root scope if it
/// exists, so that the frontend might handle it in case variable shadowing
/// is disallowed.
pub fn add_root(&mut self, name: Name, var: Var) -> Option<Var> {
self.scopes[0].insert(name, var)
}
}
impl<Name, Var> Default for SymbolTable<Name, Var> {
/// Constructs a new symbol table with a root scope
fn default() -> Self {
Self {
scopes: vec![FastHashMap::default()],
cursor: 1,
}
}
}
use std::fmt;
impl<Name: fmt::Debug, Var: fmt::Debug> fmt::Debug for SymbolTable<Name, Var> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SymbolTable ")?;
f.debug_list()
.entries(self.scopes[..self.cursor].iter())
.finish()
}
}
+186
View File
@@ -0,0 +1,186 @@
use super::error::Error;
use std::convert::TryInto;
pub(super) const fn map_binary_operator(word: spirv::Op) -> Result<crate::BinaryOperator, Error> {
use crate::BinaryOperator;
use spirv::Op;
match word {
// Arithmetic Instructions +, -, *, /, %
Op::IAdd | Op::FAdd => Ok(BinaryOperator::Add),
Op::ISub | Op::FSub => Ok(BinaryOperator::Subtract),
Op::IMul | Op::FMul => Ok(BinaryOperator::Multiply),
Op::UDiv | Op::SDiv | Op::FDiv => Ok(BinaryOperator::Divide),
Op::SRem => Ok(BinaryOperator::Modulo),
// Relational and Logical Instructions
Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => {
Ok(BinaryOperator::Equal)
}
Op::INotEqual | Op::FOrdNotEqual | Op::FUnordNotEqual | Op::LogicalNotEqual => {
Ok(BinaryOperator::NotEqual)
}
Op::ULessThan | Op::SLessThan | Op::FOrdLessThan | Op::FUnordLessThan => {
Ok(BinaryOperator::Less)
}
Op::ULessThanEqual
| Op::SLessThanEqual
| Op::FOrdLessThanEqual
| Op::FUnordLessThanEqual => Ok(BinaryOperator::LessEqual),
Op::UGreaterThan | Op::SGreaterThan | Op::FOrdGreaterThan | Op::FUnordGreaterThan => {
Ok(BinaryOperator::Greater)
}
Op::UGreaterThanEqual
| Op::SGreaterThanEqual
| Op::FOrdGreaterThanEqual
| Op::FUnordGreaterThanEqual => Ok(BinaryOperator::GreaterEqual),
Op::BitwiseOr => Ok(BinaryOperator::InclusiveOr),
Op::BitwiseXor => Ok(BinaryOperator::ExclusiveOr),
Op::BitwiseAnd => Ok(BinaryOperator::And),
_ => Err(Error::UnknownBinaryOperator(word)),
}
}
pub(super) const fn map_relational_fun(
word: spirv::Op,
) -> Result<crate::RelationalFunction, Error> {
use crate::RelationalFunction as Rf;
use spirv::Op;
match word {
Op::All => Ok(Rf::All),
Op::Any => Ok(Rf::Any),
Op::IsNan => Ok(Rf::IsNan),
Op::IsInf => Ok(Rf::IsInf),
_ => Err(Error::UnknownRelationalFunction(word)),
}
}
pub(super) const fn map_vector_size(word: spirv::Word) -> Result<crate::VectorSize, Error> {
match word {
2 => Ok(crate::VectorSize::Bi),
3 => Ok(crate::VectorSize::Tri),
4 => Ok(crate::VectorSize::Quad),
_ => Err(Error::InvalidVectorSize(word)),
}
}
pub(super) fn map_image_dim(word: spirv::Word) -> Result<crate::ImageDimension, Error> {
use spirv::Dim as D;
match D::from_u32(word) {
Some(D::Dim1D) => Ok(crate::ImageDimension::D1),
Some(D::Dim2D) => Ok(crate::ImageDimension::D2),
Some(D::Dim3D) => Ok(crate::ImageDimension::D3),
Some(D::DimCube) => Ok(crate::ImageDimension::Cube),
_ => Err(Error::UnsupportedImageDim(word)),
}
}
pub(super) fn map_image_format(word: spirv::Word) -> Result<crate::StorageFormat, Error> {
match spirv::ImageFormat::from_u32(word) {
Some(spirv::ImageFormat::R8) => Ok(crate::StorageFormat::R8Unorm),
Some(spirv::ImageFormat::R8Snorm) => Ok(crate::StorageFormat::R8Snorm),
Some(spirv::ImageFormat::R8ui) => Ok(crate::StorageFormat::R8Uint),
Some(spirv::ImageFormat::R8i) => Ok(crate::StorageFormat::R8Sint),
Some(spirv::ImageFormat::R16) => Ok(crate::StorageFormat::R16Unorm),
Some(spirv::ImageFormat::R16Snorm) => Ok(crate::StorageFormat::R16Snorm),
Some(spirv::ImageFormat::R16ui) => Ok(crate::StorageFormat::R16Uint),
Some(spirv::ImageFormat::R16i) => Ok(crate::StorageFormat::R16Sint),
Some(spirv::ImageFormat::R16f) => Ok(crate::StorageFormat::R16Float),
Some(spirv::ImageFormat::Rg8) => Ok(crate::StorageFormat::Rg8Unorm),
Some(spirv::ImageFormat::Rg8Snorm) => Ok(crate::StorageFormat::Rg8Snorm),
Some(spirv::ImageFormat::Rg8ui) => Ok(crate::StorageFormat::Rg8Uint),
Some(spirv::ImageFormat::Rg8i) => Ok(crate::StorageFormat::Rg8Sint),
Some(spirv::ImageFormat::R32ui) => Ok(crate::StorageFormat::R32Uint),
Some(spirv::ImageFormat::R32i) => Ok(crate::StorageFormat::R32Sint),
Some(spirv::ImageFormat::R32f) => Ok(crate::StorageFormat::R32Float),
Some(spirv::ImageFormat::Rg16) => Ok(crate::StorageFormat::Rg16Unorm),
Some(spirv::ImageFormat::Rg16Snorm) => Ok(crate::StorageFormat::Rg16Snorm),
Some(spirv::ImageFormat::Rg16ui) => Ok(crate::StorageFormat::Rg16Uint),
Some(spirv::ImageFormat::Rg16i) => Ok(crate::StorageFormat::Rg16Sint),
Some(spirv::ImageFormat::Rg16f) => Ok(crate::StorageFormat::Rg16Float),
Some(spirv::ImageFormat::Rgba8) => Ok(crate::StorageFormat::Rgba8Unorm),
Some(spirv::ImageFormat::Rgba8Snorm) => Ok(crate::StorageFormat::Rgba8Snorm),
Some(spirv::ImageFormat::Rgba8ui) => Ok(crate::StorageFormat::Rgba8Uint),
Some(spirv::ImageFormat::Rgba8i) => Ok(crate::StorageFormat::Rgba8Sint),
Some(spirv::ImageFormat::Rgb10a2ui) => Ok(crate::StorageFormat::Rgb10a2Uint),
Some(spirv::ImageFormat::Rgb10A2) => Ok(crate::StorageFormat::Rgb10a2Unorm),
Some(spirv::ImageFormat::R11fG11fB10f) => Ok(crate::StorageFormat::Rg11b10Ufloat),
Some(spirv::ImageFormat::R64ui) => Ok(crate::StorageFormat::R64Uint),
Some(spirv::ImageFormat::Rg32ui) => Ok(crate::StorageFormat::Rg32Uint),
Some(spirv::ImageFormat::Rg32i) => Ok(crate::StorageFormat::Rg32Sint),
Some(spirv::ImageFormat::Rg32f) => Ok(crate::StorageFormat::Rg32Float),
Some(spirv::ImageFormat::Rgba16) => Ok(crate::StorageFormat::Rgba16Unorm),
Some(spirv::ImageFormat::Rgba16Snorm) => Ok(crate::StorageFormat::Rgba16Snorm),
Some(spirv::ImageFormat::Rgba16ui) => Ok(crate::StorageFormat::Rgba16Uint),
Some(spirv::ImageFormat::Rgba16i) => Ok(crate::StorageFormat::Rgba16Sint),
Some(spirv::ImageFormat::Rgba16f) => Ok(crate::StorageFormat::Rgba16Float),
Some(spirv::ImageFormat::Rgba32ui) => Ok(crate::StorageFormat::Rgba32Uint),
Some(spirv::ImageFormat::Rgba32i) => Ok(crate::StorageFormat::Rgba32Sint),
Some(spirv::ImageFormat::Rgba32f) => Ok(crate::StorageFormat::Rgba32Float),
_ => Err(Error::UnsupportedImageFormat(word)),
}
}
pub(super) fn map_width(word: spirv::Word) -> Result<crate::Bytes, Error> {
(word >> 3) // bits to bytes
.try_into()
.map_err(|_| Error::InvalidTypeWidth(word))
}
pub(super) fn map_builtin(word: spirv::Word, invariant: bool) -> Result<crate::BuiltIn, Error> {
use spirv::BuiltIn as Bi;
Ok(match spirv::BuiltIn::from_u32(word) {
Some(Bi::Position | Bi::FragCoord) => crate::BuiltIn::Position { invariant },
Some(Bi::ViewIndex) => crate::BuiltIn::ViewIndex,
// vertex
Some(Bi::BaseInstance) => crate::BuiltIn::BaseInstance,
Some(Bi::BaseVertex) => crate::BuiltIn::BaseVertex,
Some(Bi::ClipDistance) => crate::BuiltIn::ClipDistance,
Some(Bi::CullDistance) => crate::BuiltIn::CullDistance,
Some(Bi::InstanceIndex) => crate::BuiltIn::InstanceIndex,
Some(Bi::PointSize) => crate::BuiltIn::PointSize,
Some(Bi::VertexIndex) => crate::BuiltIn::VertexIndex,
Some(Bi::DrawIndex) => crate::BuiltIn::DrawID,
// fragment
Some(Bi::FragDepth) => crate::BuiltIn::FragDepth,
Some(Bi::PointCoord) => crate::BuiltIn::PointCoord,
Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing,
Some(Bi::PrimitiveId) => crate::BuiltIn::PrimitiveIndex,
Some(Bi::SampleId) => crate::BuiltIn::SampleIndex,
Some(Bi::SampleMask) => crate::BuiltIn::SampleMask,
// compute
Some(Bi::GlobalInvocationId) => crate::BuiltIn::GlobalInvocationId,
Some(Bi::LocalInvocationId) => crate::BuiltIn::LocalInvocationId,
Some(Bi::LocalInvocationIndex) => crate::BuiltIn::LocalInvocationIndex,
Some(Bi::WorkgroupId) => crate::BuiltIn::WorkGroupId,
Some(Bi::WorkgroupSize) => crate::BuiltIn::WorkGroupSize,
Some(Bi::NumWorkgroups) => crate::BuiltIn::NumWorkGroups,
// subgroup
Some(Bi::NumSubgroups) => crate::BuiltIn::NumSubgroups,
Some(Bi::SubgroupId) => crate::BuiltIn::SubgroupId,
Some(Bi::SubgroupSize) => crate::BuiltIn::SubgroupSize,
Some(Bi::SubgroupLocalInvocationId) => crate::BuiltIn::SubgroupInvocationId,
_ => return Err(Error::UnsupportedBuiltIn(word)),
})
}
pub(super) fn map_storage_class(word: spirv::Word) -> Result<super::ExtendedClass, Error> {
use super::ExtendedClass as Ec;
use spirv::StorageClass as Sc;
Ok(match Sc::from_u32(word) {
Some(Sc::Function) => Ec::Global(crate::AddressSpace::Function),
Some(Sc::Input) => Ec::Input,
Some(Sc::Output) => Ec::Output,
Some(Sc::Private) => Ec::Global(crate::AddressSpace::Private),
Some(Sc::UniformConstant) => Ec::Global(crate::AddressSpace::Handle),
Some(Sc::StorageBuffer) => Ec::Global(crate::AddressSpace::Storage {
//Note: this is restricted by decorations later
access: crate::StorageAccess::LOAD | crate::StorageAccess::STORE,
}),
// we expect the `Storage` case to be filtered out before calling this function.
Some(Sc::Uniform) => Ec::Global(crate::AddressSpace::Uniform),
Some(Sc::Workgroup) => Ec::Global(crate::AddressSpace::WorkGroup),
Some(Sc::PushConstant) => Ec::Global(crate::AddressSpace::PushConstant),
_ => return Err(Error::UnsupportedStorageClass(word)),
})
}
+173
View File
@@ -0,0 +1,173 @@
use super::ModuleState;
use crate::{arena::Handle, front::atomic_upgrade};
use codespan_reporting::diagnostic::Diagnostic;
use codespan_reporting::files::SimpleFile;
use codespan_reporting::term;
use termcolor::{NoColor, WriteColor};
#[derive(Clone, Debug, thiserror::Error)]
pub enum Error {
#[error("invalid header")]
InvalidHeader,
#[error("invalid word count")]
InvalidWordCount,
#[error("unknown instruction {0}")]
UnknownInstruction(u16),
#[error("unknown capability %{0}")]
UnknownCapability(spirv::Word),
#[error("unsupported instruction {1:?} at {0:?}")]
UnsupportedInstruction(ModuleState, spirv::Op),
#[error("unsupported capability {0:?}")]
UnsupportedCapability(spirv::Capability),
#[error("unsupported extension {0}")]
UnsupportedExtension(String),
#[error("unsupported extension set {0}")]
UnsupportedExtSet(String),
#[error("unsupported extension instantiation set %{0}")]
UnsupportedExtInstSet(spirv::Word),
#[error("unsupported extension instantiation %{0}")]
UnsupportedExtInst(spirv::Word),
#[error("unsupported type {0:?}")]
UnsupportedType(Handle<crate::Type>),
#[error("unsupported execution model %{0}")]
UnsupportedExecutionModel(spirv::Word),
#[error("unsupported execution mode %{0}")]
UnsupportedExecutionMode(spirv::Word),
#[error("unsupported storage class %{0}")]
UnsupportedStorageClass(spirv::Word),
#[error("unsupported image dimension %{0}")]
UnsupportedImageDim(spirv::Word),
#[error("unsupported image format %{0}")]
UnsupportedImageFormat(spirv::Word),
#[error("unsupported builtin %{0}")]
UnsupportedBuiltIn(spirv::Word),
#[error("unsupported control flow %{0}")]
UnsupportedControlFlow(spirv::Word),
#[error("unsupported binary operator %{0}")]
UnsupportedBinaryOperator(spirv::Word),
#[error("Naga supports OpTypeRuntimeArray in the StorageBuffer storage class only")]
UnsupportedRuntimeArrayStorageClass,
#[error(
"unsupported matrix stride {} for a {}x{} matrix with scalar width={}",
stride,
columns,
rows,
width
)]
UnsupportedMatrixStride {
stride: u32,
columns: u8,
rows: u8,
width: u8,
},
#[error("unknown binary operator {0:?}")]
UnknownBinaryOperator(spirv::Op),
#[error("unknown relational function {0:?}")]
UnknownRelationalFunction(spirv::Op),
#[error("unsupported group operation %{0}")]
UnsupportedGroupOperation(spirv::Word),
#[error("invalid parameter {0:?}")]
InvalidParameter(spirv::Op),
#[error("invalid operand count {1} for {0:?}")]
InvalidOperandCount(spirv::Op, u16),
#[error("invalid operand")]
InvalidOperand,
#[error("invalid id %{0}")]
InvalidId(spirv::Word),
#[error("invalid decoration %{0}")]
InvalidDecoration(spirv::Word),
#[error("invalid type width %{0}")]
InvalidTypeWidth(spirv::Word),
#[error("invalid sign %{0}")]
InvalidSign(spirv::Word),
#[error("invalid inner type %{0}")]
InvalidInnerType(spirv::Word),
#[error("invalid vector size %{0}")]
InvalidVectorSize(spirv::Word),
#[error("invalid access type %{0}")]
InvalidAccessType(spirv::Word),
#[error("invalid access {0:?}")]
InvalidAccess(crate::Expression),
#[error("invalid access index %{0}")]
InvalidAccessIndex(spirv::Word),
#[error("invalid index type %{0}")]
InvalidIndexType(spirv::Word),
#[error("invalid binding %{0}")]
InvalidBinding(spirv::Word),
#[error("invalid global var {0:?}")]
InvalidGlobalVar(crate::Expression),
#[error("invalid image/sampler expression {0:?}")]
InvalidImageExpression(crate::Expression),
#[error("invalid image base type {0:?}")]
InvalidImageBaseType(Handle<crate::Type>),
#[error("invalid image {0:?}")]
InvalidImage(Handle<crate::Type>),
#[error("invalid as type {0:?}")]
InvalidAsType(Handle<crate::Type>),
#[error("invalid vector type {0:?}")]
InvalidVectorType(Handle<crate::Type>),
#[error("inconsistent comparison sampling {0:?}")]
InconsistentComparisonSampling(Handle<crate::GlobalVariable>),
#[error("wrong function result type %{0}")]
WrongFunctionResultType(spirv::Word),
#[error("wrong function argument type %{0}")]
WrongFunctionArgumentType(spirv::Word),
#[error("missing decoration {0:?}")]
MissingDecoration(spirv::Decoration),
#[error("bad string")]
BadString,
#[error("incomplete data")]
IncompleteData,
#[error("invalid terminator")]
InvalidTerminator,
#[error("invalid edge classification")]
InvalidEdgeClassification,
#[error("cycle detected in the CFG during traversal at {0}")]
ControlFlowGraphCycle(crate::front::spv::BlockId),
#[error("recursive function call %{0}")]
FunctionCallCycle(spirv::Word),
#[error("invalid array size %{0}")]
InvalidArraySize(spirv::Word),
#[error("invalid barrier scope %{0}")]
InvalidBarrierScope(spirv::Word),
#[error("invalid barrier memory semantics %{0}")]
InvalidBarrierMemorySemantics(spirv::Word),
#[error(
"arrays of images / samplers are supported only through bindings for \
now (i.e. you can't create an array of images or samplers that doesn't \
come from a binding)"
)]
NonBindingArrayOfImageOrSamplers,
#[error("naga only supports specialization constant IDs up to 65535 but was given {0}")]
SpecIdTooHigh(u32),
#[error("atomic upgrade error: {0}")]
AtomicUpgradeError(atomic_upgrade::Error),
}
impl Error {
pub fn emit_to_writer(&self, writer: &mut impl WriteColor, source: &str) {
self.emit_to_writer_with_path(writer, source, "glsl");
}
pub fn emit_to_writer_with_path(&self, writer: &mut impl WriteColor, source: &str, path: &str) {
let path = path.to_string();
let files = SimpleFile::new(path, source);
let config = term::Config::default();
let diagnostic = Diagnostic::error().with_message(format!("{self:?}"));
term::emit(writer, &config, &files, &diagnostic).expect("cannot write error");
}
pub fn emit_to_string(&self, source: &str) -> String {
let mut writer = NoColor::new(Vec::new());
self.emit_to_writer(&mut writer, source);
String::from_utf8(writer.into_inner()).unwrap()
}
}
impl From<atomic_upgrade::Error> for Error {
fn from(source: atomic_upgrade::Error) -> Self {
Error::AtomicUpgradeError(source)
}
}
+683
View File
@@ -0,0 +1,683 @@
use crate::{
arena::{Arena, Handle},
front::spv::{BlockContext, BodyIndex},
};
use super::{Error, Instruction, LookupExpression, LookupHelper as _};
use crate::proc::Emitter;
pub type BlockId = u32;
impl<I: Iterator<Item = u32>> super::Frontend<I> {
// Registers a function call. It will generate a dummy handle to call, which
// gets resolved after all the functions are processed.
pub(super) fn add_call(
&mut self,
from: spirv::Word,
to: spirv::Word,
) -> Handle<crate::Function> {
let dummy_handle = self
.dummy_functions
.append(crate::Function::default(), Default::default());
self.deferred_function_calls.push(to);
self.function_call_graph.add_edge(from, to, ());
dummy_handle
}
pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> {
let start = self.data_offset;
self.lookup_expression.clear();
self.lookup_load_override.clear();
self.lookup_sampled_image.clear();
let result_type_id = self.next()?;
let fun_id = self.next()?;
let _fun_control = self.next()?;
let fun_type_id = self.next()?;
let mut fun = {
let ft = self.lookup_function_type.lookup(fun_type_id)?;
if ft.return_type_id != result_type_id {
return Err(Error::WrongFunctionResultType(result_type_id));
}
crate::Function {
name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name),
arguments: Vec::with_capacity(ft.parameter_type_ids.len()),
result: if self.lookup_void_type == Some(result_type_id) {
None
} else {
let lookup_result_ty = self.lookup_type.lookup(result_type_id)?;
Some(crate::FunctionResult {
ty: lookup_result_ty.handle,
binding: None,
})
},
local_variables: Arena::new(),
expressions: self.make_expression_storage(
&module.global_variables,
&module.constants,
&module.overrides,
),
named_expressions: crate::NamedExpressions::default(),
body: crate::Block::new(),
diagnostic_filter_leaf: None,
}
};
// read parameters
for i in 0..fun.arguments.capacity() {
let start = self.data_offset;
match self.next_inst()? {
Instruction {
op: spirv::Op::FunctionParameter,
wc: 3,
} => {
let type_id = self.next()?;
let id = self.next()?;
let handle = fun.expressions.append(
crate::Expression::FunctionArgument(i as u32),
self.span_from(start),
);
self.lookup_expression.insert(
id,
LookupExpression {
handle,
type_id,
// Setting this to an invalid id will cause get_expr_handle
// to default to the main body making sure no load/stores
// are added.
block_id: 0,
},
);
//Note: we redo the lookup in order to work around `self` borrowing
if type_id
!= self
.lookup_function_type
.lookup(fun_type_id)?
.parameter_type_ids[i]
{
return Err(Error::WrongFunctionArgumentType(type_id));
}
let ty = self.lookup_type.lookup(type_id)?.handle;
let decor = self.future_decor.remove(&id).unwrap_or_default();
fun.arguments.push(crate::FunctionArgument {
name: decor.name,
ty,
binding: None,
});
}
Instruction { op, .. } => return Err(Error::InvalidParameter(op)),
}
}
// Note the index this function's handle will be assigned, for tracing.
let function_index = module.functions.len();
// Read body
self.function_call_graph.add_node(fun_id);
let mut parameters_sampling =
vec![super::image::SamplingFlags::empty(); fun.arguments.len()];
let mut block_ctx = BlockContext {
phis: Default::default(),
blocks: Default::default(),
body_for_label: Default::default(),
mergers: Default::default(),
bodies: Default::default(),
module,
function_id: fun_id,
expressions: &mut fun.expressions,
local_arena: &mut fun.local_variables,
arguments: &fun.arguments,
parameter_sampling: &mut parameters_sampling,
};
// Insert the main body whose parent is also himself
block_ctx.bodies.push(super::Body::with_parent(0));
// Scan the blocks and add them as nodes
loop {
let fun_inst = self.next_inst()?;
log::debug!("{:?}", fun_inst.op);
match fun_inst.op {
spirv::Op::Line => {
fun_inst.expect(4)?;
let _file_id = self.next()?;
let _row_id = self.next()?;
let _col_id = self.next()?;
}
spirv::Op::Label => {
// Read the label ID
fun_inst.expect(2)?;
let block_id = self.next()?;
self.next_block(block_id, &mut block_ctx)?;
}
spirv::Op::FunctionEnd => {
fun_inst.expect(1)?;
break;
}
_ => {
return Err(Error::UnsupportedInstruction(self.state, fun_inst.op));
}
}
}
if let Some(ref prefix) = self.options.block_ctx_dump_prefix {
let dump_suffix = match self.lookup_entry_point.get(&fun_id) {
Some(ep) => format!("block_ctx.{:?}-{}.txt", ep.stage, ep.name),
None => format!("block_ctx.Fun-{}.txt", function_index),
};
let dest = prefix.join(dump_suffix);
let dump = format!("{block_ctx:#?}");
if let Err(e) = std::fs::write(&dest, dump) {
log::error!("Unable to dump the block context into {:?}: {}", dest, e);
}
}
// Emit `Store` statements to properly initialize all the local variables we
// created for `phi` expressions.
//
// Note that get_expr_handle also contributes slightly odd entries to this table,
// to get the spill.
for phi in block_ctx.phis.iter() {
// Get a pointer to the local variable for the phi's value.
let phi_pointer = block_ctx.expressions.append(
crate::Expression::LocalVariable(phi.local),
crate::Span::default(),
);
// At the end of each of `phi`'s predecessor blocks, store the corresponding
// source value in the phi's local variable.
for &(source, predecessor) in phi.expressions.iter() {
let source_lexp = &self.lookup_expression[&source];
let predecessor_body_idx = block_ctx.body_for_label[&predecessor];
// If the expression is a global/argument it will have a 0 block
// id so we must use a default value instead of panicking
let source_body_idx = block_ctx
.body_for_label
.get(&source_lexp.block_id)
.copied()
.unwrap_or(0);
// If the Naga `Expression` generated for `source` is in scope, then we
// can simply store that in the phi's local variable.
//
// Otherwise, spill the source value to a local variable in the block that
// defines it. (We know this store dominates the predecessor; otherwise,
// the phi wouldn't have been able to refer to that source expression in
// the first place.) Then, the predecessor block can count on finding the
// source's value in that local variable.
let value = if super::is_parent(predecessor_body_idx, source_body_idx, &block_ctx) {
source_lexp.handle
} else {
// The source SPIR-V expression is not defined in the phi's
// predecessor block, nor is it a globally available expression. So it
// must be defined off in some other block that merely dominates the
// predecessor. This means that the corresponding Naga `Expression`
// may not be in scope in the predecessor block.
//
// In the block that defines `source`, spill it to a fresh local
// variable, to ensure we can still use it at the end of the
// predecessor.
let ty = self.lookup_type[&source_lexp.type_id].handle;
let local = block_ctx.local_arena.append(
crate::LocalVariable {
name: None,
ty,
init: None,
},
crate::Span::default(),
);
let pointer = block_ctx.expressions.append(
crate::Expression::LocalVariable(local),
crate::Span::default(),
);
// Get the spilled value of the source expression.
let start = block_ctx.expressions.len();
let expr = block_ctx
.expressions
.append(crate::Expression::Load { pointer }, crate::Span::default());
let range = block_ctx.expressions.range_from(start);
block_ctx
.blocks
.get_mut(&predecessor)
.unwrap()
.push(crate::Statement::Emit(range), crate::Span::default());
// At the end of the block that defines it, spill the source
// expression's value.
block_ctx
.blocks
.get_mut(&source_lexp.block_id)
.unwrap()
.push(
crate::Statement::Store {
pointer,
value: source_lexp.handle,
},
crate::Span::default(),
);
expr
};
// At the end of the phi predecessor block, store the source
// value in the phi's value.
block_ctx.blocks.get_mut(&predecessor).unwrap().push(
crate::Statement::Store {
pointer: phi_pointer,
value,
},
crate::Span::default(),
)
}
}
fun.body = block_ctx.lower();
// done
let fun_handle = module.functions.append(fun, self.span_from_with_op(start));
self.lookup_function.insert(
fun_id,
super::LookupFunction {
handle: fun_handle,
parameters_sampling,
},
);
if let Some(ep) = self.lookup_entry_point.remove(&fun_id) {
self.deferred_entry_points.push((ep, fun_id));
}
Ok(())
}
pub(super) fn process_entry_point(
&mut self,
module: &mut crate::Module,
ep: super::EntryPoint,
fun_id: u32,
) -> Result<(), Error> {
// create a wrapping function
let mut function = crate::Function {
name: Some(format!("{}_wrap", ep.name)),
arguments: Vec::new(),
result: None,
local_variables: Arena::new(),
expressions: Arena::new(),
named_expressions: crate::NamedExpressions::default(),
body: crate::Block::new(),
diagnostic_filter_leaf: None,
};
// 1. copy the inputs from arguments to privates
for &v_id in ep.variable_ids.iter() {
let lvar = self.lookup_variable.lookup(v_id)?;
if let super::Variable::Input(ref arg) = lvar.inner {
let span = module.global_variables.get_span(lvar.handle);
let arg_expr = function.expressions.append(
crate::Expression::FunctionArgument(function.arguments.len() as u32),
span,
);
let load_expr = if arg.ty == module.global_variables[lvar.handle].ty {
arg_expr
} else {
// The only case where the type is different is if we need to treat
// unsigned integer as signed.
let mut emitter = Emitter::default();
emitter.start(&function.expressions);
let handle = function.expressions.append(
crate::Expression::As {
expr: arg_expr,
kind: crate::ScalarKind::Sint,
convert: Some(4),
},
span,
);
function.body.extend(emitter.finish(&function.expressions));
handle
};
function.body.push(
crate::Statement::Store {
pointer: function
.expressions
.append(crate::Expression::GlobalVariable(lvar.handle), span),
value: load_expr,
},
span,
);
let mut arg = arg.clone();
if ep.stage == crate::ShaderStage::Fragment {
if let Some(ref mut binding) = arg.binding {
binding.apply_default_interpolation(&module.types[arg.ty].inner);
}
}
function.arguments.push(arg);
}
}
// 2. call the wrapped function
let fake_id = !(module.entry_points.len() as u32); // doesn't matter, as long as it's not a collision
let dummy_handle = self.add_call(fake_id, fun_id);
function.body.push(
crate::Statement::Call {
function: dummy_handle,
arguments: Vec::new(),
result: None,
},
crate::Span::default(),
);
// 3. copy the outputs from privates to the result
let mut members = Vec::new();
let mut components = Vec::new();
for &v_id in ep.variable_ids.iter() {
let lvar = self.lookup_variable.lookup(v_id)?;
if let super::Variable::Output(ref result) = lvar.inner {
let span = module.global_variables.get_span(lvar.handle);
let expr_handle = function
.expressions
.append(crate::Expression::GlobalVariable(lvar.handle), span);
// Cull problematic builtins of gl_PerVertex.
// See the docs for `Frontend::gl_per_vertex_builtin_access`.
{
let ty = &module.types[result.ty];
if let crate::TypeInner::Struct {
members: ref original_members,
span,
} = ty.inner
{
let mut new_members = None;
for (idx, member) in original_members.iter().enumerate() {
if let Some(crate::Binding::BuiltIn(built_in)) = member.binding {
if !self.gl_per_vertex_builtin_access.contains(&built_in) {
new_members.get_or_insert_with(|| original_members.clone())
[idx]
.binding = None;
}
}
}
if let Some(new_members) = new_members {
module.types.replace(
result.ty,
crate::Type {
name: ty.name.clone(),
inner: crate::TypeInner::Struct {
members: new_members,
span,
},
},
);
}
}
}
match module.types[result.ty].inner {
crate::TypeInner::Struct {
members: ref sub_members,
..
} => {
for (index, sm) in sub_members.iter().enumerate() {
if sm.binding.is_none() {
continue;
}
let mut sm = sm.clone();
if let Some(ref mut binding) = sm.binding {
if ep.stage == crate::ShaderStage::Vertex {
binding.apply_default_interpolation(&module.types[sm.ty].inner);
}
}
members.push(sm);
components.push(function.expressions.append(
crate::Expression::AccessIndex {
base: expr_handle,
index: index as u32,
},
span,
));
}
}
ref inner => {
let mut binding = result.binding.clone();
if let Some(ref mut binding) = binding {
if ep.stage == crate::ShaderStage::Vertex {
binding.apply_default_interpolation(inner);
}
}
members.push(crate::StructMember {
name: None,
ty: result.ty,
binding,
offset: 0,
});
// populate just the globals first, then do `Load` in a
// separate step, so that we can get a range.
components.push(expr_handle);
}
}
}
}
for (member_index, member) in members.iter().enumerate() {
match member.binding {
Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { .. }))
if self.options.adjust_coordinate_space =>
{
let mut emitter = Emitter::default();
emitter.start(&function.expressions);
let global_expr = components[member_index];
let span = function.expressions.get_span(global_expr);
let access_expr = function.expressions.append(
crate::Expression::AccessIndex {
base: global_expr,
index: 1,
},
span,
);
let load_expr = function.expressions.append(
crate::Expression::Load {
pointer: access_expr,
},
span,
);
let neg_expr = function.expressions.append(
crate::Expression::Unary {
op: crate::UnaryOperator::Negate,
expr: load_expr,
},
span,
);
function.body.extend(emitter.finish(&function.expressions));
function.body.push(
crate::Statement::Store {
pointer: access_expr,
value: neg_expr,
},
span,
);
}
_ => {}
}
}
let mut emitter = Emitter::default();
emitter.start(&function.expressions);
for component in components.iter_mut() {
let load_expr = crate::Expression::Load {
pointer: *component,
};
let span = function.expressions.get_span(*component);
*component = function.expressions.append(load_expr, span);
}
match members[..] {
[] => {}
[ref member] => {
function.body.extend(emitter.finish(&function.expressions));
let span = function.expressions.get_span(components[0]);
function.body.push(
crate::Statement::Return {
value: components.first().cloned(),
},
span,
);
function.result = Some(crate::FunctionResult {
ty: member.ty,
binding: member.binding.clone(),
});
}
_ => {
let span = crate::Span::total_span(
components.iter().map(|h| function.expressions.get_span(*h)),
);
let ty = module.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Struct {
members,
span: 0xFFFF, // shouldn't matter
},
},
span,
);
let result_expr = function
.expressions
.append(crate::Expression::Compose { ty, components }, span);
function.body.extend(emitter.finish(&function.expressions));
function.body.push(
crate::Statement::Return {
value: Some(result_expr),
},
span,
);
function.result = Some(crate::FunctionResult { ty, binding: None });
}
}
module.entry_points.push(crate::EntryPoint {
name: ep.name,
stage: ep.stage,
early_depth_test: ep.early_depth_test,
workgroup_size: ep.workgroup_size,
workgroup_size_overrides: None,
function,
});
Ok(())
}
}
impl BlockContext<'_> {
pub(super) fn gctx(&self) -> crate::proc::GlobalCtx {
crate::proc::GlobalCtx {
types: &self.module.types,
constants: &self.module.constants,
overrides: &self.module.overrides,
global_expressions: &self.module.global_expressions,
}
}
/// Consumes the `BlockContext` producing a Ir [`Block`](crate::Block)
fn lower(mut self) -> crate::Block {
fn lower_impl(
blocks: &mut crate::FastHashMap<spirv::Word, crate::Block>,
bodies: &[super::Body],
body_idx: BodyIndex,
) -> crate::Block {
let mut block = crate::Block::new();
for item in bodies[body_idx].data.iter() {
match *item {
super::BodyFragment::BlockId(id) => block.append(blocks.get_mut(&id).unwrap()),
super::BodyFragment::If {
condition,
accept,
reject,
} => {
let accept = lower_impl(blocks, bodies, accept);
let reject = lower_impl(blocks, bodies, reject);
block.push(
crate::Statement::If {
condition,
accept,
reject,
},
crate::Span::default(),
)
}
super::BodyFragment::Loop {
body,
continuing,
break_if,
} => {
let body = lower_impl(blocks, bodies, body);
let continuing = lower_impl(blocks, bodies, continuing);
block.push(
crate::Statement::Loop {
body,
continuing,
break_if,
},
crate::Span::default(),
)
}
super::BodyFragment::Switch {
selector,
ref cases,
default,
} => {
let mut ir_cases: Vec<_> = cases
.iter()
.map(|&(value, body_idx)| {
let body = lower_impl(blocks, bodies, body_idx);
// Handle simple cases that would make a fallthrough statement unreachable code
let fall_through = body.last().map_or(true, |s| !s.is_terminator());
crate::SwitchCase {
value: crate::SwitchValue::I32(value),
body,
fall_through,
}
})
.collect();
ir_cases.push(crate::SwitchCase {
value: crate::SwitchValue::Default,
body: lower_impl(blocks, bodies, default),
fall_through: false,
});
block.push(
crate::Statement::Switch {
selector,
cases: ir_cases,
},
crate::Span::default(),
)
}
super::BodyFragment::Break => {
block.push(crate::Statement::Break, crate::Span::default())
}
super::BodyFragment::Continue => {
block.push(crate::Statement::Continue, crate::Span::default())
}
}
}
block
}
lower_impl(&mut self.blocks, &self.bodies, 0)
}
}
+839
View File
@@ -0,0 +1,839 @@
use crate::{
arena::{Handle, UniqueArena},
Scalar,
};
use super::{Error, LookupExpression, LookupHelper as _};
#[derive(Clone, Debug)]
pub(super) struct LookupSampledImage {
image: Handle<crate::Expression>,
sampler: Handle<crate::Expression>,
}
bitflags::bitflags! {
/// Flags describing sampling method.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SamplingFlags: u32 {
/// Regular sampling.
const REGULAR = 0x1;
/// Comparison sampling.
const COMPARISON = 0x2;
}
}
impl super::BlockContext<'_> {
fn get_image_expr_ty(
&self,
handle: Handle<crate::Expression>,
) -> Result<Handle<crate::Type>, Error> {
match self.expressions[handle] {
crate::Expression::GlobalVariable(handle) => {
Ok(self.module.global_variables[handle].ty)
}
crate::Expression::FunctionArgument(i) => Ok(self.arguments[i as usize].ty),
crate::Expression::Access { base, .. } => Ok(self.get_image_expr_ty(base)?),
ref other => Err(Error::InvalidImageExpression(other.clone())),
}
}
}
/// Options of a sampling operation.
#[derive(Debug)]
pub struct SamplingOptions {
/// Projection sampling: the division by W is expected to happen
/// in the texture unit.
pub project: bool,
/// Depth comparison sampling with a reference value.
pub compare: bool,
}
enum ExtraCoordinate {
ArrayLayer,
Projection,
Garbage,
}
/// Return the texture coordinates separated from the array layer,
/// and/or divided by the projection term.
///
/// The Proj sampling ops expect an extra coordinate for the W.
/// The arrayed (can't be Proj!) images expect an extra coordinate for the layer.
fn extract_image_coordinates(
image_dim: crate::ImageDimension,
extra_coordinate: ExtraCoordinate,
base: Handle<crate::Expression>,
coordinate_ty: Handle<crate::Type>,
ctx: &mut super::BlockContext,
) -> (Handle<crate::Expression>, Option<Handle<crate::Expression>>) {
let (given_size, kind) = match ctx.module.types[coordinate_ty].inner {
crate::TypeInner::Scalar(Scalar { kind, .. }) => (None, kind),
crate::TypeInner::Vector {
size,
scalar: Scalar { kind, .. },
} => (Some(size), kind),
ref other => unreachable!("Unexpected texture coordinate {:?}", other),
};
let required_size = image_dim.required_coordinate_size();
let required_ty = required_size.map(|size| {
ctx.module
.types
.get(&crate::Type {
name: None,
inner: crate::TypeInner::Vector {
size,
scalar: Scalar { kind, width: 4 },
},
})
.expect("Required coordinate type should have been set up by `parse_type_image`!")
});
let extra_expr = crate::Expression::AccessIndex {
base,
index: required_size.map_or(1, |size| size as u32),
};
let base_span = ctx.expressions.get_span(base);
match extra_coordinate {
ExtraCoordinate::ArrayLayer => {
let extracted = match required_size {
None => ctx
.expressions
.append(crate::Expression::AccessIndex { base, index: 0 }, base_span),
Some(size) => {
let mut components = Vec::with_capacity(size as usize);
for index in 0..size as u32 {
let comp = ctx
.expressions
.append(crate::Expression::AccessIndex { base, index }, base_span);
components.push(comp);
}
ctx.expressions.append(
crate::Expression::Compose {
ty: required_ty.unwrap(),
components,
},
base_span,
)
}
};
let array_index_f32 = ctx.expressions.append(extra_expr, base_span);
let array_index = ctx.expressions.append(
crate::Expression::As {
kind: crate::ScalarKind::Sint,
expr: array_index_f32,
convert: Some(4),
},
base_span,
);
(extracted, Some(array_index))
}
ExtraCoordinate::Projection => {
let projection = ctx.expressions.append(extra_expr, base_span);
let divided = match required_size {
None => {
let temp = ctx
.expressions
.append(crate::Expression::AccessIndex { base, index: 0 }, base_span);
ctx.expressions.append(
crate::Expression::Binary {
op: crate::BinaryOperator::Divide,
left: temp,
right: projection,
},
base_span,
)
}
Some(size) => {
let mut components = Vec::with_capacity(size as usize);
for index in 0..size as u32 {
let temp = ctx
.expressions
.append(crate::Expression::AccessIndex { base, index }, base_span);
let comp = ctx.expressions.append(
crate::Expression::Binary {
op: crate::BinaryOperator::Divide,
left: temp,
right: projection,
},
base_span,
);
components.push(comp);
}
ctx.expressions.append(
crate::Expression::Compose {
ty: required_ty.unwrap(),
components,
},
base_span,
)
}
};
(divided, None)
}
ExtraCoordinate::Garbage if given_size == required_size => (base, None),
ExtraCoordinate::Garbage => {
use crate::SwizzleComponent as Sc;
let cut_expr = match required_size {
None => crate::Expression::AccessIndex { base, index: 0 },
Some(size) => crate::Expression::Swizzle {
size,
vector: base,
pattern: [Sc::X, Sc::Y, Sc::Z, Sc::W],
},
};
(ctx.expressions.append(cut_expr, base_span), None)
}
}
}
pub(super) fn patch_comparison_type(
flags: SamplingFlags,
var: &mut crate::GlobalVariable,
arena: &mut UniqueArena<crate::Type>,
) -> bool {
if !flags.contains(SamplingFlags::COMPARISON) {
return true;
}
if flags == SamplingFlags::all() {
return false;
}
log::debug!("Flipping comparison for {:?}", var);
let original_ty = &arena[var.ty];
let original_ty_span = arena.get_span(var.ty);
let ty_inner = match original_ty.inner {
crate::TypeInner::Image {
class: crate::ImageClass::Sampled { multi, .. },
dim,
arrayed,
} => crate::TypeInner::Image {
class: crate::ImageClass::Depth { multi },
dim,
arrayed,
},
crate::TypeInner::Sampler { .. } => crate::TypeInner::Sampler { comparison: true },
ref other => unreachable!("Unexpected type for comparison mutation: {:?}", other),
};
let name = original_ty.name.clone();
var.ty = arena.insert(
crate::Type {
name,
inner: ty_inner,
},
original_ty_span,
);
true
}
impl<I: Iterator<Item = u32>> super::Frontend<I> {
pub(super) fn parse_image_couple(&mut self) -> Result<(), Error> {
let _result_type_id = self.next()?;
let result_id = self.next()?;
let image_id = self.next()?;
let sampler_id = self.next()?;
let image_lexp = self.lookup_expression.lookup(image_id)?;
let sampler_lexp = self.lookup_expression.lookup(sampler_id)?;
self.lookup_sampled_image.insert(
result_id,
LookupSampledImage {
image: image_lexp.handle,
sampler: sampler_lexp.handle,
},
);
Ok(())
}
pub(super) fn parse_image_uncouple(&mut self, block_id: spirv::Word) -> Result<(), Error> {
let result_type_id = self.next()?;
let result_id = self.next()?;
let sampled_image_id = self.next()?;
self.lookup_expression.insert(
result_id,
LookupExpression {
handle: self.lookup_sampled_image.lookup(sampled_image_id)?.image,
type_id: result_type_id,
block_id,
},
);
Ok(())
}
pub(super) fn parse_image_write(
&mut self,
words_left: u16,
ctx: &mut super::BlockContext,
emitter: &mut crate::proc::Emitter,
block: &mut crate::Block,
body_idx: usize,
) -> Result<crate::Statement, Error> {
let image_id = self.next()?;
let coordinate_id = self.next()?;
let value_id = self.next()?;
let image_ops = if words_left != 0 { self.next()? } else { 0 };
if image_ops != 0 {
let other = spirv::ImageOperands::from_bits_truncate(image_ops);
log::warn!("Unknown image write ops {:?}", other);
for _ in 1..words_left {
self.next()?;
}
}
let image_lexp = self.lookup_expression.lookup(image_id)?;
let image_ty = ctx.get_image_expr_ty(image_lexp.handle)?;
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
let coord_handle =
self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx);
let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle;
let (coordinate, array_index) = match ctx.module.types[image_ty].inner {
crate::TypeInner::Image {
dim,
arrayed,
class: _,
} => extract_image_coordinates(
dim,
if arrayed {
ExtraCoordinate::ArrayLayer
} else {
ExtraCoordinate::Garbage
},
coord_handle,
coord_type_handle,
ctx,
),
_ => return Err(Error::InvalidImage(image_ty)),
};
let value_lexp = self.lookup_expression.lookup(value_id)?;
let value = self.get_expr_handle(value_id, value_lexp, ctx, emitter, block, body_idx);
Ok(crate::Statement::ImageStore {
image: image_lexp.handle,
coordinate,
array_index,
value,
})
}
pub(super) fn parse_image_load(
&mut self,
mut words_left: u16,
ctx: &mut super::BlockContext,
emitter: &mut crate::proc::Emitter,
block: &mut crate::Block,
block_id: spirv::Word,
body_idx: usize,
) -> Result<(), Error> {
let start = self.data_offset;
let result_type_id = self.next()?;
let result_id = self.next()?;
let image_id = self.next()?;
let coordinate_id = self.next()?;
let mut image_ops = if words_left != 0 {
words_left -= 1;
self.next()?
} else {
0
};
let mut sample = None;
let mut level = None;
while image_ops != 0 {
let bit = 1 << image_ops.trailing_zeros();
match spirv::ImageOperands::from_bits_truncate(bit) {
spirv::ImageOperands::LOD => {
let lod_expr = self.next()?;
let lod_lexp = self.lookup_expression.lookup(lod_expr)?;
let lod_handle =
self.get_expr_handle(lod_expr, lod_lexp, ctx, emitter, block, body_idx);
level = Some(lod_handle);
words_left -= 1;
}
spirv::ImageOperands::SAMPLE => {
let sample_expr = self.next()?;
let sample_handle = self.lookup_expression.lookup(sample_expr)?.handle;
sample = Some(sample_handle);
words_left -= 1;
}
other => {
log::warn!("Unknown image load op {:?}", other);
for _ in 0..words_left {
self.next()?;
}
break;
}
}
image_ops ^= bit;
}
// No need to call get_expr_handle here since only globals/arguments are
// allowed as images and they are always in the root scope
let image_lexp = self.lookup_expression.lookup(image_id)?;
let image_ty = ctx.get_image_expr_ty(image_lexp.handle)?;
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
let coord_handle =
self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx);
let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle;
let (coordinate, array_index, is_depth) = match ctx.module.types[image_ty].inner {
crate::TypeInner::Image {
dim,
arrayed,
class,
} => {
let (coord, array_index) = extract_image_coordinates(
dim,
if arrayed {
ExtraCoordinate::ArrayLayer
} else {
ExtraCoordinate::Garbage
},
coord_handle,
coord_type_handle,
ctx,
);
(coord, array_index, class.is_depth())
}
_ => return Err(Error::InvalidImage(image_ty)),
};
let image_load_expr = crate::Expression::ImageLoad {
image: image_lexp.handle,
coordinate,
array_index,
sample,
level,
};
let image_load_handle = ctx
.expressions
.append(image_load_expr, self.span_from_with_op(start));
let handle = if is_depth {
let result_ty = self.lookup_type.lookup(result_type_id)?;
// The return type of `OpImageRead` can be a scalar or vector.
match ctx.module.types[result_ty.handle].inner {
crate::TypeInner::Vector { size, .. } => {
let splat_expr = crate::Expression::Splat {
size,
value: image_load_handle,
};
ctx.expressions
.append(splat_expr, self.span_from_with_op(start))
}
_ => image_load_handle,
}
} else {
image_load_handle
};
self.lookup_expression.insert(
result_id,
LookupExpression {
handle,
type_id: result_type_id,
block_id,
},
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(super) fn parse_image_sample(
&mut self,
mut words_left: u16,
options: SamplingOptions,
ctx: &mut super::BlockContext,
emitter: &mut crate::proc::Emitter,
block: &mut crate::Block,
block_id: spirv::Word,
body_idx: usize,
) -> Result<(), Error> {
let start = self.data_offset;
let result_type_id = self.next()?;
let result_id = self.next()?;
let sampled_image_id = self.next()?;
let coordinate_id = self.next()?;
let dref_id = if options.compare {
Some(self.next()?)
} else {
None
};
let span = self.span_from_with_op(start);
let mut image_ops = if words_left != 0 {
words_left -= 1;
self.next()?
} else {
0
};
let mut level = crate::SampleLevel::Auto;
let mut offset = None;
while image_ops != 0 {
let bit = 1 << image_ops.trailing_zeros();
match spirv::ImageOperands::from_bits_truncate(bit) {
spirv::ImageOperands::BIAS => {
let bias_expr = self.next()?;
let bias_lexp = self.lookup_expression.lookup(bias_expr)?;
let bias_handle =
self.get_expr_handle(bias_expr, bias_lexp, ctx, emitter, block, body_idx);
level = crate::SampleLevel::Bias(bias_handle);
words_left -= 1;
}
spirv::ImageOperands::LOD => {
let lod_expr = self.next()?;
let lod_lexp = self.lookup_expression.lookup(lod_expr)?;
let lod_handle =
self.get_expr_handle(lod_expr, lod_lexp, ctx, emitter, block, body_idx);
let is_depth_image = {
let image_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?;
let image_ty = ctx.get_image_expr_ty(image_lexp.image)?;
matches!(
ctx.module.types[image_ty].inner,
crate::TypeInner::Image {
class: crate::ImageClass::Depth { .. },
..
}
)
};
level = if options.compare {
log::debug!("Assuming {:?} is zero", lod_handle);
crate::SampleLevel::Zero
} else if is_depth_image {
log::debug!(
"Assuming level {:?} converts losslessly to an integer",
lod_handle
);
let expr = crate::Expression::As {
expr: lod_handle,
kind: crate::ScalarKind::Sint,
convert: Some(4),
};
let s32_lod_handle = ctx.expressions.append(expr, span);
crate::SampleLevel::Exact(s32_lod_handle)
} else {
crate::SampleLevel::Exact(lod_handle)
};
words_left -= 1;
}
spirv::ImageOperands::GRAD => {
let grad_x_expr = self.next()?;
let grad_x_lexp = self.lookup_expression.lookup(grad_x_expr)?;
let grad_x_handle = self.get_expr_handle(
grad_x_expr,
grad_x_lexp,
ctx,
emitter,
block,
body_idx,
);
let grad_y_expr = self.next()?;
let grad_y_lexp = self.lookup_expression.lookup(grad_y_expr)?;
let grad_y_handle = self.get_expr_handle(
grad_y_expr,
grad_y_lexp,
ctx,
emitter,
block,
body_idx,
);
level = if options.compare {
log::debug!(
"Assuming gradients {:?} and {:?} are not greater than 1",
grad_x_handle,
grad_y_handle
);
crate::SampleLevel::Zero
} else {
crate::SampleLevel::Gradient {
x: grad_x_handle,
y: grad_y_handle,
}
};
words_left -= 2;
}
spirv::ImageOperands::CONST_OFFSET => {
let offset_constant = self.next()?;
let offset_expr = self
.lookup_constant
.lookup(offset_constant)?
.inner
.to_expr();
let offset_handle = ctx
.module
.global_expressions
.append(offset_expr, Default::default());
offset = Some(offset_handle);
words_left -= 1;
}
other => {
log::warn!("Unknown image sample operand {:?}", other);
for _ in 0..words_left {
self.next()?;
}
break;
}
}
image_ops ^= bit;
}
let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?;
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
let coord_handle =
self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx);
let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle;
let sampling_bit = if options.compare {
SamplingFlags::COMPARISON
} else {
SamplingFlags::REGULAR
};
let image_ty = match ctx.expressions[si_lexp.image] {
crate::Expression::GlobalVariable(handle) => {
if let Some(flags) = self.handle_sampling.get_mut(&handle) {
*flags |= sampling_bit;
}
ctx.module.global_variables[handle].ty
}
crate::Expression::FunctionArgument(i) => {
ctx.parameter_sampling[i as usize] |= sampling_bit;
ctx.arguments[i as usize].ty
}
crate::Expression::Access { base, .. } => match ctx.expressions[base] {
crate::Expression::GlobalVariable(handle) => {
if let Some(flags) = self.handle_sampling.get_mut(&handle) {
*flags |= sampling_bit;
}
match ctx.module.types[ctx.module.global_variables[handle].ty].inner {
crate::TypeInner::BindingArray { base, .. } => base,
_ => return Err(Error::InvalidGlobalVar(ctx.expressions[base].clone())),
}
}
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
},
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
};
match ctx.expressions[si_lexp.sampler] {
crate::Expression::GlobalVariable(handle) => {
*self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit;
}
crate::Expression::FunctionArgument(i) => {
ctx.parameter_sampling[i as usize] |= sampling_bit;
}
crate::Expression::Access { base, .. } => match ctx.expressions[base] {
crate::Expression::GlobalVariable(handle) => {
*self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit;
}
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
},
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
}
let ((coordinate, array_index), depth_ref, is_depth) =
match ctx.module.types[image_ty].inner {
crate::TypeInner::Image {
dim,
arrayed,
class,
} => (
extract_image_coordinates(
dim,
if options.project {
ExtraCoordinate::Projection
} else if arrayed {
ExtraCoordinate::ArrayLayer
} else {
ExtraCoordinate::Garbage
},
coord_handle,
coord_type_handle,
ctx,
),
{
match dref_id {
Some(id) => {
let expr_lexp = self.lookup_expression.lookup(id)?;
let mut expr = self
.get_expr_handle(id, expr_lexp, ctx, emitter, block, body_idx);
if options.project {
let required_size = dim.required_coordinate_size();
let right = ctx.expressions.append(
crate::Expression::AccessIndex {
base: coord_handle,
index: required_size.map_or(1, |size| size as u32),
},
crate::Span::default(),
);
expr = ctx.expressions.append(
crate::Expression::Binary {
op: crate::BinaryOperator::Divide,
left: expr,
right,
},
crate::Span::default(),
)
};
Some(expr)
}
None => None,
}
},
class.is_depth(),
),
_ => return Err(Error::InvalidImage(image_ty)),
};
let expr = crate::Expression::ImageSample {
image: si_lexp.image,
sampler: si_lexp.sampler,
gather: None, //TODO
coordinate,
array_index,
offset,
level,
depth_ref,
};
let image_sample_handle = ctx.expressions.append(expr, self.span_from_with_op(start));
let handle = if is_depth && depth_ref.is_none() {
let splat_expr = crate::Expression::Splat {
size: crate::VectorSize::Quad,
value: image_sample_handle,
};
ctx.expressions
.append(splat_expr, self.span_from_with_op(start))
} else {
image_sample_handle
};
self.lookup_expression.insert(
result_id,
LookupExpression {
handle,
type_id: result_type_id,
block_id,
},
);
Ok(())
}
pub(super) fn parse_image_query_size(
&mut self,
at_level: bool,
ctx: &mut super::BlockContext,
emitter: &mut crate::proc::Emitter,
block: &mut crate::Block,
block_id: spirv::Word,
body_idx: usize,
) -> Result<(), Error> {
let start = self.data_offset;
let result_type_id = self.next()?;
let result_id = self.next()?;
let image_id = self.next()?;
let level = if at_level {
let level_id = self.next()?;
let level_lexp = self.lookup_expression.lookup(level_id)?;
Some(self.get_expr_handle(level_id, level_lexp, ctx, emitter, block, body_idx))
} else {
None
};
// No need to call get_expr_handle here since only globals/arguments are
// allowed as images and they are always in the root scope
//TODO: handle arrays and cubes
let image_lexp = self.lookup_expression.lookup(image_id)?;
let expr = crate::Expression::ImageQuery {
image: image_lexp.handle,
query: crate::ImageQuery::Size { level },
};
let result_type_handle = self.lookup_type.lookup(result_type_id)?.handle;
let maybe_scalar_kind = ctx.module.types[result_type_handle].inner.scalar_kind();
let expr = if maybe_scalar_kind == Some(crate::ScalarKind::Sint) {
crate::Expression::As {
expr: ctx.expressions.append(expr, self.span_from_with_op(start)),
kind: crate::ScalarKind::Sint,
convert: Some(4),
}
} else {
expr
};
self.lookup_expression.insert(
result_id,
LookupExpression {
handle: ctx.expressions.append(expr, self.span_from_with_op(start)),
type_id: result_type_id,
block_id,
},
);
Ok(())
}
pub(super) fn parse_image_query_other(
&mut self,
query: crate::ImageQuery,
ctx: &mut super::BlockContext,
block_id: spirv::Word,
) -> Result<(), Error> {
let start = self.data_offset;
let result_type_id = self.next()?;
let result_id = self.next()?;
let image_id = self.next()?;
// No need to call get_expr_handle here since only globals/arguments are
// allowed as images and they are always in the root scope
let image_lexp = self.lookup_expression.lookup(image_id)?.clone();
let expr = crate::Expression::ImageQuery {
image: image_lexp.handle,
query,
};
let result_type_handle = self.lookup_type.lookup(result_type_id)?.handle;
let maybe_scalar_kind = ctx.module.types[result_type_handle].inner.scalar_kind();
let expr = if maybe_scalar_kind == Some(crate::ScalarKind::Sint) {
crate::Expression::As {
expr: ctx.expressions.append(expr, self.span_from_with_op(start)),
kind: crate::ScalarKind::Sint,
convert: Some(4),
}
} else {
expr
};
self.lookup_expression.insert(
result_id,
LookupExpression {
handle: ctx.expressions.append(expr, self.span_from_with_op(start)),
type_id: result_type_id,
block_id,
},
);
Ok(())
}
}
+6078
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
use super::Error;
use crate::arena::{Arena, Handle};
/// Create a default value for an output built-in.
pub fn generate_default_built_in(
built_in: Option<crate::BuiltIn>,
ty: Handle<crate::Type>,
global_expressions: &mut Arena<crate::Expression>,
span: crate::Span,
) -> Result<Handle<crate::Expression>, Error> {
let expr = match built_in {
Some(crate::BuiltIn::Position { .. }) => {
let zero = global_expressions
.append(crate::Expression::Literal(crate::Literal::F32(0.0)), span);
let one = global_expressions
.append(crate::Expression::Literal(crate::Literal::F32(1.0)), span);
crate::Expression::Compose {
ty,
components: vec![zero, zero, zero, one],
}
}
Some(crate::BuiltIn::PointSize) => crate::Expression::Literal(crate::Literal::F32(1.0)),
Some(crate::BuiltIn::FragDepth) => crate::Expression::Literal(crate::Literal::F32(0.0)),
Some(crate::BuiltIn::SampleMask) => {
crate::Expression::Literal(crate::Literal::U32(u32::MAX))
}
// Note: `crate::BuiltIn::ClipDistance` is intentionally left for the default path
_ => crate::Expression::ZeroValue(ty),
};
Ok(global_expressions.append(expr, span))
}
+431
View File
@@ -0,0 +1,431 @@
/*!
Type generators.
*/
use crate::{arena::Handle, span::Span};
impl crate::Module {
/// Populate this module's [`SpecialTypes::ray_desc`] type.
///
/// [`SpecialTypes::ray_desc`] is the type of the [`descriptor`] operand of
/// an [`Initialize`] [`RayQuery`] statement. In WGSL, it is a struct type
/// referred to as `RayDesc`.
///
/// Backends consume values of this type to drive platform APIs, so if you
/// change any its fields, you must update the backends to match. Look for
/// backend code dealing with [`RayQueryFunction::Initialize`].
///
/// [`SpecialTypes::ray_desc`]: crate::SpecialTypes::ray_desc
/// [`descriptor`]: crate::RayQueryFunction::Initialize::descriptor
/// [`Initialize`]: crate::RayQueryFunction::Initialize
/// [`RayQuery`]: crate::Statement::RayQuery
/// [`RayQueryFunction::Initialize`]: crate::RayQueryFunction::Initialize
pub fn generate_ray_desc_type(&mut self) -> Handle<crate::Type> {
if let Some(handle) = self.special_types.ray_desc {
return handle;
}
let ty_flag = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar::U32),
},
Span::UNDEFINED,
);
let ty_scalar = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar::F32),
},
Span::UNDEFINED,
);
let ty_vector = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Vector {
size: crate::VectorSize::Tri,
scalar: crate::Scalar::F32,
},
},
Span::UNDEFINED,
);
let handle = self.types.insert(
crate::Type {
name: Some("RayDesc".to_string()),
inner: crate::TypeInner::Struct {
members: vec![
crate::StructMember {
name: Some("flags".to_string()),
ty: ty_flag,
binding: None,
offset: 0,
},
crate::StructMember {
name: Some("cull_mask".to_string()),
ty: ty_flag,
binding: None,
offset: 4,
},
crate::StructMember {
name: Some("tmin".to_string()),
ty: ty_scalar,
binding: None,
offset: 8,
},
crate::StructMember {
name: Some("tmax".to_string()),
ty: ty_scalar,
binding: None,
offset: 12,
},
crate::StructMember {
name: Some("origin".to_string()),
ty: ty_vector,
binding: None,
offset: 16,
},
crate::StructMember {
name: Some("dir".to_string()),
ty: ty_vector,
binding: None,
offset: 32,
},
],
span: 48,
},
},
Span::UNDEFINED,
);
self.special_types.ray_desc = Some(handle);
handle
}
/// Populate this module's [`SpecialTypes::ray_intersection`] type.
///
/// [`SpecialTypes::ray_intersection`] is the type of a
/// `RayQueryGetIntersection` expression. In WGSL, it is a struct type
/// referred to as `RayIntersection`.
///
/// Backends construct values of this type based on platform APIs, so if you
/// change any its fields, you must update the backends to match. Look for
/// the backend's handling for [`Expression::RayQueryGetIntersection`].
///
/// [`SpecialTypes::ray_intersection`]: crate::SpecialTypes::ray_intersection
/// [`Expression::RayQueryGetIntersection`]: crate::Expression::RayQueryGetIntersection
pub fn generate_ray_intersection_type(&mut self) -> Handle<crate::Type> {
if let Some(handle) = self.special_types.ray_intersection {
return handle;
}
let ty_flag = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar::U32),
},
Span::UNDEFINED,
);
let ty_scalar = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar::F32),
},
Span::UNDEFINED,
);
let ty_barycentrics = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Vector {
size: crate::VectorSize::Bi,
scalar: crate::Scalar::F32,
},
},
Span::UNDEFINED,
);
let ty_bool = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar::BOOL),
},
Span::UNDEFINED,
);
let ty_transform = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Tri,
scalar: crate::Scalar::F32,
},
},
Span::UNDEFINED,
);
let handle = self.types.insert(
crate::Type {
name: Some("RayIntersection".to_string()),
inner: crate::TypeInner::Struct {
members: vec![
crate::StructMember {
name: Some("kind".to_string()),
ty: ty_flag,
binding: None,
offset: 0,
},
crate::StructMember {
name: Some("t".to_string()),
ty: ty_scalar,
binding: None,
offset: 4,
},
crate::StructMember {
name: Some("instance_custom_index".to_string()),
ty: ty_flag,
binding: None,
offset: 8,
},
crate::StructMember {
name: Some("instance_id".to_string()),
ty: ty_flag,
binding: None,
offset: 12,
},
crate::StructMember {
name: Some("sbt_record_offset".to_string()),
ty: ty_flag,
binding: None,
offset: 16,
},
crate::StructMember {
name: Some("geometry_index".to_string()),
ty: ty_flag,
binding: None,
offset: 20,
},
crate::StructMember {
name: Some("primitive_index".to_string()),
ty: ty_flag,
binding: None,
offset: 24,
},
crate::StructMember {
name: Some("barycentrics".to_string()),
ty: ty_barycentrics,
binding: None,
offset: 28,
},
crate::StructMember {
name: Some("front_face".to_string()),
ty: ty_bool,
binding: None,
offset: 36,
},
crate::StructMember {
name: Some("object_to_world".to_string()),
ty: ty_transform,
binding: None,
offset: 48,
},
crate::StructMember {
name: Some("world_to_object".to_string()),
ty: ty_transform,
binding: None,
offset: 112,
},
],
span: 176,
},
},
Span::UNDEFINED,
);
self.special_types.ray_intersection = Some(handle);
handle
}
/// Populate this module's [`SpecialTypes::predeclared_types`] type and return the handle.
///
/// [`SpecialTypes::predeclared_types`]: crate::SpecialTypes::predeclared_types
pub fn generate_predeclared_type(
&mut self,
special_type: crate::PredeclaredType,
) -> Handle<crate::Type> {
use std::fmt::Write;
if let Some(value) = self.special_types.predeclared_types.get(&special_type) {
return *value;
}
let ty = match special_type {
crate::PredeclaredType::AtomicCompareExchangeWeakResult(scalar) => {
let bool_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar::BOOL),
},
Span::UNDEFINED,
);
let scalar_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(scalar),
},
Span::UNDEFINED,
);
crate::Type {
name: Some(format!(
"__atomic_compare_exchange_result<{:?},{}>",
scalar.kind, scalar.width,
)),
inner: crate::TypeInner::Struct {
members: vec![
crate::StructMember {
name: Some("old_value".to_string()),
ty: scalar_ty,
binding: None,
offset: 0,
},
crate::StructMember {
name: Some("exchanged".to_string()),
ty: bool_ty,
binding: None,
offset: scalar.width as u32,
},
],
span: scalar.width as u32 * 2,
},
}
}
crate::PredeclaredType::ModfResult { size, scalar } => {
let float_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(scalar),
},
Span::UNDEFINED,
);
let (member_ty, second_offset) = if let Some(size) = size {
let vec_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Vector { size, scalar },
},
Span::UNDEFINED,
);
(vec_ty, size as u32 * scalar.width as u32)
} else {
(float_ty, scalar.width as u32)
};
let mut type_name = "__modf_result_".to_string();
if let Some(size) = size {
let _ = write!(type_name, "vec{}_", size as u8);
}
let _ = write!(type_name, "f{}", scalar.width * 8);
crate::Type {
name: Some(type_name),
inner: crate::TypeInner::Struct {
members: vec![
crate::StructMember {
name: Some("fract".to_string()),
ty: member_ty,
binding: None,
offset: 0,
},
crate::StructMember {
name: Some("whole".to_string()),
ty: member_ty,
binding: None,
offset: second_offset,
},
],
span: second_offset * 2,
},
}
}
crate::PredeclaredType::FrexpResult { size, scalar } => {
let float_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(scalar),
},
Span::UNDEFINED,
);
let int_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Scalar(crate::Scalar {
kind: crate::ScalarKind::Sint,
width: scalar.width,
}),
},
Span::UNDEFINED,
);
let (fract_member_ty, exp_member_ty, second_offset) = if let Some(size) = size {
let vec_float_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Vector { size, scalar },
},
Span::UNDEFINED,
);
let vec_int_ty = self.types.insert(
crate::Type {
name: None,
inner: crate::TypeInner::Vector {
size,
scalar: crate::Scalar {
kind: crate::ScalarKind::Sint,
width: scalar.width,
},
},
},
Span::UNDEFINED,
);
(vec_float_ty, vec_int_ty, size as u32 * scalar.width as u32)
} else {
(float_ty, int_ty, scalar.width as u32)
};
let mut type_name = "__frexp_result_".to_string();
if let Some(size) = size {
let _ = write!(type_name, "vec{}_", size as u8);
}
let _ = write!(type_name, "f{}", scalar.width * 8);
crate::Type {
name: Some(type_name),
inner: crate::TypeInner::Struct {
members: vec![
crate::StructMember {
name: Some("fract".to_string()),
ty: fract_member_ty,
binding: None,
offset: 0,
},
crate::StructMember {
name: Some("exp".to_string()),
ty: exp_member_ty,
binding: None,
offset: second_offset,
},
],
span: second_offset * 2,
},
}
}
};
let handle = self.types.insert(ty, Span::UNDEFINED);
self.special_types
.predeclared_types
.insert(special_type, handle);
handle
}
}
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
use super::Error;
use crate::front::wgsl::parse::ast;
use crate::{FastHashMap, Handle, Span};
/// A `GlobalDecl` list in which each definition occurs before all its uses.
pub struct Index<'a> {
dependency_order: Vec<Handle<ast::GlobalDecl<'a>>>,
}
impl<'a> Index<'a> {
/// Generate an `Index` for the given translation unit.
///
/// Perform a topological sort on `tu`'s global declarations, placing
/// referents before the definitions that refer to them.
///
/// Return an error if the graph of references between declarations contains
/// any cycles.
pub fn generate(tu: &ast::TranslationUnit<'a>) -> Result<Self, Error<'a>> {
// Produce a map from global definitions' names to their `Handle<GlobalDecl>`s.
// While doing so, reject conflicting definitions.
let mut globals = FastHashMap::with_capacity_and_hasher(tu.decls.len(), Default::default());
for (handle, decl) in tu.decls.iter() {
if let Some(ident) = decl_ident(decl) {
let name = ident.name;
if let Some(old) = globals.insert(name, handle) {
return Err(Error::Redefinition {
previous: decl_ident(&tu.decls[old])
.expect("decl should have ident for redefinition")
.span,
current: ident.span,
});
}
}
}
let len = tu.decls.len();
let solver = DependencySolver {
globals: &globals,
module: tu,
visited: vec![false; len],
temp_visited: vec![false; len],
path: Vec::new(),
out: Vec::with_capacity(len),
};
let dependency_order = solver.solve()?;
Ok(Self { dependency_order })
}
/// Iterate over `GlobalDecl`s, visiting each definition before all its uses.
///
/// Produce handles for all of the `GlobalDecl`s of the `TranslationUnit`
/// passed to `Index::generate`, ordered so that a given declaration is
/// produced before any other declaration that uses it.
pub fn visit_ordered(&self) -> impl Iterator<Item = Handle<ast::GlobalDecl<'a>>> + '_ {
self.dependency_order.iter().copied()
}
}
/// An edge from a reference to its referent in the current depth-first
/// traversal.
///
/// This is like `ast::Dependency`, except that we've determined which
/// `GlobalDecl` it refers to.
struct ResolvedDependency<'a> {
/// The referent of some identifier used in the current declaration.
decl: Handle<ast::GlobalDecl<'a>>,
/// Where that use occurs within the current declaration.
usage: Span,
}
/// Local state for ordering a `TranslationUnit`'s module-scope declarations.
///
/// Values of this type are used temporarily by `Index::generate`
/// to perform a depth-first sort on the declarations.
/// Technically, what we want is a topological sort, but a depth-first sort
/// has one key benefit - it's much more efficient in storing
/// the path of each node for error generation.
struct DependencySolver<'source, 'temp> {
/// A map from module-scope definitions' names to their handles.
globals: &'temp FastHashMap<&'source str, Handle<ast::GlobalDecl<'source>>>,
/// The translation unit whose declarations we're ordering.
module: &'temp ast::TranslationUnit<'source>,
/// For each handle, whether we have pushed it onto `out` yet.
visited: Vec<bool>,
/// For each handle, whether it is an predecessor in the current depth-first
/// traversal. This is used to detect cycles in the reference graph.
temp_visited: Vec<bool>,
/// The current path in our depth-first traversal. Used for generating
/// error messages for non-trivial reference cycles.
path: Vec<ResolvedDependency<'source>>,
/// The list of declaration handles, with declarations before uses.
out: Vec<Handle<ast::GlobalDecl<'source>>>,
}
impl<'a> DependencySolver<'a, '_> {
/// Produce the sorted list of declaration handles, and check for cycles.
fn solve(mut self) -> Result<Vec<Handle<ast::GlobalDecl<'a>>>, Error<'a>> {
for (id, _) in self.module.decls.iter() {
if self.visited[id.index()] {
continue;
}
self.dfs(id)?;
}
Ok(self.out)
}
/// Ensure that all declarations used by `id` have been added to the
/// ordering, and then append `id` itself.
fn dfs(&mut self, id: Handle<ast::GlobalDecl<'a>>) -> Result<(), Error<'a>> {
let decl = &self.module.decls[id];
let id_usize = id.index();
self.temp_visited[id_usize] = true;
for dep in decl.dependencies.iter() {
if let Some(&dep_id) = self.globals.get(dep.ident) {
self.path.push(ResolvedDependency {
decl: dep_id,
usage: dep.usage,
});
let dep_id_usize = dep_id.index();
if self.temp_visited[dep_id_usize] {
// Found a cycle.
return if dep_id == id {
// A declaration refers to itself directly.
Err(Error::RecursiveDeclaration {
ident: decl_ident(decl).expect("decl should have ident").span,
usage: dep.usage,
})
} else {
// A declaration refers to itself indirectly, through
// one or more other definitions. Report the entire path
// of references.
let start_at = self
.path
.iter()
.rev()
.enumerate()
.find_map(|(i, dep)| (dep.decl == dep_id).then_some(i))
.unwrap_or(0);
Err(Error::CyclicDeclaration {
ident: decl_ident(&self.module.decls[dep_id])
.expect("decl should have ident")
.span,
path: self.path[start_at..]
.iter()
.map(|curr_dep| {
let curr_id = curr_dep.decl;
let curr_decl = &self.module.decls[curr_id];
(
decl_ident(curr_decl).expect("decl should have ident").span,
curr_dep.usage,
)
})
.collect(),
})
};
} else if !self.visited[dep_id_usize] {
self.dfs(dep_id)?;
}
// Remove this edge from the current path.
self.path.pop();
}
// Ignore unresolved identifiers; they may be predeclared objects.
}
// Remove this node from the current path.
self.temp_visited[id_usize] = false;
// Now everything this declaration uses has been visited, and is already
// present in `out`. That means we we can append this one to the
// ordering, and mark it as visited.
self.out.push(id);
self.visited[id_usize] = true;
Ok(())
}
}
const fn decl_ident<'a>(decl: &ast::GlobalDecl<'a>) -> Option<ast::Ident<'a>> {
match decl.kind {
ast::GlobalDeclKind::Fn(ref f) => Some(f.name),
ast::GlobalDeclKind::Var(ref v) => Some(v.name),
ast::GlobalDeclKind::Const(ref c) => Some(c.name),
ast::GlobalDeclKind::Override(ref o) => Some(o.name),
ast::GlobalDeclKind::Struct(ref s) => Some(s.name),
ast::GlobalDeclKind::Type(ref t) => Some(t.name),
ast::GlobalDeclKind::ConstAssert(_) => None,
}
}
+630
View File
@@ -0,0 +1,630 @@
use std::num::NonZeroU32;
use crate::front::wgsl::parse::ast;
use crate::{Handle, Span};
use crate::front::wgsl::error::Error;
use crate::front::wgsl::lower::{ExpressionContext, Lowerer};
/// A cooked form of `ast::ConstructorType` that uses Naga types whenever
/// possible.
enum Constructor<T> {
/// A vector construction whose component type is inferred from the
/// argument: `vec3(1.0)`.
PartialVector { size: crate::VectorSize },
/// A matrix construction whose component type is inferred from the
/// argument: `mat2x2(1,2,3,4)`.
PartialMatrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
},
/// An array whose component type and size are inferred from the arguments:
/// `array(3,4,5)`.
PartialArray,
/// A known Naga type.
///
/// When we match on this type, we need to see the `TypeInner` here, but at
/// the point that we build this value we'll still need mutable access to
/// the module later. To avoid borrowing from the module, the type parameter
/// `T` is `Handle<Type>` initially. Then we use `borrow_inner` to produce a
/// version holding a tuple `(Handle<Type>, &TypeInner)`.
Type(T),
}
impl Constructor<Handle<crate::Type>> {
/// Return an equivalent `Constructor` value that includes borrowed
/// `TypeInner` values alongside any type handles.
///
/// The returned form is more convenient to match on, since the patterns
/// can actually see what the handle refers to.
fn borrow_inner(
self,
module: &crate::Module,
) -> Constructor<(Handle<crate::Type>, &crate::TypeInner)> {
match self {
Constructor::PartialVector { size } => Constructor::PartialVector { size },
Constructor::PartialMatrix { columns, rows } => {
Constructor::PartialMatrix { columns, rows }
}
Constructor::PartialArray => Constructor::PartialArray,
Constructor::Type(handle) => Constructor::Type((handle, &module.types[handle].inner)),
}
}
}
impl Constructor<(Handle<crate::Type>, &crate::TypeInner)> {
fn to_error_string(&self, ctx: &ExpressionContext) -> String {
match *self {
Self::PartialVector { size } => {
format!("vec{}<?>", size as u32,)
}
Self::PartialMatrix { columns, rows } => {
format!("mat{}x{}<?>", columns as u32, rows as u32,)
}
Self::PartialArray => "array<?, ?>".to_string(),
Self::Type((handle, _inner)) => handle.to_wgsl(&ctx.module.to_ctx()),
}
}
}
enum Components<'a> {
None,
One {
component: Handle<crate::Expression>,
span: Span,
ty_inner: &'a crate::TypeInner,
},
Many {
components: Vec<Handle<crate::Expression>>,
spans: Vec<Span>,
},
}
impl Components<'_> {
fn into_components_vec(self) -> Vec<Handle<crate::Expression>> {
match self {
Self::None => vec![],
Self::One { component, .. } => vec![component],
Self::Many { components, .. } => components,
}
}
}
impl<'source> Lowerer<'source, '_> {
/// Generate Naga IR for a type constructor expression.
///
/// The `constructor` value represents the head of the constructor
/// expression, which is at least a hint of which type is being built; if
/// it's one of the `Partial` variants, we need to consider the argument
/// types as well.
///
/// This is used for [`Construct`] expressions, but also for [`Call`]
/// expressions, once we've determined that the "callable" (in WGSL spec
/// terms) is actually a type.
///
/// [`Construct`]: ast::Expression::Construct
/// [`Call`]: ast::Expression::Call
pub fn construct(
&mut self,
span: Span,
constructor: &ast::ConstructorType<'source>,
ty_span: Span,
components: &[Handle<ast::Expression<'source>>],
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<Handle<crate::Expression>, Error<'source>> {
use crate::proc::TypeResolution as Tr;
let constructor_h = self.constructor(constructor, ctx)?;
let components = match *components {
[] => Components::None,
[component] => {
let span = ctx.ast_expressions.get_span(component);
let component = self.expression_for_abstract(component, ctx)?;
let ty_inner = super::resolve_inner!(ctx, component);
Components::One {
component,
span,
ty_inner,
}
}
ref ast_components @ [_, _, ..] => {
let components = ast_components
.iter()
.map(|&expr| self.expression_for_abstract(expr, ctx))
.collect::<Result<_, _>>()?;
let spans = ast_components
.iter()
.map(|&expr| ctx.ast_expressions.get_span(expr))
.collect();
for &component in &components {
ctx.grow_types(component)?;
}
Components::Many { components, spans }
}
};
// Even though we computed `constructor` above, wait until now to borrow
// a reference to the `TypeInner`, so that the component-handling code
// above can have mutable access to the type arena.
let constructor = constructor_h.borrow_inner(ctx.module);
let expr;
match (components, constructor) {
// Empty constructor
(Components::None, dst_ty) => match dst_ty {
Constructor::Type((result_ty, _)) => {
return ctx.append_expression(crate::Expression::ZeroValue(result_ty), span)
}
Constructor::PartialVector { .. }
| Constructor::PartialMatrix { .. }
| Constructor::PartialArray => {
// We have no arguments from which to infer the result type, so
// partial constructors aren't acceptable here.
return Err(Error::TypeNotInferable(ty_span));
}
},
// Scalar constructor & conversion (scalar -> scalar)
(
Components::One {
component,
ty_inner: &crate::TypeInner::Scalar { .. },
..
},
Constructor::Type((_, &crate::TypeInner::Scalar(scalar))),
) => {
expr = crate::Expression::As {
expr: component,
kind: scalar.kind,
convert: Some(scalar.width),
};
}
// Vector conversion (vector -> vector)
(
Components::One {
component,
ty_inner: &crate::TypeInner::Vector { size: src_size, .. },
..
},
Constructor::Type((
_,
&crate::TypeInner::Vector {
size: dst_size,
scalar: dst_scalar,
},
)),
) if dst_size == src_size => {
expr = crate::Expression::As {
expr: component,
kind: dst_scalar.kind,
convert: Some(dst_scalar.width),
};
}
// Vector conversion (vector -> vector) - partial
(
Components::One {
component,
ty_inner: &crate::TypeInner::Vector { size: src_size, .. },
..
},
Constructor::PartialVector { size: dst_size },
) if dst_size == src_size => {
// This is a trivial conversion: the sizes match, and a Partial
// constructor doesn't specify a scalar type, so nothing can
// possibly happen.
return Ok(component);
}
// Matrix conversion (matrix -> matrix)
(
Components::One {
component,
ty_inner:
&crate::TypeInner::Matrix {
columns: src_columns,
rows: src_rows,
..
},
..
},
Constructor::Type((
_,
&crate::TypeInner::Matrix {
columns: dst_columns,
rows: dst_rows,
scalar: dst_scalar,
},
)),
) if dst_columns == src_columns && dst_rows == src_rows => {
expr = crate::Expression::As {
expr: component,
kind: dst_scalar.kind,
convert: Some(dst_scalar.width),
};
}
// Matrix conversion (matrix -> matrix) - partial
(
Components::One {
component,
ty_inner:
&crate::TypeInner::Matrix {
columns: src_columns,
rows: src_rows,
..
},
..
},
Constructor::PartialMatrix {
columns: dst_columns,
rows: dst_rows,
},
) if dst_columns == src_columns && dst_rows == src_rows => {
// This is a trivial conversion: the sizes match, and a Partial
// constructor doesn't specify a scalar type, so nothing can
// possibly happen.
return Ok(component);
}
// Vector constructor (splat) - infer type
(
Components::One {
component,
ty_inner: &crate::TypeInner::Scalar { .. },
..
},
Constructor::PartialVector { size },
) => {
expr = crate::Expression::Splat {
size,
value: component,
};
}
// Vector constructor (splat)
(
Components::One {
mut component,
ty_inner: &crate::TypeInner::Scalar(_),
..
},
Constructor::Type((_, &crate::TypeInner::Vector { size, scalar })),
) => {
ctx.convert_slice_to_common_leaf_scalar(
std::slice::from_mut(&mut component),
scalar,
)?;
expr = crate::Expression::Splat {
size,
value: component,
};
}
// Vector constructor (by elements), partial
(
Components::Many {
mut components,
spans,
},
Constructor::PartialVector { size },
) => {
let consensus_scalar =
ctx.automatic_conversion_consensus(&components)
.map_err(|index| {
Error::InvalidConstructorComponentType(spans[index], index as i32)
})?;
ctx.convert_slice_to_common_leaf_scalar(&mut components, consensus_scalar)?;
let inner = consensus_scalar.to_inner_vector(size);
let ty = ctx.ensure_type_exists(inner);
expr = crate::Expression::Compose { ty, components };
}
// Vector constructor (by elements), full type given
(
Components::Many { mut components, .. },
Constructor::Type((ty, &crate::TypeInner::Vector { scalar, .. })),
) => {
ctx.try_automatic_conversions_for_vector(&mut components, scalar, ty_span)?;
expr = crate::Expression::Compose { ty, components };
}
// Matrix constructor (by elements), partial
(
Components::Many {
mut components,
spans,
},
Constructor::PartialMatrix { columns, rows },
) if components.len() == columns as usize * rows as usize => {
let consensus_scalar =
ctx.automatic_conversion_consensus(&components)
.map_err(|index| {
Error::InvalidConstructorComponentType(spans[index], index as i32)
})?;
// We actually only accept floating-point elements.
let consensus_scalar = consensus_scalar
.automatic_conversion_combine(crate::Scalar::ABSTRACT_FLOAT)
.unwrap_or(consensus_scalar);
ctx.convert_slice_to_common_leaf_scalar(&mut components, consensus_scalar)?;
let vec_ty = ctx.ensure_type_exists(consensus_scalar.to_inner_vector(rows));
let components = components
.chunks(rows as usize)
.map(|vec_components| {
ctx.append_expression(
crate::Expression::Compose {
ty: vec_ty,
components: Vec::from(vec_components),
},
Default::default(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix {
columns,
rows,
scalar: consensus_scalar,
});
expr = crate::Expression::Compose { ty, components };
}
// Matrix constructor (by elements), type given
(
Components::Many { mut components, .. },
Constructor::Type((
_,
&crate::TypeInner::Matrix {
columns,
rows,
scalar,
},
)),
) if components.len() == columns as usize * rows as usize => {
let element = Tr::Value(crate::TypeInner::Scalar(scalar));
ctx.try_automatic_conversions_slice(&mut components, &element, ty_span)?;
let vec_ty = ctx.ensure_type_exists(scalar.to_inner_vector(rows));
let components = components
.chunks(rows as usize)
.map(|vec_components| {
ctx.append_expression(
crate::Expression::Compose {
ty: vec_ty,
components: Vec::from(vec_components),
},
Default::default(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix {
columns,
rows,
scalar,
});
expr = crate::Expression::Compose { ty, components };
}
// Matrix constructor (by columns), partial
(
Components::Many {
mut components,
spans,
},
Constructor::PartialMatrix { columns, rows },
) => {
let consensus_scalar =
ctx.automatic_conversion_consensus(&components)
.map_err(|index| {
Error::InvalidConstructorComponentType(spans[index], index as i32)
})?;
ctx.convert_slice_to_common_leaf_scalar(&mut components, consensus_scalar)?;
let ty = ctx.ensure_type_exists(crate::TypeInner::Matrix {
columns,
rows,
scalar: consensus_scalar,
});
expr = crate::Expression::Compose { ty, components };
}
// Matrix constructor (by columns), type given
(
Components::Many { mut components, .. },
Constructor::Type((
ty,
&crate::TypeInner::Matrix {
columns: _,
rows,
scalar,
},
)),
) => {
let component_ty = crate::TypeInner::Vector { size: rows, scalar };
ctx.try_automatic_conversions_slice(
&mut components,
&Tr::Value(component_ty),
ty_span,
)?;
expr = crate::Expression::Compose { ty, components };
}
// Array constructor - infer type
(components, Constructor::PartialArray) => {
let mut components = components.into_components_vec();
if let Ok(consensus_scalar) = ctx.automatic_conversion_consensus(&components) {
// Note that this will *not* necessarily convert all the
// components to the same type! The `automatic_conversion_consensus`
// method only considers the parameters' leaf scalar
// types; the parameters themselves could be any mix of
// vectors, matrices, and scalars.
//
// But *if* it is possible for this array construction
// expression to be well-typed at all, then all the
// parameters must have the same type constructors (vec,
// matrix, scalar) applied to their leaf scalars, so
// reconciling their scalars is always the right thing to
// do. And if this array construction is not well-typed,
// these conversions will not make it so, and we can let
// validation catch the error.
ctx.convert_slice_to_common_leaf_scalar(&mut components, consensus_scalar)?;
} else {
// There's no consensus scalar. Emit the `Compose`
// expression anyway, and let validation catch the problem.
}
let base = ctx.register_type(components[0])?;
let inner = crate::TypeInner::Array {
base,
size: crate::ArraySize::Constant(
NonZeroU32::new(u32::try_from(components.len()).unwrap()).unwrap(),
),
stride: {
self.layouter.update(ctx.module.to_ctx()).unwrap();
self.layouter[base].to_stride()
},
};
let ty = ctx.ensure_type_exists(inner);
expr = crate::Expression::Compose { ty, components };
}
// Array constructor, explicit type
(components, Constructor::Type((ty, &crate::TypeInner::Array { base, .. }))) => {
let mut components = components.into_components_vec();
ctx.try_automatic_conversions_slice(&mut components, &Tr::Handle(base), ty_span)?;
expr = crate::Expression::Compose { ty, components };
}
// Struct constructor
(
components,
Constructor::Type((ty, &crate::TypeInner::Struct { ref members, .. })),
) => {
let mut components = components.into_components_vec();
let struct_ty_span = ctx.module.types.get_span(ty);
// Make a vector of the members' type handles in advance, to
// avoid borrowing `members` from `ctx` while we generate
// new code.
let members: Vec<Handle<crate::Type>> = members.iter().map(|m| m.ty).collect();
for (component, &ty) in components.iter_mut().zip(&members) {
*component =
ctx.try_automatic_conversions(*component, &Tr::Handle(ty), struct_ty_span)?;
}
expr = crate::Expression::Compose { ty, components };
}
// ERRORS
// Bad conversion (type cast)
(Components::One { span, ty_inner, .. }, constructor) => {
let from_type = ty_inner.to_wgsl(&ctx.module.to_ctx()).into();
return Err(Error::BadTypeCast {
span,
from_type,
to_type: constructor.to_error_string(ctx).into(),
});
}
// Too many parameters for scalar constructor
(
Components::Many { spans, .. },
Constructor::Type((_, &crate::TypeInner::Scalar { .. })),
) => {
let span = spans[1].until(spans.last().unwrap());
return Err(Error::UnexpectedComponents(span));
}
// Other types can't be constructed
_ => return Err(Error::TypeNotConstructible(ty_span)),
}
let expr = ctx.append_expression(expr, span)?;
Ok(expr)
}
/// Build a [`Constructor`] for a WGSL construction expression.
///
/// If `constructor` conveys enough information to determine which Naga [`Type`]
/// we're actually building (i.e., it's not a partial constructor), then
/// ensure the `Type` exists in [`ctx.module`], and return
/// [`Constructor::Type`].
///
/// Otherwise, return the [`Constructor`] partial variant corresponding to
/// `constructor`.
///
/// [`Type`]: crate::Type
/// [`ctx.module`]: ExpressionContext::module
fn constructor<'out>(
&mut self,
constructor: &ast::ConstructorType<'source>,
ctx: &mut ExpressionContext<'source, '_, 'out>,
) -> Result<Constructor<Handle<crate::Type>>, Error<'source>> {
let handle = match *constructor {
ast::ConstructorType::Scalar(scalar) => {
let ty = ctx.ensure_type_exists(scalar.to_inner_scalar());
Constructor::Type(ty)
}
ast::ConstructorType::PartialVector { size } => Constructor::PartialVector { size },
ast::ConstructorType::Vector { size, ty, ty_span } => {
let ty = self.resolve_ast_type(ty, &mut ctx.as_global())?;
let scalar = match ctx.module.types[ty].inner {
crate::TypeInner::Scalar(sc) => sc,
_ => return Err(Error::UnknownScalarType(ty_span)),
};
let ty = ctx.ensure_type_exists(crate::TypeInner::Vector { size, scalar });
Constructor::Type(ty)
}
ast::ConstructorType::PartialMatrix { columns, rows } => {
Constructor::PartialMatrix { columns, rows }
}
ast::ConstructorType::Matrix {
rows,
columns,
ty,
ty_span,
} => {
let ty = self.resolve_ast_type(ty, &mut ctx.as_global())?;
let scalar = match ctx.module.types[ty].inner {
crate::TypeInner::Scalar(sc) => sc,
_ => return Err(Error::UnknownScalarType(ty_span)),
};
let ty = match scalar.kind {
crate::ScalarKind::Float => ctx.ensure_type_exists(crate::TypeInner::Matrix {
columns,
rows,
scalar,
}),
_ => return Err(Error::BadMatrixScalarKind(ty_span, scalar)),
};
Constructor::Type(ty)
}
ast::ConstructorType::PartialArray => Constructor::PartialArray,
ast::ConstructorType::Array { base, size } => {
let base = self.resolve_ast_type(base, &mut ctx.as_global())?;
let size = self.array_size(size, &mut ctx.as_global())?;
self.layouter.update(ctx.module.to_ctx()).unwrap();
let stride = self.layouter[base].to_stride();
let ty = ctx.ensure_type_exists(crate::TypeInner::Array { base, size, stride });
Constructor::Type(ty)
}
ast::ConstructorType::Type(ty) => Constructor::Type(ty),
};
Ok(handle)
}
}
+534
View File
@@ -0,0 +1,534 @@
//! WGSL's automatic conversions for abstract types.
use crate::front::wgsl::error::{
AutoConversionError, AutoConversionLeafScalarError, ConcretizationFailedError,
};
use crate::{Handle, Span};
impl<'source> super::ExpressionContext<'source, '_, '_> {
/// Try to use WGSL's automatic conversions to convert `expr` to `goal_ty`.
///
/// If no conversions are necessary, return `expr` unchanged.
///
/// If automatic conversions cannot convert `expr` to `goal_ty`, return an
/// [`AutoConversion`] error.
///
/// Although the Load Rule is one of the automatic conversions, this
/// function assumes it has already been applied if appropriate, as
/// indicated by the fact that the Rust type of `expr` is not `Typed<_>`.
///
/// [`AutoConversion`]: super::Error::AutoConversion
pub fn try_automatic_conversions(
&mut self,
expr: Handle<crate::Expression>,
goal_ty: &crate::proc::TypeResolution,
goal_span: Span,
) -> Result<Handle<crate::Expression>, super::Error<'source>> {
let expr_span = self.get_expression_span(expr);
// Keep the TypeResolution so we can get type names for
// structs in error messages.
let expr_resolution = super::resolve!(self, expr);
let types = &self.module.types;
let expr_inner = expr_resolution.inner_with(types);
let goal_inner = goal_ty.inner_with(types);
// If `expr` already has the requested type, we're done.
if expr_inner.equivalent(goal_inner, types) {
return Ok(expr);
}
let (_expr_scalar, goal_scalar) =
match expr_inner.automatically_converts_to(goal_inner, types) {
Some(scalars) => scalars,
None => {
let gctx = &self.module.to_ctx();
let source_type = expr_resolution.to_wgsl(gctx).into();
let dest_type = goal_ty.to_wgsl(gctx).into();
return Err(super::Error::AutoConversion(Box::new(
AutoConversionError {
dest_span: goal_span,
dest_type,
source_span: expr_span,
source_type,
},
)));
}
};
self.convert_leaf_scalar(expr, expr_span, goal_scalar)
}
/// Try to convert `expr`'s leaf scalar to `goal` using automatic conversions.
///
/// If no conversions are necessary, return `expr` unchanged.
///
/// If automatic conversions cannot convert `expr` to `goal_scalar`, return
/// an [`AutoConversionLeafScalar`] error.
///
/// Although the Load Rule is one of the automatic conversions, this
/// function assumes it has already been applied if appropriate, as
/// indicated by the fact that the Rust type of `expr` is not `Typed<_>`.
///
/// [`AutoConversionLeafScalar`]: super::Error::AutoConversionLeafScalar
pub fn try_automatic_conversion_for_leaf_scalar(
&mut self,
expr: Handle<crate::Expression>,
goal_scalar: crate::Scalar,
goal_span: Span,
) -> Result<Handle<crate::Expression>, super::Error<'source>> {
let expr_span = self.get_expression_span(expr);
let expr_resolution = super::resolve!(self, expr);
let types = &self.module.types;
let expr_inner = expr_resolution.inner_with(types);
let make_error = || {
let gctx = &self.module.to_ctx();
let source_type = expr_resolution.to_wgsl(gctx).into();
super::Error::AutoConversionLeafScalar(Box::new(AutoConversionLeafScalarError {
dest_span: goal_span,
dest_scalar: goal_scalar.to_wgsl().into(),
source_span: expr_span,
source_type,
}))
};
let expr_scalar = match expr_inner.automatically_convertible_scalar(&self.module.types) {
Some(scalar) => scalar,
None => return Err(make_error()),
};
if expr_scalar == goal_scalar {
return Ok(expr);
}
if !expr_scalar.automatically_converts_to(goal_scalar) {
return Err(make_error());
}
assert!(expr_scalar.is_abstract());
self.convert_leaf_scalar(expr, expr_span, goal_scalar)
}
fn convert_leaf_scalar(
&mut self,
expr: Handle<crate::Expression>,
expr_span: Span,
goal_scalar: crate::Scalar,
) -> Result<Handle<crate::Expression>, super::Error<'source>> {
let expr_inner = super::resolve_inner!(self, expr);
if let crate::TypeInner::Array { .. } = *expr_inner {
self.as_const_evaluator()
.cast_array(expr, goal_scalar, expr_span)
.map_err(|err| super::Error::ConstantEvaluatorError(err.into(), expr_span))
} else {
let cast = crate::Expression::As {
expr,
kind: goal_scalar.kind,
convert: Some(goal_scalar.width),
};
self.append_expression(cast, expr_span)
}
}
/// Try to convert `exprs` to `goal_ty` using WGSL's automatic conversions.
pub fn try_automatic_conversions_slice(
&mut self,
exprs: &mut [Handle<crate::Expression>],
goal_ty: &crate::proc::TypeResolution,
goal_span: Span,
) -> Result<(), super::Error<'source>> {
for expr in exprs.iter_mut() {
*expr = self.try_automatic_conversions(*expr, goal_ty, goal_span)?;
}
Ok(())
}
/// Apply WGSL's automatic conversions to a vector constructor's arguments.
///
/// When calling a vector constructor like `vec3<f32>(...)`, the parameters
/// can be a mix of scalars and vectors, with the latter being spread out to
/// contribute each of their components as a component of the new value.
/// When the element type is explicit, as with `<f32>` in the example above,
/// WGSL's automatic conversions should convert abstract scalar and vector
/// parameters to the constructor's required scalar type.
pub fn try_automatic_conversions_for_vector(
&mut self,
exprs: &mut [Handle<crate::Expression>],
goal_scalar: crate::Scalar,
goal_span: Span,
) -> Result<(), super::Error<'source>> {
use crate::proc::TypeResolution as Tr;
use crate::TypeInner as Ti;
let goal_scalar_res = Tr::Value(Ti::Scalar(goal_scalar));
for (i, expr) in exprs.iter_mut().enumerate() {
// Keep the TypeResolution so we can get full type names
// in error messages.
let expr_resolution = super::resolve!(self, *expr);
let types = &self.module.types;
let expr_inner = expr_resolution.inner_with(types);
match *expr_inner {
Ti::Scalar(_) => {
*expr = self.try_automatic_conversions(*expr, &goal_scalar_res, goal_span)?;
}
Ti::Vector { size, scalar: _ } => {
let goal_vector_res = Tr::Value(Ti::Vector {
size,
scalar: goal_scalar,
});
*expr = self.try_automatic_conversions(*expr, &goal_vector_res, goal_span)?;
}
_ => {
let span = self.get_expression_span(*expr);
return Err(super::Error::InvalidConstructorComponentType(
span, i as i32,
));
}
}
}
Ok(())
}
/// Convert `expr` to the leaf scalar type `scalar`.
pub fn convert_to_leaf_scalar(
&mut self,
expr: &mut Handle<crate::Expression>,
goal: crate::Scalar,
) -> Result<(), super::Error<'source>> {
let inner = super::resolve_inner!(self, *expr);
// Do nothing if `inner` doesn't even have leaf scalars;
// it's a type error that validation will catch.
if inner.scalar() != Some(goal) {
let cast = crate::Expression::As {
expr: *expr,
kind: goal.kind,
convert: Some(goal.width),
};
let expr_span = self.get_expression_span(*expr);
*expr = self.append_expression(cast, expr_span)?;
}
Ok(())
}
/// Convert all expressions in `exprs` to a common scalar type.
///
/// Note that the caller is responsible for making sure these
/// conversions are actually justified. This function simply
/// generates `As` expressions, regardless of whether they are
/// permitted WGSL automatic conversions. Callers intending to
/// implement automatic conversions need to determine for
/// themselves whether the casts we we generate are justified,
/// perhaps by calling `TypeInner::automatically_converts_to` or
/// `Scalar::automatic_conversion_combine`.
pub fn convert_slice_to_common_leaf_scalar(
&mut self,
exprs: &mut [Handle<crate::Expression>],
goal: crate::Scalar,
) -> Result<(), super::Error<'source>> {
for expr in exprs.iter_mut() {
self.convert_to_leaf_scalar(expr, goal)?;
}
Ok(())
}
/// Return an expression for the concretized value of `expr`.
///
/// If `expr` is already concrete, return it unchanged.
pub fn concretize(
&mut self,
mut expr: Handle<crate::Expression>,
) -> Result<Handle<crate::Expression>, super::Error<'source>> {
let inner = super::resolve_inner!(self, expr);
if let Some(scalar) = inner.automatically_convertible_scalar(&self.module.types) {
let concretized = scalar.concretize();
if concretized != scalar {
assert!(scalar.is_abstract());
let expr_span = self.get_expression_span(expr);
expr = self
.as_const_evaluator()
.cast_array(expr, concretized, expr_span)
.map_err(|err| {
// A `TypeResolution` includes the type's full name, if
// it has one. Also, avoid holding the borrow of `inner`
// across the call to `cast_array`.
let expr_type = &self.typifier()[expr];
super::Error::ConcretizationFailed(Box::new(ConcretizationFailedError {
expr_span,
expr_type: expr_type.to_wgsl(&self.module.to_ctx()).into(),
scalar: concretized.to_wgsl().into(),
inner: err,
}))
})?;
}
}
Ok(expr)
}
/// Find the consensus scalar of `components` under WGSL's automatic
/// conversions.
///
/// If `components` can all be converted to any common scalar via
/// WGSL's automatic conversions, return the best such scalar.
///
/// The `components` slice must not be empty. All elements' types must
/// have been resolved.
///
/// If `components` are definitely not acceptable as arguments to such
/// constructors, return `Err(i)`, where `i` is the index in
/// `components` of some problematic argument.
///
/// This function doesn't fully type-check the arguments - it only
/// considers their leaf scalar types. This means it may return `Ok`
/// even when the Naga validator will reject the resulting
/// construction expression later.
pub fn automatic_conversion_consensus<'handle, I>(
&self,
components: I,
) -> Result<crate::Scalar, usize>
where
I: IntoIterator<Item = &'handle Handle<crate::Expression>>,
I::IntoIter: Clone, // for debugging
{
let types = &self.module.types;
let mut inners = components
.into_iter()
.map(|&c| self.typifier()[c].inner_with(types));
log::debug!(
"wgsl automatic_conversion_consensus: {:?}",
inners
.clone()
.map(|inner| inner.to_wgsl(&self.module.to_ctx()))
.collect::<Vec<String>>()
);
let mut best = inners.next().unwrap().scalar().ok_or(0_usize)?;
for (inner, i) in inners.zip(1..) {
let scalar = inner.scalar().ok_or(i)?;
match best.automatic_conversion_combine(scalar) {
Some(new_best) => {
best = new_best;
}
None => return Err(i),
}
}
log::debug!(" consensus: {:?}", best.to_wgsl());
Ok(best)
}
}
impl crate::TypeInner {
/// Determine whether `self` automatically converts to `goal`.
///
/// If WGSL's automatic conversions (excluding the Load Rule) will
/// convert `self` to `goal`, then return a pair `(from, to)`,
/// where `from` and `to` are the scalar types of the leaf values
/// of `self` and `goal`.
///
/// This function assumes that `self` and `goal` are different
/// types. Callers should first check whether any conversion is
/// needed at all.
///
/// If the automatic conversions cannot convert `self` to `goal`,
/// return `None`.
fn automatically_converts_to(
&self,
goal: &Self,
types: &crate::UniqueArena<crate::Type>,
) -> Option<(crate::Scalar, crate::Scalar)> {
use crate::ScalarKind as Sk;
use crate::TypeInner as Ti;
// Automatic conversions only change the scalar type of a value's leaves
// (e.g., `vec4<AbstractFloat>` to `vec4<f32>`), never the type
// constructors applied to those scalar types (e.g., never scalar to
// `vec4`, or `vec2` to `vec3`). So first we check that the type
// constructors match, extracting the leaf scalar types in the process.
let expr_scalar;
let goal_scalar;
match (self, goal) {
(&Ti::Scalar(expr), &Ti::Scalar(goal)) => {
expr_scalar = expr;
goal_scalar = goal;
}
(
&Ti::Vector {
size: expr_size,
scalar: expr,
},
&Ti::Vector {
size: goal_size,
scalar: goal,
},
) if expr_size == goal_size => {
expr_scalar = expr;
goal_scalar = goal;
}
(
&Ti::Matrix {
rows: expr_rows,
columns: expr_columns,
scalar: expr,
},
&Ti::Matrix {
rows: goal_rows,
columns: goal_columns,
scalar: goal,
},
) if expr_rows == goal_rows && expr_columns == goal_columns => {
expr_scalar = expr;
goal_scalar = goal;
}
(
&Ti::Array {
base: expr_base,
size: expr_size,
stride: _,
},
&Ti::Array {
base: goal_base,
size: goal_size,
stride: _,
},
) if expr_size == goal_size => {
return types[expr_base]
.inner
.automatically_converts_to(&types[goal_base].inner, types);
}
_ => return None,
}
match (expr_scalar.kind, goal_scalar.kind) {
(Sk::AbstractFloat, Sk::Float) => {}
(Sk::AbstractInt, Sk::Sint | Sk::Uint | Sk::AbstractFloat | Sk::Float) => {}
_ => return None,
}
log::trace!(" okay: expr {expr_scalar:?}, goal {goal_scalar:?}");
Some((expr_scalar, goal_scalar))
}
fn automatically_convertible_scalar(
&self,
types: &crate::UniqueArena<crate::Type>,
) -> Option<crate::Scalar> {
use crate::TypeInner as Ti;
match *self {
Ti::Scalar(scalar) | Ti::Vector { scalar, .. } | Ti::Matrix { scalar, .. } => {
Some(scalar)
}
Ti::Array { base, .. } => types[base].inner.automatically_convertible_scalar(types),
Ti::Atomic(_)
| Ti::Pointer { .. }
| Ti::ValuePointer { .. }
| Ti::Struct { .. }
| Ti::Image { .. }
| Ti::Sampler { .. }
| Ti::AccelerationStructure
| Ti::RayQuery
| Ti::BindingArray { .. } => None,
}
}
/// Return the leaf scalar type of `pointer`.
///
/// `pointer` must be a `TypeInner` representing a pointer type.
pub fn pointer_automatically_convertible_scalar(
&self,
types: &crate::UniqueArena<crate::Type>,
) -> Option<crate::Scalar> {
use crate::TypeInner as Ti;
match *self {
Ti::Scalar(scalar) | Ti::Vector { scalar, .. } | Ti::Matrix { scalar, .. } => {
Some(scalar)
}
Ti::Atomic(_) => None,
Ti::Pointer { base, .. } | Ti::Array { base, .. } => {
types[base].inner.automatically_convertible_scalar(types)
}
Ti::ValuePointer { scalar, .. } => Some(scalar),
Ti::Struct { .. }
| Ti::Image { .. }
| Ti::Sampler { .. }
| Ti::AccelerationStructure
| Ti::RayQuery
| Ti::BindingArray { .. } => None,
}
}
}
impl crate::Scalar {
/// Find the common type of `self` and `other` under WGSL's
/// automatic conversions.
///
/// If there are any scalars to which WGSL's automatic conversions
/// will convert both `self` and `other`, return the best such
/// scalar. Otherwise, return `None`.
pub const fn automatic_conversion_combine(self, other: Self) -> Option<crate::Scalar> {
use crate::ScalarKind as Sk;
match (self.kind, other.kind) {
// When the kinds match...
(Sk::AbstractFloat, Sk::AbstractFloat)
| (Sk::AbstractInt, Sk::AbstractInt)
| (Sk::Sint, Sk::Sint)
| (Sk::Uint, Sk::Uint)
| (Sk::Float, Sk::Float)
| (Sk::Bool, Sk::Bool) => {
if self.width == other.width {
// ... either no conversion is necessary ...
Some(self)
} else {
// ... or no conversion is possible.
// We never convert concrete to concrete, and
// abstract types should have only one size.
None
}
}
// AbstractInt converts to AbstractFloat.
(Sk::AbstractFloat, Sk::AbstractInt) => Some(self),
(Sk::AbstractInt, Sk::AbstractFloat) => Some(other),
// AbstractFloat converts to Float.
(Sk::AbstractFloat, Sk::Float) => Some(other),
(Sk::Float, Sk::AbstractFloat) => Some(self),
// AbstractInt converts to concrete integer or float.
(Sk::AbstractInt, Sk::Uint | Sk::Sint | Sk::Float) => Some(other),
(Sk::Uint | Sk::Sint | Sk::Float, Sk::AbstractInt) => Some(self),
// AbstractFloat can't be reconciled with concrete integer types.
(Sk::AbstractFloat, Sk::Uint | Sk::Sint) | (Sk::Uint | Sk::Sint, Sk::AbstractFloat) => {
None
}
// Nothing can be reconciled with `bool`.
(Sk::Bool, _) | (_, Sk::Bool) => None,
// Different concrete types cannot be reconciled.
(Sk::Sint | Sk::Uint | Sk::Float, Sk::Sint | Sk::Uint | Sk::Float) => None,
}
}
/// Return `true` if automatic conversions will covert `self` to `goal`.
pub fn automatically_converts_to(self, goal: Self) -> bool {
self.automatic_conversion_combine(goal) == Some(goal)
}
const fn concretize(self) -> Self {
use crate::ScalarKind as Sk;
match self.kind {
Sk::Sint | Sk::Uint | Sk::Float | Sk::Bool => self,
Sk::AbstractInt => Self::I32,
Sk::AbstractFloat => Self::F32,
}
}
}
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
/*!
Frontend for [WGSL][wgsl] (WebGPU Shading Language).
[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html
*/
mod error;
mod index;
mod lower;
mod parse;
#[cfg(test)]
mod tests;
mod to_wgsl;
use crate::front::wgsl::error::Error;
use crate::front::wgsl::parse::Parser;
use thiserror::Error;
pub use crate::front::wgsl::error::ParseError;
use crate::front::wgsl::lower::Lowerer;
use crate::Scalar;
pub use crate::front::wgsl::parse::directive::language_extension::{
ImplementedLanguageExtension, LanguageExtension, UnimplementedLanguageExtension,
};
pub struct Frontend {
parser: Parser,
}
impl Frontend {
pub const fn new() -> Self {
Self {
parser: Parser::new(),
}
}
pub fn parse(&mut self, source: &str) -> Result<crate::Module, ParseError> {
self.inner(source).map_err(|x| x.as_parse_error(source))
}
fn inner<'a>(&mut self, source: &'a str) -> Result<crate::Module, Error<'a>> {
let tu = self.parser.parse(source)?;
let index = index::Index::generate(&tu)?;
let module = Lowerer::new(&index).lower(&tu)?;
Ok(module)
}
}
/// <div class="warning">
// NOTE: Keep this in sync with `wgpu::Device::create_shader_module`!
// NOTE: Keep this in sync with `wgpu_core::Global::device_create_shader_module`!
///
/// This function may consume a lot of stack space. Compiler-enforced limits for parsing recursion
/// exist; if shader compilation runs into them, it will return an error gracefully. However, on
/// some build profiles and platforms, the default stack size for a thread may be exceeded before
/// this limit is reached during parsing. Callers should ensure that there is enough stack space
/// for this, particularly if calls to this method are exposed to user input.
///
/// </div>
pub fn parse_str(source: &str) -> Result<crate::Module, ParseError> {
Frontend::new().parse(source)
}
#[cfg(test)]
#[track_caller]
pub fn assert_parse_err(input: &str, snapshot: &str) {
let output = parse_str(input)
.expect_err("expected parser error")
.emit_to_string(input);
if output != snapshot {
for diff in diff::lines(snapshot, &output) {
match diff {
diff::Result::Left(l) => println!("-{l}"),
diff::Result::Both(l, _) => println!(" {l}"),
diff::Result::Right(r) => println!("+{r}"),
}
}
panic!("Error snapshot failed");
}
}
+503
View File
@@ -0,0 +1,503 @@
use crate::diagnostic_filter::DiagnosticFilterNode;
use crate::front::wgsl::parse::directive::enable_extension::EnableExtensions;
use crate::front::wgsl::parse::number::Number;
use crate::front::wgsl::Scalar;
use crate::{Arena, FastIndexSet, Handle, Span};
use std::hash::Hash;
#[derive(Debug, Default)]
pub struct TranslationUnit<'a> {
pub enable_extensions: EnableExtensions,
pub decls: Arena<GlobalDecl<'a>>,
/// The common expressions arena for the entire translation unit.
///
/// All functions, global initializers, array lengths, etc. store their
/// expressions here. We apportion these out to individual Naga
/// [`Function`]s' expression arenas at lowering time. Keeping them all in a
/// single arena simplifies handling of things like array lengths (which are
/// effectively global and thus don't clearly belong to any function) and
/// initializers (which can appear in both function-local and module-scope
/// contexts).
///
/// [`Function`]: crate::Function
pub expressions: Arena<Expression<'a>>,
/// Non-user-defined types, like `vec4<f32>` or `array<i32, 10>`.
///
/// These are referred to by `Handle<ast::Type<'a>>` values.
/// User-defined types are referred to by name until lowering.
pub types: Arena<Type<'a>>,
/// Arena for all diagnostic filter rules parsed in this module, including those in functions.
///
/// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
/// validation.
pub diagnostic_filters: Arena<DiagnosticFilterNode>,
/// The leaf of all `diagnostic(…)` directives in this module.
///
/// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
/// validation.
pub diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
}
#[derive(Debug, Clone, Copy)]
pub struct Ident<'a> {
pub name: &'a str,
pub span: Span,
}
#[derive(Debug)]
pub enum IdentExpr<'a> {
Unresolved(&'a str),
Local(Handle<Local>),
}
/// A reference to a module-scope definition or predeclared object.
///
/// Each [`GlobalDecl`] holds a set of these values, to be resolved to
/// specific definitions later. To support de-duplication, `Eq` and
/// `Hash` on a `Dependency` value consider only the name, not the
/// source location at which the reference occurs.
#[derive(Debug)]
pub struct Dependency<'a> {
/// The name referred to.
pub ident: &'a str,
/// The location at which the reference to that name occurs.
pub usage: Span,
}
impl Hash for Dependency<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.ident.hash(state);
}
}
impl PartialEq for Dependency<'_> {
fn eq(&self, other: &Self) -> bool {
self.ident == other.ident
}
}
impl Eq for Dependency<'_> {}
/// A module-scope declaration.
#[derive(Debug)]
pub struct GlobalDecl<'a> {
pub kind: GlobalDeclKind<'a>,
/// Names of all module-scope or predeclared objects this
/// declaration uses.
pub dependencies: FastIndexSet<Dependency<'a>>,
}
#[derive(Debug)]
pub enum GlobalDeclKind<'a> {
Fn(Function<'a>),
Var(GlobalVariable<'a>),
Const(Const<'a>),
Override(Override<'a>),
Struct(Struct<'a>),
Type(TypeAlias<'a>),
ConstAssert(Handle<Expression<'a>>),
}
#[derive(Debug)]
pub struct FunctionArgument<'a> {
pub name: Ident<'a>,
pub ty: Handle<Type<'a>>,
pub binding: Option<Binding<'a>>,
pub handle: Handle<Local>,
}
#[derive(Debug)]
pub struct FunctionResult<'a> {
pub ty: Handle<Type<'a>>,
pub binding: Option<Binding<'a>>,
}
#[derive(Debug)]
pub struct EntryPoint<'a> {
pub stage: crate::ShaderStage,
pub early_depth_test: Option<crate::EarlyDepthTest>,
pub workgroup_size: Option<[Option<Handle<Expression<'a>>>; 3]>,
}
#[cfg(doc)]
use crate::front::wgsl::lower::{LocalExpressionContext, StatementContext};
#[derive(Debug)]
pub struct Function<'a> {
pub entry_point: Option<EntryPoint<'a>>,
pub name: Ident<'a>,
pub arguments: Vec<FunctionArgument<'a>>,
pub result: Option<FunctionResult<'a>>,
pub body: Block<'a>,
pub diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
}
#[derive(Debug)]
pub enum Binding<'a> {
BuiltIn(crate::BuiltIn),
Location {
location: Handle<Expression<'a>>,
second_blend_source: bool,
interpolation: Option<crate::Interpolation>,
sampling: Option<crate::Sampling>,
},
}
#[derive(Debug)]
pub struct ResourceBinding<'a> {
pub group: Handle<Expression<'a>>,
pub binding: Handle<Expression<'a>>,
}
#[derive(Debug)]
pub struct GlobalVariable<'a> {
pub name: Ident<'a>,
pub space: crate::AddressSpace,
pub binding: Option<ResourceBinding<'a>>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Option<Handle<Expression<'a>>>,
}
#[derive(Debug)]
pub struct StructMember<'a> {
pub name: Ident<'a>,
pub ty: Handle<Type<'a>>,
pub binding: Option<Binding<'a>>,
pub align: Option<Handle<Expression<'a>>>,
pub size: Option<Handle<Expression<'a>>>,
}
#[derive(Debug)]
pub struct Struct<'a> {
pub name: Ident<'a>,
pub members: Vec<StructMember<'a>>,
}
#[derive(Debug)]
pub struct TypeAlias<'a> {
pub name: Ident<'a>,
pub ty: Handle<Type<'a>>,
}
#[derive(Debug)]
pub struct Const<'a> {
pub name: Ident<'a>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Handle<Expression<'a>>,
}
#[derive(Debug)]
pub struct Override<'a> {
pub name: Ident<'a>,
pub id: Option<Handle<Expression<'a>>>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Option<Handle<Expression<'a>>>,
}
/// The size of an [`Array`] or [`BindingArray`].
///
/// [`Array`]: Type::Array
/// [`BindingArray`]: Type::BindingArray
#[derive(Debug, Copy, Clone)]
pub enum ArraySize<'a> {
/// The length as a constant expression.
Constant(Handle<Expression<'a>>),
Dynamic,
}
#[derive(Debug)]
pub enum Type<'a> {
Scalar(Scalar),
Vector {
size: crate::VectorSize,
ty: Handle<Type<'a>>,
ty_span: Span,
},
Matrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
ty: Handle<Type<'a>>,
ty_span: Span,
},
Atomic(Scalar),
Pointer {
base: Handle<Type<'a>>,
space: crate::AddressSpace,
},
Array {
base: Handle<Type<'a>>,
size: ArraySize<'a>,
},
Image {
dim: crate::ImageDimension,
arrayed: bool,
class: crate::ImageClass,
},
Sampler {
comparison: bool,
},
AccelerationStructure,
RayQuery,
RayDesc,
RayIntersection,
BindingArray {
base: Handle<Type<'a>>,
size: ArraySize<'a>,
},
/// A user-defined type, like a struct or a type alias.
User(Ident<'a>),
}
#[derive(Debug, Default)]
pub struct Block<'a> {
pub stmts: Vec<Statement<'a>>,
}
#[derive(Debug)]
pub struct Statement<'a> {
pub kind: StatementKind<'a>,
pub span: Span,
}
#[derive(Debug)]
pub enum StatementKind<'a> {
LocalDecl(LocalDecl<'a>),
Block(Block<'a>),
If {
condition: Handle<Expression<'a>>,
accept: Block<'a>,
reject: Block<'a>,
},
Switch {
selector: Handle<Expression<'a>>,
cases: Vec<SwitchCase<'a>>,
},
Loop {
body: Block<'a>,
continuing: Block<'a>,
break_if: Option<Handle<Expression<'a>>>,
},
Break,
Continue,
Return {
value: Option<Handle<Expression<'a>>>,
},
Kill,
Call {
function: Ident<'a>,
arguments: Vec<Handle<Expression<'a>>>,
},
Assign {
target: Handle<Expression<'a>>,
op: Option<crate::BinaryOperator>,
value: Handle<Expression<'a>>,
},
Increment(Handle<Expression<'a>>),
Decrement(Handle<Expression<'a>>),
Phony(Handle<Expression<'a>>),
ConstAssert(Handle<Expression<'a>>),
}
#[derive(Debug)]
pub enum SwitchValue<'a> {
Expr(Handle<Expression<'a>>),
Default,
}
#[derive(Debug)]
pub struct SwitchCase<'a> {
pub value: SwitchValue<'a>,
pub body: Block<'a>,
pub fall_through: bool,
}
/// A type at the head of a [`Construct`] expression.
///
/// WGSL has two types of [`type constructor expressions`]:
///
/// - Those that fully specify the type being constructed, like
/// `vec3<f32>(x,y,z)`, which obviously constructs a `vec3<f32>`.
///
/// - Those that leave the component type of the composite being constructed
/// implicit, to be inferred from the argument types, like `vec3(x,y,z)`,
/// which constructs a `vec3<T>` where `T` is the type of `x`, `y`, and `z`.
///
/// This enum represents the head type of both cases. The `PartialFoo` variants
/// represent the second case, where the component type is implicit.
///
/// This does not cover structs or types referred to by type aliases. See the
/// documentation for [`Construct`] and [`Call`] expressions for details.
///
/// [`Construct`]: Expression::Construct
/// [`type constructor expressions`]: https://gpuweb.github.io/gpuweb/wgsl/#type-constructor-expr
/// [`Call`]: Expression::Call
#[derive(Debug)]
pub enum ConstructorType<'a> {
/// A scalar type or conversion: `f32(1)`.
Scalar(Scalar),
/// A vector construction whose component type is inferred from the
/// argument: `vec3(1.0)`.
PartialVector { size: crate::VectorSize },
/// A vector construction whose component type is written out:
/// `vec3<f32>(1.0)`.
Vector {
size: crate::VectorSize,
ty: Handle<Type<'a>>,
ty_span: Span,
},
/// A matrix construction whose component type is inferred from the
/// argument: `mat2x2(1,2,3,4)`.
PartialMatrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
},
/// A matrix construction whose component type is written out:
/// `mat2x2<f32>(1,2,3,4)`.
Matrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
ty: Handle<Type<'a>>,
ty_span: Span,
},
/// An array whose component type and size are inferred from the arguments:
/// `array(3,4,5)`.
PartialArray,
/// An array whose component type and size are written out:
/// `array<u32, 4>(3,4,5)`.
Array {
base: Handle<Type<'a>>,
size: ArraySize<'a>,
},
/// Constructing a value of a known Naga IR type.
///
/// This variant is produced only during lowering, when we have Naga types
/// available, never during parsing.
Type(Handle<crate::Type>),
}
#[derive(Debug, Copy, Clone)]
pub enum Literal {
Bool(bool),
Number(Number),
}
#[cfg(doc)]
use crate::front::wgsl::lower::Lowerer;
#[derive(Debug)]
pub enum Expression<'a> {
Literal(Literal),
Ident(IdentExpr<'a>),
/// A type constructor expression.
///
/// This is only used for expressions like `KEYWORD(EXPR...)` and
/// `KEYWORD<PARAM>(EXPR...)`, where `KEYWORD` is a [type-defining keyword] like
/// `vec3`. These keywords cannot be shadowed by user definitions, so we can
/// tell that such an expression is a construction immediately.
///
/// For ordinary identifiers, we can't tell whether an expression like
/// `IDENTIFIER(EXPR, ...)` is a construction expression or a function call
/// until we know `IDENTIFIER`'s definition, so we represent those as
/// [`Call`] expressions.
///
/// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords
/// [`Call`]: Expression::Call
Construct {
ty: ConstructorType<'a>,
ty_span: Span,
components: Vec<Handle<Expression<'a>>>,
},
Unary {
op: crate::UnaryOperator,
expr: Handle<Expression<'a>>,
},
AddrOf(Handle<Expression<'a>>),
Deref(Handle<Expression<'a>>),
Binary {
op: crate::BinaryOperator,
left: Handle<Expression<'a>>,
right: Handle<Expression<'a>>,
},
/// A function call or type constructor expression.
///
/// We can't tell whether an expression like `IDENTIFIER(EXPR, ...)` is a
/// construction expression or a function call until we know `IDENTIFIER`'s
/// definition, so we represent everything of that form as one of these
/// expressions until lowering. At that point, [`Lowerer::call`] has
/// everything's definition in hand, and can decide whether to emit a Naga
/// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression.
///
/// [`Lowerer::call`]: Lowerer::call
/// [`Constant`]: crate::Expression::Constant
/// [`As`]: crate::Expression::As
/// [`Splat`]: crate::Expression::Splat
/// [`Compose`]: crate::Expression::Compose
Call {
function: Ident<'a>,
arguments: Vec<Handle<Expression<'a>>>,
},
Index {
base: Handle<Expression<'a>>,
index: Handle<Expression<'a>>,
},
Member {
base: Handle<Expression<'a>>,
field: Ident<'a>,
},
Bitcast {
expr: Handle<Expression<'a>>,
to: Handle<Type<'a>>,
ty_span: Span,
},
}
#[derive(Debug)]
pub struct LocalVariable<'a> {
pub name: Ident<'a>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Option<Handle<Expression<'a>>>,
pub handle: Handle<Local>,
}
#[derive(Debug)]
pub struct Let<'a> {
pub name: Ident<'a>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Handle<Expression<'a>>,
pub handle: Handle<Local>,
}
#[derive(Debug)]
pub struct LocalConst<'a> {
pub name: Ident<'a>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Handle<Expression<'a>>,
pub handle: Handle<Local>,
}
#[derive(Debug)]
pub enum LocalDecl<'a> {
Var(LocalVariable<'a>),
Let(Let<'a>),
Const(LocalConst<'a>),
}
#[derive(Debug)]
/// A placeholder for a local variable declaration.
///
/// See [`super::ExpressionContext::locals`] for more information.
pub struct Local;
+298
View File
@@ -0,0 +1,298 @@
use super::Error;
use crate::front::wgsl::Scalar;
use crate::Span;
pub fn map_address_space(word: &str, span: Span) -> Result<crate::AddressSpace, Error<'_>> {
match word {
"private" => Ok(crate::AddressSpace::Private),
"workgroup" => Ok(crate::AddressSpace::WorkGroup),
"uniform" => Ok(crate::AddressSpace::Uniform),
"storage" => Ok(crate::AddressSpace::Storage {
access: crate::StorageAccess::default(),
}),
"push_constant" => Ok(crate::AddressSpace::PushConstant),
"function" => Ok(crate::AddressSpace::Function),
_ => Err(Error::UnknownAddressSpace(span)),
}
}
pub fn map_built_in(word: &str, span: Span) -> Result<crate::BuiltIn, Error<'_>> {
Ok(match word {
"position" => crate::BuiltIn::Position { invariant: false },
// vertex
"vertex_index" => crate::BuiltIn::VertexIndex,
"instance_index" => crate::BuiltIn::InstanceIndex,
"view_index" => crate::BuiltIn::ViewIndex,
// fragment
"front_facing" => crate::BuiltIn::FrontFacing,
"frag_depth" => crate::BuiltIn::FragDepth,
"primitive_index" => crate::BuiltIn::PrimitiveIndex,
"sample_index" => crate::BuiltIn::SampleIndex,
"sample_mask" => crate::BuiltIn::SampleMask,
// compute
"global_invocation_id" => crate::BuiltIn::GlobalInvocationId,
"local_invocation_id" => crate::BuiltIn::LocalInvocationId,
"local_invocation_index" => crate::BuiltIn::LocalInvocationIndex,
"workgroup_id" => crate::BuiltIn::WorkGroupId,
"num_workgroups" => crate::BuiltIn::NumWorkGroups,
// subgroup
"num_subgroups" => crate::BuiltIn::NumSubgroups,
"subgroup_id" => crate::BuiltIn::SubgroupId,
"subgroup_size" => crate::BuiltIn::SubgroupSize,
"subgroup_invocation_id" => crate::BuiltIn::SubgroupInvocationId,
_ => return Err(Error::UnknownBuiltin(span)),
})
}
pub fn map_interpolation(word: &str, span: Span) -> Result<crate::Interpolation, Error<'_>> {
match word {
"linear" => Ok(crate::Interpolation::Linear),
"flat" => Ok(crate::Interpolation::Flat),
"perspective" => Ok(crate::Interpolation::Perspective),
_ => Err(Error::UnknownAttribute(span)),
}
}
pub fn map_sampling(word: &str, span: Span) -> Result<crate::Sampling, Error<'_>> {
match word {
"center" => Ok(crate::Sampling::Center),
"centroid" => Ok(crate::Sampling::Centroid),
"sample" => Ok(crate::Sampling::Sample),
"first" => Ok(crate::Sampling::First),
"either" => Ok(crate::Sampling::Either),
_ => Err(Error::UnknownAttribute(span)),
}
}
pub fn map_storage_format(word: &str, span: Span) -> Result<crate::StorageFormat, Error<'_>> {
use crate::StorageFormat as Sf;
Ok(match word {
"r8unorm" => Sf::R8Unorm,
"r8snorm" => Sf::R8Snorm,
"r8uint" => Sf::R8Uint,
"r8sint" => Sf::R8Sint,
"r16unorm" => Sf::R16Unorm,
"r16snorm" => Sf::R16Snorm,
"r16uint" => Sf::R16Uint,
"r16sint" => Sf::R16Sint,
"r16float" => Sf::R16Float,
"rg8unorm" => Sf::Rg8Unorm,
"rg8snorm" => Sf::Rg8Snorm,
"rg8uint" => Sf::Rg8Uint,
"rg8sint" => Sf::Rg8Sint,
"r32uint" => Sf::R32Uint,
"r32sint" => Sf::R32Sint,
"r32float" => Sf::R32Float,
"rg16unorm" => Sf::Rg16Unorm,
"rg16snorm" => Sf::Rg16Snorm,
"rg16uint" => Sf::Rg16Uint,
"rg16sint" => Sf::Rg16Sint,
"rg16float" => Sf::Rg16Float,
"rgba8unorm" => Sf::Rgba8Unorm,
"rgba8snorm" => Sf::Rgba8Snorm,
"rgba8uint" => Sf::Rgba8Uint,
"rgba8sint" => Sf::Rgba8Sint,
"rgb10a2uint" => Sf::Rgb10a2Uint,
"rgb10a2unorm" => Sf::Rgb10a2Unorm,
"rg11b10float" => Sf::Rg11b10Ufloat,
"r64uint" => Sf::R64Uint,
"rg32uint" => Sf::Rg32Uint,
"rg32sint" => Sf::Rg32Sint,
"rg32float" => Sf::Rg32Float,
"rgba16unorm" => Sf::Rgba16Unorm,
"rgba16snorm" => Sf::Rgba16Snorm,
"rgba16uint" => Sf::Rgba16Uint,
"rgba16sint" => Sf::Rgba16Sint,
"rgba16float" => Sf::Rgba16Float,
"rgba32uint" => Sf::Rgba32Uint,
"rgba32sint" => Sf::Rgba32Sint,
"rgba32float" => Sf::Rgba32Float,
"bgra8unorm" => Sf::Bgra8Unorm,
_ => return Err(Error::UnknownStorageFormat(span)),
})
}
pub fn get_scalar_type(word: &str) -> Option<Scalar> {
use crate::ScalarKind as Sk;
match word {
// "f16" => Some(Scalar { kind: Sk::Float, width: 2 }),
"f32" => Some(Scalar {
kind: Sk::Float,
width: 4,
}),
"f64" => Some(Scalar {
kind: Sk::Float,
width: 8,
}),
"i32" => Some(Scalar {
kind: Sk::Sint,
width: 4,
}),
"u32" => Some(Scalar {
kind: Sk::Uint,
width: 4,
}),
"i64" => Some(Scalar {
kind: Sk::Sint,
width: 8,
}),
"u64" => Some(Scalar {
kind: Sk::Uint,
width: 8,
}),
"bool" => Some(Scalar {
kind: Sk::Bool,
width: crate::BOOL_WIDTH,
}),
_ => None,
}
}
pub fn map_derivative(word: &str) -> Option<(crate::DerivativeAxis, crate::DerivativeControl)> {
use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
match word {
"dpdxCoarse" => Some((Axis::X, Ctrl::Coarse)),
"dpdyCoarse" => Some((Axis::Y, Ctrl::Coarse)),
"fwidthCoarse" => Some((Axis::Width, Ctrl::Coarse)),
"dpdxFine" => Some((Axis::X, Ctrl::Fine)),
"dpdyFine" => Some((Axis::Y, Ctrl::Fine)),
"fwidthFine" => Some((Axis::Width, Ctrl::Fine)),
"dpdx" => Some((Axis::X, Ctrl::None)),
"dpdy" => Some((Axis::Y, Ctrl::None)),
"fwidth" => Some((Axis::Width, Ctrl::None)),
_ => None,
}
}
pub fn map_relational_fun(word: &str) -> Option<crate::RelationalFunction> {
match word {
"any" => Some(crate::RelationalFunction::Any),
"all" => Some(crate::RelationalFunction::All),
_ => None,
}
}
pub fn map_standard_fun(word: &str) -> Option<crate::MathFunction> {
use crate::MathFunction as Mf;
Some(match word {
// comparison
"abs" => Mf::Abs,
"min" => Mf::Min,
"max" => Mf::Max,
"clamp" => Mf::Clamp,
"saturate" => Mf::Saturate,
// trigonometry
"cos" => Mf::Cos,
"cosh" => Mf::Cosh,
"sin" => Mf::Sin,
"sinh" => Mf::Sinh,
"tan" => Mf::Tan,
"tanh" => Mf::Tanh,
"acos" => Mf::Acos,
"acosh" => Mf::Acosh,
"asin" => Mf::Asin,
"asinh" => Mf::Asinh,
"atan" => Mf::Atan,
"atanh" => Mf::Atanh,
"atan2" => Mf::Atan2,
"radians" => Mf::Radians,
"degrees" => Mf::Degrees,
// decomposition
"ceil" => Mf::Ceil,
"floor" => Mf::Floor,
"round" => Mf::Round,
"fract" => Mf::Fract,
"trunc" => Mf::Trunc,
"modf" => Mf::Modf,
"frexp" => Mf::Frexp,
"ldexp" => Mf::Ldexp,
// exponent
"exp" => Mf::Exp,
"exp2" => Mf::Exp2,
"log" => Mf::Log,
"log2" => Mf::Log2,
"pow" => Mf::Pow,
// geometry
"dot" => Mf::Dot,
"cross" => Mf::Cross,
"distance" => Mf::Distance,
"length" => Mf::Length,
"normalize" => Mf::Normalize,
"faceForward" => Mf::FaceForward,
"reflect" => Mf::Reflect,
"refract" => Mf::Refract,
// computational
"sign" => Mf::Sign,
"fma" => Mf::Fma,
"mix" => Mf::Mix,
"step" => Mf::Step,
"smoothstep" => Mf::SmoothStep,
"sqrt" => Mf::Sqrt,
"inverseSqrt" => Mf::InverseSqrt,
"transpose" => Mf::Transpose,
"determinant" => Mf::Determinant,
"quantizeToF16" => Mf::QuantizeToF16,
// bits
"countTrailingZeros" => Mf::CountTrailingZeros,
"countLeadingZeros" => Mf::CountLeadingZeros,
"countOneBits" => Mf::CountOneBits,
"reverseBits" => Mf::ReverseBits,
"extractBits" => Mf::ExtractBits,
"insertBits" => Mf::InsertBits,
"firstTrailingBit" => Mf::FirstTrailingBit,
"firstLeadingBit" => Mf::FirstLeadingBit,
// data packing
"pack4x8snorm" => Mf::Pack4x8snorm,
"pack4x8unorm" => Mf::Pack4x8unorm,
"pack2x16snorm" => Mf::Pack2x16snorm,
"pack2x16unorm" => Mf::Pack2x16unorm,
"pack2x16float" => Mf::Pack2x16float,
"pack4xI8" => Mf::Pack4xI8,
"pack4xU8" => Mf::Pack4xU8,
// data unpacking
"unpack4x8snorm" => Mf::Unpack4x8snorm,
"unpack4x8unorm" => Mf::Unpack4x8unorm,
"unpack2x16snorm" => Mf::Unpack2x16snorm,
"unpack2x16unorm" => Mf::Unpack2x16unorm,
"unpack2x16float" => Mf::Unpack2x16float,
"unpack4xI8" => Mf::Unpack4xI8,
"unpack4xU8" => Mf::Unpack4xU8,
_ => return None,
})
}
pub fn map_conservative_depth(
word: &str,
span: Span,
) -> Result<crate::ConservativeDepth, Error<'_>> {
use crate::ConservativeDepth as Cd;
match word {
"greater_equal" => Ok(Cd::GreaterEqual),
"less_equal" => Ok(Cd::LessEqual),
"unchanged" => Ok(Cd::Unchanged),
_ => Err(Error::UnknownConservativeDepth(span)),
}
}
pub fn map_subgroup_operation(
word: &str,
) -> Option<(crate::SubgroupOperation, crate::CollectiveOperation)> {
use crate::CollectiveOperation as co;
use crate::SubgroupOperation as sg;
Some(match word {
"subgroupAll" => (sg::All, co::Reduce),
"subgroupAny" => (sg::Any, co::Reduce),
"subgroupAdd" => (sg::Add, co::Reduce),
"subgroupMul" => (sg::Mul, co::Reduce),
"subgroupMin" => (sg::Min, co::Reduce),
"subgroupMax" => (sg::Max, co::Reduce),
"subgroupAnd" => (sg::And, co::Reduce),
"subgroupOr" => (sg::Or, co::Reduce),
"subgroupXor" => (sg::Xor, co::Reduce),
"subgroupExclusiveAdd" => (sg::Add, co::ExclusiveScan),
"subgroupExclusiveMul" => (sg::Mul, co::ExclusiveScan),
"subgroupInclusiveAdd" => (sg::Add, co::InclusiveScan),
"subgroupInclusiveMul" => (sg::Mul, co::InclusiveScan),
_ => return None,
})
}
+114
View File
@@ -0,0 +1,114 @@
//! WGSL directives. The focal point of this API is [`DirectiveKind`].
//!
//! See also <https://www.w3.org/TR/WGSL/#directives>.
pub mod enable_extension;
pub(crate) mod language_extension;
/// A parsed sentinel word indicating the type of directive to be parsed next.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(test, derive(strum::EnumIter))]
pub(crate) enum DirectiveKind {
/// A [`crate::diagnostic_filter`].
Diagnostic,
/// An [`enable_extension`].
Enable,
/// A [`language_extension`].
Requires,
}
impl DirectiveKind {
const DIAGNOSTIC: &'static str = "diagnostic";
const ENABLE: &'static str = "enable";
const REQUIRES: &'static str = "requires";
/// Convert from a sentinel word in WGSL into its associated [`DirectiveKind`], if possible.
pub fn from_ident(s: &str) -> Option<Self> {
Some(match s {
Self::DIAGNOSTIC => Self::Diagnostic,
Self::ENABLE => Self::Enable,
Self::REQUIRES => Self::Requires,
_ => return None,
})
}
}
impl crate::diagnostic_filter::Severity {
#[cfg(feature = "wgsl-in")]
pub(crate) fn report_wgsl_parse_diag<'a>(
self,
err: crate::front::wgsl::error::Error<'a>,
source: &str,
) -> Result<(), crate::front::wgsl::error::Error<'a>> {
self.report_diag(err, |e, level| {
let e = e.as_parse_error(source);
log::log!(level, "{}", e.emit_to_string(source));
})
}
}
#[cfg(test)]
mod test {
use strum::IntoEnumIterator;
use crate::front::wgsl::assert_parse_err;
use super::DirectiveKind;
#[test]
fn directive_after_global_decl() {
for unsupported_shader in DirectiveKind::iter() {
let directive;
let expected_msg;
match unsupported_shader {
DirectiveKind::Diagnostic => {
directive = "diagnostic(off,derivative_uniformity)";
expected_msg = "\
error: expected global declaration, but found a global directive
┌─ wgsl:2:1
│
2 │ diagnostic(off,derivative_uniformity);
│ ^^^^^^^^^^ written after first global declaration
│
= note: global directives are only allowed before global declarations; maybe hoist this closer to the top of the shader module?
";
}
DirectiveKind::Enable => {
directive = "enable f16";
expected_msg = "\
error: expected global declaration, but found a global directive
┌─ wgsl:2:1
│
2 │ enable f16;
│ ^^^^^^ written after first global declaration
│
= note: global directives are only allowed before global declarations; maybe hoist this closer to the top of the shader module?
";
}
DirectiveKind::Requires => {
directive = "requires readonly_and_readwrite_storage_textures";
expected_msg = "\
error: expected global declaration, but found a global directive
┌─ wgsl:2:1
│
2 │ requires readonly_and_readwrite_storage_textures;
│ ^^^^^^^^ written after first global declaration
│
= note: global directives are only allowed before global declarations; maybe hoist this closer to the top of the shader module?
";
}
}
let shader = format!(
"\
@group(0) @binding(0) var<storage> thing: i32;
{directive};
"
);
assert_parse_err(&shader, expected_msg);
}
}
}
@@ -0,0 +1,112 @@
//! `enable …;` extensions in WGSL.
//!
//! The focal point of this module is the [`EnableExtension`] API.
use crate::{front::wgsl::error::Error, Span};
/// Tracks the status of every enable-extension known to Naga.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnableExtensions {}
impl EnableExtensions {
pub(crate) const fn empty() -> Self {
Self {}
}
/// Add an enable-extension to the set requested by a module.
#[allow(unreachable_code)]
pub(crate) fn add(&mut self, ext: ImplementedEnableExtension) {
let _field: &mut bool = match ext {};
*_field = true;
}
/// Query whether an enable-extension tracked here has been requested.
#[allow(unused)]
pub(crate) const fn contains(&self, ext: ImplementedEnableExtension) -> bool {
match ext {}
}
}
impl Default for EnableExtensions {
fn default() -> Self {
Self::empty()
}
}
/// An enable-extension not guaranteed to be present in all environments.
///
/// WGSL spec.: <https://www.w3.org/TR/WGSL/#enable-extensions-sec>
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum EnableExtension {
#[allow(unused)]
Implemented(ImplementedEnableExtension),
Unimplemented(UnimplementedEnableExtension),
}
impl EnableExtension {
const F16: &'static str = "f16";
const CLIP_DISTANCES: &'static str = "clip_distances";
const DUAL_SOURCE_BLENDING: &'static str = "dual_source_blending";
/// Convert from a sentinel word in WGSL into its associated [`EnableExtension`], if possible.
pub(crate) fn from_ident(word: &str, span: Span) -> Result<Self, Error<'_>> {
Ok(match word {
Self::F16 => Self::Unimplemented(UnimplementedEnableExtension::F16),
Self::CLIP_DISTANCES => {
Self::Unimplemented(UnimplementedEnableExtension::ClipDistances)
}
Self::DUAL_SOURCE_BLENDING => {
Self::Unimplemented(UnimplementedEnableExtension::DualSourceBlending)
}
_ => return Err(Error::UnknownEnableExtension(span, word)),
})
}
/// Maps this [`EnableExtension`] into the sentinel word associated with it in WGSL.
pub const fn to_ident(self) -> &'static str {
match self {
Self::Implemented(kind) => match kind {},
Self::Unimplemented(kind) => match kind {
UnimplementedEnableExtension::F16 => Self::F16,
UnimplementedEnableExtension::ClipDistances => Self::CLIP_DISTANCES,
UnimplementedEnableExtension::DualSourceBlending => Self::DUAL_SOURCE_BLENDING,
},
}
}
}
/// A variant of [`EnableExtension::Implemented`].
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum ImplementedEnableExtension {}
/// A variant of [`EnableExtension::Unimplemented`].
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum UnimplementedEnableExtension {
/// Enables `f16`/`half` primitive support in all shader languages.
///
/// In the WGSL standard, this corresponds to [`enable f16;`].
///
/// [`enable f16;`]: https://www.w3.org/TR/WGSL/#extension-f16
F16,
/// Enables the `clip_distances` variable in WGSL.
///
/// In the WGSL standard, this corresponds to [`enable clip_distances;`].
///
/// [`enable clip_distances;`]: https://www.w3.org/TR/WGSL/#extension-f16
ClipDistances,
/// Enables the `blend_src` attribute in WGSL.
///
/// In the WGSL standard, this corresponds to [`enable dual_source_blending;`].
///
/// [`enable dual_source_blending;`]: https://www.w3.org/TR/WGSL/#extension-f16
DualSourceBlending,
}
impl UnimplementedEnableExtension {
pub(crate) const fn tracking_issue_num(self) -> u16 {
match self {
Self::F16 => 4384,
Self::ClipDistances => 6236,
Self::DualSourceBlending => 6402,
}
}
}
@@ -0,0 +1,99 @@
//! `requires …;` extensions in WGSL.
//!
//! The focal point of this module is the [`LanguageExtension`] API.
use strum::VariantArray;
/// A language extension recognized by Naga, but not guaranteed to be present in all environments.
///
/// WGSL spec.: <https://www.w3.org/TR/WGSL/#language-extensions-sec>
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LanguageExtension {
#[allow(unused)]
Implemented(ImplementedLanguageExtension),
Unimplemented(UnimplementedLanguageExtension),
}
impl LanguageExtension {
const READONLY_AND_READWRITE_STORAGE_TEXTURES: &'static str =
"readonly_and_readwrite_storage_textures";
const PACKED4X8_INTEGER_DOT_PRODUCT: &'static str = "packed_4x8_integer_dot_product";
const UNRESTRICTED_POINTER_PARAMETERS: &'static str = "unrestricted_pointer_parameters";
const POINTER_COMPOSITE_ACCESS: &'static str = "pointer_composite_access";
/// Convert from a sentinel word in WGSL into its associated [`LanguageExtension`], if possible.
pub fn from_ident(s: &str) -> Option<Self> {
Some(match s {
Self::READONLY_AND_READWRITE_STORAGE_TEXTURES => Self::Unimplemented(
UnimplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures,
),
Self::PACKED4X8_INTEGER_DOT_PRODUCT => {
Self::Unimplemented(UnimplementedLanguageExtension::Packed4x8IntegerDotProduct)
}
Self::UNRESTRICTED_POINTER_PARAMETERS => {
Self::Unimplemented(UnimplementedLanguageExtension::UnrestrictedPointerParameters)
}
Self::POINTER_COMPOSITE_ACCESS => {
Self::Unimplemented(UnimplementedLanguageExtension::PointerCompositeAccess)
}
_ => return None,
})
}
/// Maps this [`LanguageExtension`] into the sentinel word associated with it in WGSL.
pub const fn to_ident(self) -> &'static str {
match self {
Self::Implemented(kind) => kind.to_ident(),
Self::Unimplemented(kind) => match kind {
UnimplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => {
Self::READONLY_AND_READWRITE_STORAGE_TEXTURES
}
UnimplementedLanguageExtension::Packed4x8IntegerDotProduct => {
Self::PACKED4X8_INTEGER_DOT_PRODUCT
}
UnimplementedLanguageExtension::UnrestrictedPointerParameters => {
Self::UNRESTRICTED_POINTER_PARAMETERS
}
UnimplementedLanguageExtension::PointerCompositeAccess => {
Self::POINTER_COMPOSITE_ACCESS
}
},
}
}
}
/// A variant of [`LanguageExtension::Implemented`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, VariantArray)]
pub enum ImplementedLanguageExtension {}
impl ImplementedLanguageExtension {
/// Returns slice of all variants of [`ImplementedLanguageExtension`].
pub const fn all() -> &'static [Self] {
Self::VARIANTS
}
/// Maps this [`ImplementedLanguageExtension`] into the sentinel word associated with it in WGSL.
pub const fn to_ident(self) -> &'static str {
match self {}
}
}
/// A variant of [`LanguageExtension::Unimplemented`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum UnimplementedLanguageExtension {
ReadOnlyAndReadWriteStorageTextures,
Packed4x8IntegerDotProduct,
UnrestrictedPointerParameters,
PointerCompositeAccess,
}
impl UnimplementedLanguageExtension {
pub(crate) const fn tracking_issue_num(self) -> u16 {
match self {
Self::ReadOnlyAndReadWriteStorageTextures => 6204,
Self::Packed4x8IntegerDotProduct => 6445,
Self::UnrestrictedPointerParameters => 5158,
Self::PointerCompositeAccess => 6192,
}
}
}
+774
View File
@@ -0,0 +1,774 @@
use super::{number::consume_number, Error, ExpectedToken};
use crate::front::wgsl::error::NumberError;
use crate::front::wgsl::parse::directive::enable_extension::EnableExtensions;
use crate::front::wgsl::parse::{conv, Number};
use crate::front::wgsl::Scalar;
use crate::Span;
type TokenSpan<'a> = (Token<'a>, Span);
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Token<'a> {
Separator(char),
Paren(char),
Attribute,
Number(Result<Number, NumberError>),
Word(&'a str),
Operation(char),
LogicalOperation(char),
ShiftOperation(char),
AssignmentOperation(char),
IncrementOperation,
DecrementOperation,
Arrow,
Unknown(char),
Trivia,
End,
}
fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) {
let pos = input.find(|c| !what(c)).unwrap_or(input.len());
input.split_at(pos)
}
/// Return the token at the start of `input`.
///
/// If `generic` is `false`, then the bit shift operators `>>` or `<<`
/// are valid lookahead tokens for the current parser state (see [§3.1
/// Parsing] in the WGSL specification). In other words:
///
/// - If `generic` is `true`, then we are expecting an angle bracket
/// around a generic type parameter, like the `<` and `>` in
/// `vec3<f32>`, so interpret `<` and `>` as `Token::Paren` tokens,
/// even if they're part of `<<` or `>>` sequences.
///
/// - Otherwise, interpret `<<` and `>>` as shift operators:
/// `Token::LogicalOperation` tokens.
///
/// [§3.1 Parsing]: https://gpuweb.github.io/gpuweb/wgsl/#parsing
fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) {
let mut chars = input.chars();
let cur = match chars.next() {
Some(c) => c,
None => return (Token::End, ""),
};
match cur {
':' | ';' | ',' => (Token::Separator(cur), chars.as_str()),
'.' => {
let og_chars = chars.as_str();
match chars.next() {
Some('0'..='9') => consume_number(input),
_ => (Token::Separator(cur), og_chars),
}
}
'@' => (Token::Attribute, chars.as_str()),
'(' | ')' | '{' | '}' | '[' | ']' => (Token::Paren(cur), chars.as_str()),
'<' | '>' => {
let og_chars = chars.as_str();
match chars.next() {
Some('=') if !generic => (Token::LogicalOperation(cur), chars.as_str()),
Some(c) if c == cur && !generic => {
let og_chars = chars.as_str();
match chars.next() {
Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
_ => (Token::ShiftOperation(cur), og_chars),
}
}
_ => (Token::Paren(cur), og_chars),
}
}
'0'..='9' => consume_number(input),
'/' => {
let og_chars = chars.as_str();
match chars.next() {
Some('/') => {
let _ = chars.position(is_comment_end);
(Token::Trivia, chars.as_str())
}
Some('*') => {
let mut depth = 1;
let mut prev = None;
for c in &mut chars {
match (prev, c) {
(Some('*'), '/') => {
prev = None;
depth -= 1;
if depth == 0 {
return (Token::Trivia, chars.as_str());
}
}
(Some('/'), '*') => {
prev = None;
depth += 1;
}
_ => {
prev = Some(c);
}
}
}
(Token::End, "")
}
Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
_ => (Token::Operation(cur), og_chars),
}
}
'-' => {
let og_chars = chars.as_str();
match chars.next() {
Some('>') => (Token::Arrow, chars.as_str()),
Some('-') => (Token::DecrementOperation, chars.as_str()),
Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
_ => (Token::Operation(cur), og_chars),
}
}
'+' => {
let og_chars = chars.as_str();
match chars.next() {
Some('+') => (Token::IncrementOperation, chars.as_str()),
Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
_ => (Token::Operation(cur), og_chars),
}
}
'*' | '%' | '^' => {
let og_chars = chars.as_str();
match chars.next() {
Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
_ => (Token::Operation(cur), og_chars),
}
}
'~' => (Token::Operation(cur), chars.as_str()),
'=' | '!' => {
let og_chars = chars.as_str();
match chars.next() {
Some('=') => (Token::LogicalOperation(cur), chars.as_str()),
_ => (Token::Operation(cur), og_chars),
}
}
'&' | '|' => {
let og_chars = chars.as_str();
match chars.next() {
Some(c) if c == cur => (Token::LogicalOperation(cur), chars.as_str()),
Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
_ => (Token::Operation(cur), og_chars),
}
}
_ if is_blankspace(cur) => {
let (_, rest) = consume_any(input, is_blankspace);
(Token::Trivia, rest)
}
_ if is_word_start(cur) => {
let (word, rest) = consume_any(input, is_word_part);
(Token::Word(word), rest)
}
_ => (Token::Unknown(cur), chars.as_str()),
}
}
/// Returns whether or not a char is a comment end
/// (Unicode Pattern_White_Space excluding U+0020, U+0009, U+200E and U+200F)
const fn is_comment_end(c: char) -> bool {
match c {
'\u{000a}'..='\u{000d}' | '\u{0085}' | '\u{2028}' | '\u{2029}' => true,
_ => false,
}
}
/// Returns whether or not a char is a blankspace (Unicode Pattern_White_Space)
const fn is_blankspace(c: char) -> bool {
match c {
'\u{0020}'
| '\u{0009}'..='\u{000d}'
| '\u{0085}'
| '\u{200e}'
| '\u{200f}'
| '\u{2028}'
| '\u{2029}' => true,
_ => false,
}
}
/// Returns whether or not a char is a word start (Unicode XID_Start + '_')
fn is_word_start(c: char) -> bool {
c == '_' || unicode_xid::UnicodeXID::is_xid_start(c)
}
/// Returns whether or not a char is a word part (Unicode XID_Continue)
fn is_word_part(c: char) -> bool {
unicode_xid::UnicodeXID::is_xid_continue(c)
}
#[derive(Clone)]
pub(in crate::front::wgsl) struct Lexer<'a> {
/// The remaining unconsumed input.
input: &'a str,
/// The full original source code.
///
/// We compare `input` against this to compute the lexer's current offset in
/// the source.
pub(in crate::front::wgsl) source: &'a str,
/// The byte offset of the end of the most recently returned non-trivia
/// token.
///
/// This is consulted by the `span_from` function, for finding the
/// end of the span for larger structures like expressions or
/// statements.
last_end_offset: usize,
#[allow(dead_code)]
pub(in crate::front::wgsl) enable_extensions: EnableExtensions,
}
impl<'a> Lexer<'a> {
pub(in crate::front::wgsl) const fn new(input: &'a str) -> Self {
Lexer {
input,
source: input,
last_end_offset: 0,
enable_extensions: EnableExtensions::empty(),
}
}
/// Calls the function with a lexer and returns the result of the function as well as the span for everything the function parsed
///
/// # Examples
/// ```ignore
/// let lexer = Lexer::new("5");
/// let (value, span) = lexer.capture_span(Lexer::next_uint_literal);
/// assert_eq!(value, 5);
/// ```
#[inline]
pub fn capture_span<T, E>(
&mut self,
inner: impl FnOnce(&mut Self) -> Result<T, E>,
) -> Result<(T, Span), E> {
let start = self.current_byte_offset();
let res = inner(self)?;
let end = self.current_byte_offset();
Ok((res, Span::from(start..end)))
}
pub(in crate::front::wgsl) fn start_byte_offset(&mut self) -> usize {
loop {
// Eat all trivia because `next` doesn't eat trailing trivia.
let (token, rest) = consume_token(self.input, false);
if let Token::Trivia = token {
self.input = rest;
} else {
return self.current_byte_offset();
}
}
}
fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) {
let mut cloned = self.clone();
let token = cloned.next();
let rest = cloned.input;
(token, rest)
}
const fn current_byte_offset(&self) -> usize {
self.source.len() - self.input.len()
}
pub(in crate::front::wgsl) fn span_from(&self, offset: usize) -> Span {
Span::from(offset..self.last_end_offset)
}
/// Return the next non-whitespace token from `self`.
///
/// Assume we are a parse state where bit shift operators may
/// occur, but not angle brackets.
#[must_use]
pub(in crate::front::wgsl) fn next(&mut self) -> TokenSpan<'a> {
self.next_impl(false)
}
/// Return the next non-whitespace token from `self`.
///
/// Assume we are in a parse state where angle brackets may occur,
/// but not bit shift operators.
#[must_use]
pub(in crate::front::wgsl) fn next_generic(&mut self) -> TokenSpan<'a> {
self.next_impl(true)
}
/// Return the next non-whitespace token from `self`, with a span.
///
/// See [`consume_token`] for the meaning of `generic`.
fn next_impl(&mut self, generic: bool) -> TokenSpan<'a> {
let mut start_byte_offset = self.current_byte_offset();
loop {
let (token, rest) = consume_token(self.input, generic);
self.input = rest;
match token {
Token::Trivia => start_byte_offset = self.current_byte_offset(),
_ => {
self.last_end_offset = self.current_byte_offset();
return (token, self.span_from(start_byte_offset));
}
}
}
}
#[must_use]
pub(in crate::front::wgsl) fn peek(&mut self) -> TokenSpan<'a> {
let (token, _) = self.peek_token_and_rest();
token
}
pub(in crate::front::wgsl) fn expect_span(
&mut self,
expected: Token<'a>,
) -> Result<Span, Error<'a>> {
let next = self.next();
if next.0 == expected {
Ok(next.1)
} else {
Err(Error::Unexpected(next.1, ExpectedToken::Token(expected)))
}
}
pub(in crate::front::wgsl) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> {
self.expect_span(expected)?;
Ok(())
}
pub(in crate::front::wgsl) fn expect_generic_paren(
&mut self,
expected: char,
) -> Result<(), Error<'a>> {
let next = self.next_generic();
if next.0 == Token::Paren(expected) {
Ok(())
} else {
Err(Error::Unexpected(
next.1,
ExpectedToken::Token(Token::Paren(expected)),
))
}
}
/// If the next token matches it is skipped and true is returned
pub(in crate::front::wgsl) fn skip(&mut self, what: Token<'_>) -> bool {
let (peeked_token, rest) = self.peek_token_and_rest();
if peeked_token.0 == what {
self.input = rest;
true
} else {
false
}
}
pub(in crate::front::wgsl) fn next_ident_with_span(
&mut self,
) -> Result<(&'a str, Span), Error<'a>> {
match self.next() {
(Token::Word(word), span) => Self::word_as_ident_with_span(word, span),
other => Err(Error::Unexpected(other.1, ExpectedToken::Identifier)),
}
}
pub(in crate::front::wgsl) fn peek_ident_with_span(
&mut self,
) -> Result<(&'a str, Span), Error<'a>> {
match self.peek() {
(Token::Word(word), span) => Self::word_as_ident_with_span(word, span),
other => Err(Error::Unexpected(other.1, ExpectedToken::Identifier)),
}
}
fn word_as_ident_with_span(word: &'a str, span: Span) -> Result<(&'a str, Span), Error<'a>> {
match word {
"_" => Err(Error::InvalidIdentifierUnderscore(span)),
word if word.starts_with("__") => Err(Error::ReservedIdentifierPrefix(span)),
word => Ok((word, span)),
}
}
pub(in crate::front::wgsl) fn next_ident(
&mut self,
) -> Result<super::ast::Ident<'a>, Error<'a>> {
self.next_ident_with_span()
.and_then(|(word, span)| Self::word_as_ident(word, span))
.map(|(name, span)| super::ast::Ident { name, span })
}
fn word_as_ident(word: &'a str, span: Span) -> Result<(&'a str, Span), Error<'a>> {
if crate::keywords::wgsl::RESERVED.contains(&word) {
Err(Error::ReservedKeyword(span))
} else {
Ok((word, span))
}
}
/// Parses a generic scalar type, for example `<f32>`.
pub(in crate::front::wgsl) fn next_scalar_generic(&mut self) -> Result<Scalar, Error<'a>> {
self.expect_generic_paren('<')?;
let pair = match self.next() {
(Token::Word(word), span) => {
conv::get_scalar_type(word).ok_or(Error::UnknownScalarType(span))
}
(_, span) => Err(Error::UnknownScalarType(span)),
}?;
self.expect_generic_paren('>')?;
Ok(pair)
}
/// Parses a generic scalar type, for example `<f32>`.
///
/// Returns the span covering the inner type, excluding the brackets.
pub(in crate::front::wgsl) fn next_scalar_generic_with_span(
&mut self,
) -> Result<(Scalar, Span), Error<'a>> {
self.expect_generic_paren('<')?;
let pair = match self.next() {
(Token::Word(word), span) => conv::get_scalar_type(word)
.map(|scalar| (scalar, span))
.ok_or(Error::UnknownScalarType(span)),
(_, span) => Err(Error::UnknownScalarType(span)),
}?;
self.expect_generic_paren('>')?;
Ok(pair)
}
pub(in crate::front::wgsl) fn next_storage_access(
&mut self,
) -> Result<crate::StorageAccess, Error<'a>> {
let (ident, span) = self.next_ident_with_span()?;
match ident {
"read" => Ok(crate::StorageAccess::LOAD),
"write" => Ok(crate::StorageAccess::STORE),
"read_write" => Ok(crate::StorageAccess::LOAD | crate::StorageAccess::STORE),
"atomic" => Ok(crate::StorageAccess::ATOMIC
| crate::StorageAccess::LOAD
| crate::StorageAccess::STORE),
_ => Err(Error::UnknownAccess(span)),
}
}
pub(in crate::front::wgsl) fn next_format_generic(
&mut self,
) -> Result<(crate::StorageFormat, crate::StorageAccess), Error<'a>> {
self.expect(Token::Paren('<'))?;
let (ident, ident_span) = self.next_ident_with_span()?;
let format = conv::map_storage_format(ident, ident_span)?;
self.expect(Token::Separator(','))?;
let access = self.next_storage_access()?;
self.expect(Token::Paren('>'))?;
Ok((format, access))
}
pub(in crate::front::wgsl) fn open_arguments(&mut self) -> Result<(), Error<'a>> {
self.expect(Token::Paren('('))
}
pub(in crate::front::wgsl) fn close_arguments(&mut self) -> Result<(), Error<'a>> {
let _ = self.skip(Token::Separator(','));
self.expect(Token::Paren(')'))
}
pub(in crate::front::wgsl) fn next_argument(&mut self) -> Result<bool, Error<'a>> {
let paren = Token::Paren(')');
if self.skip(Token::Separator(',')) {
Ok(!self.skip(paren))
} else {
self.expect(paren).map(|()| false)
}
}
}
#[cfg(test)]
#[track_caller]
fn sub_test(source: &str, expected_tokens: &[Token]) {
let mut lex = Lexer::new(source);
for &token in expected_tokens {
assert_eq!(lex.next().0, token);
}
assert_eq!(lex.next().0, Token::End);
}
#[test]
fn test_numbers() {
// WGSL spec examples //
// decimal integer
sub_test(
"0x123 0X123u 1u 123 0 0i 0x3f",
&[
Token::Number(Ok(Number::AbstractInt(291))),
Token::Number(Ok(Number::U32(291))),
Token::Number(Ok(Number::U32(1))),
Token::Number(Ok(Number::AbstractInt(123))),
Token::Number(Ok(Number::AbstractInt(0))),
Token::Number(Ok(Number::I32(0))),
Token::Number(Ok(Number::AbstractInt(63))),
],
);
// decimal floating point
sub_test(
"0.e+4f 01. .01 12.34 .0f 0h 1e-3 0xa.fp+2 0x1P+4f 0X.3 0x3p+2h 0X1.fp-4 0x3.2p+2h",
&[
Token::Number(Ok(Number::F32(0.))),
Token::Number(Ok(Number::AbstractFloat(1.))),
Token::Number(Ok(Number::AbstractFloat(0.01))),
Token::Number(Ok(Number::AbstractFloat(12.34))),
Token::Number(Ok(Number::F32(0.))),
Token::Number(Err(NumberError::UnimplementedF16)),
Token::Number(Ok(Number::AbstractFloat(0.001))),
Token::Number(Ok(Number::AbstractFloat(43.75))),
Token::Number(Ok(Number::F32(16.))),
Token::Number(Ok(Number::AbstractFloat(0.1875))),
Token::Number(Err(NumberError::UnimplementedF16)),
Token::Number(Ok(Number::AbstractFloat(0.12109375))),
Token::Number(Err(NumberError::UnimplementedF16)),
],
);
// MIN / MAX //
// min / max decimal integer
sub_test(
"0i 2147483647i 2147483648i",
&[
Token::Number(Ok(Number::I32(0))),
Token::Number(Ok(Number::I32(i32::MAX))),
Token::Number(Err(NumberError::NotRepresentable)),
],
);
// min / max decimal unsigned integer
sub_test(
"0u 4294967295u 4294967296u",
&[
Token::Number(Ok(Number::U32(u32::MIN))),
Token::Number(Ok(Number::U32(u32::MAX))),
Token::Number(Err(NumberError::NotRepresentable)),
],
);
// min / max hexadecimal signed integer
sub_test(
"0x0i 0x7FFFFFFFi 0x80000000i",
&[
Token::Number(Ok(Number::I32(0))),
Token::Number(Ok(Number::I32(i32::MAX))),
Token::Number(Err(NumberError::NotRepresentable)),
],
);
// min / max hexadecimal unsigned integer
sub_test(
"0x0u 0xFFFFFFFFu 0x100000000u",
&[
Token::Number(Ok(Number::U32(u32::MIN))),
Token::Number(Ok(Number::U32(u32::MAX))),
Token::Number(Err(NumberError::NotRepresentable)),
],
);
// min/max decimal abstract int
sub_test(
"0 9223372036854775807 9223372036854775808",
&[
Token::Number(Ok(Number::AbstractInt(0))),
Token::Number(Ok(Number::AbstractInt(i64::MAX))),
Token::Number(Err(NumberError::NotRepresentable)),
],
);
// min/max hexadecimal abstract int
sub_test(
"0 0x7fffffffffffffff 0x8000000000000000",
&[
Token::Number(Ok(Number::AbstractInt(0))),
Token::Number(Ok(Number::AbstractInt(i64::MAX))),
Token::Number(Err(NumberError::NotRepresentable)),
],
);
/// ≈ 2^-126 * 2^−23 (= 2^−149)
const SMALLEST_POSITIVE_SUBNORMAL_F32: f32 = 1e-45;
/// ≈ 2^-126 * (1 − 2^−23)
const LARGEST_SUBNORMAL_F32: f32 = 1.1754942e-38;
/// ≈ 2^-126
const SMALLEST_POSITIVE_NORMAL_F32: f32 = f32::MIN_POSITIVE;
/// ≈ 1 − 2^−24
const LARGEST_F32_LESS_THAN_ONE: f32 = 0.99999994;
/// ≈ 1 + 2^−23
const SMALLEST_F32_LARGER_THAN_ONE: f32 = 1.0000001;
/// ≈ 2^127 * (2 − 2^−23)
const LARGEST_NORMAL_F32: f32 = f32::MAX;
// decimal floating point
sub_test(
"1e-45f 1.1754942e-38f 1.17549435e-38f 0.99999994f 1.0000001f 3.40282347e+38f",
&[
Token::Number(Ok(Number::F32(SMALLEST_POSITIVE_SUBNORMAL_F32))),
Token::Number(Ok(Number::F32(LARGEST_SUBNORMAL_F32))),
Token::Number(Ok(Number::F32(SMALLEST_POSITIVE_NORMAL_F32))),
Token::Number(Ok(Number::F32(LARGEST_F32_LESS_THAN_ONE))),
Token::Number(Ok(Number::F32(SMALLEST_F32_LARGER_THAN_ONE))),
Token::Number(Ok(Number::F32(LARGEST_NORMAL_F32))),
],
);
sub_test(
"3.40282367e+38f",
&[
Token::Number(Err(NumberError::NotRepresentable)), // ≈ 2^128
],
);
// hexadecimal floating point
sub_test(
"0x1p-149f 0x7FFFFFp-149f 0x1p-126f 0xFFFFFFp-24f 0x800001p-23f 0xFFFFFFp+104f",
&[
Token::Number(Ok(Number::F32(SMALLEST_POSITIVE_SUBNORMAL_F32))),
Token::Number(Ok(Number::F32(LARGEST_SUBNORMAL_F32))),
Token::Number(Ok(Number::F32(SMALLEST_POSITIVE_NORMAL_F32))),
Token::Number(Ok(Number::F32(LARGEST_F32_LESS_THAN_ONE))),
Token::Number(Ok(Number::F32(SMALLEST_F32_LARGER_THAN_ONE))),
Token::Number(Ok(Number::F32(LARGEST_NORMAL_F32))),
],
);
sub_test(
"0x1p128f 0x1.000001p0f",
&[
Token::Number(Err(NumberError::NotRepresentable)), // = 2^128
Token::Number(Err(NumberError::NotRepresentable)),
],
);
}
#[test]
fn double_floats() {
sub_test(
"0x1.2p4lf 0x1p8lf 0.0625lf 625e-4lf 10lf 10l",
&[
Token::Number(Ok(Number::F64(18.0))),
Token::Number(Ok(Number::F64(256.0))),
Token::Number(Ok(Number::F64(0.0625))),
Token::Number(Ok(Number::F64(0.0625))),
Token::Number(Ok(Number::F64(10.0))),
Token::Number(Ok(Number::AbstractInt(10))),
Token::Word("l"),
],
)
}
#[test]
fn test_tokens() {
sub_test("id123_OK", &[Token::Word("id123_OK")]);
sub_test(
"92No",
&[
Token::Number(Ok(Number::AbstractInt(92))),
Token::Word("No"),
],
);
sub_test(
"2u3o",
&[
Token::Number(Ok(Number::U32(2))),
Token::Number(Ok(Number::AbstractInt(3))),
Token::Word("o"),
],
);
sub_test(
"2.4f44po",
&[
Token::Number(Ok(Number::F32(2.4))),
Token::Number(Ok(Number::AbstractInt(44))),
Token::Word("po"),
],
);
sub_test(
"Δέλτα réflexion Кызыл 𐰓𐰏𐰇 朝焼け سلام 검정 שָׁלוֹם गुलाबी փիրուզ",
&[
Token::Word("Δέλτα"),
Token::Word("réflexion"),
Token::Word("Кызыл"),
Token::Word("𐰓𐰏𐰇"),
Token::Word("朝焼け"),
Token::Word("سلام"),
Token::Word("검정"),
Token::Word("שָׁלוֹם"),
Token::Word("गुलाबी"),
Token::Word("փիրուզ"),
],
);
sub_test("æNoø", &[Token::Word("æNoø")]);
sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]);
sub_test("No好", &[Token::Word("No好")]);
sub_test("_No", &[Token::Word("_No")]);
sub_test(
"*/*/***/*//=/*****//",
&[
Token::Operation('*'),
Token::AssignmentOperation('/'),
Token::Operation('/'),
],
);
// Type suffixes are only allowed on hex float literals
// if you provided an exponent.
sub_test(
"0x1.2f 0x1.2f 0x1.2h 0x1.2H 0x1.2lf",
&[
// The 'f' suffixes are taken as a hex digit:
// the fractional part is 0x2f / 256.
Token::Number(Ok(Number::AbstractFloat(1.0 + 0x2f as f64 / 256.0))),
Token::Number(Ok(Number::AbstractFloat(1.0 + 0x2f as f64 / 256.0))),
Token::Number(Ok(Number::AbstractFloat(1.125))),
Token::Word("h"),
Token::Number(Ok(Number::AbstractFloat(1.125))),
Token::Word("H"),
Token::Number(Ok(Number::AbstractFloat(1.125))),
Token::Word("lf"),
],
)
}
#[test]
fn test_variable_decl() {
sub_test(
"@group(0 ) var< uniform> texture: texture_multisampled_2d <f32 >;",
&[
Token::Attribute,
Token::Word("group"),
Token::Paren('('),
Token::Number(Ok(Number::AbstractInt(0))),
Token::Paren(')'),
Token::Word("var"),
Token::Paren('<'),
Token::Word("uniform"),
Token::Paren('>'),
Token::Word("texture"),
Token::Separator(':'),
Token::Word("texture_multisampled_2d"),
Token::Paren('<'),
Token::Word("f32"),
Token::Paren('>'),
Token::Separator(';'),
],
);
sub_test(
"var<storage,read_write> buffer: array<u32>;",
&[
Token::Word("var"),
Token::Paren('<'),
Token::Word("storage"),
Token::Separator(','),
Token::Word("read_write"),
Token::Paren('>'),
Token::Word("buffer"),
Token::Separator(':'),
Token::Word("array"),
Token::Paren('<'),
Token::Word("u32"),
Token::Paren('>'),
Token::Separator(';'),
],
);
}

Some files were not shown because too many files have changed in this diff Show More