Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

75.5 KB
Raw Blame
//! PHP: composer.json packages and PSR-4 roots, `require`/`use` imports, risks, the
//! Composer-to-crate table, and exports (functions and public static methods) with native and
//! phpdoc types mapped into the TS-like type dialect.

use std::collections::HashMap;
use std::path::Path;

use anyhow::Result;
use serde_json::Value;
use tree_sitter::Node;

use super::syntax::{self, named_children, text};
use crate::risks::{Risk, regex_needs_fancy};
use crate::ts::deps::CrateMatch;
use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
use crate::ts::exports::{ExportedFn, Param};
use crate::ts::scan::{FileFacts, Import};

fn language() -> tree_sitter::Language {
    tree_sitter_php::LANGUAGE_PHP.into()
}

pub(crate) const SKIP_DIRS: &[&str] = &[
    "vendor",
    "node_modules",
    "var",
    "storage",
    "cache",
    "target",
    ".phpunit.cache",
];

// ---- discovery -------------------------------------------------------------------------------

/// Composer packages that are PHP itself or its extensions, not dependencies to port.
fn is_platform(name: &str) -> bool {
    name == "php" || name.starts_with("ext-") || name.starts_with("lib-") || !name.contains('/')
}

/// `require` and `require-dev` package names, and the first PSR-4 source folder.
fn composer(text: &str) -> (Option<String>, Vec<String>, Vec<String>, Option<String>) {
    let Ok(doc) = serde_json::from_str::<Value>(text) else {
        return (None, Vec::new(), Vec::new(), None);
    };
    let names = |key: &str| -> Vec<String> {
        doc[key]
            .as_object()
            .map(|o| o.keys().filter(|k| !is_platform(k)).cloned().collect())
            .unwrap_or_default()
    };
    let src = doc["autoload"]["psr-4"].as_object().and_then(|o| {
        o.values().find_map(|v| match v {
            Value::String(s) => Some(s.trim_end_matches('/').to_string()),
            Value::Array(a) => a
                .first()
                .and_then(Value::as_str)
                .map(|s| s.trim_end_matches('/').to_string()),
            _ => None,
        })
    });
    (
        doc["name"].as_str().map(str::to_string),
        names("require"),
        names("require-dev"),
        src,
    )
}

/// The PSR-4 namespaces of `autoload` and `autoload-dev`: the project's own code.
fn own_namespaces(text: &str) -> Vec<String> {
    let Ok(doc) = serde_json::from_str::<Value>(text) else {
        return Vec::new();
    };
    ["autoload", "autoload-dev"]
        .iter()
        .filter_map(|key| doc[key]["psr-4"].as_object())
        .flat_map(|o| o.keys())
        .map(|ns| ns.trim_matches('\\').to_string())
        .filter(|ns| !ns.is_empty())
        .collect()
}

pub fn discover(root: &Path) -> Result<Workspace> {
    let mut packages: Vec<Package> = Vec::new();
    let mut files = Vec::new();
    let walker = crate::walk::filtered(root, |e| {
        !(e.file_type().is_some_and(|t| t.is_dir())
            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
    })
    .hidden(true)
    .require_git(false)
    .build();
    for entry in walker.flatten() {
        if !entry.file_type().is_some_and(|t| t.is_file()) {
            continue;
        }
        let Ok(rel) = entry.path().strip_prefix(root) else {
            continue;
        };
        let rel = rel.to_string_lossy().replace('\\', "/");
        let name = rel.rsplit('/').next().unwrap_or(&rel);
        let dir = rel
            .rsplit_once('/')
            .map_or(String::new(), |(d, _)| d.to_string());
        if name == "composer.json" {
            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
            let text = super::without_bom(&text);
            let (pkg_name, deps, dev, src) = composer(text);
            packages.push(Package {
                name: pkg_name.unwrap_or_else(|| {
                    if dir.is_empty() {
                        root.file_name()
                            .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
                    } else {
                        dir.clone()
                    }
                }),
                src_root: match src {
                    Some(s) if !s.is_empty() => join(&dir, &s),
                    _ => dir.clone(),
                },
                dir,
                deps,
                dev_deps: dev,
                namespaces: own_namespaces(text),
            });
        } else if name.ends_with(".php") {
            let is_test = name.ends_with("Test.php")
                || name.ends_with("_test.php")
                || rel
                    .split('/')
                    .any(|p| matches!(p, "tests" | "test" | "Tests" | "spec"));
            files.push((
                rel,
                if is_test {
                    FileKind::Test
                } else {
                    FileKind::Source
                },
            ));
        }
    }
    if !packages.iter().any(|p| p.dir.is_empty()) {
        packages.push(Package {
            name: root
                .file_name()
                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
            dir: String::new(),
            src_root: if root.join("src").is_dir() {
                "src".into()
            } else {
                String::new()
            },
            deps: Vec::new(),
            dev_deps: Vec::new(),
            namespaces: Vec::new(),
        });
    }
    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
    files.sort_by(|a, b| a.0.cmp(&b.0));
    let files = files
        .into_iter()
        .map(|(path, kind)| {
            let package = packages
                .iter()
                .enumerate()
                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
                .max_by_key(|(_, p)| p.dir.len())
                .map_or(0, |(i, _)| i);
            SourceFile {
                path,
                package,
                kind,
            }
        })
        .collect();
    Ok(Workspace { packages, files })
}

fn join(dir: &str, rest: &str) -> String {
    if dir.is_empty() {
        rest.to_string()
    } else {
        format!("{dir}/{rest}")
    }
}

// ---- risks and imports -----------------------------------------------------------------------

/// The pattern inside a PCRE string (`'/\w+/u'`, `"#a#i"`, `'~x~'`), without delimiters and flags.
fn pcre_body(literal: &str) -> Option<&str> {
    let s = literal.trim_matches(|c| c == '\'' || c == '"');
    let open = s.chars().next()?;
    let close = match open {
        '(' => ')',
        '{' => '}',
        '[' => ']',
        '<' => '>',
        c if !c.is_alphanumeric() && c != '\\' && !c.is_whitespace() => c,
        _ => return None,
    };
    let end = s.rfind(close)?;
    (end > 0).then(|| &s[open.len_utf8()..end])
}

/// The path a `require`/`include` names: `'x.php'` or `__DIR__ . '/x.php'`.
fn include_target(arg: Node, source: &str) -> Option<String> {
    let literal = |n: Node| -> Option<String> {
        matches!(n.kind(), "string" | "encapsed_string")
            .then(|| {
                text(n, source)
                    .trim_matches(|c| c == '\'' || c == '"')
                    .to_string()
            })
            .filter(|s| !s.contains('$'))
    };
    if let Some(s) = literal(arg) {
        return Some(if s.starts_with('/') || s.starts_with('.') {
            s
        } else {
            format!("./{s}")
        });
    }
    if arg.kind() == "binary_expression" {
        let left = arg.child_by_field_name("left")?;
        let right = arg.child_by_field_name("right")?;
        if text(left, source) == "__DIR__" {
            return literal(right).map(|s| format!(".{s}"));
        }
    }
    None
}

fn operator<'a>(node: Node, source: &'a str) -> &'a str {
    node.child_by_field_name("operator").map_or_else(
        || {
            let mut cursor = node.walk();
            node.children(&mut cursor)
                .find(|c| !c.is_named())
                .map_or("", |c| text(c, source))
        },
        |o| text(o, source),
    )
}

const REFLECTION: &[&str] = &[
    "method_exists",
    "property_exists",
    "function_exists",
    "class_exists",
    "get_class",
    "get_object_vars",
    "call_user_func",
    "call_user_func_array",
    "is_callable",
    "func_get_args",
    "compact",
    "extract",
];

