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.

67.2 KB
Raw Blame
//! Builds the migration plan: units, their dependency graph, port order and readiness.
//!
//! A *unit* is the smallest thing we suggest porting at once: a folder of source files,
//! or a single file that sits directly in a package's source root.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::Path;

use anyhow::{Context, Result, bail};
use serde::Serialize;

use crate::lang::Lang;
use crate::risks::{Risk, Severity};
use crate::ts::deps::{self, Fit};
use crate::ts::discover::{self, FileKind, Package, Workspace};
use crate::ts::scan::{self, FileFacts, Platform};

/// Version of the JSON output. Bump on any breaking change to its shape.
pub const SCHEMA: &str = "rust-anything/analyze@1";
const SAMPLES_PER_RISK: usize = 3;
/// Units smaller than this are not suggested as a first port.
const MIN_CANDIDATE_LOC: usize = 20;
/// A unit with more high-severity risk hits than this is `caution`, not `ready`.
const MAX_READY_HIGH_HITS: usize = 25;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Status {
    /// Good to port now.
    Ready,
    /// Portable, with risks to handle first.
    Caution,
    /// Depends on something with no Rust equivalent, or on dynamic code.
    Blocked,
    /// UI or editor code: stays in JS/TS.
    Keep,
}

impl Status {
    pub fn label(self) -> &'static str {
        match self {
            Self::Ready => "ready",
            Self::Caution => "caution",
            Self::Blocked => "blocked",
            Self::Keep => "keep",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Bridge {
    NapiRs,
    WasmBindgen,
    /// Keep in the source language (named for JS, the first language; applies to all).
    KeepInJs,
    Pyo3,
    /// A C ABI: drop-in `extern "C"` functions for C.
    CAbi,
    /// Go through cgo over a C ABI.
    Cgo,
    /// Ruby through a magnus native extension. `--json` keeps the value `fiddle`, which the
    /// bridge was called before it generated magnus crates, so readers of it keep working.
    #[serde(rename = "fiddle")]
    Magnus,
    Jni,
    /// PHP through its FFI extension over a C ABI.
    PhpFfi,
    DotnetFfi,
    /// PowerShell through P/Invoke over a C ABI, declared at run time with Reflection.Emit.
    PwshFfi,
    /// Swift through a C module map over a C ABI.
    SwiftFfi,
}

impl Bridge {
    pub fn label(self) -> &'static str {
        match self {
            Self::NapiRs => "napi-rs",
            Self::WasmBindgen => "wasm-bindgen",
            Self::KeepInJs => "keep",
            Self::Pyo3 => "PyO3",
            Self::CAbi => "C ABI",
            Self::Cgo => "cgo",
            Self::Magnus => "magnus",
            Self::Jni => "JNI",
            Self::PhpFfi => "PHP FFI (C ABI)",
            Self::DotnetFfi => "P/Invoke (C ABI)",
            Self::PwshFfi => "PowerShell P/Invoke (C ABI)",
            Self::SwiftFfi => "Swift module map (C ABI)",
        }
    }

    /// The bridge a language uses for code that can move.
    pub fn for_lang(lang: Lang) -> Self {
        match lang {
            Lang::Ts => Self::NapiRs,
            Lang::Python => Self::Pyo3,
            Lang::C => Self::CAbi,
            Lang::Go => Self::Cgo,
            Lang::Ruby => Self::Magnus,
            Lang::Java | Lang::Kotlin => Self::Jni,
            Lang::Php => Self::PhpFfi,
            Lang::Csharp => Self::DotnetFfi,
            Lang::Powershell => Self::PwshFfi,
            Lang::Swift => Self::SwiftFfi,
        }
    }
}

/// The Rust counterpart of a dependency, from the language's table.
pub fn crate_for(lang: Lang, name: &str) -> Option<deps::CrateMatch> {
    match lang {
        Lang::Ts => deps::lookup(name),
        Lang::Python => crate::lang::python::lookup(name),
        _ => crate::lang::lookup(lang, name),
    }
}

#[derive(Debug, Serialize)]
pub struct Report {
    pub schema: &'static str,
    pub language: Lang,
    pub summary: Summary,
    pub packages: Vec<PackageReport>,
    pub units: Vec<UnitReport>,
    /// Unit ids suggested as the first ports, best first.
    pub start_here: Vec<String>,
    pub dependencies: Vec<DependencyReport>,
    /// `analyze --whole-app`: entry points, every dependency, pieces and decisions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub whole_app: Option<crate::whole_app::WholeApp>,
    /// Problems with the input itself, such as every source file being excluded by ignore rules.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

/// How the warning for a folder with no source of a supported language starts; the folder follows.
pub const NO_SOURCE: &str = "no source files of a supported language \
    (TS/JS, Python, C, Go, Ruby, Java, Kotlin, PHP, C#, PowerShell, Swift)";

impl Report {
    /// The warning that the folder has no source file of a supported language, when `analyze`
    /// gave it: the plan and the port map say so instead of describing an empty project.
    pub fn no_source_warning(&self) -> Option<&str> {
        self.warnings
            .iter()
            .map(String::as_str)
            .find(|w| w.starts_with(NO_SOURCE))
    }
}

#[derive(Debug, Default, Serialize)]
pub struct Summary {
    pub packages: usize,
    pub source_files: usize,
    pub test_files: usize,
    pub ui_files: usize,
    pub loc: usize,
    pub units: usize,
    pub ready: usize,
    pub caution: usize,
    pub blocked: usize,
    pub keep: usize,
    pub parse_errors: usize,
}

#[derive(Debug, Serialize)]
pub struct PackageReport {
    pub name: String,
    pub dir: String,
    /// Position in dependency order: packages come after the workspace packages they use.
    pub order: usize,
    /// `node` when any of its code uses Node APIs, else `portable`.
    pub runtime: &'static str,
    pub workspace_deps: Vec<String>,
    pub test_files: usize,
    pub units: Vec<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct UnitReport {
    pub id: String,
    pub package: String,
    pub files: Vec<String>,
    pub loc: usize,
    /// Port order inside the repo: a unit's dependencies are in earlier waves.
    pub wave: usize,
    /// 0-100: how safe and easy a port looks from the code alone.
    pub readiness: u32,
    pub status: Status,
    pub bridge: Bridge,
    pub platforms: Vec<Platform>,
    pub risks: Vec<RiskReport>,
    pub internal_deps: Vec<String>,
    pub workspace_deps: Vec<String>,
    pub external_deps: Vec<String>,
    /// Test files that import this unit directly.
    pub direct_tests: usize,
    /// Units that import this one.
    pub fan_in: usize,
    /// Loops and string-offset operations per 100 lines: a rough hint of compute-heavy code.
    pub density: f64,
    /// 0-100: readiness balanced with value (compute-heavy, tested, big enough to matter).
    /// `start_here` is ordered by it.
    pub priority: u32,
    /// Exported functions and classes, and how many of them can cross a bridge unchanged.
    pub exports: usize,
    pub bridgeable: usize,
    /// Files of the unit with a syntax error, or that are not valid UTF-8: the export list above
    /// may be missing functions that follow the error, so `bridge` refuses it without `--force`.
    pub parse_errors: usize,
    /// Which of the unit's `files` those are, so bridging one file of the unit is judged by that
    /// file alone.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parse_error_files: Vec<String>,
    pub notes: Vec<String>,
    /// The notes that explain `status` when it is blocked or keep, for `map`.
    #[serde(skip)]
    pub reasons: Vec<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct RiskReport {
    pub risk: Risk,
    pub severity: Severity,
    pub count: usize,
    /// `path:line` of the first occurrences.
    pub samples: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct DependencyReport {
    pub name: String,
    pub used_by: usize,
    pub crates: Option<&'static str>,
    /// `good`, `partial`, `none`, or `unknown` when the table has no entry.
    pub fit: &'static str,
    pub note: &'static str,
}

/// What an import specifier points at.
enum Target {
    File(usize),
    Workspace(String),
    External(String),
    Platform,
    Unresolved,
}

#[derive(Default)]
struct UnitBuild {
    id: String,
    package: usize,
    files: Vec<usize>,
    ui: bool,
    loc: usize,
    loops: usize,
    risks: BTreeMap<Risk, (usize, Vec<String>)>,
    platforms: BTreeSet<Platform>,
    deps: BTreeSet<usize>,
    workspace_deps: BTreeSet<String>,
    external_deps: BTreeSet<String>,
    unresolved: usize,
    /// One note per parameter decoded inside an exported function (TS/JS).
    decoded: Vec<String>,
    parse_errors: usize,
    /// The files that counted in `parse_errors`.
    parse_error_files: Vec<usize>,
    direct_tests: usize,
    fan_in: usize,
}

/// Compiled or packaged files: what someone may point `analyze` at instead of source.
const COMPILED: [&str; 17] = [
    "apk", "aab", "ipa", "xapk", "jar", "war", "aar", "class", "dex", "exe", "dll", "so", "dylib",
    "wasm", "pyc", "msi", "appimage",
];

fn compiled_hint() -> &'static str {
    "rust-anything ports source code: it parses functions, records what they do, and checks the \
     Rust port against the running original. A compiled app (an APK, a JAR, an .exe) has no \
     source to port and no way to record it function by function. Point it at the app's source \
     folder instead; for an app you only have as a binary, writing a new Rust app from its \
     visible behavior is a separate project"
}

/// The source files of *other* supported languages under `root`, by language: a repository is analysed
/// as one language, and a file of another one is not a source file here. Counting them lets the plan
/// say why a mixed folder came out empty instead of saying nothing.
fn other_language_sources(root: &Path, lang: Lang) -> Vec<(Lang, usize)> {
    use clap::ValueEnum;
    let mut counts: BTreeMap<&'static str, (Lang, usize)> = BTreeMap::new();
    for entry in crate::walk::builder(root).build().flatten() {
        // `.flatten()` yields directories too: a folder called `example.py` is not a Python source.
        if !entry.file_type().is_some_and(|t| t.is_file()) {
            continue;
        }
        let Some(ext) = entry.path().extension().and_then(|e| e.to_str()) else {
            continue;
        };
        for other in Lang::value_variants() {
            if *other == lang || !other.extensions().contains(&ext) {
                continue;
            }
            // That language's own discovery skips its dependency tree and virtual environments, so
            // counting those files would suggest a language that then finds nothing. Only components
            // inside `root` count: a project that happens to live under a folder called `docs` is not
            // skipped by discovery, which starts at `root`.
            let skipped = other.skip_dirs();
            let Ok(rel) = entry.path().strip_prefix(root) else {
                continue;
            };
            if rel
                .components()
                .any(|c| skipped.contains(&c.as_os_str().to_string_lossy().as_ref()))
            {
                continue;
            }
            let slot = counts.entry(other.name()).or_insert((*other, 0));
            slot.1 += 1;
        }
    }
    counts.into_values().collect()
}

pub fn analyze(root: &Path) -> Result<Report> {
    analyze_opts(root, None)
}

pub fn analyze_lang(root: &Path, lang: Lang) -> Result<Report> {
    analyze_opts(root, Some(lang))
}

pub fn analyze_opts(root: &Path, requested_lang: Option<Lang>) -> Result<Report> {
    let lang = requested_lang.unwrap_or_else(|| Lang::detect(root));
    if !root
        .try_exists()
        .with_context(|| format!("reading {}", root.display()))?
    {
        bail!("no folder {}", root.display());
    }
    if root.is_file() {
        let ext = root
            .extension()
            .map(|e| e.to_string_lossy().to_lowercase())
            .unwrap_or_default();
        if COMPILED.contains(&ext.as_str()) {
            bail!(
                "{} is a compiled .{ext} file. {}",
                root.display(),
                compiled_hint()
            );
        }
        bail!(
            "{} is a file; `analyze` takes the folder of a project's source code",
            root.display()
        );
    }
    let ws = match lang {
        Lang::Ts => discover::discover(root)?,
        _ => crate::lang::discover(lang, root)?,
    };
    let not_utf8 = std::cell::RefCell::new(Vec::<String>::new());
    let mut facts: Vec<Option<FileFacts>> = ws
        .files
        .iter()
        .map(|file| {
            let (text, lossy) = read_source(&root.join(&file.path))?;
            if lossy {
                not_utf8.borrow_mut().push(file.path.clone());
            }
            if lang == Lang::C {
                let mut facts = crate::lang::scan(lang, &file.path, &text);
                if let Some(header) = own_header(root, &file.path) {
                    facts
                        .imports
                        .extend(crate::lang::scan(lang, &header.0, &header.1).imports);
                }
                return Some(facts);
            }
            if lang != Lang::Ts {
                return Some(crate::lang::scan(lang, &file.path, &text));
            }
            let code = crate::ts::script_of(&file.path, &text);
            let is_sfc = [".vue", ".svelte", ".astro"]
                .iter()
                .any(|e| file.path.ends_with(e));
            let parse_as = if is_sfc { "sfc.ts" } else { file.path.as_str() };
            Some(scan::scan(parse_as, &code))
        })
        .collect();
    // A file read with replacement characters is a file the scan may have misread: count it as
    // a parse error, so its unit is `caution` and says the results are partial.
    let not_utf8 = not_utf8.into_inner();
    for (file, f) in ws.files.iter().zip(&mut facts) {
        if let Some(f) = f
            && not_utf8.contains(&file.path)
        {
            f.parse_errors += 1;
        }
    }
    let mut report = build(root, &ws, &facts, lang, requested_lang);
    if !not_utf8.is_empty() {
        let (what, them) = if not_utf8.len() == 1 {
            ("1 source file is", "it")
        } else {
            ("source files are", "them")
        };
        let what = if not_utf8.len() == 1 {
            what.to_string()
        } else {
            format!("{} {what}", not_utf8.len())
        };
        report.warnings.push(format!(
            "{what} not valid UTF-8 and read with replacement characters (results for their \
             units are partial): {}. Save {them} as UTF-8 to analyze {them}.",
            not_utf8.join(", "),
        ));
    }
    // A language the folder does not hold (a typo, or code in a subfolder) would read like a
    // finished plan with nothing to do. Any file of the language counts, UI and tests included,
    // and the warnings (files hidden by ignore rules) say why the plan would have been empty.
    if ws.files.is_empty()
        && let Some(detected) = Lang::detect_optional(root)
        && detected != lang
    {
        // The mixed-folder warning says this again, and its advice ("passing `--lang` picks
        // another") is what the user just did (issue #1206).
        let mixed = format!("no {} source file was analyzed, but ", lang.name());
        let reasons: String = report
            .warnings
            .iter()
            .filter(|w| !w.starts_with(&mixed))
            .map(|w| {
                let mut chars = w.chars();
                match chars.next() {
                    Some(first) => format!(". {}{}", first.to_uppercase(), chars.as_str()),
                    None => String::new(),
                }
            })
            .collect();
        // The value the CLI accepts, not the file extension: `cs` is `csharp`, `ps1` is `powershell`
        // (review of #1206). The retained warnings come before the fix, so the sentence ends with
        // what to do.
        use clap::ValueEnum as _;
        let hint = detected
            .to_possible_value()
            .map(|v| v.get_name().to_string())
            .unwrap_or_default();
        bail!(
            "no {} source files found; the code here looks like {}{reasons}: drop --lang, or pass --lang {hint}",
            lang.name(),
            detected.name()
        );
    }
    check_bridgeable(root, &mut report, lang);
    Ok(report)
}

/// A source file's text. A file that is not UTF-8 (Latin-1 Java, UTF-16 PowerShell saved from the
/// ISE) is decoded rather than skipped: UTF-16 by its byte-order mark, anything else with
/// replacement characters. The flag says the text may not be what the file holds.
pub fn read_source(path: &Path) -> Option<(String, bool)> {
    let bytes = std::fs::read(path).ok()?;
    match String::from_utf8(bytes) {
        Ok(text) => Some((text, false)),
        Err(e) => {
            let bytes = e.into_bytes();
            let utf16 = |le: bool| {
                let (pairs, rest) = bytes[2..].as_chunks::<2>();
                // A byte left over is a code unit cut off: the text is not what was written.
                if !rest.is_empty() {
                    return None;
                }
                let units: Vec<u16> = pairs
                    .iter()
                    .map(|p| {
                        if le {
                            u16::from_le_bytes([p[0], p[1]])
                        } else {
                            u16::from_be_bytes([p[0], p[1]])
                        }
                    })
                    .collect();
                String::from_utf16(&units).ok()
            };
            let decoded = match bytes.get(..2) {
                Some([0xff, 0xfe]) => utf16(true),
                Some([0xfe, 0xff]) => utf16(false),
                _ => None,
            };
            match decoded {
                Some(text) => Some((text, false)),
                None => Some((String::from_utf8_lossy(&bytes).into_owned(), true)),
            }
        }
    }
}

fn own_header(root: &Path, unit: &str) -> Option<(String, String)> {
    let stem = unit.strip_suffix(".c")?;
    let name = stem.rsplit('/').next().unwrap_or(stem);
    [format!("{stem}.h"), format!("include/{name}.h")]
        .into_iter()
        .find_map(|h| Some((h.clone(), std::fs::read_to_string(root.join(&h)).ok()?)))
}

/// Counts each unit's exports that can cross a bridge, with the rules `bridge` applies. A unit
/// whose exports are all JS-shaped (plugin objects, callbacks) cannot be ported without an API
/// change: it is marked `caution` and left out of `start_here`.
fn check_bridgeable(root: &Path, report: &mut Report, lang: Lang) {
    use crate::ts::exports::exported_classes;
    crate::profile::use_project_types(root, lang);
    // Every file of every unit reaches the same barrels and workspace packages: parse each once.
    let mut type_cache = crate::bridge::TypeCache::default();
    let mut outside_index = None;
    for unit in &mut report.units {
        let (mut exports, mut bridgeable) = (0, 0);
        let mut foreign = Vec::new();
        for file in &unit.files {
            let Some((text, _)) = read_source(&root.join(file)) else {
                continue;
            };
            let types = crate::bridge::types_in_scope_cached(root, file, &text, &mut type_cache);
            if lang != Lang::Ts {
                let (functions, classes) = crate::lang::exports(lang, file, &text);
                exports += functions.len() + classes.len();
                foreign.extend(functions);
                bridgeable += classes
                    .iter()
                    .filter(|c| crate::bridge::class_reason(c, &[], false).is_none())
                    .count();
                continue;
            }
            // A component's markup is not TypeScript: count from its `<script>` blocks, as the scan does.
            let code = crate::ts::script_of(file, &text);
            for f in crate::bridge::ts_functions(root, file, &code, &types) {
                exports += 1;
                bridgeable += usize::from(crate::bridge::js_only_reason(&f, &types).is_none());
            }
            for class in exported_classes(file, &code) {
                exports += 1;
                bridgeable +=
                    usize::from(crate::bridge::class_reason(&class, &types, true).is_none());
            }
        }
        // The same call chain `bridge` follows: a helper in another unit carries the state it reads
        // (issue #1042), so `bridgeable` has to count the same exports as `bridge`.
        let outside = crate::bridge::outside_state_calls(lang, root, &mut outside_index, &foreign);
        // The reason `bridge` gives each kept export, in order: the first one names the note.
        let kept: Vec<(String, String)> = foreign
            .iter()
            .zip(crate::bridge::state_through_calls_with(&foreign, &outside))
            .filter_map(|(f, state)| {
                state
                    .or_else(|| crate::bridge::js_only_reason(f, &[]))
                    .map(|why| (f.name.clone(), why))
            })
            .collect();
        bridgeable += foreign.len() - kept.len();
        unit.exports = exports;
        unit.bridgeable = bridgeable;
        // A unit that stays in the original keeps its status, but its exports are still there.
        if matches!(unit.status, Status::Keep | Status::Blocked) {
            continue;
        }
        if exports > 0 && bridgeable == 0 {
            unit.status = Status::Caution;
            let note = match lang {
                Lang::C => "No export can cross the C ABI bridge (contexts, function pointers, \
                     structs by value, pointers it cannot pair with a length): bridge a wrapper \
                     with plain arguments, an API change."
                    .to_string(),
                Lang::Ts => "Every export is JS-shaped (functions, plugin objects, iterators): \
                     porting the logic means adding a data-only function, an API change."
                    .to_string(),
                // Other languages keep an export for the reason `bridge` gives (#1402): the
                // clock, the environment, app state, a type the wrapper cannot carry.
                _ => match kept.first() {
                    Some((name, why)) => format!(
                        "No export can be bridged: `{name}` {why}. Pass what it reads in as a \
                         parameter, or change the signature, an API change."
                    ),
                    None => "No export can be bridged as it is: `bridge` names each export's \
                         reason; porting means an API change."
                        .to_string(),
                },
            };
            unit.notes.insert(0, note);
        }
    }
    let summary = &mut report.summary;
    (
        summary.ready,
        summary.caution,
        summary.blocked,
        summary.keep,
    ) = (0, 0, 0, 0);
    for u in &report.units {
        match u.status {
            Status::Ready => summary.ready += 1,
            Status::Caution => summary.caution += 1,
            Status::Blocked => summary.blocked += 1,
            Status::Keep => summary.keep += 1,
        }
    }
    report.start_here = start_here(&report.units);
    note_caution_starts(&mut report.units, &report.start_here);
}

/// A `caution` unit is listed in `start_here` only when too few are ready; the report's table has
/// no status column, so the unit says it itself.
fn note_caution_starts(units: &mut [UnitReport], start: &[String]) {
    for u in units
        .iter_mut()
        .filter(|u| u.status == Status::Caution && start.contains(&u.id))
    {
        u.notes.push(
            "Status caution: listed under start here only because fewer than three units are \
             ready. Read its risks before you pick it."
                .into(),
        );
    }
}

fn build(
    root: &Path,
    ws: &Workspace,
    facts: &[Option<FileFacts>],
    lang: Lang,
    requested_lang: Option<Lang>,
) -> Report {
    let file_index: HashMap<&str, usize> = ws
        .files
        .iter()
        .enumerate()
        .map(|(i, f)| (f.path.as_str(), i))
        .collect();
    let workspace_names: HashSet<&str> = ws.packages.iter().map(|p| p.name.as_str()).collect();
    let alias_cache: std::cell::RefCell<HashMap<String, crate::ts::tsconfig::PathAliases>> =
        std::cell::RefCell::new(HashMap::new());
    // Every import of a run asks the same questions of the same file paths: answer them once.
    let resolve_cache = crate::lang::ResolveCache::default();
    let classify = |from: &str, spec: &str| -> Target {
        if lang != Lang::Ts {
            return match crate::lang::resolve_cached(
                lang,
                from,
                spec,
                &file_index,
                ws,
                &resolve_cache,
            ) {
                crate::lang::Resolution::File(i) => Target::File(i),
                crate::lang::Resolution::External(name) => Target::External(name),
                crate::lang::Resolution::Stdlib => Target::Platform,
                crate::lang::Resolution::Unresolved => Target::Unresolved,
            };
        }
        if spec.starts_with("./") || spec.starts_with("../") || spec == "." || spec == ".." {
            return resolve_relative(from, spec, &file_index)
                .map_or(Target::Unresolved, Target::File);
        }
        if scan::platform_of(spec).is_some() {
            return Target::Platform;
        }
        // tsconfig `paths` (`~/utils`, `@/lib`), from the tsconfig nearest the importing file.
        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
        let aliases = alias_cache
            .borrow_mut()
            .entry(dir.to_string())
            .or_insert_with(|| crate::ts::tsconfig::PathAliases::nearest(root, dir))
            .clone();
        let candidates = aliases.candidates(spec);
        if let Some(file) = candidates
            .iter()
            .find_map(|base| resolve_base(base, &file_index))
        {
            return Target::File(file);
        }
        if spec.starts_with('#')
            || spec.starts_with('~')
            || spec.starts_with("@/")
            || spec.contains(':')
        {
            return Target::Unresolved;
        }
        let name = deps::package_name(spec);
        if workspace_names.contains(name) {
            Target::Workspace(name.to_string())
        } else {
            Target::External(name.to_string())
        }
    };

    // Group source and UI files into units.
    let mut units: Vec<UnitBuild> = Vec::new();
    let mut unit_ids: HashMap<String, usize> = HashMap::new();
    let mut unit_of: Vec<Option<usize>> = vec![None; ws.files.len()];
    for (i, file) in ws.files.iter().enumerate() {
        if file.kind == FileKind::Test {
            continue;
        }
        let id = unit_id(&ws.packages[file.package], &file.path);
        let u = *unit_ids.entry(id.clone()).or_insert_with(|| {
            units.push(UnitBuild {
                id,
                package: file.package,
                ..UnitBuild::default()
            });
            units.len() - 1
        });
        units[u].files.push(i);
        units[u].ui |= file.kind == FileKind::Ui;
        unit_of[i] = Some(u);
    }

    // Aggregate facts and imports per unit; credit tests to what they import.
    let mut package_tests = vec![0usize; ws.packages.len()];
    let mut summary = Summary {
        packages: ws.packages.len(),
        ..Summary::default()
    };
    for (i, file) in ws.files.iter().enumerate() {
        match file.kind {
            FileKind::Source => summary.source_files += 1,
            FileKind::Test => summary.test_files += 1,
            FileKind::Ui => summary.ui_files += 1,
        }
        let Some(f) = &facts[i] else { continue };
        summary.parse_errors += usize::from(f.parse_errors > 0);
        if file.kind == FileKind::Test {
            package_tests[file.package] += 1;
            let mut hit_units = BTreeSet::new();
            let mut hit_packages = BTreeSet::new();
            for import in &f.imports {
                match classify(&file.path, &import.specifier) {
                    Target::File(j) => hit_units.extend(unit_of[j]),
                    Target::Workspace(name) => {
                        hit_packages.extend(ws.packages.iter().position(|p| p.name == name));
                    }
                    _ => {}
                }
            }
            for u in hit_units {
                units[u].direct_tests += 1;
            }
            for p in hit_packages.into_iter().filter(|&p| p != file.package) {
                package_tests[p] += 1;
            }
            continue;
        }
        let Some(u) = unit_of[i] else { continue };
        summary.loc += f.loc;
        let unit = &mut units[u];
        unit.loc += f.loc;
        unit.loops += f.loops;
        unit.parse_errors += f.parse_errors;
        if f.parse_errors > 0 {
            unit.parse_error_files.push(i);
        }
        unit.platforms.extend(f.platforms.iter().copied());
        if lang == Lang::C && crate::lang::c::in_arch_dir(&file.path) {
            let entry = unit.risks.entry(Risk::PlatformSpecific).or_default();
            entry.0 += 1;
            if entry.1.len() < SAMPLES_PER_RISK {
                entry.1.push(format!("{}:1", file.path));
            }
        }
        for (risk, lines) in &f.risks {
            let entry = unit.risks.entry(*risk).or_default();
            entry.0 += lines.len();
            for line in lines {
                let sample = format!("{}:{line}", file.path);
                // Several hits on one line count separately but share one sample, so the slots
                // go to distinct locations.
                if entry.1.len() < SAMPLES_PER_RISK && !entry.1.contains(&sample) {
                    entry.1.push(sample);
                }
            }
        }
        unit.decoded.extend(f.decoded.iter().map(|d| {
            format!(
                "{}: `{}` is decoded inside ({}, {}:{}): {}",
                d.function,
                d.param,
                d.call,
                file.path,
                d.line,
                scan::DECODED_INPUT_ADVICE
            )
        }));
        for import in &f.imports {
            match classify(&file.path, &import.specifier) {
                Target::File(j) => {
                    if let Some(v) = unit_of[j].filter(|&v| v != u) {
                        units[u].deps.insert(v);
                    }
                }
                Target::Workspace(name) => {
                    if name != ws.packages[units[u].package].name {
                        units[u].workspace_deps.insert(name);
                    }
                }
                Target::External(name) if !import.type_only => {
                    units[u].external_deps.insert(name);
                }
                Target::Unresolved if !import.type_only => units[u].unresolved += 1,
                Target::Unresolved => {}
                Target::External(_) | Target::Platform => {}
            }
        }
    }
    for u in 0..units.len() {
        for v in units[u].deps.clone() {
            units[v].fan_in += 1;
        }
    }

    let edges: Vec<Vec<usize>> = units
        .iter()
        .map(|u| u.deps.iter().copied().collect())
        .collect();
    let (waves, cycles) = waves(&edges);
    // A unit needs Node when it, or anything it imports, uses Node APIs.
    let node_reach = reaches(
        &edges,
        &units
            .iter()
            .map(|u| u.platforms.contains(&Platform::Node))
            .collect::<Vec<_>>(),
    );
    // A package is Node-only when its source root needs Node; build scripts beside it do not count.
    let node_packages: BTreeSet<usize> = units
        .iter()
        .enumerate()
        .filter(|(u, unit)| {
            let src = &ws.packages[unit.package].src_root;
            node_reach[*u] && (src.is_empty() || unit.id.starts_with(&format!("{src}/")))
        })
        .map(|(_, unit)| unit.package)
        .collect();
    let ctx = Ctx {
        lang,
        ws,
        units: &units,
        package_tests: &package_tests,
        node_packages: &node_packages,
        node_reach: &node_reach,
        waves: &waves,
        cycles: &cycles,
    };
    let mut reports: Vec<UnitReport> = (0..units.len()).map(|u| score(u, &ctx)).collect();
    reports.sort_by(|a, b| a.id.cmp(&b.id));
    for r in &reports {
        match r.status {
            Status::Ready => summary.ready += 1,
            Status::Caution => summary.caution += 1,
            Status::Blocked => summary.blocked += 1,
            Status::Keep => summary.keep += 1,
        }
    }
    summary.units = reports.len();

    let start_here = start_here(&reports);
    note_caution_starts(&mut reports, &start_here);
    let packages = package_reports(ws, &reports, &package_tests, &node_packages);
    let dependencies = dependency_reports(&reports, lang);
    let mut warnings = Vec::new();
    if ws.files.is_empty() {
        let hidden = crate::walk::ignored_files(root, lang.extensions());
        let compiled = crate::walk::builder(root)
            .standard_filters(false)
            .max_depth(Some(4))
            .build()
            .flatten()
            .filter(|e| {
                e.path().extension().is_some_and(|x| {
                    COMPILED.contains(&x.to_string_lossy().to_lowercase().as_str())
                })
            })
            .count();
        if hidden == 0 && compiled > 0 {
            warnings.push(format!(
                "no source files were found, only {}. {}",
                crate::report::count(compiled, "compiled or packaged file"),
                compiled_hint()
            ));
        }
        if hidden > 0 {
            warnings.push(format!(
                "no source files were analyzed, but {} under {} {} excluded by \
                 ignore rules (.gitignore or .ignore files in this repository); the plan is empty \
                 because of them, not because there is nothing to port",
                crate::report::count(hidden, &format!("{} file", lang.name())),
                root.display(),
                if hidden == 1 { "is" } else { "are" },
            ));
        }
        // A mixed folder: files of another language are there, but this plan is for `lang`, so they
        // are not sources here. Saying so beats "No unit to port was found" with no reason.
        let others = other_language_sources(root, lang);
        if !others.is_empty() {
            let listed: Vec<String> = others
                .iter()
                .map(|(other, n)| {
                    format!("{} of {}", crate::report::count(*n, "file"), other.name())
                })
                .collect();
            warnings.push(format!(
                "no {} source file was analyzed, but {} under {}: one repository is analyzed as one \
                 language, and passing `--lang` picks another",
                lang.name(),
                listed.join(", "),
                root.display()
            ));
        }
        if hidden == 0
            && compiled == 0
            && others.is_empty()
            && requested_lang.is_none()
            && Lang::detect_optional(root).is_none()
        {
            warnings.push(format!("{NO_SOURCE} under {}", root.display()));
        }
    }
    Report {
        schema: SCHEMA,
        language: lang,
        summary,
        packages,
        units: reports,
        start_here,
        dependencies,
        whole_app: None,
        warnings,
    }
}

struct Ctx<'a> {
    lang: Lang,
    ws: &'a Workspace,
    units: &'a [UnitBuild],
    package_tests: &'a [usize],
    node_packages: &'a BTreeSet<usize>,
    node_reach: &'a [bool],
    waves: &'a [usize],
    cycles: &'a [Vec<usize>],
}

fn score(u: usize, ctx: &Ctx) -> UnitReport {
    let unit = &ctx.units[u];
    let all = ctx.units;
    let ws = ctx.ws;
    let packages = &ws.packages;
    let package_tests = ctx.package_tests[unit.package];
    let wave = ctx.waves[u];
    let cycle = &ctx.cycles[u];
    let mut notes = Vec::new();
    let keep = unit.ui
        || unit.platforms.contains(&Platform::Ui)
        || unit.platforms.contains(&Platform::Editor);
    let blocking_deps: Vec<&String> = unit
        .external_deps
        .iter()
        .filter(|d| crate_for(ctx.lang, d).is_some_and(|m| m.fit == Fit::None))
        .collect();
    let unknown_deps = unit
        .external_deps
        .iter()
        .filter(|d| crate_for(ctx.lang, d).is_none())
        .count();

    let risk_points: f64 = unit
        .risks
        .iter()
        .map(|(risk, (count, _))| risk.severity().weight() * (1.0 + *count as f64).ln())
        .sum();
    // Readiness is a logarithm of each risk's count, so a hundred string slices cost little more
    // than ten: a unit with that many high-severity hits is not "ready" however short it is.
    let high_hits: usize = unit
        .risks
        .iter()
        .filter(|(risk, _)| risk.severity() == Severity::High)
        .map(|(_, (count, _))| *count)
        .sum();
    let size_penalty = unit.loc as f64 / 40.0;
    let fan_in_penalty = (unit.fan_in as f64 * 1.5).min(15.0);
    let dep_penalty = blocking_deps.len() as f64 * 12.0 + unknown_deps as f64 * 4.0;
    let test_bonus = if unit.direct_tests > 0 {
        10.0
    } else if package_tests > 0 {
        4.0
    } else {
        0.0
    };
    let readiness = (100.0 - risk_points - size_penalty - fan_in_penalty - dep_penalty
        + test_bonus)
        .clamp(0.0, 100.0);

    let platform = unit.risks.contains_key(&Risk::PlatformSpecific);
    let status = if platform {
        notes.push(
            "Depends on the target (hardware registers, memory layout, inline assembly): keep in \
             C, since a recording on this machine cannot vouch for the target."
                .to_string(),
        );
        Status::Keep
    } else if keep {
        notes.push(if unit.platforms.contains(&Platform::Editor) {
            "Runs in the editor's extension host: keep in TS.".to_string()
        } else {
            "UI code: keep in the original language.".to_string()
        });
        Status::Keep
    } else if !blocking_deps.is_empty() || unit.risks.contains_key(&Risk::DynamicCode) {
        for dep in &blocking_deps {
            notes.push(format!("`{dep}` has no Rust equivalent."));
        }
        if unit.risks.contains_key(&Risk::DynamicCode) {
            notes.push(
                "Uses dynamic code (eval, code built at runtime or computed imports).".into(),
            );
        }
        Status::Blocked
    } else if readiness < 50.0 || unit.parse_errors > 0 || high_hits > MAX_READY_HIGH_HITS {
        if high_hits > MAX_READY_HIGH_HITS && readiness >= 50.0 && unit.parse_errors == 0 {
            notes.push(format!(
                "{high_hits} places use constructs of high risk (string offsets, regex features, \
                 hash order, ...): port it with care, or in smaller pieces."
            ));
        }
        Status::Caution
    } else {
        Status::Ready
    };
    let reasons = notes.clone();
    if unit.parse_errors > 0 {
        notes.push(format!(
            "{}: results for this unit are partial.",
            crate::report::count(unit.parse_errors, "parse error")
        ));
    }
    if unknown_deps > 0 {
        let reg = ctx.lang.registry();
        notes.push(if unknown_deps == 1 {
            format!("1 {reg} dependency not in the crate table: check it by hand.")
        } else {
            format!("{unknown_deps} {reg} dependencies not in the crate table: check them by hand.")
        });
    }
    notes.extend(unit.decoded.iter().cloned());
    if unit.unresolved > 0 {
        notes.push(if unit.unresolved == 1 {
            "1 import uses aliases or virtual modules and was not followed.".into()
        } else {
            format!(
                "{} imports use aliases or virtual modules and were not followed.",
                unit.unresolved
            )
        });
    }
    if cycle.len() > 1 {
        let others: Vec<&str> = cycle
            .iter()
            .map(|&v| all[v].id.as_str())
            .filter(|id| *id != unit.id)
            .collect();
        notes.push(format!(
            "Import cycle with {}: port them together.",
            others.join(", ")
        ));
    }
    if !keep && !unit.deps.is_empty() {
        // A unit in wave 1 because it imports a sibling: say which, or the wave order is unexplained.
        let names: Vec<String> = unit
            .deps
            .iter()
            .map(|&v| format!("`{}`", all[v].id))
            .collect();
        notes.push(format!(
            "Imports {}: port {} first, or port them together.",
            names.join(", "),
            if names.len() == 1 { "it" } else { "them" }
        ));
    } else if unit.deps.is_empty() && !keep {
        if unit.workspace_deps.is_empty() {
            notes.push("Leaf: imports no other unit.".into());
        } else {
            let names: Vec<String> = unit
                .workspace_deps
                .iter()
                .map(|d| format!("`{d}`"))
                .collect();
            notes.push(format!(
                "Imports {} from another workspace package: port {} first.",
                names.join(", "),
                if names.len() == 1 {
                    "that package"
                } else {
                    "those packages"
                }
            ));
        }
    }
    if unit.direct_tests > 0 {
        notes.push(if unit.direct_tests == 1 {
            "1 test file imports it directly.".to_string()
        } else {
            format!("{} test files import it directly.", unit.direct_tests)
        });
    } else if package_tests == 0 && !keep {
        notes.push(
            "No tests found: write characterization tests against the original code first.".into(),
        );
    }

    let string_ops = unit.risks.get(&Risk::StringOffsets).map_or(0, |r| r.0);
    let per_100_lines = |n: usize| {
        if unit.loc == 0 {
            0.0
        } else {
            (n as f64 * 100.0 / unit.loc as f64 * 10.0).round() / 10.0
        }
    };
    let density = per_100_lines(unit.loops + string_ops);
    // What a port would speed up is loops. String offsets are counted in `density` for what they
    // say about the code, but they are also a penalised risk: they must not buy priority.
    let compute_density = per_100_lines(unit.loops);
    let bridge = if keep {
        Bridge::KeepInJs
    } else if ctx.lang != Lang::Ts {
        Bridge::for_lang(ctx.lang)
    } else if ctx.node_reach[u] || ctx.node_packages.contains(&unit.package) {
        Bridge::NapiRs
    } else {
        Bridge::WasmBindgen
    };
    if bridge == Bridge::WasmBindgen {
        notes.push(
            "Portable code: wasm-bindgen keeps it running in browsers and Node. It needs the \
             wasm32-unknown-unknown target and wasm-bindgen; `bridge --kind napi` runs with what \
             Node already has."
                .into(),
        );
    }

    let mut files: Vec<String> = unit
        .files
        .iter()
        .map(|&i| ws.files[i].path.clone())
        .collect();
    files.sort();
    let mut risks: Vec<RiskReport> = unit
        .risks
        .iter()
        .map(|(risk, (count, samples))| RiskReport {
            risk: *risk,
            severity: risk.severity(),
            count: *count,
            samples: samples.clone(),
        })
        .collect();
    risks.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.count.cmp(&a.count)));

