Skip to main content

larust_convert/
php.rs

1//! Thin wrapper over `tree-sitter`/`tree-sitter-php`, shared by every
2//! converter module. `tree-sitter-php` was chosen (over the alternative
3//! crates surveyed - `php-parser`, a brand-new single-maintainer crate with
4//! no independent evidence backing its own claims, and `php-parser-rs`,
5//! explicitly alpha) for its error-tolerant CST: a syntax-error-adjacent
6//! chunk of real-world PHP still parses into a walkable tree with a
7//! detectable `ERROR` node, rather than aborting the whole file - the right
8//! fit for a converter whose core rule is "never silently mistranslate."
9//!
10//! Every converter matches structure via tree-sitter's own query language
11//! (`.scm` patterns), not manual tree-walking - see each converter module
12//! for its query source.
13
14use anyhow::{Context, Result};
15use streaming_iterator::StreamingIterator;
16use tree_sitter::{Language, Node, Parser, Query, QueryCursor, Tree};
17
18/// Parses `source` as a PHP file (the `<?php ... ?>`-tagged dialect, not
19/// the "assume the whole file is PHP with no tags" variant - every real
20/// Laravel source file opens with `<?php`).
21pub fn parse(source: &str) -> Result<Tree> {
22    let mut parser = Parser::new();
23    parser
24        .set_language(&language())
25        .context("loading the PHP grammar")?;
26    parser
27        .parse(source, None)
28        .context("tree-sitter failed to produce a parse tree")
29}
30
31fn language() -> Language {
32    tree_sitter_php::LANGUAGE_PHP.into()
33}
34
35/// `true` if any node in `tree` is a tree-sitter `ERROR` node - a syntax
36/// construct the grammar couldn't make sense of. Callers use this to
37/// decide whether a file is safe to mechanically convert at all, or should
38/// be flagged for manual review instead of risking a partial/misleading
39/// translation.
40pub fn has_syntax_error(tree: &Tree) -> bool {
41    fn walk(node: tree_sitter::Node) -> bool {
42        if node.is_error() {
43            return true;
44        }
45        let mut cursor = node.walk();
46        let children: Vec<_> = node.children(&mut cursor).collect();
47        children.into_iter().any(walk)
48    }
49    walk(tree.root_node())
50}
51
52/// One matched query capture: the capture's name (from `(... ) @name` in
53/// the `.scm` source) and its exact source text.
54#[derive(Debug, Clone)]
55pub struct Capture {
56    pub name: String,
57    pub text: String,
58}
59
60/// Runs `query_source` against `tree`, returning one `Vec<Capture>` per
61/// match (in source order) - the shape every converter builds its
62/// extraction logic on top of, so no converter module touches the raw
63/// `tree-sitter` API directly.
64pub fn run_query(tree: &Tree, source: &str, query_source: &str) -> Result<Vec<Vec<Capture>>> {
65    let query = Query::new(&language(), query_source).context("compiling tree-sitter query")?;
66    let capture_names = query.capture_names();
67    let mut cursor = QueryCursor::new();
68    let bytes = source.as_bytes();
69
70    let mut results = Vec::new();
71    let mut matches = cursor.matches(&query, tree.root_node(), bytes);
72    while let Some(m) = matches.next() {
73        let mut captures = Vec::with_capacity(m.captures.len());
74        for capture in m.captures {
75            let name = capture_names[capture.index as usize].to_string();
76            let text = capture
77                .node
78                .utf8_text(bytes)
79                .unwrap_or_default()
80                .to_string();
81            captures.push(Capture { name, text });
82        }
83        results.push(captures);
84    }
85    Ok(results)
86}
87
88/// Like [`run_query`], but returns the matched [`Node`]s under one named
89/// capture directly, rather than their text - for callers (migrations,
90/// routes) that need to keep walking the tree structurally from the match
91/// (e.g. into a closure argument's own body) instead of just reading the
92/// matched text.
93pub fn query_nodes<'a>(
94    tree: &'a Tree,
95    source: &str,
96    query_source: &str,
97    capture_name: &str,
98) -> Result<Vec<Node<'a>>> {
99    let query = Query::new(&language(), query_source).context("compiling tree-sitter query")?;
100    let Some(target_index) = query
101        .capture_names()
102        .iter()
103        .position(|name| *name == capture_name)
104    else {
105        return Ok(Vec::new());
106    };
107    let mut cursor = QueryCursor::new();
108    let bytes = source.as_bytes();
109    let mut results = Vec::new();
110    let mut matches = cursor.matches(&query, tree.root_node(), bytes);
111    while let Some(m) = matches.next() {
112        for capture in m.captures {
113            if capture.index as usize == target_index {
114                results.push(capture.node);
115            }
116        }
117    }
118    Ok(results)
119}
120
121/// Convenience for the common case: a match's single capture text by name
122/// (`None` if that capture didn't fire in this match - some captures in a
123/// query are conditional on optional syntax, e.g. `->nullable()`).
124pub fn capture<'a>(captures: &'a [Capture], name: &str) -> Option<&'a str> {
125    captures
126        .iter()
127        .find(|c| c.name == name)
128        .map(|c| c.text.as_str())
129}
130
131/// Every capture matching `name`, in source order - for queries where a
132/// construct can repeat within one match (e.g. every `->method(...)` call
133/// chained off one Blueprint column).
134pub fn captures_named<'a>(captures: &'a [Capture], name: &str) -> Vec<&'a str> {
135    captures
136        .iter()
137        .filter(|c| c.name == name)
138        .map(|c| c.text.as_str())
139        .collect()
140}
141
142/// Strips a PHP single- or double-quoted string literal's surrounding
143/// quotes. Laravel source is overwhelmingly single-quoted string literals
144/// for route paths/table names/column names - this doesn't attempt real
145/// PHP string-escape unescaping (`\'`, `\n`, interpolation), since none of
146/// that shows up in the mechanically-regular constructs Phase 1 converts
147/// (a route path, a column name, a config key are never written with
148/// embedded escapes or interpolation in practice).
149pub fn unquote(literal: &str) -> String {
150    let trimmed = literal.trim();
151    if trimmed.len() >= 2 {
152        let bytes = trimmed.as_bytes();
153        let first = bytes[0];
154        let last = bytes[bytes.len() - 1];
155        if (first == b'\'' && last == b'\'') || (first == b'"' && last == b'"') {
156            return trimmed[1..trimmed.len() - 1].to_string();
157        }
158    }
159    trimmed.to_string()
160}
161
162/// One link in a fluent method-call chain - `$table->string('x')` or
163/// `Route::get('/x', ...)` (a [`scoped_call_expression`], `scope: Some`)
164/// vs. `->nullable()`/`->name(...)` (a [`member_call_expression`] chained
165/// off a preceding call, `scope: None`).
166///
167/// [`scoped_call_expression`]: https://github.com/tree-sitter/tree-sitter-php
168/// [`member_call_expression`]: https://github.com/tree-sitter/tree-sitter-php
169#[derive(Debug, Clone)]
170pub struct CallStep {
171    pub scope: Option<String>,
172    pub method: String,
173    /// Each argument's raw source text, still exactly as written (a
174    /// string literal still quoted, `Foo::class` verbatim, an inline
175    /// closure's full source) - callers that need an unquoted string call
176    /// [`unquote`] themselves; callers that need to recurse into a closure
177    /// argument's structure use [`argument_node`] on the original node
178    /// instead of this field.
179    pub args: Vec<String>,
180}
181
182/// Walks a call-chain node (nested `member_call_expression`s wrapping one
183/// base `scoped_call_expression`, e.g.
184/// `Route::get('/x', $h)->name('x')->middleware($m)`) from the base of the
185/// chain outward. Returns `None` if `node` isn't a call-chain node at all.
186/// Used by both `migrations.rs` ($table->id()->nullable() chains) and
187/// `routes.rs` (Route::get(...)->name(...) chains) - the two constructs
188/// this phase converts that both need arbitrary-depth chain unwrapping,
189/// which tree-sitter's query language can't express in one fixed pattern.
190pub fn walk_call_chain(node: Node, source: &str) -> Option<Vec<CallStep>> {
191    let bytes = source.as_bytes();
192    match node.kind() {
193        "member_call_expression" => {
194            let object = node.child_by_field_name("object")?;
195            let mut chain = walk_call_chain(object, source).unwrap_or_default();
196            let name = node
197                .child_by_field_name("name")?
198                .utf8_text(bytes)
199                .ok()?
200                .to_string();
201            chain.push(CallStep {
202                scope: None,
203                method: name,
204                args: call_argument_texts(node, bytes),
205            });
206            Some(chain)
207        }
208        "scoped_call_expression" => {
209            let scope = node
210                .child_by_field_name("scope")?
211                .utf8_text(bytes)
212                .ok()?
213                .to_string();
214            let name = node
215                .child_by_field_name("name")?
216                .utf8_text(bytes)
217                .ok()?
218                .to_string();
219            Some(vec![CallStep {
220                scope: Some(scope),
221                method: name,
222                args: call_argument_texts(node, bytes),
223            }])
224        }
225        _ => None,
226    }
227}
228
229/// Every direct child of `node`, materialized eagerly so the borrow of a
230/// short-lived local `TreeCursor` never has to outlive the function that
231/// created it - `Node` itself is `Copy` and carries the tree's own
232/// lifetime, independent of whatever cursor was used to reach it.
233fn children_vec(node: Node) -> Vec<Node> {
234    let mut cursor = node.walk();
235    let children: Vec<Node> = node.children(&mut cursor).collect();
236    children
237}
238
239/// The single expression a wrapping node's first child holds - used to
240/// unwrap an `argument` node (which always wraps exactly one expression)
241/// or an `expression_statement` (ditto).
242fn first_child(node: Node) -> Option<Node> {
243    children_vec(node).into_iter().next()
244}
245
246/// Every **direct** child of `node` with the given kind - for a caller
247/// that already has a specific node in hand (e.g. one particular
248/// `rules()` method's own array literal, found via [`find_ancestor`]) and
249/// wants its immediate entries, not a fresh tree-wide query. A tree-wide
250/// query anchored only by node *kind* (no specific node identity) risks
251/// also matching same-shaped nodes nested arbitrarily deeper in the same
252/// subtree (e.g. an array-form rule value like `['required', 'max:255']`
253/// has its own `array_element_initializer` children, which a naive
254/// `(array_element_initializer) @entry` query run from the tree root
255/// would also match) - direct-children iteration has no such risk since
256/// it only ever looks at `node`'s own immediate children.
257pub fn direct_children_of_kind<'a>(node: Node<'a>, kind: &str) -> Vec<Node<'a>> {
258    children_vec(node)
259        .into_iter()
260        .filter(|c| c.kind() == kind)
261        .collect()
262}
263
264fn call_argument_texts(node: Node, bytes: &[u8]) -> Vec<String> {
265    let Some(arguments) = node.child_by_field_name("arguments") else {
266        return Vec::new();
267    };
268    children_vec(arguments)
269        .into_iter()
270        .filter(|c| c.kind() == "argument")
271        .filter_map(|arg| first_child(arg).map(|expr| text(expr, bytes)))
272        .collect()
273}
274
275fn text(node: Node, bytes: &[u8]) -> String {
276    node.utf8_text(bytes).unwrap_or_default().to_string()
277}
278
279/// The raw (unwrapped-from-`argument`) expression node at position
280/// `index` of `node`'s call arguments - used instead of [`CallStep::args`]
281/// when a caller needs to recurse into an argument's own structure (e.g.
282/// `Route::middleware(...)->group(function () { ... })`'s closure body),
283/// not just its source text.
284pub fn argument_node(node: Node, index: usize) -> Option<Node> {
285    let arguments = node.child_by_field_name("arguments")?;
286    let nth = children_vec(arguments)
287        .into_iter()
288        .filter(|c| c.kind() == "argument")
289        .nth(index)?;
290    first_child(nth)
291}
292
293/// Every top-level `expression_statement`'s inner expression node, directly
294/// inside `body` (a `compound_statement`, e.g. an anonymous function's
295/// block) - used to enumerate each `$table->...;` line in a migration
296/// closure, or each `Route::...;` line inside a `->group(...)` closure.
297pub fn statement_expressions(body: Node) -> Vec<Node> {
298    children_vec(body)
299        .into_iter()
300        .filter(|c| c.kind() == "expression_statement")
301        .filter_map(first_child)
302        .collect()
303}
304
305/// The `body` field of an `anonymous_function` node (itself a
306/// `compound_statement`) - `None` if `node` isn't an anonymous function.
307pub fn closure_body(node: Node) -> Option<Node> {
308    if node.kind() != "anonymous_function" {
309        return None;
310    }
311    node.child_by_field_name("body")
312}
313
314/// Walks upward from `node` to the nearest ancestor of kind `kind` -
315/// used instead of a query predicate (e.g. matching a `rules()` method
316/// declaration by name) when it's simpler to query broadly for a
317/// structural shape and then check/climb from each match than to encode
318/// the constraint in the query itself. `None` if no such ancestor exists.
319pub fn find_ancestor<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
320    let mut current = node.parent();
321    while let Some(candidate) = current {
322        if candidate.kind() == kind {
323            return Some(candidate);
324        }
325        current = candidate.parent();
326    }
327    None
328}
329
330/// The `method_declaration` named `method_name` inside the `class_
331/// declaration` named `class_name` - queries broadly for every
332/// `method_declaration` by kind, then filters by name and climbs to its
333/// enclosing class via [`find_ancestor`] (the same "query broadly, check/
334/// climb from each match" shape `requests.rs` already established for
335/// `rules()`, rather than trying to correlate a class-name capture and a
336/// method-name capture from one query - this crate's query helpers only
337/// return nodes for one named capture at a time).
338pub fn find_method<'a>(
339    tree: &'a Tree,
340    source: &str,
341    class_name: &str,
342    method_name: &str,
343) -> Option<Node<'a>> {
344    let query = r#"(method_declaration name: (name) @name) @method"#;
345    let bytes = source.as_bytes();
346    let candidates = query_nodes(tree, source, query, "method").ok()?;
347
348    for method_node in candidates {
349        let name_node = method_node.child_by_field_name("name")?;
350        if name_node.utf8_text(bytes).ok()? != method_name {
351            continue;
352        }
353        let class_decl = find_ancestor(method_node, "class_declaration")?;
354        let class_name_node = class_decl.child_by_field_name("name")?;
355        if class_name_node.utf8_text(bytes).ok()? == class_name {
356            return Some(method_node);
357        }
358    }
359    None
360}
361
362/// The single expression a `return_statement` wraps - `None` if `node`
363/// isn't a return statement, or it's a bare `return;` with nothing to
364/// return.
365pub fn return_expression(node: Node) -> Option<Node> {
366    if node.kind() != "return_statement" {
367        return None;
368    }
369    node.named_child(0)
370}
371
372/// Renders a method/closure `body` node's original PHP source as a
373/// comment block - the shared "preserve, never translate" primitive used
374/// by `controllers.rs`/`policies.rs`/`jobs.rs` for exactly the same
375/// purpose (a reference for whoever ports the real logic by hand). Strips
376/// the wrapping `{ }` before splitting into lines - a single-line body
377/// (`{ return $x; }`) has both braces and the statement on one physical
378/// line, so relying on `.lines()` alone to separate them (as a
379/// multi-line body's own formatting naturally does) wouldn't work.
380pub fn body_as_comment(body: Node, source: &str) -> String {
381    let text = body.utf8_text(source.as_bytes()).unwrap_or("");
382    let inner = text
383        .trim()
384        .strip_prefix('{')
385        .unwrap_or(text)
386        .strip_suffix('}')
387        .unwrap_or(text)
388        .trim();
389    let mut out = String::from(
390        "    // Original Laravel method body, preserved for reference - not translated:\n",
391    );
392    for line in inner.lines() {
393        out.push_str(&format!("    // {}\n", line.trim()));
394    }
395    out
396}
397
398/// The `class_declaration` named `class_name`, anywhere in `tree` - the
399/// shared "find a class by name" primitive every Phase 3 converter needs
400/// (models, controllers, policies, events, jobs all start here).
401pub fn find_class<'a>(tree: &'a Tree, source: &str, class_name: &str) -> Option<Node<'a>> {
402    let query = r#"(class_declaration name: (name) @name) @class"#;
403    let bytes = source.as_bytes();
404    let candidates = query_nodes(tree, source, query, "class").ok()?;
405    candidates.into_iter().find(|node| {
406        node.child_by_field_name("name")
407            .and_then(|n| n.utf8_text(bytes).ok())
408            == Some(class_name)
409    })
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn parses_a_simple_php_file_without_error() {
418        let tree = parse("<?php\n\n$x = 1;\n").unwrap();
419        assert!(!has_syntax_error(&tree));
420    }
421
422    #[test]
423    fn detects_a_syntax_error() {
424        let tree = parse("<?php\n\nRoute::get('/x', [PostController::class 'index']);\n").unwrap();
425        assert!(has_syntax_error(&tree));
426    }
427
428    #[test]
429    fn find_method_locates_a_method_by_class_and_name() {
430        let source = "<?php\nclass Post {\n    public function index() { return 1; }\n}\nclass User {\n    public function index() { return 2; }\n}\n";
431        let tree = parse(source).unwrap();
432        let method = find_method(&tree, source, "User", "index").unwrap();
433        let body = method.child_by_field_name("body").unwrap();
434        assert!(body
435            .utf8_text(source.as_bytes())
436            .unwrap()
437            .contains("return 2"));
438    }
439
440    #[test]
441    fn find_method_returns_none_for_a_missing_method() {
442        let source = "<?php\nclass Post {\n    public function index() {}\n}\n";
443        let tree = parse(source).unwrap();
444        assert!(find_method(&tree, source, "Post", "show").is_none());
445    }
446
447    #[test]
448    fn find_class_locates_a_class_by_name() {
449        let source = "<?php\nclass Post {}\nclass User {}\n";
450        let tree = parse(source).unwrap();
451        let class = find_class(&tree, source, "User").unwrap();
452        assert_eq!(class.kind(), "class_declaration");
453    }
454
455    #[test]
456    fn find_class_returns_none_for_a_missing_class() {
457        let source = "<?php\nclass Post {}\n";
458        let tree = parse(source).unwrap();
459        assert!(find_class(&tree, source, "User").is_none());
460    }
461
462    #[test]
463    fn return_expression_unwraps_a_return_statement() {
464        let source = "<?php\nclass X {\n    public function f() { return $this->hasMany(Post::class); }\n}\n";
465        let tree = parse(source).unwrap();
466        let method = find_method(&tree, source, "X", "f").unwrap();
467        let body = method.child_by_field_name("body").unwrap();
468
469        // The return statement isn't an expression_statement, so
470        // statement_expressions (which only unwraps expression_statement)
471        // finds nothing here - confirms the two are genuinely different
472        // constructs, not overlapping unwrap targets.
473        assert!(statement_expressions(body).is_empty());
474
475        let return_stmt = direct_children_of_kind(body, "return_statement")
476            .into_iter()
477            .next()
478            .unwrap();
479        let expr = return_expression(return_stmt).unwrap();
480        assert_eq!(expr.kind(), "member_call_expression");
481    }
482
483    #[test]
484    fn unquote_strips_single_and_double_quotes() {
485        assert_eq!(unquote("'posts'"), "posts");
486        assert_eq!(unquote("\"posts\""), "posts");
487        assert_eq!(unquote("posts"), "posts");
488    }
489
490    #[test]
491    fn walk_call_chain_unwraps_a_member_call_chain() {
492        let source = "<?php\n\n$table->foreignId('user_id')->constrained()->nullable();\n";
493        let tree = parse(source).unwrap();
494        // program -> expression_statement -> member_call_expression (the outermost)
495        let program = tree.root_node();
496        let stmt = program.child(1).unwrap();
497        let expr = stmt.child(0).unwrap();
498        let chain = walk_call_chain(expr, source).unwrap();
499        assert_eq!(chain.len(), 3);
500        assert_eq!(chain[0].method, "foreignId");
501        assert_eq!(chain[0].args, vec!["'user_id'".to_string()]);
502        assert_eq!(chain[1].method, "constrained");
503        assert_eq!(chain[2].method, "nullable");
504    }
505
506    #[test]
507    fn walk_call_chain_captures_scope_on_the_base_call() {
508        let source = "<?php\n\nRoute::get('/posts', $h)->name('posts.index');\n";
509        let tree = parse(source).unwrap();
510        let program = tree.root_node();
511        let stmt = program.child(1).unwrap();
512        let expr = stmt.child(0).unwrap();
513        let chain = walk_call_chain(expr, source).unwrap();
514        assert_eq!(chain.len(), 2);
515        assert_eq!(chain[0].scope.as_deref(), Some("Route"));
516        assert_eq!(chain[0].method, "get");
517        assert_eq!(chain[1].scope, None);
518        assert_eq!(chain[1].method, "name");
519        assert_eq!(chain[1].args, vec!["'posts.index'".to_string()]);
520    }
521
522    #[test]
523    fn run_query_finds_a_static_method_call() {
524        let source = "<?php\n\nRoute::get('/posts', [PostController::class, 'index']);\n";
525        let tree = parse(source).unwrap();
526        let query = r#"
527            (scoped_call_expression
528                scope: (name) @class
529                name: (name) @method) @call
530        "#;
531        let matches = run_query(&tree, source, query).unwrap();
532        assert!(!matches.is_empty());
533        let first = &matches[0];
534        assert_eq!(capture(first, "class"), Some("Route"));
535        assert_eq!(capture(first, "method"), Some("get"));
536    }
537}