Skip to main content

larust_convert/
livewire.rs

1//! Reads two more mechanical things straight out of a Laravel Livewire
2//! component's own PHP source, beyond the route/mount shell `xr convert`'s
3//! caller already builds around every `livewire_component` route entry:
4//!
5//! - Every `public $prop = <literal>;` property ([`public_properties`]) -
6//!   Laravel's own convention for a Livewire component's reactive state.
7//!   Typed and defaulted straight from the literal, the same "only what's
8//!   mechanically certain, name the rest" discipline
9//!   `models::inferred_fields` already uses for a model with no migration.
10//! - The Blade view `render()` itself names
11//!   (`return view('livewire.pages.index')`, however it's chained
12//!   afterward - [`render_view_target`]) - not re-parsed or re-translated
13//!   here; `blade.rs`'s own conversion pass has *already* turned that
14//!   exact template into a real `resources/views/**/*.blade.xr` file, so
15//!   the caller only needs the *name* to reuse it directly in the
16//!   generated shell's own `render()`.
17//!
18//! Also decides *whether* that reuse is actually safe
19//! ([`view_is_safe_for_scope`]) - `render(&self)` has no `session`/
20//! `csrf_token` binding, unlike the wrapper page's own route handler, so
21//! a template using `@wire`/`@csrf` (or `<wire:...>`, the tag-form
22//! equivalent) anywhere in its *resolved* tree - including transitively,
23//! through every `<resource:...>`/`@resource(...)` include - would
24//! generate a `view!(...)` call that fails to compile. This walks the
25//! real parsed [`larust_view::Node`] tree to answer that precisely,
26//! rather than a blunt raw-text scan that would reject (or wrongly
27//! accept) far more than necessary - real Larust pages lean on
28//! `<resource:...>` heavily for shared layout pieces (nav bars, page
29//! heads, footers), so treating *any* `<resource:...>` as automatically
30//! unsafe would make this whole mechanism fire for almost nothing.
31
32use crate::php;
33use std::collections::HashSet;
34use std::path::Path;
35use syn::parse::Parser;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct PublicProperty {
39    pub name: String,
40    pub rust_type: String,
41    /// Rust literal expression text ready to splice into a field
42    /// initializer, e.g. `"Larust".to_string()`, `true`, `0`.
43    pub default_literal: String,
44}
45
46pub struct ConvertedLivewireComponent {
47    /// Every `public $prop = <supported literal>;` property.
48    pub properties: Vec<PublicProperty>,
49    /// One note per public property this phase couldn't translate - no
50    /// literal default at all (Livewire itself allows this; `mount()`
51    /// fills it in later), or a default value that isn't a plain literal
52    /// (an array, `null`, a constant reference, a method call, ...). The
53    /// property is left out of the generated struct entirely - an
54    /// *absent* field is honest; a wrong-typed guessed one isn't.
55    pub unsupported_properties: Vec<String>,
56    /// The dotted view name `render()`'s own `return view('...')...;`
57    /// call names, if `render()` has that exact shape. `None` for
58    /// anything else (no `render()` method, no matching `return`, a
59    /// computed view name) - left for a manual port either way.
60    pub view_name: Option<String>,
61    /// The dotted view name from a chained `->layout('name', [...])`
62    /// call on the same `return view(...)...;` statement, if present.
63    /// The array argument itself is never read - the shell's own full
64    /// prop set (already threaded to `view_name`'s own `view!(...)`
65    /// call) is reused for the layout's call too, covering every real
66    /// `->layout()` array this converter has been run against so far
67    /// without a second, redundant PHP-array parser. `None` for no
68    /// `->layout(...)` call, or one whose first argument isn't a plain
69    /// string literal.
70    pub layout_name: Option<String>,
71}
72
73pub fn convert(source: &str, class_name: &str) -> Result<ConvertedLivewireComponent, String> {
74    let tree = php::parse(source).map_err(|e| e.to_string())?;
75    if php::has_syntax_error(&tree) {
76        return Err("file has a syntax error the parser couldn't recover from".to_string());
77    }
78    let Some(class_node) = php::find_class(&tree, source, class_name) else {
79        return Err(format!("class `{class_name}` not found in this file"));
80    };
81
82    let (properties, unsupported_properties) = public_properties(class_node, source);
83    let (view_name, layout_name) = render_view_target(class_node, source);
84
85    Ok(ConvertedLivewireComponent {
86        properties,
87        unsupported_properties,
88        view_name,
89        layout_name,
90    })
91}
92
93/// Every `public $name = <value>;` property declared directly on the
94/// class. `protected`/`private` properties are skipped entirely - not
95/// exposed to a Blade template the way Livewire's own public-property
96/// binding works, so irrelevant to `render()`'s own variables (unlike
97/// `models::inferred_fields`'s own property reader, which only ever
98/// reads specific known `protected` framework properties like
99/// `$fillable`/`$casts`, not arbitrary `public` ones).
100fn public_properties(
101    class_node: tree_sitter::Node,
102    source: &str,
103) -> (Vec<PublicProperty>, Vec<String>) {
104    let bytes = source.as_bytes();
105    let mut properties = Vec::new();
106    let mut unsupported = Vec::new();
107    let Some(body) = class_node.child_by_field_name("body") else {
108        return (properties, unsupported);
109    };
110    for declaration in php::direct_children_of_kind(body, "property_declaration") {
111        let is_public = php::direct_children_of_kind(declaration, "visibility_modifier")
112            .iter()
113            .any(|m| m.utf8_text(bytes) == Ok("public"));
114        if !is_public {
115            continue;
116        }
117        for element in php::direct_children_of_kind(declaration, "property_element") {
118            let Some(name_node) = element.child_by_field_name("name") else {
119                continue;
120            };
121            let Some(name_inner) = name_node.named_child(0) else {
122                continue;
123            };
124            let Ok(name) = name_inner.utf8_text(bytes) else {
125                continue;
126            };
127            let Some(default_value) = element.child_by_field_name("default_value") else {
128                unsupported.push(format!(
129                    "${name}: no literal default value to infer a Rust type/default from"
130                ));
131                continue;
132            };
133            match rust_literal(default_value, bytes) {
134                Some((rust_type, default_literal)) => properties.push(PublicProperty {
135                    name: name.to_string(),
136                    rust_type,
137                    default_literal,
138                }),
139                None => unsupported.push(format!(
140                    "${name}: default value isn't a plain literal this phase can translate"
141                )),
142            }
143        }
144    }
145    (properties, unsupported)
146}
147
148/// A plain PHP literal → `(rust_type, default_literal)`. `None` for
149/// anything else (an array, `null`, a constant reference, a method
150/// call, ...).
151///
152/// PHP's own single- and double-quoted strings are two different
153/// grammar productions - `'text'` is a plain `string` node, but `"text"`
154/// is an `encapsed_string` (it supports `{$var}` interpolation, which
155/// `'text'` never does) - real source: `Home::$title`/`$description`/...
156/// are all double-quoted. An `encapsed_string` with exactly one named
157/// child, itself a plain `string_content`, has no interpolation and is
158/// just as safe a literal as a single-quoted one; anything else (a
159/// `variable_name`/`{`-delimited expression child alongside it) means
160/// real interpolation, which this phase can't evaluate at convert time -
161/// treated as unsupported, not guessed at.
162fn rust_literal(node: tree_sitter::Node, bytes: &[u8]) -> Option<(String, String)> {
163    match node.kind() {
164        "string" => {
165            let text = php::unquote(node.utf8_text(bytes).ok()?);
166            Some(("String".to_string(), format!("{text:?}.to_string()")))
167        }
168        // An empty `""` has zero named children at all (no `string_content`
169        // to hold, nothing to interpolate) - as safe a literal as any
170        // other, distinct from the one-child case below only in that
171        // there's no content node to read text from.
172        "encapsed_string" if node.named_child_count() == 0 => {
173            Some(("String".to_string(), "\"\".to_string()".to_string()))
174        }
175        "encapsed_string" if node.named_child_count() == 1 => {
176            let content = node.named_child(0)?;
177            if content.kind() != "string_content" {
178                return None;
179            }
180            let text = content.utf8_text(bytes).ok()?;
181            Some(("String".to_string(), format!("{text:?}.to_string()")))
182        }
183        "boolean" => Some(("bool".to_string(), node.utf8_text(bytes).ok()?.to_string())),
184        "integer" => Some(("i64".to_string(), node.utf8_text(bytes).ok()?.to_string())),
185        "float" => Some(("f64".to_string(), node.utf8_text(bytes).ok()?.to_string())),
186        _ => None,
187    }
188}
189
190/// `render()`'s own `return view('dotted.name')...;` - only the plain
191/// shape (a bare string-literal first argument to `view(...)`) - plus,
192/// separately, a chained `->layout('dotted.name', [...])` call's own
193/// target name (see [`ConvertedLivewireComponent::layout_name`]'s own
194/// doc comment for why its array argument is never read). `(None, _)`
195/// for no `render()` method or a `return` that isn't shaped like this;
196/// `(Some(_), None)` is the common case of no `->layout(...)` at all.
197fn render_view_target(
198    class_node: tree_sitter::Node,
199    source: &str,
200) -> (Option<String>, Option<String>) {
201    let Some(body) = class_node.child_by_field_name("body") else {
202        return (None, None);
203    };
204    for method in php::direct_children_of_kind(body, "method_declaration") {
205        let Some(name_node) = method.child_by_field_name("name") else {
206            continue;
207        };
208        if name_node.utf8_text(source.as_bytes()) != Ok("render") {
209            continue;
210        }
211        let Some(method_body) = method.child_by_field_name("body") else {
212            continue;
213        };
214        for statement in php::direct_children_of_kind(method_body, "return_statement") {
215            let Some(expr) = php::return_expression(statement) else {
216                continue;
217            };
218            if let Some(name) = view_call_argument(expr, source) {
219                return (Some(name), render_layout_target(expr, source));
220            }
221        }
222    }
223    (None, None)
224}
225
226/// Walks the same `view('x')->chained(...)->calls(...)` expression
227/// [`view_call_argument`] reads, looking instead for a `->layout(...)`
228/// call anywhere in the chain and returning its own first argument (if a
229/// plain string literal) - `None` if there's no `->layout(...)` call, or
230/// its first argument isn't a bare string.
231fn render_layout_target(node: tree_sitter::Node, source: &str) -> Option<String> {
232    match node.kind() {
233        "member_call_expression" => {
234            let name_node = node.child_by_field_name("name")?;
235            if name_node.utf8_text(source.as_bytes()).ok()? == "layout" {
236                let arg = php::argument_node(node, 0)?;
237                return if arg.kind() == "string" {
238                    Some(php::unquote(arg.utf8_text(source.as_bytes()).ok()?))
239                } else {
240                    None
241                };
242            }
243            let object = node.child_by_field_name("object")?;
244            render_layout_target(object, source)
245        }
246        _ => None,
247    }
248}
249
250/// Walks a `view('x.y.z')->chained(...)->calls(...)` expression looking
251/// for the root `view(...)` call, regardless of how many method calls
252/// are chained after it. `php::walk_call_chain` isn't quite right for
253/// this shape - it's built to walk from a chain's own base outward, but
254/// its only recognized base case is `scoped_call_expression`
255/// (`Class::method(...)`), not a bare function call like `view(...)`.
256fn view_call_argument(node: tree_sitter::Node, source: &str) -> Option<String> {
257    match node.kind() {
258        "function_call_expression" => {
259            let function = node.child_by_field_name("function")?;
260            if function.utf8_text(source.as_bytes()).ok()? != "view" {
261                return None;
262            }
263            let arg = php::argument_node(node, 0)?;
264            if arg.kind() != "string" {
265                return None;
266            }
267            Some(php::unquote(arg.utf8_text(source.as_bytes()).ok()?))
268        }
269        "member_call_expression" => {
270            let object = node.child_by_field_name("object")?;
271            view_call_argument(object, source)
272        }
273        _ => None,
274    }
275}
276
277/// Whether the already-converted template `view_name` names (a dotted
278/// Larust view name, e.g. `"livewire.pages.index"`, resolved against
279/// `views_root` - an app's own `resources/views` directory) is safe to
280/// call directly from `WireComponent::render(&self)`, where only
281/// `bound_names` (the shell's own struct fields, plus `"query"`) are in
282/// scope. Loads and fully resolves the template - its `@extends` chain
283/// via [`larust_view::resolve`], plus every `<resource:...>`/
284/// `@resource(...)` include, recursively (`resolve()` itself does *not*
285/// flatten those; that only happens later, per-node, in
286/// `larust-macros`'s own codegen) - because without a `session` binding
287/// at all, even a resource-included `@wire`/`@csrf` breaks compilation
288/// the same way a top-level one would; unlike `view!`'s own
289/// `contains_wire` scan (which only checks a `@resource(...)`'s own
290/// `slot`, an accepted v1 boundary there - see `larust-macros::view`'s
291/// own doc comment - since that scan only has to decide whether to emit
292/// a *helpful* error, not whether compilation is possible at all), this
293/// can't stop at the same boundary. `false` on any parse/read failure,
294/// any `@wire`/`@csrf` usage anywhere in the reachable tree, or any
295/// interpolation referencing a name outside `bound_names` - conservative
296/// by design: falling back to the placeholder is always safe, wiring in
297/// a template that doesn't compile isn't.
298pub fn view_is_safe_for_scope(
299    views_root: &Path,
300    view_name: &str,
301    bound_names: &HashSet<String>,
302) -> bool {
303    let Some(nodes) = load_and_resolve(views_root, view_name) else {
304        return false;
305    };
306    tree_is_safe(&nodes, views_root, bound_names)
307}
308
309/// One `@push('head')` occurrence found while walking `view_name`'s own
310/// tree - see [`head_pushes`] for why this exists and what it's used for.
311pub struct HeadPush {
312    /// The block's literal source text, present only when its entire body
313    /// is static (plain `Node::Text`, no interpolation/directive/prop
314    /// reference) - always safe to re-embed verbatim elsewhere, since
315    /// nothing in it depends on any particular scope. `None` means the
316    /// block contains something dynamic a plain text re-embed can't
317    /// reproduce faithfully; the caller should leave it for manual
318    /// porting rather than silently drop or mis-render it.
319    pub text: Option<String>,
320}
321
322/// Every `@push('head')` occurrence reachable from `view_name`'s own
323/// resolved tree, transitively through every `<resource:...>` tag it (or
324/// anything *it* includes) uses - same traversal
325/// `larust_view::resolve`'s own push collection performs internally, but
326/// kept one-entry-per-occurrence here (never merged into a single flat
327/// list) specifically so each can be judged individually for whether
328/// re-embedding it verbatim is actually safe.
329///
330/// Real motivation: `@push('head')` content declared inside a page's own
331/// content template - or, just as often, inside a *nested*
332/// `<resource:...>` it includes (`livewire.elements.sunrise`'s own
333/// `sunrise.min.css` `<link>` tags are the real case that surfaced this) -
334/// never reaches a `@stack('head')` living in the generated wire-shell
335/// template on its own. The shell and the content template are compiled
336/// as two separate `view!(...)` macro invocations - a `<wire:...>` tag is
337/// a runtime session-backed mount, not a compile-time `<resource:...>`
338/// inlining, so there's no shared AST for `@push`/`@stack` to cross (see
339/// `docs/GOTCHAS.md`). The shell generator (`larust-cli::convert`) hoists
340/// each [`HeadPush`] with a `Some(text)` directly into the shell's own
341/// `@push('head')` block, closing that gap automatically instead of
342/// requiring each page to be hand-patched after the fact.
343///
344/// A missing or unparseable `view_name` returns an empty list - same
345/// "conservative, never fabricate" fallback `view_is_safe_for_scope` uses
346/// for the same failure modes.
347pub fn head_pushes(views_root: &Path, view_name: &str) -> Vec<HeadPush> {
348    let Some(root) = load_template(views_root, view_name) else {
349        return Vec::new();
350    };
351    let mut out = Vec::new();
352    let mut visited = HashSet::new();
353    collect_head_pushes(&root, views_root, &mut visited, &mut out);
354    out
355}
356
357fn collect_head_pushes(
358    nodes: &[larust_view::Node],
359    views_root: &Path,
360    visited: &mut HashSet<String>,
361    out: &mut Vec<HeadPush>,
362) {
363    use larust_view::Node;
364    for node in nodes {
365        match node {
366            Node::Push { name, body } if name == "head" => {
367                out.push(HeadPush {
368                    text: static_push_text(body),
369                });
370                // Mirrors `collect_pushes`'s own recursion into a push's
371                // own body - a `@push` nested inside another `@push` is
372                // an edge case `resolve.rs` already has to handle, not
373                // one this walker should silently skip.
374                collect_head_pushes(body, views_root, visited, out);
375            }
376            Node::If {
377                then_branch,
378                else_branch,
379                ..
380            } => {
381                collect_head_pushes(then_branch, views_root, visited, out);
382                collect_head_pushes(else_branch, views_root, visited, out);
383            }
384            Node::Foreach { body, .. }
385            | Node::Section { body, .. }
386            | Node::LoadOnce(body)
387            | Node::Live { body, .. } => collect_head_pushes(body, views_root, visited, out),
388            Node::Resource { name, slot, .. } => {
389                collect_head_pushes(slot, views_root, visited, out);
390                // Keyed by template name, not content - visiting the same
391                // named resource a second time (`questions`/`blogside`
392                // included several times on one page is real, observed
393                // source) is skipped both to avoid infinite recursion on
394                // a cycle and to avoid hoisting the same resource's own
395                // `@push` content once per inclusion.
396                if visited.insert(name.clone()) {
397                    if let Some(resource_nodes) = load_template(views_root, name) {
398                        collect_head_pushes(&resource_nodes, views_root, visited, out);
399                    }
400                }
401            }
402            _ => {}
403        }
404    }
405}
406
407fn static_push_text(nodes: &[larust_view::Node]) -> Option<String> {
408    let mut out = String::new();
409    for node in nodes {
410        match node {
411            larust_view::Node::Text(text) => out.push_str(text),
412            _ => return None,
413        }
414    }
415    Some(out)
416}
417
418/// How a [`LayoutGlobal`] gets a real value in generated code.
419#[derive(Debug, Clone, Copy)]
420pub enum LayoutGlobalResolution {
421    /// A plain Rust literal expression - safe only because the value is
422    /// purely cosmetic (see `theme` below); never used for anything
423    /// security- or identity-sensitive.
424    Literal(&'static str),
425    /// `render(&self)` has no `session`, but `mount(session, props)`
426    /// does - captured there once, into a new struct field of
427    /// `field_type`, via `mount_expr` (a `session`-referencing
428    /// expression, evaluated with `.await`).
429    CapturedAtMount {
430        field_type: &'static str,
431        mount_expr: &'static str,
432    },
433}
434
435pub struct LayoutGlobal {
436    pub name: &'static str,
437    pub resolution: LayoutGlobalResolution,
438}
439
440/// Laravel view variables a *layout* template can reference that come
441/// from `View::share()` or a middleware - never from any component's own
442/// props, and never nameable by a bound-name set built purely from a
443/// component's own `public $prop` declarations. A small, explicit,
444/// hand-curated list (not a general "guess a default" mechanism): each
445/// entry is a real, recurring pattern this converter has actually hit,
446/// with a resolution strategy chosen for that specific name's own
447/// sensitivity.
448///
449/// - `theme` (real source: `components/layouts/app.blade.xr`, set by a
450///   `SetTheme` middleware never translated by this tool) - cosmetic
451///   only (a CSS class name), so a literal fallback default is honest:
452///   wrong at worst means the wrong CSS theme class until the real
453///   middleware is ported by hand, never a security concern.
454/// - `csrf_token` (real source: the same layout's `<meta name=
455///   "csrf-token">` tag) - never given a fake literal: a real CSRF token
456///   must come from the real session, so this captures one via the
457///   exact same `larust_http::csrf::token(session)` call `@csrf`'s own
458///   codegen already uses elsewhere, at `mount()` time (where `session`
459///   is actually available).
460pub const KNOWN_LAYOUT_GLOBALS: &[LayoutGlobal] = &[
461    LayoutGlobal {
462        name: "theme",
463        resolution: LayoutGlobalResolution::Literal("\"lightmode\".to_string()"),
464    },
465    LayoutGlobal {
466        name: "csrf_token",
467        resolution: LayoutGlobalResolution::CapturedAtMount {
468            field_type: "String",
469            mount_expr: "larust_http::csrf::token(session).await",
470        },
471    },
472];
473
474/// Whether `layout_view` is safe to render given `bound_names` (typically
475/// a content component's own struct fields, plus `"query"` and `"slot"`)
476/// once every [`KNOWN_LAYOUT_GLOBALS`] name the layout actually references
477/// is *also* considered bound. Returns exactly the subset of globals
478/// referenced - so a caller only generates the extra field/`mount()`
479/// statement/context binding each one specifically needs, never an
480/// unused one for a global this particular layout doesn't read - or
481/// `None` if the layout still isn't safe even with every known global
482/// applied (some other, genuinely unhandled unbound name, `@wire`/
483/// `@csrf`, ...).
484pub fn layout_globals_for(
485    views_root: &Path,
486    layout_view: &str,
487    bound_names: &HashSet<String>,
488) -> Option<Vec<&'static LayoutGlobal>> {
489    let global_names: HashSet<String> = KNOWN_LAYOUT_GLOBALS
490        .iter()
491        .map(|global| global.name.to_string())
492        .collect();
493    let referenced = referenced_names(views_root, layout_view, bound_names, &global_names)?;
494    Some(
495        KNOWN_LAYOUT_GLOBALS
496            .iter()
497            .filter(|global| referenced.contains(global.name))
498            .collect(),
499    )
500}
501
502/// Exactly the subset of `candidates` that `view_name` (already resolved
503/// safe given `always_bound ∪ candidates` - checked here as a
504/// precondition, `None` if it isn't) actually references, found by
505/// re-running the *real* tree-walking safety checker once per candidate
506/// with just that one name removed: if removing it breaks safety, the
507/// template genuinely depended on it; if the template is still safe
508/// without it, nothing in the reachable tree ever read it. Reuses
509/// [`view_is_safe_for_scope`]'s own real parse-and-walk analysis rather
510/// than a raw-text scan, so it can't false-positive on a name that only
511/// coincidentally appears as a substring of unrelated markup - real
512/// source: `components/layouts/app.blade.xr`'s `<meta name="apple-
513/// mobile-web-app-title">` attribute contains the literal text `title`
514/// (hyphen-bounded, so a naive identifier-boundary text scan would still
515/// treat it as "referenced") despite the template never actually reading
516/// a `title` variable anywhere. Used to decide which of a content
517/// component's own struct fields a *layout* template actually reads, so
518/// codegen only binds those: unlike a content view (which typically
519/// threads every prop onward into nested `<resource:...>` includes, so
520/// an unused one is rare in practice), a flat layout shell often
521/// references only a handful of its caller's values.
522pub fn referenced_names(
523    views_root: &Path,
524    view_name: &str,
525    always_bound: &HashSet<String>,
526    candidates: &HashSet<String>,
527) -> Option<HashSet<String>> {
528    let full_bound: HashSet<String> = always_bound.union(candidates).cloned().collect();
529    if !view_is_safe_for_scope(views_root, view_name, &full_bound) {
530        return None;
531    }
532    Some(
533        candidates
534            .iter()
535            .filter(|candidate| {
536                let mut without_candidate = full_bound.clone();
537                without_candidate.remove(*candidate);
538                !view_is_safe_for_scope(views_root, view_name, &without_candidate)
539            })
540            .cloned()
541            .collect(),
542    )
543}
544
545fn load_and_resolve(views_root: &Path, view_name: &str) -> Option<Vec<larust_view::Node>> {
546    let root = load_template(views_root, view_name)?;
547    larust_view::resolve(root, &mut |parent| {
548        load_template(views_root, parent)
549            .ok_or_else(|| larust_view::ParseError::new(format!("template `{parent}` not found")))
550    })
551    .ok()
552}
553
554fn load_template(views_root: &Path, name: &str) -> Option<Vec<larust_view::Node>> {
555    let path = views_root
556        .join(name.replace('.', "/"))
557        .with_extension("blade.xr");
558    let source = std::fs::read_to_string(&path).ok()?;
559    larust_view::parse(&source).ok()
560}
561
562/// Unlike every other node kind, `Node::Code` can *grow* the bound set
563/// for whatever follows it in the same node list (its own `let` targets
564/// become real local variables real Rust scoping makes visible to later
565/// siblings) - so this walks `nodes` sequentially over an owned, growing
566/// copy of `bound`, rather than `node_is_safe`'s otherwise-uniform
567/// "check each node against the same fixed set" shape. The clone is
568/// local to this call: a sibling list's own bindings never leak back to
569/// the caller's own `bound`.
570fn tree_is_safe(nodes: &[larust_view::Node], views_root: &Path, bound: &HashSet<String>) -> bool {
571    let mut scope = bound.clone();
572    for node in nodes {
573        if let larust_view::Node::Code(code) = node {
574            match code_block_bound_names(code, &scope) {
575                Some(new_names) => {
576                    scope.extend(new_names);
577                    continue;
578                }
579                None => return false,
580            }
581        }
582        if !node_is_safe(node, views_root, &scope) {
583            return false;
584        }
585    }
586    true
587}
588
589/// Whether a raw expression string - an interpolation's own `expr`, an
590/// `@if`'s `cond`, a `<resource:...>` prop's value, ... - only
591/// references names in `bound`. Real interpolations here are often full
592/// Rust expressions in their own right (real source: `navbar.blade.xr`'s
593/// `{{ if larust_support::truthy::truthy(&(banner)) { "" } else {
594/// "sticky-nav" } }}`), not just a bare identifier, so this parses the
595/// text as a real `syn::Expr` and reuses the same
596/// [`expr_free_names_are_bound`] walker `@code` blocks use - `false` on
597/// any parse failure, same conservative default as everywhere else here.
598fn expr_is_bound(expr: &str, bound: &HashSet<String>) -> bool {
599    syn::parse_str::<syn::Expr>(expr).is_ok_and(|parsed| expr_free_names_are_bound(&parsed, bound))
600}
601
602fn node_is_safe(node: &larust_view::Node, views_root: &Path, bound: &HashSet<String>) -> bool {
603    use larust_view::Node;
604    match node {
605        Node::Text(_) => true,
606        // `tree_is_safe` intercepts `Code` nodes itself (its own `let`
607        // targets need to become visible to *later siblings*, which a
608        // per-node check like this one can't express) - reachable here
609        // only if something calls `node_is_safe` directly on a `Code`
610        // node outside that sequential walk, so this mirrors the same
611        // check without propagating newly-bound names anywhere.
612        Node::Code(code) => code_block_bound_names(code, bound).is_some(),
613        Node::Interpolate { expr, .. } => expr_is_bound(expr, bound),
614        // Same leaf-expression shape as `Interpolate` above, just a
615        // different render-time escaping - the "does this only reference
616        // bound names" question is identical.
617        Node::Js(expr) => expr_is_bound(expr, bound),
618        Node::If {
619            cond,
620            then_branch,
621            else_branch,
622        } => {
623            expr_is_bound(cond, bound)
624                && tree_is_safe(then_branch, views_root, bound)
625                && tree_is_safe(else_branch, views_root, bound)
626        }
627        // Introduces a new pattern-bound variable scoped to `body` - real
628        // source only ever generates a bare identifier (`item`) or a
629        // tuple of them, nested for `with_loop` (`((key, item), loop_)`
630        // - see `scan.rs`'s own keyed-foreach/loop-metadata tests), so
631        // `pat_bound_names` widens `bound` for exactly that vocabulary
632        // and conservatively rejects anything else (destructuring a
633        // struct/slice pattern, `ref`/`mut` bindings with a subpattern).
634        Node::Foreach {
635            binding,
636            iter,
637            body,
638        } => {
639            // `Pat` doesn't implement `Parse` directly (patterns are
640            // ambiguous in general parsing contexts, e.g. leading `|`
641            // for or-patterns) - `parse_single` is `syn`'s own sanctioned
642            // entry point for parsing exactly one pattern in isolation.
643            let Ok(pat) = syn::Pat::parse_single.parse_str(binding) else {
644                return false;
645            };
646            let Some(pat_names) = pat_bound_names(&pat) else {
647                return false;
648            };
649            if !expr_is_bound(iter, bound) {
650                return false;
651            }
652            let mut scope = bound.clone();
653            scope.extend(pat_names);
654            tree_is_safe(body, views_root, &scope)
655        }
656        Node::Extends(_) => true,
657        Node::Section { body, .. } => tree_is_safe(body, views_root, bound),
658        Node::Yield(_) => true,
659        Node::Push { body, .. } => tree_is_safe(body, views_root, bound),
660        Node::Stack(_) => true,
661        // Needs a `csrf_token` binding `render(&self)` never has.
662        Node::Csrf => false,
663        Node::Global { fallback, .. } => fallback
664            .as_deref()
665            .map(|f| expr_is_bound(f, bound))
666            .unwrap_or(true),
667        Node::Globals(_) => true,
668        // Needs a `session` binding `render(&self)` never has.
669        Node::Wire { .. } => false,
670        // Only depends on compile-time flags computed by the *enclosing*
671        // `view!` call's own scan of the whole resolved tree - no
672        // `session` reference at runtime.
673        Node::LarustScripts => true,
674        Node::LoadOnce(body) => tree_is_safe(body, views_root, bound),
675        Node::Resource { name, props, slot } => {
676            if !props.iter().all(|(_, expr)| expr_is_bound(expr, bound)) {
677                return false;
678            }
679            if !tree_is_safe(slot, views_root, bound) {
680                return false;
681            }
682            // The included template's own scope is *only* its own props
683            // (real `let` bindings at codegen time - see
684            // `larust_view::Node::Resource`'s own doc comment) - not the
685            // caller's `bound` at all.
686            let Some(included) = load_template(views_root, name) else {
687                return false;
688            };
689            let included_bound: HashSet<String> =
690                props.iter().map(|(key, _)| key.clone()).collect();
691            tree_is_safe(&included, views_root, &included_bound)
692        }
693        // No `session`/`csrf_token` dependency in its own codegen (just
694        // `channel`'s own `ToString` value plus `body`, rendered inline)
695        // - still conservative about `body`'s own scope, since it's the
696        // caller's, same as everything else here.
697        Node::Live { channel, body } => {
698            expr_is_bound(channel, bound) && tree_is_safe(body, views_root, bound)
699        }
700        // No `session`/`csrf_token` dependency at all - its own entries
701        // are plain string literals, never expressions referencing the
702        // caller's scope (see `larust_view::Node::Vitex`'s own doc
703        // comment).
704        Node::Vitex(_) => true,
705        // Structurally unreachable here: `PersistGlobal` only ever exists
706        // in a *resolved* tree (`resolve::substitute_globals`'s own
707        // output), and everything this module scans is raw, unresolved
708        // `larust_view::parse` output - `xr convert` never calls
709        // `resolve()` at all. `false`, not `true`, as the conservative
710        // fallback if that invariant were ever violated: same reasoning
711        // as `Wire` above - a `persist` global needs a `cookies` binding
712        // `render(&self)` never has.
713        Node::PersistGlobal { .. } => false,
714        // Needs a `user` binding `render(&self)` never has - same
715        // reasoning as `Wire`'s own `session` requirement above (see
716        // `larust_view::Node::Can`'s own doc comment for the full design).
717        Node::Can { .. } | Node::Role { .. } => false,
718        // No `session`/`cookies`/`user` dependency at all - `@spa`'s own
719        // codegen emits only a static sentinel `<div id="...">` wrapper
720        // plus, via `@larustscripts` elsewhere, a static `<script>` tag,
721        // matching `Vitex`'s "safe anywhere" reasoning above, not `Wire`'s.
722        // Still conservative about the wrapped body's own scope, same as
723        // `LoadOnce`/`Live` immediately above.
724        Node::Spa(body) => tree_is_safe(body, views_root, bound),
725        // No `session`/`cookies`/`user` dependency at all - `<Image ...>`'s
726        // own codegen is a pure, synchronous call building a URL (the
727        // actual decode/resize/encode work happens later, at request time,
728        // behind that URL - see `larust_view::Node::Image`'s own doc
729        // comment). Still conservative about each prop's own expression,
730        // same as `Resource`'s props above.
731        Node::Image { props } => props.iter().all(|(_, expr)| expr_is_bound(expr, bound)),
732    }
733}
734
735/// Whether `code` (a `@code ... @endcode` block's raw text) is a
736/// sequence of plain `let [mut] IDENT = EXPR;` statements whose every
737/// `EXPR` only references `bound` - growing as each statement's own
738/// `IDENT` becomes available to the ones after it, matching real Rust
739/// scoping (real source: `head.blade.xr`'s `canonicalUrl` referencing
740/// `appUrl`, bound by an earlier statement in the same block). `@code`
741/// blocks in this codebase are never a hand-written PHP escape hatch -
742/// only ever generated by `blade::expr::translate_expression`'s own
743/// deterministic, bounded vocabulary of Rust shapes (`format!(...)`,
744/// method-call chains, `if`/`else`, indexing, single-parameter
745/// closures, ...) - so this doesn't need to handle arbitrary Rust, only
746/// that vocabulary (see [`expr_free_names_are_bound`]). Any statement
747/// that isn't a plain `let` (a bare expression statement, a `let-else`,
748/// a destructuring pattern, a `let` with no initializer) rejects the
749/// whole block - conservative, matching everything else in this module.
750/// Returns the set of names the block itself binds (its own `let`
751/// targets) on success, so [`tree_is_safe`] can extend the bound set for
752/// whatever follows the block in the same template.
753fn code_block_bound_names(code: &str, bound: &HashSet<String>) -> Option<HashSet<String>> {
754    let Ok(block) = syn::parse_str::<syn::Block>(&format!("{{{code}}}")) else {
755        return None;
756    };
757    let mut scope = bound.clone();
758    let mut own_names = HashSet::new();
759    for stmt in &block.stmts {
760        match stmt {
761            syn::Stmt::Local(local) => {
762                let init = local.init.as_ref()?;
763                if init.diverge.is_some() {
764                    return None; // `let ... else { ... }` - different control flow, not verified
765                }
766                let syn::Pat::Ident(pat_ident) = &local.pat else {
767                    return None; // destructuring - not verified
768                };
769                if pat_ident.by_ref.is_some() || pat_ident.subpat.is_some() {
770                    return None;
771                }
772                if !expr_free_names_are_bound(&init.expr, &scope) {
773                    return None;
774                }
775                let name = pat_ident.ident.to_string();
776                scope.insert(name.clone());
777                own_names.insert(name);
778            }
779            // `x += 1;` - a compound-assignment statement mutating an
780            // *already*-bound variable in place, real source:
781            // `blogcarditem.blade.xr`'s own `let mut x = 0;` (an earlier
782            // `@code` block) incremented once per matched keyword inside
783            // a later `@foreach`. Introduces no new binding (`own_names`
784            // stays untouched) - only legal when the left-hand side is a
785            // single bare identifier already in scope, never a `let mut`
786            // target this same statement is trying to introduce.
787            syn::Stmt::Expr(syn::Expr::Binary(bin), Some(_))
788                if matches!(
789                    bin.op,
790                    syn::BinOp::AddAssign(_)
791                        | syn::BinOp::SubAssign(_)
792                        | syn::BinOp::MulAssign(_)
793                        | syn::BinOp::DivAssign(_)
794                        | syn::BinOp::RemAssign(_)
795                ) =>
796            {
797                let syn::Expr::Path(path) = bin.left.as_ref() else {
798                    return None;
799                };
800                if path.qself.is_some() || path.path.segments.len() != 1 {
801                    return None;
802                }
803                let name = path.path.segments[0].ident.to_string();
804                if !scope.contains(&name) {
805                    return None;
806                }
807                if !expr_free_names_are_bound(&bin.right, &scope) {
808                    return None;
809                }
810            }
811            _ => return None,
812        }
813    }
814    Some(own_names)
815}
816
817/// Names a `@foreach(PATTERN in ITER)` binding pattern introduces -
818/// either a bare identifier (`item`) or a tuple of them, nested to any
819/// depth (`(key, item)`, `((key, item), loop_)` for the `with_loop`
820/// shape `scan.rs`'s own keyed-foreach/loop-metadata tests generate).
821/// `None` for anything outside that vocabulary (struct/slice patterns, a
822/// `ref`/`mut` binding with its own subpattern) - conservative, matching
823/// [`code_block_bound_names`]'s own treatment of destructuring.
824fn pat_bound_names(pat: &syn::Pat) -> Option<HashSet<String>> {
825    match pat {
826        syn::Pat::Ident(pat_ident) if pat_ident.by_ref.is_none() && pat_ident.subpat.is_none() => {
827            Some(HashSet::from([pat_ident.ident.to_string()]))
828        }
829        syn::Pat::Tuple(tuple) => {
830            let mut names = HashSet::new();
831            for elem in &tuple.elems {
832                names.extend(pat_bound_names(elem)?);
833            }
834            Some(names)
835        }
836        _ => None,
837    }
838}
839
840/// Recursively checks that every free (not locally-introduced) variable
841/// reference in `expr` is in `bound` - covering the realistic subset of
842/// Rust shapes `blade::expr::translate_expression` actually emits (see
843/// [`code_block_bound_names`]'s own doc comment for why that's the right
844/// scope, not general Rust). Any expression variant not explicitly
845/// handled here (`match`, `loop`, `struct` literals, `await`, ...)
846/// conservatively fails rather than guessing.
847fn expr_free_names_are_bound(expr: &syn::Expr, bound: &HashSet<String>) -> bool {
848    use syn::Expr;
849    match expr {
850        Expr::Lit(_) => true,
851        // A single-segment path (`title`, `appUrl`) is a plain variable
852        // reference; a multi-segment one (`larust_support::config`,
853        // `String::new`, `crate::config::app::config`) is a function,
854        // type, or module reference, never a variable - real source has
855        // both shapes throughout `head.blade.xr` alone.
856        Expr::Path(path_expr) => {
857            if path_expr.qself.is_none() && path_expr.path.segments.len() == 1 {
858                bound.contains(&path_expr.path.segments[0].ident.to_string())
859            } else {
860                true
861            }
862        }
863        Expr::Call(call) => {
864            expr_free_names_are_bound(&call.func, bound)
865                && call
866                    .args
867                    .iter()
868                    .all(|arg| expr_free_names_are_bound(arg, bound))
869        }
870        Expr::MethodCall(call) => {
871            expr_free_names_are_bound(&call.receiver, bound)
872                && call
873                    .args
874                    .iter()
875                    .all(|arg| expr_free_names_are_bound(arg, bound))
876        }
877        // `loop_.last`/`loop_.first` - the one real shape (`WithLoop`'s
878        // own per-iteration metadata field access) `scan.rs`'s foreach
879        // translation generates. The field name itself is never a
880        // variable reference - only the base needs checking.
881        Expr::Field(field) => expr_free_names_are_bound(&field.base, bound),
882        // `&[...]` array-literal arguments - real source:
883        // `larust_support::vitex::tags(&["resources/css/app.min.css",
884        // "resources/js/app.min.js"])`, `@vite(...)`'s own translated
885        // `@code` block. Every element just needs the same check any
886        // other expression gets; a bare string-literal array (the only
887        // shape this vocabulary's own generators ever produce) is
888        // already covered by the `Lit` arm per element.
889        Expr::Array(array) => array
890            .elems
891            .iter()
892            .all(|elem| expr_free_names_are_bound(elem, bound)),
893        Expr::Binary(bin) => {
894            expr_free_names_are_bound(&bin.left, bound)
895                && expr_free_names_are_bound(&bin.right, bound)
896        }
897        Expr::Unary(un) => expr_free_names_are_bound(&un.expr, bound),
898        Expr::Reference(r) => expr_free_names_are_bound(&r.expr, bound),
899        Expr::Paren(p) => expr_free_names_are_bound(&p.expr, bound),
900        Expr::Group(g) => expr_free_names_are_bound(&g.expr, bound),
901        Expr::Cast(c) => expr_free_names_are_bound(&c.expr, bound),
902        Expr::Index(idx) => {
903            expr_free_names_are_bound(&idx.expr, bound)
904                && expr_free_names_are_bound(&idx.index, bound)
905        }
906        Expr::If(if_expr) => {
907            expr_free_names_are_bound(&if_expr.cond, bound)
908                && block_free_names_are_bound(&if_expr.then_branch, bound)
909                && if_expr
910                    .else_branch
911                    .as_ref()
912                    .is_none_or(|(_, else_expr)| expr_free_names_are_bound(else_expr, bound))
913        }
914        Expr::Block(b) => block_free_names_are_bound(&b.block, bound),
915        // The one macro this vocabulary actually uses - parsed as a
916        // plain comma-separated expression list (its own real grammar:
917        // a format string literal followed by its interpolated args).
918        Expr::Macro(m) => {
919            if !m.mac.path.is_ident("format") {
920                return false;
921            }
922            let Ok(args) = m.mac.parse_body_with(
923                syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
924            ) else {
925                return false;
926            };
927            args.iter().all(|arg| expr_free_names_are_bound(arg, bound))
928        }
929        // `blade::expr` only ever emits closures for `.map(...)`/
930        // `.unwrap_or_else(...)`-style single-argument use - a bare `||
931        // ...` or one plain identifier parameter, never destructuring or
932        // multiple parameters.
933        Expr::Closure(closure) => {
934            if closure.inputs.len() > 1 {
935                return false;
936            }
937            let mut scope = bound.clone();
938            if let Some(input) = closure.inputs.first() {
939                let syn::Pat::Ident(pat_ident) = input else {
940                    return false;
941                };
942                scope.insert(pat_ident.ident.to_string());
943            }
944            expr_free_names_are_bound(&closure.body, &scope)
945        }
946        _ => false,
947    }
948}
949
950/// A block used as an `if`/`else` branch in the real generated shapes
951/// this vocabulary produces is always a single trailing expression (no
952/// nested `let`s observed in practice) - conservatively rejects anything
953/// else rather than recursing into a second, nested `let`-sequence
954/// scope.
955fn block_free_names_are_bound(block: &syn::Block, bound: &HashSet<String>) -> bool {
956    block.stmts.iter().all(|stmt| match stmt {
957        syn::Stmt::Expr(expr, _) => expr_free_names_are_bound(expr, bound),
958        _ => false,
959    })
960}
961
962#[cfg(test)]
963mod tests {
964    use super::*;
965
966    #[test]
967    fn extracts_public_properties_with_literal_defaults() {
968        let source = "<?php\nclass Home extends Component {\n    public $title = \"Hello\";\n    public $banner = true;\n    public $count = 5;\n}\n";
969        let result = convert(source, "Home").unwrap();
970        assert_eq!(result.properties.len(), 3);
971        let title = result
972            .properties
973            .iter()
974            .find(|p| p.name == "title")
975            .unwrap();
976        assert_eq!(title.rust_type, "String");
977        assert_eq!(title.default_literal, "\"Hello\".to_string()");
978        let banner = result
979            .properties
980            .iter()
981            .find(|p| p.name == "banner")
982            .unwrap();
983        assert_eq!(banner.rust_type, "bool");
984        assert_eq!(banner.default_literal, "true");
985        let count = result
986            .properties
987            .iter()
988            .find(|p| p.name == "count")
989            .unwrap();
990        assert_eq!(count.rust_type, "i64");
991        assert_eq!(count.default_literal, "5");
992        assert!(result.unsupported_properties.is_empty());
993    }
994
995    #[test]
996    fn an_empty_double_quoted_string_default_is_a_supported_literal() {
997        // Real source: `Home::$canonical = "";` - a double-quoted empty
998        // string parses with zero named children (no `string_content` to
999        // hold, nothing to interpolate), a distinct shape from a
1000        // non-empty one-child `encapsed_string`.
1001        let source = r#"<?php
1002class Home extends Component {
1003    public $canonical = "";
1004}
1005"#;
1006        let result = convert(source, "Home").unwrap();
1007        assert!(result.unsupported_properties.is_empty());
1008        assert_eq!(result.properties.len(), 1);
1009        assert_eq!(result.properties[0].rust_type, "String");
1010        assert_eq!(result.properties[0].default_literal, "\"\".to_string()");
1011    }
1012
1013    #[test]
1014    fn protected_and_private_properties_are_never_exposed() {
1015        let source = "<?php\nclass Home extends Component {\n    protected $guard = 'web';\n    private $secret = 'x';\n    public $title = \"Hello\";\n}\n";
1016        let result = convert(source, "Home").unwrap();
1017        assert_eq!(result.properties.len(), 1);
1018        assert_eq!(result.properties[0].name, "title");
1019    }
1020
1021    #[test]
1022    fn an_interpolated_double_quoted_string_is_flagged_not_guessed() {
1023        let source = r#"<?php
1024class Home extends Component {
1025    public $greeting = "Hello {$name}";
1026}
1027"#;
1028        let result = convert(source, "Home").unwrap();
1029        assert!(result.properties.is_empty());
1030        assert_eq!(result.unsupported_properties.len(), 1);
1031        assert!(result.unsupported_properties[0].contains("greeting"));
1032    }
1033
1034    #[test]
1035    fn a_property_with_no_default_is_flagged_not_guessed() {
1036        let source = "<?php\nclass Home extends Component {\n    public $current;\n}\n";
1037        let result = convert(source, "Home").unwrap();
1038        assert!(result.properties.is_empty());
1039        assert_eq!(result.unsupported_properties.len(), 1);
1040        assert!(result.unsupported_properties[0].contains("current"));
1041    }
1042
1043    #[test]
1044    fn a_non_literal_default_is_flagged_not_guessed() {
1045        let source = "<?php\nclass Home extends Component {\n    public $items = [1, 2, 3];\n}\n";
1046        let result = convert(source, "Home").unwrap();
1047        assert!(result.properties.is_empty());
1048        assert_eq!(result.unsupported_properties.len(), 1);
1049        assert!(result.unsupported_properties[0].contains("items"));
1050    }
1051
1052    #[test]
1053    fn extracts_the_view_name_from_a_plain_render_return() {
1054        let source = "<?php\nclass Home extends Component {\n    public function render()\n    {\n        return view('livewire.pages.index');\n    }\n}\n";
1055        let result = convert(source, "Home").unwrap();
1056        assert_eq!(result.view_name.as_deref(), Some("livewire.pages.index"));
1057        assert!(result.layout_name.is_none());
1058    }
1059
1060    #[test]
1061    fn extracts_the_view_name_through_a_chained_layout_call() {
1062        // Real source: `App\Livewire\Home::render()`.
1063        let source = "<?php\nclass Home extends Component {\n    public function render()\n    {\n        return view('livewire.pages.index')->layout('components.layouts.app', ['title' => $this->title]);\n    }\n}\n";
1064        let result = convert(source, "Home").unwrap();
1065        assert_eq!(result.view_name.as_deref(), Some("livewire.pages.index"));
1066        assert_eq!(
1067            result.layout_name.as_deref(),
1068            Some("components.layouts.app")
1069        );
1070    }
1071
1072    #[test]
1073    fn no_render_method_means_no_view_name() {
1074        let source = "<?php\nclass Home extends Component {\n}\n";
1075        let result = convert(source, "Home").unwrap();
1076        assert!(result.view_name.is_none());
1077    }
1078
1079    #[test]
1080    fn rejects_when_the_class_is_not_found_in_the_file() {
1081        let source = "<?php\nclass Other extends Component {}\n";
1082        assert!(convert(source, "Home").is_err());
1083    }
1084
1085    fn write_view(dir: &std::path::Path, dotted_name: &str, content: &str) {
1086        let path = dir.join(dotted_name.replace('.', "/") + ".blade.xr");
1087        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1088        std::fs::write(path, content).unwrap();
1089    }
1090
1091    #[test]
1092    fn a_template_with_only_bound_interpolations_is_safe() {
1093        let dir = tempfile::tempdir().unwrap();
1094        write_view(
1095            dir.path(),
1096            "pages.index",
1097            "<h1>{{ title }}</h1><p>{{ query }}</p>",
1098        );
1099        let bound = HashSet::from(["title".to_string(), "query".to_string()]);
1100        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1101    }
1102
1103    #[test]
1104    fn layout_globals_for_finds_only_the_names_actually_referenced() {
1105        // Real source: `components/layouts/app.blade.xr` references both
1106        // known globals (`theme`, `csrf_token`) alongside `slot` - only
1107        // the two known-global names should come back, not `slot` itself
1108        // (already in `bound`, not a "global" this mechanism resolves).
1109        let dir = tempfile::tempdir().unwrap();
1110        write_view(
1111            dir.path(),
1112            "layouts.app",
1113            r#"<html class="{{ theme }}"><meta name="csrf-token" content="{{ csrf_token }}"><body>{{ slot }}</body></html>"#,
1114        );
1115        let bound = HashSet::from(["slot".to_string()]);
1116        let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
1117        let names: HashSet<&str> = globals.iter().map(|g| g.name).collect();
1118        assert_eq!(names, HashSet::from(["theme", "csrf_token"]));
1119    }
1120
1121    #[test]
1122    fn layout_globals_for_finds_nothing_when_the_layout_uses_neither_known_global() {
1123        let dir = tempfile::tempdir().unwrap();
1124        write_view(dir.path(), "layouts.app", "<body>{{ slot }}</body>");
1125        let bound = HashSet::from(["slot".to_string()]);
1126        let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
1127        assert!(globals.is_empty());
1128    }
1129
1130    #[test]
1131    fn layout_globals_for_is_none_when_an_unrelated_name_stays_unbound() {
1132        let dir = tempfile::tempdir().unwrap();
1133        write_view(
1134            dir.path(),
1135            "layouts.app",
1136            "<body>{{ slot }}{{ theme }}{{ subtitle }}</body>",
1137        );
1138        let bound = HashSet::from(["slot".to_string()]);
1139        assert!(layout_globals_for(dir.path(), "layouts.app", &bound).is_none());
1140    }
1141
1142    #[test]
1143    fn referenced_names_finds_only_the_candidates_the_template_actually_mentions() {
1144        // Real source shape: `components/layouts/app.blade.xr` reads
1145        // `theme`/`slot` but never `title`/`url`/`canonical` even though
1146        // a wired `Home` component's own struct has all of them.
1147        let dir = tempfile::tempdir().unwrap();
1148        write_view(
1149            dir.path(),
1150            "layouts.app",
1151            r#"<html class="{{ theme }}"><body>{{ slot }}</body></html>"#,
1152        );
1153        let candidates: HashSet<String> = ["theme", "slot", "title", "url", "canonical"]
1154            .into_iter()
1155            .map(String::from)
1156            .collect();
1157        let found =
1158            referenced_names(dir.path(), "layouts.app", &HashSet::new(), &candidates).unwrap();
1159        assert_eq!(
1160            found,
1161            HashSet::from(["theme".to_string(), "slot".to_string()])
1162        );
1163    }
1164
1165    #[test]
1166    fn a_bare_word_that_only_appears_as_a_substring_of_another_identifier_is_not_referenced() {
1167        // Real source: `components/layouts/app.blade.xr`'s `<meta
1168        // name="apple-mobile-web-app-title">` contains the literal text
1169        // `title`, hyphen-bounded - a naive text scan would treat that as
1170        // "referenced"; the real tree-walking removal-probe correctly
1171        // doesn't, since the template never actually interpolates a
1172        // `title` variable anywhere.
1173        let dir = tempfile::tempdir().unwrap();
1174        write_view(
1175            dir.path(),
1176            "layouts.app",
1177            "<meta name=\"mytheme-title\"><body>{{ slot }}</body>",
1178        );
1179        let bound = HashSet::from(["slot".to_string()]);
1180        let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
1181        assert!(globals.is_empty());
1182    }
1183
1184    #[test]
1185    fn an_unbound_interpolation_is_unsafe() {
1186        let dir = tempfile::tempdir().unwrap();
1187        write_view(dir.path(), "pages.index", "<h1>{{ subtitle }}</h1>");
1188        let bound = HashSet::from(["title".to_string()]);
1189        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1190    }
1191
1192    #[test]
1193    fn a_top_level_wire_tag_is_unsafe() {
1194        let dir = tempfile::tempdir().unwrap();
1195        write_view(
1196            dir.path(),
1197            "pages.index",
1198            "<wire:search-box :query='query' />",
1199        );
1200        let bound = HashSet::from(["query".to_string()]);
1201        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1202    }
1203
1204    #[test]
1205    fn a_resource_include_with_no_wire_or_csrf_inside_is_safe() {
1206        let dir = tempfile::tempdir().unwrap();
1207        write_view(
1208            dir.path(),
1209            "pages.index",
1210            "<resource:components.head :title='title'></resource:components.head>",
1211        );
1212        write_view(dir.path(), "components.head", "<title>{{ title }}</title>");
1213        let bound = HashSet::from(["title".to_string()]);
1214        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1215    }
1216
1217    #[test]
1218    fn a_resource_include_that_transitively_uses_wire_is_unsafe() {
1219        // The exact real-world shape this whole check exists for: a
1220        // top-level page with no `@wire`/`<wire:>` of its own, but a
1221        // `<resource:...>`-included shared component (e.g. a navbar)
1222        // that mounts one - `view!`'s own `contains_wire` scan wouldn't
1223        // catch this either (it only looks at a resource's own `slot`),
1224        // so without this check the generated `view!(...)` call would
1225        // fail with "cannot find value `session`" instead of falling
1226        // back to the placeholder.
1227        let dir = tempfile::tempdir().unwrap();
1228        write_view(
1229            dir.path(),
1230            "pages.index",
1231            "<resource:components.navbar></resource:components.navbar>",
1232        );
1233        write_view(dir.path(), "components.navbar", "<wire:search-box />");
1234        let bound: HashSet<String> = HashSet::new();
1235        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1236    }
1237
1238    #[test]
1239    fn a_foreach_over_a_bound_iterable_referencing_its_own_binding_is_safe() {
1240        // Real source: `package.blade.xr`'s `@foreach(item in itemlist)`
1241        // (a `@code` block earlier in the same template splits a bound
1242        // `items` prop into `itemlist`), body referencing `item`.
1243        let dir = tempfile::tempdir().unwrap();
1244        write_view(
1245            dir.path(),
1246            "pages.index",
1247            "@foreach(item in itemlist)<p>{{ item }}</p>@endforeach",
1248        );
1249        let bound = HashSet::from(["itemlist".to_string()]);
1250        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1251    }
1252
1253    #[test]
1254    fn a_foreach_over_an_unbound_iterable_is_unsafe() {
1255        let dir = tempfile::tempdir().unwrap();
1256        write_view(
1257            dir.path(),
1258            "pages.index",
1259            "@foreach(item in itemlist)<p>{{ item }}</p>@endforeach",
1260        );
1261        let bound: HashSet<String> = HashSet::new();
1262        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1263    }
1264
1265    #[test]
1266    fn a_foreach_body_referencing_a_name_outside_the_binding_and_outer_scope_is_unsafe() {
1267        let dir = tempfile::tempdir().unwrap();
1268        write_view(
1269            dir.path(),
1270            "pages.index",
1271            "@foreach(item in itemlist)<p>{{ subtitle }}</p>@endforeach",
1272        );
1273        let bound = HashSet::from(["itemlist".to_string()]);
1274        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1275    }
1276
1277    #[test]
1278    fn a_keyed_with_loop_foreach_binds_both_tuple_names_and_the_loop_variable() {
1279        // Real source: `blog.blade.xr`'s translated
1280        // `@foreach($items as $key => $item)` with a `$loop->last`
1281        // reference becomes `@foreach(((key, item), loop_) in
1282        // larust_support::WithLoop::with_loop((items).iter().enumerate()))`
1283        // - a nested tuple pattern, body referencing `loop_.last` (a
1284        // field access, not a bound identifier itself).
1285        let dir = tempfile::tempdir().unwrap();
1286        write_view(
1287            dir.path(),
1288            "pages.index",
1289            "@foreach(((key, item), loop_) in larust_support::WithLoop::with_loop((items).iter().enumerate()))\
1290             {{ if larust_support::truthy::truthy(&(!(loop_.last))) { (\",\").to_string() } else { (\"\").to_string() } }}\
1291             @endforeach",
1292        );
1293        let bound = HashSet::from(["items".to_string()]);
1294        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1295    }
1296
1297    #[test]
1298    fn a_resource_props_own_expression_must_also_be_bound() {
1299        let dir = tempfile::tempdir().unwrap();
1300        write_view(
1301            dir.path(),
1302            "pages.index",
1303            "<resource:components.head :title='unbound_name'></resource:components.head>",
1304        );
1305        write_view(dir.path(), "components.head", "<title>{{ title }}</title>");
1306        let bound: HashSet<String> = HashSet::new();
1307        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1308    }
1309
1310    #[test]
1311    fn a_missing_template_is_unsafe() {
1312        let dir = tempfile::tempdir().unwrap();
1313        let bound: HashSet<String> = HashSet::new();
1314        assert!(!view_is_safe_for_scope(dir.path(), "pages.missing", &bound));
1315    }
1316
1317    #[test]
1318    fn a_csrf_directive_is_unsafe() {
1319        let dir = tempfile::tempdir().unwrap();
1320        write_view(dir.path(), "pages.form", "<form>@csrf</form>");
1321        let bound: HashSet<String> = HashSet::new();
1322        assert!(!view_is_safe_for_scope(dir.path(), "pages.form", &bound));
1323    }
1324
1325    #[test]
1326    fn a_can_directive_is_unsafe() {
1327        // `@can(...)`/`@role(...)` need a `user` binding `render(&self)`
1328        // never has - same reasoning as `@wire(...)`'s own `session`
1329        // requirement above.
1330        let dir = tempfile::tempdir().unwrap();
1331        write_view(
1332            dir.path(),
1333            "pages.editable",
1334            "@can(Permission::EditPosts)yes@endcan",
1335        );
1336        let bound: HashSet<String> = HashSet::new();
1337        assert!(!view_is_safe_for_scope(
1338            dir.path(),
1339            "pages.editable",
1340            &bound
1341        ));
1342    }
1343
1344    #[test]
1345    fn a_role_directive_is_unsafe() {
1346        let dir = tempfile::tempdir().unwrap();
1347        write_view(dir.path(), "pages.admin", "@role(Role::Admin)yes@endrole");
1348        let bound: HashSet<String> = HashSet::new();
1349        assert!(!view_is_safe_for_scope(dir.path(), "pages.admin", &bound));
1350    }
1351
1352    #[test]
1353    fn a_spa_directive_with_a_safe_body_is_safe() {
1354        // Unlike `@wire`/`@can`/`@role`, `@spa` needs no `session`/`user`
1355        // binding at all - it emits only a static sentinel `<div>` wrapper,
1356        // matching `@vitex`'s own "safe anywhere" reasoning, so its body is
1357        // recursively checked rather than blanket-rejected.
1358        let dir = tempfile::tempdir().unwrap();
1359        write_view(dir.path(), "pages.home", "@spa <p>hi</p> @endspa");
1360        let bound: HashSet<String> = HashSet::new();
1361        assert!(view_is_safe_for_scope(dir.path(), "pages.home", &bound));
1362    }
1363
1364    #[test]
1365    fn a_spa_directive_wrapping_an_unsafe_node_is_still_unsafe() {
1366        let dir = tempfile::tempdir().unwrap();
1367        write_view(dir.path(), "pages.home", "@spa @csrf @endspa");
1368        let bound: HashSet<String> = HashSet::new();
1369        assert!(!view_is_safe_for_scope(dir.path(), "pages.home", &bound));
1370    }
1371
1372    #[test]
1373    fn a_code_block_with_only_literal_lets_is_safe() {
1374        // Real source: `errors/404.blade.xr`.
1375        let dir = tempfile::tempdir().unwrap();
1376        write_view(
1377            dir.path(),
1378            "errors.404",
1379            "@code let mut title = \"Page Not Found\"; let mut noindex = true; @endcode<h1>{{ title }}</h1>",
1380        );
1381        let bound: HashSet<String> = HashSet::new();
1382        assert!(view_is_safe_for_scope(dir.path(), "errors.404", &bound));
1383    }
1384
1385    #[test]
1386    fn a_code_blocks_own_bindings_are_visible_to_later_siblings() {
1387        let dir = tempfile::tempdir().unwrap();
1388        write_view(
1389            dir.path(),
1390            "pages.index",
1391            "@code let mut greeting = \"hi\"; @endcode<p>{{ greeting }}</p>",
1392        );
1393        let bound: HashSet<String> = HashSet::new();
1394        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1395    }
1396
1397    #[test]
1398    fn a_code_block_referencing_an_unbound_name_is_unsafe() {
1399        let dir = tempfile::tempdir().unwrap();
1400        write_view(
1401            dir.path(),
1402            "pages.index",
1403            "@code let mut greeting = format!(\"hi {}\", session); @endcode",
1404        );
1405        let bound: HashSet<String> = HashSet::new();
1406        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1407    }
1408
1409    #[test]
1410    fn a_code_block_incrementing_an_already_bound_counter_is_safe() {
1411        // Real source: `blogcarditem.blade.xr` - `let mut x = 0;` in one
1412        // `@code` block, `x += 1;` in a later one (inside a `@foreach`,
1413        // counting matched keywords). Introduces no new binding; only
1414        // legal because `x` is already bound by the time it mutates it.
1415        let dir = tempfile::tempdir().unwrap();
1416        write_view(
1417            dir.path(),
1418            "pages.index",
1419            "@code let mut x = 0; @endcode@code x += 1; @endcode{{ x }}",
1420        );
1421        let bound: HashSet<String> = HashSet::new();
1422        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1423    }
1424
1425    #[test]
1426    fn a_compound_assignment_to_an_unbound_name_is_unsafe() {
1427        let dir = tempfile::tempdir().unwrap();
1428        write_view(dir.path(), "pages.index", "@code x += 1; @endcode");
1429        let bound: HashSet<String> = HashSet::new();
1430        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1431    }
1432
1433    #[test]
1434    fn a_compound_assignment_referencing_an_unbound_name_on_the_right_is_unsafe() {
1435        let dir = tempfile::tempdir().unwrap();
1436        write_view(
1437            dir.path(),
1438            "pages.index",
1439            "@code let mut x = 0; x += unbound_step; @endcode",
1440        );
1441        let bound: HashSet<String> = HashSet::new();
1442        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1443    }
1444
1445    #[test]
1446    fn a_code_block_matching_the_real_head_component_shape_is_safe() {
1447        // Real source: `livewire/components/head.blade.xr` - chained
1448        // `if`/`else`, multi-segment function paths (`larust_support::
1449        // config`, not a variable), `format!`, method calls, and a later
1450        // statement referencing an earlier one's own binding.
1451        let dir = tempfile::tempdir().unwrap();
1452        write_view(
1453            dir.path(),
1454            "components.head",
1455            r#"@code let mut appUrl = larust_support::config("app.url").unwrap_or_default(); let mut canonicalUrl = if larust_support::truthy::truthy(&((canonical).starts_with("http://") || (canonical).starts_with("https://"))) { canonical } else { format!("{}{}", appUrl, canonical) }; @endcode<link href="{{ canonicalUrl }}" />"#,
1456        );
1457        let bound = HashSet::from(["canonical".to_string()]);
1458        assert!(view_is_safe_for_scope(
1459            dir.path(),
1460            "components.head",
1461            &bound
1462        ));
1463    }
1464
1465    #[test]
1466    fn a_code_block_calling_vitex_tags_with_an_array_literal_is_safe() {
1467        // Real source: `components/layouts/app.blade.xr`'s translated
1468        // `@vite(['resources/css/app.min.css', 'resources/js/app.min.js'])`
1469        // - an array-literal argument (`&["...", "..."]`), which a
1470        // missing `Expr::Array` arm previously made this whole `@code`
1471        // block (and therefore the entire layout) unsafe, silently
1472        // dropping every page's layout wrap back to content-only wiring.
1473        let dir = tempfile::tempdir().unwrap();
1474        write_view(
1475            dir.path(),
1476            "layouts.app",
1477            r#"@code let __vitex_tags = larust_support::vitex::tags(&["resources/css/app.min.css", "resources/js/app.min.js"]); @endcode{!! __vitex_tags !!}"#,
1478        );
1479        assert!(view_is_safe_for_scope(
1480            dir.path(),
1481            "layouts.app",
1482            &HashSet::new()
1483        ));
1484    }
1485
1486    #[test]
1487    fn a_code_block_with_a_bound_single_param_closure_is_safe() {
1488        // Real source: `livewire/elements/cardwide.blade.xr`'s
1489        // `.map(|s| s.to_string())` chain.
1490        let dir = tempfile::tempdir().unwrap();
1491        write_view(
1492            dir.path(),
1493            "pages.index",
1494            r#"@code let mut keys = (keywords).split(",").map(|s| s.to_string()).collect::<Vec<String>>(); @endcode"#,
1495        );
1496        let bound = HashSet::from(["keywords".to_string()]);
1497        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1498    }
1499
1500    #[test]
1501    fn a_code_block_with_a_bare_expression_statement_is_unsafe() {
1502        // A bare call/method-invocation statement - neither a `let`
1503        // declaration nor a compound-assignment to an already-bound
1504        // name (see `a_code_block_incrementing_an_already_bound_counter_
1505        // is_safe`, which covers the one bare-statement shape this
1506        // vocabulary *does* accept: `x += 1;`) - still conservatively
1507        // rejected.
1508        let dir = tempfile::tempdir().unwrap();
1509        write_view(
1510            dir.path(),
1511            "pages.index",
1512            "@code let mut x = 0; x.clear(); @endcode",
1513        );
1514        let bound: HashSet<String> = HashSet::new();
1515        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1516    }
1517
1518    #[test]
1519    fn a_code_block_destructuring_a_pattern_is_unsafe() {
1520        let dir = tempfile::tempdir().unwrap();
1521        write_view(
1522            dir.path(),
1523            "pages.index",
1524            "@code let (a, b) = (1, 2); @endcode",
1525        );
1526        let bound: HashSet<String> = HashSet::new();
1527        assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1528    }
1529
1530    #[test]
1531    fn a_code_block_indexing_a_bound_value_is_safe() {
1532        // Real source: `livewire/pages/blogpage.blade.xr`'s
1533        // `data["bodytext"]`.
1534        let dir = tempfile::tempdir().unwrap();
1535        write_view(
1536            dir.path(),
1537            "pages.index",
1538            r#"@code let mut body = (data["bodytext"]).replace("a", "b"); @endcode"#,
1539        );
1540        let bound = HashSet::from(["data".to_string()]);
1541        assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1542    }
1543
1544    #[test]
1545    fn an_interpolation_containing_a_full_if_else_expression_is_safe_when_bound() {
1546        // Real source: `livewire/components/navbar.blade.xr`'s `{{ if
1547        // larust_support::truthy::truthy(&(banner)) { "" } else {
1548        // "sticky-nav" } }}` - not a bare identifier, a whole `if`/`else`
1549        // Rust expression. The old leading-identifier text scan would
1550        // extract `"if"` as "the identifier" and reject this outright;
1551        // the real `syn::Expr` parse correctly sees only `banner` as a
1552        // free name.
1553        let dir = tempfile::tempdir().unwrap();
1554        write_view(
1555            dir.path(),
1556            "components.navbar",
1557            r#"<nav class="{{ if larust_support::truthy::truthy(&(banner)) { "" } else { "sticky-nav" } }}"></nav>"#,
1558        );
1559        let bound = HashSet::from(["banner".to_string()]);
1560        assert!(view_is_safe_for_scope(
1561            dir.path(),
1562            "components.navbar",
1563            &bound
1564        ));
1565    }
1566
1567    #[test]
1568    fn an_interpolation_with_a_method_chain_on_a_bound_value_is_safe() {
1569        // Real source: `navbar.blade.xr`'s `(current).contains(&("home"))`.
1570        let dir = tempfile::tempdir().unwrap();
1571        write_view(
1572            dir.path(),
1573            "components.navbar",
1574            r#"<a class="{{ if (current).contains(&("home")) { "active" } else { "" } }}">Home</a>"#,
1575        );
1576        let bound = HashSet::from(["current".to_string()]);
1577        assert!(view_is_safe_for_scope(
1578            dir.path(),
1579            "components.navbar",
1580            &bound
1581        ));
1582    }
1583
1584    #[test]
1585    fn head_pushes_finds_a_push_in_the_content_template_itself() {
1586        let dir = tempfile::tempdir().unwrap();
1587        write_view(
1588            dir.path(),
1589            "pages.contact",
1590            "@push('head')<link rel=\"stylesheet\" href=\"/css/text.min.css\">@endpush<div>hi</div>",
1591        );
1592        let pushes = head_pushes(dir.path(), "pages.contact");
1593        assert_eq!(pushes.len(), 1);
1594        assert_eq!(
1595            pushes[0].text.as_deref(),
1596            Some("<link rel=\"stylesheet\" href=\"/css/text.min.css\">")
1597        );
1598    }
1599
1600    #[test]
1601    fn head_pushes_reaches_through_a_nested_resource_tag() {
1602        // Real bug this fixes: `livewire.elements.sunrise`'s own
1603        // `sunrise.min.css` link, pushed from *inside* the resource file
1604        // itself rather than at its `<resource:...>` call site.
1605        let dir = tempfile::tempdir().unwrap();
1606        write_view(
1607            dir.path(),
1608            "elements.sunrise",
1609            "@push('head')<link rel=\"stylesheet\" href=\"/css/sunrise.min.css\">@endpush<div>sun</div>",
1610        );
1611        write_view(
1612            dir.path(),
1613            "pages.index",
1614            "<resource:elements.sunrise></resource:elements.sunrise>",
1615        );
1616        let pushes = head_pushes(dir.path(), "pages.index");
1617        assert_eq!(pushes.len(), 1);
1618        assert_eq!(
1619            pushes[0].text.as_deref(),
1620            Some("<link rel=\"stylesheet\" href=\"/css/sunrise.min.css\">")
1621        );
1622    }
1623
1624    #[test]
1625    fn head_pushes_with_dynamic_content_are_reported_as_unhoistable() {
1626        let dir = tempfile::tempdir().unwrap();
1627        write_view(
1628            dir.path(),
1629            "pages.contact",
1630            "@push('head')<title>{{ title }}</title>@endpush",
1631        );
1632        let pushes = head_pushes(dir.path(), "pages.contact");
1633        assert_eq!(pushes.len(), 1);
1634        assert!(pushes[0].text.is_none());
1635    }
1636
1637    #[test]
1638    fn head_pushes_does_not_duplicate_a_resource_included_more_than_once() {
1639        let dir = tempfile::tempdir().unwrap();
1640        write_view(
1641            dir.path(),
1642            "elements.questions",
1643            "@push('head')<link rel=\"stylesheet\" href=\"/css/questions.min.css\">@endpush",
1644        );
1645        write_view(
1646            dir.path(),
1647            "pages.contact",
1648            "<resource:elements.questions></resource:elements.questions>\
1649             <resource:elements.questions></resource:elements.questions>",
1650        );
1651        let pushes = head_pushes(dir.path(), "pages.contact");
1652        assert_eq!(pushes.len(), 1);
1653    }
1654
1655    #[test]
1656    fn head_pushes_for_a_missing_template_is_empty_not_an_error() {
1657        let dir = tempfile::tempdir().unwrap();
1658        assert!(head_pushes(dir.path(), "pages.nonexistent").is_empty());
1659    }
1660}