pub fn scan(source: &str) -> FileFacts {
    let mut facts = FileFacts {
        loc: syntax::loc(source, crate::lang::Lang::Php),
        ..FileFacts::default()
    };
    let Some(tree) = syntax::parse(&language(), source) else {
        return facts;
    };
    let root = tree.root_node();
    facts.parse_errors = usize::from(root.has_error());
    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
        facts
            .risks
            .entry(risk)
            .or_default()
            .push(syntax::line(node))
    };
    syntax::walk(root, |node| match node.kind() {
        "require_expression"
        | "require_once_expression"
        | "include_expression"
        | "include_once_expression" => {
            match named_children(node)
                .into_iter()
                .next()
                .and_then(|a| include_target(a, source))
            {
                Some(spec) => facts.imports.push(Import {
                    specifier: spec,
                    type_only: false,
                    dynamic: false,
                }),
                None => add(&mut facts, Risk::DynamicCode, node),
            }
        }
        "namespace_use_clause" => {
            let name = node
                .named_child(0)
                .map_or_else(|| text(node, source), |n| text(n, source));
            let prefix = node
                .parent()
                .filter(|p| p.kind() == "namespace_use_group")
                .and_then(|g| g.parent())
                .and_then(|d| {
                    named_children(d)
                        .into_iter()
                        .find(|n| n.kind() == "namespace_name")
                })
                .map(|p| format!("{}\\", text(p, source)))
                .unwrap_or_default();
            facts.imports.push(Import {
                specifier: format!("{prefix}{}", name.trim_start_matches('\\')),
                type_only: false,
                dynamic: false,
            });
        }
        "function_call_expression" => {
            let callee = node
                .child_by_field_name("function")
                .map_or("", |f| text(f, source))
                .trim_start_matches('\\');
            match callee {
                "eval" | "create_function" | "assert" => add(&mut facts, Risk::DynamicCode, node),
                c if REFLECTION.contains(&c) => add(&mut facts, Risk::Reflection, node),
                c if c.starts_with("preg_") => {
                    let pattern = node
                        .child_by_field_name("arguments")
                        .and_then(|a| named_children(a).into_iter().next())
                        .and_then(|a| a.named_child(0));
                    match pattern.filter(|p| matches!(p.kind(), "string" | "encapsed_string")) {
                        Some(p) if text(p, source).contains('$') => {
                            add(&mut facts, Risk::DynamicRegex, node)
                        }
                        Some(p) => {
                            if pcre_body(text(p, source)).is_some_and(|b| {
                                regex_needs_fancy(b, "") || b.contains("(?>") || b.contains("\\K")
                            }) {
                                add(&mut facts, Risk::RegexSyntax, node);
                            }
                        }
                        None => add(&mut facts, Risk::DynamicRegex, node),
                    }
                }
                "substr" | "strpos" | "strrpos" | "strlen" | "str_pad" | "substr_replace"
                | "mb_substr" | "mb_strpos" | "mb_strlen" | "ucfirst" | "strtoupper"
                | "strtolower" | "str_split" | "wordwrap" => {
                    add(&mut facts, Risk::StringOffsets, node)
                }
                "intdiv" | "fmod" => add(&mut facts, Risk::DivisionSemantics, node),
                "json_encode" | "json_decode" | "serialize" | "unserialize" => {
                    add(&mut facts, Risk::Json, node)
                }
                "pcntl_fork" | "proc_open" | "curl_multi_exec" => {
                    add(&mut facts, Risk::Concurrency, node)
                }
                "class_alias" | "runkit_function_redefine" | "uopz_set_return" => {
                    add(&mut facts, Risk::Monkeypatching, node)
                }
                "array_map" | "array_filter" | "array_walk" | "array_reduce" | "usort"
                | "uasort" | "uksort" => {
                    facts.loops += 1;
                    add(&mut facts, Risk::Callbacks, node);
                }
                "sort" | "asort" | "ksort" | "array_unique" | "array_keys" | "array_values" => {
                    add(&mut facts, Risk::OrderedCollections, node)
                }
                _ => {}
            }
        }
        "object_creation_expression" => {
            let class = text(node, source);
            if class.contains("Reflection") {
                add(&mut facts, Risk::Reflection, node);
            } else if class.contains("Fiber") || class.contains("parallel\\") {
                add(&mut facts, Risk::Concurrency, node);
            }
        }
        "dynamic_variable_name" => add(&mut facts, Risk::Reflection, node),
        "method_declaration" => {
            let name = node
                .child_by_field_name("name")
                .map_or("", |n| text(n, source));
            if matches!(
                name,
                "__call" | "__callStatic" | "__get" | "__set" | "__isset" | "__unset"
            ) {
                add(&mut facts, Risk::Reflection, node);
            }
        }
        "class_declaration" | "interface_declaration" | "trait_declaration" => {
            if named_children(node)
                .iter()
                .any(|c| c.kind() == "base_clause")
            {
                add(&mut facts, Risk::ClassInheritance, node);
            }
        }
        "use_declaration" => add(&mut facts, Risk::ClassInheritance, node),
        "binary_expression" => match operator(node, source) {
            "/" => add(&mut facts, Risk::NumberSemantics, node),
            "%" => add(&mut facts, Risk::DivisionSemantics, node),
            "**" | "<<" | "*" => add(&mut facts, Risk::IntegerSemantics, node),
            "==" | "!=" | "<>" | "<=>" => add(&mut facts, Risk::DynamicTyping, node),
            _ => {}
        },
        "array_creation_expression" => add(&mut facts, Risk::OrderedCollections, node),
        "throw_expression" | "try_statement" => add(&mut facts, Risk::Exceptions, node),
        "yield_expression" => add(&mut facts, Risk::Generators, node),
        "anonymous_function" | "anonymous_function_creation_expression" | "arrow_function" => {
            add(&mut facts, Risk::Callbacks, node)
        }
        "null" => add(&mut facts, Risk::NullReferences, node),
        "foreach_statement" | "for_statement" | "while_statement" | "do_statement" => {
            facts.loops += 1
        }
        _ => {}
    });
    facts
}

/// Namespace roots of common Composer packages: `use GuzzleHttp\Client` needs `guzzlehttp/guzzle`.
const NAMESPACE_PACKAGES: &[(&str, &str)] = &[
    ("GuzzleHttp", "guzzlehttp/guzzle"),
    ("Monolog", "monolog/monolog"),
    ("Carbon", "nesbot/carbon"),
    ("Ramsey\\Uuid", "ramsey/uuid"),
    ("Illuminate", "laravel/framework"),
    ("Doctrine\\ORM", "doctrine/orm"),
    ("Doctrine\\DBAL", "doctrine/dbal"),
    ("Twig", "twig/twig"),
    ("League\\CommonMark", "league/commonmark"),
    ("League\\Csv", "league/csv"),
    ("League\\Flysystem", "league/flysystem"),
    ("Dotenv", "vlucas/phpdotenv"),
    ("Firebase\\JWT", "firebase/php-jwt"),
    ("Predis", "predis/predis"),
    ("Slim", "slim/slim"),
    ("PHPUnit", "phpunit/phpunit"),
    ("Psr\\Log", "psr/log"),
    ("Psr\\Http\\Message", "psr/http-message"),
    ("Respect\\Validation", "respect/validation"),
    ("Brick\\Math", "brick/math"),
];

/// The Composer package a namespace belongs to: `Symfony\Component\Yaml\Yaml` is
/// `symfony/yaml`; otherwise from [`NAMESPACE_PACKAGES`], else the namespace root.
fn package_of(spec: &str) -> String {
    if let Some(rest) = spec.strip_prefix("Symfony\\Component\\") {
        let component = rest.split('\\').next().unwrap_or(rest);
        let mut kebab = String::new();
        for (i, c) in component.chars().enumerate() {
            if c.is_uppercase() && i > 0 {
                kebab.push('-');
            }
            kebab.extend(c.to_lowercase());
        }
        return format!("symfony/{kebab}");
    }
    NAMESPACE_PACKAGES
        .iter()
        .find(|(ns, _)| spec == *ns || spec.starts_with(&format!("{ns}\\")))
        .map_or_else(
            || spec.split('\\').next().unwrap_or(spec).to_string(),
            |(_, p)| (*p).to_string(),
        )
}

pub fn resolve(
    from: &str,
    spec: &str,
    index: &HashMap<&str, usize>,
    ws: &Workspace,
) -> super::Resolution {
    if spec.starts_with("./") || spec.starts_with("../") || spec.ends_with(".php") {
        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
        let rel = spec.trim_start_matches("./");
        if let Some(path) = normalize(&join(dir, rel))
            && let Some(i) = index.get(path.as_str())
        {
            return super::Resolution::File(*i);
        }
        return super::Resolution::Unresolved;
    }
    // PSR-4: `App\Text\Slug` is `<src>/Text/Slug.php` for the `App\` prefix; the prefix is
    // unknown here, so try each tail of the namespace under each package's source root.
    let parts: Vec<&str> = spec.split('\\').filter(|p| !p.is_empty()).collect();
    for p in &ws.packages {
        for skip in 0..parts.len() {
            let candidate = join(&p.src_root, &format!("{}.php", parts[skip..].join("/")));
            if let Some(i) = index.get(candidate.as_str()) {
                return super::Resolution::File(*i);
            }
        }
    }
    let own = |ns: &String| {
        let spec = spec.trim_start_matches('\\');
        spec == ns || spec.starts_with(&format!("{ns}\\"))
    };
    if ws.packages.iter().flat_map(|p| &p.namespaces).any(own) {
        return super::Resolution::Unresolved;
    }
    if parts.len() <= 1 {
        return super::Resolution::Stdlib;
    }
    super::Resolution::External(package_of(spec))
}

