wgslift-syntax 0.2.0

Preprocessor, lexer and parser for HLSL, the front end of the wgslift translator
Documentation
//! The front end of wgslift: an HLSL preprocessor, lexer and parser.
//!
//! It turns HLSL source text into a syntax tree with source spans. It does no type
//! checking and no translation; the `wgslift` crate does that on top of this tree.
//!
//! ```
//! let parsed = wgslift_syntax::parse("main.hlsl", "float4 tint : register(c0);", Default::default());
//! assert!(!parsed.has_errors());
//! assert_eq!(parsed.unit.items.len(), 1);
//! ```

pub mod ast;
pub mod diagnostic;
pub mod lexer;
pub mod parser;
pub mod pp;
pub mod span;

pub use ast::TranslationUnit;
pub use diagnostic::{Diagnostic, Severity};
pub use lexer::{Punct, Token, TokenKind};
pub use pp::{IncludeResolver, NoIncludes};
pub use span::{FileId, SourceFile, SourceFiles, Span};

/// Settings for one parse.
#[derive(Default)]
pub struct Options<'a> {
    /// Macros defined before the source, as name and value.
    pub defines: Vec<(String, String)>,
    /// Text that is preprocessed and parsed before the source, as the file
    /// `<prelude>`. Its macros apply to the source.
    pub prelude: Option<String>,
    /// Finds `#include` files. Without one, every `#include` is an error.
    pub includes: Option<&'a mut dyn IncludeResolver>,
}

/// The result of a parse.
#[derive(Debug, Clone)]
pub struct Parsed {
    /// The syntax tree. After errors it holds every item that parsed.
    pub unit: TranslationUnit,
    /// The main file, every included file and one `<define NAME>` file for each
    /// predefined macro, for diagnostics and spans.
    pub files: SourceFiles,
    /// Errors and warnings in source order of discovery.
    pub diagnostics: Vec<Diagnostic>,
}

impl Parsed {
    /// At least one diagnostic is an error.
    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.severity == Severity::Error)
    }
}

/// Preprocesses and parses the HLSL source `text`. `name` is the file name in
/// diagnostics.
pub fn parse(name: &str, text: &str, options: Options<'_>) -> Parsed {
    let mut files = SourceFiles::default();
    let (unit, diagnostics) = parse_into(&mut files, name, text, options);
    Parsed {
        unit,
        files,
        diagnostics,
    }
}

/// Like [`parse`], but adds the files to `files`, so the spans of several parses
/// share one file table.
pub fn parse_into(
    files: &mut SourceFiles,
    name: &str,
    text: &str,
    options: Options<'_>,
) -> (TranslationUnit, Vec<Diagnostic>) {
    let main = files.add(name, text);
    let mut diagnostics = Vec::new();
    let mut no_includes = NoIncludes;
    let includes: &mut dyn IncludeResolver = match options.includes {
        Some(resolver) => resolver,
        None => &mut no_includes,
    };
    let mut sources = Vec::new();
    if let Some(prelude) = options.prelude {
        sources.push(files.add("<prelude>", prelude));
    }
    sources.push(main);
    let tokens = pp::preprocess_files(
        files,
        &sources,
        &options.defines,
        includes,
        &mut diagnostics,
    );
    let eof = Span::new(main, text.len(), text.len());
    let unit = parser::parse_tokens(tokens, eof, &mut diagnostics);
    (unit, diagnostics)
}

#[cfg(test)]
mod tests;