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