Skip to main content

rust_anything/
analyze.rs

1//! Builds the migration plan: units, their dependency graph, port order and readiness.
2//!
3//! A *unit* is the smallest thing we suggest porting at once: a folder of source files,
4//! or a single file that sits directly in a package's source root.
5
6use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
7use std::path::Path;
8
9use anyhow::{Result, bail};
10use serde::Serialize;
11
12use crate::lang::Lang;
13use crate::risks::{Risk, Severity};
14use crate::ts::deps::{self, Fit};
15use crate::ts::discover::{self, FileKind, Package, Workspace};
16use crate::ts::scan::{self, FileFacts, Platform};
17
18/// Version of the JSON output. Bump on any breaking change to its shape.
19pub const SCHEMA: &str = "rust-anything/analyze@1";
20const SAMPLES_PER_RISK: usize = 3;
21/// Units smaller than this are not suggested as a first port.
22const MIN_CANDIDATE_LOC: usize = 20;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
25#[serde(rename_all = "kebab-case")]
26pub enum Status {
27    /// Good to port now.
28    Ready,
29    /// Portable, with risks to handle first.
30    Caution,
31    /// Depends on something with no Rust equivalent, or on dynamic code.
32    Blocked,
33    /// UI or editor code: stays in JS/TS.
34    Keep,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
38#[serde(rename_all = "kebab-case")]
39pub enum Bridge {
40    NapiRs,
41    WasmBindgen,
42    /// Keep in the source language (named for JS, the first language; applies to all).
43    KeepInJs,
44    Pyo3,
45    /// A C ABI: drop-in `extern "C"` functions for C.
46    CAbi,
47    /// Go through cgo over a C ABI.
48    Cgo,
49    /// Ruby through Fiddle over a C ABI.
50    Fiddle,
51    Jni,
52    /// PHP through its FFI extension over a C ABI.
53    PhpFfi,
54    DotnetFfi,
55}
56
57impl Bridge {
58    pub fn label(self) -> &'static str {
59        match self {
60            Self::NapiRs => "napi-rs",
61            Self::WasmBindgen => "wasm-bindgen",
62            Self::KeepInJs => "keep",
63            Self::Pyo3 => "PyO3",
64            Self::CAbi => "C ABI",
65            Self::Cgo => "cgo",
66            Self::Fiddle => "Fiddle (C ABI)",
67            Self::Jni => "JNI",
68            Self::PhpFfi => "PHP FFI (C ABI)",
69            Self::DotnetFfi => "P/Invoke (C ABI)",
70        }
71    }
72
73    /// The bridge a language uses for code that can move.
74    pub fn for_lang(lang: Lang) -> Self {
75        match lang {
76            Lang::Ts => Self::NapiRs,
77            Lang::Python => Self::Pyo3,
78            Lang::C => Self::CAbi,
79            Lang::Go => Self::Cgo,
80            Lang::Ruby => Self::Fiddle,
81            Lang::Java | Lang::Kotlin => Self::Jni,
82            Lang::Php => Self::PhpFfi,
83            Lang::Csharp => Self::DotnetFfi,
84        }
85    }
86}
87
88/// The Rust counterpart of a dependency, from the language's table.
89pub fn crate_for(lang: Lang, name: &str) -> Option<deps::CrateMatch> {
90    match lang {
91        Lang::Ts => deps::lookup(name),
92        Lang::Python => crate::lang::python::lookup(name),
93        _ => crate::lang::lookup(lang, name),
94    }
95}
96
97#[derive(Debug, Serialize)]
98pub struct Report {
99    pub schema: &'static str,
100    pub language: Lang,
101    pub summary: Summary,
102    pub packages: Vec<PackageReport>,
103    pub units: Vec<UnitReport>,
104    /// Unit ids suggested as the first ports, best first.
105    pub start_here: Vec<String>,
106    pub dependencies: Vec<DependencyReport>,
107    /// `analyze --whole-app`: entry points, every dependency, pieces and decisions.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub whole_app: Option<crate::whole_app::WholeApp>,
110    /// Problems with the input itself, such as every source file being excluded by ignore rules.
111    #[serde(skip_serializing_if = "Vec::is_empty")]
112    pub warnings: Vec<String>,
113}
114
115#[derive(Debug, Default, Serialize)]
116pub struct Summary {
117    pub packages: usize,
118    pub source_files: usize,
119    pub test_files: usize,
120    pub ui_files: usize,
121    pub loc: usize,
122    pub units: usize,
123    pub ready: usize,
124    pub caution: usize,
125    pub blocked: usize,
126    pub keep: usize,
127    pub parse_errors: usize,
128}
129
130#[derive(Debug, Serialize)]
131pub struct PackageReport {
132    pub name: String,
133    pub dir: String,
134    /// Position in dependency order: packages come after the workspace packages they use.
135    pub order: usize,
136    /// `node` when any of its code uses Node APIs, else `portable`.
137    pub runtime: &'static str,
138    pub workspace_deps: Vec<String>,
139    pub test_files: usize,
140    pub units: Vec<String>,
141}
142
143#[derive(Clone, Debug, Serialize)]
144pub struct UnitReport {
145    pub id: String,
146    pub package: String,
147    pub files: Vec<String>,
148    pub loc: usize,
149    /// Port order inside the repo: a unit's dependencies are in earlier waves.
150    pub wave: usize,
151    /// 0-100: how safe and easy a port looks from the code alone.
152    pub readiness: u32,
153    pub status: Status,
154    pub bridge: Bridge,
155    pub platforms: Vec<Platform>,
156    pub risks: Vec<RiskReport>,
157    pub internal_deps: Vec<String>,
158    pub workspace_deps: Vec<String>,
159    pub external_deps: Vec<String>,
160    /// Test files that import this unit directly.
161    pub direct_tests: usize,
162    /// Units that import this one.
163    pub fan_in: usize,
164    /// Loops and string-offset operations per 100 lines: a rough hint of compute-heavy code.
165    pub density: f64,
166    /// 0-100: readiness balanced with value (compute-heavy, tested, big enough to matter).
167    /// `start_here` is ordered by it.
168    pub priority: u32,
169    /// Exported functions and classes, and how many of them can cross a bridge unchanged.
170    pub exports: usize,
171    pub bridgeable: usize,
172    pub notes: Vec<String>,
173}
174
175#[derive(Clone, Debug, Serialize)]
176pub struct RiskReport {
177    pub risk: Risk,
178    pub severity: Severity,
179    pub count: usize,
180    /// `path:line` of the first occurrences.
181    pub samples: Vec<String>,
182}
183
184#[derive(Debug, Serialize)]
185pub struct DependencyReport {
186    pub name: String,
187    pub used_by: usize,
188    pub crates: Option<&'static str>,
189    /// `good`, `partial`, `none`, or `unknown` when the table has no entry.
190    pub fit: &'static str,
191    pub note: &'static str,
192}
193
194/// What an import specifier points at.
195enum Target {
196    File(usize),
197    Workspace(String),
198    External(String),
199    Platform,
200    Unresolved,
201}
202
203#[derive(Default)]
204struct UnitBuild {
205    id: String,
206    package: usize,
207    files: Vec<usize>,
208    ui: bool,
209    loc: usize,
210    loops: usize,
211    risks: BTreeMap<Risk, (usize, Vec<String>)>,
212    platforms: BTreeSet<Platform>,
213    deps: BTreeSet<usize>,
214    workspace_deps: BTreeSet<String>,
215    external_deps: BTreeSet<String>,
216    unresolved: usize,
217    parse_errors: usize,
218    direct_tests: usize,
219    fan_in: usize,
220}
221
222pub fn analyze(root: &Path) -> Result<Report> {
223    analyze_lang(root, Lang::detect(root))
224}
225
226/// Compiled or packaged files: what someone may point `analyze` at instead of source.
227const COMPILED: [&str; 17] = [
228    "apk", "aab", "ipa", "xapk", "jar", "war", "aar", "class", "dex", "exe", "dll", "so", "dylib",
229    "wasm", "pyc", "msi", "appimage",
230];
231
232fn compiled_hint() -> &'static str {
233    "rust-anything ports source code: it parses functions, records what they do, and checks the \
234     Rust port against the running original. A compiled app (an APK, a JAR, an .exe) has no \
235     source to port and no way to record it function by function. Point it at the app's source \
236     folder instead; for an app you only have as a binary, writing a new Rust app from its \
237     visible behavior is a separate project"
238}
239
240pub fn analyze_lang(root: &Path, lang: Lang) -> Result<Report> {
241    if root.is_file() {
242        let ext = root
243            .extension()
244            .map(|e| e.to_string_lossy().to_lowercase())
245            .unwrap_or_default();
246        if COMPILED.contains(&ext.as_str()) {
247            bail!(
248                "{} is a compiled .{ext} file. {}",
249                root.display(),
250                compiled_hint()
251            );
252        }
253        bail!(
254            "{} is a file; `analyze` takes the folder of a project's source code",
255            root.display()
256        );
257    }
258    let ws = match lang {
259        Lang::Ts => discover::discover(root)?,
260        _ => crate::lang::discover(lang, root)?,
261    };
262    let facts: Vec<Option<FileFacts>> = ws
263        .files
264        .iter()
265        .map(|file| {
266            let text = std::fs::read_to_string(root.join(&file.path)).ok()?;
267            if lang == Lang::C {
268                let mut facts = crate::lang::scan(lang, &file.path, &text);
269                if let Some(header) = own_header(root, &file.path) {
270                    facts
271                        .imports
272                        .extend(crate::lang::scan(lang, &header.0, &header.1).imports);
273                }
274                return Some(facts);
275            }
276            if lang != Lang::Ts {
277                return Some(crate::lang::scan(lang, &file.path, &text));
278            }
279            let code = crate::ts::script_of(&file.path, &text);
280            let is_sfc = [".vue", ".svelte", ".astro"]
281                .iter()
282                .any(|e| file.path.ends_with(e));
283            let parse_as = if is_sfc { "sfc.ts" } else { file.path.as_str() };
284            Some(scan::scan(parse_as, &code))
285        })
286        .collect();
287    let mut report = build(root, &ws, &facts, lang);
288    check_bridgeable(root, &mut report, lang);
289    Ok(report)
290}
291
292fn own_header(root: &Path, unit: &str) -> Option<(String, String)> {
293    let stem = unit.strip_suffix(".c")?;
294    let name = stem.rsplit('/').next().unwrap_or(stem);
295    [format!("{stem}.h"), format!("include/{name}.h")]
296        .into_iter()
297        .find_map(|h| Some((h.clone(), std::fs::read_to_string(root.join(&h)).ok()?)))
298}
299
300/// Counts each unit's exports that can cross a bridge, with the rules `bridge` applies. A unit
301/// whose exports are all JS-shaped (plugin objects, callbacks) cannot be ported without an API
302/// change: it is marked `caution` and left out of `start_here`.
303fn check_bridgeable(root: &Path, report: &mut Report, lang: Lang) {
304    use crate::ts::exports::{exported_classes, exported_functions};
305    if lang == Lang::C {
306        crate::lang::c::use_typedefs(root);
307    }
308    for unit in &mut report.units {
309        if matches!(unit.status, Status::Keep | Status::Blocked) {
310            continue;
311        }
312        let (mut exports, mut bridgeable) = (0, 0);
313        for file in &unit.files {
314            let Ok(text) = std::fs::read_to_string(root.join(file)) else {
315                continue;
316            };
317            let types = crate::bridge::types_in_scope(root, file, &text);
318            if lang != Lang::Ts {
319                let (functions, classes) = crate::lang::exports(lang, file, &text);
320                exports += functions.len() + classes.len();
321                bridgeable += functions
322                    .iter()
323                    .filter(|f| crate::bridge::js_only_reason(f, &[]).is_none())
324                    .count();
325                bridgeable += classes.iter().filter(|c| c.blocker.is_none()).count();
326                continue;
327            }
328            for mut f in exported_functions(file, &text) {
329                exports += 1;
330                crate::bridge::substitute_constraints(&mut f, &types);
331                bridgeable += usize::from(crate::bridge::js_only_reason(&f, &types).is_none());
332            }
333            for class in exported_classes(file, &text) {
334                exports += 1;
335                bridgeable += usize::from(class.blocker.is_none());
336            }
337        }
338        unit.exports = exports;
339        unit.bridgeable = bridgeable;
340        if exports > 0 && bridgeable == 0 {
341            unit.status = Status::Caution;
342            unit.notes.insert(
343                0,
344                if lang == Lang::C {
345                    "No export can cross the C ABI bridge (contexts, function pointers, structs by \
346                     value, pointers it cannot pair with a length): bridge a wrapper with plain \
347                     arguments, an API change."
348                } else {
349                    "Every export is JS-shaped (functions, plugin objects, iterators): porting the \
350                     logic means adding a data-only function, an API change."
351                }
352                .into(),
353            );
354        }
355    }
356    let summary = &mut report.summary;
357    (
358        summary.ready,
359        summary.caution,
360        summary.blocked,
361        summary.keep,
362    ) = (0, 0, 0, 0);
363    for u in &report.units {
364        match u.status {
365            Status::Ready => summary.ready += 1,
366            Status::Caution => summary.caution += 1,
367            Status::Blocked => summary.blocked += 1,
368            Status::Keep => summary.keep += 1,
369        }
370    }
371    report.start_here = start_here(&report.units);
372}
373
374fn build(root: &Path, ws: &Workspace, facts: &[Option<FileFacts>], lang: Lang) -> Report {
375    let file_index: HashMap<&str, usize> = ws
376        .files
377        .iter()
378        .enumerate()
379        .map(|(i, f)| (f.path.as_str(), i))
380        .collect();
381    let workspace_names: HashSet<&str> = ws.packages.iter().map(|p| p.name.as_str()).collect();
382    let alias_cache: std::cell::RefCell<HashMap<String, crate::ts::tsconfig::PathAliases>> =
383        std::cell::RefCell::new(HashMap::new());
384    let classify = |from: &str, spec: &str| -> Target {
385        if lang != Lang::Ts {
386            return match crate::lang::resolve(lang, from, spec, &file_index, ws) {
387                crate::lang::Resolution::File(i) => Target::File(i),
388                crate::lang::Resolution::External(name) => Target::External(name),
389                crate::lang::Resolution::Stdlib => Target::Platform,
390                crate::lang::Resolution::Unresolved => Target::Unresolved,
391            };
392        }
393        if spec.starts_with("./") || spec.starts_with("../") || spec == "." || spec == ".." {
394            return resolve_relative(from, spec, &file_index)
395                .map_or(Target::Unresolved, Target::File);
396        }
397        if scan::platform_of(spec).is_some() {
398            return Target::Platform;
399        }
400        // tsconfig `paths` (`~/utils`, `@/lib`), from the tsconfig nearest the importing file.
401        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
402        let aliases = alias_cache
403            .borrow_mut()
404            .entry(dir.to_string())
405            .or_insert_with(|| crate::ts::tsconfig::PathAliases::nearest(root, dir))
406            .clone();
407        let candidates = aliases.candidates(spec);
408        if !candidates.is_empty() {
409            return candidates
410                .iter()
411                .find_map(|base| resolve_base(base, &file_index))
412                .map_or(Target::Unresolved, Target::File);
413        }
414        if spec.starts_with('#')
415            || spec.starts_with('~')
416            || spec.starts_with("@/")
417            || spec.contains(':')
418        {
419            return Target::Unresolved;
420        }
421        let name = deps::package_name(spec);
422        if workspace_names.contains(name) {
423            Target::Workspace(name.to_string())
424        } else {
425            Target::External(name.to_string())
426        }
427    };
428
429    // Group source and UI files into units.
430    let mut units: Vec<UnitBuild> = Vec::new();
431    let mut unit_ids: HashMap<String, usize> = HashMap::new();
432    let mut unit_of: Vec<Option<usize>> = vec![None; ws.files.len()];
433    for (i, file) in ws.files.iter().enumerate() {
434        if file.kind == FileKind::Test {
435            continue;
436        }
437        let id = unit_id(&ws.packages[file.package], &file.path);
438        let u = *unit_ids.entry(id.clone()).or_insert_with(|| {
439            units.push(UnitBuild {
440                id,
441                package: file.package,
442                ..UnitBuild::default()
443            });
444            units.len() - 1
445        });
446        units[u].files.push(i);
447        units[u].ui |= file.kind == FileKind::Ui;
448        unit_of[i] = Some(u);
449    }
450
451    // Aggregate facts and imports per unit; credit tests to what they import.
452    let mut package_tests = vec![0usize; ws.packages.len()];
453    let mut summary = Summary {
454        packages: ws.packages.len(),
455        ..Summary::default()
456    };
457    for (i, file) in ws.files.iter().enumerate() {
458        match file.kind {
459            FileKind::Source => summary.source_files += 1,
460            FileKind::Test => summary.test_files += 1,
461            FileKind::Ui => summary.ui_files += 1,
462        }
463        let Some(f) = &facts[i] else { continue };
464        summary.parse_errors += usize::from(f.parse_errors > 0);
465        if file.kind == FileKind::Test {
466            package_tests[file.package] += 1;
467            let mut hit_units = BTreeSet::new();
468            let mut hit_packages = BTreeSet::new();
469            for import in &f.imports {
470                match classify(&file.path, &import.specifier) {
471                    Target::File(j) => hit_units.extend(unit_of[j]),
472                    Target::Workspace(name) => {
473                        hit_packages.extend(ws.packages.iter().position(|p| p.name == name));
474                    }
475                    _ => {}
476                }
477            }
478            for u in hit_units {
479                units[u].direct_tests += 1;
480            }
481            for p in hit_packages.into_iter().filter(|&p| p != file.package) {
482                package_tests[p] += 1;
483            }
484            continue;
485        }
486        let Some(u) = unit_of[i] else { continue };
487        summary.loc += f.loc;
488        let unit = &mut units[u];
489        unit.loc += f.loc;
490        unit.loops += f.loops;
491        unit.parse_errors += f.parse_errors;
492        unit.platforms.extend(f.platforms.iter().copied());
493        if lang == Lang::C && crate::lang::c::in_arch_dir(&file.path) {
494            let entry = unit.risks.entry(Risk::PlatformSpecific).or_default();
495            entry.0 += 1;
496            if entry.1.len() < SAMPLES_PER_RISK {
497                entry.1.push(format!("{}:1", file.path));
498            }
499        }
500        for (risk, lines) in &f.risks {
501            let entry = unit.risks.entry(*risk).or_default();
502            entry.0 += lines.len();
503            for line in lines {
504                if entry.1.len() < SAMPLES_PER_RISK {
505                    entry.1.push(format!("{}:{line}", file.path));
506                }
507            }
508        }
509        for import in &f.imports {
510            match classify(&file.path, &import.specifier) {
511                Target::File(j) => {
512                    if let Some(v) = unit_of[j].filter(|&v| v != u) {
513                        units[u].deps.insert(v);
514                    }
515                }
516                Target::Workspace(name) => {
517                    if name != ws.packages[units[u].package].name {
518                        units[u].workspace_deps.insert(name);
519                    }
520                }
521                Target::External(name) if !import.type_only => {
522                    units[u].external_deps.insert(name);
523                }
524                Target::Unresolved if !import.type_only => units[u].unresolved += 1,
525                Target::Unresolved => {}
526                Target::External(_) | Target::Platform => {}
527            }
528        }
529    }
530    for u in 0..units.len() {
531        for v in units[u].deps.clone() {
532            units[v].fan_in += 1;
533        }
534    }
535
536    let edges: Vec<Vec<usize>> = units
537        .iter()
538        .map(|u| u.deps.iter().copied().collect())
539        .collect();
540    let (waves, cycles) = waves(&edges);
541    // A unit needs Node when it, or anything it imports, uses Node APIs.
542    let node_reach = reaches(
543        &edges,
544        &units
545            .iter()
546            .map(|u| u.platforms.contains(&Platform::Node))
547            .collect::<Vec<_>>(),
548    );
549    // A package is Node-only when its source root needs Node; build scripts beside it do not count.
550    let node_packages: BTreeSet<usize> = units
551        .iter()
552        .enumerate()
553        .filter(|(u, unit)| {
554            let src = &ws.packages[unit.package].src_root;
555            node_reach[*u] && (src.is_empty() || unit.id.starts_with(&format!("{src}/")))
556        })
557        .map(|(_, unit)| unit.package)
558        .collect();
559    let ctx = Ctx {
560        lang,
561        ws,
562        units: &units,
563        package_tests: &package_tests,
564        node_packages: &node_packages,
565        node_reach: &node_reach,
566        waves: &waves,
567        cycles: &cycles,
568    };
569    let mut reports: Vec<UnitReport> = (0..units.len()).map(|u| score(u, &ctx)).collect();
570    reports.sort_by(|a, b| a.id.cmp(&b.id));
571    for r in &reports {
572        match r.status {
573            Status::Ready => summary.ready += 1,
574            Status::Caution => summary.caution += 1,
575            Status::Blocked => summary.blocked += 1,
576            Status::Keep => summary.keep += 1,
577        }
578    }
579    summary.units = reports.len();
580
581    let start_here = start_here(&reports);
582    let packages = package_reports(ws, &reports, &package_tests, &node_packages);
583    let dependencies = dependency_reports(&reports, lang);
584    let mut warnings = Vec::new();
585    if ws.files.is_empty() {
586        let hidden = crate::walk::ignored_files(root, lang.extensions());
587        let compiled = crate::walk::builder(root)
588            .standard_filters(false)
589            .max_depth(Some(4))
590            .build()
591            .flatten()
592            .filter(|e| {
593                e.path().extension().is_some_and(|x| {
594                    COMPILED.contains(&x.to_string_lossy().to_lowercase().as_str())
595                })
596            })
597            .count();
598        if hidden == 0 && compiled > 0 {
599            warnings.push(format!(
600                "no source files were found, only {compiled} compiled or packaged files. {}",
601                compiled_hint()
602            ));
603        }
604        if hidden > 0 {
605            warnings.push(format!(
606                "no source files were analyzed, but {hidden} {} files under {} are excluded by \
607                 ignore rules (.gitignore or .ignore files in this repository); the plan is empty \
608                 because of them, not because there is nothing to port",
609                lang.name(),
610                root.display()
611            ));
612        }
613    }
614    Report {
615        schema: SCHEMA,
616        language: lang,
617        summary,
618        packages,
619        units: reports,
620        start_here,
621        dependencies,
622        whole_app: None,
623        warnings,
624    }
625}
626
627struct Ctx<'a> {
628    lang: Lang,
629    ws: &'a Workspace,
630    units: &'a [UnitBuild],
631    package_tests: &'a [usize],
632    node_packages: &'a BTreeSet<usize>,
633    node_reach: &'a [bool],
634    waves: &'a [usize],
635    cycles: &'a [Vec<usize>],
636}
637
638fn score(u: usize, ctx: &Ctx) -> UnitReport {
639    let unit = &ctx.units[u];
640    let all = ctx.units;
641    let ws = ctx.ws;
642    let packages = &ws.packages;
643    let package_tests = ctx.package_tests[unit.package];
644    let wave = ctx.waves[u];
645    let cycle = &ctx.cycles[u];
646    let mut notes = Vec::new();
647    let keep = unit.ui
648        || unit.platforms.contains(&Platform::Ui)
649        || unit.platforms.contains(&Platform::Editor);
650    let blocking_deps: Vec<&String> = unit
651        .external_deps
652        .iter()
653        .filter(|d| crate_for(ctx.lang, d).is_some_and(|m| m.fit == Fit::None))
654        .collect();
655    let unknown_deps = unit
656        .external_deps
657        .iter()
658        .filter(|d| crate_for(ctx.lang, d).is_none())
659        .count();
660
661    let risk_points: f64 = unit
662        .risks
663        .iter()
664        .map(|(risk, (count, _))| risk.severity().weight() * (1.0 + *count as f64).ln())
665        .sum();
666    let size_penalty = unit.loc as f64 / 40.0;
667    let fan_in_penalty = (unit.fan_in as f64 * 1.5).min(15.0);
668    let dep_penalty = blocking_deps.len() as f64 * 12.0 + unknown_deps as f64 * 4.0;
669    let test_bonus = if unit.direct_tests > 0 {
670        10.0
671    } else if package_tests > 0 {
672        4.0
673    } else {
674        0.0
675    };
676    let readiness = (100.0 - risk_points - size_penalty - fan_in_penalty - dep_penalty
677        + test_bonus)
678        .clamp(0.0, 100.0);
679
680    let platform = unit.risks.contains_key(&Risk::PlatformSpecific);
681    let status = if platform {
682        notes.push(
683            "Depends on the target (hardware registers, memory layout, inline assembly): keep in \
684             C, since a recording on this machine cannot vouch for the target."
685                .to_string(),
686        );
687        Status::Keep
688    } else if keep {
689        notes.push(if unit.platforms.contains(&Platform::Editor) {
690            "Runs in the editor's extension host: keep in TS.".to_string()
691        } else {
692            "UI code: keep in the original language.".to_string()
693        });
694        Status::Keep
695    } else if !blocking_deps.is_empty() || unit.risks.contains_key(&Risk::DynamicCode) {
696        for dep in &blocking_deps {
697            notes.push(format!("`{dep}` has no Rust equivalent."));
698        }
699        if unit.risks.contains_key(&Risk::DynamicCode) {
700            notes.push("Uses dynamic code (eval, new Function or computed imports).".into());
701        }
702        Status::Blocked
703    } else if readiness < 50.0 || unit.parse_errors > 0 {
704        Status::Caution
705    } else {
706        Status::Ready
707    };
708    if unit.parse_errors > 0 {
709        notes.push(format!(
710            "{} parse errors: results for this unit are partial.",
711            unit.parse_errors
712        ));
713    }
714    if unknown_deps > 0 {
715        notes.push(format!(
716            "{unknown_deps} {} dependencies not in the crate table: check them by hand.",
717            ctx.lang.registry()
718        ));
719    }
720    if unit.unresolved > 0 {
721        notes.push(format!(
722            "{} imports use aliases or virtual modules and were not followed.",
723            unit.unresolved
724        ));
725    }
726    if cycle.len() > 1 {
727        let others: Vec<&str> = cycle
728            .iter()
729            .map(|&v| all[v].id.as_str())
730            .filter(|id| *id != unit.id)
731            .collect();
732        notes.push(format!(
733            "Import cycle with {}: port them together.",
734            others.join(", ")
735        ));
736    }
737    if unit.deps.is_empty() && !keep {
738        if unit.workspace_deps.is_empty() {
739            notes.push("Leaf: imports no other unit.".into());
740        } else {
741            let names: Vec<String> = unit
742                .workspace_deps
743                .iter()
744                .map(|d| format!("`{d}`"))
745                .collect();
746            notes.push(format!(
747                "Imports {} from another workspace package: port {} first.",
748                names.join(", "),
749                if names.len() == 1 {
750                    "that package"
751                } else {
752                    "those packages"
753                }
754            ));
755        }
756    }
757    if unit.direct_tests > 0 {
758        notes.push(if unit.direct_tests == 1 {
759            "1 test file imports it directly.".to_string()
760        } else {
761            format!("{} test files import it directly.", unit.direct_tests)
762        });
763    } else if package_tests == 0 && !keep {
764        notes.push(
765            "No tests found: write characterization tests against the original code first.".into(),
766        );
767    }
768
769    let string_ops = unit.risks.get(&Risk::StringOffsets).map_or(0, |r| r.0);
770    let density = if unit.loc == 0 {
771        0.0
772    } else {
773        ((unit.loops + string_ops) as f64 * 100.0 / unit.loc as f64 * 10.0).round() / 10.0
774    };
775    let bridge = if keep {
776        Bridge::KeepInJs
777    } else if ctx.lang != Lang::Ts {
778        Bridge::for_lang(ctx.lang)
779    } else if ctx.node_reach[u] || ctx.node_packages.contains(&unit.package) {
780        Bridge::NapiRs
781    } else {
782        Bridge::WasmBindgen
783    };
784    if bridge == Bridge::WasmBindgen {
785        notes.push(
786            "Portable code: wasm-bindgen keeps it running in browsers and Node. It needs the \
787             wasm32-unknown-unknown target and wasm-bindgen; `bridge --kind napi` runs with what \
788             Node already has."
789                .into(),
790        );
791    }
792
793    let mut files: Vec<String> = unit
794        .files
795        .iter()
796        .map(|&i| ws.files[i].path.clone())
797        .collect();
798    files.sort();
799    let mut risks: Vec<RiskReport> = unit
800        .risks
801        .iter()
802        .map(|(risk, (count, samples))| RiskReport {
803            risk: *risk,
804            severity: risk.severity(),
805            count: *count,
806            samples: samples.clone(),
807        })
808        .collect();
809    risks.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.count.cmp(&a.count)));
810
811    UnitReport {
812        id: unit.id.clone(),
813        package: packages[unit.package].name.clone(),
814        files,
815        loc: unit.loc,
816        wave,
817        readiness: readiness.round() as u32,
818        status,
819        bridge,
820        platforms: unit.platforms.iter().copied().collect(),
821        risks,
822        internal_deps: unit.deps.iter().map(|&v| all[v].id.clone()).collect(),
823        workspace_deps: unit.workspace_deps.iter().cloned().collect(),
824        external_deps: unit.external_deps.iter().cloned().collect(),
825        direct_tests: unit.direct_tests,
826        fan_in: unit.fan_in,
827        density,
828        priority: priority(
829            readiness,
830            density,
831            unit.loc,
832            unit.direct_tests,
833            package_tests,
834        ),
835        exports: 0,
836        bridgeable: 0,
837        notes,
838    }
839}
840
841fn start_here(units: &[UnitReport]) -> Vec<String> {
842    let pick = |statuses: &[Status], min_loc: usize| -> Vec<&UnitReport> {
843        let mut list: Vec<&UnitReport> = units
844            .iter()
845            .filter(|u| statuses.contains(&u.status) && u.loc >= min_loc && u.bridgeable > 0)
846            .collect();
847        list.sort_by(|a, b| {
848            b.priority
849                .cmp(&a.priority)
850                .then(b.readiness.cmp(&a.readiness))
851                .then(a.wave.cmp(&b.wave))
852                .then(b.density.total_cmp(&a.density))
853                .then(a.id.cmp(&b.id))
854        });
855        list
856    };
857    let mut list = pick(&[Status::Ready], MIN_CANDIDATE_LOC);
858    if list.len() < 3 {
859        list = pick(&[Status::Ready, Status::Caution], MIN_CANDIDATE_LOC);
860    }
861    if list.is_empty() {
862        // Small repos: every unit is under the size floor.
863        list = pick(&[Status::Ready, Status::Caution], 1);
864    }
865    list.into_iter().take(10).map(|u| u.id.clone()).collect()
866}
867
868fn package_reports(
869    ws: &Workspace,
870    units: &[UnitReport],
871    package_tests: &[usize],
872    node_packages: &BTreeSet<usize>,
873) -> Vec<PackageReport> {
874    let names: HashMap<&str, usize> = ws
875        .packages
876        .iter()
877        .enumerate()
878        .map(|(i, p)| (p.name.as_str(), i))
879        .collect();
880    let deps_of: Vec<Vec<usize>> = ws
881        .packages
882        .iter()
883        .enumerate()
884        .map(|(i, p)| {
885            let mut d: Vec<usize> = p
886                .deps
887                .iter()
888                .chain(&p.dev_deps)
889                .filter_map(|n| names.get(n.as_str()).copied())
890                .filter(|&j| j != i)
891                .collect();
892            d.sort_unstable();
893            d.dedup();
894            d
895        })
896        .collect();
897    let order = topological(&deps_of);
898    let mut reports: Vec<PackageReport> = order
899        .iter()
900        .map(|&i| {
901            let p = &ws.packages[i];
902            PackageReport {
903                name: p.name.clone(),
904                dir: p.dir.clone(),
905                order: 0,
906                runtime: if node_packages.contains(&i) {
907                    "node"
908                } else {
909                    "portable"
910                },
911                workspace_deps: deps_of[i]
912                    .iter()
913                    .map(|&j| ws.packages[j].name.clone())
914                    .collect(),
915                test_files: package_tests[i],
916                units: units
917                    .iter()
918                    .filter(|u| u.package == p.name)
919                    .map(|u| u.id.clone())
920                    .collect(),
921            }
922        })
923        .filter(|p| !p.units.is_empty())
924        .collect();
925    for (position, report) in reports.iter_mut().enumerate() {
926        report.order = position + 1;
927    }
928    reports
929}
930
931fn dependency_reports(units: &[UnitReport], lang: Lang) -> Vec<DependencyReport> {
932    let mut used: BTreeMap<&str, usize> = BTreeMap::new();
933    for unit in units.iter().filter(|u| u.status != Status::Keep) {
934        for dep in &unit.external_deps {
935            *used.entry(dep).or_default() += 1;
936        }
937    }
938    let mut out: Vec<DependencyReport> = used
939        .into_iter()
940        .map(|(name, used_by)| {
941            let found = crate_for(lang, name);
942            DependencyReport {
943                name: name.to_string(),
944                used_by,
945                crates: found.map(|m| m.crates),
946                fit: match found.map(|m| m.fit) {
947                    Some(Fit::Good) => "good",
948                    Some(Fit::Partial) => "partial",
949                    Some(Fit::None) => "none",
950                    None => "unknown",
951                },
952                note: found.map_or("", |m| m.note),
953            }
954        })
955        .collect();
956    let rank = |fit: &str| match fit {
957        "none" => 0,
958        "unknown" => 1,
959        "partial" => 2,
960        _ => 3,
961    };
962    out.sort_by(|a, b| {
963        rank(a.fit)
964            .cmp(&rank(b.fit))
965            .then(b.used_by.cmp(&a.used_by))
966    });
967    out
968}
969
970/// Readiness balanced with how much a port would gain.
971fn priority(
972    readiness: f64,
973    density: f64,
974    loc: usize,
975    direct_tests: usize,
976    package_tests: usize,
977) -> u32 {
978    let compute = (density * 4.0).min(50.0);
979    let tests = if direct_tests > 0 {
980        30.0
981    } else if package_tests > 0 {
982        15.0
983    } else {
984        0.0
985    };
986    // Below ~80 lines a port rarely pays for its bridge; past ~600 it is too big for a first step.
987    let size = match loc {
988        0..80 => loc as f64 / 4.0,
989        80..600 => 20.0,
990        _ => 10.0,
991    };
992    let value = compute + tests + size;
993    (readiness * 0.5 + value * 0.5).round().clamp(0.0, 100.0) as u32
994}
995
996/// For each node, whether it or anything reachable from it is flagged.
997fn reaches(edges: &[Vec<usize>], flagged: &[bool]) -> Vec<bool> {
998    let mut out = flagged.to_vec();
999    let mut changed = true;
1000    while changed {
1001        changed = false;
1002        for v in 0..edges.len() {
1003            if !out[v] && edges[v].iter().any(|&w| out[w]) {
1004                out[v] = true;
1005                changed = true;
1006            }
1007        }
1008    }
1009    out
1010}
1011
1012/// The unit id for a file: its folder, or the file itself when it sits at the source root.
1013fn unit_id(package: &Package, path: &str) -> String {
1014    let base =
1015        if !package.src_root.is_empty() && path.starts_with(&format!("{}/", package.src_root)) {
1016            &package.src_root
1017        } else {
1018            &package.dir
1019        };
1020    let rel = if base.is_empty() {
1021        path
1022    } else {
1023        &path[base.len() + 1..]
1024    };
1025    match rel.rsplit_once('/') {
1026        Some((parent, _)) => format!("{}/", discover::join(base, parent)),
1027        None => path.to_string(),
1028    }
1029}
1030
1031/// Resolves `./x`, `../x.js` and folder imports the way TS bundler resolution does.
1032fn resolve_relative(from: &str, spec: &str, index: &HashMap<&str, usize>) -> Option<usize> {
1033    let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
1034    resolve_base(&normalize(&discover::join(dir, spec))?, index)
1035}
1036
1037/// A root-relative import target, with the extensions and index files bundlers try.
1038fn resolve_base(base: &str, index: &HashMap<&str, usize>) -> Option<usize> {
1039    let base = base.to_string();
1040    let mut candidates = vec![base.clone()];
1041    for (js, ts) in [
1042        (".js", ".ts"),
1043        (".js", ".tsx"),
1044        (".jsx", ".tsx"),
1045        (".mjs", ".mts"),
1046        (".cjs", ".cts"),
1047    ] {
1048        if let Some(stem) = base.strip_suffix(js) {
1049            candidates.push(format!("{stem}{ts}"));
1050        }
1051    }
1052    for ext in [
1053        "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "vue", "svelte", "astro",
1054    ] {
1055        candidates.push(format!("{base}.{ext}"));
1056        candidates.push(format!("{base}/index.{ext}"));
1057    }
1058    candidates
1059        .iter()
1060        .find_map(|c| index.get(c.as_str()).copied())
1061}
1062
1063/// Collapses `.` and `..` segments; `None` when the path leaves the root.
1064fn normalize(path: &str) -> Option<String> {
1065    let mut parts: Vec<&str> = Vec::new();
1066    for part in path.split('/') {
1067        match part {
1068            "" | "." => {}
1069            ".." => {
1070                parts.pop()?;
1071            }
1072            _ => parts.push(part),
1073        }
1074    }
1075    Some(parts.join("/"))
1076}
1077
1078/// Port waves from strongly connected components: a unit comes after everything it imports.
1079/// Returns each node's wave and the members of its component.
1080pub(crate) fn waves(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<Vec<usize>>) {
1081    struct Tarjan<'e> {
1082        edges: &'e [Vec<usize>],
1083        index: Vec<Option<usize>>,
1084        low: Vec<usize>,
1085        on_stack: Vec<bool>,
1086        stack: Vec<usize>,
1087        next: usize,
1088        components: Vec<Vec<usize>>,
1089    }
1090    fn visit(t: &mut Tarjan, v: usize) {
1091        t.index[v] = Some(t.next);
1092        t.low[v] = t.next;
1093        t.next += 1;
1094        t.stack.push(v);
1095        t.on_stack[v] = true;
1096        let edges = t.edges;
1097        for &w in &edges[v] {
1098            match t.index[w] {
1099                None => {
1100                    visit(t, w);
1101                    t.low[v] = t.low[v].min(t.low[w]);
1102                }
1103                Some(iw) if t.on_stack[w] => t.low[v] = t.low[v].min(iw),
1104                Some(_) => {}
1105            }
1106        }
1107        if t.index[v] == Some(t.low[v]) {
1108            let mut component = Vec::new();
1109            while let Some(w) = t.stack.pop() {
1110                t.on_stack[w] = false;
1111                component.push(w);
1112                if w == v {
1113                    break;
1114                }
1115            }
1116            t.components.push(component);
1117        }
1118    }
1119    let n = edges.len();
1120    let mut t = Tarjan {
1121        edges,
1122        index: vec![None; n],
1123        low: vec![0; n],
1124        on_stack: vec![false; n],
1125        stack: Vec::new(),
1126        next: 0,
1127        components: Vec::new(),
1128    };
1129    for v in 0..n {
1130        if t.index[v].is_none() {
1131            visit(&mut t, v);
1132        }
1133    }
1134    // Tarjan emits components after everything they reach, so dependencies come first.
1135    let mut wave = vec![0usize; n];
1136    let mut members = vec![Vec::new(); n];
1137    for component in &t.components {
1138        let w = component
1139            .iter()
1140            .flat_map(|&v| edges[v].iter())
1141            .filter(|w| !component.contains(w))
1142            .map(|&w| wave[w] + 1)
1143            .max()
1144            .unwrap_or(0);
1145        for &v in component {
1146            wave[v] = w;
1147            members[v] = component.clone();
1148        }
1149    }
1150    (wave, members)
1151}
1152
1153/// Kahn's algorithm; nodes in cycles are appended in index order.
1154fn topological(deps_of: &[Vec<usize>]) -> Vec<usize> {
1155    let n = deps_of.len();
1156    let mut remaining: Vec<usize> = deps_of.iter().map(Vec::len).collect();
1157    let mut order = Vec::with_capacity(n);
1158    let mut done = vec![false; n];
1159    while let Some(next) = (0..n).find(|&i| !done[i] && remaining[i] == 0) {
1160        done[next] = true;
1161        order.push(next);
1162        for (i, deps) in deps_of.iter().enumerate() {
1163            if deps.contains(&next) {
1164                remaining[i] -= 1;
1165            }
1166        }
1167    }
1168    order.extend((0..n).filter(|&i| !done[i]));
1169    order
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    use super::*;
1175
1176    #[test]
1177    fn normalizes_paths() {
1178        assert_eq!(normalize("a/./b/../c").as_deref(), Some("a/c"));
1179        assert_eq!(normalize("../x"), None);
1180    }
1181
1182    #[test]
1183    fn orders_waves_and_cycles() {
1184        // 0 -> 1 -> 2, 3 <-> 4 -> 2
1185        let edges = vec![vec![1], vec![2], vec![], vec![4], vec![3, 2]];
1186        let (wave, members) = waves(&edges);
1187        assert_eq!(wave, [2, 1, 0, 1, 1]);
1188        assert_eq!(members[3].len(), 2);
1189    }
1190
1191    #[test]
1192    fn sorts_packages_topologically() {
1193        assert_eq!(topological(&[vec![1], vec![], vec![0, 1]]), [1, 0, 2]);
1194    }
1195}