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 std::{borrow::Cow, sync::Arc};

use crate::{
    ast::DirectiveName,
    compile::Program,
    error::{Error, ErrorKind, Result},
    lexer::{self, DirectiveTable, Lexed, Mode, Token, TokenKind},
    loader::{Loader, Source},
    span::{FileId, SourceMap, Span},
    syntax::parse_arguments,
};

use super::Extensions;

pub(crate) fn compile(
    loader: &impl Loader,
    source: &Source,
    sources: &mut SourceMap,
    table: &DirectiveTable,
    extensions: &Extensions,
) -> Result<Arc<Program>> {
    let mut text = Cow::Borrowed(source.text.as_ref());
    for prepare in &extensions.prepare {
        text = Cow::Owned(prepare(&text));
    }
    if !extensions.precompilers.is_empty() {
        text = Cow::Owned(precompile(&text, table, extensions)?);
    }
    if extensions.templates.is_empty() {
        return compile_plain(loader, source, sources, &text, table);
    }
    let file = sources.next_file_id().ok_or_else(source_limit)?;
    let tokens = match checked_lex(file, &text, table) {
        Ok(tokens) => tokens,
        Err(error) => {
            add_source(sources, source, text.as_ref())?;
            return Err(error);
        }
    };
    if !tokens.iter().any(|token| {
        matches!(&token.kind, TokenKind::Directive(DirectiveName::Custom(name), _)
            if extensions.templates.contains_key(name))
    }) {
        return compile_plain(loader, source, sources, &text, table);
    }
    let mut expansion = Expansion {
        table,
        extensions,
        text: text.into_owned(),
    };
    let tokens = match expansion.tokens(tokens, 0) {
        Ok(tokens) => tokens,
        Err(error) => {
            add_source(sources, source, expansion.text)?;
            return Err(error);
        }
    };
    let file = add_source(sources, source, expansion.text)?;
    let text = sources.source(file).ok_or_else(source_limit)?;
    Program::compile_tokens(file, text, table, &tokens).map(Arc::new)
}

fn compile_plain(
    loader: &impl Loader,
    source: &Source,
    sources: &mut SourceMap,
    text: &str,
    table: &DirectiveTable,
) -> Result<Arc<Program>> {
    let file = add_source(sources, source, text)?;
    let mut compile = || Program::compile(file, text, table);
    if text == source.text.as_ref() {
        loader.compile(source, file, &mut compile)
    } else {
        loader.compile(&Source::new(&source.name, text), file, &mut compile)
    }
}

fn add_source(sources: &mut SourceMap, source: &Source, text: impl Into<String>) -> Result<FileId> {
    sources.add(&source.name, text).ok_or_else(source_limit)
}

fn source_limit() -> Error {
    Error::new(ErrorKind::Limit, "view source exceeds span limits", None)
}

fn checked_lex(file: FileId, text: &str, table: &DirectiveTable) -> Result<Vec<Token>> {
    let Lexed { tokens, errors } = lexer::lex(file, text, table, Mode::Template);
    if let Some(error) = errors.into_iter().next() {
        return Err(error);
    }
    Ok(tokens)
}

fn precompile(text: &str, table: &DirectiveTable, extensions: &Extensions) -> Result<String> {
    let lexed = lexer::lex(FileId::default(), text, table, Mode::Template);
    let mut marker = "\0oxblade:".to_owned();
    while text.contains(&marker) {
        marker.push(':');
    }
    let mut masked = String::new();
    let mut regions = Vec::new();
    for token in lexed.tokens {
        let part = token.span.slice(text).ok_or_else(source_limit)?;
        if matches!(
            token.kind,
            TokenKind::Verbatim(_)
                | TokenKind::Code(_)
                | TokenKind::Php(_)
                | TokenKind::Comment
                | TokenKind::Directive(DirectiveName::Php | DirectiveName::Code, _)
        ) {
            masked.push_str(&format!("{marker}{}\0", regions.len()));
            regions.push(part);
        } else {
            masked.push_str(part);
        }
    }
    if let Some(error) = lexed
        .errors
        .into_iter()
        .find(|error| error.kind == ErrorKind::Limit)
    {
        return Err(error);
    }
    for hook in &extensions.precompilers {
        masked = hook(&masked);
    }
    let mut restored = String::new();
    let mut remainder = masked.as_str();
    while let Some((head, tail)) = remainder.split_once(&marker) {
        restored.push_str(head);
        let (index, tail) = tail.split_once('\0').ok_or_else(invalid_marker)?;
        let region = index
            .parse::<usize>()
            .ok()
            .and_then(|index| regions.get(index))
            .ok_or_else(invalid_marker)?;
        restored.push_str(region);
        remainder = tail;
    }
    restored.push_str(remainder);
    Ok(restored)
}

