use std::collections::HashMap;
use regex::Regex;
use crate::audit::balanced;
use crate::codegen::{expr, split_args, unquote};
pub type Props = HashMap<String, Vec<(String, Option<String>)>>;
fn macro_name(component: &str) -> String {
component.replace(['-', '.', ':'], "_")
}
fn snake(s: &str) -> String {
let mut out = String::new();
for ch in s.chars() {
if ch.is_uppercase() {
out.push('_');
out.extend(ch.to_lowercase());
} else {
out.push(if ch == '-' { '_' } else { ch });
}
}
out
}
pub fn props(src: &str, names: &HashMap<String, String>) -> Vec<(String, Option<String>)> {
let Some(at) = src.find("@props(") else { return vec![] };
let Some(args) = balanced(&src[at + 6..], '(', ')') else { return vec![] };
let inner = args[1..args.len() - 1].trim().trim_start_matches('[').trim_end_matches(']');
split_args(inner).iter().map(|p| match p.split_once("=>") {
Some((k, v)) => (unquote(k), Some(expr(v, names).0)),
None => (unquote(p), None),
}).collect()
}
pub fn definition(component: &str, src: &str, names: &HashMap<String, String>, to_jinja: impl Fn(&str) -> String) -> String {
let props = props(src, names);
let mut body = src.to_string();
if let Some(at) = body.find("@props(") {
let len = balanced(&body[at + 6..], '(', ')').map_or(0, |a| a.len() + 6);
body.replace_range(at..at + len, "");
}
let mut parked: Vec<String> = Vec::new();
let mut park = |s: String| {
parked.push(s);
format!("\u{1}{}\u{1}", parked.len() - 1)
};
let merge = Regex::new(r"\{\{\s*\$attributes->merge\(\s*\[").unwrap();
while let Some(m) = merge.find(&body) {
let start = m.start();
let Some(arr) = balanced(&body[m.end() - 1..], '[', ']') else { break };
let after = m.end() - 1 + arr.len();
let Some(close) = body[after..].find("}}") else { break };
let kwargs: Vec<String> = split_args(&arr[1..arr.len() - 1]).iter().filter_map(|kv| {
let (k, v) = kv.split_once("=>")?;
Some(format!("{}={}", snake(&unquote(k)), expr(v, names).0))
}).collect();
let text = park(format!("{{{{ attributes(attrs).merge({}) }}}}", kwargs.join(", ")));
body.replace_range(start..after + close + 2, &text);
}
body = Regex::new(r"\{\{\s*\$attributes\s*\}\}").unwrap().replace_all(&body, park("{{ attributes(attrs) }}".into()).as_str()).into_owned();
body = Regex::new(r"\{\{\s*\$slot\s*\}\}").unwrap().replace_all(&body, park("{{ caller() }}".into()).as_str()).into_owned();
let assigned: Vec<String> = Regex::new(r"\$(\w+)\s*=[^=>]").unwrap().captures_iter(&body).map(|c| c[1].to_string()).collect();
let mut slots: Vec<String> = Regex::new(r"\{\{\s*\$(\w+)\s*\}\}").unwrap().captures_iter(&body)
.map(|c| c[1].to_string())
.filter(|v| !props.iter().any(|(p, _)| p == v) && !assigned.contains(v) && v != "attributes")
.collect();
slots.dedup();
let mut jinja = to_jinja(&body);
for (i, p) in parked.iter().enumerate() {
jinja = jinja.replace(&format!("\u{1}{i}\u{1}"), p);
}
let mut args: Vec<String> = props.iter().map(|(p, d)| match d {
Some(d) => format!("{}={d}", snake(p)),
None => snake(p),
}).collect();
args.extend(slots.iter().map(|s| format!("{}=none", snake(s))));
args.push("attrs={}".into());
let todo = if src.contains("@php") { "{# PORT-TODO: port the @php block below to {% set %} #}\n" } else { "" };
format!("{{# larakiln: view:components.{component} #}}\n{todo}{{% macro {}({}) -%}}\n{}\n{{%- endmacro %}}\n", macro_name(component), args.join(", "), jinja.trim())
}
fn attributes(raw: &str, names: &HashMap<String, String>) -> Vec<(String, String, bool)> {
let attr = Regex::new(r#"([:@]?[\w\-.:]+)(?:=("[^"]*"|'[^']*'))?"#).unwrap();
attr.captures_iter(raw).map(|c| {
let name = c[1].to_string();
match c.get(2) {
None => (name, "true".into(), false),
Some(v) => {
let v = &v.as_str()[1..v.as_str().len() - 1];
if let Some(bound) = name.strip_prefix(':') {
let (e, todo) = expr(v, names);
(bound.to_string(), e, todo)
} else {
(name, literal(v), false)
}
}
}
}).collect()
}
fn literal(v: &str) -> String {
let echo = Regex::new(r"\{\{\s*(.*?)\s*\}\}").unwrap();
let mut parts = Vec::new();
let mut last = 0;
for c in echo.captures_iter(v) {
let m = c.get(0).unwrap();
if m.start() > last {
parts.push(format!("{:?}", &v[last..m.start()]));
}
parts.push(format!("({})", &c[1]));
last = m.end();
}
if last < v.len() || parts.is_empty() {
parts.push(format!("{:?}", &v[last..]));
}
parts.join(" ~ ")
}
struct Frame {
tag: String,
args: Vec<(String, String, bool)>,
body: String,
slots: Vec<(String, String)>,
}
pub fn usages(src: &str, props: &Props, names: &HashMap<String, String>) -> (String, bool) {
let tag = Regex::new(r#"<(/?)x-([\w.\-:]+)((?:\s+[^\s=/>]+(?:=(?:"[^"]*"|'[^']*'))?)*)\s*(/?)>"#).unwrap();
let mut stack: Vec<Frame> = Vec::new();
let mut out = String::new();
let mut used = false;
let mut last = 0;
let push = |stack: &mut Vec<Frame>, out: &mut String, s: &str| match stack.last_mut() {
Some(f) => f.body += s,
None => *out += s,
};
for c in tag.captures_iter(src) {
let m = c.get(0).unwrap();
push(&mut stack, &mut out, &src[last..m.start()]);
last = m.end();
let (closing, name, raw, selfclose) = (!c[1].is_empty(), c[2].to_string(), c.get(3).map_or("", |m| m.as_str()), !c[4].is_empty());
if !closing {
let frame = Frame { tag: name, args: attributes(raw, names), body: String::new(), slots: Vec::new() };
if selfclose {
used = true;
let text = render(frame, props);
push(&mut stack, &mut out, &text);
} else {
stack.push(frame);
}
continue;
}
let Some(frame) = stack.pop() else { continue };
if frame.tag == "slot" || frame.tag.starts_with("slot:") {
let slot = frame.tag.strip_prefix("slot:").map(String::from)
.or_else(|| frame.args.iter().find(|a| a.0 == "name").map(|a| a.1.trim_matches('"').to_string()))
.unwrap_or_else(|| "slot".into());
if let Some(parent) = stack.last_mut() {
parent.slots.push((snake(&slot), frame.body));
}
continue;
}
if !frame.tag.ends_with("-layout") {
used = true;
}
let text = render(frame, props);
push(&mut stack, &mut out, &text);
}
push(&mut stack, &mut out, &src[last..]);
(out, used)
}
fn render(frame: Frame, props: &Props) -> String {
if let Some(layout) = frame.tag.strip_suffix("-layout") {
let mut s = format!("{{% extends \"layouts.{layout}\" %}}\n");
for (slot, body) in &frame.slots {
s += &format!("{{% block {slot} %}}{body}{{% endblock %}}\n");
}
return s + &format!("{{% block content %}}{}{{% endblock %}}\n", frame.body);
}
let known = props.get(&frame.tag);
let is_prop = |n: &str| known.is_some_and(|p| p.iter().any(|(name, _)| name == n || snake(name) == snake(n)));
let mut kwargs: Vec<String> = Vec::new();
let mut attrs: Vec<String> = Vec::new();
let mut todo = false;
for (name, value, t) in &frame.args {
todo |= *t;
if is_prop(name) {
kwargs.push(format!("{}={value}", snake(name)));
} else {
attrs.push(format!("{name:?}: {value}"));
}
}
let mut sets = String::new();
for (slot, body) in &frame.slots {
sets += &format!("{{% set {slot} %}}{body}{{% endset %}}");
kwargs.push(format!("{slot}={slot}"));
}
if !attrs.is_empty() {
kwargs.push(format!("attrs={{{}}}", attrs.join(", ")));
}
let call = format!("ui.{}({})", macro_name(&frame.tag), kwargs.join(", "));
let note = if todo { "{# PORT-TODO: check this component's attributes #}" } else { "" };
let unknown = if known.is_none() { format!("{{# PORT-TODO: no components/{}.blade.php found; write the macro by hand #}}", frame.tag) } else { String::new() };
if frame.body.trim().is_empty() {
format!("{unknown}{sets}{{{{ {call} }}}}{note}")
} else {
format!("{unknown}{sets}{{% call {call} %}}{}{{% endcall %}}{note}", frame.body)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn usages_become_macro_calls() {
let names = HashMap::from([("login".to_string(), "authenticated_sessions::create".to_string())]);
let props: Props = HashMap::from([
("input-label".into(), vec![("value".into(), None)]),
("primary-button".into(), vec![]),
("dropdown".into(), vec![("align".into(), Some("\"right\"".into()))]),
]);
let blade = r#"<x-guest-layout><x-slot name="header">H</x-slot><x-input-label for="email" :value="'Email'" /><x-primary-button class="ms-3 {{ x }}">Log in</x-primary-button><x-dropdown align="left"><x-slot name="trigger">T</x-slot>C</x-dropdown><x-text-input required /></x-guest-layout>"#;
let (out, used) = usages(blade, &props, &names);
assert!(used);
assert!(out.starts_with("{% extends \"layouts.guest\" %}\n{% block header %}H{% endblock %}\n{% block content %}"), "{out}");
assert!(out.contains(r#"{{ ui.input_label(value="Email", attrs={"for": "email"}) }}"#), "{out}");
assert!(out.contains(r#"{% call ui.primary_button(attrs={"class": "ms-3 " ~ (x)}) %}Log in{% endcall %}"#), "{out}");
assert!(out.contains(r#"{% set trigger %}T{% endset %}{% call ui.dropdown(align="left", trigger=trigger) %}C{% endcall %}"#), "{out}");
assert!(out.contains("no components/text-input.blade.php") && out.contains(r#"ui.text_input(attrs={"required": true})"#), "{out}");
}
#[test]
fn definitions_become_macros() {
let names = HashMap::new();
let src = "@props(['status'])\n@if ($status)\n<div {{ $attributes->merge(['class' => 'font-medium']) }}>{{ $status }}</div>\n@endif\n";
let m = definition("auth-session-status", src, &names, |s| s.replace("@if ($status)", "{% if status %}").replace("@endif", "{% endif %}").replace("{{ $status }}", "{{ status }}"));
assert!(m.contains("{% macro auth_session_status(status, attrs={}) -%}"), "{m}");
assert!(m.contains(r#"<div {{ attributes(attrs).merge(class="font-medium") }}>{{ status }}</div>"#), "{m}");
let slotted = definition("dropdown", "<div>{{ $trigger }}</div><a>{{ $slot }}</a>", &names, |s| s.to_string());
assert!(slotted.contains("dropdown(trigger=none, attrs={})") && slotted.contains("{{ caller() }}"), "{slotted}");
}
}