wgslift-syntax 0.2.0

Preprocessor, lexer and parser for HLSL, the front end of the wgslift translator
Documentation
//! Errors and warnings with the source span they refer to.

use std::fmt;

use crate::span::{SourceFiles, Span};

/// How serious a diagnostic is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Severity {
    /// The input is wrong; the result is not complete.
    Error,
    /// The input is accepted, but probably not what the author meant.
    Warning,
}

/// A message about the input, with the place it refers to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    /// Error or warning.
    pub severity: Severity,
    /// What is wrong, in one sentence.
    pub message: String,
    /// Where it is wrong.
    pub span: Span,
}

impl Diagnostic {
    /// An error at `span`.
    pub fn error(span: Span, message: impl Into<String>) -> Diagnostic {
        Diagnostic {
            severity: Severity::Error,
            message: message.into(),
            span,
        }
    }

    /// A warning at `span`.
    pub fn warning(span: Span, message: impl Into<String>) -> Diagnostic {
        Diagnostic {
            severity: Severity::Warning,
            message: message.into(),
            span,
        }
    }

    /// The diagnostic as `file:line:column: error: message`.
    pub fn display<'a>(&'a self, files: &'a SourceFiles) -> impl fmt::Display + 'a {
        DisplayDiagnostic {
            diagnostic: self,
            files,
        }
    }

    /// The diagnostic as `display` gives it, then its source line with carets under
    /// the span, and the `#include` chain of its file.
    pub fn render<'a>(&'a self, files: &'a SourceFiles) -> impl fmt::Display + 'a {
        Rendered {
            diagnostic: self,
            files,
        }
    }

    fn kind(&self) -> &'static str {
        match self.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
        }
    }
}

struct DisplayDiagnostic<'a> {
    diagnostic: &'a Diagnostic,
    files: &'a SourceFiles,
}

impl fmt::Display for DisplayDiagnostic<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: {}: {}",
            self.files.location(self.diagnostic.span),
            self.diagnostic.kind(),
            self.diagnostic.message
        )
    }
}

/// `kind: message`, without a location: use `display` or `render` for that.
impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.kind(), self.message)
    }
}

impl std::error::Error for Diagnostic {}

struct Rendered<'a> {
    diagnostic: &'a Diagnostic,
    files: &'a SourceFiles,
}

impl fmt::Display for Rendered<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let d = self.diagnostic;
        write!(f, "{}", d.display(self.files))?;
        let Some(file) = self.files.get(d.span.file) else {
            return Ok(());
        };
        let (line, line_start) = file.line_text(d.span.start);
        let before = line
            .get(..(d.span.start - line_start) as usize)
            .unwrap_or(line);
        let pad: String = before
            .chars()
            .map(|c| if c == '\t' { '\t' } else { ' ' })
            .collect();
        let end = (d.span.end.saturating_sub(line_start) as usize).min(line.len());
        let carets = line
            .get(before.len()..end)
            .map_or(1, |s| s.chars().count())
            .max(1);
        let (number, _) = file.line_column(d.span.start);
        write!(
            f,
            "\n{number:>5} | {line}\n      | {pad}{}",
            "^".repeat(carets)
        )?;
        // Include chains are short; the bound only guards a malformed table.
        let mut from = file.included_from();
        for _ in 0..64 {
            let Some(span) = from else { break };
            write!(
                f,
                "\n  in a file included from {}",
                self.files.location(span)
            )?;
            from = self.files.get(span.file).and_then(|f| f.included_from());
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn displays_location_severity_and_message() {
        let mut files = SourceFiles::default();
        let id = files.add("main.hlsl", "float x\n;");
        let d = Diagnostic::error(Span::new(id, 8, 9), "expected a name");
        assert_eq!(
            d.display(&files).to_string(),
            "main.hlsl:2:1: error: expected a name"
        );
        let w = Diagnostic::warning(Span::new(id, 0, 5), "unused");
        assert_eq!(
            w.display(&files).to_string(),
            "main.hlsl:1:1: warning: unused"
        );
    }

    #[test]
    fn render_shows_the_line_with_carets_and_counts_columns_in_characters() {
        let mut files = SourceFiles::default();
        let id = files.add("m.hlsl", "// \u{e9}\n\tx = \u{e9}t\u{e9};\n");
        let at = "// \u{e9}\n\tx = ".len();
        let end = at + "\u{e9}t\u{e9}".len();
        let d = Diagnostic::error(Span::new(id, at, end), "unknown name");
        assert_eq!(
            d.render(&files).to_string(),
            "m.hlsl:2:6: error: unknown name\n    2 | \tx = \u{e9}t\u{e9};\n      | \t    ^^^"
        );
        assert_eq!(d.to_string(), "error: unknown name");
    }

    #[test]
    fn render_names_the_files_that_include_the_file() {
        struct Files;
        impl crate::IncludeResolver for Files {
            fn resolve(
                &mut self,
                path: &str,
                _: bool,
                _: &str,
            ) -> Result<(String, String), String> {
                match path {
                    "a.h" => Ok(("a.h".into(), "#include \"b.h\"\n".into())),
                    _ => Ok(("b.h".into(), "float x = @;\n".into())),
                }
            }
        }
        let mut files = Files;
        let options = crate::Options {
            includes: Some(&mut files),
            ..Default::default()
        };
        let parsed = crate::parse("main.hlsl", "#include \"a.h\"\n", options);
        let text = parsed.diagnostics[0].render(&parsed.files).to_string();
        assert!(text.contains("in a file included from a.h:1:1"), "{text}");
        assert!(
            text.ends_with("in a file included from main.hlsl:1:1"),
            "{text}"
        );
    }
}