Skip to main content

rust_anything/
analyze.rs

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