larust_convert/blade/expr.rs
1//! The safe PHP-expression-to-`syn::Expr` translator - the one piece of
2//! this whole tool where a wrong translation doesn't just get flagged in
3//! a report, it breaks the *converted app's own compile* (via
4//! `crates/larust-macros/src/view.rs`'s `syn::parse_str::<syn::Expr>`
5//! calls, which accept zero PHP syntax). Every node kind here was
6//! verified empirically (a throwaway `examples/inspect.rs` dumping
7//! `to_sexp()` against literal samples - the same technique Phase 1/2a
8//! used), not guessed. Two real findings that corrected the original
9//! design sketch, worth remembering if this file is ever revisited:
10//! `empty(...)`/`isset(...)` are plain `function_call_expression`s, not
11//! dedicated intrinsic node kinds - there's no "excluded for free" here,
12//! `empty` needs an explicit function-name check; and **every** binary
13//! operator (`&&`, `==`, `.` concatenation, `and`, `??`, all of them)
14//! shares the exact same `binary_expression` node kind, so the operator
15//! itself has to be recovered from raw source text between `left` and
16//! `right`, not from the node kind.
17//!
18//! **Translates**: `$var` → `var`; property chains (`->` → `.`); array/
19//! index access (`$x['y']`/`$arr[0]` → `x["y"]`/`arr[0]`, composing freely
20//! with property chains and further subscripts, since both recurse
21//! through this same dispatch); bool/int/float/plain-string literals;
22//! unary `!`; parenthesized grouping; `&&`/`||`/comparison operators (PHP
23//! `===`/`!==`/`<>` collapse to Rust's single `==`/`!=`)/arithmetic
24//! operators; string concatenation (PHP `.` → `format!("{}{}", ...)`);
25//! `empty($x)` → `x.is_empty()`; `str_contains($x, $y)` →
26//! `x.contains(&y)`; `trim($x)` → `x.trim().to_string()`; `count($x)` →
27//! `x.len()`; `ucwords($x)` → `larust_support::strings::ucwords(&x)` (no
28//! stdlib equivalent - PHP capitalizes each whitespace-separated word,
29//! `str::to_uppercase()` capitalizes the whole string); `str_replace($s,
30//! $r, $x)` → `x.replace(s, r)` (only plain-string `$s`/`$r` - PHP's array
31//! form has no single-line equivalent, and simply fails to translate here
32//! with no separate detection needed, since an `array_creation_expression`
33//! argument has no matching arm); `explode($sep, $x)` →
34//! `x.split(sep).map(|s| s.to_string()).collect::<Vec<String>>()` (2-arg
35//! form only - PHP's optional `$limit` third argument has no direct
36//! equivalent); `csrf_token()` → the bare `csrf_token` context
37//! variable (same one `@csrf` itself already reads - see
38//! `larust_view::ast::Node::Csrf`'s doc comment); ternary →
39//! `if larust_support::truthy::truthy(&(cond)) { a } else { b }` (also
40//! how every `@if`/`@elseif` condition translates, in `blade::scan`) -
41//! PHP's implicit truthy check has no Rust equivalent (`if` needs a
42//! genuine `bool`), so every condition is wrapped uniformly rather than
43//! guessing which ones need it; see `larust_support::truthy`'s own doc
44//! comment for why an already-`bool` condition passes through unchanged
45//! either way; `config('file.key')` → either a direct
46//! `larust_support::config(...)` runtime call (a small fixed set of keys
47//! already backed by `larust_core::Config`, see
48//! [`is_known_config_helper_key`]) or an indexing expression against a
49//! generated `crate::config::{file}::config()` module (see
50//! `larust_convert::config::convert_body`), whichever the key actually
51//! resolves to; `date($format)` and `date($format,
52//! strtotime($x))` for a fixed vocabulary of PHP format characters, via
53//! `larust_support::date::format`/`strtotime` (see
54//! [`is_supported_php_date_format`] for exactly which format characters,
55//! and `larust_support::date`'s own doc comment for exactly what its
56//! `strtotime` does and doesn't parse - not a full port of PHP's
57//! genuinely fuzzy natural-language date parsing, just the common
58//! machine-readable timestamp shapes an Eloquent `created_at`/
59//! `updated_at` column actually produces); a second `date(...)` argument
60//! that isn't `strtotime(...)` stays unsupported. `$x['key'] ??
61//! $fallback` → `x.get("key").cloned().unwrap_or_else(|| fallback.to_string())`
62//! (`.to_string()` always, since a literal fallback like `''` translates
63//! to `&str`, but `unwrap_or_else`'s closure needs exactly `String`), and
64//! `isset($x['key'])` → `x.contains_key("key")` - both **only** for a
65//! string-keyed subscript on the left/argument side (see
66//! [`string_keyed_subscript`] for exactly why that's the one shape either
67//! has an unambiguous Rust meaning for); `isset($x[key]) ? $x[key] :
68//! fallback` (Laravel's own more verbose, explicit spelling of the same
69//! `??`) translates identically - see
70//! [`translate_isset_ternary_idiom_text`]; `$_GET` → the `query` context
71//! variable (the one superglobal with a real Larust equivalent - see
72//! `translate`'s own `"variable_name"` arm); `Vite::asset('resources/css/
73//! app.css')` → `larust_support::asset("css/app.css")` - a deliberate
74//! best-effort guess (Larust has no build/bundling pipeline to resolve
75//! Vite's own content-hashed served path with), not a claim of
76//! correctness; see the `"scoped_call_expression"` arm's own comment.
77//! `\Illuminate\Support\Str::startsWith($x, [...])` (or the bare,
78//! `use`-imported `Str::startsWith`) against an array of string-literal
79//! prefixes → a chain of `.starts_with(...)` calls joined by `||`;
80//! `preg_replace($pattern, $replacement, $subject)` → `larust_support::
81//! regex_replace::replace_all(...)`, only for a single-quoted `$pattern`
82//! literal using the common same-character delimiter form (`/.../`,
83//! `#...#`, ...) with a recognized flag set (see
84//! [`translate_pcre_pattern`] for exactly which) - self-checked with a
85//! real `regex::Regex::new` call at convert time (the same crate,
86//! same version, `larust_support::regex_replace::replace_all` runs the
87//! pattern through again at runtime), so a PCRE construct Rust's `regex`
88//! crate doesn't support (lookaround, in-pattern backreferences, PCRE's
89//! `(?<name>...)`-style named groups) rejects the whole call rather than
90//! translating to something that silently never matches. `$cond ? A :
91//! null` / `$cond ? null : B` (real Laravel code's common "maybe-empty
92//! string" idiom) → an `if`/`else` that's always `String`-typed: `null`
93//! becomes `String::new()`, the other branch is coerced with
94//! `.to_string()` - see [`translate_null_branch_ternary`]'s own doc
95//! comment for why (a first, discarded design typed this `Option<T>` and
96//! broke every later `{{ }}` use of the same variable).
97//! Every recursively-translated
98//! sub-expression is defensively parenthesized when spliced into its
99//! parent - cheap insurance against a PHP/Rust operator-precedence
100//! mismatch producing a syntactically valid but semantically wrong
101//! translation.
102//!
103//! **Never translates** (always `None`, caller flags the whole file):
104//! any other function/method call; a bare-variable `??` or `isset($x)`
105//! (no way to know at convert time whether `x` is genuinely `Option<T>`)
106//! or either one over an *integer*-indexed subscript (`$arr[0] ?? ...`,
107//! `isset($arr[0])` - a different, unimplemented Rust idiom, not the same
108//! one guessed at); the bare `null` literal outside a ternary branch (a
109//! standalone `$x = null;`, or `null` as a plain function argument - only
110//! a ternary's own `null` branch has an unambiguous, always-safe
111//! translation, per [`translate_null_branch_ternary`]); `and`/`or`/`xor`
112//! operators; interpolated strings (a distinct `encapsed_string` node
113//! kind - never matches the plain-`string` arm); any superglobal other
114//! than `$_GET` (`$_POST`/`$_SERVER`/etc. - Larust's view context has no
115//! equivalent for raw request-body/environment access).
116//!
117//! **Self-checks its own output**: [`translate_expression`] rejects its
118//! own result if `syn::parse_str::<syn::Expr>` doesn't accept it, turning
119//! a translator bug into a normal `None` (flagged, whole file rejected)
120//! instead of a syntax error surfacing three layers away in the
121//! converted app's own `cargo build`.
122
123use super::ConvertContext;
124use crate::php;
125use tree_sitter::Node;
126
127/// Parses `source` (a bare PHP expression fragment, exactly as captured
128/// from inside a Blade `{{ }}`/`@if(...)`/`@foreach(...)`'s iterable
129/// side - no `<?php` tag, no trailing `;`) and translates it, or returns
130/// `None` if any part of it falls outside the safe subset **or** the
131/// translator's own output fails to parse as a real `syn::Expr`. `ctx` is
132/// only ever read by the `"config"` function-call arm inside [`translate`]
133/// (to decide whether `config('file.key')` has a generated
134/// `crate::config::{file}::config()` module to reference) - every other
135/// construct ignores it, but it's threaded through this whole recursive
136/// call chain rather than read from an ambient source, matching
137/// `blade::scan`'s own `ConvertContext` threading.
138pub fn translate_expression(source: &str, ctx: &ConvertContext) -> Option<String> {
139 if let Some(translated) = translate_simple_ternary(source, ctx) {
140 return Some(translated);
141 }
142 let wrapped = format!("<?php {source};");
143 let tree = php::parse(&wrapped).ok()?;
144 if php::has_syntax_error(&tree) {
145 return None;
146 }
147 let stmt = php::statement_expressions(tree.root_node())
148 .into_iter()
149 .next()?;
150 let translated = translate(stmt, &wrapped, ctx)?;
151 syn::parse_str::<syn::Expr>(&translated).ok()?;
152 Some(translated)
153}
154
155/// Tree-sitter exposes a conditional's condition/body/alternative fields for
156/// simple values, but PHP's comparison-plus-ternary form is represented with
157/// a different field shape. Handle the common, non-nested form before the AST
158/// translation so CSS-class and attribute conditionals don't reject a file.
159fn translate_simple_ternary(source: &str, ctx: &ConvertContext) -> Option<String> {
160 let question = source.find('?')?;
161 let colon = source[question + 1..].find(':')? + question + 1;
162 let condition_raw = source[..question].trim();
163 let when_true_raw = source[question + 1..colon].trim();
164 let when_false_raw = source[colon + 1..].trim();
165
166 if let Some(translated) =
167 translate_isset_ternary_idiom_text(condition_raw, when_true_raw, when_false_raw, ctx)
168 {
169 return Some(translated);
170 }
171
172 let condition = translate_expression(condition_raw, ctx)?;
173 if when_true_raw.eq_ignore_ascii_case("null") || when_false_raw.eq_ignore_ascii_case("null") {
174 // See `translate_null_branch_ternary`'s own doc comment (the AST
175 // counterpart of this same detection) for why a null branch keeps
176 // the whole ternary `String`-typed instead of `Option<T>`.
177 let when_true = translate_null_coerced_branch(when_true_raw, ctx)?;
178 let when_false = translate_null_coerced_branch(when_false_raw, ctx)?;
179 return Some(format!(
180 "if larust_support::truthy::truthy(&({condition})) {{ {when_true} }} else {{ {when_false} }}"
181 ));
182 }
183 let when_true = translate_expression(when_true_raw, ctx)?;
184 let when_false = translate_expression(when_false_raw, ctx)?;
185 // See the `"conditional_expression"` AST arm's own matching comment
186 // for the full reasoning (this is the text-based, top-level
187 // counterpart of that same fix - the actual real-world case this
188 // exists for, `dividers.blade.php`'s top-level `{{ ... ?
189 // "{$position}-{$type}" : $position }}`, is precisely this
190 // function's own code path, not the nested AST one).
191 if looks_like_php_string_literal(when_true_raw) || looks_like_php_string_literal(when_false_raw)
192 {
193 return Some(format!(
194 "if larust_support::truthy::truthy(&({condition})) {{ ({when_true}).to_string() }} else {{ ({when_false}).to_string() }}"
195 ));
196 }
197 Some(format!(
198 "if larust_support::truthy::truthy(&({condition})) {{ {when_true} }} else {{ {when_false} }}"
199 ))
200}
201
202/// A cheap, text-only proxy for "this ternary branch is a PHP string
203/// literal" - good enough to decide when [`translate_simple_ternary`]
204/// needs to coerce both branches to a common `String` type (see that
205/// function's own comment for why only *sometimes*, not always: forcing
206/// `.to_string()` on an already-consistent `bool`/`bool` ternary would
207/// silently change its meaning - a `String` `"false"` is still a
208/// non-empty string, hence *truthy* under `larust_support::truthy`'s own
209/// "empty string is falsy" convention, the exact opposite of a real
210/// `false`). A leading quote is unambiguous for this codebase's own
211/// translated PHP source: nothing else this translator emits as a
212/// ternary branch starts with `'`/`"`.
213fn looks_like_php_string_literal(text: &str) -> bool {
214 matches!(text.trim().chars().next(), Some('\'') | Some('"'))
215}
216
217/// One ternary branch, already known to be raw text (either `"null"` or
218/// an ordinary expression) - `"null"` becomes `String::new()`, anything
219/// else is translated normally and coerced with `.to_string()` so both
220/// branches unify to the same `String` type regardless of what the
221/// non-null branch's own native type would otherwise have been (safe for
222/// any `Display`-implementing value, matching `??`'s own established
223/// fallback-typing fix elsewhere in this file). Text-based counterpart of
224/// [`translate_null_branch_ternary`], for [`translate_simple_ternary`]'s
225/// own top-level, text-only path.
226fn translate_null_coerced_branch(raw: &str, ctx: &ConvertContext) -> Option<String> {
227 if raw.eq_ignore_ascii_case("null") {
228 Some("String::new()".to_string())
229 } else {
230 let translated = translate_expression(raw, ctx)?;
231 Some(format!("({translated}).to_string()"))
232 }
233}
234
235/// `Some(translated)` if `condition_raw`/`when_true_raw`/`when_false_raw`
236/// (already trimmed) match the `isset($x[key]) ? $x[key] : fallback`
237/// idiom - Laravel's own explicit, more verbose spelling of `$x[key] ??
238/// fallback` (the real source this exists for: `isset($_GET['q']) ?
239/// $_GET['q'] : ""`, `$_GET` translating like any other context variable
240/// per `translate`'s own `variable_name` arm). Detected by an exact text
241/// match between `isset(...)`'s argument and the true branch, not a deep
242/// structural comparison - sufficient because PHP source written this way
243/// always repeats the identical expression verbatim. Re-expressing it as
244/// `??` and re-running it through [`translate_expression`] reuses that
245/// translation exactly (including its `.to_string()` fallback-
246/// normalization) instead of duplicating it; the rebuilt `??` text is
247/// safe to hand back in because it contains no `:`, so
248/// [`translate_simple_ternary`]'s own `?`/`:` split bails out immediately
249/// (no colon found) and falls through to the real AST-based
250/// `binary_expression` path. Shared by both `translate_simple_ternary`
251/// (a top-level ternary, working on raw text directly) and `translate`'s
252/// own `"conditional_expression"` arm (a ternary reached through AST
253/// recursion - nested inside another expression, e.g. as a
254/// `str_replace(...)` argument, the actual real-world shape this exists
255/// for - which never passes through `translate_simple_ternary`'s
256/// top-level-only fast path at all).
257fn translate_isset_ternary_idiom_text(
258 condition_raw: &str,
259 when_true_raw: &str,
260 when_false_raw: &str,
261 ctx: &ConvertContext,
262) -> Option<String> {
263 let isset_arg = condition_raw
264 .strip_prefix("isset(")
265 .and_then(|rest| rest.strip_suffix(')'))?;
266 if isset_arg.trim() != when_true_raw {
267 return None;
268 }
269 translate_expression(&format!("{when_true_raw} ?? {when_false_raw}"), ctx)
270}
271
272/// [`translate_isset_ternary_idiom_text`], for AST nodes instead of raw
273/// text slices - see that function's doc comment for the full reasoning.
274fn translate_isset_ternary_idiom(
275 condition: Node,
276 body: Node,
277 alternative: Node,
278 source: &str,
279 ctx: &ConvertContext,
280) -> Option<String> {
281 let bytes = source.as_bytes();
282 translate_isset_ternary_idiom_text(
283 condition.utf8_text(bytes).ok()?.trim(),
284 body.utf8_text(bytes).ok()?.trim(),
285 alternative.utf8_text(bytes).ok()?.trim(),
286 ctx,
287 )
288}
289
290/// `Some(translated)` when this ternary's `body`/`alternative` includes a
291/// bare `null` branch - PHP's `null`, in a Blade-consumed context, always
292/// renders as nothing and is falsy in an `@if`, the same behavior an
293/// empty Rust `String` already has under `larust_support::truthy` (see
294/// its own doc comment: empty strings are falsy). Rather than typing the
295/// whole ternary `Option<T>` (which would break every *later* `{{ $x }}`
296/// use of the resulting variable - `Option<T>` doesn't implement
297/// `Display` - the real problem with a first, discarded design for this:
298/// `$previewUrl = $cond ? (...) : null;` followed by `{{ $previewUrl }}`
299/// elsewhere in the same template, the actual real-world shape this
300/// exists for), the whole ternary stays uniformly `String`-typed: the
301/// non-null branch is coerced with `.to_string()` (safe for any
302/// `Display`-implementing value, matching `??`'s own established
303/// fallback-typing fix elsewhere in this file), the null branch becomes
304/// `String::new()`. `None` when neither branch is null - the ordinary
305/// ternary path handles that case. Text-based counterpart:
306/// [`translate_null_coerced_branch`], for [`translate_simple_ternary`]'s
307/// own top-level, text-only path.
308fn translate_null_branch_ternary(
309 condition: Node,
310 body: Node,
311 alternative: Node,
312 source: &str,
313 ctx: &ConvertContext,
314) -> Option<String> {
315 let body_is_null = body.kind() == "null";
316 let alternative_is_null = alternative.kind() == "null";
317 if !body_is_null && !alternative_is_null {
318 return None;
319 }
320 let condition_text = translate(condition, source, ctx)?;
321 let body_text = if body_is_null {
322 "String::new()".to_string()
323 } else {
324 format!("({}).to_string()", translate(body, source, ctx)?)
325 };
326 let alternative_text = if alternative_is_null {
327 "String::new()".to_string()
328 } else {
329 format!("({}).to_string()", translate(alternative, source, ctx)?)
330 };
331 Some(format!(
332 "if larust_support::truthy::truthy(&({condition_text})) {{ {body_text} }} else {{ {alternative_text} }}"
333 ))
334}
335
336/// A `@foreach(binding in iterable)` binding - a single bare identifier
337/// (Laravel's `$post` becomes `post`), or Laravel's `$key => $item` /
338/// `$index => $item` keyed form, which becomes a genuine Rust tuple
339/// pattern (`(key, item)`) now that Larust's own grammar accepts one (see
340/// `larust_view::ast::Node::Foreach`'s doc comment; `larust-macros` parses
341/// this as `syn::Pat`, not just `syn::Ident`). Every identifier on either
342/// side is verified via the same helper every other converter uses - a
343/// keyed binding with either half invalid fails the whole thing, same as a
344/// plain binding always has. Pair with [`is_keyed_binding`] on the
345/// caller's side: the iterable needs `.iter().enumerate()` appended for
346/// the resulting `for (key, item) in iterable` to type-check.
347pub fn translate_binding(source: &str) -> Option<String> {
348 let source = source.trim();
349 if let Some((key, item)) = source.split_once("=>") {
350 let key = translate_single_binding(key)?;
351 let item = translate_single_binding(item)?;
352 return Some(format!("({key}, {item})"));
353 }
354 translate_single_binding(source)
355}
356
357/// `true` for the `$key => $item` / `$index => $item` shape
358/// [`translate_binding`] turns into a tuple pattern. Laravel's plain-list
359/// `$key => $item` is PHP's own positional index - `.enumerate()` is the
360/// direct Rust equivalent - never genuine associative-map iteration,
361/// which this never attempts (Larust's view context values are typed, not
362/// generic PHP arrays that blur the two).
363pub fn is_keyed_binding(source: &str) -> bool {
364 source.trim().contains("=>")
365}
366
367fn translate_single_binding(source: &str) -> Option<String> {
368 let name = source.trim().strip_prefix('$')?.trim();
369 // Same keyword-escaping as `translate`'s own `variable_name` arm - a
370 // `@foreach($items as $type)` binding name is just as real a
371 // collision as a reference to `$type` inside the loop body, and
372 // deserves the same `type_` treatment rather than rejecting the
373 // whole `@foreach`.
374 let escaped = if crate::codegen::is_rust_keyword(name) {
375 format!("{name}_")
376 } else {
377 name.to_string()
378 };
379 crate::codegen::validate_identifier(&escaped).ok()?;
380 Some(escaped)
381}
382
383/// Translates a Laravel `@php ... @endphp` block's body into Larust's own
384/// `@code ... @endcode` escape hatch (`larust_view::ast::Node::Code`'s own
385/// doc comment: "trusted, inline Rust statements executed in the
386/// generated view function") - only for the two shapes that are genuinely
387/// mechanical: a `$var = <expr>;` assignment (each already translatable
388/// by [`translate`]), always emitted as `let mut` (see the match arm's
389/// own comment for why unconditionally), and a bare `$var++`/`$var--`
390/// increment/decrement. Anything else - a single statement of any other
391/// shape (an `if`, a loop, a function definition), or a `$var = <expr>;`
392/// whose right-hand side falls outside the safe subset - rejects the
393/// *whole block* (returns `None`), the same "no smaller natural unit to
394/// fail independently" reasoning that applies to any construct in this
395/// crate with no partial-translation shape of its own. What the *caller*
396/// does with that `None` is a separate decision, made one level up in
397/// `scan.rs`'s `"php"` arm: a top-level block degrades in place (with
398/// taint-tracking - see that arm's own doc comment and
399/// [`php_block_assigned_variable_names`]) rather than rejecting the
400/// file; only a *nested* one still propagates as a hard failure.
401pub fn translate_php_block(php_source: &str, ctx: &ConvertContext) -> Option<String> {
402 let wrapped = format!("<?php\n{php_source}\n");
403 let tree = php::parse(&wrapped).ok()?;
404 if php::has_syntax_error(&tree) {
405 return None;
406 }
407 let root = tree.root_node();
408 let statements = php::statement_expressions(root);
409 // `statement_expressions` only returns `expression_statement`
410 // children - it silently *skips* any other top-level statement kind
411 // (an `if`, a loop, `echo`, a function definition, ...) rather than
412 // erroring on them. This count check is what actually catches that:
413 // `php_tag` is always exactly one named child, so if anything besides
414 // a plain expression-statement sits at the top level, the two counts
415 // won't match - content this translator can't even see, which MUST
416 // reject the whole block rather than silently drop it.
417 if statements.is_empty() || root.named_child_count() != statements.len() + 1 {
418 return None;
419 }
420
421 let mut lines = Vec::with_capacity(statements.len());
422 for stmt in statements {
423 match stmt.kind() {
424 "assignment_expression" => {
425 let left = stmt.child_by_field_name("left")?;
426 let right = stmt.child_by_field_name("right")?;
427 if left.kind() != "variable_name" {
428 return None;
429 }
430 let name = left.named_child(0)?.utf8_text(wrapped.as_bytes()).ok()?;
431 crate::codegen::validate_identifier(name).ok()?;
432 let value = translate(right, &wrapped, ctx)?;
433 // `mut`, unconditionally - a `@php $x = 0; @endphp` block
434 // has no visibility into a *separate*, later `@php
435 // $x++; @endphp` block (the real source this exists for:
436 // a counter declared once, incremented inside a nested
437 // `@foreach`'s own `@php` block - each block translates
438 // independently, with no cross-block analysis of whether
439 // `x` is reassigned anywhere else), so there's no reliable
440 // way to know at this point whether `x` needs to be
441 // mutable. An unconditionally-`mut` binding that's never
442 // actually reassigned is at worst an `unused_mut`
443 // *warning* in the converted app, not a compile error -
444 // the safe direction to err in.
445 lines.push(format!("let mut {name} = {value};"));
446 }
447 "update_expression" => {
448 let argument = stmt.child_by_field_name("argument")?;
449 if argument.kind() != "variable_name" {
450 return None;
451 }
452 let name = argument
453 .named_child(0)?
454 .utf8_text(wrapped.as_bytes())
455 .ok()?;
456 crate::codegen::validate_identifier(name).ok()?;
457 // Prefix (`++$x`) vs. postfix (`$x++`) makes no difference
458 // for a bare statement whose result is never used - both
459 // just increment.
460 let text = stmt.utf8_text(wrapped.as_bytes()).ok()?;
461 let op = if text.contains("++") {
462 "+= 1"
463 } else if text.contains("--") {
464 "-= 1"
465 } else {
466 return None;
467 };
468 lines.push(format!("{name} {op};"));
469 }
470 _ => return None,
471 }
472 }
473
474 let joined = lines.join(" ");
475 // Same self-check discipline as `translate_expression` - a `syn::
476 // Block` (not `syn::Expr`; this is a statement sequence) confirms the
477 // whole thing is genuinely valid Rust before it's ever handed back,
478 // turning a translator bug into a normal `None` here instead of a
479 // syntax error surfacing three layers away in `cargo build`.
480 syn::parse_str::<syn::Block>(&format!("{{ {joined} }}")).ok()?;
481 Some(joined)
482}
483
484/// Best-effort variable-name extraction for a `@php` block [`translate_php_block`]
485/// couldn't translate - used only by a *top-level* `@php` failure
486/// (`scan.rs`'s `"php"` arm) to populate `ConvertContext::tainted_vars`,
487/// so later references to these names degrade instead of translating into
488/// a reference to a binding that no longer exists. Deliberately more
489/// lenient than `translate_php_block`: walks the *entire* tree, not just
490/// top-level `statement_expressions`, since a block this phase can't
491/// translate is exactly the kind that has assignments nested inside an
492/// `if`/loop the real, motivating case for this whole mechanism
493/// (`guest.blade.php`'s `@php` block reassigns `$brandName` inside a
494/// nested `if ($isEnterpriseEdition) { if (...) { ... } }`). Tolerant of
495/// a tree with parse errors (never propagates one) - over-collecting a
496/// name is always safe here (a spot that degrades that didn't strictly
497/// need to), under-collecting is not.
498pub fn php_block_assigned_variable_names(php_source: &str) -> std::collections::HashSet<String> {
499 let wrapped = format!("<?php\n{php_source}\n");
500 let mut names = std::collections::HashSet::new();
501 let Ok(tree) = php::parse(&wrapped) else {
502 return names;
503 };
504 collect_assigned_variable_names(tree.root_node(), wrapped.as_bytes(), &mut names);
505 names
506}
507
508fn collect_assigned_variable_names(
509 node: Node,
510 bytes: &[u8],
511 names: &mut std::collections::HashSet<String>,
512) {
513 if node.kind() == "assignment_expression" {
514 if let Some(left) = node.child_by_field_name("left") {
515 if left.kind() == "variable_name" {
516 if let Some(name_node) = left.named_child(0) {
517 if let Ok(name) = name_node.utf8_text(bytes) {
518 names.insert(name.to_string());
519 }
520 }
521 }
522 }
523 }
524 let mut cursor = node.walk();
525 for child in node.children(&mut cursor) {
526 collect_assigned_variable_names(child, bytes, names);
527 }
528}
529
530fn translate(node: Node, source: &str, ctx: &ConvertContext) -> Option<String> {
531 let bytes = source.as_bytes();
532 match node.kind() {
533 "variable_name" => {
534 let name = node.named_child(0)?.utf8_text(bytes).ok()?;
535 if ctx.tainted_vars.borrow().contains(name) {
536 // A dropped top-level `@php` block would have assigned
537 // this name - see `ConvertContext::tainted_vars`'s own
538 // doc comment and `scan.rs`'s module doc comment for the
539 // full mechanism. Translating it as an ordinary bare
540 // variable reference (the `else` arm below) would emit a
541 // reference to a Rust binding that no longer exists;
542 // `None` here is what makes every call site (an
543 // interpolation, an `@if`/`@elseif` condition, a
544 // `@foreach` iterable/binding) degrade this one spot in
545 // place instead, the same as any other unsupported
546 // expression.
547 None
548 } else if name == "_GET" {
549 // The one superglobal with a real Larust equivalent: a
550 // `query: HashMap<String, String>` context value, the
551 // same "explicit, compile-checked" convention every other
552 // context variable already follows (`csrf_token`,
553 // `post_count`, ...) - `view!(...)` never injects
554 // anything implicitly, so an app that doesn't actually
555 // pass `query` in gets a plain, honest "cannot find
556 // value `query`" at `cargo build` time, not a runtime
557 // surprise. `$_POST`/`$_SERVER`/etc. have no equivalent
558 // (posting a raw, untyped request body into a template
559 // isn't a "give me the query string" kind of ask), so
560 // they still fall through to [`is_superglobal`]'s
561 // rejection below.
562 Some("query".to_string())
563 } else if is_superglobal(name) {
564 // `$_POST`/`$_SERVER`/etc. read HTTP request state
565 // Larust's view context doesn't carry today (a template
566 // has no notion of "the current request" at all) -
567 // translating this to a bare `_POST` identifier the way
568 // an ordinary variable translates would compile-error
569 // three layers away in the converted app with a
570 // confusing "cannot find value `_POST`", instead of
571 // failing loudly *here* with a reason that actually
572 // explains what's missing.
573 None
574 } else if crate::codegen::is_rust_keyword(name) {
575 // Any PHP variable literally named after a Rust keyword
576 // (`$type`, `$match`, `$fn`, ... - Laravel's automatic
577 // `$loop`, implicitly available inside any `@foreach`
578 // body, is just the most common real case) can't survive
579 // the ordinary `$var` → `var` stripping below unchanged;
580 // `type` alone isn't valid Rust syntax to reference as a
581 // value. Escaping via a trailing underscore - Rust's own
582 // common idiom for exactly this collision - keeps the
583 // variable usable instead of rejecting the whole
584 // expression outright. `blade::scan`'s `@foreach` codegen
585 // independently relies on this producing exactly `loop_`
586 // for `loop` (see `larust_support::loop_iter`'s own doc
587 // comment) - this generalizes that one hardcoded case to
588 // every Rust keyword, not just `loop`.
589 Some(format!("{name}_"))
590 } else {
591 Some(name.to_string())
592 }
593 }
594 "member_access_expression" => {
595 let object = node.child_by_field_name("object")?;
596 let name = node.child_by_field_name("name")?;
597 let object_text = translate(object, source, ctx)?;
598 Some(format!("{object_text}.{}", name.utf8_text(bytes).ok()?))
599 }
600 "boolean" | "integer" | "float" => Some(node.utf8_text(bytes).ok()?.to_string()),
601 "string" => {
602 let raw = node.utf8_text(bytes).ok()?;
603 let text = php::unquote(raw);
604 Some(format!("{text:?}"))
605 }
606 "encapsed_string" => translate_interpolated_string(node.utf8_text(bytes).ok()?),
607 "parenthesized_expression" => {
608 let inner = node.named_child(0)?;
609 translate(inner, source, ctx)
610 }
611 "unary_op_expression" => {
612 let argument = node.child_by_field_name("argument")?;
613 let operator = source.get(node.start_byte()..argument.start_byte())?.trim();
614 if operator != "!" {
615 return None;
616 }
617 let inner = translate(argument, source, ctx)?;
618 // PHP's `!` coerces *any* operand type to boolean first (its
619 // own truthiness rules - an empty string, `0`, an empty
620 // array all negate to `true`), not just a real `bool`. A
621 // bare `!(inner)` only works when `inner` already happens to
622 // be a Rust `bool` - real source breaks this the moment it
623 // doesn't: `index/main.blade.xr`'s `!$status` (`$status` a
624 // plain `String` built from a query param) translates to
625 // `!(status)`, and `String` has no `Not` impl, so it fails
626 // to compile with `E0600` the instant that `!$status` sits
627 // inside anything (a ternary, another `&&`) other than a
628 // bare `@if` condition, where the *outer* `truthy(&(...))`
629 // wrap `scan.rs` already applies masks the same bug for the
630 // top-level-condition case only. Routing through the same
631 // `truthy` helper every other boolean-coercion site in this
632 // module already uses fixes both: it's a no-op for a
633 // genuine `bool` (`truthy(&bool)` returns that same value)
634 // and correct PHP-truthiness coercion for anything else.
635 Some(format!("!larust_support::truthy::truthy(&({inner}))"))
636 }
637 "binary_expression" => {
638 let left = node.child_by_field_name("left")?;
639 let right = node.child_by_field_name("right")?;
640 let operator = source.get(left.end_byte()..right.start_byte())?.trim();
641 // Checked before the generic `left`/`right` translation below -
642 // `??`'s one supported shape needs `left` translated
643 // *differently* than plain interpolation would (`.get(key)`,
644 // not `[key]`), so it can't reuse `left_text`/`right_text`.
645 // Every other left-hand shape (a bare variable, a property
646 // chain, ...) still isn't supported - there's no way to know
647 // at convert time whether it's genuinely `Option<T>` - so this
648 // only ever succeeds for the one case it can prove safe.
649 if operator == "??" {
650 let (object, key) = string_keyed_subscript(left, source)?;
651 let object_text = translate(object, source, ctx)?;
652 let fallback_text = translate(right, source, ctx)?;
653 // `.to_string()` on the fallback, always - `.cloned()` on
654 // `Option<&String>` needs `unwrap_or_else`'s closure to
655 // return exactly `String`, but a literal fallback
656 // (`$x['key'] ?? ''`, the common case) translates to a
657 // bare `&str`, which fails to compile without this
658 // (verified empirically: `unwrap_or_else(|| "")` is a
659 // real `E0308` type mismatch). `.to_string()` normalizes
660 // either shape - it's a no-op-cost identity for something
661 // already `String`-typed via `Display`/`ToString`.
662 return Some(format!(
663 "({object_text}).get({key:?}).cloned().unwrap_or_else(|| ({fallback_text}).to_string())"
664 ));
665 }
666 let left_text = translate(left, source, ctx)?;
667 let right_text = translate(right, source, ctx)?;
668 if operator == "." {
669 Some(format!("format!(\"{{}}{{}}\", {left_text}, {right_text})"))
670 } else {
671 let rust_op = map_operator(operator)?;
672 Some(format!("({left_text}) {rust_op} ({right_text})"))
673 }
674 }
675 // `$item['title']` (a string key) and `$arr[0]` (an integer index)
676 // are the same grammar node - verified empirically (`to_sexp()`
677 // against both literal samples), two named children, no field
678 // names exposed on this node in this grammar version (unlike
679 // `binary_expression`'s `left`/`right`), so positional
680 // `named_child` is the only way to reach them. Recursing through
681 // `translate` for both sides means this falls out of the existing
682 // `string`/`integer`/`variable_name`/nested-`subscript_expression`
683 // support for free - no special-casing needed for either key kind,
684 // since Rust's own `[]` indexing already overloads the same way
685 // (`HashMap<String, _>: Index<&str>`, `Vec<_>: Index<usize>`).
686 "subscript_expression" => {
687 let object = node.named_child(0)?;
688 let index = node.named_child(1)?;
689 let object_text = translate(object, source, ctx)?;
690 let index_text = translate(index, source, ctx)?;
691 Some(format!("{object_text}[{index_text}]"))
692 }
693 "conditional_expression" => {
694 let condition = node.child_by_field_name("condition")?;
695 let body = node.child_by_field_name("body")?;
696 let alternative = node.child_by_field_name("alternative")?;
697
698 // `isset($x[key]) ? $x[key] : fallback` - the same idiom
699 // `translate_simple_ternary` detects (see its own doc
700 // comment for the full reasoning), duplicated here because a
701 // ternary reached through AST recursion - nested inside
702 // another expression, e.g. as a `str_replace(...)` argument,
703 // the actual real-world shape this exists for
704 // (`str_replace('_', ' ', isset($_GET['q']) ? $_GET['q'] :
705 // "")`) - never passes through `translate_expression`'s
706 // top-level fast path at all.
707 if let Some(translated) =
708 translate_isset_ternary_idiom(condition, body, alternative, source, ctx)
709 {
710 return Some(translated);
711 }
712 if let Some(translated) =
713 translate_null_branch_ternary(condition, body, alternative, source, ctx)
714 {
715 return Some(translated);
716 }
717
718 let condition_text = translate(condition, source, ctx)?;
719 let body_text = translate(body, source, ctx)?;
720 let alternative_text = translate(alternative, source, ctx)?;
721 // Coerce both branches to a common `String` type - but only
722 // when at least one branch is itself a PHP string literal
723 // (real source: `dividers.blade.php`'s `$type !== '' &&
724 // $type !== 'slant' ? "{$position}-{$type}" : $position` -
725 // one branch a computed `format!(...)`-shaped `String`, the
726 // other a bare `&str` prop reference; PHP's ternary never
727 // needs its two branches to agree on a type, Rust's `if`/
728 // `else` *expression* does). *Not* unconditional the way
729 // `translate_null_branch_ternary`'s own coercion is: forcing
730 // `.to_string()` on an already-consistent `bool`/`bool`
731 // ternary (real source: `$q ? substr_count(...) > 0 : true`)
732 // would silently change its meaning - a `String` `"false"`
733 // is still a non-empty string, hence *truthy* under
734 // `larust_support::truthy`'s own "empty string is falsy"
735 // convention, the exact opposite of a real `false`.
736 let body_is_literal = matches!(body.kind(), "string" | "encapsed_string");
737 let alternative_is_literal = matches!(alternative.kind(), "string" | "encapsed_string");
738 if body_is_literal || alternative_is_literal {
739 return Some(format!(
740 "if larust_support::truthy::truthy(&({condition_text})) {{ ({body_text}).to_string() }} else {{ ({alternative_text}).to_string() }}"
741 ));
742 }
743 Some(format!(
744 "if larust_support::truthy::truthy(&({condition_text})) {{ {body_text} }} else {{ {alternative_text} }}"
745 ))
746 }
747 // `Vite::asset('resources/css/app.css')` - the one static-method
748 // call this translates, and the only reason this node kind (also
749 // used for `Route::get(...)`, see `routes.rs`) is handled here at
750 // all. Larust has no build/bundling pipeline - no Vite manifest,
751 // no content-hashed filenames - so there's no way to resolve the
752 // *real* served path the way Vite's own manifest lookup would;
753 // this instead assumes the asset gets copied to the same
754 // relative path under `public/` with its `resources/` source-tree
755 // prefix stripped, a deliberate best-effort guess (documented,
756 // not hidden) rather than refusing to translate the call at all.
757 "scoped_call_expression" => {
758 let scope = node.child_by_field_name("scope")?;
759 let scope_text = scope.utf8_text(bytes).ok()?;
760 let name = node.child_by_field_name("name")?;
761 let name_text = name.utf8_text(bytes).ok()?;
762
763 if scope.kind() == "name" && scope_text == "Vite" && name_text == "asset" {
764 let arg = php::argument_node(node, 0)?;
765 if arg.kind() != "string" {
766 return None;
767 }
768 let source_path = php::unquote(arg.utf8_text(bytes).ok()?);
769 let served_path = source_path
770 .strip_prefix("resources/")
771 .unwrap_or(&source_path);
772 return Some(format!("larust_support::asset({served_path:?})"));
773 }
774
775 // Laravel's `Str` facade, `\Illuminate\Support\Str` (a
776 // `qualified_name` scope - the leading `\` PHP source always
777 // writes it with is part of that node's own text, trimmed
778 // here) or the bare, `use`-imported `Str`. Only
779 // `startsWith($x, [...])` - checking a string against an
780 // *array* of candidate prefixes, real Laravel code's common
781 // shape for this - translates to a chain of `.starts_with(...)`
782 // calls joined by `||`; anything else on `Str` stays
783 // unsupported.
784 let is_str_facade = (scope.kind() == "qualified_name"
785 && scope_text.trim_start_matches('\\') == "Illuminate\\Support\\Str")
786 || (scope.kind() == "name" && scope_text == "Str");
787 if is_str_facade && name_text == "startsWith" {
788 let subject = php::argument_node(node, 0)?;
789 let subject_text = translate(subject, source, ctx)?;
790 let prefixes_arg = php::argument_node(node, 1)?;
791 if prefixes_arg.kind() != "array_creation_expression" {
792 return None;
793 }
794 let mut checks = Vec::new();
795 for i in 0..prefixes_arg.named_child_count() {
796 let element = prefixes_arg.named_child(i)?;
797 if element.kind() != "array_element_initializer" {
798 return None;
799 }
800 let value = element.named_child(0)?;
801 let prefix_text = translate(value, source, ctx)?;
802 checks.push(format!("({subject_text}).starts_with({prefix_text})"));
803 }
804 if checks.is_empty() {
805 return None;
806 }
807 return Some(checks.join(" || "));
808 }
809
810 None
811 }
812 "function_call_expression" => {
813 let function = node.child_by_field_name("function")?;
814 let function = function.utf8_text(bytes).ok()?;
815 // Checked before the unconditional `arg` fetch below - unlike
816 // every other recognized function here, `csrf_token()` takes
817 // no arguments at all in real Laravel code. Larust's own
818 // `@csrf` directive already established `csrf_token` as a
819 // bare context variable, not a function call (see
820 // `larust_view::ast::Node::Csrf`'s doc comment) - a direct
821 // `csrf_token()` call (Laravel's own common `<meta
822 // name="csrf-token" content="{{ csrf_token() }}">` AJAX-token
823 // boilerplate, distinct from `@csrf`'s hidden `<input>`) reads
824 // that exact same context value. Both existing side by side is
825 // fine: `@csrf` renders the input, this renders just the raw
826 // token string, and both ultimately read the one variable the
827 // view's own context supplies.
828 if function == "csrf_token" {
829 return Some("csrf_token".to_string());
830 }
831 let arg = php::argument_node(node, 0)?;
832 if function == "empty" {
833 let arg_text = translate(arg, source, ctx)?;
834 Some(format!("({arg_text}).is_empty()"))
835 } else if function == "trim" {
836 let text = translate(arg, source, ctx)?;
837 Some(format!("({text}).trim().to_string()"))
838 } else if function == "count" {
839 let text = translate(arg, source, ctx)?;
840 Some(format!("({text}).len()"))
841 } else if function == "ucwords" {
842 let text = translate(arg, source, ctx)?;
843 Some(format!("larust_support::strings::ucwords(&({text}))"))
844 } else if function == "strtolower" {
845 let text = translate(arg, source, ctx)?;
846 Some(format!("({text}).to_lowercase()"))
847 } else if function == "substr_count" {
848 let needle = php::argument_node(node, 1)?;
849 let haystack_text = translate(arg, source, ctx)?;
850 let needle_text = translate(needle, source, ctx)?;
851 Some(format!("({haystack_text}).matches({needle_text}).count()"))
852 } else if function == "isset" {
853 // Only `isset($x['stringkey'])` - the one shape with an
854 // unambiguous Rust translation (`.contains_key(...)`,
855 // matching this file's `??` support for the exact same
856 // reason: see [`string_keyed_subscript`]). A bare
857 // `isset($x)` would need to know whether `x` is genuinely
858 // `Option<T>`, which isn't knowable at convert time, so
859 // that shape stays unsupported.
860 let (object, key) = string_keyed_subscript(arg, source)?;
861 let object_text = translate(object, source, ctx)?;
862 Some(format!("({object_text}).contains_key({key:?})"))
863 } else if function == "config" {
864 let key = php::unquote(arg.utf8_text(bytes).ok()?);
865 // A key `config_helper::config` already resolves at
866 // runtime from `larust_core::Config` (`app.name`/
867 // `app.env`/`app.url`/`app.port`/`app.debug`/
868 // `session.secure_cookie`/`mail.*`) needs no generated
869 // file at all - it's already backed by `Config`/
870 // `config.toml`/`Config::load_from`'s own env override.
871 if is_known_config_helper_key(&key) {
872 return Some(format!(
873 "larust_support::config({key:?}).unwrap_or_default()"
874 ));
875 }
876 // Everything else resolves (if at all) against a
877 // generated `crate::config::{file}::config()` module -
878 // see `larust_convert::config::convert_body`. Only a
879 // key that module actually resolved gets the indexing
880 // expression; anything else stays unsupported rather
881 // than guessing at a module/field that was never
882 // generated.
883 let (file, top_key) = key.split_once('.')?;
884 if ctx.resolved_config_keys.contains(&key) {
885 Some(format!(
886 "crate::config::{file}::config()[{top_key:?}].as_str().unwrap_or_default().to_string()"
887 ))
888 } else {
889 None
890 }
891 } else if function == "str_contains" {
892 let needle = php::argument_node(node, 1)?;
893 let haystack = translate(arg, source, ctx)?;
894 let needle = translate(needle, source, ctx)?;
895 Some(format!("({haystack}).contains(&({needle}))"))
896 } else if function == "str_replace" {
897 // Only the plain-string-argument form - PHP's own
898 // `str_replace` also accepts arrays for `$search`/
899 // `$replace` (multi-pattern replace in one call), which
900 // has no single-line Rust equivalent; that shape simply
901 // fails to translate here (an `array_creation_expression`
902 // argument has no matching `translate` arm), no separate
903 // detection needed.
904 let replace = php::argument_node(node, 1)?;
905 let subject = php::argument_node(node, 2)?;
906 let search_text = translate(arg, source, ctx)?;
907 let replace_text = translate(replace, source, ctx)?;
908 let subject_text = translate(subject, source, ctx)?;
909 Some(format!(
910 "({subject_text}).replace({search_text}, {replace_text})"
911 ))
912 } else if function == "explode" {
913 // Only the 2-argument form - PHP's optional third `$limit`
914 // argument (cap the resulting array's length) has no
915 // direct `str::split` equivalent without extra
916 // post-processing, so a 3rd argument fails the whole call
917 // rather than silently ignoring it.
918 if php::argument_node(node, 2).is_some() {
919 return None;
920 }
921 let string_arg = php::argument_node(node, 1)?;
922 let separator_text = translate(arg, source, ctx)?;
923 let string_text = translate(string_arg, source, ctx)?;
924 Some(format!(
925 "({string_text}).split({separator_text}).map(|s| s.to_string()).collect::<Vec<String>>()"
926 ))
927 } else if function == "preg_replace" {
928 // Only the plain 3-argument scalar form - PHP's array-
929 // argument forms and the optional `$limit`/`&$count`
930 // parameters have no single-line Rust equivalent.
931 // `arg.kind() != "string"` also excludes an
932 // `encapsed_string` (any double-quoted pattern, even one
933 // with zero interpolation) - restricting to single-quoted
934 // patterns means `unescape_single_quoted_php_string` below
935 // is applying the *right* escape rules for what's
936 // actually there, not silently wrong ones for a
937 // double-quoted literal's different escape semantics.
938 if arg.kind() != "string" || php::argument_node(node, 3).is_some() {
939 return None;
940 }
941 let replacement = php::argument_node(node, 1)?;
942 let subject = php::argument_node(node, 2)?;
943 let raw = php::unquote(arg.utf8_text(bytes).ok()?);
944 let unescaped = unescape_single_quoted_php_string(&raw);
945 let pattern = translate_pcre_pattern(&unescaped)?;
946 // Self-checks against the *exact* crate `larust_support::
947 // regex_replace` runs the same pattern through at
948 // runtime - see that module's own doc comment. Without
949 // this, a pattern Rust's `regex` crate can't compile
950 // would still translate "successfully" here, then
951 // silently do nothing at runtime (that helper's own
952 // never-panic fallback) - exactly the kind of quiet-wrong
953 // behavior this whole tool exists to avoid, so it's
954 // rejected at convert time instead, the same role
955 // `syn::parse_str::<syn::Expr>` plays for every other
956 // construct in this file.
957 if regex::Regex::new(&pattern).is_err() {
958 return None;
959 }
960 let replacement_text = translate(replacement, source, ctx)?;
961 let subject_text = translate(subject, source, ctx)?;
962 Some(format!(
963 "larust_support::regex_replace::replace_all({pattern:?}, {replacement_text}, {subject_text})"
964 ))
965 } else if function == "date" {
966 let format_string = php::unquote(arg.utf8_text(bytes).ok()?);
967 if !is_supported_php_date_format(&format_string) {
968 return None;
969 }
970 let when = match php::argument_node(node, 1) {
971 None => "larust_support::date::now()".to_string(),
972 // The one second-argument shape with an unambiguous
973 // translation: `strtotime(...)` wrapping an already-
974 // translatable expression, matching real Laravel code's
975 // near-universal `date($format, strtotime($x))`
976 // pattern - anything else (a raw Unix timestamp
977 // integer, an arbitrary expression) stays unsupported.
978 // `larust_support::date::strtotime`'s own doc comment
979 // covers exactly what it does and doesn't parse; this
980 // never pretends PHP's real, genuinely fuzzy
981 // `strtotime()` is fully ported.
982 Some(second_arg) => {
983 if second_arg.kind() != "function_call_expression" {
984 return None;
985 }
986 let inner_function = second_arg.child_by_field_name("function")?;
987 if inner_function.utf8_text(bytes).ok()? != "strtotime" {
988 return None;
989 }
990 let strtotime_arg = php::argument_node(second_arg, 0)?;
991 let strtotime_arg_text = translate(strtotime_arg, source, ctx)?;
992 format!("larust_support::date::strtotime(&({strtotime_arg_text}))")
993 }
994 };
995 Some(format!(
996 "larust_support::date::format({when}, {format_string:?})"
997 ))
998 } else {
999 None
1000 }
1001 }
1002 _ => None,
1003 }
1004}
1005
1006/// `(object_node, key)` if `node` is `$x['stringkey']` - a
1007/// `subscript_expression` whose index is a plain string literal, not an
1008/// integer index or a computed key - or `None` for anything else. The one
1009/// shape `??` and `isset(...)` translate specially: unlike ordinary
1010/// interpolation (which indexes with `[]`, panicking on a missing key),
1011/// both need "does this key exist" phrased as `.get(...)`/
1012/// `.contains_key(...)`, which only has an unambiguous meaning for a
1013/// string-keyed map - an integer index's equivalent ("is this within
1014/// bounds") is a different method (`.get(i).is_some()` on a slice, not
1015/// `.contains_key(i)`, which `Vec` doesn't even have), so that case stays
1016/// unsupported rather than guessed at.
1017fn string_keyed_subscript<'a>(node: Node<'a>, source: &str) -> Option<(Node<'a>, String)> {
1018 if node.kind() != "subscript_expression" {
1019 return None;
1020 }
1021 let object = node.named_child(0)?;
1022 let index = node.named_child(1)?;
1023 if index.kind() != "string" {
1024 return None;
1025 }
1026 let key = php::unquote(index.utf8_text(source.as_bytes()).ok()?);
1027 Some((object, key))
1028}
1029
1030/// `true` for exactly the dotted keys `larust_support::config_helper::
1031/// lookup` (the runtime half of `larust_support::config`) knows how to
1032/// resolve against `larust_core::Config` - kept in sync by hand with that
1033/// match table (separate crates: this is a convert-time tool, that's a
1034/// runtime library, the same "can't share one literal table" situation
1035/// `is_supported_php_date_format`'s own doc comment describes). A key
1036/// here gets the direct `larust_support::config(...)` runtime call;
1037/// every other key falls through to the generated
1038/// `crate::config::{file}::config()` module lookup instead.
1039fn is_known_config_helper_key(key: &str) -> bool {
1040 matches!(
1041 key,
1042 "app.name"
1043 | "app.env"
1044 | "app.url"
1045 | "app.port"
1046 | "app.debug"
1047 | "session.secure_cookie"
1048 | "mail.driver"
1049 | "mail.host"
1050 | "mail.port"
1051 | "mail.from_address"
1052 | "mail.from_name"
1053 )
1054}
1055
1056/// PHP's superglobals - `$name` (already stripped of its `$`) refers to
1057/// request/environment/session state, never an ordinary local or context
1058/// variable, regardless of what template it appears in. `_GET` isn't
1059/// here - `translate`'s `variable_name` arm handles it separately, one
1060/// step earlier, since unlike the rest it *does* have a real Larust
1061/// equivalent (a `query` context value).
1062fn is_superglobal(name: &str) -> bool {
1063 matches!(
1064 name,
1065 "_POST" | "_REQUEST" | "_SERVER" | "_SESSION" | "_COOKIE" | "_FILES" | "_ENV" | "GLOBALS"
1066 )
1067}
1068
1069/// `true` if every character in `format_string` is either a PHP `date()`
1070/// format code `larust_support::date::format` implements, or one of a
1071/// small set of literal separator characters real date formats use
1072/// (space, `-`, `/`, `:`, `,`, `.`) - anything else (a PHP format code
1073/// this phase hasn't ported, or an ordinary letter meant as literal text,
1074/// which real PHP itself requires escaping with `\` for) fails the whole
1075/// translation rather than guessing. Kept in sync by hand with
1076/// `larust_support::date::format`'s own recognized-character match arms -
1077/// see that function's own doc comment for why the two can't share one
1078/// literal table (separate crates, convert-time tool vs. runtime library).
1079fn is_supported_php_date_format(format_string: &str) -> bool {
1080 const RECOGNIZED_CODES: &str = "YymndjFMlDHGhgisAaNwS";
1081 const LITERAL_SEPARATORS: &str = " -/:,.";
1082 format_string
1083 .chars()
1084 .all(|ch| RECOGNIZED_CODES.contains(ch) || LITERAL_SEPARATORS.contains(ch))
1085}
1086
1087/// A PHP single-quoted string literal's *content* (already stripped of
1088/// its surrounding quotes by [`php::unquote`]) → its real value: PHP
1089/// recognizes exactly two escapes inside single quotes, `\\` → `\` and
1090/// `\'` → `'` - every other backslash sequence (including `\n`, `\t`,
1091/// `\/`) is literal, both characters unchanged. [`php::unquote`] itself
1092/// deliberately doesn't do this (documented there as not attempting real
1093/// PHP string-escape handling, since nothing else this phase converts
1094/// needs it) - a regex pattern genuinely does: without it, an escaped
1095/// quote inside a character class like `['\'"]` would leave a spurious
1096/// literal backslash in the generated Rust pattern instead of a plain
1097/// `'`.
1098fn unescape_single_quoted_php_string(raw: &str) -> String {
1099 let mut out = String::with_capacity(raw.len());
1100 let mut chars = raw.chars().peekable();
1101 while let Some(c) = chars.next() {
1102 if c != '\\' {
1103 out.push(c);
1104 continue;
1105 }
1106 match chars.peek() {
1107 Some('\\') => {
1108 out.push('\\');
1109 chars.next();
1110 }
1111 Some('\'') => {
1112 out.push('\'');
1113 chars.next();
1114 }
1115 _ => out.push('\\'),
1116 }
1117 }
1118 out
1119}
1120
1121/// PHP's `preg_replace` pattern argument is PCRE source wrapped in a
1122/// delimiter pair with optional trailing flags (`/pattern/flags`) - Rust's
1123/// `regex` crate takes bare pattern source with no delimiters, flags
1124/// expressed as an inline `(?flags)` prefix instead. Only the common
1125/// same-character delimiter form (`/.../`, `#...#`, `~...~`, ...) is
1126/// supported - PHP's alternate bracket-pair delimiters (`(...)`, `{...}`,
1127/// `[...]`, `<...>`) are rejected, a narrower but honest scope decision
1128/// matching this file's others. Recognizes PHP's `i`/`m`/`s` flags
1129/// (identical single-letter inline flags in Rust `regex` syntax) and
1130/// silently drops `u` (Rust strings are always valid UTF-8 and the crate
1131/// always operates in Unicode mode, so PHP's UTF-8-mode flag is already a
1132/// no-op here) - any other flag character (`x`, `A`, `D`, `U`, the
1133/// deprecated `e`, ...) rejects the whole pattern rather than silently
1134/// ignoring it. Doesn't itself guarantee the resulting Rust pattern
1135/// compiles (PCRE has constructs - lookaround, in-pattern backreferences,
1136/// `(?<name>...)`-style named groups - Rust's `regex` crate deliberately
1137/// doesn't support); the caller (`translate`'s own `"preg_replace"` arm)
1138/// self-checks the result with a real `regex::Regex::new` call.
1139fn translate_pcre_pattern(value: &str) -> Option<String> {
1140 let mut chars = value.chars();
1141 let delimiter = chars.next()?;
1142 if delimiter.is_alphanumeric()
1143 || delimiter.is_whitespace()
1144 || matches!(
1145 delimiter,
1146 '\\' | '(' | ')' | '{' | '}' | '[' | ']' | '<' | '>'
1147 )
1148 {
1149 return None;
1150 }
1151 let rest = chars.as_str();
1152 let closing = find_unescaped_delimiter(rest, delimiter)?;
1153 let body = &rest[..closing];
1154 let flags = &rest[closing + delimiter.len_utf8()..];
1155
1156 let mut prefix_flags = String::new();
1157 for flag in flags.chars() {
1158 match flag {
1159 'i' | 'm' | 's' => prefix_flags.push(flag),
1160 'u' => {}
1161 _ => return None,
1162 }
1163 }
1164 if prefix_flags.is_empty() {
1165 Some(body.to_string())
1166 } else {
1167 Some(format!("(?{prefix_flags}){body}"))
1168 }
1169}
1170
1171/// The byte offset of the first occurrence of `delimiter` in `s` that
1172/// isn't preceded by a backslash - mirrors `blade::scan::parse_paren_arg`'s
1173/// own escape-aware scanning technique, applied to a single delimiter
1174/// character instead of a balanced paren pair.
1175fn find_unescaped_delimiter(s: &str, delimiter: char) -> Option<usize> {
1176 let mut chars = s.char_indices();
1177 while let Some((i, c)) = chars.next() {
1178 if c == '\\' {
1179 chars.next();
1180 } else if c == delimiter {
1181 return Some(i);
1182 }
1183 }
1184 None
1185}
1186
1187fn translate_interpolated_string(raw: &str) -> Option<String> {
1188 let text = php::unquote(raw);
1189 if !text.contains('$') {
1190 return Some(format!("{text:?}"));
1191 }
1192 let mut format = String::new();
1193 let mut args = Vec::new();
1194 let mut chars = text.chars().peekable();
1195 while let Some(ch) = chars.next() {
1196 if ch != '$' {
1197 format.push(ch);
1198 continue;
1199 }
1200 // Peek-then-conditionally-consume, not `take_while` on
1201 // `chars.by_ref()` - `Iterator::take_while` consumes (without
1202 // yielding) the first element that fails its predicate, which
1203 // here would silently *drop* whatever literal character
1204 // immediately follows the variable name (`"$position-$type"`'s
1205 // `-`, lost entirely from `format` if `chars.by_ref().take_while`
1206 // were used, verified empirically before this fix). Peeking keeps
1207 // that boundary character in the iterator for the next outer-loop
1208 // pass to correctly treat as literal text.
1209 let mut name = String::new();
1210 while let Some(&next) = chars.peek() {
1211 if next.is_ascii_alphanumeric() || next == '_' {
1212 name.push(next);
1213 chars.next();
1214 } else {
1215 break;
1216 }
1217 }
1218 if name.is_empty() {
1219 return None;
1220 }
1221 // Same keyword-escaping as `translate`'s own `variable_name` arm
1222 // (`$type` inside `"$position-$type"` hits the identical
1223 // collision `$type` alone does) - a separate check because this
1224 // function builds `name` itself from raw text rather than
1225 // recursing through `translate`.
1226 let escaped = if crate::codegen::is_rust_keyword(&name) {
1227 format!("{name}_")
1228 } else {
1229 name
1230 };
1231 if crate::codegen::validate_identifier(&escaped).is_err() {
1232 return None;
1233 }
1234 format.push_str("{}");
1235 args.push(escaped);
1236 }
1237 Some(format!("format!({format:?}, {})", args.join(", ")))
1238}
1239
1240/// PHP's own operator token text -> the equivalent Rust operator. `.`
1241/// (concatenation), `??`, `and`/`or`/`xor` all reach here (every PHP
1242/// infix operator parses as the same `binary_expression` node kind) and
1243/// fall through the catch-all, unsupported.
1244fn map_operator(php_operator: &str) -> Option<&'static str> {
1245 match php_operator {
1246 "&&" => Some("&&"),
1247 "||" => Some("||"),
1248 "==" | "===" => Some("=="),
1249 "!=" | "!==" | "<>" => Some("!="),
1250 "<" => Some("<"),
1251 ">" => Some(">"),
1252 "<=" => Some("<="),
1253 ">=" => Some(">="),
1254 "+" => Some("+"),
1255 "-" => Some("-"),
1256 "*" => Some("*"),
1257 "/" => Some("/"),
1258 "%" => Some("%"),
1259 _ => None,
1260 }
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265 use super::*;
1266
1267 /// Builds a `&ConvertContext` inline for a test call site - bare
1268 /// `test_ctx!()` is an empty `resolved_config_keys` set (every test
1269 /// that doesn't exercise `config(...)` resolution against a
1270 /// generated module), `test_ctx!("file.key", ...)` pre-populates it
1271 /// (for the handful of tests exercising the generated-module side of
1272 /// the `"config"` arm). Lives only as long as the enclosing statement
1273 /// via ordinary temporary lifetime extension, same as
1274 /// `blade::scan`'s own `test_ctx!` helper.
1275 macro_rules! test_ctx {
1276 () => {
1277 &ConvertContext {
1278 laravel_root: std::path::Path::new("/nonexistent"),
1279 resolved_config_keys: &std::collections::HashSet::new(),
1280 tainted_vars: std::cell::RefCell::new(std::collections::HashSet::new()),
1281 degraded_spot_count: std::cell::Cell::new(0),
1282 }
1283 };
1284 ($($key:expr),+ $(,)?) => {
1285 &ConvertContext {
1286 laravel_root: std::path::Path::new("/nonexistent"),
1287 resolved_config_keys: &[$($key.to_string()),+]
1288 .into_iter()
1289 .collect::<std::collections::HashSet<String>>(),
1290 tainted_vars: std::cell::RefCell::new(std::collections::HashSet::new()),
1291 degraded_spot_count: std::cell::Cell::new(0),
1292 }
1293 };
1294 }
1295
1296 #[test]
1297 fn translates_a_bare_variable() {
1298 assert_eq!(
1299 translate_expression("$x", test_ctx!()),
1300 Some("x".to_string())
1301 );
1302 }
1303
1304 #[test]
1305 fn translates_a_property_chain() {
1306 assert_eq!(
1307 translate_expression("$post->title", test_ctx!()),
1308 Some("post.title".to_string())
1309 );
1310 assert_eq!(
1311 translate_expression("$post->author->name", test_ctx!()),
1312 Some("post.author.name".to_string())
1313 );
1314 }
1315
1316 #[test]
1317 fn translates_literals() {
1318 assert_eq!(
1319 translate_expression("true", test_ctx!()),
1320 Some("true".to_string())
1321 );
1322 assert_eq!(
1323 translate_expression("42", test_ctx!()),
1324 Some("42".to_string())
1325 );
1326 assert_eq!(
1327 translate_expression("4.2", test_ctx!()),
1328 Some("4.2".to_string())
1329 );
1330 assert_eq!(
1331 translate_expression("'hello'", test_ctx!()),
1332 Some("\"hello\"".to_string())
1333 );
1334 }
1335
1336 #[test]
1337 fn translates_unary_not() {
1338 // Real source: `index/main.blade.xr`'s `!$status` - `$status`
1339 // is a plain `String`, which has no `Not` impl, so a bare
1340 // `!(x)` would fail to compile the moment this sits inside
1341 // anything other than a bare `@if` condition (where the
1342 // *outer* `truthy(&(...))` wrap masks the bug for that one
1343 // case). Routed through `truthy` here too - a no-op for a
1344 // genuine `bool` operand, correct PHP-truthiness coercion
1345 // otherwise.
1346 assert_eq!(
1347 translate_expression("!$x", test_ctx!()),
1348 Some("!larust_support::truthy::truthy(&(x))".to_string())
1349 );
1350 }
1351
1352 #[test]
1353 fn translates_comparison_and_logical_operators() {
1354 assert_eq!(
1355 translate_expression("$x == $y", test_ctx!()),
1356 Some("(x) == (y)".to_string())
1357 );
1358 assert_eq!(
1359 translate_expression("$current == \"home\"", test_ctx!()),
1360 Some("(current) == (\"home\")".to_string())
1361 );
1362 assert_eq!(
1363 translate_expression("$x && $y", test_ctx!()),
1364 Some("(x) && (y)".to_string())
1365 );
1366 }
1367
1368 #[test]
1369 fn collapses_strict_equality_to_rusts_single_form() {
1370 assert_eq!(
1371 translate_expression("$x === $y", test_ctx!()),
1372 Some("(x) == (y)".to_string())
1373 );
1374 assert_eq!(
1375 translate_expression("$x !== $y", test_ctx!()),
1376 Some("(x) != (y)".to_string())
1377 );
1378 assert_eq!(
1379 translate_expression("$x <> $y", test_ctx!()),
1380 Some("(x) != (y)".to_string())
1381 );
1382 }
1383
1384 #[test]
1385 fn rejects_keyword_form_logical_operators() {
1386 assert_eq!(translate_expression("$x and $y", test_ctx!()), None);
1387 assert_eq!(translate_expression("$x or $y", test_ctx!()), None);
1388 }
1389
1390 #[test]
1391 fn translates_empty_and_not_empty() {
1392 assert_eq!(
1393 translate_expression("empty($x)", test_ctx!()),
1394 Some("(x).is_empty()".to_string())
1395 );
1396 assert_eq!(
1397 translate_expression("!empty($x)", test_ctx!()),
1398 Some("!larust_support::truthy::truthy(&((x).is_empty()))".to_string())
1399 );
1400 }
1401
1402 #[test]
1403 fn rejects_isset_and_other_function_calls() {
1404 assert_eq!(translate_expression("isset($x)", test_ctx!()), None);
1405 assert_eq!(
1406 translate_expression("route('posts.show')", test_ctx!()),
1407 None
1408 );
1409 assert_eq!(
1410 translate_expression("$post->getExcerpt()", test_ctx!()),
1411 None
1412 );
1413 }
1414
1415 #[test]
1416 fn translates_isset_over_a_string_keyed_subscript_to_contains_key() {
1417 assert_eq!(
1418 translate_expression("isset($data['keywords'])", test_ctx!()),
1419 Some(r#"(data).contains_key("keywords")"#.to_string())
1420 );
1421 }
1422
1423 #[test]
1424 fn rejects_isset_over_an_integer_indexed_subscript() {
1425 // A different, unimplemented Rust idiom (`Vec` has no
1426 // `contains_key`) - not the same one guessed at.
1427 assert_eq!(translate_expression("isset($arr[0])", test_ctx!()), None);
1428 }
1429
1430 #[test]
1431 fn translates_ternary_to_an_if_else_expression() {
1432 // Neither branch is a string literal (both bare variables) - no
1433 // `.to_string()` coercion needed or applied; see
1434 // `a_ternary_with_one_computed_and_one_literal_branch_coerces_both_to_string`
1435 // for the case that *does* need it.
1436 assert_eq!(
1437 translate_expression("$cond == true ? $a : $b", test_ctx!()),
1438 Some(
1439 "if larust_support::truthy::truthy(&((cond) == (true))) { a } else { b }"
1440 .to_string()
1441 )
1442 );
1443 }
1444
1445 #[test]
1446 fn a_ternary_with_one_computed_and_one_literal_branch_coerces_both_to_string() {
1447 // The exact real-world case this whole fix is for:
1448 // `dividers.blade.php`'s `$type !== '' && $type !== 'slant' ?
1449 // "{$position}-{$type}" : $position` - one branch a computed
1450 // `format!(...)`-shaped `String`, the other a bare variable.
1451 // Without coercion this doesn't compile (`if`/`else` branches
1452 // disagree on `String` vs whatever `$position`'s own type turns
1453 // out to be at the call site).
1454 let translated = translate_expression(
1455 r#"$type !== '' && $type !== 'slant' ? "{$position}-{$type}" : $position"#,
1456 test_ctx!(),
1457 )
1458 .unwrap();
1459 assert!(translated.contains(").to_string() } else {"));
1460 assert!(translated.ends_with(").to_string() }"));
1461 }
1462
1463 #[test]
1464 fn a_boolean_ternary_is_never_coerced_to_string() {
1465 // Real source: `blogcarditem.blade.php`'s keyword-match filter,
1466 // `$q ? substr_count($item['keywords'], $q) > 0 : true` - both
1467 // branches are already `bool`-typed and type-consistent; forcing
1468 // `.to_string()` here would be actively wrong, not just
1469 // unnecessary: a `String` `"false"` is still a non-empty string,
1470 // hence *truthy* under `larust_support::truthy`'s own "empty
1471 // string is falsy" convention - silently inverting the filter
1472 // whenever the count is zero. Neither branch is a string
1473 // literal, so the coercion heuristic never fires.
1474 let translated = translate_expression(
1475 r#"$q ? substr_count($item['keywords'], $q) > 0 : true"#,
1476 test_ctx!(),
1477 )
1478 .unwrap();
1479 assert!(!translated.contains(".to_string()"));
1480 }
1481
1482 #[test]
1483 fn translates_a_ternary_with_a_bare_variable_condition_via_the_truthy_helper() {
1484 // The real-world case this exists for: `$q ? ... : ...`, where
1485 // `$q` holds a search-query `String`, not a bool -
1486 // `larust_support::truthy` handles it correctly regardless of
1487 // what the underlying type actually is.
1488 assert_eq!(
1489 translate_expression("$q ? $a : $b", test_ctx!()),
1490 Some("if larust_support::truthy::truthy(&(q)) { a } else { b }".to_string())
1491 );
1492 }
1493
1494 #[test]
1495 fn translates_a_ternary_with_a_comparison_and_strings() {
1496 // Both branches are string literals - coerced to `.to_string()`
1497 // (see the general-ternary comment for why: harmless here since
1498 // both are already string-shaped, and load-bearing for the case
1499 // where only one side is, e.g. `dividers.blade.php`'s own
1500 // literal-vs-computed ternary).
1501 assert_eq!(
1502 translate_expression("$current == \"home\" ? \"active\" : \"idle\"", test_ctx!()),
1503 Some(
1504 "if larust_support::truthy::truthy(&((current) == (\"home\"))) { (\"active\").to_string() } else { (\"idle\").to_string() }"
1505 .to_string()
1506 )
1507 );
1508 }
1509
1510 #[test]
1511 fn translates_vite_asset_stripping_the_resources_prefix() {
1512 assert_eq!(
1513 translate_expression("Vite::asset('resources/css/app.css')", test_ctx!()),
1514 Some(r#"larust_support::asset("css/app.css")"#.to_string())
1515 );
1516 }
1517
1518 #[test]
1519 fn translates_vite_asset_without_a_resources_prefix_unchanged() {
1520 assert_eq!(
1521 translate_expression("Vite::asset('images/logo.svg')", test_ctx!()),
1522 Some(r#"larust_support::asset("images/logo.svg")"#.to_string())
1523 );
1524 }
1525
1526 #[test]
1527 fn rejects_other_static_method_calls() {
1528 assert_eq!(translate_expression("Vite::hotReload()", test_ctx!()), None);
1529 assert_eq!(
1530 translate_expression(r"\Illuminate\Support\Str::endsWith($x, ['a'])", test_ctx!()),
1531 None
1532 );
1533 }
1534
1535 #[test]
1536 fn translates_a_top_level_ternary_with_a_null_false_branch() {
1537 assert_eq!(
1538 translate_expression("$x ? $x : null", test_ctx!()),
1539 Some(
1540 "if larust_support::truthy::truthy(&(x)) { (x).to_string() } else { String::new() }"
1541 .to_string()
1542 )
1543 );
1544 }
1545
1546 #[test]
1547 fn translates_a_top_level_ternary_with_a_null_true_branch() {
1548 assert_eq!(
1549 translate_expression("$x ? null : $x", test_ctx!()),
1550 Some(
1551 "if larust_support::truthy::truthy(&(x)) { String::new() } else { (x).to_string() }"
1552 .to_string()
1553 )
1554 );
1555 }
1556
1557 #[test]
1558 fn translates_a_nested_ternary_with_a_null_branch_reached_through_a_function_argument() {
1559 // A ternary nested inside a function call argument reaches the
1560 // AST-based `"conditional_expression"` arm directly, never
1561 // `translate_simple_ternary`'s top-level-only text path - the
1562 // real-world shape this covers (`preg_replace`/`str_replace`
1563 // arguments, and the motivating case: a `@php` block assignment,
1564 // reached the same way via `translate_php_block`).
1565 let translated = translate_expression("trim($x ? $x : null)", test_ctx!()).unwrap();
1566 assert!(translated.contains("String::new()"));
1567 assert!(translated.contains("larust_support::truthy::truthy"));
1568 assert!(syn::parse_str::<syn::Expr>(&translated).is_ok());
1569 }
1570
1571 #[test]
1572 fn a_null_ternary_assignment_still_parses_alongside_a_later_interpolation() {
1573 // The exact regression the first, discarded `Option<T>` design
1574 // hit: `$previewUrl = $cond ? A : null;` followed by
1575 // `{{ $previewUrl }}` elsewhere in the same template.
1576 // `Option<T>` doesn't implement `Display`; `String` does - this
1577 // only proves the combined shape parses as valid Rust syntax
1578 // (`syn`, like the rest of this file's self-checks, doesn't type-
1579 // check); the real proof is the real-world yardstick project's
1580 // own `cargo build` after conversion.
1581 let assignment =
1582 translate_php_block("$previewUrl = $cond ? $x : null;", test_ctx!()).unwrap();
1583 let full = format!(
1584 "fn render(cond: bool, x: String) -> String {{ {assignment} format!(\"{{}}\", previewUrl) }}"
1585 );
1586 assert!(
1587 syn::parse_str::<syn::ItemFn>(&full).is_ok(),
1588 "generated code failed to parse as a function: {full}"
1589 );
1590 }
1591
1592 #[test]
1593 fn translates_preg_replace_with_a_slash_delimited_pattern_and_backreference_replacement() {
1594 // The real-world case this exists for: rewriting a stored
1595 // relative `/storage/...` path into a full URL, only when it
1596 // appears at the start of the string or right after a quote/
1597 // paren/whitespace (the `(^|["'(\s])` alternation, captured as
1598 // `$1` so the replacement preserves whatever preceded the match).
1599 let source = r#"preg_replace('/(^|["\'(\s])\/storage/', '$1' . config('app.apiurl') . '/storage', $body)"#;
1600 let translated = translate_expression(source, test_ctx!("app.apiurl")).unwrap();
1601 assert!(translated.starts_with("larust_support::regex_replace::replace_all("));
1602 assert!(translated.contains(r#""(^|[\"'(\\s])\\/storage""#));
1603 assert!(translated.contains(r#"crate::config::app::config()["apiurl"]"#));
1604 assert!(translated.ends_with("body)"));
1605 assert!(syn::parse_str::<syn::Expr>(&translated).is_ok());
1606 }
1607
1608 #[test]
1609 fn rejects_preg_replace_with_a_double_quoted_pattern() {
1610 // Only a single-quoted pattern is supported - see
1611 // `unescape_single_quoted_php_string`'s own doc comment for why a
1612 // double-quoted pattern's different escape rules make this unsafe
1613 // to guess at.
1614 assert_eq!(
1615 translate_expression(r#"preg_replace("/a/", 'b', $x)"#, test_ctx!()),
1616 None
1617 );
1618 }
1619
1620 #[test]
1621 fn rejects_preg_replace_with_the_array_form() {
1622 assert_eq!(
1623 translate_expression(r"preg_replace(['/a/', '/b/'], 'x', $y)", test_ctx!()),
1624 None
1625 );
1626 }
1627
1628 #[test]
1629 fn rejects_preg_replace_with_a_bracket_delimiter() {
1630 assert_eq!(
1631 translate_expression(r"preg_replace('(a)', 'b', $x)", test_ctx!()),
1632 None
1633 );
1634 }
1635
1636 #[test]
1637 fn rejects_preg_replace_with_an_unrecognized_flag() {
1638 // `x` (extended/whitespace mode) isn't in the recognized set.
1639 assert_eq!(
1640 translate_expression(r"preg_replace('/a/x', 'b', $x)", test_ctx!()),
1641 None
1642 );
1643 }
1644
1645 #[test]
1646 fn rejects_preg_replace_with_a_pcre_construct_rust_regex_does_not_support() {
1647 // Lookahead - Rust's `regex` crate deliberately doesn't support
1648 // it, so the convert-time `regex::Regex::new` self-check catches
1649 // this rather than emitting a call that would panic (or, given
1650 // `regex_replace::replace_all`'s never-panic fallback, silently
1651 // never match) at runtime.
1652 assert_eq!(
1653 translate_expression(r"preg_replace('/foo(?=bar)/', 'x', $y)", test_ctx!()),
1654 None
1655 );
1656 }
1657
1658 #[test]
1659 fn translates_str_starts_with_against_an_array_of_prefixes() {
1660 assert_eq!(
1661 translate_expression(
1662 r"\Illuminate\Support\Str::startsWith($x, ['a'])",
1663 test_ctx!()
1664 ),
1665 Some(r#"(x).starts_with("a")"#.to_string())
1666 );
1667 assert_eq!(
1668 translate_expression(
1669 r"\Illuminate\Support\Str::startsWith($x, ['http://', 'https://'])",
1670 test_ctx!()
1671 ),
1672 Some(r#"(x).starts_with("http://") || (x).starts_with("https://")"#.to_string())
1673 );
1674 assert_eq!(
1675 translate_expression(r"Str::startsWith($x, ['a'])", test_ctx!()),
1676 Some(r#"(x).starts_with("a")"#.to_string())
1677 );
1678 }
1679
1680 #[test]
1681 fn translates_str_replace_and_explode() {
1682 assert_eq!(
1683 translate_expression("str_replace('_', ' ', $x)", test_ctx!()),
1684 Some(r#"(x).replace("_", " ")"#.to_string())
1685 );
1686 assert_eq!(
1687 translate_expression("explode(',', $x)", test_ctx!()),
1688 Some(r#"(x).split(",").map(|s| s.to_string()).collect::<Vec<String>>()"#.to_string())
1689 );
1690 }
1691
1692 #[test]
1693 fn rejects_explode_with_a_limit_argument() {
1694 assert_eq!(
1695 translate_expression("explode(',', $x, 2)", test_ctx!()),
1696 None
1697 );
1698 }
1699
1700 #[test]
1701 fn translates_trim_count_and_ucwords() {
1702 assert_eq!(
1703 translate_expression("trim($x)", test_ctx!()),
1704 Some("(x).trim().to_string()".to_string())
1705 );
1706 assert_eq!(
1707 translate_expression("count($keywords)", test_ctx!()),
1708 Some("(keywords).len()".to_string())
1709 );
1710 assert_eq!(
1711 translate_expression("ucwords($item['page'])", test_ctx!()),
1712 Some(r#"larust_support::strings::ucwords(&(item["page"]))"#.to_string())
1713 );
1714 }
1715
1716 #[test]
1717 fn translates_strtolower_and_substr_count() {
1718 assert_eq!(
1719 translate_expression("strtolower($x)", test_ctx!()),
1720 Some("(x).to_lowercase()".to_string())
1721 );
1722 assert_eq!(
1723 translate_expression("substr_count($haystack, $needle)", test_ctx!()),
1724 Some("(haystack).matches(needle).count()".to_string())
1725 );
1726 }
1727
1728 #[test]
1729 fn translates_the_real_world_substr_count_filter_shape() {
1730 // The exact real-world case this was built for, `$q` bare (a
1731 // search-query string, not a bool) and all:
1732 // `$q ? substr_count($item['keywords'], $q) > 0 : true`.
1733 assert_eq!(
1734 translate_expression(r#"$q ? substr_count($item['keywords'], $q) > 0 : true"#, test_ctx!()),
1735 Some(
1736 r#"if larust_support::truthy::truthy(&(q)) { ((item["keywords"]).matches(q).count()) > (0) } else { true }"#
1737 .to_string()
1738 )
1739 );
1740 }
1741
1742 #[test]
1743 fn translates_count_inside_a_comparison() {
1744 assert_eq!(
1745 translate_expression("count($keywords) > 1", test_ctx!()),
1746 Some("((keywords).len()) > (1)".to_string())
1747 );
1748 }
1749
1750 #[test]
1751 fn rejects_str_replace_with_array_arguments() {
1752 // No `translate` arm matches `array_creation_expression` - this
1753 // fails on its own, no separate array-detection needed.
1754 assert_eq!(
1755 translate_expression("str_replace(['a', 'b'], 'c', $x)", test_ctx!()),
1756 None
1757 );
1758 }
1759
1760 #[test]
1761 fn rejects_php_superglobals_other_than_get() {
1762 assert_eq!(translate_expression("$_POST", test_ctx!()), None);
1763 assert_eq!(translate_expression("$_POST['q']", test_ctx!()), None);
1764 assert_eq!(
1765 translate_expression("isset($_SERVER['q'])", test_ctx!()),
1766 None
1767 );
1768 }
1769
1770 #[test]
1771 fn translates_get_to_the_query_context_variable() {
1772 assert_eq!(
1773 translate_expression("$_GET", test_ctx!()),
1774 Some("query".to_string())
1775 );
1776 assert_eq!(
1777 translate_expression("$_GET['q']", test_ctx!()),
1778 Some(r#"query["q"]"#.to_string())
1779 );
1780 assert_eq!(
1781 translate_expression("isset($_GET['q'])", test_ctx!()),
1782 Some(r#"(query).contains_key("q")"#.to_string())
1783 );
1784 assert_eq!(
1785 translate_expression("$_GET['q'] ?? ''", test_ctx!()),
1786 Some(r#"(query).get("q").cloned().unwrap_or_else(|| ("").to_string())"#.to_string())
1787 );
1788 }
1789
1790 #[test]
1791 fn translates_the_isset_ternary_idiom_the_same_way_as_null_coalescing() {
1792 // The exact real-world shape this was built for:
1793 // `isset($_GET['q']) ? $_GET['q'] : ""` - Laravel's own more
1794 // verbose, explicit spelling of `$_GET['q'] ?? ""`.
1795 assert_eq!(
1796 translate_expression(r#"isset($_GET['q']) ? $_GET['q'] : """#, test_ctx!()),
1797 Some(r#"(query).get("q").cloned().unwrap_or_else(|| ("").to_string())"#.to_string())
1798 );
1799 }
1800
1801 #[test]
1802 fn translates_the_isset_ternary_idiom_when_nested_inside_a_function_call() {
1803 // The actual real-world shape: the idiom as a `str_replace(...)`
1804 // argument, not a bare top-level expression - reaches
1805 // `translate`'s AST-based `"conditional_expression"` arm, not
1806 // `translate_simple_ternary`'s top-level-only text fast path.
1807 assert_eq!(
1808 translate_expression(r#"str_replace('_', ' ', isset($_GET['q']) ? $_GET['q'] : "")"#, test_ctx!()),
1809 Some(
1810 r#"((query).get("q").cloned().unwrap_or_else(|| ("").to_string())).replace("_", " ")"#
1811 .to_string()
1812 )
1813 );
1814 }
1815
1816 #[test]
1817 fn does_not_misfire_the_isset_ternary_idiom_on_an_unrelated_ternary() {
1818 // Both branches are string literals - see
1819 // `translates_a_ternary_with_a_comparison_and_strings`'s own
1820 // comment for why they're coerced to `.to_string()`.
1821 assert_eq!(
1822 translate_expression(r#"$q == trim($word) ? "a" : "b""#, test_ctx!()),
1823 Some(
1824 r#"if larust_support::truthy::truthy(&((q) == ((word).trim().to_string()))) { ("a").to_string() } else { ("b").to_string() }"#
1825 .to_string()
1826 )
1827 );
1828 }
1829
1830 #[test]
1831 fn does_not_misfire_the_isset_ternary_idiom_when_the_branches_differ() {
1832 // `isset($x['a'])` but the true branch reads `$x['b']` - not the
1833 // same expression, must not be treated as the `??` idiom. The
1834 // alternative branch (`"x"`) is a string literal, so both sides
1835 // coerce to `.to_string()` - the exact real-world shape this
1836 // whole fix is for: a computed branch (`$item['b']`) paired with
1837 // a literal one.
1838 assert_eq!(
1839 translate_expression(r#"isset($item['a']) ? $item['b'] : "x""#, test_ctx!()),
1840 Some(
1841 r#"if larust_support::truthy::truthy(&((item).contains_key("a"))) { (item["b"]).to_string() } else { ("x").to_string() }"#
1842 .to_string()
1843 )
1844 );
1845 }
1846
1847 #[test]
1848 fn translates_a_php_block_of_simple_assignments_to_code_block_statements() {
1849 let translated = translate_php_block(
1850 r#"$keywords = explode(",", str_replace('"', "", $item['keywords']));"#,
1851 test_ctx!(),
1852 )
1853 .unwrap();
1854 assert_eq!(
1855 translated,
1856 r#"let mut keywords = ((item["keywords"]).replace("\"", "")).split(",").map(|s| s.to_string()).collect::<Vec<String>>();"#
1857 );
1858 }
1859
1860 #[test]
1861 fn translates_multiple_assignment_statements_in_order() {
1862 let translated = translate_php_block("$a = $x; $b = $a;", test_ctx!()).unwrap();
1863 assert_eq!(translated, "let mut a = x; let mut b = a;");
1864 }
1865
1866 #[test]
1867 fn translates_an_increment_and_decrement_statement() {
1868 let translated = translate_php_block("$x = 0; $x++; $x--;", test_ctx!()).unwrap();
1869 assert_eq!(translated, "let mut x = 0; x += 1; x -= 1;");
1870 }
1871
1872 #[test]
1873 fn rejects_a_php_block_containing_a_superglobal() {
1874 // `$_GET` specifically now has a real translation (the `query`
1875 // context variable) - `$_POST` doesn't, so it's still the right
1876 // example of a genuinely unsupported superglobal.
1877 assert_eq!(
1878 translate_php_block(r#"$q = str_replace('_', " ", $_POST['q']);"#, test_ctx!()),
1879 None
1880 );
1881 }
1882
1883 #[test]
1884 fn rejects_a_php_block_with_a_non_assignment_statement() {
1885 // `statement_expressions` silently skips non-`expression_statement`
1886 // kinds like `if` - this proves the block-level count check
1887 // actually catches that rather than partially translating just
1888 // the assignment and silently dropping the `if`.
1889 assert_eq!(
1890 translate_php_block(r#"$a = $x; if ($a) { $b = $y; }"#, test_ctx!()),
1891 None
1892 );
1893 }
1894
1895 #[test]
1896 fn rejects_a_php_block_with_an_unsupported_assignment_target() {
1897 // Left-hand side isn't a plain `$var` (a property/array-element
1898 // assignment) - no unambiguous Rust `let` translation.
1899 assert_eq!(translate_php_block(r#"$arr['x'] = $y;"#, test_ctx!()), None);
1900 }
1901
1902 #[test]
1903 fn translates_csrf_token_to_the_bare_context_variable() {
1904 assert_eq!(
1905 translate_expression("csrf_token()", test_ctx!()),
1906 Some("csrf_token".to_string())
1907 );
1908 }
1909
1910 #[test]
1911 fn translates_a_single_argument_date_call() {
1912 assert_eq!(
1913 translate_expression("date('Y')", test_ctx!()),
1914 Some(r#"larust_support::date::format(larust_support::date::now(), "Y")"#.to_string())
1915 );
1916 assert_eq!(
1917 translate_expression("date(\"F jS, Y\")", test_ctx!()),
1918 Some(
1919 r#"larust_support::date::format(larust_support::date::now(), "F jS, Y")"#
1920 .to_string()
1921 )
1922 );
1923 }
1924
1925 #[test]
1926 fn translates_date_with_a_strtotime_second_argument() {
1927 // The real-world shape this exists for:
1928 // `date("F jS, Y", strtotime($data['updated_at']))`.
1929 assert_eq!(
1930 translate_expression("date('Y-m-d', strtotime($x))", test_ctx!()),
1931 Some(
1932 r#"larust_support::date::format(larust_support::date::strtotime(&(x)), "Y-m-d")"#
1933 .to_string()
1934 )
1935 );
1936 }
1937
1938 #[test]
1939 fn rejects_date_with_a_non_strtotime_second_argument() {
1940 // A raw Unix timestamp, or any other expression - `strtotime(...)`
1941 // is the one second-argument shape with an unambiguous
1942 // translation.
1943 assert_eq!(
1944 translate_expression("date('Y', $timestamp)", test_ctx!()),
1945 None
1946 );
1947 assert_eq!(translate_expression("date('Y', time())", test_ctx!()), None);
1948 }
1949
1950 #[test]
1951 fn rejects_date_with_an_unrecognized_format_character() {
1952 // `W` (ISO week number) is real PHP, just not one this phase has
1953 // ported - must fail, not silently pass the letter through as if
1954 // it were literal text.
1955 assert_eq!(translate_expression("date('W')", test_ctx!()), None);
1956 }
1957
1958 #[test]
1959 fn translates_a_known_config_helper_key_to_a_direct_runtime_call() {
1960 // `app.url` is one of `config_helper::lookup`'s own known keys -
1961 // already backed by `larust_core::Config`, so it needs no
1962 // generated `crate::config::*` module at all (works even with an
1963 // empty `resolved_config_keys` set).
1964 assert_eq!(
1965 translate_expression("config('app.url')", test_ctx!()),
1966 Some(r#"larust_support::config("app.url").unwrap_or_default()"#.to_string())
1967 );
1968 }
1969
1970 #[test]
1971 fn translates_a_resolved_generated_config_key_to_a_module_indexing_expression() {
1972 // `app.apiurl` isn't one of `config_helper`'s known keys - it
1973 // only resolves once `config/app.rs` was actually generated
1974 // for it (see `larust_convert::config::convert_body`), tracked
1975 // here via `resolved_config_keys`.
1976 assert_eq!(
1977 translate_expression("config('app.apiurl')", test_ctx!("app.apiurl")),
1978 Some(
1979 r#"crate::config::app::config()["apiurl"].as_str().unwrap_or_default().to_string()"#
1980 .to_string()
1981 )
1982 );
1983 }
1984
1985 #[test]
1986 fn rejects_a_config_key_with_no_known_helper_home_and_no_generated_module() {
1987 // `app.apiurl` with an *empty* `resolved_config_keys` - no
1988 // generated module was produced for it, so there's nothing safe
1989 // to reference.
1990 assert_eq!(
1991 translate_expression("config('app.apiurl')", test_ctx!()),
1992 None
1993 );
1994 }
1995
1996 #[test]
1997 fn translates_common_string_helpers() {
1998 assert_eq!(
1999 translate_expression("str_contains($url, 'blog')", test_ctx!()),
2000 Some("(url).contains(&(\"blog\"))".to_string())
2001 );
2002 assert_eq!(
2003 translate_expression("$path . '/hosting'", test_ctx!()),
2004 Some("format!(\"{}{}\", path, \"/hosting\")".to_string())
2005 );
2006 }
2007
2008 #[test]
2009 fn translates_string_concatenation() {
2010 assert_eq!(
2011 translate_expression("$x . $y", test_ctx!()),
2012 Some("format!(\"{}{}\", x, y)".to_string())
2013 );
2014 }
2015
2016 #[test]
2017 fn rejects_null_coalescing() {
2018 assert_eq!(translate_expression("$x ?? $y", test_ctx!()), None);
2019 }
2020
2021 #[test]
2022 fn translates_null_coalescing_over_a_string_keyed_subscript() {
2023 assert_eq!(
2024 translate_expression("$item['created_at'] ?? $fallback", test_ctx!()),
2025 Some(
2026 r#"(item).get("created_at").cloned().unwrap_or_else(|| (fallback).to_string())"#
2027 .to_string()
2028 )
2029 );
2030 }
2031
2032 #[test]
2033 fn translates_null_coalescing_with_a_date_call_as_the_fallback() {
2034 // The exact real-world shape this was built for:
2035 // `$item['created_at'] ?? date('Y-m-d')`.
2036 assert_eq!(
2037 translate_expression("$item['created_at'] ?? date('Y-m-d')", test_ctx!()),
2038 Some(
2039 r#"(item).get("created_at").cloned().unwrap_or_else(|| (larust_support::date::format(larust_support::date::now(), "Y-m-d")).to_string())"#
2040 .to_string()
2041 )
2042 );
2043 }
2044
2045 #[test]
2046 fn translates_null_coalescing_with_a_literal_fallback() {
2047 // Regression test: `unwrap_or_else`'s closure must return exactly
2048 // `String` (the `Option` came from `.cloned()` on
2049 // `Option<&String>`) - a bare string-literal fallback translates
2050 // to `&str`, which is a real, verified `E0308` type mismatch
2051 // without the `.to_string()` normalization this proves.
2052 assert_eq!(
2053 translate_expression("$item['created_at'] ?? ''", test_ctx!()),
2054 Some(
2055 r#"(item).get("created_at").cloned().unwrap_or_else(|| ("").to_string())"#
2056 .to_string()
2057 )
2058 );
2059 }
2060
2061 #[test]
2062 fn rejects_null_coalescing_over_an_integer_indexed_subscript() {
2063 assert_eq!(translate_expression("$arr[0] ?? $y", test_ctx!()), None);
2064 }
2065
2066 #[test]
2067 fn translates_string_key_array_index_access() {
2068 assert_eq!(
2069 translate_expression("$x['y']", test_ctx!()),
2070 Some("x[\"y\"]".to_string())
2071 );
2072 }
2073
2074 #[test]
2075 fn translates_integer_index_array_access() {
2076 assert_eq!(
2077 translate_expression("$arr[0]", test_ctx!()),
2078 Some("arr[0]".to_string())
2079 );
2080 }
2081
2082 #[test]
2083 fn translates_a_property_access_chained_off_a_subscript() {
2084 // Proves recursion, not just a single flat case: the subscripted
2085 // value itself feeds back through the same `translate` dispatch
2086 // as everything else, so `->`/`[...]` compose freely in either
2087 // order with no special-casing for the combination.
2088 assert_eq!(
2089 translate_expression("$item['author']->name", test_ctx!()),
2090 Some("item[\"author\"].name".to_string())
2091 );
2092 }
2093
2094 #[test]
2095 fn rejects_bare_null() {
2096 assert_eq!(translate_expression("null", test_ctx!()), None);
2097 }
2098
2099 #[test]
2100 fn translates_interpolated_strings() {
2101 assert_eq!(
2102 translate_expression("\"hello $x\"", test_ctx!()),
2103 Some("format!(\"hello {}\", x)".to_string())
2104 );
2105 }
2106
2107 #[test]
2108 fn preserves_a_literal_character_immediately_after_an_interpolated_variable() {
2109 // Regression test: `Iterator::take_while` on `chars.by_ref()`
2110 // consumes (without yielding) the first non-matching character -
2111 // a literal `-` right after `$position` was previously lost
2112 // entirely (`"{}{}"` instead of `"{}-{}"`), a real, silent
2113 // correctness bug (not a rejection) the existing test suite never
2114 // exercised because its only case had nothing after the variable
2115 // at all.
2116 assert_eq!(
2117 translate_expression(r#""$position-$type""#, test_ctx!()),
2118 Some(r#"format!("{}-{}", position, type_)"#.to_string())
2119 );
2120 }
2121
2122 #[test]
2123 fn escapes_a_rust_keyword_shaped_php_variable_name() {
2124 assert_eq!(
2125 translate_expression("$type", test_ctx!()),
2126 Some("type_".to_string())
2127 );
2128 assert_eq!(
2129 translate_expression("$type == 'slant'", test_ctx!()),
2130 Some(r#"(type_) == ("slant")"#.to_string())
2131 );
2132 }
2133
2134 #[test]
2135 fn translates_parenthesized_grouping() {
2136 assert_eq!(
2137 translate_expression("($x && $y)", test_ctx!()),
2138 Some("(x) && (y)".to_string())
2139 );
2140 }
2141
2142 #[test]
2143 fn every_accepted_translation_is_valid_syn_expr() {
2144 for source in [
2145 "$x",
2146 "$post->title",
2147 "true",
2148 "42",
2149 "4.2",
2150 "'hello'",
2151 "!$x",
2152 "$x == $y",
2153 "$x && $y",
2154 "empty($x)",
2155 "$cond == true ? $a : $b",
2156 "$x['y']",
2157 "$arr[0]",
2158 "date('Y')",
2159 "date(\"F jS, Y\")",
2160 "csrf_token()",
2161 "isset($data['keywords'])",
2162 "$item['created_at'] ?? date('Y-m-d')",
2163 "trim($x)",
2164 "count($keywords)",
2165 "ucwords($item['page'])",
2166 "str_replace('_', ' ', $x)",
2167 "explode(',', $x)",
2168 "strtolower($x)",
2169 "substr_count($haystack, $needle)",
2170 "date('Y-m-d', strtotime($x))",
2171 "Vite::asset('resources/css/app.css')",
2172 r"\Illuminate\Support\Str::startsWith($x, ['http://', 'https://'])",
2173 r"preg_replace('/(^|[\'(\s])\/storage/', '$1' . config('app.apiurl') . '/storage', $body)",
2174 "$x ? $x : null",
2175 "trim($x ? $x : null)",
2176 ] {
2177 let translated = translate_expression(source, test_ctx!("app.apiurl")).unwrap();
2178 assert!(
2179 syn::parse_str::<syn::Expr>(&translated).is_ok(),
2180 "translation of `{source}` produced invalid Rust: `{translated}`"
2181 );
2182 }
2183 }
2184
2185 #[test]
2186 fn translate_binding_strips_the_dollar_sigil() {
2187 assert_eq!(translate_binding("$post"), Some("post".to_string()));
2188 }
2189
2190 #[test]
2191 fn translate_binding_escapes_a_rust_keyword_shaped_name() {
2192 assert_eq!(translate_binding("$type"), Some("type_".to_string()));
2193 }
2194
2195 #[test]
2196 fn translate_binding_rejects_a_non_identifier() {
2197 assert_eq!(translate_binding("$post->id"), None);
2198 }
2199}