use std::collections::HashSet;
pub(crate) struct BlockSpec {
pub open: &'static str,
pub middle: &'static [&'static str],
pub close: &'static [&'static str],
pub args: ArgRule,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ArgRule {
Any,
Required,
ExactlyOne,
Section,
Slot,
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,
),
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),
block("teleport", &[], &["endteleport"], Any),
block("script", &[], &["endscript"], Any),
block("assets", &[], &["endassets"], Any),
block("persist", &[], &["endpersist"], Any),
];
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)
}
pub(crate) fn is_builtin_closer(name: &str) -> bool {
BLOCKS.iter().any(|b| b.close.contains(&name))
}
static INLINE: &[&str] = &[
"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",
"livewirestyles",
"livewirescripts",
"livewirescriptconfig",
"this",
"entangle",
];
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))
}
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()
}
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;
}
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)"]
);
}
}