    UnitReport {
        id: unit.id.clone(),
        package: packages[unit.package].name.clone(),
        files,
        loc: unit.loc,
        wave,
        readiness: readiness.round() as u32,
        status,
        bridge,
        platforms: unit.platforms.iter().copied().collect(),
        risks,
        internal_deps: unit.deps.iter().map(|&v| all[v].id.clone()).collect(),
        workspace_deps: unit.workspace_deps.iter().cloned().collect(),
        external_deps: unit.external_deps.iter().cloned().collect(),
        direct_tests: unit.direct_tests,
        fan_in: unit.fan_in,
        density,
        priority: priority(
            readiness,
            compute_density,
            unit.loc,
            unit.direct_tests,
            package_tests,
        ),
        exports: 0,
        bridgeable: 0,
        parse_errors: unit.parse_errors,
        parse_error_files: {
            let mut bad: Vec<String> = unit
                .parse_error_files
                .iter()
                .map(|&i| ws.files[i].path.clone())
                .collect();
            bad.sort();
            bad
        },
        notes,
        reasons,
    }
}

fn start_here(units: &[UnitReport]) -> Vec<String> {
    let pick = |statuses: &[Status], min_loc: usize| -> Vec<&UnitReport> {
        let mut list: Vec<&UnitReport> = units
            .iter()
            .filter(|u| statuses.contains(&u.status) && u.loc >= min_loc && u.bridgeable > 0)
            .collect();
        list.sort_by(|a, b| {
            b.priority
                .cmp(&a.priority)
                .then(b.readiness.cmp(&a.readiness))
                .then(a.wave.cmp(&b.wave))
                .then(b.density.total_cmp(&a.density))
                .then(a.id.cmp(&b.id))
        });
        list
    };
    let mut list = pick(&[Status::Ready], MIN_CANDIDATE_LOC);
    if list.len() < 3 {
        list = pick(&[Status::Ready, Status::Caution], MIN_CANDIDATE_LOC);
    }
    if list.is_empty() {
        // Small repos: every unit is under the size floor.
        list = pick(&[Status::Ready, Status::Caution], 1);
    }
    list.into_iter().take(10).map(|u| u.id.clone()).collect()
}

fn package_reports(
    ws: &Workspace,
    units: &[UnitReport],
    package_tests: &[usize],
    node_packages: &BTreeSet<usize>,
) -> Vec<PackageReport> {
    let names: HashMap<&str, usize> = ws
        .packages
        .iter()
        .enumerate()
        .map(|(i, p)| (p.name.as_str(), i))
        .collect();
    let deps_of: Vec<Vec<usize>> = ws
        .packages
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let mut d: Vec<usize> = p
                .deps
                .iter()
                .chain(&p.dev_deps)
                .filter_map(|n| names.get(n.as_str()).copied())
                .filter(|&j| j != i)
                .collect();
            d.sort_unstable();
            d.dedup();
            d
        })
        .collect();
    let order = topological(&deps_of);
    let mut reports: Vec<PackageReport> = order
        .iter()
        .map(|&i| {
            let p = &ws.packages[i];
            PackageReport {
                name: p.name.clone(),
                dir: p.dir.clone(),
                order: 0,
                runtime: if node_packages.contains(&i) {
                    "node"
                } else {
                    "portable"
                },
                workspace_deps: deps_of[i]
                    .iter()
                    .map(|&j| ws.packages[j].name.clone())
                    .collect(),
                test_files: package_tests[i],
                units: units
                    .iter()
                    .filter(|u| u.package == p.name)
                    .map(|u| u.id.clone())
                    .collect(),
            }
        })
        .filter(|p| !p.units.is_empty())
        .collect();
    for (position, report) in reports.iter_mut().enumerate() {
        report.order = position + 1;
    }
    reports
}