fn normalize(path: &str) -> Option<String> {
    let mut parts: Vec<&str> = Vec::new();
    for part in path.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                parts.pop()?;
            }
            _ => parts.push(part),
        }
    }
    Some(parts.join("/"))
}

/// Rust counterparts of common Composer packages.
pub fn lookup(package: &str) -> Option<CrateMatch> {
    crate::crates::find("php", package)
}

// ---- exports ---------------------------------------------------------------------------------

/// A PHP type (native or phpdoc: `?int`, `string|null`, `int[]`, `array<string, int>`,
/// `list<string>`) in the dialect.
pub fn php_to_ts(t: &str) -> String {
    let t = t.trim().trim_start_matches('\\');
    if let Some(inner) = t.strip_prefix('?') {
        return format!("{} | undefined", php_to_ts(inner));
    }
    let parts = split_top(t, '|');
    if parts.len() > 1 {
        let mapped: Vec<String> = parts.iter().map(|p| php_to_ts(p)).collect();
        return mapped.join(" | ");
    }
    if let Some(inner) = t.strip_suffix("[]") {
        let inner = php_to_ts(inner);
        return if inner.contains(' ') {
            format!("({inner})[]")
        } else {
            format!("{inner}[]")
        };
    }
    for generic in [
        "list<",
        "array<",
        "iterable<",
        "non-empty-list<",
        "non-empty-array<",
    ] {
        if let Some(inner) = t.strip_prefix(generic).and_then(|r| r.strip_suffix('>')) {
            let args = split_top(inner, ',');
            return match args.as_slice() {
                [v] => format!("{}[]", php_to_ts(v)),
                [k, v] if php_to_ts(k) == "string" => format!("Record<string, {}>", php_to_ts(v)),
                [k, v] if php_to_ts(k) == "int" => format!("{}[]", php_to_ts(v)),
                _ => "unknown".into(),
            };
        }
    }
    match t.to_ascii_lowercase().as_str() {
        "string" | "non-empty-string" | "class-string" | "numeric-string" => "string".into(),
        "int" | "integer" | "positive-int" | "negative-int" | "non-negative-int" => "int".into(),
        "float" | "double" => "number".into(),
        "bool" | "boolean" | "true" | "false" => "boolean".into(),
        "null" | "void" => "undefined".into(),
        "array" | "iterable" => "unknown[] | Record<string, unknown>".into(),
        _ => "unknown".into(),
    }
}

/// A tag body split into its type and the rest: a type may hold a space (`array<string, int>`),
/// so the split happens at the first space outside `<>`, `()`, `[]` and `{}`.
fn type_and_rest(rest: &str) -> Option<(&str, &str)> {
    let rest = rest.trim_start();
    if rest.is_empty() {
        return None;
    }
    let mut depth = 0i32;
    for (i, c) in rest.char_indices() {
        match c {
            '<' | '(' | '[' | '{' => depth += 1,
            '>' | ')' | ']' | '}' => depth -= 1,
            c if c.is_whitespace() && depth == 0 => {
                return Some((&rest[..i], rest[i..].trim_start()));
            }
            _ => {}
        }
    }
    Some((rest.trim_end(), ""))
}

fn plain_type(t: &str) -> bool {
    t.trim()
        .trim_start_matches('?')
        .split(['|', '&'])
        .map(|p| p.trim().trim_matches(['(', ')']).to_ascii_lowercase())
        .all(|p| {
            matches!(
                p.as_str(),
                "int"
                    | "float"
                    | "string"
                    | "bool"
                    | "array"
                    | "mixed"
                    | "null"
                    | "true"
                    | "false"
                    | "void"
                    | "never"
            )
        })
}

fn bare_array(t: &str) -> bool {
    t.trim()
        .trim_start_matches('?')
        .split('|')
        .map(|p| p.trim().to_ascii_lowercase())
        .all(|p| matches!(p.as_str(), "array" | "iterable" | "null"))
}

fn split_top(text: &str, sep: char) -> Vec<String> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut current = String::new();
    for c in text.chars() {
        match c {
            '<' | '{' | '(' | '[' => depth += 1,
            '>' | '}' | ')' | ']' => depth -= 1,
            _ if c == sep && depth == 0 => {
                out.push(current.trim().to_string());
                current.clear();
                continue;
            }
            _ => {}
        }
        current.push(c);
    }
    if !current.trim().is_empty() {
        out.push(current.trim().to_string());
    }
    out
}

/// The phpdoc block right above `node`, one tag per entry (`@param string $s`).
fn phpdoc(node: Node, source: &str) -> Vec<String> {
    let Some(prev) = node.prev_named_sibling().filter(|p| p.kind() == "comment") else {
        return Vec::new();
    };
    let doc = text(prev, source);
    if !doc.starts_with("/**") {
        return Vec::new();
    }
    doc.trim_start_matches("/**")
        .trim_end_matches("*/")
        .split('@')
        .skip(1)
        .map(|tag| {
            format!(
                "@{}",
                tag.lines()
                    .map(|l| l.trim().trim_start_matches('*').trim())
                    .collect::<Vec<_>>()
                    .join(" ")
                    .trim()
            )
        })
        .collect()
}

/// The dialect type of a literal default (`'-'`, `0`, `1.5`, `true`, `[]`).
fn literal_type(value: &str) -> Option<&'static str> {
    let v = value.trim();
    if v.starts_with('"') || v.starts_with('\'') {
        Some("string")
    } else if v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("false") {
        Some("boolean")
    } else if v.parse::<i64>().is_ok() {
        Some("int")
    } else if v.parse::<f64>().is_ok() {
        Some("number")
    } else if v.starts_with('[') {
        Some("unknown[]")
    } else {
        None
    }
}

