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
#![allow(missing_docs, clippy::unwrap_used, clippy::expect_used)] // Test, bench and example code may unwrap.
use oxblade::{lexer::DirectiveTable, parser::parse, span::FileId};

struct Fence<'a> {
    language: &'a str,
    lead: &'a str,
    heading: &'a str,
    line: usize,
    body: String,
}

fn fences(markdown: &str) -> Vec<Fence<'_>> {
    let mut previous = "";
    let mut heading = "";
    let mut open: Option<Fence<'_>> = None;
    let mut result = Vec::new();
    for (line, text) in markdown.lines().enumerate() {
        if let Some(fence) = &mut open {
            if text == "```" {
                result.extend(open.take());
                previous = text;
            } else {
                fence.body.push_str(text);
                fence.body.push('\n');
            }
        } else if let Some(language) = text.strip_prefix("```") {
            open = Some(Fence {
                language,
                lead: previous,
                heading,
                line: line + 2,
                body: String::new(),
            });
        } else if !text.trim().is_empty() {
            if text.starts_with('#') {
                heading = text;
            }
            previous = text;
        }
    }
    result
}

fn example_sources() -> Vec<(usize, String)> {
    let blocks = fences(include_str!("../../../design/EXAMPLES.md"));
    let mut rust_component = false;
    let mut result = Vec::new();
    for block in blocks {
        if block.language == "rust" && block.heading == "### A class component" {
            rust_component = true;
        }
        if block.language == "blade"
            && (block.lead.ends_with("oxblade:")
                || rust_component
                || block.lead == "Identical, as is the component that pushes once:")
        {
            result.push((block.line, block.body));
            rust_component = false;
        }
    }
    result
}

fn spec_sources() -> Vec<(usize, String)> {
    let sections = [
        "### Arithmetic",
        "### Strings",
        "### Collections and closures",
        "### `@php` becomes `@code`",
        "### Casts and conditionals",
        "### Str, numbers and dates",
        "### Methods on your own types",
        "### Loops",
        "### Includes and `@each`",
        "### Attribute bags",
        "### Dynamic and legacy components",
        "### Forms and attribute directives",
        "### Translations",
        "### Auth, abilities, environment, session and context",
        "### `@inject` and `@use`",
        "### Pagination and debugging",
        "### What doesn't port",
    ];
    let mut result = Vec::new();
    for block in fences(include_str!("../../../design/SPEC.md")) {
        let Fence {
            language,
            lead,
            heading,
            line,
            mut body,
        } = block;
        if language == "diff" && matches!(heading, "### Named slots and slot attributes") {
            body = body
                .lines()
                .filter(|line| !line.starts_with('-'))
                .map(|line| line.strip_prefix('+').unwrap_or(line))
                .collect::<Vec<_>>()
                .join("\n");
        } else if language != "blade" {
            continue;
        } else if lead.starts_with("Rust Blade")
            || lead.starts_with("**Rust Blade")
            || lead.contains("the Rust file is the same")
            || lead.contains("the same in both")
            || matches!(lead, "HTML comment:" | "spellings work:")
            || heading == "### Fragments"
            || heading == "### TODO markers"
            || (sections.contains(&heading) && lead == "```")
        {
            // Complete Rust Blade and shared sources.
        } else if heading == "### Template inheritance" {
            body = body.replace("$name", "name");
        } else if matches!(
            heading,
            "### Stacks"
                | "### Custom directives and conditions"
                | "### `@json` and `@js`"
                | "### Alpine, htmx and literal `@`"
        ) {
            // The surrounding prose explicitly gives the variable substitutions.
            for variable in [
                "maps",
                "price",
                "day",
                "conversions",
                "tabs",
                "active",
                "key",
                "label",
            ] {
                body = body.replace(&format!("${variable}"), variable);
            }
        } else if heading == "### Conditionals and the whitespace model" {
            body = body
                .replace('$', "")
                .replace("@if (title)", "@if (filled(title))")
                .replace("@elseif (fallback)", "@elseif (filled(fallback))");
        } else {
            continue;
        }
        result.push((line, body));
    }
    result
}

fn assert_sources(file: &str, examples: &[(usize, String)]) {
    let mut directives = DirectiveTable::new();
    directives.register_directive("money", true);
    directives.register_condition("weekend");
    let failures = examples
        .iter()
        .filter_map(|(line, source)| {
            let parsed = parse(FileId(0), source, &directives);
            (!parsed.errors.is_empty())
                .then(|| format!("{file}:{line}\n{:#?}\n{source}", parsed.errors))
        })
        .collect::<Vec<_>>();
    assert!(failures.is_empty(), "{}", failures.join("\n"));
}

#[test]
fn all_oxblade_examples_and_component_sources_parse() {
    let sources = example_sources();
    assert_eq!(sources.len(), 75);
    assert_sources("EXAMPLES.md", &sources);
}

#[test]
fn all_spec_rust_blade_sources_parse() {
    let sources = spec_sources();
    assert!(sources.len() >= 35, "only {} sources found", sources.len());
    assert_sources("SPEC.md", &sources);
}