1use anyhow::{Context, Result};
15use streaming_iterator::StreamingIterator;
16use tree_sitter::{Language, Node, Parser, Query, QueryCursor, Tree};
17
18pub 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
35pub 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#[derive(Debug, Clone)]
55pub struct Capture {
56 pub name: String,
57 pub text: String,
58}
59
60pub 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
88pub 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
121pub 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
131pub 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
142pub 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#[derive(Debug, Clone)]
170pub struct CallStep {
171 pub scope: Option<String>,
172 pub method: String,
173 pub args: Vec<String>,
180}
181
182pub 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
229fn 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
239fn first_child(node: Node) -> Option<Node> {
243 children_vec(node).into_iter().next()
244}
245
246pub 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
279pub 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
293pub 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
305pub 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
314pub 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
330pub 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
362pub fn return_expression(node: Node) -> Option<Node> {
366 if node.kind() != "return_statement" {
367 return None;
368 }
369 node.named_child(0)
370}
371
372pub 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
398pub 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 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 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}