fn function_fn(
    path: &str,
    receiver: &str,
    sep: &str,
    node: Node,
    source: &str,
) -> Option<ExportedFn> {
    let name = text(node.child_by_field_name("name")?, source).to_string();
    let doc = phpdoc(node, source);
    let doc_param = |p: &str| {
        doc.iter().find_map(|tag| {
            let (t, rest) = type_and_rest(tag.strip_prefix("@param ")?)?;
            let name = rest.split_whitespace().next()?;
            (name == format!("${p}")).then(|| php_to_ts(t))
        })
    };
    let doc_return = doc.iter().find_map(|tag| {
        let (t, _) = type_and_rest(tag.strip_prefix("@return ")?)?;
        Some(php_to_ts(t))
    });
    let returns = node
        .child_by_field_name("return_type")
        .map(|t| text(t, source))
        .filter(|t| !(bare_array(t) && doc_return.is_some()))
        .map(php_to_ts)
        .filter(|t| t != "unknown")
        .or(doc_return)
        .unwrap_or_else(|| "unknown".into());
    let mut blocker = None;
    if name.starts_with("__") {
        blocker = Some(format!("`{name}` is a magic method"));
    }
    if sep == "::"
        && named_children(node)
            .iter()
            .any(|c| c.kind() == "reference_modifier")
    {
        blocker.get_or_insert_with(|| {
            "returns by reference (`&`), so the wrapper cannot preserve the reference".into()
        });
    }
    let mut params = Vec::new();
    let mut by_reference: Vec<String> = Vec::new();
    let mut signature = String::new();
    if let Some(list) = node.child_by_field_name("parameters") {
        let list_text = text(list, source);
        signature = list_text
            .strip_prefix('(')
            .and_then(|t| t.strip_suffix(')'))
            .unwrap_or(list_text)
            .to_string();
        for p in named_children(list) {
            let pname = p
                .child_by_field_name("name")
                .map(|n| text(n, source).trim_start_matches('$').to_string())
                .unwrap_or_default();
            match p.kind() {
                "simple_parameter" => {}
                "variadic_parameter" => {
                    blocker.get_or_insert_with(|| "takes `...$args`".into());
                    continue;
                }
                _ => {
                    blocker.get_or_insert_with(|| format!("parameter `{}`", text(p, source)));
                    continue;
                }
            }
            // A parameter taken by reference changes the caller's variable: the port takes it
            // by `&mut`, and `record` keeps its value after the call.
            if named_children(p)
                .iter()
                .any(|c| c.kind() == "reference_modifier")
                || text(p, source).contains("&$")
            {
                by_reference.push(pname.clone());
            }
            let declared = p.child_by_field_name("type").map(|t| text(t, source));
            if declared.is_some_and(|t| t.contains("callable") || t.contains("Closure")) {
                blocker.get_or_insert_with(|| format!("takes a callable `${pname}`"));
            }
            if let Some(t) = declared.filter(|t| !plain_type(t)) {
                blocker.get_or_insert_with(|| format!("takes an object `${pname}` (`{t}`)"));
            }
            let value = p
                .child_by_field_name("default_value")
                .map(|v| text(v, source).to_string());
            let mut ts_type = declared
                .filter(|t| !(bare_array(t) && doc_param(&pname).is_some()))
                .map(php_to_ts)
                .filter(|t| t != "unknown")
                .or_else(|| doc_param(&pname))
                .or_else(|| value.as_deref().and_then(literal_type).map(str::to_string))
                .unwrap_or_else(|| "unknown".into());
            if value
                .as_deref()
                .is_some_and(|v| v.eq_ignore_ascii_case("null"))
                && !ts_type.contains("undefined")
            {
                ts_type = format!("{ts_type} | undefined");
            }
            params.push(Param {
                name: pname,
                ts_type,
                optional: value.is_some(),
                default: value,
                ..Default::default()
            });
        }
    }
    if let Some(t) = node
        .child_by_field_name("return_type")
        .map(|t| text(t, source))
        .filter(|t| !plain_type(t))
    {
        blocker.get_or_insert_with(|| format!("returns an object (`{t}`)"));
    }
    if let Some(body) = node.child_by_field_name("body") {
        let mut yields = false;
        syntax::walk(body, |n| yields |= n.kind() == "yield_expression");
        if yields {
            blocker.get_or_insert_with(|| "is a generator (`yield`)".into());
        }
    }
    let prefix = if receiver.is_empty() {
        String::new()
    } else {
        format!("{receiver}{sep}")
    };
    if blocker.is_none() {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        blocker = super::effects::function_reason(super::Lang::Php, &names, text(node, source));
    }
    let (_, prints) =
        crate::ts::exports::observed_effects(super::Lang::Php, &params, text(node, source));
    Some(ExportedFn {
        mutates: by_reference,
        prints,
        name: name.clone(),
        file: path.to_string(),
        line: syntax::line(node),
        params,
        returns,
        prototype: Some(format!("{prefix}{name}({signature})")),
        blocker,
        ..Default::default()
    })
}

/// PHP keywords are case-insensitive: `PRIVATE` is as private as `private`.
fn modifiers(node: Node, source: &str) -> Vec<String> {
    named_children(node)
        .iter()
        .filter(|c| c.kind().ends_with("_modifier"))
        .map(|c| text(*c, source).to_ascii_lowercase())
        .collect()
}

/// A method the wrapper exports: public and static.
fn is_public_static(node: Node, source: &str) -> bool {
    let mods = modifiers(node, source);
    !mods
        .iter()
        .any(|m| matches!(m.as_str(), "private" | "protected"))
        && mods.iter().any(|m| m.as_str() == "static")
}

/// Why a class cannot be replaced by a wrapper that only holds its public static methods. Private
/// and protected members are left out, except the constructor: the wrapper has none, so a class
/// the original made impossible to construct would become instantiable. A non-final class is left
/// out too: the wrapper is final, and the protected members a subclass could use do not come
/// along.
fn class_reason(item: Node, class: &str, source: &str) -> Option<String> {
    let body = item.child_by_field_name("body")?;
    let (mut instance, mut public_property, mut static_property, mut public_const, mut trait_use) =
        (false, false, false, false, false);
    for member in named_children(body) {
        let mods = modifiers(member, source);
        let public = !mods
            .iter()
            .any(|m| matches!(m.as_str(), "private" | "protected"));
        let constructor = member
            .child_by_field_name("name")
            .is_some_and(|n| text(n, source).eq_ignore_ascii_case("__construct"));
        match member.kind() {
            "method_declaration"
                if !mods.iter().any(|m| m.as_str() == "static") && (public || constructor) =>
            {
                instance = true
            }
            "property_declaration" => {
                if mods.iter().any(|m| m.as_str() == "static") {
                    static_property = true;
                }
                if public {
                    public_property = true;
                }
            }
            "const_declaration" if public => public_const = true,
            "use_declaration" => trait_use = true,
            _ => {}
        }
    }
    let inherits = named_children(item)
        .iter()
        .any(|c| matches!(c.kind(), "base_clause" | "class_interface_clause"));
    if instance {
        Some(format!(
            "`{class}` also has instance methods, so its static methods stay in PHP"
        ))
    } else if static_property {
        Some(format!(
            "`{class}` has static properties, so its static methods stay in PHP"
        ))
    } else if inherits {
        Some(format!(
            "`{class}` extends or implements another type, so its static methods stay in PHP"
        ))
    } else if trait_use {
        Some(format!(
            "`{class}` uses a trait, so its static methods stay in PHP"
        ))
    } else if public_property {
        Some(format!(
            "`{class}` has public properties, so its static methods stay in PHP"
        ))
    } else if public_const {
        Some(format!(
            "`{class}` has public constants, so its static methods stay in PHP"
        ))
    } else if !modifiers(item, source)
        .iter()
        .any(|m| m.as_str() == "final")
    {
        Some(format!(
            "`{class}` is not final, so its static methods stay in PHP (the wrapper is `final`)"
        ))
    } else {
        None
    }
}

/// The local names of constants imported with `use const` (`LIMIT` for
/// `use const PHP_INT_MAX as LIMIT`). The wrapper copies neither the import nor the constant.
fn imported_constants(root: Node, source: &str) -> Vec<String> {
    fn clause_name(clause: Node, source: &str) -> Option<String> {
        let alias = clause
            .child_by_field_name("alias")
            .map(|a| text(a, source).to_string());
        let name = clause.named_child(0).map(|n| text(n, source))?;
        Some(alias.unwrap_or_else(|| name.rsplit('\\').next().unwrap_or(name).to_string()))
    }
    fn collect(items: Vec<Node>, source: &str, out: &mut Vec<String>) {
        for item in items {
            match item.kind() {
                "namespace_definition" => {
                    if let Some(body) = item.child_by_field_name("body") {
                        collect(named_children(body), source, out);
                    }
                }
                "namespace_use_declaration" => {
                    let declared = item.child_by_field_name("type").map(|t| text(t, source));
                    if let Some(group) = item.child_by_field_name("body") {
                        for clause in named_children(group)
                            .into_iter()
                            .filter(|c| c.kind() == "namespace_use_clause")
                        {
                            let kind = clause
                                .child_by_field_name("type")
                                .map(|t| text(t, source))
                                .or(declared);
                            if kind.is_some_and(|k| k.eq_ignore_ascii_case("const"))
                                && let Some(name) = clause_name(clause, source)
                            {
                                out.push(name);
                            }
                        }
                    } else {
                        let mut kind = declared;
                        for clause in named_children(item)
                            .into_iter()
                            .filter(|c| c.kind() == "namespace_use_clause")
                        {
                            if let Some(t) =
                                clause.child_by_field_name("type").map(|t| text(t, source))
                            {
                                kind = Some(t);
                            }
                            if kind.is_some_and(|k| k.eq_ignore_ascii_case("const"))
                                && let Some(name) = clause_name(clause, source)
                            {
                                out.push(name);
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }
    let mut out = Vec::new();
    collect(named_children(root), source, &mut out);
    out
}

/// Whether a default expression mentions `name` as a whole identifier (not inside a string).
fn mentions_identifier(code: &str, name: &str) -> bool {
    code.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '\\'))
        .any(|word| word.trim_start_matches('\\') == name)
}

/// The default expressions of the public static methods the wrapper exports.
fn public_static_defaults<'t>(item: Node<'t>, source: &str) -> Vec<Node<'t>> {
    let Some(body) = item.child_by_field_name("body") else {
        return Vec::new();
    };
    named_children(body)
        .into_iter()
        .filter(|m| m.kind() == "method_declaration" && is_public_static(*m, source))
        .filter_map(|m| m.child_by_field_name("parameters"))
        .flat_map(named_children)
        .filter_map(|p| p.child_by_field_name("default_value"))
        .collect()
}

/// The location-dependent magic constant a default expression uses (`__LINE__`, `__FILE__`,
/// `__DIR__`). The wrapper is a different file at a different line, so the value would change.
/// PHP magic constants are case-insensitive; the parser keeps the word inside a string out.
fn location_magic(node: Node, source: &str) -> Option<&'static str> {
    const NAMES: [&str; 3] = ["__LINE__", "__FILE__", "__DIR__"];
    let mut found = None;
    syntax::walk(node, |n| {
        if found.is_none() && n.kind() == "name" {
            let word = text(n, source);
            found = NAMES
                .iter()
                .copied()
                .find(|name| word.eq_ignore_ascii_case(name));
        }
    });
    found
}

fn location_magic_default(item: Node, source: &str) -> Option<&'static str> {
    public_static_defaults(item, source)
        .into_iter()
        .find_map(|default| location_magic(default, source))
}

