Skip to main content

rust_anything/lang/
php.rs

1//! PHP: composer.json packages and PSR-4 roots, `require`/`use` imports, risks, the
2//! Composer-to-crate table, and exports (functions and public static methods) with native and
3//! phpdoc types mapped into the TS-like type dialect.
4
5use std::collections::HashMap;
6use std::path::Path;
7
8use anyhow::Result;
9use serde_json::Value;
10use tree_sitter::Node;
11
12use super::syntax::{self, named_children, text};
13use crate::risks::{Risk, regex_needs_fancy};
14use crate::ts::deps::CrateMatch;
15use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
16use crate::ts::exports::{ExportedFn, Param};
17use crate::ts::scan::{FileFacts, Import};
18
19fn language() -> tree_sitter::Language {
20    tree_sitter_php::LANGUAGE_PHP.into()
21}
22
23const SKIP_DIRS: &[&str] = &[
24    "vendor",
25    "node_modules",
26    "var",
27    "storage",
28    "cache",
29    "target",
30    ".phpunit.cache",
31];
32
33// ---- discovery -------------------------------------------------------------------------------
34
35/// Composer packages that are PHP itself or its extensions, not dependencies to port.
36fn is_platform(name: &str) -> bool {
37    name == "php" || name.starts_with("ext-") || name.starts_with("lib-") || !name.contains('/')
38}
39
40/// `require` and `require-dev` package names, and the first PSR-4 source folder.
41fn composer(text: &str) -> (Option<String>, Vec<String>, Vec<String>, Option<String>) {
42    let Ok(doc) = serde_json::from_str::<Value>(text) else {
43        return (None, Vec::new(), Vec::new(), None);
44    };
45    let names = |key: &str| -> Vec<String> {
46        doc[key]
47            .as_object()
48            .map(|o| o.keys().filter(|k| !is_platform(k)).cloned().collect())
49            .unwrap_or_default()
50    };
51    let src = doc["autoload"]["psr-4"].as_object().and_then(|o| {
52        o.values().find_map(|v| match v {
53            Value::String(s) => Some(s.trim_end_matches('/').to_string()),
54            Value::Array(a) => a
55                .first()
56                .and_then(Value::as_str)
57                .map(|s| s.trim_end_matches('/').to_string()),
58            _ => None,
59        })
60    });
61    (
62        doc["name"].as_str().map(str::to_string),
63        names("require"),
64        names("require-dev"),
65        src,
66    )
67}
68
69/// The PSR-4 namespaces of `autoload` and `autoload-dev`: the project's own code.
70fn own_namespaces(text: &str) -> Vec<String> {
71    let Ok(doc) = serde_json::from_str::<Value>(text) else {
72        return Vec::new();
73    };
74    ["autoload", "autoload-dev"]
75        .iter()
76        .filter_map(|key| doc[key]["psr-4"].as_object())
77        .flat_map(|o| o.keys())
78        .map(|ns| ns.trim_matches('\\').to_string())
79        .filter(|ns| !ns.is_empty())
80        .collect()
81}
82
83pub fn discover(root: &Path) -> Result<Workspace> {
84    let mut packages: Vec<Package> = Vec::new();
85    let mut files = Vec::new();
86    let walker = crate::walk::filtered(root, |e| {
87        !(e.file_type().is_some_and(|t| t.is_dir())
88            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
89    })
90    .hidden(true)
91    .require_git(false)
92    .build();
93    for entry in walker.flatten() {
94        if !entry.file_type().is_some_and(|t| t.is_file()) {
95            continue;
96        }
97        let Ok(rel) = entry.path().strip_prefix(root) else {
98            continue;
99        };
100        let rel = rel.to_string_lossy().replace('\\', "/");
101        let name = rel.rsplit('/').next().unwrap_or(&rel);
102        let dir = rel
103            .rsplit_once('/')
104            .map_or(String::new(), |(d, _)| d.to_string());
105        if name == "composer.json" {
106            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
107            let (pkg_name, deps, dev, src) = composer(&text);
108            packages.push(Package {
109                name: pkg_name.unwrap_or_else(|| {
110                    if dir.is_empty() {
111                        root.file_name()
112                            .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
113                    } else {
114                        dir.clone()
115                    }
116                }),
117                src_root: match src {
118                    Some(s) if !s.is_empty() => join(&dir, &s),
119                    _ => dir.clone(),
120                },
121                dir,
122                deps,
123                dev_deps: dev,
124                namespaces: own_namespaces(&text),
125            });
126        } else if name.ends_with(".php") {
127            let is_test = name.ends_with("Test.php")
128                || name.ends_with("_test.php")
129                || rel
130                    .split('/')
131                    .any(|p| matches!(p, "tests" | "test" | "Tests" | "spec"));
132            files.push((
133                rel,
134                if is_test {
135                    FileKind::Test
136                } else {
137                    FileKind::Source
138                },
139            ));
140        }
141    }
142    if !packages.iter().any(|p| p.dir.is_empty()) {
143        packages.push(Package {
144            name: root
145                .file_name()
146                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
147            dir: String::new(),
148            src_root: if root.join("src").is_dir() {
149                "src".into()
150            } else {
151                String::new()
152            },
153            deps: Vec::new(),
154            dev_deps: Vec::new(),
155            namespaces: Vec::new(),
156        });
157    }
158    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
159    files.sort_by(|a, b| a.0.cmp(&b.0));
160    let files = files
161        .into_iter()
162        .map(|(path, kind)| {
163            let package = packages
164                .iter()
165                .enumerate()
166                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
167                .max_by_key(|(_, p)| p.dir.len())
168                .map_or(0, |(i, _)| i);
169            SourceFile {
170                path,
171                package,
172                kind,
173            }
174        })
175        .collect();
176    Ok(Workspace { packages, files })
177}
178
179fn join(dir: &str, rest: &str) -> String {
180    if dir.is_empty() {
181        rest.to_string()
182    } else {
183        format!("{dir}/{rest}")
184    }
185}
186
187// ---- risks and imports -----------------------------------------------------------------------
188
189/// The pattern inside a PCRE string (`'/\w+/u'`, `"#a#i"`, `'~x~'`), without delimiters and flags.
190fn pcre_body(literal: &str) -> Option<&str> {
191    let s = literal.trim_matches(|c| c == '\'' || c == '"');
192    let open = s.chars().next()?;
193    let close = match open {
194        '(' => ')',
195        '{' => '}',
196        '[' => ']',
197        '<' => '>',
198        c if !c.is_alphanumeric() && c != '\\' && !c.is_whitespace() => c,
199        _ => return None,
200    };
201    let end = s.rfind(close)?;
202    (end > 0).then(|| &s[open.len_utf8()..end])
203}
204
205/// The path a `require`/`include` names: `'x.php'` or `__DIR__ . '/x.php'`.
206fn include_target(arg: Node, source: &str) -> Option<String> {
207    let literal = |n: Node| -> Option<String> {
208        matches!(n.kind(), "string" | "encapsed_string")
209            .then(|| {
210                text(n, source)
211                    .trim_matches(|c| c == '\'' || c == '"')
212                    .to_string()
213            })
214            .filter(|s| !s.contains('$'))
215    };
216    if let Some(s) = literal(arg) {
217        return Some(if s.starts_with('/') || s.starts_with('.') {
218            s
219        } else {
220            format!("./{s}")
221        });
222    }
223    if arg.kind() == "binary_expression" {
224        let left = arg.child_by_field_name("left")?;
225        let right = arg.child_by_field_name("right")?;
226        if text(left, source) == "__DIR__" {
227            return literal(right).map(|s| format!(".{s}"));
228        }
229    }
230    None
231}
232
233fn operator<'a>(node: Node, source: &'a str) -> &'a str {
234    node.child_by_field_name("operator").map_or_else(
235        || {
236            let mut cursor = node.walk();
237            node.children(&mut cursor)
238                .find(|c| !c.is_named())
239                .map_or("", |c| text(c, source))
240        },
241        |o| text(o, source),
242    )
243}
244
245const REFLECTION: &[&str] = &[
246    "method_exists",
247    "property_exists",
248    "function_exists",
249    "class_exists",
250    "get_class",
251    "get_object_vars",
252    "call_user_func",
253    "call_user_func_array",
254    "is_callable",
255    "func_get_args",
256    "compact",
257    "extract",
258];
259
260pub fn scan(source: &str) -> FileFacts {
261    let mut facts = FileFacts {
262        loc: syntax::loc(source, crate::lang::Lang::Php),
263        ..FileFacts::default()
264    };
265    let Some(tree) = syntax::parse(&language(), source) else {
266        return facts;
267    };
268    let root = tree.root_node();
269    facts.parse_errors = usize::from(root.has_error());
270    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
271        facts
272            .risks
273            .entry(risk)
274            .or_default()
275            .push(syntax::line(node))
276    };
277    syntax::walk(root, |node| match node.kind() {
278        "require_expression"
279        | "require_once_expression"
280        | "include_expression"
281        | "include_once_expression" => {
282            match named_children(node)
283                .into_iter()
284                .next()
285                .and_then(|a| include_target(a, source))
286            {
287                Some(spec) => facts.imports.push(Import {
288                    specifier: spec,
289                    type_only: false,
290                    dynamic: false,
291                }),
292                None => add(&mut facts, Risk::DynamicCode, node),
293            }
294        }
295        "namespace_use_clause" => {
296            let name = node
297                .named_child(0)
298                .map_or_else(|| text(node, source), |n| text(n, source));
299            let prefix = node
300                .parent()
301                .filter(|p| p.kind() == "namespace_use_group")
302                .and_then(|g| g.parent())
303                .and_then(|d| {
304                    named_children(d)
305                        .into_iter()
306                        .find(|n| n.kind() == "namespace_name")
307                })
308                .map(|p| format!("{}\\", text(p, source)))
309                .unwrap_or_default();
310            facts.imports.push(Import {
311                specifier: format!("{prefix}{}", name.trim_start_matches('\\')),
312                type_only: false,
313                dynamic: false,
314            });
315        }
316        "function_call_expression" => {
317            let callee = node
318                .child_by_field_name("function")
319                .map_or("", |f| text(f, source))
320                .trim_start_matches('\\');
321            match callee {
322                "eval" | "create_function" | "assert" => add(&mut facts, Risk::DynamicCode, node),
323                c if REFLECTION.contains(&c) => add(&mut facts, Risk::Reflection, node),
324                c if c.starts_with("preg_") => {
325                    let pattern = node
326                        .child_by_field_name("arguments")
327                        .and_then(|a| named_children(a).into_iter().next())
328                        .and_then(|a| a.named_child(0));
329                    match pattern.filter(|p| matches!(p.kind(), "string" | "encapsed_string")) {
330                        Some(p) if text(p, source).contains('$') => {
331                            add(&mut facts, Risk::DynamicRegex, node)
332                        }
333                        Some(p) => {
334                            if pcre_body(text(p, source)).is_some_and(|b| {
335                                regex_needs_fancy(b, "") || b.contains("(?>") || b.contains("\\K")
336                            }) {
337                                add(&mut facts, Risk::RegexSyntax, node);
338                            }
339                        }
340                        None => add(&mut facts, Risk::DynamicRegex, node),
341                    }
342                }
343                "substr" | "strpos" | "strrpos" | "strlen" | "str_pad" | "substr_replace"
344                | "mb_substr" | "mb_strpos" | "mb_strlen" | "ucfirst" | "strtoupper"
345                | "strtolower" | "str_split" | "wordwrap" => {
346                    add(&mut facts, Risk::StringOffsets, node)
347                }
348                "intdiv" | "fmod" => add(&mut facts, Risk::DivisionSemantics, node),
349                "json_encode" | "json_decode" | "serialize" | "unserialize" => {
350                    add(&mut facts, Risk::Json, node)
351                }
352                "pcntl_fork" | "proc_open" | "curl_multi_exec" => {
353                    add(&mut facts, Risk::Concurrency, node)
354                }
355                "class_alias" | "runkit_function_redefine" | "uopz_set_return" => {
356                    add(&mut facts, Risk::Monkeypatching, node)
357                }
358                "array_map" | "array_filter" | "array_walk" | "array_reduce" | "usort"
359                | "uasort" | "uksort" => {
360                    facts.loops += 1;
361                    add(&mut facts, Risk::Callbacks, node);
362                }
363                "sort" | "asort" | "ksort" | "array_unique" | "array_keys" | "array_values" => {
364                    add(&mut facts, Risk::OrderedCollections, node)
365                }
366                _ => {}
367            }
368        }
369        "object_creation_expression" => {
370            let class = text(node, source);
371            if class.contains("Reflection") {
372                add(&mut facts, Risk::Reflection, node);
373            } else if class.contains("Fiber") || class.contains("parallel\\") {
374                add(&mut facts, Risk::Concurrency, node);
375            }
376        }
377        "dynamic_variable_name" => add(&mut facts, Risk::Reflection, node),
378        "method_declaration" => {
379            let name = node
380                .child_by_field_name("name")
381                .map_or("", |n| text(n, source));
382            if matches!(
383                name,
384                "__call" | "__callStatic" | "__get" | "__set" | "__isset" | "__unset"
385            ) {
386                add(&mut facts, Risk::Reflection, node);
387            }
388        }
389        "class_declaration" | "interface_declaration" | "trait_declaration" => {
390            if named_children(node)
391                .iter()
392                .any(|c| c.kind() == "base_clause")
393            {
394                add(&mut facts, Risk::ClassInheritance, node);
395            }
396        }
397        "use_declaration" => add(&mut facts, Risk::ClassInheritance, node),
398        "binary_expression" => match operator(node, source) {
399            "/" => add(&mut facts, Risk::NumberSemantics, node),
400            "%" => add(&mut facts, Risk::DivisionSemantics, node),
401            "**" | "<<" | "*" => add(&mut facts, Risk::IntegerSemantics, node),
402            "==" | "!=" | "<>" | "<=>" => add(&mut facts, Risk::DynamicTyping, node),
403            _ => {}
404        },
405        "array_creation_expression" => add(&mut facts, Risk::OrderedCollections, node),
406        "throw_expression" | "try_statement" => add(&mut facts, Risk::Exceptions, node),
407        "yield_expression" => add(&mut facts, Risk::Generators, node),
408        "anonymous_function" | "anonymous_function_creation_expression" | "arrow_function" => {
409            add(&mut facts, Risk::Callbacks, node)
410        }
411        "null" => add(&mut facts, Risk::NullReferences, node),
412        "foreach_statement" | "for_statement" | "while_statement" | "do_statement" => {
413            facts.loops += 1
414        }
415        _ => {}
416    });
417    facts
418}
419
420/// Namespace roots of common Composer packages: `use GuzzleHttp\Client` needs `guzzlehttp/guzzle`.
421const NAMESPACE_PACKAGES: &[(&str, &str)] = &[
422    ("GuzzleHttp", "guzzlehttp/guzzle"),
423    ("Monolog", "monolog/monolog"),
424    ("Carbon", "nesbot/carbon"),
425    ("Ramsey\\Uuid", "ramsey/uuid"),
426    ("Illuminate", "laravel/framework"),
427    ("Doctrine\\ORM", "doctrine/orm"),
428    ("Doctrine\\DBAL", "doctrine/dbal"),
429    ("Twig", "twig/twig"),
430    ("League\\CommonMark", "league/commonmark"),
431    ("League\\Csv", "league/csv"),
432    ("League\\Flysystem", "league/flysystem"),
433    ("Dotenv", "vlucas/phpdotenv"),
434    ("Firebase\\JWT", "firebase/php-jwt"),
435    ("Predis", "predis/predis"),
436    ("Slim", "slim/slim"),
437    ("PHPUnit", "phpunit/phpunit"),
438    ("Psr\\Log", "psr/log"),
439    ("Psr\\Http\\Message", "psr/http-message"),
440    ("Respect\\Validation", "respect/validation"),
441    ("Brick\\Math", "brick/math"),
442];
443
444/// The Composer package a namespace belongs to: `Symfony\Component\Yaml\Yaml` is
445/// `symfony/yaml`; otherwise from [`NAMESPACE_PACKAGES`], else the namespace root.
446fn package_of(spec: &str) -> String {
447    if let Some(rest) = spec.strip_prefix("Symfony\\Component\\") {
448        let component = rest.split('\\').next().unwrap_or(rest);
449        let mut kebab = String::new();
450        for (i, c) in component.chars().enumerate() {
451            if c.is_uppercase() && i > 0 {
452                kebab.push('-');
453            }
454            kebab.extend(c.to_lowercase());
455        }
456        return format!("symfony/{kebab}");
457    }
458    NAMESPACE_PACKAGES
459        .iter()
460        .find(|(ns, _)| spec == *ns || spec.starts_with(&format!("{ns}\\")))
461        .map_or_else(
462            || spec.split('\\').next().unwrap_or(spec).to_string(),
463            |(_, p)| (*p).to_string(),
464        )
465}
466
467pub fn resolve(
468    from: &str,
469    spec: &str,
470    index: &HashMap<&str, usize>,
471    ws: &Workspace,
472) -> super::Resolution {
473    if spec.starts_with("./") || spec.starts_with("../") || spec.ends_with(".php") {
474        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
475        let rel = spec.trim_start_matches("./");
476        if let Some(path) = normalize(&join(dir, rel))
477            && let Some(i) = index.get(path.as_str())
478        {
479            return super::Resolution::File(*i);
480        }
481        return super::Resolution::Unresolved;
482    }
483    // PSR-4: `App\Text\Slug` is `<src>/Text/Slug.php` for the `App\` prefix; the prefix is
484    // unknown here, so try each tail of the namespace under each package's source root.
485    let parts: Vec<&str> = spec.split('\\').filter(|p| !p.is_empty()).collect();
486    for p in &ws.packages {
487        for skip in 0..parts.len() {
488            let candidate = join(&p.src_root, &format!("{}.php", parts[skip..].join("/")));
489            if let Some(i) = index.get(candidate.as_str()) {
490                return super::Resolution::File(*i);
491            }
492        }
493    }
494    let own = |ns: &String| {
495        let spec = spec.trim_start_matches('\\');
496        spec == ns || spec.starts_with(&format!("{ns}\\"))
497    };
498    if ws.packages.iter().flat_map(|p| &p.namespaces).any(own) {
499        return super::Resolution::Unresolved;
500    }
501    if parts.len() <= 1 {
502        return super::Resolution::Stdlib;
503    }
504    super::Resolution::External(package_of(spec))
505}
506
507fn normalize(path: &str) -> Option<String> {
508    let mut parts: Vec<&str> = Vec::new();
509    for part in path.split('/') {
510        match part {
511            "" | "." => {}
512            ".." => {
513                parts.pop()?;
514            }
515            _ => parts.push(part),
516        }
517    }
518    Some(parts.join("/"))
519}
520
521/// Rust counterparts of common Composer packages.
522pub fn lookup(package: &str) -> Option<CrateMatch> {
523    crate::crates::find("php", package)
524}
525
526// ---- exports ---------------------------------------------------------------------------------
527
528/// A PHP type (native or phpdoc: `?int`, `string|null`, `int[]`, `array<string, int>`,
529/// `list<string>`) in the dialect.
530pub fn php_to_ts(t: &str) -> String {
531    let t = t.trim().trim_start_matches('\\');
532    if let Some(inner) = t.strip_prefix('?') {
533        return format!("{} | undefined", php_to_ts(inner));
534    }
535    let parts = split_top(t, '|');
536    if parts.len() > 1 {
537        let mapped: Vec<String> = parts.iter().map(|p| php_to_ts(p)).collect();
538        return mapped.join(" | ");
539    }
540    if let Some(inner) = t.strip_suffix("[]") {
541        let inner = php_to_ts(inner);
542        return if inner.contains(' ') {
543            format!("({inner})[]")
544        } else {
545            format!("{inner}[]")
546        };
547    }
548    for generic in [
549        "list<",
550        "array<",
551        "iterable<",
552        "non-empty-list<",
553        "non-empty-array<",
554    ] {
555        if let Some(inner) = t.strip_prefix(generic).and_then(|r| r.strip_suffix('>')) {
556            let args = split_top(inner, ',');
557            return match args.as_slice() {
558                [v] => format!("{}[]", php_to_ts(v)),
559                [k, v] if php_to_ts(k) == "string" => format!("Record<string, {}>", php_to_ts(v)),
560                [k, v] if php_to_ts(k) == "int" => format!("{}[]", php_to_ts(v)),
561                _ => "unknown".into(),
562            };
563        }
564    }
565    match t.to_ascii_lowercase().as_str() {
566        "string" | "non-empty-string" | "class-string" | "numeric-string" => "string".into(),
567        "int" | "integer" | "positive-int" | "negative-int" | "non-negative-int" => "int".into(),
568        "float" | "double" => "number".into(),
569        "bool" | "boolean" | "true" | "false" => "boolean".into(),
570        "null" | "void" => "undefined".into(),
571        "array" | "iterable" => "unknown[] | Record<string, unknown>".into(),
572        _ => "unknown".into(),
573    }
574}
575
576/// A tag body split into its type and the rest: a type may hold a space (`array<string, int>`),
577/// so the split happens at the first space outside `<>`, `()`, `[]` and `{}`.
578fn type_and_rest(rest: &str) -> Option<(&str, &str)> {
579    let rest = rest.trim_start();
580    if rest.is_empty() {
581        return None;
582    }
583    let mut depth = 0i32;
584    for (i, c) in rest.char_indices() {
585        match c {
586            '<' | '(' | '[' | '{' => depth += 1,
587            '>' | ')' | ']' | '}' => depth -= 1,
588            c if c.is_whitespace() && depth == 0 => {
589                return Some((&rest[..i], rest[i..].trim_start()));
590            }
591            _ => {}
592        }
593    }
594    Some((rest.trim_end(), ""))
595}
596
597fn plain_type(t: &str) -> bool {
598    t.trim()
599        .trim_start_matches('?')
600        .split(['|', '&'])
601        .map(|p| p.trim().trim_matches(['(', ')']).to_ascii_lowercase())
602        .all(|p| {
603            matches!(
604                p.as_str(),
605                "int"
606                    | "float"
607                    | "string"
608                    | "bool"
609                    | "array"
610                    | "mixed"
611                    | "null"
612                    | "true"
613                    | "false"
614                    | "void"
615                    | "never"
616            )
617        })
618}
619
620fn bare_array(t: &str) -> bool {
621    t.trim()
622        .trim_start_matches('?')
623        .split('|')
624        .map(|p| p.trim().to_ascii_lowercase())
625        .all(|p| matches!(p.as_str(), "array" | "iterable" | "null"))
626}
627
628fn split_top(text: &str, sep: char) -> Vec<String> {
629    let mut out = Vec::new();
630    let mut depth = 0i32;
631    let mut current = String::new();
632    for c in text.chars() {
633        match c {
634            '<' | '{' | '(' | '[' => depth += 1,
635            '>' | '}' | ')' | ']' => depth -= 1,
636            _ if c == sep && depth == 0 => {
637                out.push(current.trim().to_string());
638                current.clear();
639                continue;
640            }
641            _ => {}
642        }
643        current.push(c);
644    }
645    if !current.trim().is_empty() {
646        out.push(current.trim().to_string());
647    }
648    out
649}
650
651/// The phpdoc block right above `node`, one tag per entry (`@param string $s`).
652fn phpdoc(node: Node, source: &str) -> Vec<String> {
653    let Some(prev) = node.prev_named_sibling().filter(|p| p.kind() == "comment") else {
654        return Vec::new();
655    };
656    let doc = text(prev, source);
657    if !doc.starts_with("/**") {
658        return Vec::new();
659    }
660    doc.trim_start_matches("/**")
661        .trim_end_matches("*/")
662        .split('@')
663        .skip(1)
664        .map(|tag| {
665            format!(
666                "@{}",
667                tag.lines()
668                    .map(|l| l.trim().trim_start_matches('*').trim())
669                    .collect::<Vec<_>>()
670                    .join(" ")
671                    .trim()
672            )
673        })
674        .collect()
675}
676
677/// The dialect type of a literal default (`'-'`, `0`, `1.5`, `true`, `[]`).
678fn literal_type(value: &str) -> Option<&'static str> {
679    let v = value.trim();
680    if v.starts_with('"') || v.starts_with('\'') {
681        Some("string")
682    } else if v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("false") {
683        Some("boolean")
684    } else if v.parse::<i64>().is_ok() {
685        Some("int")
686    } else if v.parse::<f64>().is_ok() {
687        Some("number")
688    } else if v.starts_with('[') {
689        Some("unknown[]")
690    } else {
691        None
692    }
693}
694
695fn function_fn(
696    path: &str,
697    receiver: &str,
698    sep: &str,
699    node: Node,
700    source: &str,
701) -> Option<ExportedFn> {
702    let name = text(node.child_by_field_name("name")?, source).to_string();
703    let doc = phpdoc(node, source);
704    let doc_param = |p: &str| {
705        doc.iter().find_map(|tag| {
706            let (t, rest) = type_and_rest(tag.strip_prefix("@param ")?)?;
707            let name = rest.split_whitespace().next()?;
708            (name == format!("${p}")).then(|| php_to_ts(t))
709        })
710    };
711    let doc_return = doc.iter().find_map(|tag| {
712        let (t, _) = type_and_rest(tag.strip_prefix("@return ")?)?;
713        Some(php_to_ts(t))
714    });
715    let returns = node
716        .child_by_field_name("return_type")
717        .map(|t| text(t, source))
718        .filter(|t| !(bare_array(t) && doc_return.is_some()))
719        .map(php_to_ts)
720        .filter(|t| t != "unknown")
721        .or(doc_return)
722        .unwrap_or_else(|| "unknown".into());
723    let mut blocker = None;
724    if name.starts_with("__") {
725        blocker = Some(format!("`{name}` is a magic method"));
726    }
727    let mut params = Vec::new();
728    let mut signature = String::new();
729    if let Some(list) = node.child_by_field_name("parameters") {
730        signature = text(list, source)
731            .trim_start_matches('(')
732            .trim_end_matches(')')
733            .to_string();
734        for p in named_children(list) {
735            let pname = p
736                .child_by_field_name("name")
737                .map(|n| text(n, source).trim_start_matches('$').to_string())
738                .unwrap_or_default();
739            match p.kind() {
740                "simple_parameter" => {}
741                "variadic_parameter" => {
742                    blocker.get_or_insert_with(|| "takes `...$args`".into());
743                    continue;
744                }
745                _ => {
746                    blocker.get_or_insert_with(|| format!("parameter `{}`", text(p, source)));
747                    continue;
748                }
749            }
750            if named_children(p)
751                .iter()
752                .any(|c| c.kind() == "reference_modifier")
753                || text(p, source).contains("&$")
754            {
755                blocker.get_or_insert_with(|| format!("takes `${pname}` by reference"));
756            }
757            let declared = p.child_by_field_name("type").map(|t| text(t, source));
758            if declared.is_some_and(|t| t.contains("callable") || t.contains("Closure")) {
759                blocker.get_or_insert_with(|| format!("takes a callable `${pname}`"));
760            }
761            if let Some(t) = declared.filter(|t| !plain_type(t)) {
762                blocker.get_or_insert_with(|| format!("takes an object `${pname}` (`{t}`)"));
763            }
764            let value = p
765                .child_by_field_name("default_value")
766                .map(|v| text(v, source).to_string());
767            let mut ts_type = declared
768                .filter(|t| !(bare_array(t) && doc_param(&pname).is_some()))
769                .map(php_to_ts)
770                .filter(|t| t != "unknown")
771                .or_else(|| doc_param(&pname))
772                .or_else(|| value.as_deref().and_then(literal_type).map(str::to_string))
773                .unwrap_or_else(|| "unknown".into());
774            if value
775                .as_deref()
776                .is_some_and(|v| v.eq_ignore_ascii_case("null"))
777                && !ts_type.contains("undefined")
778            {
779                ts_type = format!("{ts_type} | undefined");
780            }
781            params.push(Param {
782                name: pname,
783                ts_type,
784                optional: value.is_some(),
785                default: value,
786                ..Default::default()
787            });
788        }
789    }
790    if let Some(t) = node
791        .child_by_field_name("return_type")
792        .map(|t| text(t, source))
793        .filter(|t| !plain_type(t))
794    {
795        blocker.get_or_insert_with(|| format!("returns an object (`{t}`)"));
796    }
797    if let Some(body) = node.child_by_field_name("body") {
798        let mut yields = false;
799        syntax::walk(body, |n| yields |= n.kind() == "yield_expression");
800        if yields {
801            blocker.get_or_insert_with(|| "is a generator (`yield`)".into());
802        }
803    }
804    if sep == "::" {
805        blocker.get_or_insert_with(|| {
806            "a static method: the PHP bridge takes top-level functions for now".into()
807        });
808    }
809    let prefix = if receiver.is_empty() {
810        String::new()
811    } else {
812        format!("{receiver}{sep}")
813    };
814    Some(ExportedFn {
815        name: name.clone(),
816        file: path.to_string(),
817        line: syntax::line(node),
818        params,
819        returns,
820        prototype: Some(format!("{prefix}{name}({signature})")),
821        blocker,
822        ..Default::default()
823    })
824}
825
826pub(crate) fn declared_types(source: &str) -> Vec<String> {
827    let Some(tree) = syntax::parse(&language(), source) else {
828        return Vec::new();
829    };
830    let mut namespace = "";
831    let mut types = Vec::new();
832    for item in named_children(tree.root_node()) {
833        let mut items = if item.kind() == "namespace_definition" {
834            namespace = item
835                .child_by_field_name("name")
836                .map_or("", |name| text(name, source));
837            item.child_by_field_name("body")
838                .map_or_else(Vec::new, named_children)
839        } else {
840            vec![item]
841        };
842        while let Some(node) = items.pop() {
843            match node.kind() {
844                "class_declaration"
845                | "interface_declaration"
846                | "trait_declaration"
847                | "enum_declaration" => {
848                    if let Some(name) = node.child_by_field_name("name") {
849                        let name = text(name, source);
850                        types.push(if namespace.is_empty() {
851                            name.to_owned()
852                        } else {
853                            format!("{namespace}\\{name}")
854                        });
855                    }
856                }
857                "function_definition"
858                | "anonymous_function"
859                | "arrow_function"
860                | "anonymous_class" => {}
861                _ => items.extend(named_children(node)),
862            }
863        }
864    }
865    types
866}
867
868/// Functions (`Ns\name(...)`) and public static methods of classes (`Ns\Class::name(...)`).
869pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
870    if !path.ends_with(".php") {
871        return Vec::new();
872    }
873    let Some(tree) = syntax::parse(&language(), source) else {
874        return Vec::new();
875    };
876    let mut out = Vec::new();
877    let mut namespace = String::new();
878    let visit = |items: Vec<Node>, namespace: &mut String, out: &mut Vec<ExportedFn>| {
879        for item in items {
880            match item.kind() {
881                "namespace_definition" => {
882                    *namespace = item
883                        .child_by_field_name("name")
884                        .map(|n| text(n, source).to_string())
885                        .unwrap_or_default();
886                }
887                "function_definition" => {
888                    out.extend(function_fn(path, namespace, "\\", item, source));
889                }
890                "class_declaration" => {
891                    if named_children(item)
892                        .iter()
893                        .any(|c| c.kind() == "abstract_modifier")
894                    {
895                        continue;
896                    }
897                    let Some(class) = item.child_by_field_name("name") else {
898                        continue;
899                    };
900                    let class = text(class, source);
901                    let receiver = if namespace.is_empty() {
902                        class.to_string()
903                    } else {
904                        format!("{namespace}\\{class}")
905                    };
906                    for method in item
907                        .child_by_field_name("body")
908                        .map(named_children)
909                        .unwrap_or_default()
910                        .into_iter()
911                        .filter(|m| m.kind() == "method_declaration")
912                    {
913                        let mods: Vec<&str> = named_children(method)
914                            .iter()
915                            .filter(|c| c.kind().ends_with("_modifier"))
916                            .map(|c| text(*c, source))
917                            .collect();
918                        let public = !mods.iter().any(|m| matches!(*m, "private" | "protected"));
919                        if public && mods.contains(&"static") {
920                            out.extend(function_fn(path, &receiver, "::", method, source));
921                        }
922                    }
923                }
924                _ => {}
925            }
926        }
927    };
928    let root = tree.root_node();
929    for item in named_children(root) {
930        if item.kind() == "namespace_definition"
931            && let Some(body) = item.child_by_field_name("body")
932        {
933            namespace = item
934                .child_by_field_name("name")
935                .map(|n| text(n, source).to_string())
936                .unwrap_or_default();
937            visit(named_children(body), &mut namespace, &mut out);
938        } else {
939            visit(vec![item], &mut namespace, &mut out);
940        }
941    }
942    out.sort_by_key(|f| f.line);
943    out
944}
945
946#[cfg(test)]
947mod tests {
948    use super::*;
949
950    #[test]
951    fn a_phpdoc_type_with_a_space_keeps_its_arguments() {
952        // `array<string, int>` holds a space: splitting the tag on whitespace cut it in half.
953        assert_eq!(
954            type_and_rest("array<string, int> $counts"),
955            Some(("array<string, int>", "$counts"))
956        );
957        assert_eq!(type_and_rest("?int $x"), Some(("?int", "$x")));
958        assert_eq!(
959            type_and_rest("array{a: int, b: string} $x"),
960            Some(("array{a: int, b: string}", "$x"))
961        );
962        assert_eq!(type_and_rest("string"), Some(("string", "")));
963        assert_eq!(type_and_rest("   "), None);
964        assert_eq!(php_to_ts("array<string, int>"), "Record<string, int>");
965    }
966
967    const SRC: &str = r#"<?php
968declare(strict_types=1);
969namespace App\Text;
970use App\Util\Str;
971use GuzzleHttp\Client;
972use Symfony\Component\Yaml\Yaml;
973require_once __DIR__ . '/helpers.php';
974
975/**
976 * @param string $s
977 * @param list<string> $stop
978 * @return string
979 */
980function slugify(string $s, $stop = [], string $sep = '-', ?int $max = null): string {
981    if ($s === '') { throw new \InvalidArgumentException("empty"); }
982    $x = intdiv(7, 2) % 3;
983    return strtolower(preg_replace('/(?<=a)b/u', $sep, $s));
984}
985
986function words($text) { foreach (explode(' ', $text) as $w) { yield $w; } }
987
988final class Words extends Base {
989    public static function count(string $s, int ...$rest): int { return str_word_count($s); }
990    public static function scale($x, float $factor = 1.5) { return $x * $factor; }
991    private static function hidden() {}
992    public function instance() {}
993}
994eval('1;');
995"#;
996
997    #[test]
998    fn a_phpdoc_param_or_return_with_a_space_in_its_type_is_read_whole() {
999        // `@param array<string, int> $counts` holds a space inside the type: splitting the tag on
1000        // whitespace cut it to `array<string,` and the parameter came out `unknown`.
1001        let src = "<?php\n/**\n * @param array<string, int> $counts\n * @return array<string, int>\n */\nfunction double_counts(array $counts): array { return $counts; }\n";
1002        let fns = exports("src/counts.php", src);
1003        assert_eq!(fns.len(), 1);
1004        assert_eq!(fns[0].params[0].ts_type, "Record<string, int>");
1005        assert_eq!(fns[0].returns, "Record<string, int>");
1006        assert!(fns[0].blocker.is_none());
1007    }
1008
1009    #[test]
1010    fn maps_php_types() {
1011        assert_eq!(php_to_ts("?int"), "int | undefined");
1012        assert_eq!(php_to_ts("string|null"), "string | undefined");
1013        assert_eq!(php_to_ts("int[]"), "int[]");
1014        assert_eq!(php_to_ts("array<string, int>"), "Record<string, int>");
1015        assert_eq!(php_to_ts("list<float>"), "number[]");
1016        assert_eq!(php_to_ts("\\DateTime"), "unknown");
1017    }
1018
1019    #[test]
1020    fn finds_functions_and_static_methods() {
1021        let fns = exports("src/Text/slug.php", SRC);
1022        let protos: Vec<&str> = fns
1023            .iter()
1024            .map(|f| f.prototype.as_deref().unwrap_or(""))
1025            .collect();
1026        assert_eq!(
1027            protos,
1028            [
1029                "App\\Text\\slugify(string $s, $stop = [], string $sep = '-', ?int $max = null)",
1030                "App\\Text\\words($text)",
1031                "App\\Text\\Words::count(string $s, int ...$rest)",
1032                "App\\Text\\Words::scale($x, float $factor = 1.5)",
1033            ]
1034        );
1035        let slug = &fns[0];
1036        let types: Vec<&str> = slug.params.iter().map(|p| p.ts_type.as_str()).collect();
1037        assert_eq!(types, ["string", "string[]", "string", "int | undefined"]);
1038        assert_eq!(slug.returns, "string");
1039        assert!(slug.blocker.is_none());
1040        assert!(fns[1].blocker.as_deref().unwrap().contains("generator"));
1041        assert!(fns[2].blocker.as_deref().unwrap().contains("...$args"));
1042        assert_eq!(fns[3].params[1].ts_type, "number");
1043    }
1044
1045    #[test]
1046    fn resolves_import_names_from_a_group_use() {
1047        let facts = scan(
1048            r"<?php
1049namespace App;
1050use Vendor\Library\{One, Two as Alias, function helpers\trim_value};
1051use Other\Three;
1052",
1053        );
1054        assert_eq!(facts.parse_errors, 0);
1055        assert_eq!(
1056            facts
1057                .imports
1058                .iter()
1059                .map(|i| i.specifier.as_str())
1060                .collect::<Vec<_>>(),
1061            [
1062                "Vendor\\Library\\One",
1063                "Vendor\\Library\\Two",
1064                "Vendor\\Library\\helpers\\trim_value",
1065                "Other\\Three"
1066            ]
1067        );
1068    }
1069
1070    #[test]
1071    fn scans_imports_and_risks() {
1072        let facts = scan(SRC);
1073        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
1074        assert_eq!(
1075            specs,
1076            [
1077                "App\\Util\\Str",
1078                "GuzzleHttp\\Client",
1079                "Symfony\\Component\\Yaml\\Yaml",
1080                "./helpers.php"
1081            ]
1082        );
1083        for risk in [
1084            Risk::Exceptions,
1085            Risk::RegexSyntax,
1086            Risk::DivisionSemantics,
1087            Risk::Generators,
1088            Risk::ClassInheritance,
1089            Risk::DynamicCode,
1090            Risk::StringOffsets,
1091        ] {
1092            assert!(
1093                facts.risks.contains_key(&risk),
1094                "{risk:?}: {:?}",
1095                facts.risks
1096            );
1097        }
1098        assert_eq!(package_of("GuzzleHttp\\Client"), "guzzlehttp/guzzle");
1099        assert_eq!(
1100            package_of("Symfony\\Component\\HttpFoundation\\Request"),
1101            "symfony/http-foundation"
1102        );
1103        assert_eq!(pcre_body("'#a+#i'"), Some("a+"));
1104        assert_eq!(pcre_body("'{x}u'"), Some("x"));
1105    }
1106
1107    #[test]
1108    fn reads_composer() {
1109        let text = r#"{"name": "acme/tool", "require": {"php": ">=8.1", "ext-json": "*", "guzzlehttp/guzzle": "^7"},
1110               "require-dev": {"phpunit/phpunit": "^10"}, "autoload": {"psr-4": {"Acme\\": "src/"}},
1111               "autoload-dev": {"psr-4": {"Acme\\Tests\\": "tests/"}}}"#;
1112        let (name, deps, dev, src) = composer(text);
1113        assert_eq!(name.as_deref(), Some("acme/tool"));
1114        assert_eq!(deps, ["guzzlehttp/guzzle"]);
1115        assert_eq!(dev, ["phpunit/phpunit"]);
1116        assert_eq!(src.as_deref(), Some("src"));
1117        assert_eq!(own_namespaces(text), ["Acme", "Acme\\Tests"]);
1118    }
1119}