fn dependency_reports(units: &[UnitReport], lang: Lang) -> Vec<DependencyReport> {
    let mut used: BTreeMap<&str, usize> = BTreeMap::new();
    for unit in units.iter().filter(|u| u.status != Status::Keep) {
        for dep in &unit.external_deps {
            *used.entry(dep).or_default() += 1;
        }
    }
    let mut out: Vec<DependencyReport> = used
        .into_iter()
        .map(|(name, used_by)| {
            let found = crate_for(lang, name);
            DependencyReport {
                name: name.to_string(),
                used_by,
                crates: found.map(|m| m.crates),
                fit: match found.map(|m| m.fit) {
                    Some(Fit::Good) => "good",
                    Some(Fit::Partial) => "partial",
                    Some(Fit::None) => "none",
                    None => "unknown",
                },
                note: found.map_or("", |m| m.note),
            }
        })
        .collect();
    let rank = |fit: &str| match fit {
        "none" => 0,
        "unknown" => 1,
        "partial" => 2,
        _ => 3,
    };
    out.sort_by(|a, b| {
        rank(a.fit)
            .cmp(&rank(b.fit))
            .then(b.used_by.cmp(&a.used_by))
    });
    out
}

/// Readiness balanced with how much a port would gain.
fn priority(
    readiness: f64,
    density: f64,
    loc: usize,
    direct_tests: usize,
    package_tests: usize,
) -> u32 {
    let compute = (density * 4.0).min(50.0);
    let tests = if direct_tests > 0 {
        30.0
    } else if package_tests > 0 {
        15.0
    } else {
        0.0
    };
    // Below ~80 lines a port rarely pays for its bridge; past ~600 it is too big for a first step.
    let size = match loc {
        0..80 => loc as f64 / 4.0,
        80..600 => 20.0,
        _ => 10.0,
    };
    let value = compute + tests + size;
    (readiness * 0.5 + value * 0.5).round().clamp(0.0, 100.0) as u32
}

