| 1 |
/*! |
| 2 |
Backend for [WGSL][wgsl] (WebGPU Shading Language). |
| 3 |
|
| 4 |
[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html |
| 5 |
*/ |
| 6 |
|
| 7 |
mod polyfill; |
| 8 |
mod writer; |
| 9 |
|
| 10 |
use alloc::format; |
| 11 |
use alloc::string::String; |
| 12 |
|
| 13 |
use thiserror::Error; |
| 14 |
|
| 15 |
pub use writer::{Writer, WriterFlags}; |
| 16 |
|
| 17 |
use crate::common::wgsl; |
| 18 |
|
| 19 |
#[derive(Error, Debug)] |
| 20 |
pub enum Error { |
| 21 |
#[error(transparent)] |
| 22 |
FmtError(#[from] core::fmt::Error), |
| 23 |
#[error("{0}")] |
| 24 |
Custom(String), |
| 25 |
#[error("{0}")] |
| 26 |
Unimplemented(String), // TODO: Error used only during development |
| 27 |
#[error("Unsupported relational function: {0:?}")] |
| 28 |
UnsupportedRelationalFunction(crate::RelationalFunction), |
| 29 |
#[error("Unsupported {kind}: {value}")] |
| 30 |
Unsupported { |
| 31 |
/// What kind of unsupported thing this is: interpolation, builtin, etc. |
| 32 |
kind: &'static str, |
| 33 |
|
| 34 |
/// The debug form of the Naga IR value that this backend can't express. |
| 35 |
value: String, |
| 36 |
}, |
| 37 |
} |
| 38 |
|
| 39 |
impl Error { |
| 40 |
/// Produce an [`Unsupported`] error for `value`. |
| 41 |
/// |
| 42 |
/// [`Unsupported`]: Error::Unsupported |
| 43 |
fn unsupported<T: core::fmt::Debug>(kind: &'static str, value: T) -> Error { |
| 44 |
Error::Unsupported { |
| 45 |
kind, |
| 46 |
value: format!("{value:?}"), |
| 47 |
} |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
trait ToWgslIfImplemented { |
| 52 |
fn to_wgsl_if_implemented(self) -> Result<&'static str, Error>; |
| 53 |
} |
| 54 |
|
| 55 |
impl<T> ToWgslIfImplemented for T |
| 56 |
where |
| 57 |
T: wgsl::TryToWgsl + core::fmt::Debug + Copy, |
| 58 |
{ |
| 59 |
fn to_wgsl_if_implemented(self) -> Result<&'static str, Error> { |
| 60 |
self.try_to_wgsl() |
| 61 |
.ok_or_else(|| Error::unsupported(T::DESCRIPTION, self)) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
pub fn write_string( |
| 66 |
module: &crate::Module, |
| 67 |
info: &crate::valid::ModuleInfo, |
| 68 |
flags: WriterFlags, |
| 69 |
) -> Result<String, Error> { |
| 70 |
let mut w = Writer::new(String::new(), flags); |
| 71 |
w.write(module, info)?; |
| 72 |
let output = w.finish(); |
| 73 |
Ok(output) |
| 74 |
} |
| 75 |
|
| 76 |
impl crate::AtomicFunction { |
| 77 |
const fn to_wgsl(self) -> &'static str { |
| 78 |
match self { |
| 79 |
Self::Add => "Add", |
| 80 |
Self::Subtract => "Sub", |
| 81 |
Self::And => "And", |
| 82 |
Self::InclusiveOr => "Or", |
| 83 |
Self::ExclusiveOr => "Xor", |
| 84 |
Self::Min => "Min", |
| 85 |
Self::Max => "Max", |
| 86 |
Self::Exchange { compare: None } => "Exchange", |
| 87 |
Self::Exchange { .. } => "CompareExchangeWeak", |
| 88 |
} |
| 89 |
} |
| 90 |
} |