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