/// For each node, whether it or anything reachable from it is flagged.
fn reaches(edges: &[Vec<usize>], flagged: &[bool]) -> Vec<bool> {
    let mut out = flagged.to_vec();
    let mut changed = true;
    while changed {
        changed = false;
        for v in 0..edges.len() {
            if !out[v] && edges[v].iter().any(|&w| out[w]) {
                out[v] = true;
                changed = true;
            }
        }
    }
    out
}

/// The unit id for a file: its folder, or the file itself when it sits at the source root.
fn unit_id(package: &Package, path: &str) -> String {
    let base =
        if !package.src_root.is_empty() && path.starts_with(&format!("{}/", package.src_root)) {
            &package.src_root
        } else {
            &package.dir
        };
    let rel = if base.is_empty() {
        path
    } else {
        &path[base.len() + 1..]
    };
    match rel.rsplit_once('/') {
        Some((parent, _)) => format!("{}/", discover::join(base, parent)),
        None => path.to_string(),
    }
}

/// Resolves `./x`, `../x.js` and folder imports the way TS bundler resolution does.
fn resolve_relative(from: &str, spec: &str, index: &HashMap<&str, usize>) -> Option<usize> {
    let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
    resolve_base(&normalize(&discover::join(dir, spec))?, index)
}

/// A root-relative import target, with the extensions and index files bundlers try.
fn resolve_base(base: &str, index: &HashMap<&str, usize>) -> Option<usize> {
    let base = base.to_string();
    let mut candidates = vec![base.clone()];
    for (js, ts) in [
        (".js", ".ts"),
        (".js", ".tsx"),
        (".jsx", ".tsx"),
        (".mjs", ".mts"),
        (".cjs", ".cts"),
    ] {
        if let Some(stem) = base.strip_suffix(js) {
            candidates.push(format!("{stem}{ts}"));
        }
    }
    let extensions = [
        "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "vue", "svelte", "astro",
    ];
    candidates.extend(extensions.iter().map(|ext| format!("{base}.{ext}")));
    candidates.extend(extensions.iter().map(|ext| format!("{base}/index.{ext}")));
    candidates
        .iter()
        .find_map(|c| index.get(c.as_str()).copied())
}

