oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
use crate::span::{SourceMap, Span};
use serde::Serialize;
use std::fmt::Write as _;

/// Whether a finding is proven, advisory, or needs runtime verification.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticKind {
    /// A proven template error.
    Error,
    /// A lint.
    Warning,
    /// A path the static checker cannot prove.
    Unchecked,
}

/// An expression replacement suggested by the checker.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Fix {
    /// Bytes to replace.
    pub span: Span,
    /// Replacement template source.
    pub replacement: String,
}

/// A source-spanned result of checking a template.
#[derive(Clone, Debug)]
pub struct Diagnostic {
    /// Stable identifier suitable for storing accepted unchecked paths.
    pub id: String,
    /// Stable category code.
    pub code: &'static str,
    /// Severity or proof status.
    pub kind: DiagnosticKind,
    /// Primary source range.
    pub span: Span,
    /// Explanation of the finding.
    pub message: String,
    /// Supplemental context, if any.
    pub notes: Vec<String>,
    /// Suggested replacement, if available.
    pub fix: Option<Fix>,
    /// Include or component call sites at which this finding applies.
    pub callers: Vec<Span>,
}

/// Diagnostics and PHP compatibility calls gathered during a run.
#[derive(Debug, Default)]
pub struct Report {
    /// Number of distinct source files checked.
    pub templates: usize,
    /// Findings in discovery order.
    pub diagnostics: Vec<Diagnostic>,
    /// Source locations and names of explicit `php::` calls.
    pub php_calls: Vec<(Span, String)>,
}

impl Report {
    /// Whether the checker proved no errors.
    pub fn is_clean(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|d| d.kind == DiagnosticKind::Error)
    }

    /// Panics with the rendered report when a template has errors.
    pub fn assert_clean(&self, sources: &SourceMap) {
        assert!(self.is_clean(), "{}", self.render(sources));
    }

    pub(super) fn add(
        &mut self,
        sources: &SourceMap,
        kind: DiagnosticKind,
        code: &'static str,
        span: Span,
        message: String,
    ) -> usize {
        if let Some(index) = self
            .diagnostics
            .iter()
            .position(|d| d.code == code && d.span == span && d.message == message)
        {
            return index;
        }
        let name = sources.location(span).map_or("<unknown>", |loc| loc.name);
        let source = sources.source(span.file).unwrap_or_default();
        let fragment = span.slice(source).unwrap_or_default();
        let before = source.get(..span.start as usize).unwrap_or_default();
        let after = source.get(span.start as usize..).unwrap_or_default();
        let prefix = before.rsplit(['\n', '\r']).next().unwrap_or_default();
        let suffix = after.split(['\n', '\r']).next().unwrap_or_default();
        let line = format!("{prefix}{suffix}");
        let column = prefix
            .len()
            .saturating_sub(line.len() - line.trim_start().len());
        let ordinal = before[..before.len() - prefix.len()]
            .lines()
            .filter(|other| other.trim() == line.trim())
            .count();
        // FNV-1a is specified independently of Rust's randomized map hashing.
        let mut hash = 0xcbf29ce484222325_u64;
        for byte in format!(
            "{name}\0{code}\0{}\0{column}\0{fragment}\0{ordinal}\0{message}",
            line.trim()
        )
        .bytes()
        {
            hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
        }
        let id = format!("{code}-{hash:016x}");
        self.diagnostics.push(Diagnostic {
            id,
            code,
            kind,
            span,
            message,
            notes: Vec::new(),
            fix: None,
            callers: Vec::new(),
        });
        self.diagnostics.len() - 1
    }

    /// Formats findings with source lines, underlines, and caller locations.
    pub fn render(&self, sources: &SourceMap) -> String {
        let mut output = String::new();
        for d in &self.diagnostics {
            let kind = match d.kind {
                DiagnosticKind::Error => "error",
                DiagnosticKind::Warning => "warning",
                DiagnosticKind::Unchecked => "unchecked",
            };
            let _ = writeln!(output, "{kind}[{}]: {}", d.id, d.message);
            if let Some(loc) = sources.location(d.span) {
                let _ = writeln!(output, "  --> {}:{}:{}", loc.name, loc.line, loc.column);
                let source = sources.source(d.span.file).unwrap_or_default();
                if let Some(before) = source.get(..d.span.start as usize)
                    && let Some(after) = source.get(d.span.start as usize..)
                {
                    let prefix = before.rsplit(['\n', '\r']).next().unwrap_or_default();
                    let suffix = after.split(['\n', '\r']).next().unwrap_or_default();
                    let width = d
                        .span
                        .slice(source)
                        .unwrap_or_default()
                        .split(['\n', '\r'])
                        .next()
                        .unwrap_or_default()
                        .chars()
                        .count()
                        .max(1);
                    let indentation: String = prefix
                        .chars()
                        .map(|c| if c == '\t' { '\t' } else { ' ' })
                        .collect();
                    let _ = writeln!(
                        output,
                        "   |\n{} | {prefix}{suffix}\n   | {indentation}{}",
                        loc.line,
                        "^".repeat(width)
                    );
                }
            }
            for note in &d.notes {
                let _ = writeln!(output, "   = note: {note}");
            }
            for &caller in &d.callers {
                if let Some(loc) = sources.location(caller) {
                    let _ = writeln!(
                        output,
                        "   = called from {}:{}:{}",
                        loc.name, loc.line, loc.column
                    );
                }
            }
            if let Some(fix) = &d.fix {
                let _ = writeln!(output, "   = help: use `{}`", fix.replacement);
            }
        }
        let counts = self
            .diagnostics
            .iter()
            .fold([0; 3], |mut counts, diagnostic| {
                let at = match diagnostic.kind {
                    DiagnosticKind::Error => 0,
                    DiagnosticKind::Warning => 1,
                    DiagnosticKind::Unchecked => 2,
                };
                counts[at] += 1;
                counts
            });
        let [errors, warnings, unchecked] = counts;
        if !self.diagnostics.is_empty() {
            let _ = writeln!(
                output,
                "{errors} errors, {warnings} warnings, {unchecked} unchecked across {} templates",
                self.templates
            );
        }
        output
    }

    /// Returns machine-readable findings, including byte ranges and one-based source positions.
    pub fn to_json(&self, sources: &SourceMap) -> serde_json::Value {
        use serde_json::json;
        let span = |span: Span| {
            let loc = sources.location(span);
            json!({
                "file": loc.map(|loc| loc.name), "line": loc.map(|loc| loc.line),
                "column": loc.map(|loc| loc.column), "start": span.start, "end": span.end,
            })
        };
        json!({
            "templates": self.templates,
            "diagnostics": self.diagnostics.iter().map(|d| json!({
                "id": d.id, "code": d.code, "kind": d.kind, "message": d.message, "location": span(d.span),
                "notes": d.notes, "callers": d.callers.iter().copied().map(span).collect::<Vec<_>>(),
                "fix": d.fix.as_ref().map(|fix| json!({"location": span(fix.span), "replacement": fix.replacement})),
            })).collect::<Vec<_>>(),
            "php_calls": self.php_calls.iter().map(|(at, name)| json!({"name": name, "location": span(*at)})).collect::<Vec<_>>(),
        })
    }
}