naga/front/wgsl/
mod.rs

1/*!
2Frontend for [WGSL][wgsl] (WebGPU Shading Language).
3
4[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html
5*/
6
7mod error;
8mod index;
9mod lower;
10mod parse;
11#[cfg(test)]
12mod tests;
13mod to_wgsl;
14
15use crate::front::wgsl::error::Error;
16use crate::front::wgsl::parse::Parser;
17use thiserror::Error;
18
19pub use crate::front::wgsl::error::ParseError;
20use crate::front::wgsl::lower::Lowerer;
21use crate::Scalar;
22
23pub struct Frontend {
24    parser: Parser,
25}
26
27impl Frontend {
28    pub const fn new() -> Self {
29        Self {
30            parser: Parser::new(),
31        }
32    }
33
34    pub fn parse(&mut self, source: &str) -> Result<crate::Module, ParseError> {
35        self.inner(source).map_err(|x| x.as_parse_error(source))
36    }
37
38    fn inner<'a>(&mut self, source: &'a str) -> Result<crate::Module, Error<'a>> {
39        let tu = self.parser.parse(source)?;
40        let index = index::Index::generate(&tu)?;
41        let module = Lowerer::new(&index).lower(&tu)?;
42
43        Ok(module)
44    }
45}
46
47/// <div class="warning">
48// NOTE: Keep this in sync with `wgpu::Device::create_shader_module`!
49// NOTE: Keep this in sync with `wgpu_core::Global::device_create_shader_module`!
50///
51/// This function may consume a lot of stack space. Compiler-enforced limits for parsing recursion
52/// exist; if shader compilation runs into them, it will return an error gracefully. However, on
53/// some build profiles and platforms, the default stack size for a thread may be exceeded before
54/// this limit is reached during parsing. Callers should ensure that there is enough stack space
55/// for this, particularly if calls to this method are exposed to user input.
56///
57/// </div>
58pub fn parse_str(source: &str) -> Result<crate::Module, ParseError> {
59    Frontend::new().parse(source)
60}
61
62#[cfg(test)]
63#[track_caller]
64pub fn assert_parse_err(input: &str, snapshot: &str) {
65    let output = parse_str(input)
66        .expect_err("expected parser error")
67        .emit_to_string(input);
68    if output != snapshot {
69        for diff in diff::lines(snapshot, &output) {
70            match diff {
71                diff::Result::Left(l) => println!("-{l}"),
72                diff::Result::Both(l, _) => println!(" {l}"),
73                diff::Result::Right(r) => println!("+{r}"),
74            }
75        }
76        panic!("Error snapshot failed");
77    }
78}