/// Collapses `.` and `..` segments; `None` when the path leaves the root.
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("/"))
}

/// Port waves from strongly connected components: a unit comes after everything it imports.
/// Returns each node's wave and the members of its component.
pub(crate) fn waves(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<Vec<usize>>) {
    struct Tarjan<'e> {
        edges: &'e [Vec<usize>],
        index: Vec<Option<usize>>,
        low: Vec<usize>,
        on_stack: Vec<bool>,
        stack: Vec<usize>,
        next: usize,
        components: Vec<Vec<usize>>,
    }
    fn visit(t: &mut Tarjan, v: usize) {
        t.index[v] = Some(t.next);
        t.low[v] = t.next;
        t.next += 1;
        t.stack.push(v);
        t.on_stack[v] = true;
        let edges = t.edges;
        for &w in &edges[v] {
            match t.index[w] {
                None => {
                    visit(t, w);
                    t.low[v] = t.low[v].min(t.low[w]);
                }
                Some(iw) if t.on_stack[w] => t.low[v] = t.low[v].min(iw),
                Some(_) => {}
            }
        }
        if t.index[v] == Some(t.low[v]) {
            let mut component = Vec::new();
            while let Some(w) = t.stack.pop() {
                t.on_stack[w] = false;
                component.push(w);
                if w == v {
                    break;
                }
            }
            t.components.push(component);
        }
    }
    let n = edges.len();
    let mut t = Tarjan {
        edges,
        index: vec![None; n],
        low: vec![0; n],
        on_stack: vec![false; n],
        stack: Vec::new(),
        next: 0,
        components: Vec::new(),
    };
    for v in 0..n {
        if t.index[v].is_none() {
            visit(&mut t, v);
        }
    }
    // Tarjan emits components after everything they reach, so dependencies come first.
    let mut wave = vec![0usize; n];
    let mut members = vec![Vec::new(); n];
    for component in &t.components {
        let w = component
            .iter()
            .flat_map(|&v| edges[v].iter())
            .filter(|w| !component.contains(w))
            .map(|&w| wave[w] + 1)
            .max()
            .unwrap_or(0);
        for &v in component {
            wave[v] = w;
            members[v] = component.clone();
        }
    }
    (wave, members)
}

