blade-syntax 0.1.1

Lossless parser for Laravel Blade templates
Documentation
//! Which Blade directives open blocks, and what continues or closes them.
//!
//! Names here are lowercase and without the `@`. Blade compiles directives through
//! PHP methods, which are case-insensitive, so `@endPushOnce` and `@endpushonce`
//! are the same directive.

use std::collections::HashSet;

pub(crate) struct BlockSpec {
    pub open: &'static str,
    /// Directives that split the block into another body, like `@else`.
    pub middle: &'static [&'static str],
    /// Directives that end the block. The first one is used in error messages.
    pub close: &'static [&'static str],
    pub args: ArgRule,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ArgRule {
    /// Opens a block with or without arguments.
    Any,
    /// Opens a block only when it has arguments (`@empty($x)`; a bare `@empty` is the
    /// middle of `@forelse`).
    Required,
    /// Opens a block only with exactly one argument (`@push('s')`); with two it's
    /// inline (`@push('s', 'content')`, Laravel's `startPush` appends right away).
    ExactlyOne,
    /// `@section`: Laravel's `startSection` opens a block when `$content` is absent or
    /// `null`, so `@section('a')` and `@section('a', null)` open, `@section('t', 'Home')`
    /// doesn't.
    Section,
    /// `@slot`: Laravel's `slot()` is inline when called with exactly two arguments or
    /// with non-null content, so a block needs one argument, or `null` plus attributes.
    Slot,
    /// `@lang`: Laravel's `compileLang` opens a block with no arguments or with an
    /// array of replacements (`@lang(['n' => 1])`); `@lang('key')` is inline.
    NoneOrArray,
}

use ArgRule::*;

const fn block(
    open: &'static str,
    middle: &'static [&'static str],
    close: &'static [&'static str],
    args: ArgRule,
) -> BlockSpec {
    BlockSpec {
        open,
        middle,
        close,
        args,
    }
}

static BLOCKS: &[BlockSpec] = &[
    block("if", &["elseif", "else"], &["endif"], Any),
    block("unless", &["else"], &["endunless"], Any),
    block("isset", &["else"], &["endisset"], Any),
    block("empty", &["else"], &["endempty"], Required),
    block("auth", &["elseauth", "else"], &["endauth"], Any),
    block("guest", &["elseguest", "else"], &["endguest"], Any),
    block("production", &["else"], &["endproduction"], Any),
    block("env", &["else"], &["endenv"], Any),
    block("hassection", &["else"], &["endif"], Any),
    block("sectionmissing", &["else"], &["endif"], Any),
    block("can", &["elsecan", "else"], &["endcan"], Any),
    block("cannot", &["elsecannot", "else"], &["endcannot"], Any),
    block("canany", &["elsecanany", "else"], &["endcanany"], Any),
    block("foreach", &[], &["endforeach"], Any),
    block("for", &[], &["endfor"], Any),
    block("while", &[], &["endwhile"], Any),
    block("forelse", &["empty"], &["endforelse"], Any),
    block("switch", &["case", "default"], &["endswitch"], Any),
    block(
        "section",
        &[],
        &["endsection", "show", "stop", "append", "overwrite"],
        Section,
    ),
    // `@push('name', 'content')` appends immediately (Laravel's startPush), no closer.
    block("push", &[], &["endpush"], ExactlyOne),
    block("prepend", &[], &["endprepend"], ExactlyOne),
    block("pushonce", &[], &["endpushonce"], Any),
    block("prependonce", &[], &["endprependonce"], Any),
    block("pushif", &[], &["endpushif"], Any),
    block("once", &[], &["endonce"], Any),
    block("error", &[], &["enderror"], Any),
    block("fragment", &[], &["endfragment"], Any),
    block("session", &[], &["endsession"], Any),
    block("context", &[], &["endcontext"], Any),
    block("component", &[], &["endcomponent"], Any),
    block("slot", &[], &["endslot"], Slot),
    block("lang", &[], &["endlang"], NoneOrArray),
    // Livewire
    block("teleport", &[], &["endteleport"], Any),
    block("script", &[], &["endscript"], Any),
    block("assets", &[], &["endassets"], Any),
    block("persist", &[], &["endpersist"], Any),
];

