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
//! An immutable, source-spanned program for the renderer.

mod slots;

pub(crate) mod read_only;

pub(crate) use slots::{RowOp, RowProgram};

use crate::{
    ast::{
        AttributePart, Block, ComponentAttr, ComponentAttrKind, DirectiveName, Expr, ExprKind,
        MapKey, Node, NodeKind, Stmt, StmtKind, Template,
    },
    error::{Error, ErrorKind, Result},
    eval::{FormatPiece, format_pieces},
    lexer::{self, DirectiveTable, Mode, Token, TokenKind},
    parser,
    span::FileId,
};

/// A parsed program with whitespace decisions applied by the parser.
#[derive(Debug)]
pub struct Program {
    pub(crate) template: Template,
    pub(crate) layout_separator: bool,
    pub(crate) read_only: bool,
    pub(crate) read_only_layout: Option<usize>,
    pub(crate) projected_component: bool,
    pub(crate) row_programs: std::collections::HashMap<crate::span::Span, RowProgram>,
}

impl Program {
    /// Parses a view and returns its first diagnostic on failure.
    pub fn compile(file: FileId, source: &str, directives: &DirectiveTable) -> Result<Self> {
        let lexed = lexer::lex(file, source, directives, Mode::Template);
        Self::from_tokens(file, source, directives, &lexed.tokens, lexed.errors)
    }

    /// Returns the parsed template after compilation, including generated directive bodies.
    pub fn template(&self) -> &Template {
        &self.template
    }

    pub(crate) fn compile_tokens(
        file: FileId,
        source: &str,
        directives: &DirectiveTable,
        tokens: &[Token],
    ) -> Result<Self> {
        Self::from_tokens(file, source, directives, tokens, Vec::new())
    }

    fn from_tokens(
        file: FileId,
        source: &str,
        directives: &DirectiveTable,
        tokens: &[Token],
        errors: Vec<Error>,
    ) -> Result<Self> {
        let mut parsed = parser::parse_tokens(file, source, tokens, errors);
        if let Some(error) = parsed.errors.into_iter().next() {
            return Err(error);
        }
        nodes(&mut parsed.template.nodes)?;
        let mut row_programs = std::collections::HashMap::new();
        slots::compile(&parsed.template.nodes, &mut row_programs);
        Ok(Self {
            read_only: read_only::nodes(&parsed.template.nodes),
            read_only_layout: read_only::layout(&parsed.template.nodes),
            projected_component: read_only::projected_component(&parsed.template.nodes),
            template: parsed.template,
            row_programs,
            layout_separator: layout_separator(source, directives, tokens),
        })
    }
}

/// Blade appends one LF before its layout footer. A closing PHP tag at the end of
/// the body can consume that LF, either alone or as the second byte of a CRLF.
fn layout_separator(source: &str, directives: &DirectiveTable, tokens: &[Token]) -> bool {
    use DirectiveName::{Extends, ExtendsFirst};
    let mut body = tokens.iter().rev().filter(|token| {
        !matches!(
            token.kind,
            TokenKind::Comment | TokenKind::Directive(Extends | ExtendsFirst, _)
        )
    });
    let mut tail = body.next();
    if tail.is_some_and(|token| {
        token.kind == TokenKind::Text && token.span.slice(source) == Some("\r")
    }) {
        tail = body.next();
    }
    !tail.is_some_and(|token| match &token.kind {
        TokenKind::Directive(name, args) => directives.whole_tag(name, args.is_some()),
        TokenKind::Echo(..) | TokenKind::Code(..) => true,
        TokenKind::Tag(tag) => tag.closing || (tag.self_closing && !tag.is_slot()),
        _ => false,
    })
}

fn nodes(nodes: &mut [Node]) -> Result<()> {
    let mut previous_echo = None;
    for item in nodes {
        if let NodeKind::Text(text) = &mut item.kind
            && previous_echo == Some(item.span.start)
            && text.starts_with('\r')
            && !text.starts_with("\r\n")
        {
            text.remove(0);
        }
        previous_echo = matches!(item.kind, NodeKind::Echo(..)).then_some(item.span.end);
        node(item)?;
    }
    Ok(())
}

fn expressions(exprs: &[Expr]) -> Result<()> {
    exprs.iter().try_for_each(expression)
}

fn fields(fields: &[crate::ast::FieldDecl]) -> Result<()> {
    fields
        .iter()
        .filter_map(|field| field.default.as_ref())
        .try_for_each(expression)
}

