Debian Codegraph @

third_party/rust/naga/src/front/wgsl/mod.rs

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