/// The first default of a public static method that creates an object, if any. The parser sees
/// `new` as an `object_creation_expression`, so the word inside a string or a comment does not
/// count; the wrapper copies neither the class import nor the constructor semantics.
fn object_creation_default(item: Node, source: &str) -> Option<String> {
    public_static_defaults(item, source)
        .into_iter()
        .find_map(|default| {
            let mut creates = false;
            syntax::walk(default, |n| {
                creates |= n.kind() == "object_creation_expression";
            });
            creates.then(|| text(default, source).trim().to_string())
        })
}

/// Why the file cannot be replaced by a wrapper that holds only the class: top-level code (a
/// `define`, a `require`, a side effect) or another declaration would be dropped.
fn file_class_reason(root: Node) -> Option<String> {
    let mut declarations = 0usize;
    let mut code = false;
    fn scan(items: Vec<Node>, declarations: &mut usize, code: &mut bool) {
        for item in items {
            match item.kind() {
                "namespace_definition" => {
                    if let Some(body) = item.child_by_field_name("body") {
                        scan(named_children(body), declarations, code);
                    }
                }
                "declare_statement" => {
                    // `declare_statement` has no `body` field: a block or a following statement
                    // is an executable form, while `declare(strict_types=1);` is only the
                    // directive and stays transparent.
                    if named_children(item)
                        .iter()
                        .any(|c| c.kind() != "declare_directive")
                    {
                        *code = true;
                    }
                }
                "namespace_use_declaration" | "comment" | "php_tag" => {}
                "function_definition"
                | "class_declaration"
                | "interface_declaration"
                | "trait_declaration"
                | "enum_declaration" => *declarations += 1,
                _ => *code = true,
            }
        }
    }
    scan(named_children(root), &mut declarations, &mut code);
    if code {
        Some(
            "is in a file with top-level code (a constant, a require or a side effect), so the \
             wrapper cannot replace the file"
                .into(),
        )
    } else if declarations > 1 {
        Some(
            "shares its file with another declaration, so the wrapper cannot replace the file"
                .into(),
        )
    } else {
        None
    }
}

pub(crate) fn declared_types(source: &str) -> Vec<String> {
    let Some(tree) = syntax::parse(&language(), source) else {
        return Vec::new();
    };
    let mut namespace = "";
    let mut types = Vec::new();
    for item in named_children(tree.root_node()) {
        let mut items = if item.kind() == "namespace_definition" {
            namespace = item
                .child_by_field_name("name")
                .map_or("", |name| text(name, source));
            item.child_by_field_name("body")
                .map_or_else(Vec::new, named_children)
        } else {
            vec![item]
        };
        while let Some(node) = items.pop() {
            match node.kind() {
                "class_declaration"
                | "interface_declaration"
                | "trait_declaration"
                | "enum_declaration" => {
                    if let Some(name) = node.child_by_field_name("name") {
                        let name = text(name, source);
                        types.push(if namespace.is_empty() {
                            name.to_owned()
                        } else {
                            format!("{namespace}\\{name}")
                        });
                    }
                }
                "function_definition"
                | "anonymous_function"
                | "arrow_function"
                | "anonymous_class" => {}
                _ => items.extend(named_children(node)),
            }
        }
    }
    types
}

/// Functions (`Ns\name(...)`) and public static methods of classes (`Ns\Class::name(...)`).
pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
    if !path.ends_with(".php") {
        return Vec::new();
    }
    let Some(tree) = syntax::parse(&language(), source) else {
        return Vec::new();
    };
    let file_reason = file_class_reason(tree.root_node());
    let imported_consts = imported_constants(tree.root_node(), source);
    let mut out = Vec::new();
    let mut namespace = String::new();
    let visit = |items: Vec<Node>, namespace: &mut String, out: &mut Vec<ExportedFn>| {
        for item in items {
            match item.kind() {
                "namespace_definition" => {
                    *namespace = item
                        .child_by_field_name("name")
                        .map(|n| text(n, source).to_string())
                        .unwrap_or_default();
                }
                "function_definition" => {
                    out.extend(function_fn(path, namespace, "\\", item, source));
                }
                "class_declaration" => {
                    if named_children(item)
                        .iter()
                        .any(|c| c.kind() == "abstract_modifier")
                    {
                        continue;
                    }
                    let Some(class) = item.child_by_field_name("name") else {
                        continue;
                    };
                    let class = text(class, source);
                    let receiver = if namespace.is_empty() {
                        class.to_string()
                    } else {
                        format!("{namespace}\\{class}")
                    };
                    let mut methods: Vec<ExportedFn> = item
                        .child_by_field_name("body")
                        .map(named_children)
                        .unwrap_or_default()
                        .into_iter()
                        .filter(|m| m.kind() == "method_declaration")
                        .filter(|m| is_public_static(*m, source))
                        .filter_map(|m| function_fn(path, &receiver, "::", m, source))
                        .collect();
                    // The wrapper replaces the class's file and the class as a whole: top-level
                    // code or another declaration, one method that cannot cross the bridge, or a
                    // default that names a class constant or an imported constant, depends on the
                    // file or line, or creates an object keeps all of them in PHP.
                    let class_constant_default = methods.iter().find_map(|f| {
                        f.params.iter().find_map(|p| {
                            let d = p.default.as_deref()?;
                            super::effects::blank(super::Lang::Php, d)
                                .contains("::")
                                .then(|| d.trim().to_string())
                        })
                    });
                    let imported_constant_default = methods.iter().find_map(|f| {
                        f.params.iter().find_map(|p| {
                            let d = p.default.as_deref()?;
                            let code = super::effects::blank(super::Lang::Php, d);
                            imported_consts
                                .iter()
                                .find(|name| mentions_identifier(&code, name))
                                .cloned()
                        })
                    });
                    let location_default = location_magic_default(item, source);
                    let object_default = object_creation_default(item, source);
                    let reason = file_reason
                        .as_ref()
                        .map(|r| format!("`{class}` {r}"))
                        .or_else(|| class_reason(item, class, source))
                        .or_else(|| {
                            class_constant_default.map(|d| {
                                format!(
                                    "`{class}` has a default that names a class constant (`{d}`), \
                                     so its static methods stay in PHP"
                                )
                            })
                        })
                        .or_else(|| {
                            imported_constant_default.map(|name| {
                                format!(
                                    "`{class}` has a default that names an imported constant \
                                     (`{name}`), so its static methods stay in PHP"
                                )
                            })
                        })
                        .or_else(|| {
                            location_default.map(|name| {
                                format!(
                                    "`{class}` has a default that depends on the file or line \
                                     (`{name}`), so its static methods stay in PHP"
                                )
                            })
                        })
                        .or_else(|| {
                            object_default.map(|d| {
                                format!(
                                    "`{class}` has a default that creates an object (`{d}`), so \
                                     its static methods stay in PHP"
                                )
                            })
                        });
                    if let Some(reason) = reason {
                        for f in &mut methods {
                            f.blocker.get_or_insert_with(|| reason.clone());
                        }
                    } else if let Some((name, why)) = methods
                        .iter()
                        .find_map(|f| f.blocker.clone().map(|b| (f.name.clone(), b)))
                    {
                        let reason = format!(
                            "`{class}` has a method that stays in PHP (`{name}`: {why}), so its \
                             static methods stay"
                        );
                        for f in &mut methods {
                            f.blocker.get_or_insert(reason.clone());
                        }
                    }
                    out.extend(methods);
                }
                _ => {}
            }
        }
    };
    let root = tree.root_node();
    for item in named_children(root) {
        if item.kind() == "namespace_definition"
            && let Some(body) = item.child_by_field_name("body")
        {
            namespace = item
                .child_by_field_name("name")
                .map(|n| text(n, source).to_string())
                .unwrap_or_default();
            visit(named_children(body), &mut namespace, &mut out);
        } else {
            visit(vec![item], &mut namespace, &mut out);
        }
    }
    out.sort_by_key(|f| f.line);
    qualify_clashing_methods(&mut out);
    out
}

