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