Skip to main content

wgslift_syntax/
lib.rs

1//! The front end of wgslift: an HLSL preprocessor, lexer and parser.
2//!
3//! It turns HLSL source text into a syntax tree with source spans. It does no type
4//! checking and no translation; the `wgslift` crate does that on top of this tree.
5//!
6//! ```
7//! let parsed = wgslift_syntax::parse("main.hlsl", "float4 tint : register(c0);", Default::default());
8//! assert!(!parsed.has_errors());
9//! assert_eq!(parsed.unit.items.len(), 1);
10//! ```
11
12pub mod ast;
13pub mod diagnostic;
14pub mod lexer;
15pub mod parser;
16pub mod pp;
17pub mod span;
18
19pub use ast::TranslationUnit;
20pub use diagnostic::{Diagnostic, Severity};
21pub use lexer::{Punct, Token, TokenKind};
22pub use pp::{IncludeResolver, NoIncludes};
23pub use span::{FileId, SourceFile, SourceFiles, Span};
24
25/// Settings for one parse.
26#[derive(Default)]
27pub struct Options<'a> {
28    /// Macros defined before the source, as name and value.
29    pub defines: Vec<(String, String)>,
30    /// Text that is preprocessed and parsed before the source, as the file
31    /// `<prelude>`. Its macros apply to the source.
32    pub prelude: Option<String>,
33    /// Finds `#include` files. Without one, every `#include` is an error.
34    pub includes: Option<&'a mut dyn IncludeResolver>,
35}
36
37/// The result of a parse.
38#[derive(Debug, Clone)]
39pub struct Parsed {
40    /// The syntax tree. After errors it holds every item that parsed.
41    pub unit: TranslationUnit,
42    /// The main file, every included file and one `<define NAME>` file for each
43    /// predefined macro, for diagnostics and spans.
44    pub files: SourceFiles,
45    /// Errors and warnings in source order of discovery.
46    pub diagnostics: Vec<Diagnostic>,
47}
48
49impl Parsed {
50    /// At least one diagnostic is an error.
51    pub fn has_errors(&self) -> bool {
52        self.diagnostics
53            .iter()
54            .any(|d| d.severity == Severity::Error)
55    }
56}
57
58/// Preprocesses and parses the HLSL source `text`. `name` is the file name in
59/// diagnostics.
60pub fn parse(name: &str, text: &str, options: Options<'_>) -> Parsed {
61    let mut files = SourceFiles::default();
62    let (unit, diagnostics) = parse_into(&mut files, name, text, options);
63    Parsed {
64        unit,
65        files,
66        diagnostics,
67    }
68}
69
70/// Like [`parse`], but adds the files to `files`, so the spans of several parses
71/// share one file table.
72pub fn parse_into(
73    files: &mut SourceFiles,
74    name: &str,
75    text: &str,
76    options: Options<'_>,
77) -> (TranslationUnit, Vec<Diagnostic>) {
78    let main = files.add(name, text);
79    let mut diagnostics = Vec::new();
80    let mut no_includes = NoIncludes;
81    let includes: &mut dyn IncludeResolver = match options.includes {
82        Some(resolver) => resolver,
83        None => &mut no_includes,
84    };
85    let mut sources = Vec::new();
86    if let Some(prelude) = options.prelude {
87        sources.push(files.add("<prelude>", prelude));
88    }
89    sources.push(main);
90    let tokens = pp::preprocess_files(
91        files,
92        &sources,
93        &options.defines,
94        includes,
95        &mut diagnostics,
96    );
97    let eof = Span::new(main, text.len(), text.len());
98    let unit = parser::parse_tokens(tokens, eof, &mut diagnostics);
99    (unit, diagnostics)
100}
101
102#[cfg(test)]
103mod tests;