/// Qualify static method names as `Class::method` when multiple exports in a unit share the bare
/// method name; unique methods keep their bare name so existing recordings stay valid.
pub fn qualify_clashing_methods(exports: &mut [ExportedFn]) {
    let mut counts: HashMap<String, usize> = HashMap::new();
    for f in exports.iter() {
        let bare = f.name.rsplit_once("::").map_or(f.name.as_str(), |(_, m)| m);
        *counts.entry(bare.to_string()).or_insert(0) += 1;
    }
    for f in exports.iter_mut() {
        let bare = f.name.rsplit_once("::").map_or(f.name.as_str(), |(_, m)| m);
        if counts.get(bare).copied().unwrap_or(0) <= 1 || f.name.contains("::") {
            continue;
        }
        let Some(head) = f
            .prototype
            .as_deref()
            .and_then(|p| p.split('(').next())
            .map(str::trim)
        else {
            continue;
        };
        let Some((owner, _)) = head.split_once("::") else {
            continue;
        };
        let class = owner.rsplit('\\').next().unwrap_or(owner);
        if !class.is_empty() {
            f.name = format!("{class}::{}", f.name);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_phpdoc_type_with_a_space_keeps_its_arguments() {
        // `array<string, int>` holds a space: splitting the tag on whitespace cut it in half.
        assert_eq!(
            type_and_rest("array<string, int> $counts"),
            Some(("array<string, int>", "$counts"))
        );
        assert_eq!(type_and_rest("?int $x"), Some(("?int", "$x")));
        assert_eq!(
            type_and_rest("array{a: int, b: string} $x"),
            Some(("array{a: int, b: string}", "$x"))
        );
        assert_eq!(type_and_rest("string"), Some(("string", "")));
        assert_eq!(type_and_rest("   "), None);
        assert_eq!(php_to_ts("array<string, int>"), "Record<string, int>");
    }

    #[test]
    fn a_composer_json_with_a_byte_order_mark_is_read() {
        let root = std::env::temp_dir().join(format!("ra-php-bom-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join("composer.json"),
            "\u{feff}{\"name\":\"acme/demo\",\"require\":{\"guzzlehttp/guzzle\":\"^7\"},\
             \"autoload\":{\"psr-4\":{\"Acme\\\\\":\"src/\"}}}",
        )
        .unwrap();
        let workspace = discover(&root).unwrap();
        let _ = std::fs::remove_dir_all(&root);
        assert_eq!(workspace.packages[0].name, "acme/demo");
        assert_eq!(workspace.packages[0].deps, ["guzzlehttp/guzzle"]);
        assert_eq!(workspace.packages[0].namespaces, ["Acme"]);
        assert_eq!(workspace.packages[0].src_root, "src");
    }

    const SRC: &str = r#"<?php
declare(strict_types=1);
namespace App\Text;
use App\Util\Str;
use GuzzleHttp\Client;
use Symfony\Component\Yaml\Yaml;
require_once __DIR__ . '/helpers.php';

/**
 * @param string $s
 * @param list<string> $stop
 * @return string
 */
function slugify(string $s, $stop = [], string $sep = '-', ?int $max = null): string {
    if ($s === '') { throw new \InvalidArgumentException("empty"); }
    $x = intdiv(7, 2) % 3;
    return strtolower(preg_replace('/(?<=a)b/u', $sep, $s));
}

function words($text) { foreach (explode(' ', $text) as $w) { yield $w; } }

final class Words extends Base {
    public static function count(string $s, int ...$rest): int { return str_word_count($s); }
    public static function scale($x, float $factor = 1.5) { return $x * $factor; }
    private static function hidden() {}
    public function instance() {}
}
eval('1;');
"#;

    #[test]
    fn a_phpdoc_param_or_return_with_a_space_in_its_type_is_read_whole() {
        // `@param array<string, int> $counts` holds a space inside the type: splitting the tag on
        // whitespace cut it to `array<string,` and the parameter came out `unknown`.
        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";
        let fns = exports("src/counts.php", src);
        assert_eq!(fns.len(), 1);
        assert_eq!(fns[0].params[0].ts_type, "Record<string, int>");
        assert_eq!(fns[0].returns, "Record<string, int>");
        assert!(fns[0].blocker.is_none());
    }

    #[test]
    fn maps_php_types() {
        assert_eq!(php_to_ts("?int"), "int | undefined");
        assert_eq!(php_to_ts("string|null"), "string | undefined");
        assert_eq!(php_to_ts("int[]"), "int[]");
        assert_eq!(php_to_ts("array<string, int>"), "Record<string, int>");
        assert_eq!(php_to_ts("list<float>"), "number[]");
        assert_eq!(php_to_ts("\\DateTime"), "unknown");
    }

    #[test]
    fn finds_functions_and_static_methods() {
        let fns = exports("src/Text/slug.php", SRC);
        let protos: Vec<&str> = fns
            .iter()
            .map(|f| f.prototype.as_deref().unwrap_or(""))
            .collect();
        assert_eq!(
            protos,
            [
                "App\\Text\\slugify(string $s, $stop = [], string $sep = '-', ?int $max = null)",
                "App\\Text\\words($text)",
                "App\\Text\\Words::count(string $s, int ...$rest)",
                "App\\Text\\Words::scale($x, float $factor = 1.5)",
            ]
        );
        let slug = &fns[0];
        let types: Vec<&str> = slug.params.iter().map(|p| p.ts_type.as_str()).collect();
        assert_eq!(types, ["string", "string[]", "string", "int | undefined"]);
        assert_eq!(slug.returns, "string");
        assert!(slug.blocker.is_none());
        assert!(fns[1].blocker.as_deref().unwrap().contains("generator"));
        assert!(fns[2].blocker.as_deref().unwrap().contains("...$args"));
        assert_eq!(fns[3].params[1].ts_type, "number");
        // The class shares a file with top-level code and other declarations, so the file
        // reason is the one that keeps it.
        assert!(
            fns[3]
                .blocker
                .as_deref()
                .unwrap()
                .contains("cannot replace the file"),
            "{:?}",
            fns[3].blocker
        );
    }

    #[test]
    fn a_class_is_bridged_only_when_its_public_members_are_static_methods() {
        let sources: [(&str, &str); 13] = [
            (
                "src/Pure.php",
                r#"<?php
namespace App;
final class Pure {
    public static function a(int $x): int { return $x; }
    private static function helper(): int { return 1; }
    private function hidden(): void {}
}
"#,
            ),
            (
                "src/Blend.php",
                r#"<?php
namespace App;
final class Blend {
    public static function b(int $x): int { return $x; }
    public function c(): string { return 'c'; }
}
"#,
            ),
            (
                "src/Consts.php",
                r#"<?php
namespace App;
final class Consts {
    public const LIMIT = 3;
    public static function d(int $x): int { return min($x, self::LIMIT); }
}
"#,
            ),
            (
                "src/Child.php",
                r#"<?php
namespace App;
final class Child extends Pure {
    public static function e(): int { return 1; }
}
"#,
            ),
            (
                "src/Gen.php",
                r#"<?php
namespace App;
final class Gen {
    public static function g(): \Generator { yield 1; }
    public static function h(int $x): int { return $x; }
}
"#,
            ),
            (
                "src/Def.php",
                r#"<?php
namespace App;
final class Def {
    private const LIMIT = 3;
    public static function f(int $x = self::LIMIT): int { return $x; }
}
"#,
            ),
            (
                "src/Uses.php",
                r#"<?php
namespace App;
final class Uses {
    use Helper;
    public static function i(): int { return 1; }
}
"#,
            ),
            (
                "src/Props.php",
                r#"<?php
namespace App;
final class Props {
    public static $cache = 1;
    public static function k(): int { return 1; }
}
"#,
            ),
            (
                "src/Impl.php",
                r#"<?php
namespace App;
final class Impl implements Marker {
    public static function l(): int { return 1; }
}
"#,
            ),
            (
                "src/Guarded.php",
                r#"<?php
namespace App;
final class Guarded {
    protected const LIMIT = 3;
    protected int $cache = 1;
    protected function hidden(): void {}
    public static function m(): int { return 1; }
}
"#,
            ),
            (
                "src/Cache.php",
                r#"<?php
namespace App;
final class Cache {
    private static $seen = 0;
    public static function n(): int { return 1; }
}
"#,
            ),
            (
                "src/Field.php",
                r#"<?php
namespace App;
final class Field {
    public int $x = 1;
    public static function o(): int { return 1; }
}
"#,
            ),
            (
                "src/Extensible.php",
                r#"<?php
namespace App;
class Extensible {
    public static function p(): int { return 1; }
}
"#,
            ),
        ];
        let mut fns = Vec::new();
        for (file, src) in sources {
            fns.extend(exports(file, src));
        }

        let by = |name: &str| {
            fns.iter()
                .find(|f| f.name == name)
                .unwrap_or_else(|| panic!("no {name} in {fns:?}"))
        };
        assert!(by("a").blocker.is_none(), "{:?}", by("a").blocker);
        assert!(
            by("b")
                .blocker
                .as_deref()
                .unwrap()
                .contains("instance methods"),
            "{:?}",
            by("b").blocker
        );
        assert!(
            by("d")
                .blocker
                .as_deref()
                .unwrap()
                .contains("public constants"),
            "{:?}",
            by("d").blocker
        );
        assert!(
            by("e")
                .blocker
                .as_deref()
                .unwrap()
                .contains("extends or implements"),
            "{:?}",
            by("e").blocker
        );
        assert!(
            by("g").blocker.as_deref().unwrap().contains("Generator"),
            "{:?}",
            by("g").blocker
        );
        assert!(
            by("h")
                .blocker
                .as_deref()
                .unwrap()
                .contains("has a method that stays in PHP"),
            "{:?}",
            by("h").blocker
        );
        assert!(
            by("f")
                .blocker
                .as_deref()
                .unwrap()
                .contains("names a class constant"),
            "{:?}",
            by("f").blocker
        );
        assert!(
            by("i").blocker.as_deref().unwrap().contains("uses a trait"),
            "{:?}",
            by("i").blocker
        );
        assert!(
            by("k")
                .blocker
                .as_deref()
                .unwrap()
                .contains("static properties"),
            "{:?}",
            by("k").blocker
        );
        assert!(
            by("l")
                .blocker
                .as_deref()
                .unwrap()
                .contains("extends or implements"),
            "{:?}",
            by("l").blocker
        );
        assert!(by("m").blocker.is_none(), "{:?}", by("m").blocker);
        assert!(
            by("n")
                .blocker
                .as_deref()
                .unwrap()
                .contains("static properties"),
            "{:?}",
            by("n").blocker
        );
        assert!(
            by("o")
                .blocker
                .as_deref()
                .unwrap()
                .contains("public properties"),
            "{:?}",
            by("o").blocker
        );
        assert!(
            by("p").blocker.as_deref().unwrap().contains("is not final"),
            "{:?}",
            by("p").blocker
        );
    }

    #[test]
    fn a_class_with_a_non_public_constructor_stays() {
        for src in [
            "<?php final class Ctor { private function __construct() {} public static function f(): int { return 1; } }",
            "<?php final class Ctor { protected function __construct() {} public static function f(): int { return 1; } }",
            "<?php final class Ctor { PRIVATE function __construct() {} PUBLIC static function f(): int { return 1; } }",
        ] {
            let fns = exports("src/Ctor.php", src);
            assert!(
                fns.iter().all(|f| f
                    .blocker
                    .as_deref()
                    .is_some_and(|b| b.contains("instance methods"))),
                "{src}: {fns:?}"
            );
        }
    }

    #[test]
    fn mixed_case_modifiers_are_read_like_their_lowercase_spelling() {
        let fns = exports(
            "src/Cased.php",
            "<?php FINAL CLASS Cased { PRIVATE static function hidden(int $x): int { return $x; } PUBLIC STATIC function p(int $x): int { return $x; } }",
        );
        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(names, ["p"], "{fns:?}");
        assert!(fns[0].blocker.is_none(), "{fns:?}");
    }

    #[test]
    fn a_reference_returning_method_keeps_the_class() {
        let fns = exports(
            "src/Ref.php",
            "<?php final class Ref { public static function &identity(int &$x): int { return $x; } public static function count(int $x): int { return $x; } }",
        );
        assert!(
            fns.iter().all(|f| f
                .blocker
                .as_deref()
                .is_some_and(|b| b.contains("returns by reference"))),
            "{fns:?}"
        );
    }

    #[test]
    fn a_default_that_creates_an_object_keeps_the_class() {
        for src in [
            "<?php\nnamespace App;\nuse stdClass as Value;\nfinal class Defaults { public static function f($x = new Value()): mixed { return $x; } }",
            "<?php\nnamespace App;\nfinal class Defaults { public static function f($x = [new \\stdClass()]): mixed { return $x; } }",
        ] {
            let fns = exports("src/Defaults.php", src);
            assert!(
                fns[0]
                    .blocker
                    .as_deref()
                    .is_some_and(|b| b.contains("creates an object")),
                "{src}: {fns:?}"
            );
        }
        let literal = exports(
            "src/Defaults.php",
            "<?php\nnamespace App;\nfinal class Defaults { public static function f(string $s = 'new Value()'): string { return $s; } }",
        );
        assert!(literal[0].blocker.is_none(), "{literal:?}");
        let multiline = exports(
            "src/Defaults.php",
            "<?php\nnamespace App;\nfinal class Defaults { public static function f(string $s = \"first\nnew Value()\nthird\"): string { return $s; } }",
        );
        assert!(multiline[0].blocker.is_none(), "{multiline:?}");
    }

    #[test]
    fn a_default_that_depends_on_the_file_or_line_keeps_the_class() {
        for (src, name) in [
            (
                "<?php final class Loc { public static function f(int $n = __LINE__): int { return $n; } }",
                "__LINE__",
            ),
            (
                "<?php final class Loc { public static function f(string $p = __FILE__): string { return $p; } }",
                "__FILE__",
            ),
            (
                "<?php final class Loc { public static function f(string $d = __DIR__): string { return $d; } }",
                "__DIR__",
            ),
            (
                "<?php final class Loc { public static function f(int $n = __line__): int { return $n; } }",
                "__LINE__",
            ),
        ] {
            let fns = exports("src/Loc.php", src);
            assert!(
                fns[0]
                    .blocker
                    .as_deref()
                    .is_some_and(|b| b.contains("depends on the file or line") && b.contains(name)),
                "{src}: {fns:?}"
            );
        }
        let literal = exports(
            "src/Loc.php",
            "<?php final class Loc { public static function f(string $s = '__LINE__'): string { return $s; } }",
        );
        assert!(literal[0].blocker.is_none(), "{literal:?}");
        let multiline = exports(
            "src/Loc.php",
            "<?php final class Loc { public static function f(string $s = \"first\n__LINE__\nthird\"): string { return $s; } }",
        );
        assert!(multiline[0].blocker.is_none(), "{multiline:?}");
    }

    #[test]
    fn a_default_that_names_a_class_constant_keeps_the_class() {
        for src in [
            "<?php final class Def { public static function f(int $x = Def::LIMIT): int { return $x; } }",
            "<?php final class Def { public static function f(int $x = Other::LIMIT): int { return $x; } }",
            "<?php final class Def { private const LIMIT = 3; public static function f(int $x = self :: LIMIT): int { return $x; } }",
        ] {
            let fns = exports("src/Def.php", src);
            assert!(
                fns[0]
                    .blocker
                    .as_deref()
                    .is_some_and(|b| b.contains("class constant")),
                "{src}: {fns:?}"
            );
        }
        let literal = exports(
            "src/Literal.php",
            "<?php final class Literal { public static function f(string $s = 'a::b'): string { return $s; } }",
        );
        assert!(literal[0].blocker.is_none(), "{literal:?}");
    }

    #[test]
    fn a_default_that_names_an_imported_constant_keeps_the_class() {
        for src in [
            "<?php\nnamespace App;\nuse const PHP_INT_MAX as LIMIT;\nfinal class Defaults { public static function f(int $x = LIMIT): int { return $x; } }",
            "<?php\nnamespace App;\nuse const Foo\\{BAR as LIMIT};\nfinal class Defaults { public static function f(int $x = LIMIT): int { return $x; } }",
        ] {
            let fns = exports("src/Defaults.php", src);
            assert!(
                fns[0]
                    .blocker
                    .as_deref()
                    .is_some_and(|b| b.contains("imported constant (`LIMIT`)")),
                "{src}: {fns:?}"
            );
        }
        for src in [
            "<?php\nnamespace App;\nfinal class Defaults { public static function f(int $x = PHP_INT_MAX): int { return $x; } }",
            "<?php\nnamespace App;\nuse const PHP_INT_MAX as LIMIT;\nfinal class Defaults { public static function f(string $s = 'LIMIT'): string { return $s; } }",
        ] {
            let fns = exports("src/Defaults.php", src);
            assert!(fns[0].blocker.is_none(), "{src}: {fns:?}");
        }
    }

    #[test]
    fn a_class_file_must_be_replaceable_as_a_whole() {
        let kept = [
            "<?php final class A { public static function a(): int { return 1; } } final class B { public function b(): int { return 2; } }",
            "<?php define('LIMIT', 3); final class A { public static function a(): int { return 1; } }",
            "<?php function helper(): int { return 1; } final class A { public static function a(): int { return 1; } }",
            "<?php declare(ticks=1) { require 'bootstrap.php'; } final class A { public static function a(): int { return 1; } }",
        ];
        for src in kept {
            let fns = exports("src/A.php", src);
            assert!(
                fns.iter().any(|f| f.name == "a"
                    && f.blocker
                        .as_deref()
                        .is_some_and(|b| b.contains("cannot replace the file"))),
                "{src}: {fns:?}"
            );
        }
        let clean = exports(
            "src/A.php",
            "<?php declare(strict_types=1); final class A { public static function a(): int { return 1; } }",
        );
        assert!(
            clean.iter().any(|f| f.name == "a" && f.blocker.is_none()),
            "{clean:?}"
        );
    }

    #[test]
    fn a_default_that_ends_in_a_parenthesis_keeps_the_outer_parenthesis() {
        let fns = exports(
            "src/Def.php",
            "<?php final class Def { public static function size(array $xs = array()): int { return count($xs); } }",
        );
        assert_eq!(
            fns[0].prototype.as_deref(),
            Some("Def::size(array $xs = array())")
        );
    }

    #[test]
    fn resolves_import_names_from_a_group_use() {
        let facts = scan(
            r"<?php
namespace App;
use Vendor\Library\{One, Two as Alias, function helpers\trim_value};
use Other\Three;
",
        );
        assert_eq!(facts.parse_errors, 0);
        assert_eq!(
            facts
                .imports
                .iter()
                .map(|i| i.specifier.as_str())
                .collect::<Vec<_>>(),
            [
                "Vendor\\Library\\One",
                "Vendor\\Library\\Two",
                "Vendor\\Library\\helpers\\trim_value",
                "Other\\Three"
            ]
        );
    }

    #[test]
    fn scans_imports_and_risks() {
        let facts = scan(SRC);
        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
        assert_eq!(
            specs,
            [
                "App\\Util\\Str",
                "GuzzleHttp\\Client",
                "Symfony\\Component\\Yaml\\Yaml",
                "./helpers.php"
            ]
        );
        for risk in [
            Risk::Exceptions,
            Risk::RegexSyntax,
            Risk::DivisionSemantics,
            Risk::Generators,
            Risk::ClassInheritance,
            Risk::DynamicCode,
            Risk::StringOffsets,
        ] {
            assert!(
                facts.risks.contains_key(&risk),
                "{risk:?}: {:?}",
                facts.risks
            );
        }
        assert_eq!(package_of("GuzzleHttp\\Client"), "guzzlehttp/guzzle");
        assert_eq!(
            package_of("Symfony\\Component\\HttpFoundation\\Request"),
            "symfony/http-foundation"
        );
        assert_eq!(pcre_body("'#a+#i'"), Some("a+"));
        assert_eq!(pcre_body("'{x}u'"), Some("x"));
    }

    #[test]
    fn reads_composer() {
        let text = r#"{"name": "acme/tool", "require": {"php": ">=8.1", "ext-json": "*", "guzzlehttp/guzzle": "^7"},
               "require-dev": {"phpunit/phpunit": "^10"}, "autoload": {"psr-4": {"Acme\\": "src/"}},
               "autoload-dev": {"psr-4": {"Acme\\Tests\\": "tests/"}}}"#;
        let (name, deps, dev, src) = composer(text);
        assert_eq!(name.as_deref(), Some("acme/tool"));
        assert_eq!(deps, ["guzzlehttp/guzzle"]);
        assert_eq!(dev, ["phpunit/phpunit"]);
        assert_eq!(src.as_deref(), Some("src"));
        assert_eq!(own_namespaces(text), ["Acme", "Acme\\Tests"]);
    }

    #[test]
    fn a_builtin_type_survives_a_nullable_mark_and_a_union_or_intersection() {
        // `?` at the front and `|` or `&` between parts are the only things stripped, and the
        // parts may carry spaces and any case. Parentheses are trimmed from each part's ends, so
        // a parenthesized union of built-ins is plain too.
        for plain in [
            "int",
            "?int",
            "INT",
            "string | null",
            "int|string",
            "int&string",
            "(int|string)",
            "?array",
            "mixed",
            "true|false",
            "void",
            "never",
        ] {
            assert!(plain_type(plain), "{plain}");
        }
        // One class name anywhere makes the whole type unknown: `(A&B)|null` is split on the `&`
        // inside the parentheses, so `A` and `B` are read as parts of their own.
        for known in ["User", "\\App\\User", "(A&B)|null", "int|User"] {
            assert!(!plain_type(known), "{known}");
        }
    }

    #[test]
    fn a_bare_array_is_array_iterable_or_null_and_nothing_else() {
        for bare in [
            "array",
            "?array",
            "iterable",
            "iterable|null",
            "NULL",
            "?ITERABLE",
        ] {
            assert!(bare_array(bare), "{bare}");
        }
        // A key type, another built-in or a class name is more than a bare array.
        for typed in ["array<string>", "array|string", "int", "User"] {
            assert!(!bare_array(typed), "{typed}");
        }
    }

    #[test]
    fn a_literal_default_names_its_dialect_type() {
        // Quotes come first, so a numeric-looking string stays a string.
        assert_eq!(literal_type("'-'"), Some("string"));
        assert_eq!(literal_type("\"x\""), Some("string"));
        assert_eq!(literal_type("'0'"), Some("string"));
        assert_eq!(literal_type("TRUE"), Some("boolean"));
        assert_eq!(literal_type("false"), Some("boolean"));
        assert_eq!(literal_type("0"), Some("int"));
        assert_eq!(literal_type("-3"), Some("int"));
        assert_eq!(literal_type("1.5"), Some("number"));
        assert_eq!(literal_type("[]"), Some("unknown[]"));
        // A class constant, a global constant or a bare name is not a literal default.
        assert_eq!(literal_type("self::X"), None);
        assert_eq!(literal_type("PHP_EOL"), None);
    }

    #[test]
    fn a_default_in_parentheses_keeps_its_parentheses() {
        let src = "<?php\nfunction pad(string $s, $opts = array()) { return $s; }\n";
        let fns = exports("src/pad.php", src);
        assert_eq!(
            fns[0].prototype.as_deref(),
            Some("pad(string $s, $opts = array())")
        );
    }

    #[test]
    fn unique_static_method_keeps_bare_name_while_clashes_qualify() {
        let str_src = "<?php\nnamespace Acme\\Clash;\nfinal class Str {\n    public static function length(string $s): int { return strlen($s); }\n    public static function count(string $s): int { return strlen($s); }\n}\n";
        let arr_src = "<?php\nnamespace Acme\\Clash;\nfinal class Arr {\n    public static function length(string $s): int { return str_word_count($s); }\n}\n";

        // Unique within a single file keeps the bare name.
        let single = exports("src/Str.php", str_src);
        assert_eq!(
            single.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
            ["length", "count"]
        );

        // Across files in the same unit, only the clashing name gets qualified.
        let mut combined = single;
        combined.extend(exports("src/Arr.php", arr_src));
        qualify_clashing_methods(&mut combined);
        assert_eq!(
            combined.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
            ["Str::length", "count", "Arr::length"]
        );

        // Top-level function + static method with the same bare name.
        let mut mixed = exports(
            "src/funcs.php",
            "<?php\nfunction normalize(string $s): string { return $s; }\n",
        );
        mixed.extend(exports(
            "src/Text.php",
            "<?php\nfinal class Text {\n    public static function normalize(string $s): string { return $s; }\n}\n",
        ));
        qualify_clashing_methods(&mut mixed);
        assert_eq!(
            mixed.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
            ["normalize", "Text::normalize"]
        );
    }
}