/// The built-in block that `name` opens, given its argument text (with parentheses).
pub(crate) fn block_for_opener(name: &str, args: Option<&str>) -> Option<&'static BlockSpec> {
    let spec = BLOCKS.iter().find(|b| b.open == name)?;
    let args = args.map(top_level_args).unwrap_or_default();
    let second_is_null = args.get(1).is_some_and(|a| a.eq_ignore_ascii_case("null"));
    let opens = match spec.args {
        Any => true,
        Required => !args.is_empty(),
        ExactlyOne => args.len() == 1,
        Section => args.len() == 1 || (args.len() == 2 && second_is_null),
        Slot => args.len() == 1 || (args.len() >= 3 && second_is_null),
        NoneOrArray => args.first().is_none_or(|a| a.starts_with('[')),
    };
    opens.then_some(spec)
}

/// Whether `name` closes some built-in block (used to report stray closers).
pub(crate) fn is_builtin_closer(name: &str) -> bool {
    BLOCKS.iter().any(|b| b.close.contains(&name))
}

/// Directives Laravel and Livewire define that never open blocks. Blade leaves any
/// other unknown `@word` as plain text, so only known names get argument errors.
static INLINE: &[&str] = &[
    // Laravel
    "aware",
    "bool",
    "break",
    "checked",
    "choice",
    "class",
    "continue",
    "csrf",
    "dd",
    "disabled",
    "dump",
    "each",
    "else",
    "elseauth",
    "elsecan",
    "elsecanany",
    "elsecannot",
    "elseguest",
    "elseif",
    "extends",
    "extendsfirst",
    "include",
    "includefirst",
    "includeif",
    "includeunless",
    "includewhen",
    "inject",
    "js",
    "json",
    "method",
    "parent",
    "props",
    "readonly",
    "required",
    "selected",
    "stack",
    "style",
    "unset",
    "use",
    "vite",
    "vitereactrefresh",
    "yield",
    "case",
    "default",
    "componentfirst",
    // Livewire
    "livewire",
    "livewirestyles",
    "livewirescripts",
    "livewirescriptconfig",
    "this",
    "entangle",
];

/// Whether `name` (lowercase, no `@`) is a directive Laravel or Livewire defines.
pub(crate) fn is_known_directive(name: &str) -> bool {
    INLINE.contains(&name)
        || matches!(name, "php" | "endphp" | "verbatim" | "endverbatim")
        || BLOCKS
            .iter()
            .any(|b| b.open == name || b.middle.contains(&name) || b.close.contains(&name))
}

/// Custom conditionals registered with `Blade::if('disk', ...)` give `@disk`,
/// `@unlessdisk`, `@elsedisk` and `@enddisk`. We can't see the PHP that registers
/// them, so we infer them: `X` is custom if the file uses `@endX` and also `@X` or
/// `@unlessX`, and `X` isn't already a built-in.
pub(crate) fn custom_conditionals(names: &HashSet<String>) -> HashSet<String> {
    names
        .iter()
        .filter_map(|n| n.strip_prefix("end"))
        .filter(|x| !x.is_empty())
        .filter(|x| names.contains(*x) || names.contains(&format!("unless{x}")))
        .filter(|x| !matches!(*x, "php" | "verbatim") && !BLOCKS.iter().any(|b| b.open == *x))
        .map(str::to_string)
        .collect()
}

/// The comma-separated arguments in `(...)`, trimmed, ignoring commas nested in
/// brackets or inside PHP strings. `()` has none.
fn top_level_args(args: &str) -> Vec<&str> {
    let inner = args
        .strip_prefix('(')
        .and_then(|s| s.strip_suffix(')'))
        .unwrap_or(args);
    if inner.trim().is_empty() {
        return Vec::new();
    }
    let bytes = inner.as_bytes();
    let mut parts = Vec::new();
    let (mut depth, mut start, mut i) = (0usize, 0usize, 0usize);
    while i < bytes.len() {
        match bytes[i] {
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                parts.push(inner[start..i].trim());
                start = i + 1;
            }
            quote @ (b'\'' | b'"') => {
                i += 1;
                while i < bytes.len() && bytes[i] != quote {
                    if bytes[i] == b'\\' {
                        i += 1;
                    }
                    i += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }
    // `i` can step past the end inside an unterminated string; clamp before slicing.
    parts.push(inner[start.min(inner.len())..].trim());
    parts
}

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

    #[test]
    fn splits_top_level_args() {
        assert!(top_level_args("()").is_empty());
        assert_eq!(top_level_args("('a')"), ["'a'"]);
        assert_eq!(top_level_args("('a', null)"), ["'a'", "null"]);
        assert_eq!(
            top_level_args("('a, b', [1, 2], f(3, 4))"),
            ["'a, b'", "[1, 2]", "f(3, 4)"]
        );
    }
}