fn node(node: &mut Node) -> Result<()> {
    match &mut node.kind {
        NodeKind::Text(_) | NodeKind::Comment | NodeKind::Use(_) => {}
        NodeKind::Echo(_, expr) => expression(expr)?,
        NodeKind::Inline { args, .. } => expressions(args)?,
        NodeKind::Code(stmts) => statements(stmts)?,
        NodeKind::Conditional(branches) => {
            for branch in branches {
                if let Some(test) = &branch.test {
                    expressions(&test.args)?;
                }
                nodes(&mut branch.body)?;
            }
        }
        NodeKind::While { test, body } => {
            expression(test)?;
            nodes(body)?;
        }
        NodeKind::Loop {
            iterable,
            body,
            empty,
            ..
        } => {
            expression(iterable)?;
            nodes(body)?;
            if let Some(empty) = empty {
                nodes(empty)?;
            }
        }
        NodeKind::Switch { value, arms } => {
            expression(value)?;
            for arm in arms {
                if let Some(test) = &arm.test {
                    expression(test)?;
                }
                nodes(&mut arm.body)?;
            }
        }
        NodeKind::Block { args, body, .. } => {
            expressions(args)?;
            nodes(body)?;
        }
        NodeKind::Section {
            name,
            content,
            body,
            ..
        } => {
            expression(name)?;
            if let Some(content) = content {
                expression(content)?;
            }
            nodes(body)?;
        }
        NodeKind::PushIf(branches) => {
            for branch in branches {
                if let Some(test) = &branch.condition {
                    expression(test)?;
                }
                expression(&branch.stack)?;
                nodes(&mut branch.body)?;
            }
        }
        NodeKind::Props(props) | NodeKind::Aware(props) => fields(props)?,
        NodeKind::Inject(field) => fields(std::slice::from_ref(field))?,
        NodeKind::Component(component) => {
            attrs(&component.attributes)?;
            nodes(&mut component.body)?;
        }
        NodeKind::Slot(slot) => {
            attrs(&slot.attributes)?;
            nodes(&mut slot.body)?;
        }
    }
    Ok(())
}

fn attrs(attrs: &[ComponentAttr]) -> Result<()> {
    for attr in attrs {
        match &attr.kind {
            ComponentAttrKind::Bound { value, .. }
            | ComponentAttrKind::Spread(value)
            | ComponentAttrKind::Class(value)
            | ComponentAttrKind::Style(value) => expression(value)?,
            ComponentAttrKind::Literal { parts, .. }
            | ComponentAttrKind::Escaped {
                parts: Some(parts), ..
            } => {
                for part in parts {
                    if let AttributePart::Echo(_, value) = part {
                        expression(value)?;
                    }
                }
            }
            _ => {}
        }
    }
    Ok(())
}

fn block(body: &Block) -> Result<()> {
    statements(&body.statements)?;
    if let Some(tail) = &body.tail {
        expression(tail)?;
    }
    Ok(())
}

fn statements(stmts: &[Stmt]) -> Result<()> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Let { value, .. } | StmtKind::Expr(value) => expression(value)?,
            StmtKind::Assign { target, value, .. } => {
                expression(target)?;
                expression(value)?;
            }
            StmtKind::For { iterable, body, .. } => {
                expression(iterable)?;
                block(body)?;
            }
            StmtKind::While { test, body } => {
                expression(test)?;
                block(body)?;
            }
            StmtKind::Break | StmtKind::Continue => {}
        }
    }
    Ok(())
}

fn expression(expr: &Expr) -> Result<()> {
    match &expr.kind {
        ExprKind::Literal(_) | ExprKind::Path(_) => {}
        ExprKind::List(items) | ExprKind::Tuple(items) => expressions(items)?,
        ExprKind::Map(fields) => {
            for (key, value) in fields {
                if let MapKey::Computed(key) = key {
                    expression(key)?;
                }
                expression(value)?;
            }
        }
        ExprKind::ConditionalEntry { value, condition } => {
            expression(value)?;
            expression(condition)?;
        }
        ExprKind::NamedArgument { value, .. }
        | ExprKind::Field {
            receiver: value, ..
        }
        | ExprKind::Try(value)
        | ExprKind::Cast { value, .. }
        | ExprKind::Unary { value, .. } => expression(value)?,
        ExprKind::Binary { left, right, .. }
        | ExprKind::Index {
            receiver: left,
            index: right,
            ..
        } => {
            expression(left)?;
            expression(right)?;
        }
        ExprKind::Call { callee, args } => {
            if matches!(&callee.kind, ExprKind::Path(path) if path == &["format"]) {
                validate_format(&args.values, expr.span)?;
            }
            expression(callee)?;
            expressions(&args.values)?;
        }
        ExprKind::Method { receiver, args, .. } => {
            expression(receiver)?;
            expressions(&args.values)?;
        }
        ExprKind::Range { start, end, .. } => {
            for endpoint in [start, end].into_iter().flatten() {
                expression(endpoint)?;
            }
        }
        ExprKind::If {
            test,
            then,
            otherwise,
        } => {
            expression(test)?;
            block(then)?;
            if let Some(otherwise) = otherwise {
                expression(otherwise)?;
            }
        }
        ExprKind::Block(body) => block(body)?,
        ExprKind::Match { value, arms } => {
            expression(value)?;
            for arm in arms {
                if let Some(guard) = &arm.guard {
                    expression(guard)?;
                }
                expression(&arm.value)?;
            }
        }
        ExprKind::Closure { body, .. } => expression(body)?,
    }
    Ok(())
}

fn validate_format(args: &[Expr], span: crate::span::Span) -> Result<()> {
    let bad = |message| Error::new(ErrorKind::Compile, message, span);
    let [
        Expr {
            kind: ExprKind::Literal(crate::ast::Literal::String(format)),
            ..
        },
        operands @ ..,
    ] = args
    else {
        return Err(bad("format requires a literal format string".to_owned()));
    };
    let pieces = format_pieces(format).map_err(|error| bad(error.message))?;
    if pieces
        .iter()
        .filter(|piece| matches!(piece, FormatPiece::Positional))
        .count()
        != operands.len()
    {
        return Err(bad(
            "format placeholder count does not match the argument count".to_owned(),
        ));
    }
    Ok(())
}