naga/back/wgsl/
mod.rs
1mod polyfill;
8mod writer;
9
10use alloc::format;
11use alloc::string::String;
12
13use thiserror::Error;
14
15pub use writer::{Writer, WriterFlags};
16
17use crate::common::wgsl;
18
19#[derive(Error, Debug)]
20pub enum Error {
21 #[error(transparent)]
22 FmtError(#[from] core::fmt::Error),
23 #[error("{0}")]
24 Custom(String),
25 #[error("{0}")]
26 Unimplemented(String), #[error("Unsupported relational function: {0:?}")]
28 UnsupportedRelationalFunction(crate::RelationalFunction),
29 #[error("Unsupported {kind}: {value}")]
30 Unsupported {
31 kind: &'static str,
33
34 value: String,
36 },
37}
38
39impl Error {
40 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
51trait ToWgslIfImplemented {
52 fn to_wgsl_if_implemented(self) -> Result<&'static str, Error>;
53}
54
55impl<T> ToWgslIfImplemented for T
56where
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
65pub 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
76impl 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}