Skip to main content

php_ast/owned/
visitor.rs

1//! Visitor infrastructure for owned (lifetime-free) PHP AST traversal.
2//!
3//! This module mirrors [`crate::visitor`] but operates on the owned AST types
4//! in [`crate::owned`] rather than the arena-allocated types. Use it after
5//! calling `php_rs_parser::parse()` — no arena or lifetime management needed.
6//!
7//! # Example
8//!
9//! ```
10//! use php_ast::owned::visitor::{OwnedVisitor, walk_owned_expr};
11//! use php_ast::owned::{Expr, ExprKind};
12//! use std::ops::ControlFlow;
13//!
14//! struct VarCounter { count: usize }
15//!
16//! impl OwnedVisitor for VarCounter {
17//!     type Break = ();
18//!     fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
19//!         if matches!(&expr.kind, ExprKind::Variable(_)) {
20//!             self.count += 1;
21//!         }
22//!         walk_owned_expr(self, expr)
23//!     }
24//! }
25//! ```
26
27use std::ops::ControlFlow;
28
29use super::*;
30
31// =============================================================================
32// OwnedVisitor trait
33// =============================================================================
34
35/// Visitor trait for immutable traversal of owned (lifetime-free) AST nodes.
36///
37/// All methods return `ControlFlow<Self::Break>`:
38/// - `ControlFlow::Continue(())` — keep walking.
39/// - `ControlFlow::Break(value)` — stop the entire traversal immediately; `value` is returned
40///   by the call that started the walk. Use `type Break = ();` when there is nothing to return.
41///
42/// Default implementations recurse into child nodes, so implementors only need
43/// to override the node types they care about.
44///
45/// To **skip** a subtree, override the method and return `Continue(())`
46/// without calling the corresponding `walk_owned_*` function.
47pub trait OwnedVisitor {
48    /// Value carried by [`ControlFlow::Break`] when a visit stops the walk early; use `()` to
49    /// stop without a result.
50    type Break;
51
52    /// Visits a program node.
53    fn visit_program(&mut self, program: &Program) -> ControlFlow<Self::Break> {
54        walk_owned_program(self, program)
55    }
56
57    /// Visits a statement node.
58    fn visit_stmt(&mut self, stmt: &Stmt) -> ControlFlow<Self::Break> {
59        walk_owned_stmt(self, stmt)
60    }
61
62    /// Visits a block node.
63    fn visit_block(&mut self, block: &Block) -> ControlFlow<Self::Break> {
64        walk_owned_block(self, block)
65    }
66
67    /// Visits an expression node.
68    fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
69        walk_owned_expr(self, expr)
70    }
71
72    /// Visits a param node.
73    fn visit_param(&mut self, param: &Param) -> ControlFlow<Self::Break> {
74        walk_owned_param(self, param)
75    }
76
77    /// Visits an arg node.
78    fn visit_arg(&mut self, arg: &Arg) -> ControlFlow<Self::Break> {
79        walk_owned_arg(self, arg)
80    }
81
82    /// Visits a class member node.
83    fn visit_class_member(&mut self, member: &ClassMember) -> ControlFlow<Self::Break> {
84        walk_owned_class_member(self, member)
85    }
86
87    /// Visits an enum member node.
88    fn visit_enum_member(&mut self, member: &EnumMember) -> ControlFlow<Self::Break> {
89        walk_owned_enum_member(self, member)
90    }
91
92    /// Visits a property hook node.
93    fn visit_property_hook(&mut self, hook: &PropertyHook) -> ControlFlow<Self::Break> {
94        walk_owned_property_hook(self, hook)
95    }
96
97    /// Visits a type hint node.
98    fn visit_type_hint(&mut self, type_hint: &TypeHint) -> ControlFlow<Self::Break> {
99        walk_owned_type_hint(self, type_hint)
100    }
101
102    /// Visits an attribute node.
103    fn visit_attribute(&mut self, attribute: &Attribute) -> ControlFlow<Self::Break> {
104        walk_owned_attribute(self, attribute)
105    }
106
107    /// Visits a catch clause node.
108    fn visit_catch_clause(&mut self, catch: &CatchClause) -> ControlFlow<Self::Break> {
109        walk_owned_catch_clause(self, catch)
110    }
111
112    /// Visits a match arm node.
113    fn visit_match_arm(&mut self, arm: &MatchArm) -> ControlFlow<Self::Break> {
114        walk_owned_match_arm(self, arm)
115    }
116
117    /// Visits a closure use var node.
118    fn visit_closure_use_var(&mut self, _var: &ClosureUseVar) -> ControlFlow<Self::Break> {
119        ControlFlow::Continue(())
120    }
121
122    /// Visits a trait use node.
123    fn visit_trait_use(&mut self, trait_use: &TraitUseDecl) -> ControlFlow<Self::Break> {
124        walk_owned_trait_use(self, trait_use)
125    }
126
127    /// Visits a trait adaptation node.
128    fn visit_trait_adaptation(&mut self, adaptation: &TraitAdaptation) -> ControlFlow<Self::Break> {
129        walk_owned_trait_adaptation(self, adaptation)
130    }
131
132    /// Visits a name node.
133    fn visit_name(&mut self, _name: &Name) -> ControlFlow<Self::Break> {
134        ControlFlow::Continue(())
135    }
136
137    /// Visits a comment node.
138    fn visit_comment(&mut self, _comment: &Comment) -> ControlFlow<Self::Break> {
139        ControlFlow::Continue(())
140    }
141}
142
143// =============================================================================
144// Walk functions
145// =============================================================================
146
147/// Calls [`OwnedVisitor::visit_name`] on `name`.
148///
149/// `Name` is a leaf node — there are no child nodes to recurse into.
150/// This function exists for symmetry with [`walk_owned_expr`] and friends so
151/// that an override of [`OwnedVisitor::visit_name`] can call the default
152/// behaviour by name.
153pub fn walk_owned_name<V: OwnedVisitor + ?Sized>(
154    visitor: &mut V,
155    name: &Name,
156) -> ControlFlow<V::Break> {
157    visitor.visit_name(name)
158}
159
160/// Calls [`OwnedVisitor::visit_comment`] for each comment in `comments`.
161pub fn walk_owned_comments<V: OwnedVisitor + ?Sized>(
162    visitor: &mut V,
163    comments: &[Comment],
164) -> ControlFlow<V::Break> {
165    for comment in comments {
166        visitor.visit_comment(comment)?;
167    }
168    ControlFlow::Continue(())
169}
170
171/// Visits every top-level statement in `program`.
172pub fn walk_owned_program<V: OwnedVisitor + ?Sized>(
173    visitor: &mut V,
174    program: &Program,
175) -> ControlFlow<V::Break> {
176    for stmt in program.stmts.iter() {
177        visitor.visit_stmt(stmt)?;
178    }
179    ControlFlow::Continue(())
180}
181
182/// Dispatches `stmt` to the appropriate child visitors based on its [`StmtKind`].
183pub fn walk_owned_block<V: OwnedVisitor + ?Sized>(
184    visitor: &mut V,
185    block: &Block,
186) -> ControlFlow<V::Break> {
187    for stmt in block.stmts.iter() {
188        visitor.visit_stmt(stmt)?;
189    }
190    ControlFlow::Continue(())
191}
192
193/// Walks the children of a statement.
194pub fn walk_owned_stmt<V: OwnedVisitor + ?Sized>(
195    visitor: &mut V,
196    stmt: &Stmt,
197) -> ControlFlow<V::Break> {
198    match &stmt.kind {
199        StmtKind::Expression(expr) => {
200            visitor.visit_expr(expr)?;
201        }
202        StmtKind::Echo(exprs) => {
203            for expr in exprs.iter() {
204                visitor.visit_expr(expr)?;
205            }
206        }
207        StmtKind::Return(expr) => {
208            if let Some(expr) = expr {
209                visitor.visit_expr(expr)?;
210            }
211        }
212        StmtKind::Block(block) => {
213            visitor.visit_block(block)?;
214        }
215        StmtKind::If(if_stmt) => {
216            visitor.visit_expr(&if_stmt.condition)?;
217            visitor.visit_stmt(&if_stmt.then_branch)?;
218            for elseif in if_stmt.elseif_branches.iter() {
219                visitor.visit_expr(&elseif.condition)?;
220                visitor.visit_stmt(&elseif.body)?;
221            }
222            if let Some(else_branch) = &if_stmt.else_branch {
223                visitor.visit_stmt(else_branch)?;
224            }
225        }
226        StmtKind::While(while_stmt) => {
227            visitor.visit_expr(&while_stmt.condition)?;
228            visitor.visit_stmt(&while_stmt.body)?;
229        }
230        StmtKind::For(for_stmt) => {
231            for expr in for_stmt.init.iter() {
232                visitor.visit_expr(expr)?;
233            }
234            for expr in for_stmt.condition.iter() {
235                visitor.visit_expr(expr)?;
236            }
237            for expr in for_stmt.update.iter() {
238                visitor.visit_expr(expr)?;
239            }
240            visitor.visit_stmt(&for_stmt.body)?;
241        }
242        StmtKind::Foreach(foreach_stmt) => {
243            visitor.visit_expr(&foreach_stmt.expr)?;
244            if let Some(key) = &foreach_stmt.key {
245                visitor.visit_expr(key)?;
246            }
247            visitor.visit_expr(&foreach_stmt.value)?;
248            visitor.visit_stmt(&foreach_stmt.body)?;
249        }
250        StmtKind::DoWhile(do_while) => {
251            visitor.visit_stmt(&do_while.body)?;
252            visitor.visit_expr(&do_while.condition)?;
253        }
254        StmtKind::Function(func) => {
255            walk_owned_function_like(visitor, &func.attributes, &func.params, &func.return_type)?;
256            visitor.visit_block(&func.body)?;
257        }
258        StmtKind::Break(expr) | StmtKind::Continue(expr) => {
259            if let Some(expr) = expr {
260                visitor.visit_expr(expr)?;
261            }
262        }
263        StmtKind::Switch(switch_stmt) => {
264            visitor.visit_expr(&switch_stmt.expr)?;
265            for case in switch_stmt.body.cases.iter() {
266                if let Some(value) = &case.value {
267                    visitor.visit_expr(value)?;
268                }
269                for stmt in case.body.iter() {
270                    visitor.visit_stmt(stmt)?;
271                }
272            }
273        }
274        StmtKind::Throw(expr) => {
275            visitor.visit_expr(expr)?;
276        }
277        StmtKind::TryCatch(tc) => {
278            visitor.visit_block(&tc.body)?;
279            for catch in tc.catches.iter() {
280                visitor.visit_catch_clause(catch)?;
281            }
282            if let Some(finally) = &tc.finally {
283                visitor.visit_block(finally)?;
284            }
285        }
286        StmtKind::Declare(decl) => {
287            for (_, expr) in decl.directives.iter() {
288                visitor.visit_expr(expr)?;
289            }
290            if let Some(body) = &decl.body {
291                visitor.visit_stmt(body)?;
292            }
293        }
294        StmtKind::Unset(exprs) | StmtKind::Global(exprs) => {
295            for expr in exprs.iter() {
296                visitor.visit_expr(expr)?;
297            }
298        }
299        StmtKind::Class(class) => {
300            walk_owned_attributes(visitor, &class.attributes)?;
301            if let Some(extends) = &class.extends {
302                visitor.visit_name(extends)?;
303            }
304            for name in class.implements.iter() {
305                visitor.visit_name(name)?;
306            }
307            for member in class.body.members.iter() {
308                visitor.visit_class_member(member)?;
309            }
310        }
311        StmtKind::Interface(iface) => {
312            walk_owned_attributes(visitor, &iface.attributes)?;
313            for name in iface.extends.iter() {
314                visitor.visit_name(name)?;
315            }
316            for member in iface.body.members.iter() {
317                visitor.visit_class_member(member)?;
318            }
319        }
320        StmtKind::Trait(trait_decl) => {
321            walk_owned_attributes(visitor, &trait_decl.attributes)?;
322            for member in trait_decl.body.members.iter() {
323                visitor.visit_class_member(member)?;
324            }
325        }
326        StmtKind::Enum(enum_decl) => {
327            walk_owned_attributes(visitor, &enum_decl.attributes)?;
328            if let Some(scalar_type) = &enum_decl.scalar_type {
329                visitor.visit_name(scalar_type)?;
330            }
331            for name in enum_decl.implements.iter() {
332                visitor.visit_name(name)?;
333            }
334            for member in enum_decl.body.members.iter() {
335                visitor.visit_enum_member(member)?;
336            }
337        }
338        StmtKind::Namespace(ns) => {
339            if let Some(name) = &ns.name {
340                visitor.visit_name(name)?;
341            }
342            if let NamespaceBody::Braced(block) = &ns.body {
343                visitor.visit_block(block)?;
344            }
345        }
346        StmtKind::Const(items) => {
347            for item in items.iter() {
348                walk_owned_attributes(visitor, &item.attributes)?;
349                visitor.visit_expr(&item.value)?;
350            }
351        }
352        StmtKind::StaticVar(vars) => {
353            for var in vars.iter() {
354                if let Some(default) = &var.default {
355                    visitor.visit_expr(default)?;
356                }
357            }
358        }
359        StmtKind::Use(decl) => {
360            for item in decl.uses.iter() {
361                visitor.visit_name(&item.name)?;
362            }
363        }
364        StmtKind::Goto(_)
365        | StmtKind::Label(_)
366        | StmtKind::Nop
367        | StmtKind::InlineHtml(_)
368        | StmtKind::HaltCompiler(_)
369        | StmtKind::Error => {}
370    }
371    ControlFlow::Continue(())
372}
373
374/// Dispatches `expr` to the appropriate child visitors based on its [`ExprKind`].
375pub fn walk_owned_expr<V: OwnedVisitor + ?Sized>(
376    visitor: &mut V,
377    expr: &Expr,
378) -> ControlFlow<V::Break> {
379    match &expr.kind {
380        ExprKind::Name(name) => visitor.visit_name(name)?,
381        ExprKind::Assign(assign) => {
382            visitor.visit_expr(&assign.target)?;
383            visitor.visit_expr(&assign.value)?;
384        }
385        ExprKind::Binary(binary) => {
386            visitor.visit_expr(&binary.left)?;
387            visitor.visit_expr(&binary.right)?;
388        }
389        ExprKind::UnaryPrefix(unary) => {
390            visitor.visit_expr(&unary.operand)?;
391        }
392        ExprKind::UnaryPostfix(unary) => {
393            visitor.visit_expr(&unary.operand)?;
394        }
395        ExprKind::Ternary(ternary) => {
396            visitor.visit_expr(&ternary.condition)?;
397            if let Some(then_expr) = &ternary.then_expr {
398                visitor.visit_expr(then_expr)?;
399            }
400            visitor.visit_expr(&ternary.else_expr)?;
401        }
402        ExprKind::NullCoalesce(nc) => {
403            visitor.visit_expr(&nc.left)?;
404            visitor.visit_expr(&nc.right)?;
405        }
406        ExprKind::FunctionCall(call) => {
407            visitor.visit_expr(&call.name)?;
408            for arg in call.args.iter() {
409                visitor.visit_arg(arg)?;
410            }
411        }
412        ExprKind::Array(elements) => {
413            for elem in elements.iter() {
414                if let Some(key) = &elem.key {
415                    visitor.visit_expr(key)?;
416                }
417                visitor.visit_expr(elem.value())?;
418            }
419        }
420        ExprKind::ArrayAccess(access) => {
421            visitor.visit_expr(&access.array)?;
422            if let Some(index) = &access.index {
423                visitor.visit_expr(index)?;
424            }
425        }
426        ExprKind::Print(expr) => {
427            visitor.visit_expr(expr)?;
428        }
429        ExprKind::Parenthesized(expr) => {
430            visitor.visit_expr(expr)?;
431        }
432        ExprKind::Cast(_, expr) => {
433            visitor.visit_expr(expr)?;
434        }
435        ExprKind::ErrorSuppress(expr) => {
436            visitor.visit_expr(expr)?;
437        }
438        ExprKind::Isset(exprs) => {
439            for expr in exprs.iter() {
440                visitor.visit_expr(expr)?;
441            }
442        }
443        ExprKind::Empty(expr) => {
444            visitor.visit_expr(expr)?;
445        }
446        ExprKind::Include(_, expr) => {
447            visitor.visit_expr(expr)?;
448        }
449        ExprKind::Eval(expr) => {
450            visitor.visit_expr(expr)?;
451        }
452        ExprKind::Exit(expr) => {
453            if let Some(expr) = expr {
454                visitor.visit_expr(expr)?;
455            }
456        }
457        ExprKind::Clone(expr) => {
458            visitor.visit_expr(expr)?;
459        }
460        ExprKind::CloneWith(object, overrides) => {
461            visitor.visit_expr(object)?;
462            visitor.visit_expr(overrides)?;
463        }
464        ExprKind::New(new_expr) => {
465            visitor.visit_expr(&new_expr.class)?;
466            for arg in new_expr.args.iter() {
467                visitor.visit_arg(arg)?;
468            }
469        }
470        ExprKind::PropertyAccess(access) | ExprKind::NullsafePropertyAccess(access) => {
471            visitor.visit_expr(&access.object)?;
472            visitor.visit_expr(&access.property)?;
473        }
474        ExprKind::MethodCall(call) | ExprKind::NullsafeMethodCall(call) => {
475            visitor.visit_expr(&call.object)?;
476            visitor.visit_expr(&call.method)?;
477            for arg in call.args.iter() {
478                visitor.visit_arg(arg)?;
479            }
480        }
481        ExprKind::StaticPropertyAccess(access) | ExprKind::ClassConstAccess(access) => {
482            visitor.visit_expr(&access.class)?;
483            visitor.visit_expr(&access.member)?;
484        }
485        ExprKind::ClassConstAccessDynamic { class, member }
486        | ExprKind::StaticPropertyAccessDynamic { class, member } => {
487            visitor.visit_expr(class)?;
488            visitor.visit_expr(member)?;
489        }
490        ExprKind::StaticMethodCall(call) => {
491            visitor.visit_expr(&call.class)?;
492            visitor.visit_expr(&call.method)?;
493            for arg in call.args.iter() {
494                visitor.visit_arg(arg)?;
495            }
496        }
497        ExprKind::StaticMethodCallDynamic(call) => {
498            visitor.visit_expr(&call.class)?;
499            visitor.visit_expr(&call.method)?;
500            for arg in call.args.iter() {
501                visitor.visit_arg(arg)?;
502            }
503        }
504        ExprKind::Closure(closure) => {
505            walk_owned_function_like(
506                visitor,
507                &closure.attributes,
508                &closure.params,
509                &closure.return_type,
510            )?;
511            for use_var in closure.use_vars.iter() {
512                visitor.visit_closure_use_var(use_var)?;
513            }
514            visitor.visit_block(&closure.body)?;
515        }
516        ExprKind::ArrowFunction(arrow) => {
517            walk_owned_function_like(
518                visitor,
519                &arrow.attributes,
520                &arrow.params,
521                &arrow.return_type,
522            )?;
523            visitor.visit_expr(&arrow.body)?;
524        }
525        ExprKind::Match(match_expr) => {
526            visitor.visit_expr(&match_expr.subject)?;
527            for arm in match_expr.arms.iter() {
528                visitor.visit_match_arm(arm)?;
529            }
530        }
531        ExprKind::Throw(expr) => {
532            visitor.visit_expr(expr)?;
533        }
534        ExprKind::Yield(yield_expr) => {
535            if let Some(key) = &yield_expr.key {
536                visitor.visit_expr(key)?;
537            }
538            if let Some(value) = &yield_expr.value {
539                visitor.visit_expr(value)?;
540            }
541        }
542        ExprKind::AnonymousClass(class) => {
543            walk_owned_attributes(visitor, &class.attributes)?;
544            for member in class.body.members.iter() {
545                visitor.visit_class_member(member)?;
546            }
547        }
548        ExprKind::InterpolatedString(parts) | ExprKind::ShellExec(parts) => {
549            for part in parts.iter() {
550                if let StringPart::Expr(e) = part {
551                    visitor.visit_expr(e)?;
552                }
553            }
554        }
555        ExprKind::Heredoc { parts, .. } => {
556            for part in parts.iter() {
557                if let StringPart::Expr(e) = part {
558                    visitor.visit_expr(e)?;
559                }
560            }
561        }
562        ExprKind::VariableVariable(inner) => {
563            visitor.visit_expr(inner)?;
564        }
565        ExprKind::CallableCreate(cc) => match &cc.kind {
566            CallableCreateKind::Function(name) => visitor.visit_expr(name)?,
567            CallableCreateKind::Method { object, method }
568            | CallableCreateKind::NullsafeMethod { object, method } => {
569                visitor.visit_expr(object)?;
570                visitor.visit_expr(method)?;
571            }
572            CallableCreateKind::StaticMethod { class, method } => {
573                visitor.visit_expr(class)?;
574                visitor.visit_expr(method)?;
575            }
576        },
577        ExprKind::Int(_)
578        | ExprKind::Float(_)
579        | ExprKind::String(_)
580        | ExprKind::Bool(_)
581        | ExprKind::Null
582        | ExprKind::Omit
583        | ExprKind::Variable(_)
584        | ExprKind::Identifier(_)
585        | ExprKind::MagicConst(_)
586        | ExprKind::Nowdoc { .. }
587        | ExprKind::Error => {}
588    }
589    ControlFlow::Continue(())
590}
591
592/// Visits a function/method parameter's attributes, type hint, default, and hooks.
593pub fn walk_owned_param<V: OwnedVisitor + ?Sized>(
594    visitor: &mut V,
595    param: &Param,
596) -> ControlFlow<V::Break> {
597    walk_owned_attributes(visitor, &param.attributes)?;
598    if let Some(type_hint) = &param.type_hint {
599        visitor.visit_type_hint(type_hint)?;
600    }
601    if let Some(default) = &param.default {
602        visitor.visit_expr(default)?;
603    }
604    for hook in param.hooks.iter() {
605        visitor.visit_property_hook(hook)?;
606    }
607    ControlFlow::Continue(())
608}
609
610/// Visits the value expression of a call argument, skipping PHP 8.6 placeholders.
611pub fn walk_owned_arg<V: OwnedVisitor + ?Sized>(
612    visitor: &mut V,
613    arg: &Arg,
614) -> ControlFlow<V::Break> {
615    if let Some(name) = &arg.name {
616        visitor.visit_name(name)?;
617    }
618    match arg.value() {
619        Some(value) => visitor.visit_expr(value),
620        None => ControlFlow::Continue(()),
621    }
622}
623
624/// Dispatches a class member to its child visitors.
625pub fn walk_owned_class_member<V: OwnedVisitor + ?Sized>(
626    visitor: &mut V,
627    member: &ClassMember,
628) -> ControlFlow<V::Break> {
629    match &member.kind {
630        ClassMemberKind::Property(prop) => {
631            walk_owned_property_decl(visitor, prop)?;
632        }
633        ClassMemberKind::Method(method) => {
634            walk_owned_method_decl(visitor, method)?;
635        }
636        ClassMemberKind::ClassConst(cc) => {
637            walk_owned_class_const_decl(visitor, cc)?;
638        }
639        ClassMemberKind::TraitUse(trait_use) => {
640            visitor.visit_trait_use(trait_use)?;
641        }
642    }
643    ControlFlow::Continue(())
644}
645
646/// Visits a property hook's attributes, parameters, and body.
647pub fn walk_owned_property_hook<V: OwnedVisitor + ?Sized>(
648    visitor: &mut V,
649    hook: &PropertyHook,
650) -> ControlFlow<V::Break> {
651    walk_owned_attributes(visitor, &hook.attributes)?;
652    for param in hook.params.iter() {
653        visitor.visit_param(param)?;
654    }
655    match &hook.body {
656        PropertyHookBody::Block(block) => {
657            visitor.visit_block(block)?;
658        }
659        PropertyHookBody::Expression(expr) => {
660            visitor.visit_expr(expr)?;
661        }
662        PropertyHookBody::Abstract => {}
663    }
664    ControlFlow::Continue(())
665}
666
667/// Dispatches an enum member to its child visitors.
668pub fn walk_owned_enum_member<V: OwnedVisitor + ?Sized>(
669    visitor: &mut V,
670    member: &EnumMember,
671) -> ControlFlow<V::Break> {
672    match &member.kind {
673        EnumMemberKind::Case(case) => {
674            walk_owned_attributes(visitor, &case.attributes)?;
675            if let Some(value) = &case.value {
676                visitor.visit_expr(value)?;
677            }
678        }
679        EnumMemberKind::Method(method) => {
680            walk_owned_method_decl(visitor, method)?;
681        }
682        EnumMemberKind::ClassConst(cc) => {
683            walk_owned_class_const_decl(visitor, cc)?;
684        }
685        EnumMemberKind::TraitUse(trait_use) => {
686            visitor.visit_trait_use(trait_use)?;
687        }
688    }
689    ControlFlow::Continue(())
690}
691
692/// Visits the inner types of a type hint.
693pub fn walk_owned_type_hint<V: OwnedVisitor + ?Sized>(
694    visitor: &mut V,
695    type_hint: &TypeHint,
696) -> ControlFlow<V::Break> {
697    match &type_hint.kind {
698        TypeHintKind::Nullable(inner) => {
699            visitor.visit_type_hint(inner)?;
700        }
701        TypeHintKind::Union(types) | TypeHintKind::Intersection(types) => {
702            for ty in types.iter() {
703                visitor.visit_type_hint(ty)?;
704            }
705        }
706        TypeHintKind::Named(name) => {
707            visitor.visit_name(name)?;
708        }
709        TypeHintKind::Keyword(_, _) => {}
710    }
711    ControlFlow::Continue(())
712}
713
714/// Visits an attribute's name and argument expressions.
715pub fn walk_owned_attribute<V: OwnedVisitor + ?Sized>(
716    visitor: &mut V,
717    attribute: &Attribute,
718) -> ControlFlow<V::Break> {
719    visitor.visit_name(&attribute.name)?;
720    for arg in attribute.args.iter() {
721        visitor.visit_arg(arg)?;
722    }
723    ControlFlow::Continue(())
724}
725
726/// Visits a catch clause's type names and body statements.
727pub fn walk_owned_catch_clause<V: OwnedVisitor + ?Sized>(
728    visitor: &mut V,
729    catch: &CatchClause,
730) -> ControlFlow<V::Break> {
731    for ty in catch.types.iter() {
732        visitor.visit_name(ty)?;
733    }
734    visitor.visit_block(&catch.body)?;
735    ControlFlow::Continue(())
736}
737
738/// Visits a match arm's condition expressions and body expression.
739pub fn walk_owned_match_arm<V: OwnedVisitor + ?Sized>(
740    visitor: &mut V,
741    arm: &MatchArm,
742) -> ControlFlow<V::Break> {
743    if let Some(conditions) = &arm.conditions {
744        for cond in conditions.iter() {
745            visitor.visit_expr(cond)?;
746        }
747    }
748    visitor.visit_expr(&arm.body)
749}
750
751/// Visits a trait use declaration's names and adaptations.
752pub fn walk_owned_trait_use<V: OwnedVisitor + ?Sized>(
753    visitor: &mut V,
754    trait_use: &TraitUseDecl,
755) -> ControlFlow<V::Break> {
756    for name in trait_use.traits.iter() {
757        visitor.visit_name(name)?;
758    }
759    for adaptation in trait_use.adaptations.iter() {
760        visitor.visit_trait_adaptation(adaptation)?;
761    }
762    ControlFlow::Continue(())
763}
764
765/// Visits the trait and method names of an `insteadof`/`as` adaptation.
766pub fn walk_owned_trait_adaptation<V: OwnedVisitor + ?Sized>(
767    visitor: &mut V,
768    adaptation: &TraitAdaptation,
769) -> ControlFlow<V::Break> {
770    match &adaptation.kind {
771        TraitAdaptationKind::Precedence {
772            trait_name,
773            method,
774            insteadof,
775        } => {
776            visitor.visit_name(trait_name)?;
777            visitor.visit_name(method)?;
778            for name in insteadof.iter() {
779                visitor.visit_name(name)?;
780            }
781        }
782        TraitAdaptationKind::Alias {
783            trait_name,
784            method,
785            new_name,
786            ..
787        } => {
788            if let Some(name) = trait_name {
789                visitor.visit_name(name)?;
790            }
791            visitor.visit_name(method)?;
792            if let Some(name) = new_name {
793                visitor.visit_name(name)?;
794            }
795        }
796    }
797    ControlFlow::Continue(())
798}
799
800// =============================================================================
801// Internal helpers
802// =============================================================================
803
804fn walk_owned_function_like<V: OwnedVisitor + ?Sized>(
805    visitor: &mut V,
806    attributes: &[Attribute],
807    params: &[Param],
808    return_type: &Option<TypeHint>,
809) -> ControlFlow<V::Break> {
810    walk_owned_attributes(visitor, attributes)?;
811    for param in params.iter() {
812        visitor.visit_param(param)?;
813    }
814    if let Some(ret) = return_type {
815        visitor.visit_type_hint(ret)?;
816    }
817    ControlFlow::Continue(())
818}
819
820fn walk_owned_method_decl<V: OwnedVisitor + ?Sized>(
821    visitor: &mut V,
822    method: &MethodDecl,
823) -> ControlFlow<V::Break> {
824    walk_owned_function_like(
825        visitor,
826        &method.attributes,
827        &method.params,
828        &method.return_type,
829    )?;
830    if let Some(body) = &method.body {
831        visitor.visit_block(body)?;
832    }
833    ControlFlow::Continue(())
834}
835
836fn walk_owned_class_const_decl<V: OwnedVisitor + ?Sized>(
837    visitor: &mut V,
838    cc: &ClassConstDecl,
839) -> ControlFlow<V::Break> {
840    walk_owned_attributes(visitor, &cc.attributes)?;
841    if let Some(type_hint) = &cc.type_hint {
842        visitor.visit_type_hint(type_hint)?;
843    }
844    visitor.visit_expr(&cc.value)
845}
846
847fn walk_owned_property_decl<V: OwnedVisitor + ?Sized>(
848    visitor: &mut V,
849    prop: &PropertyDecl,
850) -> ControlFlow<V::Break> {
851    walk_owned_attributes(visitor, &prop.attributes)?;
852    if let Some(type_hint) = &prop.type_hint {
853        visitor.visit_type_hint(type_hint)?;
854    }
855    if let Some(default) = &prop.default {
856        visitor.visit_expr(default)?;
857    }
858    for hook in prop.hooks.iter() {
859        visitor.visit_property_hook(hook)?;
860    }
861    ControlFlow::Continue(())
862}
863
864fn walk_owned_attributes<V: OwnedVisitor + ?Sized>(
865    visitor: &mut V,
866    attributes: &[Attribute],
867) -> ControlFlow<V::Break> {
868    for attr in attributes.iter() {
869        visitor.visit_attribute(attr)?;
870    }
871    ControlFlow::Continue(())
872}
873
874// =============================================================================
875// OwnedScopeVisitor — scope-aware traversal
876// =============================================================================
877
878/// Lexical scope context for owned AST traversal.
879///
880/// Like [`crate::visitor::Scope`] but uses `Option<String>` instead of
881/// `Option<&str>` so the owned visitor has no lifetime parameters.
882#[derive(Debug, Clone, Default)]
883#[non_exhaustive]
884pub struct OwnedScope {
885    /// Current namespace, or `None` for the global namespace.
886    pub namespace: Option<String>,
887    /// Name of the immediately enclosing class-like declaration, or `None`.
888    pub class_name: Option<String>,
889    /// Name of the immediately enclosing named function or method, or `None`.
890    pub function_name: Option<String>,
891}
892
893/// A scope-aware variant of [`OwnedVisitor`].
894///
895/// Every visit method receives an [`OwnedScope`] describing the lexical context
896/// at that node. Drive traversal with [`OwnedScopeWalker`].
897pub trait OwnedScopeVisitor {
898    /// Value carried by [`ControlFlow::Break`] when a visit stops the walk early; use `()` to
899    /// stop without a result.
900    type Break;
901
902    /// Called for each program with its enclosing scope.
903    fn visit_program(
904        &mut self,
905        _program: &Program,
906        _scope: &OwnedScope,
907    ) -> ControlFlow<Self::Break> {
908        ControlFlow::Continue(())
909    }
910    /// Called for each statement with its enclosing scope.
911    fn visit_stmt(&mut self, _stmt: &Stmt, _scope: &OwnedScope) -> ControlFlow<Self::Break> {
912        ControlFlow::Continue(())
913    }
914    /// Called for each expression with its enclosing scope.
915    fn visit_expr(&mut self, _expr: &Expr, _scope: &OwnedScope) -> ControlFlow<Self::Break> {
916        ControlFlow::Continue(())
917    }
918    /// Called for each param with its enclosing scope.
919    fn visit_param(&mut self, _param: &Param, _scope: &OwnedScope) -> ControlFlow<Self::Break> {
920        ControlFlow::Continue(())
921    }
922    /// Called for each arg with its enclosing scope.
923    fn visit_arg(&mut self, _arg: &Arg, _scope: &OwnedScope) -> ControlFlow<Self::Break> {
924        ControlFlow::Continue(())
925    }
926    /// Called for each class member with its enclosing scope.
927    fn visit_class_member(
928        &mut self,
929        _member: &ClassMember,
930        _scope: &OwnedScope,
931    ) -> ControlFlow<Self::Break> {
932        ControlFlow::Continue(())
933    }
934    /// Called for each enum member with its enclosing scope.
935    fn visit_enum_member(
936        &mut self,
937        _member: &EnumMember,
938        _scope: &OwnedScope,
939    ) -> ControlFlow<Self::Break> {
940        ControlFlow::Continue(())
941    }
942    /// Called for each property hook with its enclosing scope.
943    fn visit_property_hook(
944        &mut self,
945        _hook: &PropertyHook,
946        _scope: &OwnedScope,
947    ) -> ControlFlow<Self::Break> {
948        ControlFlow::Continue(())
949    }
950    /// Called for each type hint with its enclosing scope.
951    fn visit_type_hint(
952        &mut self,
953        _type_hint: &TypeHint,
954        _scope: &OwnedScope,
955    ) -> ControlFlow<Self::Break> {
956        ControlFlow::Continue(())
957    }
958    /// Called for each attribute with its enclosing scope.
959    fn visit_attribute(
960        &mut self,
961        _attribute: &Attribute,
962        _scope: &OwnedScope,
963    ) -> ControlFlow<Self::Break> {
964        ControlFlow::Continue(())
965    }
966    /// Called for each catch clause with its enclosing scope.
967    fn visit_catch_clause(
968        &mut self,
969        _catch: &CatchClause,
970        _scope: &OwnedScope,
971    ) -> ControlFlow<Self::Break> {
972        ControlFlow::Continue(())
973    }
974    /// Called for each match arm with its enclosing scope.
975    fn visit_match_arm(
976        &mut self,
977        _arm: &MatchArm,
978        _scope: &OwnedScope,
979    ) -> ControlFlow<Self::Break> {
980        ControlFlow::Continue(())
981    }
982    /// Called for each closure use var with its enclosing scope.
983    fn visit_closure_use_var(
984        &mut self,
985        _var: &ClosureUseVar,
986        _scope: &OwnedScope,
987    ) -> ControlFlow<Self::Break> {
988        ControlFlow::Continue(())
989    }
990    /// Called for each trait use with its enclosing scope.
991    fn visit_trait_use(
992        &mut self,
993        _trait_use: &TraitUseDecl,
994        _scope: &OwnedScope,
995    ) -> ControlFlow<Self::Break> {
996        ControlFlow::Continue(())
997    }
998    /// Called for each trait adaptation with its enclosing scope.
999    fn visit_trait_adaptation(
1000        &mut self,
1001        _adaptation: &TraitAdaptation,
1002        _scope: &OwnedScope,
1003    ) -> ControlFlow<Self::Break> {
1004        ControlFlow::Continue(())
1005    }
1006    /// Called for each block with its enclosing scope.
1007    fn visit_block(&mut self, _block: &Block, _scope: &OwnedScope) -> ControlFlow<Self::Break> {
1008        ControlFlow::Continue(())
1009    }
1010    /// Called for each name reference with its enclosing scope.
1011    fn visit_name(&mut self, _name: &Name, _scope: &OwnedScope) -> ControlFlow<Self::Break> {
1012        ControlFlow::Continue(())
1013    }
1014    /// Called for each comment with its enclosing scope.
1015    fn visit_comment(
1016        &mut self,
1017        _comment: &Comment,
1018        _scope: &OwnedScope,
1019    ) -> ControlFlow<Self::Break> {
1020        ControlFlow::Continue(())
1021    }
1022}
1023
1024/// Drives an [`OwnedScopeVisitor`] over an owned AST, maintaining [`OwnedScope`] automatically.
1025pub struct OwnedScopeWalker<V> {
1026    inner: V,
1027    scope: OwnedScope,
1028}
1029
1030impl<V> OwnedScopeWalker<V> {
1031    /// Creates a new walker wrapping `inner`.
1032    pub fn new(inner: V) -> Self {
1033        Self {
1034            inner,
1035            scope: OwnedScope::default(),
1036        }
1037    }
1038
1039    /// Consumes the walker and returns the inner visitor.
1040    pub fn into_inner(self) -> V {
1041        self.inner
1042    }
1043
1044    /// Returns a reference to the inner visitor.
1045    pub fn inner(&self) -> &V {
1046        &self.inner
1047    }
1048
1049    /// Returns a mutable reference to the inner visitor.
1050    pub fn inner_mut(&mut self) -> &mut V {
1051        &mut self.inner
1052    }
1053}
1054
1055impl<V: OwnedScopeVisitor> OwnedScopeWalker<V> {
1056    /// Walks `program`, calling [`OwnedScopeVisitor`] methods with scope context.
1057    pub fn walk(&mut self, program: &Program) -> ControlFlow<V::Break> {
1058        self.visit_program(program)
1059    }
1060}
1061
1062fn owned_name_repr(name: &Name) -> Option<String> {
1063    if name.parts.is_empty() {
1064        return None;
1065    }
1066    Some(
1067        name.parts
1068            .iter()
1069            .map(|s| s.as_ref())
1070            .collect::<Vec<_>>()
1071            .join("\\"),
1072    )
1073}
1074
1075impl<V: OwnedScopeVisitor> OwnedVisitor for OwnedScopeWalker<V> {
1076    type Break = V::Break;
1077
1078    fn visit_program(&mut self, program: &Program) -> ControlFlow<V::Break> {
1079        // A previous walk may have ended inside a namespace or after a `Break`.
1080        self.scope = OwnedScope::default();
1081        self.inner.visit_program(program, &self.scope)?;
1082        walk_owned_program(self, program)
1083    }
1084
1085    fn visit_stmt(&mut self, stmt: &Stmt) -> ControlFlow<V::Break> {
1086        self.inner.visit_stmt(stmt, &self.scope)?;
1087        match &stmt.kind {
1088            StmtKind::Function(func) => {
1089                let fn_name = func.name.as_str().map(str::to_owned);
1090                let prev_fn = std::mem::replace(&mut self.scope.function_name, fn_name);
1091                walk_owned_stmt(self, stmt)?;
1092                self.scope.function_name = prev_fn;
1093            }
1094            StmtKind::Class(class) => {
1095                let class_name = class
1096                    .name
1097                    .as_ref()
1098                    .and_then(|ident| ident.as_str())
1099                    .map(|s| s.to_string());
1100                let prev_class = std::mem::replace(&mut self.scope.class_name, class_name);
1101                let prev_fn = self.scope.function_name.take();
1102                walk_owned_stmt(self, stmt)?;
1103                self.scope.class_name = prev_class;
1104                self.scope.function_name = prev_fn;
1105            }
1106            StmtKind::Interface(iface) => {
1107                let iface_name = iface.name.as_str().map(str::to_owned);
1108                let prev_class = std::mem::replace(&mut self.scope.class_name, iface_name);
1109                let prev_fn = self.scope.function_name.take();
1110                walk_owned_stmt(self, stmt)?;
1111                self.scope.class_name = prev_class;
1112                self.scope.function_name = prev_fn;
1113            }
1114            StmtKind::Trait(trait_decl) => {
1115                let trait_name = trait_decl.name.as_str().map(str::to_owned);
1116                let prev_class = std::mem::replace(&mut self.scope.class_name, trait_name);
1117                let prev_fn = self.scope.function_name.take();
1118                walk_owned_stmt(self, stmt)?;
1119                self.scope.class_name = prev_class;
1120                self.scope.function_name = prev_fn;
1121            }
1122            StmtKind::Enum(enum_decl) => {
1123                let enum_name = enum_decl.name.as_str().map(str::to_owned);
1124                let prev_class = std::mem::replace(&mut self.scope.class_name, enum_name);
1125                let prev_fn = self.scope.function_name.take();
1126                walk_owned_stmt(self, stmt)?;
1127                self.scope.class_name = prev_class;
1128                self.scope.function_name = prev_fn;
1129            }
1130            StmtKind::Namespace(ns) => {
1131                let ns_str = ns.name.as_ref().and_then(owned_name_repr);
1132                match &ns.body {
1133                    NamespaceBody::Braced(_) => {
1134                        let prev_ns = std::mem::replace(&mut self.scope.namespace, ns_str);
1135                        let prev_class = self.scope.class_name.take();
1136                        let prev_fn = self.scope.function_name.take();
1137                        walk_owned_stmt(self, stmt)?;
1138                        self.scope.namespace = prev_ns;
1139                        self.scope.class_name = prev_class;
1140                        self.scope.function_name = prev_fn;
1141                    }
1142                    NamespaceBody::Simple => {
1143                        self.scope.namespace = ns_str;
1144                        self.scope.class_name = None;
1145                        self.scope.function_name = None;
1146                    }
1147                }
1148            }
1149            _ => {
1150                walk_owned_stmt(self, stmt)?;
1151            }
1152        }
1153        ControlFlow::Continue(())
1154    }
1155
1156    fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<V::Break> {
1157        self.inner.visit_expr(expr, &self.scope)?;
1158        match &expr.kind {
1159            ExprKind::Closure(_) | ExprKind::ArrowFunction(_) => {
1160                let prev_fn = self.scope.function_name.take();
1161                walk_owned_expr(self, expr)?;
1162                self.scope.function_name = prev_fn;
1163            }
1164            ExprKind::AnonymousClass(_) => {
1165                let prev_class = self.scope.class_name.take();
1166                let prev_fn = self.scope.function_name.take();
1167                walk_owned_expr(self, expr)?;
1168                self.scope.class_name = prev_class;
1169                self.scope.function_name = prev_fn;
1170            }
1171            _ => {
1172                walk_owned_expr(self, expr)?;
1173            }
1174        }
1175        ControlFlow::Continue(())
1176    }
1177
1178    fn visit_class_member(&mut self, member: &ClassMember) -> ControlFlow<V::Break> {
1179        self.inner.visit_class_member(member, &self.scope)?;
1180        if let ClassMemberKind::Method(method) = &member.kind {
1181            let fn_name = method.name.as_str().map(str::to_owned);
1182            let prev_fn = std::mem::replace(&mut self.scope.function_name, fn_name);
1183            walk_owned_class_member(self, member)?;
1184            self.scope.function_name = prev_fn;
1185        } else {
1186            walk_owned_class_member(self, member)?;
1187        }
1188        ControlFlow::Continue(())
1189    }
1190
1191    fn visit_enum_member(&mut self, member: &EnumMember) -> ControlFlow<V::Break> {
1192        self.inner.visit_enum_member(member, &self.scope)?;
1193        if let EnumMemberKind::Method(method) = &member.kind {
1194            let fn_name = method.name.as_str().map(str::to_owned);
1195            let prev_fn = std::mem::replace(&mut self.scope.function_name, fn_name);
1196            walk_owned_enum_member(self, member)?;
1197            self.scope.function_name = prev_fn;
1198        } else {
1199            walk_owned_enum_member(self, member)?;
1200        }
1201        ControlFlow::Continue(())
1202    }
1203
1204    fn visit_param(&mut self, param: &Param) -> ControlFlow<V::Break> {
1205        self.inner.visit_param(param, &self.scope)?;
1206        walk_owned_param(self, param)
1207    }
1208
1209    fn visit_arg(&mut self, arg: &Arg) -> ControlFlow<V::Break> {
1210        self.inner.visit_arg(arg, &self.scope)?;
1211        walk_owned_arg(self, arg)
1212    }
1213
1214    fn visit_property_hook(&mut self, hook: &PropertyHook) -> ControlFlow<V::Break> {
1215        self.inner.visit_property_hook(hook, &self.scope)?;
1216        walk_owned_property_hook(self, hook)
1217    }
1218
1219    fn visit_type_hint(&mut self, type_hint: &TypeHint) -> ControlFlow<V::Break> {
1220        self.inner.visit_type_hint(type_hint, &self.scope)?;
1221        walk_owned_type_hint(self, type_hint)
1222    }
1223
1224    fn visit_attribute(&mut self, attribute: &Attribute) -> ControlFlow<V::Break> {
1225        self.inner.visit_attribute(attribute, &self.scope)?;
1226        walk_owned_attribute(self, attribute)
1227    }
1228
1229    fn visit_catch_clause(&mut self, catch: &CatchClause) -> ControlFlow<V::Break> {
1230        self.inner.visit_catch_clause(catch, &self.scope)?;
1231        walk_owned_catch_clause(self, catch)
1232    }
1233
1234    fn visit_match_arm(&mut self, arm: &MatchArm) -> ControlFlow<V::Break> {
1235        self.inner.visit_match_arm(arm, &self.scope)?;
1236        walk_owned_match_arm(self, arm)
1237    }
1238
1239    fn visit_closure_use_var(&mut self, var: &ClosureUseVar) -> ControlFlow<V::Break> {
1240        self.inner.visit_closure_use_var(var, &self.scope)
1241    }
1242
1243    fn visit_trait_use(&mut self, trait_use: &TraitUseDecl) -> ControlFlow<V::Break> {
1244        self.inner.visit_trait_use(trait_use, &self.scope)?;
1245        walk_owned_trait_use(self, trait_use)
1246    }
1247
1248    fn visit_trait_adaptation(&mut self, adaptation: &TraitAdaptation) -> ControlFlow<V::Break> {
1249        self.inner.visit_trait_adaptation(adaptation, &self.scope)?;
1250        walk_owned_trait_adaptation(self, adaptation)
1251    }
1252
1253    fn visit_block(&mut self, block: &Block) -> ControlFlow<V::Break> {
1254        self.inner.visit_block(block, &self.scope)?;
1255        walk_owned_block(self, block)
1256    }
1257
1258    fn visit_name(&mut self, name: &Name) -> ControlFlow<V::Break> {
1259        self.inner.visit_name(name, &self.scope)
1260    }
1261
1262    fn visit_comment(&mut self, comment: &Comment) -> ControlFlow<V::Break> {
1263        self.inner.visit_comment(comment, &self.scope)
1264    }
1265}
1266
1267// =============================================================================
1268// Tests
1269// =============================================================================
1270
1271#[cfg(test)]
1272mod tests {
1273    use super::*;
1274    use crate::ast::{AssignOp, BinaryOp};
1275    use crate::Span;
1276
1277    fn dummy_var(name: &str) -> Expr {
1278        Expr {
1279            kind: ExprKind::Variable(Box::from(name)),
1280            span: Span::DUMMY,
1281        }
1282    }
1283
1284    fn dummy_int(n: i64) -> Expr {
1285        Expr {
1286            kind: ExprKind::Int(n),
1287            span: Span::DUMMY,
1288        }
1289    }
1290
1291    fn binary(left: Expr, op: BinaryOp, right: Expr) -> Expr {
1292        Expr {
1293            kind: ExprKind::Binary(BinaryExpr {
1294                left: Box::new(left),
1295                op,
1296                right: Box::new(right),
1297            }),
1298            span: Span::DUMMY,
1299        }
1300    }
1301
1302    fn expr_stmt(e: Expr) -> Stmt {
1303        Stmt {
1304            kind: StmtKind::Expression(Box::new(e)),
1305            span: Span::DUMMY,
1306            doc_comment: None,
1307        }
1308    }
1309
1310    fn block_of(stmts: impl IntoIterator<Item = Stmt>) -> Box<Block> {
1311        Box::new(Block {
1312            stmts: stmts.into_iter().collect(),
1313            span: Span::DUMMY,
1314        })
1315    }
1316
1317    fn program(stmts: impl IntoIterator<Item = Stmt>) -> Program {
1318        Program {
1319            stmts: stmts.into_iter().collect(),
1320            span: Span::DUMMY,
1321        }
1322    }
1323
1324    struct VarCounter {
1325        count: usize,
1326    }
1327
1328    impl OwnedVisitor for VarCounter {
1329        type Break = ();
1330        fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
1331            if matches!(&expr.kind, ExprKind::Variable(_)) {
1332                self.count += 1;
1333            }
1334            walk_owned_expr(self, expr)
1335        }
1336    }
1337
1338    #[test]
1339    fn counts_variables() {
1340        // $x = $y + $z;
1341        let p = program([expr_stmt(Expr {
1342            kind: ExprKind::Assign(AssignExpr {
1343                target: Box::new(dummy_var("x")),
1344                op: AssignOp::Assign,
1345                value: Box::new(binary(dummy_var("y"), BinaryOp::Add, dummy_var("z"))),
1346                by_ref: false,
1347            }),
1348            span: Span::DUMMY,
1349        })]);
1350        let mut v = VarCounter { count: 0 };
1351        let _ = v.visit_program(&p);
1352        assert_eq!(v.count, 3);
1353    }
1354
1355    #[test]
1356    fn early_termination() {
1357        // $a + $b;
1358        let p = program([expr_stmt(binary(
1359            dummy_var("a"),
1360            BinaryOp::Add,
1361            dummy_var("b"),
1362        ))]);
1363
1364        struct FindFirst {
1365            found: Option<String>,
1366        }
1367        impl OwnedVisitor for FindFirst {
1368            type Break = ();
1369            fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
1370                if let ExprKind::Variable(name) = &expr.kind {
1371                    self.found = Some(name.to_string());
1372                    return ControlFlow::Break(());
1373                }
1374                walk_owned_expr(self, expr)
1375            }
1376        }
1377
1378        let mut finder = FindFirst { found: None };
1379        let r = finder.visit_program(&p);
1380        assert!(r.is_break());
1381        assert_eq!(finder.found.as_deref(), Some("a"));
1382    }
1383
1384    #[test]
1385    fn skip_subtree() {
1386        // 1 + 2; function foo() { 3 + 4; }
1387        let top = binary(dummy_int(1), BinaryOp::Add, dummy_int(2));
1388        let inner = binary(dummy_int(3), BinaryOp::Add, dummy_int(4));
1389        let func = Stmt {
1390            kind: StmtKind::Function(Box::new(FunctionDecl {
1391                name: crate::owned::Ident::new("foo", Span::DUMMY),
1392                params: Box::from([]),
1393                body: block_of([expr_stmt(inner)]),
1394                return_type: None,
1395                by_ref: false,
1396                attributes: Box::from([]),
1397                doc_comment: None,
1398            })),
1399            span: Span::DUMMY,
1400            doc_comment: None,
1401        };
1402        let p = program([expr_stmt(top), func]);
1403
1404        struct SkipFunctions {
1405            expr_count: usize,
1406        }
1407        impl OwnedVisitor for SkipFunctions {
1408            type Break = ();
1409            fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
1410                self.expr_count += 1;
1411                walk_owned_expr(self, expr)
1412            }
1413            fn visit_stmt(&mut self, stmt: &Stmt) -> ControlFlow<()> {
1414                if matches!(&stmt.kind, StmtKind::Function(_)) {
1415                    return ControlFlow::Continue(());
1416                }
1417                walk_owned_stmt(self, stmt)
1418            }
1419        }
1420
1421        let mut v = SkipFunctions { expr_count: 0 };
1422        let _ = v.visit_program(&p);
1423        // Only top-level: binary(1, 2) = 3 exprs
1424        assert_eq!(v.expr_count, 3);
1425    }
1426
1427    #[test]
1428    fn scope_walker_tracks_class_and_method() {
1429        // class Foo { public function bar() { $x; } }
1430        let method = ClassMember {
1431            kind: ClassMemberKind::Method(MethodDecl {
1432                name: crate::owned::Ident::new("bar", Span::DUMMY),
1433                modifiers: {
1434                    let mut modifiers = crate::ast::Modifiers::new();
1435                    modifiers.visibility = Some(crate::ast::Visibility::Public);
1436                    modifiers
1437                },
1438                by_ref: false,
1439                params: Box::from([]),
1440                return_type: None,
1441                body: Some(block_of([expr_stmt(dummy_var("x"))])),
1442                attributes: Box::from([]),
1443                doc_comment: None,
1444            }),
1445            span: Span::DUMMY,
1446        };
1447        let class_stmt = Stmt {
1448            kind: StmtKind::Class(Box::new(ClassDecl {
1449                name: Some(crate::owned::Ident::new("Foo", Span::DUMMY)),
1450                modifiers: crate::ast::ClassModifiers::default(),
1451                extends: None,
1452                implements: Box::from([]),
1453                body: ClassBody {
1454                    members: [method].into_iter().collect(),
1455                    span: Span::DUMMY,
1456                },
1457                attributes: Box::from([]),
1458                doc_comment: None,
1459            })),
1460            span: Span::DUMMY,
1461            doc_comment: None,
1462        };
1463        let p = program([class_stmt]);
1464
1465        struct MethodCollector {
1466            methods: Vec<String>,
1467        }
1468        impl OwnedScopeVisitor for MethodCollector {
1469            type Break = ();
1470            fn visit_class_member(
1471                &mut self,
1472                member: &ClassMember,
1473                scope: &OwnedScope,
1474            ) -> ControlFlow<()> {
1475                if let ClassMemberKind::Method(m) = &member.kind {
1476                    self.methods.push(format!(
1477                        "{}::{}",
1478                        scope.class_name.as_deref().unwrap_or("<anon>"),
1479                        m.name.or_error(),
1480                    ));
1481                }
1482                ControlFlow::Continue(())
1483            }
1484        }
1485
1486        let mut walker = OwnedScopeWalker::new(MethodCollector { methods: vec![] });
1487        let _ = walker.walk(&p);
1488        assert_eq!(walker.into_inner().methods, ["Foo::bar"]);
1489    }
1490}