Skip to main content

rust_anything/
analyze.rs

1//! Builds the migration plan: units, their dependency graph, port order and readiness.
2//!
3//! A *unit* is the smallest thing we suggest porting at once: a folder of source files,
4//! or a single file that sits directly in a package's source root.
5
6use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
7use std::path::Path;
8
9use anyhow::{Result, bail};
10use serde::Serialize;
11
12use crate::lang::Lang;
13use crate::risks::{Risk, Severity};
14use crate::ts::deps::{self, Fit};
15use crate::ts::discover::{self, FileKind, Package, Workspace};
16use crate::ts::scan::{self, FileFacts, Platform};
17
18/// Version of the JSON output. Bump on any breaking change to its shape.
19pub const SCHEMA: &str = "rust-anything/analyze@1";
20const SAMPLES_PER_RISK: usize = 3;
21/// Units smaller than this are not suggested as a first port.
22const MIN_CANDIDATE_LOC: usize = 20;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
25#[serde(rename_all = "kebab-case")]
26pub enum Status {
27    /// Good to port now.
28    Ready,
29    /// Portable, with risks to handle first.
30    Caution,
31    /// Depends on something with no Rust equivalent, or on dynamic code.
32    Blocked,
33    /// UI or editor code: stays in JS/TS.
34    Keep,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
38#[serde(rename_all = "kebab-case")]
39pub enum Bridge {
40    NapiRs,
41    WasmBindgen,
42    /// Keep in the source language (named for JS, the first language; applies to all).
43    KeepInJs,
44    Pyo3,
45    /// A C ABI: drop-in `extern "C"` functions for C.
46    CAbi,
47    /// Go through cgo over a C ABI.
48    Cgo,
49    /// Ruby through Fiddle over a C ABI.
50    Fiddle,
51    Jni,
52    /// PHP through its FFI extension over a C ABI.
53    PhpFfi,
54    DotnetFfi,
55}
56
57impl Bridge {
58    pub fn label(self) -> &'static str {
59        match self {
60            Self::NapiRs => "napi-rs",
61            Self::WasmBindgen => "wasm-bindgen",
62            Self::KeepInJs => "keep",
63            Self::Pyo3 => "PyO3",
64            Self::CAbi => "C ABI",
65            Self::Cgo => "cgo",
66            Self::Fiddle => "Fiddle (C ABI)",
67            Self::Jni => "JNI",
68            Self::PhpFfi => "PHP FFI (C ABI)",
69            Self::DotnetFfi => "P/Invoke (C ABI)",
70        }
71    }
72
73    /// The bridge a language uses for code that can move.
74    pub fn for_lang(lang: Lang) -> Self {
75        match lang {
76            Lang::Ts => Self::NapiRs,
77            Lang::Python => Self::Pyo3,
78            Lang::C => Self::CAbi,
79            Lang::Go => Self::Cgo,
80            Lang::Ruby => Self::Fiddle,
81            Lang::Java | Lang::Kotlin => Self::Jni,
82            Lang::Php => Self::PhpFfi,
83            Lang::Csharp => Self::DotnetFfi,
84        }
85    }
86}
87
88/// The Rust counterpart of a dependency, from the language's table.
89pub fn crate_for(lang: Lang, name: &str) -> Option<deps::CrateMatch> {
90    match lang {
91        Lang::Ts => deps::lookup(name),
92        Lang::Python => crate::lang::python::lookup(name),
93        _ => crate::lang::lookup(lang, name),
94    }
95}
96
97#[derive(Debug, Serialize)]
98pub struct Report {
99    pub schema: &'static str,
100    pub language: Lang,
101    pub summary: Summary,
102    pub packages: Vec<PackageReport>,
103    pub units: Vec<UnitReport>,
104    /// Unit ids suggested as the first ports, best first.
105    pub start_here: Vec<String>,
106    pub dependencies: Vec<DependencyReport>,
107    /// `analyze --whole-app`: entry points, every dependency, pieces and decisions.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub whole_app: Option<crate::whole_app::WholeApp>,
110    /// Problems with the input itself, such as every source file being excluded by ignore rules.
111    #[serde(skip_serializing_if = "Vec::is_empty")]
112    pub warnings: Vec<String>,
113}
114
115#[derive(Debug, Default, Serialize)]
116pub struct Summary {
117    pub packages: usize,
118    pub source_files: usize,
119    pub test_files: usize,
120    pub ui_files: usize,
121    pub loc: usize,
122    pub units: usize,
123    pub ready: usize,
124    pub caution: usize,
125    pub blocked: usize,
126    pub keep: usize,
127    pub parse_errors: usize,
128}
129
130#[derive(Debug, Serialize)]
131pub struct PackageReport {
132    pub name: String,
133    pub dir: String,
134    /// Position in dependency order: packages come after the workspace packages they use.
135    pub order: usize,
136    /// `node` when any of its code uses Node APIs, else `portable`.
137    pub runtime: &'static str,
138    pub workspace_deps: Vec<String>,
139    pub test_files: usize,
140    pub units: Vec<String>,
141}
142
143#[derive(Clone, Debug, Serialize)]
144pub struct UnitReport {
145    pub id: String,
146    pub package: String,
147    pub files: Vec<String>,
148    pub loc: usize,
149    /// Port order inside the repo: a unit's dependencies are in earlier waves.
150    pub wave: usize,
151    /// 0-100: how safe and easy a port looks from the code alone.
152    pub readiness: u32,
153    pub status: Status,
154    pub bridge: Bridge,
155    pub platforms: Vec<Platform>,
156    pub risks: Vec<RiskReport>,
157    pub internal_deps: Vec<String>,
158    pub workspace_deps: Vec<String>,
159    pub external_deps: Vec<String>,
160    /// Test files that import this unit directly.
161    pub direct_tests: usize,
162    /// Units that import this one.
163    pub fan_in: usize,
164    /// Loops and string-offset operations per 100 lines: a rough hint of compute-heavy code.
165    pub density: f64,
166    /// 0-100: readiness balanced with value (compute-heavy, tested, big enough to matter).
167    /// `start_here` is ordered by it.
168    pub priority: u32,
169    /// Exported functions and classes, and how many of them can cross a bridge unchanged.
170    pub exports: usize,
171    pub bridgeable: usize,
172    pub notes: Vec<String>,
173}
174
175#[derive(Clone, Debug, Serialize)]
176pub struct RiskReport {
177    pub risk: Risk,
178    pub severity: Severity,
179    pub count: usize,
180    /// `path:line` of the first occurrences.
181    pub samples: Vec<String>,
182}
183
184#[derive(Debug, Serialize)]
185pub struct DependencyReport {
186    pub name: String,
187    pub used_by: usize,
188    pub crates: Option<&'static str>,
189    /// `good`, `partial`, `none`, or `unknown` when the table has no entry.
190    pub fit: &'static str,
191    pub note: &'static str,
192}
193
194/// What an import specifier points at.
195enum Target {
196    File(usize),
197    Workspace(String),
198    External(String),
199    Platform,
200    Unresolved,
201}
202
203#[derive(Default)]
204struct UnitBuild {
205    id: String,
206    package: usize,
207    files: Vec<usize>,
208    ui: bool,
209    loc: usize,
210    loops: usize,
211    risks: BTreeMap<Risk, (usize, Vec<String>)>,
212    platforms: BTreeSet<Platform>,
213    deps: BTreeSet<usize>,
214    workspace_deps: BTreeSet<String>,
215    external_deps: BTreeSet<String>,
216    unresolved: usize,
217    parse_errors: usize,
218    direct_tests: usize,
219    fan_in: usize,
220}
221
222pub fn analyze(root: &Path) -> Result<Report> {
223    analyze_lang(root, Lang::detect(root))
224}
225
226/// Compiled or packaged files: what someone may point `analyze` at instead of source.
227const COMPILED: [&str; 17] = [
228    "apk", "aab", "ipa", "xapk", "jar", "war", "aar", "class", "dex", "exe", "dll", "so", "dylib",
229    "wasm", "pyc", "msi", "appimage",
230];
231
232fn compiled_hint() -> &'static str {
233    "rust-anything ports source code: it parses functions, records what they do, and checks the \
234     Rust port against the running original. A compiled app (an APK, a JAR, an .exe) has no \
235     source to port and no way to record it function by function. Point it at the app's source \
236     folder instead; for an app you only have as a binary, writing a new Rust app from its \
237     visible behavior is a separate project"
238}
239
240pub fn analyze_lang(root: &Path, lang: Lang) -> Result<Report> {
241    if root.is_file() {
242        let ext = root
243            .extension()
244            .map(|e| e.to_string_lossy().to_lowercase())
245            .unwrap_or_default();
246        if COMPILED.contains(&ext.as_str()) {
247            bail!(
248                "{} is a compiled .{ext} file. {}",
249                root.display(),
250                compiled_hint()
251            );
252        }
253        bail!(
254            "{} is a file; `analyze` takes the folder of a project's source code",
255            root.display()
256        );
257    }
258    let ws = match lang {
259        Lang::Ts => discover::discover(root)?,
260        _ => crate::lang::discover(lang, root)?,
261    };
262    let facts: Vec<Option<FileFacts>> = ws
263        .files
264        .iter()
265        .map(|file| {
266            let text = std::fs::read_to_string(root.join(&file.path)).ok()?;
267            if lang != Lang::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} {} dependencies not in the crate table: check them by hand.",
684            ctx.lang.registry()
685        ));
686    }
687    if unit.unresolved > 0 {
688        notes.push(format!(
689            "{} imports use aliases or virtual modules and were not followed.",
690            unit.unresolved
691        ));
692    }
693    if cycle.len() > 1 {
694        let others: Vec<&str> = cycle
695            .iter()
696            .map(|&v| all[v].id.as_str())
697            .filter(|id| *id != unit.id)
698            .collect();
699        notes.push(format!(
700            "Import cycle with {}: port them together.",
701            others.join(", ")
702        ));
703    }
704    if unit.deps.is_empty() && !keep {
705        notes.push("Leaf: imports no other unit.".into());
706    }
707    if unit.direct_tests > 0 {
708        notes.push(format!(
709            "{} test files import it directly.",
710            unit.direct_tests
711        ));
712    } else if package_tests == 0 && !keep {
713        notes.push(
714            "No tests found: write characterization tests against the original code first.".into(),
715        );
716    }
717
718    let string_ops = unit.risks.get(&Risk::StringOffsets).map_or(0, |r| r.0);
719    let density = if unit.loc == 0 {
720        0.0
721    } else {
722        ((unit.loops + string_ops) as f64 * 100.0 / unit.loc as f64 * 10.0).round() / 10.0
723    };
724    let bridge = if keep {
725        Bridge::KeepInJs
726    } else if ctx.lang != Lang::Ts {
727        Bridge::for_lang(ctx.lang)
728    } else if ctx.node_reach[u] || ctx.node_packages.contains(&unit.package) {
729        Bridge::NapiRs
730    } else {
731        Bridge::WasmBindgen
732    };
733    if bridge == Bridge::WasmBindgen {
734        notes.push(
735            "Portable code: wasm-bindgen keeps it running in browsers and Node. It needs the \
736             wasm32-unknown-unknown target and wasm-bindgen; `bridge --kind napi` runs with what \
737             Node already has."
738                .into(),
739        );
740    }
741
742    let mut files: Vec<String> = unit
743        .files
744        .iter()
745        .map(|&i| ws.files[i].path.clone())
746        .collect();
747    files.sort();
748    let mut risks: Vec<RiskReport> = unit
749        .risks
750        .iter()
751        .map(|(risk, (count, samples))| RiskReport {
752            risk: *risk,
753            severity: risk.severity(),
754            count: *count,
755            samples: samples.clone(),
756        })
757        .collect();
758    risks.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.count.cmp(&a.count)));
759
760    UnitReport {
761        id: unit.id.clone(),
762        package: packages[unit.package].name.clone(),
763        files,
764        loc: unit.loc,
765        wave,
766        readiness: readiness.round() as u32,
767        status,
768        bridge,
769        platforms: unit.platforms.iter().copied().collect(),
770        risks,
771        internal_deps: unit.deps.iter().map(|&v| all[v].id.clone()).collect(),
772        workspace_deps: unit.workspace_deps.iter().cloned().collect(),
773        external_deps: unit.external_deps.iter().cloned().collect(),
774        direct_tests: unit.direct_tests,
775        fan_in: unit.fan_in,
776        density,
777        priority: priority(
778            readiness,
779            density,
780            unit.loc,
781            unit.direct_tests,
782            package_tests,
783        ),
784        exports: 0,
785        bridgeable: 0,
786        notes,
787    }
788}
789
790fn start_here(units: &[UnitReport]) -> Vec<String> {
791    let pick = |statuses: &[Status], min_loc: usize| -> Vec<&UnitReport> {
792        let mut list: Vec<&UnitReport> = units
793            .iter()
794            .filter(|u| statuses.contains(&u.status) && u.loc >= min_loc && u.bridgeable > 0)
795            .collect();
796        list.sort_by(|a, b| {
797            b.priority
798                .cmp(&a.priority)
799                .then(b.readiness.cmp(&a.readiness))
800                .then(a.wave.cmp(&b.wave))
801                .then(b.density.total_cmp(&a.density))
802                .then(a.id.cmp(&b.id))
803        });
804        list
805    };
806    let mut list = pick(&[Status::Ready], MIN_CANDIDATE_LOC);
807    if list.len() < 3 {
808        list = pick(&[Status::Ready, Status::Caution], MIN_CANDIDATE_LOC);
809    }
810    if list.is_empty() {
811        // Small repos: every unit is under the size floor.
812        list = pick(&[Status::Ready, Status::Caution], 1);
813    }
814    list.into_iter().take(10).map(|u| u.id.clone()).collect()
815}
816
817fn package_reports(
818    ws: &Workspace,
819    units: &[UnitReport],
820    package_tests: &[usize],
821    node_packages: &BTreeSet<usize>,
822) -> Vec<PackageReport> {
823    let names: HashMap<&str, usize> = ws
824        .packages
825        .iter()
826        .enumerate()
827        .map(|(i, p)| (p.name.as_str(), i))
828        .collect();
829    let deps_of: Vec<Vec<usize>> = ws
830        .packages
831        .iter()
832        .enumerate()
833        .map(|(i, p)| {
834            let mut d: Vec<usize> = p
835                .deps
836                .iter()
837                .chain(&p.dev_deps)
838                .filter_map(|n| names.get(n.as_str()).copied())
839                .filter(|&j| j != i)
840                .collect();
841            d.sort_unstable();
842            d.dedup();
843            d
844        })
845        .collect();
846    let order = topological(&deps_of);
847    let mut reports: Vec<PackageReport> = order
848        .iter()
849        .map(|&i| {
850            let p = &ws.packages[i];
851            PackageReport {
852                name: p.name.clone(),
853                dir: p.dir.clone(),
854                order: 0,
855                runtime: if node_packages.contains(&i) {
856                    "node"
857                } else {
858                    "portable"
859                },
860                workspace_deps: deps_of[i]
861                    .iter()
862                    .map(|&j| ws.packages[j].name.clone())
863                    .collect(),
864                test_files: package_tests[i],
865                units: units
866                    .iter()
867                    .filter(|u| u.package == p.name)
868                    .map(|u| u.id.clone())
869                    .collect(),
870            }
871        })
872        .filter(|p| !p.units.is_empty())
873        .collect();
874    for (position, report) in reports.iter_mut().enumerate() {
875        report.order = position + 1;
876    }
877    reports
878}
879
880fn dependency_reports(units: &[UnitReport], lang: Lang) -> Vec<DependencyReport> {
881    let mut used: BTreeMap<&str, usize> = BTreeMap::new();
882    for unit in units.iter().filter(|u| u.status != Status::Keep) {
883        for dep in &unit.external_deps {
884            *used.entry(dep).or_default() += 1;
885        }
886    }
887    let mut out: Vec<DependencyReport> = used
888        .into_iter()
889        .map(|(name, used_by)| {
890            let found = crate_for(lang, name);
891            DependencyReport {
892                name: name.to_string(),
893                used_by,
894                crates: found.map(|m| m.crates),
895                fit: match found.map(|m| m.fit) {
896                    Some(Fit::Good) => "good",
897                    Some(Fit::Partial) => "partial",
898                    Some(Fit::None) => "none",
899                    None => "unknown",
900                },
901                note: found.map_or("", |m| m.note),
902            }
903        })
904        .collect();
905    let rank = |fit: &str| match fit {
906        "none" => 0,
907        "unknown" => 1,
908        "partial" => 2,
909        _ => 3,
910    };
911    out.sort_by(|a, b| {
912        rank(a.fit)
913            .cmp(&rank(b.fit))
914            .then(b.used_by.cmp(&a.used_by))
915    });
916    out
917}
918
919/// Readiness balanced with how much a port would gain.
920fn priority(
921    readiness: f64,
922    density: f64,
923    loc: usize,
924    direct_tests: usize,
925    package_tests: usize,
926) -> u32 {
927    let compute = (density * 4.0).min(50.0);
928    let tests = if direct_tests > 0 {
929        30.0
930    } else if package_tests > 0 {
931        15.0
932    } else {
933        0.0
934    };
935    // Below ~80 lines a port rarely pays for its bridge; past ~600 it is too big for a first step.
936    let size = match loc {
937        0..80 => loc as f64 / 4.0,
938        80..600 => 20.0,
939        _ => 10.0,
940    };
941    let value = compute + tests + size;
942    (readiness * 0.5 + value * 0.5).round().clamp(0.0, 100.0) as u32
943}
944
945/// For each node, whether it or anything reachable from it is flagged.
946fn reaches(edges: &[Vec<usize>], flagged: &[bool]) -> Vec<bool> {
947    let mut out = flagged.to_vec();
948    let mut changed = true;
949    while changed {
950        changed = false;
951        for v in 0..edges.len() {
952            if !out[v] && edges[v].iter().any(|&w| out[w]) {
953                out[v] = true;
954                changed = true;
955            }
956        }
957    }
958    out
959}
960
961/// The unit id for a file: its folder, or the file itself when it sits at the source root.
962fn unit_id(package: &Package, path: &str) -> String {
963    let base =
964        if !package.src_root.is_empty() && path.starts_with(&format!("{}/", package.src_root)) {
965            &package.src_root
966        } else {
967            &package.dir
968        };
969    let rel = if base.is_empty() {
970        path
971    } else {
972        &path[base.len() + 1..]
973    };
974    match rel.rsplit_once('/') {
975        Some((parent, _)) => format!("{}/", discover::join(base, parent)),
976        None => path.to_string(),
977    }
978}
979
980/// Resolves `./x`, `../x.js` and folder imports the way TS bundler resolution does.
981fn resolve_relative(from: &str, spec: &str, index: &HashMap<&str, usize>) -> Option<usize> {
982    let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
983    resolve_base(&normalize(&discover::join(dir, spec))?, index)
984}
985
986/// A root-relative import target, with the extensions and index files bundlers try.
987fn resolve_base(base: &str, index: &HashMap<&str, usize>) -> Option<usize> {
988    let base = base.to_string();
989    let mut candidates = vec![base.clone()];
990    for (js, ts) in [
991        (".js", ".ts"),
992        (".js", ".tsx"),
993        (".jsx", ".tsx"),
994        (".mjs", ".mts"),
995        (".cjs", ".cts"),
996    ] {
997        if let Some(stem) = base.strip_suffix(js) {
998            candidates.push(format!("{stem}{ts}"));
999        }
1000    }
1001    for ext in [
1002        "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "vue", "svelte", "astro",
1003    ] {
1004        candidates.push(format!("{base}.{ext}"));
1005        candidates.push(format!("{base}/index.{ext}"));
1006    }
1007    candidates
1008        .iter()
1009        .find_map(|c| index.get(c.as_str()).copied())
1010}
1011
1012/// Collapses `.` and `..` segments; `None` when the path leaves the root.
1013fn normalize(path: &str) -> Option<String> {
1014    let mut parts: Vec<&str> = Vec::new();
1015    for part in path.split('/') {
1016        match part {
1017            "" | "." => {}
1018            ".." => {
1019                parts.pop()?;
1020            }
1021            _ => parts.push(part),
1022        }
1023    }
1024    Some(parts.join("/"))
1025}
1026
1027/// Port waves from strongly connected components: a unit comes after everything it imports.
1028/// Returns each node's wave and the members of its component.
1029pub(crate) fn waves(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<Vec<usize>>) {
1030    struct Tarjan<'e> {
1031        edges: &'e [Vec<usize>],
1032        index: Vec<Option<usize>>,
1033        low: Vec<usize>,
1034        on_stack: Vec<bool>,
1035        stack: Vec<usize>,
1036        next: usize,
1037        components: Vec<Vec<usize>>,
1038    }
1039    fn visit(t: &mut Tarjan, v: usize) {
1040        t.index[v] = Some(t.next);
1041        t.low[v] = t.next;
1042        t.next += 1;
1043        t.stack.push(v);
1044        t.on_stack[v] = true;
1045        let edges = t.edges;
1046        for &w in &edges[v] {
1047            match t.index[w] {
1048                None => {
1049                    visit(t, w);
1050                    t.low[v] = t.low[v].min(t.low[w]);
1051                }
1052                Some(iw) if t.on_stack[w] => t.low[v] = t.low[v].min(iw),
1053                Some(_) => {}
1054            }
1055        }
1056        if t.index[v] == Some(t.low[v]) {
1057            let mut component = Vec::new();
1058            while let Some(w) = t.stack.pop() {
1059                t.on_stack[w] = false;
1060                component.push(w);
1061                if w == v {
1062                    break;
1063                }
1064            }
1065            t.components.push(component);
1066        }
1067    }
1068    let n = edges.len();
1069    let mut t = Tarjan {
1070        edges,
1071        index: vec![None; n],
1072        low: vec![0; n],
1073        on_stack: vec![false; n],
1074        stack: Vec::new(),
1075        next: 0,
1076        components: Vec::new(),
1077    };
1078    for v in 0..n {
1079        if t.index[v].is_none() {
1080            visit(&mut t, v);
1081        }
1082    }
1083    // Tarjan emits components after everything they reach, so dependencies come first.
1084    let mut wave = vec![0usize; n];
1085    let mut members = vec![Vec::new(); n];
1086    for component in &t.components {
1087        let w = component
1088            .iter()
1089            .flat_map(|&v| edges[v].iter())
1090            .filter(|w| !component.contains(w))
1091            .map(|&w| wave[w] + 1)
1092            .max()
1093            .unwrap_or(0);
1094        for &v in component {
1095            wave[v] = w;
1096            members[v] = component.clone();
1097        }
1098    }
1099    (wave, members)
1100}
1101
1102/// Kahn's algorithm; nodes in cycles are appended in index order.
1103fn topological(deps_of: &[Vec<usize>]) -> Vec<usize> {
1104    let n = deps_of.len();
1105    let mut remaining: Vec<usize> = deps_of.iter().map(Vec::len).collect();
1106    let mut order = Vec::with_capacity(n);
1107    let mut done = vec![false; n];
1108    while let Some(next) = (0..n).find(|&i| !done[i] && remaining[i] == 0) {
1109        done[next] = true;
1110        order.push(next);
1111        for (i, deps) in deps_of.iter().enumerate() {
1112            if deps.contains(&next) {
1113                remaining[i] -= 1;
1114            }
1115        }
1116    }
1117    order.extend((0..n).filter(|&i| !done[i]));
1118    order
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124
1125    #[test]
1126    fn normalizes_paths() {
1127        assert_eq!(normalize("a/./b/../c").as_deref(), Some("a/c"));
1128        assert_eq!(normalize("../x"), None);
1129    }
1130
1131    #[test]
1132    fn orders_waves_and_cycles() {
1133        // 0 -> 1 -> 2, 3 <-> 4 -> 2
1134        let edges = vec![vec![1], vec![2], vec![], vec![4], vec![3, 2]];
1135        let (wave, members) = waves(&edges);
1136        assert_eq!(wave, [2, 1, 0, 1, 1]);
1137        assert_eq!(members[3].len(), 2);
1138    }
1139
1140    #[test]
1141    fn sorts_packages_topologically() {
1142        assert_eq!(topological(&[vec![1], vec![], vec![0, 1]]), [1, 0, 2]);
1143    }
1144}