use super::ConvertContext;
use crate::php;
use tree_sitter::Node;
pub fn translate_expression(source: &str, ctx: &ConvertContext) -> Option<String> {
if let Some(translated) = translate_simple_ternary(source, ctx) {
return Some(translated);
}
let wrapped = format!("<?php {source};");
let tree = php::parse(&wrapped).ok()?;
if php::has_syntax_error(&tree) {
return None;
}
let stmt = php::statement_expressions(tree.root_node())
.into_iter()
.next()?;
let translated = translate(stmt, &wrapped, ctx)?;
syn::parse_str::<syn::Expr>(&translated).ok()?;
Some(translated)
}
fn translate_simple_ternary(source: &str, ctx: &ConvertContext) -> Option<String> {
let question = source.find('?')?;
let colon = source[question + 1..].find(':')? + question + 1;
let condition_raw = source[..question].trim();
let when_true_raw = source[question + 1..colon].trim();
let when_false_raw = source[colon + 1..].trim();
if let Some(translated) =
translate_isset_ternary_idiom_text(condition_raw, when_true_raw, when_false_raw, ctx)
{
return Some(translated);
}
let condition = translate_expression(condition_raw, ctx)?;
if when_true_raw.eq_ignore_ascii_case("null") || when_false_raw.eq_ignore_ascii_case("null") {
let when_true = translate_null_coerced_branch(when_true_raw, ctx)?;
let when_false = translate_null_coerced_branch(when_false_raw, ctx)?;
return Some(format!(
"if larust_support::truthy::truthy(&({condition})) {{ {when_true} }} else {{ {when_false} }}"
));
}
let when_true = translate_expression(when_true_raw, ctx)?;
let when_false = translate_expression(when_false_raw, ctx)?;
if looks_like_php_string_literal(when_true_raw) || looks_like_php_string_literal(when_false_raw)
{
return Some(format!(
"if larust_support::truthy::truthy(&({condition})) {{ ({when_true}).to_string() }} else {{ ({when_false}).to_string() }}"
));
}
Some(format!(
"if larust_support::truthy::truthy(&({condition})) {{ {when_true} }} else {{ {when_false} }}"
))
}
fn looks_like_php_string_literal(text: &str) -> bool {
matches!(text.trim().chars().next(), Some('\'') | Some('"'))
}
fn translate_null_coerced_branch(raw: &str, ctx: &ConvertContext) -> Option<String> {
if raw.eq_ignore_ascii_case("null") {
Some("String::new()".to_string())
} else {
let translated = translate_expression(raw, ctx)?;
Some(format!("({translated}).to_string()"))
}
}
fn translate_isset_ternary_idiom_text(
condition_raw: &str,
when_true_raw: &str,
when_false_raw: &str,
ctx: &ConvertContext,
) -> Option<String> {
let isset_arg = condition_raw
.strip_prefix("isset(")
.and_then(|rest| rest.strip_suffix(')'))?;
if isset_arg.trim() != when_true_raw {
return None;
}
translate_expression(&format!("{when_true_raw} ?? {when_false_raw}"), ctx)
}
fn translate_isset_ternary_idiom(
condition: Node,
body: Node,
alternative: Node,
source: &str,
ctx: &ConvertContext,
) -> Option<String> {
let bytes = source.as_bytes();
translate_isset_ternary_idiom_text(
condition.utf8_text(bytes).ok()?.trim(),
body.utf8_text(bytes).ok()?.trim(),
alternative.utf8_text(bytes).ok()?.trim(),
ctx,
)
}
fn translate_null_branch_ternary(
condition: Node,
body: Node,
alternative: Node,
source: &str,
ctx: &ConvertContext,
) -> Option<String> {
let body_is_null = body.kind() == "null";
let alternative_is_null = alternative.kind() == "null";
if !body_is_null && !alternative_is_null {
return None;
}
let condition_text = translate(condition, source, ctx)?;
let body_text = if body_is_null {
"String::new()".to_string()
} else {
format!("({}).to_string()", translate(body, source, ctx)?)
};
let alternative_text = if alternative_is_null {
"String::new()".to_string()
} else {
format!("({}).to_string()", translate(alternative, source, ctx)?)
};
Some(format!(
"if larust_support::truthy::truthy(&({condition_text})) {{ {body_text} }} else {{ {alternative_text} }}"
))
}
pub fn translate_binding(source: &str) -> Option<String> {
let source = source.trim();
if let Some((key, item)) = source.split_once("=>") {
let key = translate_single_binding(key)?;
let item = translate_single_binding(item)?;
return Some(format!("({key}, {item})"));
}
translate_single_binding(source)
}
pub fn is_keyed_binding(source: &str) -> bool {
source.trim().contains("=>")
}
fn translate_single_binding(source: &str) -> Option<String> {
let name = source.trim().strip_prefix('$')?.trim();
let escaped = if crate::codegen::is_rust_keyword(name) {
format!("{name}_")
} else {
name.to_string()
};
crate::codegen::validate_identifier(&escaped).ok()?;
Some(escaped)
}
pub fn translate_php_block(php_source: &str, ctx: &ConvertContext) -> Option<String> {
let wrapped = format!("<?php\n{php_source}\n");
let tree = php::parse(&wrapped).ok()?;
if php::has_syntax_error(&tree) {
return None;
}
let root = tree.root_node();
let statements = php::statement_expressions(root);
if statements.is_empty() || root.named_child_count() != statements.len() + 1 {
return None;
}
let mut lines = Vec::with_capacity(statements.len());
for stmt in statements {
match stmt.kind() {
"assignment_expression" => {
let left = stmt.child_by_field_name("left")?;
let right = stmt.child_by_field_name("right")?;
if left.kind() != "variable_name" {
return None;
}
let name = left.named_child(0)?.utf8_text(wrapped.as_bytes()).ok()?;
crate::codegen::validate_identifier(name).ok()?;
let value = translate(right, &wrapped, ctx)?;
lines.push(format!("let mut {name} = {value};"));
}
"update_expression" => {
let argument = stmt.child_by_field_name("argument")?;
if argument.kind() != "variable_name" {
return None;
}
let name = argument
.named_child(0)?
.utf8_text(wrapped.as_bytes())
.ok()?;
crate::codegen::validate_identifier(name).ok()?;
let text = stmt.utf8_text(wrapped.as_bytes()).ok()?;
let op = if text.contains("++") {
"+= 1"
} else if text.contains("--") {
"-= 1"
} else {
return None;
};
lines.push(format!("{name} {op};"));
}
_ => return None,
}
}
let joined = lines.join(" ");
syn::parse_str::<syn::Block>(&format!("{{ {joined} }}")).ok()?;
Some(joined)
}
pub fn php_block_assigned_variable_names(php_source: &str) -> std::collections::HashSet<String> {
let wrapped = format!("<?php\n{php_source}\n");
let mut names = std::collections::HashSet::new();
let Ok(tree) = php::parse(&wrapped) else {
return names;
};
collect_assigned_variable_names(tree.root_node(), wrapped.as_bytes(), &mut names);
names
}
fn collect_assigned_variable_names(
node: Node,
bytes: &[u8],
names: &mut std::collections::HashSet<String>,
) {
if node.kind() == "assignment_expression" {
if let Some(left) = node.child_by_field_name("left") {
if left.kind() == "variable_name" {
if let Some(name_node) = left.named_child(0) {
if let Ok(name) = name_node.utf8_text(bytes) {
names.insert(name.to_string());
}
}
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect_assigned_variable_names(child, bytes, names);
}
}
fn translate(node: Node, source: &str, ctx: &ConvertContext) -> Option<String> {
let bytes = source.as_bytes();
match node.kind() {
"variable_name" => {
let name = node.named_child(0)?.utf8_text(bytes).ok()?;
if ctx.tainted_vars.borrow().contains(name) {
None
} else if name == "_GET" {
Some("query".to_string())
} else if is_superglobal(name) {
None
} else if crate::codegen::is_rust_keyword(name) {
Some(format!("{name}_"))
} else {
Some(name.to_string())
}
}
"member_access_expression" => {
let object = node.child_by_field_name("object")?;
let name = node.child_by_field_name("name")?;
let object_text = translate(object, source, ctx)?;
Some(format!("{object_text}.{}", name.utf8_text(bytes).ok()?))
}
"boolean" | "integer" | "float" => Some(node.utf8_text(bytes).ok()?.to_string()),
"string" => {
let raw = node.utf8_text(bytes).ok()?;
let text = php::unquote(raw);
Some(format!("{text:?}"))
}
"encapsed_string" => translate_interpolated_string(node.utf8_text(bytes).ok()?),
"parenthesized_expression" => {
let inner = node.named_child(0)?;
translate(inner, source, ctx)
}
"unary_op_expression" => {
let argument = node.child_by_field_name("argument")?;
let operator = source.get(node.start_byte()..argument.start_byte())?.trim();
if operator != "!" {
return None;
}
let inner = translate(argument, source, ctx)?;
Some(format!("!larust_support::truthy::truthy(&({inner}))"))
}
"binary_expression" => {
let left = node.child_by_field_name("left")?;
let right = node.child_by_field_name("right")?;
let operator = source.get(left.end_byte()..right.start_byte())?.trim();
if operator == "??" {
let (object, key) = string_keyed_subscript(left, source)?;
let object_text = translate(object, source, ctx)?;
let fallback_text = translate(right, source, ctx)?;
return Some(format!(
"({object_text}).get({key:?}).cloned().unwrap_or_else(|| ({fallback_text}).to_string())"
));
}
let left_text = translate(left, source, ctx)?;
let right_text = translate(right, source, ctx)?;
if operator == "." {
Some(format!("format!(\"{{}}{{}}\", {left_text}, {right_text})"))
} else {
let rust_op = map_operator(operator)?;
Some(format!("({left_text}) {rust_op} ({right_text})"))
}
}
"subscript_expression" => {
let object = node.named_child(0)?;
let index = node.named_child(1)?;
let object_text = translate(object, source, ctx)?;
let index_text = translate(index, source, ctx)?;
Some(format!("{object_text}[{index_text}]"))
}
"conditional_expression" => {
let condition = node.child_by_field_name("condition")?;
let body = node.child_by_field_name("body")?;
let alternative = node.child_by_field_name("alternative")?;
if let Some(translated) =
translate_isset_ternary_idiom(condition, body, alternative, source, ctx)
{
return Some(translated);
}
if let Some(translated) =
translate_null_branch_ternary(condition, body, alternative, source, ctx)
{
return Some(translated);
}
let condition_text = translate(condition, source, ctx)?;
let body_text = translate(body, source, ctx)?;
let alternative_text = translate(alternative, source, ctx)?;
let body_is_literal = matches!(body.kind(), "string" | "encapsed_string");
let alternative_is_literal = matches!(alternative.kind(), "string" | "encapsed_string");
if body_is_literal || alternative_is_literal {
return Some(format!(
"if larust_support::truthy::truthy(&({condition_text})) {{ ({body_text}).to_string() }} else {{ ({alternative_text}).to_string() }}"
));
}
Some(format!(
"if larust_support::truthy::truthy(&({condition_text})) {{ {body_text} }} else {{ {alternative_text} }}"
))
}
"scoped_call_expression" => {
let scope = node.child_by_field_name("scope")?;
let scope_text = scope.utf8_text(bytes).ok()?;
let name = node.child_by_field_name("name")?;
let name_text = name.utf8_text(bytes).ok()?;
if scope.kind() == "name" && scope_text == "Vite" && name_text == "asset" {
let arg = php::argument_node(node, 0)?;
if arg.kind() != "string" {
return None;
}
let source_path = php::unquote(arg.utf8_text(bytes).ok()?);
let served_path = source_path
.strip_prefix("resources/")
.unwrap_or(&source_path);
return Some(format!("larust_support::asset({served_path:?})"));
}
let is_str_facade = (scope.kind() == "qualified_name"
&& scope_text.trim_start_matches('\\') == "Illuminate\\Support\\Str")
|| (scope.kind() == "name" && scope_text == "Str");
if is_str_facade && name_text == "startsWith" {
let subject = php::argument_node(node, 0)?;
let subject_text = translate(subject, source, ctx)?;
let prefixes_arg = php::argument_node(node, 1)?;
if prefixes_arg.kind() != "array_creation_expression" {
return None;
}
let mut checks = Vec::new();
for i in 0..prefixes_arg.named_child_count() {
let element = prefixes_arg.named_child(i)?;
if element.kind() != "array_element_initializer" {
return None;
}
let value = element.named_child(0)?;
let prefix_text = translate(value, source, ctx)?;
checks.push(format!("({subject_text}).starts_with({prefix_text})"));
}
if checks.is_empty() {
return None;
}
return Some(checks.join(" || "));
}
None
}
"function_call_expression" => {
let function = node.child_by_field_name("function")?;
let function = function.utf8_text(bytes).ok()?;
if function == "csrf_token" {
return Some("csrf_token".to_string());
}
let arg = php::argument_node(node, 0)?;
if function == "empty" {
let arg_text = translate(arg, source, ctx)?;
Some(format!("({arg_text}).is_empty()"))
} else if function == "trim" {
let text = translate(arg, source, ctx)?;
Some(format!("({text}).trim().to_string()"))
} else if function == "count" {
let text = translate(arg, source, ctx)?;
Some(format!("({text}).len()"))
} else if function == "ucwords" {
let text = translate(arg, source, ctx)?;
Some(format!("larust_support::strings::ucwords(&({text}))"))
} else if function == "strtolower" {
let text = translate(arg, source, ctx)?;
Some(format!("({text}).to_lowercase()"))
} else if function == "substr_count" {
let needle = php::argument_node(node, 1)?;
let haystack_text = translate(arg, source, ctx)?;
let needle_text = translate(needle, source, ctx)?;
Some(format!("({haystack_text}).matches({needle_text}).count()"))
} else if function == "isset" {
let (object, key) = string_keyed_subscript(arg, source)?;
let object_text = translate(object, source, ctx)?;
Some(format!("({object_text}).contains_key({key:?})"))
} else if function == "config" {
let key = php::unquote(arg.utf8_text(bytes).ok()?);
if is_known_config_helper_key(&key) {
return Some(format!(
"larust_support::config({key:?}).unwrap_or_default()"
));
}
let (file, top_key) = key.split_once('.')?;
if ctx.resolved_config_keys.contains(&key) {
Some(format!(
"crate::config::{file}::config()[{top_key:?}].as_str().unwrap_or_default().to_string()"
))
} else {
None
}
} else if function == "str_contains" {
let needle = php::argument_node(node, 1)?;
let haystack = translate(arg, source, ctx)?;
let needle = translate(needle, source, ctx)?;
Some(format!("({haystack}).contains(&({needle}))"))
} else if function == "str_replace" {
let replace = php::argument_node(node, 1)?;
let subject = php::argument_node(node, 2)?;
let search_text = translate(arg, source, ctx)?;
let replace_text = translate(replace, source, ctx)?;
let subject_text = translate(subject, source, ctx)?;
Some(format!(
"({subject_text}).replace({search_text}, {replace_text})"
))
} else if function == "explode" {
if php::argument_node(node, 2).is_some() {
return None;
}
let string_arg = php::argument_node(node, 1)?;
let separator_text = translate(arg, source, ctx)?;
let string_text = translate(string_arg, source, ctx)?;
Some(format!(
"({string_text}).split({separator_text}).map(|s| s.to_string()).collect::<Vec<String>>()"
))
} else if function == "preg_replace" {
if arg.kind() != "string" || php::argument_node(node, 3).is_some() {
return None;
}
let replacement = php::argument_node(node, 1)?;
let subject = php::argument_node(node, 2)?;
let raw = php::unquote(arg.utf8_text(bytes).ok()?);
let unescaped = unescape_single_quoted_php_string(&raw);
let pattern = translate_pcre_pattern(&unescaped)?;
if regex::Regex::new(&pattern).is_err() {
return None;
}
let replacement_text = translate(replacement, source, ctx)?;
let subject_text = translate(subject, source, ctx)?;
Some(format!(
"larust_support::regex_replace::replace_all({pattern:?}, {replacement_text}, {subject_text})"
))
} else if function == "date" {
let format_string = php::unquote(arg.utf8_text(bytes).ok()?);
if !is_supported_php_date_format(&format_string) {
return None;
}
let when = match php::argument_node(node, 1) {
None => "larust_support::date::now()".to_string(),
Some(second_arg) => {
if second_arg.kind() != "function_call_expression" {
return None;
}
let inner_function = second_arg.child_by_field_name("function")?;
if inner_function.utf8_text(bytes).ok()? != "strtotime" {
return None;
}
let strtotime_arg = php::argument_node(second_arg, 0)?;
let strtotime_arg_text = translate(strtotime_arg, source, ctx)?;
format!("larust_support::date::strtotime(&({strtotime_arg_text}))")
}
};
Some(format!(
"larust_support::date::format({when}, {format_string:?})"
))
} else {
None
}
}
_ => None,
}
}
fn string_keyed_subscript<'a>(node: Node<'a>, source: &str) -> Option<(Node<'a>, String)> {
if node.kind() != "subscript_expression" {
return None;
}
let object = node.named_child(0)?;
let index = node.named_child(1)?;
if index.kind() != "string" {
return None;
}
let key = php::unquote(index.utf8_text(source.as_bytes()).ok()?);
Some((object, key))
}
fn is_known_config_helper_key(key: &str) -> bool {
matches!(
key,
"app.name"
| "app.env"
| "app.url"
| "app.port"
| "app.debug"
| "session.secure_cookie"
| "mail.driver"
| "mail.host"
| "mail.port"
| "mail.from_address"
| "mail.from_name"
)
}
fn is_superglobal(name: &str) -> bool {
matches!(
name,
"_POST" | "_REQUEST" | "_SERVER" | "_SESSION" | "_COOKIE" | "_FILES" | "_ENV" | "GLOBALS"
)
}
fn is_supported_php_date_format(format_string: &str) -> bool {
const RECOGNIZED_CODES: &str = "YymndjFMlDHGhgisAaNwS";
const LITERAL_SEPARATORS: &str = " -/:,.";
format_string
.chars()
.all(|ch| RECOGNIZED_CODES.contains(ch) || LITERAL_SEPARATORS.contains(ch))
}
fn unescape_single_quoted_php_string(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut chars = raw.chars().peekable();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.peek() {
Some('\\') => {
out.push('\\');
chars.next();
}
Some('\'') => {
out.push('\'');
chars.next();
}
_ => out.push('\\'),
}
}
out
}
fn translate_pcre_pattern(value: &str) -> Option<String> {
let mut chars = value.chars();
let delimiter = chars.next()?;
if delimiter.is_alphanumeric()
|| delimiter.is_whitespace()
|| matches!(
delimiter,
'\\' | '(' | ')' | '{' | '}' | '[' | ']' | '<' | '>'
)
{
return None;
}
let rest = chars.as_str();
let closing = find_unescaped_delimiter(rest, delimiter)?;
let body = &rest[..closing];
let flags = &rest[closing + delimiter.len_utf8()..];
let mut prefix_flags = String::new();
for flag in flags.chars() {
match flag {
'i' | 'm' | 's' => prefix_flags.push(flag),
'u' => {}
_ => return None,
}
}
if prefix_flags.is_empty() {
Some(body.to_string())
} else {
Some(format!("(?{prefix_flags}){body}"))
}
}
fn find_unescaped_delimiter(s: &str, delimiter: char) -> Option<usize> {
let mut chars = s.char_indices();
while let Some((i, c)) = chars.next() {
if c == '\\' {
chars.next();
} else if c == delimiter {
return Some(i);
}
}
None
}
fn translate_interpolated_string(raw: &str) -> Option<String> {
let text = php::unquote(raw);
if !text.contains('$') {
return Some(format!("{text:?}"));
}
let mut format = String::new();
let mut args = Vec::new();
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
if ch != '$' {
format.push(ch);
continue;
}
let mut name = String::new();
while let Some(&next) = chars.peek() {
if next.is_ascii_alphanumeric() || next == '_' {
name.push(next);
chars.next();
} else {
break;
}
}
if name.is_empty() {
return None;
}
let escaped = if crate::codegen::is_rust_keyword(&name) {
format!("{name}_")
} else {
name
};
if crate::codegen::validate_identifier(&escaped).is_err() {
return None;
}
format.push_str("{}");
args.push(escaped);
}
Some(format!("format!({format:?}, {})", args.join(", ")))
}
fn map_operator(php_operator: &str) -> Option<&'static str> {
match php_operator {
"&&" => Some("&&"),
"||" => Some("||"),
"==" | "===" => Some("=="),
"!=" | "!==" | "<>" => Some("!="),
"<" => Some("<"),
">" => Some(">"),
"<=" => Some("<="),
">=" => Some(">="),
"+" => Some("+"),
"-" => Some("-"),
"*" => Some("*"),
"/" => Some("/"),
"%" => Some("%"),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_ctx {
() => {
&ConvertContext {
laravel_root: std::path::Path::new("/nonexistent"),
resolved_config_keys: &std::collections::HashSet::new(),
tainted_vars: std::cell::RefCell::new(std::collections::HashSet::new()),
degraded_spot_count: std::cell::Cell::new(0),
}
};
($($key:expr),+ $(,)?) => {
&ConvertContext {
laravel_root: std::path::Path::new("/nonexistent"),
resolved_config_keys: &[$($key.to_string()),+]
.into_iter()
.collect::<std::collections::HashSet<String>>(),
tainted_vars: std::cell::RefCell::new(std::collections::HashSet::new()),
degraded_spot_count: std::cell::Cell::new(0),
}
};
}
#[test]
fn translates_a_bare_variable() {
assert_eq!(
translate_expression("$x", test_ctx!()),
Some("x".to_string())
);
}
#[test]
fn translates_a_property_chain() {
assert_eq!(
translate_expression("$post->title", test_ctx!()),
Some("post.title".to_string())
);
assert_eq!(
translate_expression("$post->author->name", test_ctx!()),
Some("post.author.name".to_string())
);
}
#[test]
fn translates_literals() {
assert_eq!(
translate_expression("true", test_ctx!()),
Some("true".to_string())
);
assert_eq!(
translate_expression("42", test_ctx!()),
Some("42".to_string())
);
assert_eq!(
translate_expression("4.2", test_ctx!()),
Some("4.2".to_string())
);
assert_eq!(
translate_expression("'hello'", test_ctx!()),
Some("\"hello\"".to_string())
);
}
#[test]
fn translates_unary_not() {
assert_eq!(
translate_expression("!$x", test_ctx!()),
Some("!larust_support::truthy::truthy(&(x))".to_string())
);
}
#[test]
fn translates_comparison_and_logical_operators() {
assert_eq!(
translate_expression("$x == $y", test_ctx!()),
Some("(x) == (y)".to_string())
);
assert_eq!(
translate_expression("$current == \"home\"", test_ctx!()),
Some("(current) == (\"home\")".to_string())
);
assert_eq!(
translate_expression("$x && $y", test_ctx!()),
Some("(x) && (y)".to_string())
);
}
#[test]
fn collapses_strict_equality_to_rusts_single_form() {
assert_eq!(
translate_expression("$x === $y", test_ctx!()),
Some("(x) == (y)".to_string())
);
assert_eq!(
translate_expression("$x !== $y", test_ctx!()),
Some("(x) != (y)".to_string())
);
assert_eq!(
translate_expression("$x <> $y", test_ctx!()),
Some("(x) != (y)".to_string())
);
}
#[test]
fn rejects_keyword_form_logical_operators() {
assert_eq!(translate_expression("$x and $y", test_ctx!()), None);
assert_eq!(translate_expression("$x or $y", test_ctx!()), None);
}
#[test]
fn translates_empty_and_not_empty() {
assert_eq!(
translate_expression("empty($x)", test_ctx!()),
Some("(x).is_empty()".to_string())
);
assert_eq!(
translate_expression("!empty($x)", test_ctx!()),
Some("!larust_support::truthy::truthy(&((x).is_empty()))".to_string())
);
}
#[test]
fn rejects_isset_and_other_function_calls() {
assert_eq!(translate_expression("isset($x)", test_ctx!()), None);
assert_eq!(
translate_expression("route('posts.show')", test_ctx!()),
None
);
assert_eq!(
translate_expression("$post->getExcerpt()", test_ctx!()),
None
);
}
#[test]
fn translates_isset_over_a_string_keyed_subscript_to_contains_key() {
assert_eq!(
translate_expression("isset($data['keywords'])", test_ctx!()),
Some(r#"(data).contains_key("keywords")"#.to_string())
);
}
#[test]
fn rejects_isset_over_an_integer_indexed_subscript() {
assert_eq!(translate_expression("isset($arr[0])", test_ctx!()), None);
}
#[test]
fn translates_ternary_to_an_if_else_expression() {
assert_eq!(
translate_expression("$cond == true ? $a : $b", test_ctx!()),
Some(
"if larust_support::truthy::truthy(&((cond) == (true))) { a } else { b }"
.to_string()
)
);
}
#[test]
fn a_ternary_with_one_computed_and_one_literal_branch_coerces_both_to_string() {
let translated = translate_expression(
r#"$type !== '' && $type !== 'slant' ? "{$position}-{$type}" : $position"#,
test_ctx!(),
)
.unwrap();
assert!(translated.contains(").to_string() } else {"));
assert!(translated.ends_with(").to_string() }"));
}
#[test]
fn a_boolean_ternary_is_never_coerced_to_string() {
let translated = translate_expression(
r#"$q ? substr_count($item['keywords'], $q) > 0 : true"#,
test_ctx!(),
)
.unwrap();
assert!(!translated.contains(".to_string()"));
}
#[test]
fn translates_a_ternary_with_a_bare_variable_condition_via_the_truthy_helper() {
assert_eq!(
translate_expression("$q ? $a : $b", test_ctx!()),
Some("if larust_support::truthy::truthy(&(q)) { a } else { b }".to_string())
);
}
#[test]
fn translates_a_ternary_with_a_comparison_and_strings() {
assert_eq!(
translate_expression("$current == \"home\" ? \"active\" : \"idle\"", test_ctx!()),
Some(
"if larust_support::truthy::truthy(&((current) == (\"home\"))) { (\"active\").to_string() } else { (\"idle\").to_string() }"
.to_string()
)
);
}
#[test]
fn translates_vite_asset_stripping_the_resources_prefix() {
assert_eq!(
translate_expression("Vite::asset('resources/css/app.css')", test_ctx!()),
Some(r#"larust_support::asset("css/app.css")"#.to_string())
);
}
#[test]
fn translates_vite_asset_without_a_resources_prefix_unchanged() {
assert_eq!(
translate_expression("Vite::asset('images/logo.svg')", test_ctx!()),
Some(r#"larust_support::asset("images/logo.svg")"#.to_string())
);
}
#[test]
fn rejects_other_static_method_calls() {
assert_eq!(translate_expression("Vite::hotReload()", test_ctx!()), None);
assert_eq!(
translate_expression(r"\Illuminate\Support\Str::endsWith($x, ['a'])", test_ctx!()),
None
);
}
#[test]
fn translates_a_top_level_ternary_with_a_null_false_branch() {
assert_eq!(
translate_expression("$x ? $x : null", test_ctx!()),
Some(
"if larust_support::truthy::truthy(&(x)) { (x).to_string() } else { String::new() }"
.to_string()
)
);
}
#[test]
fn translates_a_top_level_ternary_with_a_null_true_branch() {
assert_eq!(
translate_expression("$x ? null : $x", test_ctx!()),
Some(
"if larust_support::truthy::truthy(&(x)) { String::new() } else { (x).to_string() }"
.to_string()
)
);
}
#[test]
fn translates_a_nested_ternary_with_a_null_branch_reached_through_a_function_argument() {
let translated = translate_expression("trim($x ? $x : null)", test_ctx!()).unwrap();
assert!(translated.contains("String::new()"));
assert!(translated.contains("larust_support::truthy::truthy"));
assert!(syn::parse_str::<syn::Expr>(&translated).is_ok());
}
#[test]
fn a_null_ternary_assignment_still_parses_alongside_a_later_interpolation() {
let assignment =
translate_php_block("$previewUrl = $cond ? $x : null;", test_ctx!()).unwrap();
let full = format!(
"fn render(cond: bool, x: String) -> String {{ {assignment} format!(\"{{}}\", previewUrl) }}"
);
assert!(
syn::parse_str::<syn::ItemFn>(&full).is_ok(),
"generated code failed to parse as a function: {full}"
);
}
#[test]
fn translates_preg_replace_with_a_slash_delimited_pattern_and_backreference_replacement() {
let source = r#"preg_replace('/(^|["\'(\s])\/storage/', '$1' . config('app.apiurl') . '/storage', $body)"#;
let translated = translate_expression(source, test_ctx!("app.apiurl")).unwrap();
assert!(translated.starts_with("larust_support::regex_replace::replace_all("));
assert!(translated.contains(r#""(^|[\"'(\\s])\\/storage""#));
assert!(translated.contains(r#"crate::config::app::config()["apiurl"]"#));
assert!(translated.ends_with("body)"));
assert!(syn::parse_str::<syn::Expr>(&translated).is_ok());
}
#[test]
fn rejects_preg_replace_with_a_double_quoted_pattern() {
assert_eq!(
translate_expression(r#"preg_replace("/a/", 'b', $x)"#, test_ctx!()),
None
);
}
#[test]
fn rejects_preg_replace_with_the_array_form() {
assert_eq!(
translate_expression(r"preg_replace(['/a/', '/b/'], 'x', $y)", test_ctx!()),
None
);
}
#[test]
fn rejects_preg_replace_with_a_bracket_delimiter() {
assert_eq!(
translate_expression(r"preg_replace('(a)', 'b', $x)", test_ctx!()),
None
);
}
#[test]
fn rejects_preg_replace_with_an_unrecognized_flag() {
assert_eq!(
translate_expression(r"preg_replace('/a/x', 'b', $x)", test_ctx!()),
None
);
}
#[test]
fn rejects_preg_replace_with_a_pcre_construct_rust_regex_does_not_support() {
assert_eq!(
translate_expression(r"preg_replace('/foo(?=bar)/', 'x', $y)", test_ctx!()),
None
);
}
#[test]
fn translates_str_starts_with_against_an_array_of_prefixes() {
assert_eq!(
translate_expression(
r"\Illuminate\Support\Str::startsWith($x, ['a'])",
test_ctx!()
),
Some(r#"(x).starts_with("a")"#.to_string())
);
assert_eq!(
translate_expression(
r"\Illuminate\Support\Str::startsWith($x, ['http://', 'https://'])",
test_ctx!()
),
Some(r#"(x).starts_with("http://") || (x).starts_with("https://")"#.to_string())
);
assert_eq!(
translate_expression(r"Str::startsWith($x, ['a'])", test_ctx!()),
Some(r#"(x).starts_with("a")"#.to_string())
);
}
#[test]
fn translates_str_replace_and_explode() {
assert_eq!(
translate_expression("str_replace('_', ' ', $x)", test_ctx!()),
Some(r#"(x).replace("_", " ")"#.to_string())
);
assert_eq!(
translate_expression("explode(',', $x)", test_ctx!()),
Some(r#"(x).split(",").map(|s| s.to_string()).collect::<Vec<String>>()"#.to_string())
);
}
#[test]
fn rejects_explode_with_a_limit_argument() {
assert_eq!(
translate_expression("explode(',', $x, 2)", test_ctx!()),
None
);
}
#[test]
fn translates_trim_count_and_ucwords() {
assert_eq!(
translate_expression("trim($x)", test_ctx!()),
Some("(x).trim().to_string()".to_string())
);
assert_eq!(
translate_expression("count($keywords)", test_ctx!()),
Some("(keywords).len()".to_string())
);
assert_eq!(
translate_expression("ucwords($item['page'])", test_ctx!()),
Some(r#"larust_support::strings::ucwords(&(item["page"]))"#.to_string())
);
}
#[test]
fn translates_strtolower_and_substr_count() {
assert_eq!(
translate_expression("strtolower($x)", test_ctx!()),
Some("(x).to_lowercase()".to_string())
);
assert_eq!(
translate_expression("substr_count($haystack, $needle)", test_ctx!()),
Some("(haystack).matches(needle).count()".to_string())
);
}
#[test]
fn translates_the_real_world_substr_count_filter_shape() {
assert_eq!(
translate_expression(r#"$q ? substr_count($item['keywords'], $q) > 0 : true"#, test_ctx!()),
Some(
r#"if larust_support::truthy::truthy(&(q)) { ((item["keywords"]).matches(q).count()) > (0) } else { true }"#
.to_string()
)
);
}
#[test]
fn translates_count_inside_a_comparison() {
assert_eq!(
translate_expression("count($keywords) > 1", test_ctx!()),
Some("((keywords).len()) > (1)".to_string())
);
}
#[test]
fn rejects_str_replace_with_array_arguments() {
assert_eq!(
translate_expression("str_replace(['a', 'b'], 'c', $x)", test_ctx!()),
None
);
}
#[test]
fn rejects_php_superglobals_other_than_get() {
assert_eq!(translate_expression("$_POST", test_ctx!()), None);
assert_eq!(translate_expression("$_POST['q']", test_ctx!()), None);
assert_eq!(
translate_expression("isset($_SERVER['q'])", test_ctx!()),
None
);
}
#[test]
fn translates_get_to_the_query_context_variable() {
assert_eq!(
translate_expression("$_GET", test_ctx!()),
Some("query".to_string())
);
assert_eq!(
translate_expression("$_GET['q']", test_ctx!()),
Some(r#"query["q"]"#.to_string())
);
assert_eq!(
translate_expression("isset($_GET['q'])", test_ctx!()),
Some(r#"(query).contains_key("q")"#.to_string())
);
assert_eq!(
translate_expression("$_GET['q'] ?? ''", test_ctx!()),
Some(r#"(query).get("q").cloned().unwrap_or_else(|| ("").to_string())"#.to_string())
);
}
#[test]
fn translates_the_isset_ternary_idiom_the_same_way_as_null_coalescing() {
assert_eq!(
translate_expression(r#"isset($_GET['q']) ? $_GET['q'] : """#, test_ctx!()),
Some(r#"(query).get("q").cloned().unwrap_or_else(|| ("").to_string())"#.to_string())
);
}
#[test]
fn translates_the_isset_ternary_idiom_when_nested_inside_a_function_call() {
assert_eq!(
translate_expression(r#"str_replace('_', ' ', isset($_GET['q']) ? $_GET['q'] : "")"#, test_ctx!()),
Some(
r#"((query).get("q").cloned().unwrap_or_else(|| ("").to_string())).replace("_", " ")"#
.to_string()
)
);
}
#[test]
fn does_not_misfire_the_isset_ternary_idiom_on_an_unrelated_ternary() {
assert_eq!(
translate_expression(r#"$q == trim($word) ? "a" : "b""#, test_ctx!()),
Some(
r#"if larust_support::truthy::truthy(&((q) == ((word).trim().to_string()))) { ("a").to_string() } else { ("b").to_string() }"#
.to_string()
)
);
}
#[test]
fn does_not_misfire_the_isset_ternary_idiom_when_the_branches_differ() {
assert_eq!(
translate_expression(r#"isset($item['a']) ? $item['b'] : "x""#, test_ctx!()),
Some(
r#"if larust_support::truthy::truthy(&((item).contains_key("a"))) { (item["b"]).to_string() } else { ("x").to_string() }"#
.to_string()
)
);
}
#[test]
fn translates_a_php_block_of_simple_assignments_to_code_block_statements() {
let translated = translate_php_block(
r#"$keywords = explode(",", str_replace('"', "", $item['keywords']));"#,
test_ctx!(),
)
.unwrap();
assert_eq!(
translated,
r#"let mut keywords = ((item["keywords"]).replace("\"", "")).split(",").map(|s| s.to_string()).collect::<Vec<String>>();"#
);
}
#[test]
fn translates_multiple_assignment_statements_in_order() {
let translated = translate_php_block("$a = $x; $b = $a;", test_ctx!()).unwrap();
assert_eq!(translated, "let mut a = x; let mut b = a;");
}
#[test]
fn translates_an_increment_and_decrement_statement() {
let translated = translate_php_block("$x = 0; $x++; $x--;", test_ctx!()).unwrap();
assert_eq!(translated, "let mut x = 0; x += 1; x -= 1;");
}
#[test]
fn rejects_a_php_block_containing_a_superglobal() {
assert_eq!(
translate_php_block(r#"$q = str_replace('_', " ", $_POST['q']);"#, test_ctx!()),
None
);
}
#[test]
fn rejects_a_php_block_with_a_non_assignment_statement() {
assert_eq!(
translate_php_block(r#"$a = $x; if ($a) { $b = $y; }"#, test_ctx!()),
None
);
}
#[test]
fn rejects_a_php_block_with_an_unsupported_assignment_target() {
assert_eq!(translate_php_block(r#"$arr['x'] = $y;"#, test_ctx!()), None);
}
#[test]
fn translates_csrf_token_to_the_bare_context_variable() {
assert_eq!(
translate_expression("csrf_token()", test_ctx!()),
Some("csrf_token".to_string())
);
}
#[test]
fn translates_a_single_argument_date_call() {
assert_eq!(
translate_expression("date('Y')", test_ctx!()),
Some(r#"larust_support::date::format(larust_support::date::now(), "Y")"#.to_string())
);
assert_eq!(
translate_expression("date(\"F jS, Y\")", test_ctx!()),
Some(
r#"larust_support::date::format(larust_support::date::now(), "F jS, Y")"#
.to_string()
)
);
}
#[test]
fn translates_date_with_a_strtotime_second_argument() {
assert_eq!(
translate_expression("date('Y-m-d', strtotime($x))", test_ctx!()),
Some(
r#"larust_support::date::format(larust_support::date::strtotime(&(x)), "Y-m-d")"#
.to_string()
)
);
}
#[test]
fn rejects_date_with_a_non_strtotime_second_argument() {
assert_eq!(
translate_expression("date('Y', $timestamp)", test_ctx!()),
None
);
assert_eq!(translate_expression("date('Y', time())", test_ctx!()), None);
}
#[test]
fn rejects_date_with_an_unrecognized_format_character() {
assert_eq!(translate_expression("date('W')", test_ctx!()), None);
}
#[test]
fn translates_a_known_config_helper_key_to_a_direct_runtime_call() {
assert_eq!(
translate_expression("config('app.url')", test_ctx!()),
Some(r#"larust_support::config("app.url").unwrap_or_default()"#.to_string())
);
}
#[test]
fn translates_a_resolved_generated_config_key_to_a_module_indexing_expression() {
assert_eq!(
translate_expression("config('app.apiurl')", test_ctx!("app.apiurl")),
Some(
r#"crate::config::app::config()["apiurl"].as_str().unwrap_or_default().to_string()"#
.to_string()
)
);
}
#[test]
fn rejects_a_config_key_with_no_known_helper_home_and_no_generated_module() {
assert_eq!(
translate_expression("config('app.apiurl')", test_ctx!()),
None
);
}
#[test]
fn translates_common_string_helpers() {
assert_eq!(
translate_expression("str_contains($url, 'blog')", test_ctx!()),
Some("(url).contains(&(\"blog\"))".to_string())
);
assert_eq!(
translate_expression("$path . '/hosting'", test_ctx!()),
Some("format!(\"{}{}\", path, \"/hosting\")".to_string())
);
}
#[test]
fn translates_string_concatenation() {
assert_eq!(
translate_expression("$x . $y", test_ctx!()),
Some("format!(\"{}{}\", x, y)".to_string())
);
}
#[test]
fn rejects_null_coalescing() {
assert_eq!(translate_expression("$x ?? $y", test_ctx!()), None);
}
#[test]
fn translates_null_coalescing_over_a_string_keyed_subscript() {
assert_eq!(
translate_expression("$item['created_at'] ?? $fallback", test_ctx!()),
Some(
r#"(item).get("created_at").cloned().unwrap_or_else(|| (fallback).to_string())"#
.to_string()
)
);
}
#[test]
fn translates_null_coalescing_with_a_date_call_as_the_fallback() {
assert_eq!(
translate_expression("$item['created_at'] ?? date('Y-m-d')", test_ctx!()),
Some(
r#"(item).get("created_at").cloned().unwrap_or_else(|| (larust_support::date::format(larust_support::date::now(), "Y-m-d")).to_string())"#
.to_string()
)
);
}
#[test]
fn translates_null_coalescing_with_a_literal_fallback() {
assert_eq!(
translate_expression("$item['created_at'] ?? ''", test_ctx!()),
Some(
r#"(item).get("created_at").cloned().unwrap_or_else(|| ("").to_string())"#
.to_string()
)
);
}
#[test]
fn rejects_null_coalescing_over_an_integer_indexed_subscript() {
assert_eq!(translate_expression("$arr[0] ?? $y", test_ctx!()), None);
}
#[test]
fn translates_string_key_array_index_access() {
assert_eq!(
translate_expression("$x['y']", test_ctx!()),
Some("x[\"y\"]".to_string())
);
}
#[test]
fn translates_integer_index_array_access() {
assert_eq!(
translate_expression("$arr[0]", test_ctx!()),
Some("arr[0]".to_string())
);
}
#[test]
fn translates_a_property_access_chained_off_a_subscript() {
assert_eq!(
translate_expression("$item['author']->name", test_ctx!()),
Some("item[\"author\"].name".to_string())
);
}
#[test]
fn rejects_bare_null() {
assert_eq!(translate_expression("null", test_ctx!()), None);
}
#[test]
fn translates_interpolated_strings() {
assert_eq!(
translate_expression("\"hello $x\"", test_ctx!()),
Some("format!(\"hello {}\", x)".to_string())
);
}
#[test]
fn preserves_a_literal_character_immediately_after_an_interpolated_variable() {
assert_eq!(
translate_expression(r#""$position-$type""#, test_ctx!()),
Some(r#"format!("{}-{}", position, type_)"#.to_string())
);
}
#[test]
fn escapes_a_rust_keyword_shaped_php_variable_name() {
assert_eq!(
translate_expression("$type", test_ctx!()),
Some("type_".to_string())
);
assert_eq!(
translate_expression("$type == 'slant'", test_ctx!()),
Some(r#"(type_) == ("slant")"#.to_string())
);
}
#[test]
fn translates_parenthesized_grouping() {
assert_eq!(
translate_expression("($x && $y)", test_ctx!()),
Some("(x) && (y)".to_string())
);
}
#[test]
fn every_accepted_translation_is_valid_syn_expr() {
for source in [
"$x",
"$post->title",
"true",
"42",
"4.2",
"'hello'",
"!$x",
"$x == $y",
"$x && $y",
"empty($x)",
"$cond == true ? $a : $b",
"$x['y']",
"$arr[0]",
"date('Y')",
"date(\"F jS, Y\")",
"csrf_token()",
"isset($data['keywords'])",
"$item['created_at'] ?? date('Y-m-d')",
"trim($x)",
"count($keywords)",
"ucwords($item['page'])",
"str_replace('_', ' ', $x)",
"explode(',', $x)",
"strtolower($x)",
"substr_count($haystack, $needle)",
"date('Y-m-d', strtotime($x))",
"Vite::asset('resources/css/app.css')",
r"\Illuminate\Support\Str::startsWith($x, ['http://', 'https://'])",
r"preg_replace('/(^|[\'(\s])\/storage/', '$1' . config('app.apiurl') . '/storage', $body)",
"$x ? $x : null",
"trim($x ? $x : null)",
] {
let translated = translate_expression(source, test_ctx!("app.apiurl")).unwrap();
assert!(
syn::parse_str::<syn::Expr>(&translated).is_ok(),
"translation of `{source}` produced invalid Rust: `{translated}`"
);
}
}
#[test]
fn translate_binding_strips_the_dollar_sigil() {
assert_eq!(translate_binding("$post"), Some("post".to_string()));
}
#[test]
fn translate_binding_escapes_a_rust_keyword_shaped_name() {
assert_eq!(translate_binding("$type"), Some("type_".to_string()));
}
#[test]
fn translate_binding_rejects_a_non_identifier() {
assert_eq!(translate_binding("$post->id"), None);
}
}