/// Kahn's algorithm; nodes in cycles are appended in index order.
fn topological(deps_of: &[Vec<usize>]) -> Vec<usize> {
    let n = deps_of.len();
    let mut remaining: Vec<usize> = deps_of.iter().map(Vec::len).collect();
    let mut order = Vec::with_capacity(n);
    let mut done = vec![false; n];
    while let Some(next) = (0..n).find(|&i| !done[i] && remaining[i] == 0) {
        done[next] = true;
        order.push(next);
        for (i, deps) in deps_of.iter().enumerate() {
            if deps.contains(&next) {
                remaining[i] -= 1;
            }
        }
    }
    order.extend((0..n).filter(|&i| !done[i]));
    order
}

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

    fn package(dir: &str, src_root: &str) -> Package {
        Package {
            name: "pkg".into(),
            dir: dir.into(),
            src_root: src_root.into(),
            deps: Vec::new(),
            dev_deps: Vec::new(),
            namespaces: Vec::new(),
        }
    }

    #[test]
    fn a_root_below_a_skipped_name_is_still_counted() {
        // Review on #1070: only components inside `root` count. A project that lives under a folder
        // called `docs` is found by `--lang python`, so it has to be counted.
        let outer = std::env::temp_dir().join(format!("rust-anything-docs-{}", std::process::id()));
        let dir = outer.join("docs");
        let _ = std::fs::remove_dir_all(&outer);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("a.py"), "x = 1\n").unwrap();
        let others = other_language_sources(&dir, Lang::Ts);
        let _ = std::fs::remove_dir_all(&outer);
        assert_eq!(
            others,
            vec![(Lang::Python, 1)],
            "the root's own name does not count"
        );
    }

    #[test]
    fn a_virtual_environment_is_not_counted_as_python_sources() {
        // Found by reviewing #1070: Python discovery skips `venv`, so counting `venv/lib/a.py` would
        // tell a reader to pick Python, which then finds no source files at all.
        let dir = std::env::temp_dir().join(format!("rust-anything-venv-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("venv/lib")).unwrap();
        std::fs::write(dir.join("venv/lib/a.py"), "x = 1\n").unwrap();
        let others = other_language_sources(&dir, Lang::Ts);
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            others.is_empty(),
            "a virtual environment is not a source folder: {others:?}"
        );
    }

    #[test]
    fn a_directory_named_like_a_source_file_is_not_counted() {
        // The walk yields directories as well as files, so `src/example.py/` used to count as a file.
        let dir = std::env::temp_dir().join(format!("rust-anything-dirpy-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("example.py")).unwrap();
        std::fs::write(dir.join("real.py"), "def f():\n    return 1\n").unwrap();
        let others = other_language_sources(&dir, Lang::Ts);
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(
            others,
            vec![(Lang::Python, 1)],
            "the directory is not a file"
        );
    }

    #[test]
    fn a_folder_of_another_language_says_so() {
        // Found by probing, not from an issue: a Python project that carries a `package.json` for its
        // tooling was analysed as TypeScript/JavaScript and answered "No unit to port was found" with
        // no reason at all.
        let dir = std::env::temp_dir().join(format!("rust-anything-mixed-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("package.json"), r#"{"name":"m","type":"module"}"#).unwrap();
        std::fs::write(
            dir.join("src/a.ts"),
            "export const f = (n: number) => n + 1\n",
        )
        .unwrap();
        std::fs::write(dir.join("src/b.py"), "def g(n):\n    return n + 1\n").unwrap();
        let others = other_language_sources(&dir, Lang::Ts);
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(
            others,
            vec![(Lang::Python, 1)],
            "the .py file is counted, the .ts one is not"
        );
    }

    #[test]
    fn a_unit_is_its_folder_under_the_source_root() {
        // Issue #786: the id becomes the unit's name and its column in the plan, so a file one
        // folder deeper has to keep its folder.
        let pkg = package("packages/app", "packages/app/src");
        assert_eq!(
            unit_id(&pkg, "packages/app/src/text/a.ts"),
            "packages/app/src/text/"
        );
        assert_eq!(
            unit_id(&pkg, "packages/app/src/text/deep/a.ts"),
            "packages/app/src/text/deep/"
        );
        // A file at the source root is its own unit, never an empty id.
        assert_eq!(
            unit_id(&pkg, "packages/app/src/a.ts"),
            "packages/app/src/a.ts"
        );
    }

    #[test]
    fn a_unit_falls_back_to_the_package_folder() {
        // No `src/`: the package folder is the base, so the first path component is the unit.
        let pkg = package("packages/app", "packages/app");
        assert_eq!(
            unit_id(&pkg, "packages/app/text/a.ts"),
            "packages/app/text/"
        );
        // A file at the repository root has no folder and stays itself.
        let root = package("", "");
        assert_eq!(unit_id(&root, "a.ts"), "a.ts");
    }

    #[test]
    fn priority_keeps_the_size_bands_and_the_test_bonus() {
        // Issue #786: with readiness, density and tests at 0 the score is half the size value, and
        // the value is `loc / 4` below 80 lines, 20 from 80 to 599 and 10 from 600.
        let size = |loc| priority(0.0, 0.0, loc, 0, 0);
        assert_eq!(size(0), 0, "no lines, no value");
        assert_eq!(size(40), 5, "40 lines: value 10, halved");
        assert_eq!(size(60), 8, "60 lines: value 15, halved and rounded");
        // 79 and 80 differ by a rounding step, not a jump: the band is continuous there on purpose,
        // so a port that only just reaches 80 lines is not punished.
        assert_eq!(size(79), 10, "79 lines: value 19.75, halved and rounded");
        assert_eq!(size(80), 10, "the `20` band starts here");
        assert_eq!(size(599), 10);
        assert_eq!(size(600), 5, "600 lines is the `10` band, halved");
    }

    #[test]
    fn priority_scores_tests_and_compute_density() {
        // Compute density is capped at 50, so a dense unit cannot outweigh everything else.
        assert_eq!(priority(0.0, 100.0, 0, 0, 0), 25);
        assert_eq!(priority(0.0, 12.5, 0, 0, 0), 25, "12.5 * 4 = 50, the cap");
        // Direct tests are worth twice a package's tests, and half of each lands in the score.
        assert_eq!(priority(0.0, 0.0, 0, 1, 0), 15);
        assert_eq!(priority(0.0, 0.0, 0, 0, 1), 8, "15 / 2 rounds to 8");
        assert_eq!(priority(0.0, 0.0, 0, 1, 1), 15, "a direct test wins");
        // Readiness is the other half, and the result stays in 0 to 100.
        assert_eq!(priority(100.0, 0.0, 0, 0, 0), 50);
        assert_eq!(
            priority(100.0, 100.0, 79, 1, 1),
            100,
            "99.875 rounds to 100"
        );
    }

    #[test]
    fn status_labels_match_analyze() {
        assert_eq!(Status::Ready.label(), "ready");
        assert_eq!(Status::Caution.label(), "caution");
        assert_eq!(Status::Blocked.label(), "blocked");
        assert_eq!(Status::Keep.label(), "keep");
    }

    #[test]
    fn resolves_sibling_file_before_directory_index() {
        let mut index = HashMap::from([("choice.js", 0), ("choice/index.ts", 1)]);
        assert_eq!(resolve_base("choice", &index), Some(0));
        index.remove("choice.js");
        assert_eq!(resolve_base("choice", &index), Some(1));
    }

    #[test]
    fn normalizes_paths() {
        assert_eq!(normalize("a/./b/../c").as_deref(), Some("a/c"));
        assert_eq!(normalize("../x"), None);
    }

    #[test]
    fn orders_waves_and_cycles() {
        // 0 -> 1 -> 2, 3 <-> 4 -> 2
        let edges = vec![vec![1], vec![2], vec![], vec![4], vec![3, 2]];
        let (wave, members) = waves(&edges);
        assert_eq!(wave, [2, 1, 0, 1, 1]);
        assert_eq!(members[3].len(), 2);
    }

    #[test]
    fn only_the_verdict_notes_are_reasons() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
        let report = analyze_lang(&root, Lang::Ts).unwrap();
        let svelte = report
            .units
            .iter()
            .find(|u| u.id == "packages/a/src/svelte.ts")
            .unwrap();
        assert_eq!(svelte.status, Status::Blocked);
        assert!(
            svelte.notes.len() > svelte.reasons.len(),
            "{:?}",
            svelte.notes
        );
        assert_eq!(svelte.reasons, ["`svelte` has no Rust equivalent."]);
        let ready = report
            .units
            .iter()
            .find(|u| u.status == Status::Ready)
            .unwrap();
        assert!(ready.reasons.is_empty(), "{:?}", ready.reasons);
    }

    #[test]
    fn a_unit_that_imports_a_sibling_says_which_one() {
        // `fs.ts` is in wave 1 because it imports `util.ts`; the details used to say nothing, so the
        // wave order looked arbitrary.
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
        let report = analyze_lang(&root, Lang::Ts).unwrap();
        let fs = report
            .units
            .iter()
            .find(|u| u.id.ends_with("fs.ts"))
            .expect("fixture has packages/a/src/fs.ts");
        assert_eq!(fs.internal_deps, ["packages/a/src/util.ts"]);
        assert!(
            fs.notes
                .iter()
                .any(|n| n
                    == "Imports `packages/a/src/util.ts`: port it first, or port them together."),
            "{:?}",
            fs.notes
        );
        // A unit with no sibling import keeps the leaf wording.
        let leaf = report
            .units
            .iter()
            .find(|u| u.id.ends_with("parse/"))
            .expect("fixture has packages/a/src/parse/");
        assert!(
            leaf.notes
                .iter()
                .any(|n| n == "Leaf: imports no other unit."),
            "{:?}",
            leaf.notes
        );
    }

    #[test]
    fn sorts_packages_topologically() {
        assert_eq!(topological(&[vec![1], vec![], vec![0, 1]]), [1, 0, 2]);
    }

    #[test]
    fn unit_notes_use_singular_for_one_parse_error_unknown_dep_or_unresolved_import() {
        let root = std::env::temp_dir().join(format!("ra-unit-notes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("src/errs")).unwrap();
        for (path, text) in [
            ("package.json", r#"{"name":"t"}"#),
            ("src/err1.ts", "export const x = (\n"),
            ("src/errs/a.ts", "export const a = (\n"),
            ("src/errs/b.ts", "export const b = (\n"),
            (
                "src/one.ts",
                "import 'mystery-pkg-1'\nimport 'virtual:mod-1'\nexport const x = 1\n",
            ),
            (
                "src/two.ts",
                "import 'mystery-pkg-1'\nimport 'mystery-pkg-2'\nimport 'virtual:mod-1'\nimport 'virtual:mod-2'\nexport const y = 2\n",
            ),
        ] {
            std::fs::write(root.join(path), text).unwrap();
        }
        let report = analyze(&root).unwrap();
        std::fs::remove_dir_all(&root).unwrap();
        for (id, expected) in [
            (
                "src/err1.ts",
                "1 parse error: results for this unit are partial.",
            ),
            (
                "src/errs/",
                "2 parse errors: results for this unit are partial.",
            ),
            (
                "src/one.ts",
                "1 npm dependency not in the crate table: check it by hand.",
            ),
            (
                "src/one.ts",
                "1 import uses aliases or virtual modules and was not followed.",
            ),
            (
                "src/two.ts",
                "2 npm dependencies not in the crate table: check them by hand.",
            ),
            (
                "src/two.ts",
                "2 imports use aliases or virtual modules and were not followed.",
            ),
        ] {
            let notes = &report.units.iter().find(|u| u.id == id).unwrap().notes;
            assert!(notes.iter().any(|n| n == expected), "{id}: {notes:?}");
        }
    }

    #[test]
    fn a_csharp_record_parameter_counts_as_bridgeable_as_bridge_sees_it() {
        let root = crate::app::temp_dir("analyze-csharp-shapes").unwrap();
        std::fs::create_dir_all(root.join("Geo")).unwrap();
        std::fs::write(
            root.join("Geo/Geo.csproj"),
            "<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup>\n</Project>\n",
        )
        .unwrap();
        std::fs::write(
            root.join("Geo/Shapes.cs"),
            "namespace Geo;\n\npublic record Point(double X, double Y);\n\npublic static class Shapes\n{\n    public static double Norm(Point p) => System.Math.Sqrt(p.X * p.X + p.Y * p.Y);\n}\n",
        )
        .unwrap();
        let report = analyze(&root).unwrap();
        let _ = std::fs::remove_dir_all(&root);
        let geo = report
            .units
            .iter()
            .find(|u| u.files.iter().any(|f| f.ends_with("Shapes.cs")))
            .unwrap();
        assert_eq!((geo.exports, geo.bridgeable), (1, 1), "{geo:?}");
    }
}