fn invalid_marker() -> Error {
    Error::new(
        ErrorKind::Compile,
        "precompiler changed a protected source marker",
        None,
    )
}

struct Expansion<'a> {
    table: &'a DirectiveTable,
    extensions: &'a Extensions,
    text: String,
}

impl Expansion<'_> {
    fn tokens(&mut self, tokens: Vec<Token>, depth: usize) -> Result<Vec<Token>> {
        let mut output = Vec::new();
        for token in tokens {
            let TokenKind::Directive(DirectiveName::Custom(name), raw_args) = &token.kind else {
                output.push(token);
                continue;
            };
            let Some(template) = self.extensions.templates.get(name) else {
                output.push(token);
                continue;
            };
            if depth >= 32 {
                return Err(Error::new(
                    ErrorKind::Limit,
                    "template directive expansion depth exceeded",
                    token.span,
                ));
            }
            let expanded = substitute(template, *raw_args, token.span, &self.text)?;
            let offset = u32::try_from(self.text.len().checked_add(1).ok_or_else(source_limit)?)
                .map_err(|_| source_limit())?;
            if self
                .text
                .len()
                .saturating_add(1)
                .saturating_add(expanded.len())
                > 8 * 1024 * 1024
            {
                return Err(Error::new(
                    ErrorKind::Limit,
                    "template directive expansion exceeds 8 MiB",
                    token.span,
                ));
            }
            self.text.push('\n');
            self.text.push_str(&expanded);
            let tokens =
                checked_lex(token.span.file, &expanded, self.table).map_err(|mut error| {
                    error.span = Some(token.span);
                    error
                })?;
            let tokens = tokens
                .into_iter()
                .map(|token| shifted(token, offset))
                .collect();
            let mut expansion = self.tokens(tokens, depth + 1)?;
            if token.consumes_newline {
                // A zero-width text token marks the end of the generated PHP tag.
                expansion.push(Token {
                    span: Span::new(token.span.file, token.span.end, token.span.end),
                    consumes_newline: true,
                    kind: TokenKind::Text,
                });
            }
            output.extend(expansion);
        }
        Ok(output)
    }
}

fn shifted(mut token: Token, offset: u32) -> Token {
    fn shift(span: &mut Span, offset: u32) {
        span.start += offset;
        span.end += offset;
    }
    shift(&mut token.span, offset);
    match &mut token.kind {
        TokenKind::Directive(_, Some(span))
        | TokenKind::Echo(_, span)
        | TokenKind::Verbatim(span)
        | TokenKind::Code(span)
        | TokenKind::Php(span)
        | TokenKind::RawPhp(span) => shift(span, offset),
        TokenKind::Escaped { head, arguments } => {
            shift(head, offset);
            if let Some(arguments) = arguments {
                shift(arguments, offset);
            }
        }
        TokenKind::Tag(tag) => shift(&mut tag.attributes, offset),
        _ => {}
    }
    token
}

fn substitute(template: &str, raw_args: Option<Span>, call: Span, text: &str) -> Result<String> {
    let raw = raw_args
        .and_then(|span| span.slice(text))
        .unwrap_or_default();
    let args = match raw_args {
        Some(span) => parse_arguments(text, span)?,
        None => Vec::new(),
    };
    let mut expanded = String::new();
    let mut rest = template;
    while let Some((head, tail)) = rest.split_once('{') {
        expanded.push_str(head);
        if let Some((key, after)) = tail.split_once('}') {
            if key == "args" {
                expanded.push_str(raw);
                rest = after;
                continue;
            }
            if !key.is_empty() && key.bytes().all(|byte| byte.is_ascii_digit()) {
                let arg = key
                    .parse::<usize>()
                    .ok()
                    .and_then(|index| args.get(index))
                    .and_then(|arg| arg.span.slice(text))
                    .ok_or_else(|| {
                        Error::new(
                            ErrorKind::Compile,
                            format!("directive argument {{{key}}} is missing"),
                            call,
                        )
                    })?;
                expanded.push_str(arg);
                rest = after;
                continue;
            }
        }
        expanded.push('{');
        rest = tail;
    }
    expanded.push_str(rest);
    Ok(expanded)
}