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(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("Portable code: wasm-bindgen keeps it running in browsers and Node.".into());
735    }
736
737    let mut files: Vec<String> = unit
738        .files
739        .iter()
740        .map(|&i| ws.files[i].path.clone())
741        .collect();
742    files.sort();
743    let mut risks: Vec<RiskReport> = unit
744        .risks
745        .iter()
746        .map(|(risk, (count, samples))| RiskReport {
747            risk: *risk,
748            severity: risk.severity(),
749            count: *count,
750            samples: samples.clone(),
751        })
752        .collect();
753    risks.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.count.cmp(&a.count)));
754
755    UnitReport {
756        id: unit.id.clone(),
757        package: packages[unit.package].name.clone(),
758        files,
759        loc: unit.loc,
760        wave,
761        readiness: readiness.round() as u32,
762        status,
763        bridge,
764        platforms: unit.platforms.iter().copied().collect(),
765        risks,
766        internal_deps: unit.deps.iter().map(|&v| all[v].id.clone()).collect(),
767        workspace_deps: unit.workspace_deps.iter().cloned().collect(),
768        external_deps: unit.external_deps.iter().cloned().collect(),
769        direct_tests: unit.direct_tests,
770        fan_in: unit.fan_in,
771        density,
772        priority: priority(
773            readiness,
774            density,
775            unit.loc,
776            unit.direct_tests,
777            package_tests,
778        ),
779        exports: 0,
780        bridgeable: 0,
781        notes,
782    }
783}
784
785fn start_here(units: &[UnitReport]) -> Vec<String> {
786    let pick = |statuses: &[Status], min_loc: usize| -> Vec<&UnitReport> {
787        let mut list: Vec<&UnitReport> = units
788            .iter()
789            .filter(|u| statuses.contains(&u.status) && u.loc >= min_loc && u.bridgeable > 0)
790            .collect();
791        list.sort_by(|a, b| {
792            b.priority
793                .cmp(&a.priority)
794                .then(b.readiness.cmp(&a.readiness))
795                .then(a.wave.cmp(&b.wave))
796                .then(b.density.total_cmp(&a.density))
797                .then(a.id.cmp(&b.id))
798        });
799        list
800    };
801    let mut list = pick(&[Status::Ready], MIN_CANDIDATE_LOC);
802    if list.len() < 3 {
803        list = pick(&[Status::Ready, Status::Caution], MIN_CANDIDATE_LOC);
804    }
805    if list.is_empty() {
806        // Small repos: every unit is under the size floor.
807        list = pick(&[Status::Ready, Status::Caution], 1);
808    }
809    list.into_iter().take(10).map(|u| u.id.clone()).collect()
810}
811
812fn package_reports(
813    ws: &Workspace,
814    units: &[UnitReport],
815    package_tests: &[usize],
816    node_packages: &BTreeSet<usize>,
817) -> Vec<PackageReport> {
818    let names: HashMap<&str, usize> = ws
819        .packages
820        .iter()
821        .enumerate()
822        .map(|(i, p)| (p.name.as_str(), i))
823        .collect();
824    let deps_of: Vec<Vec<usize>> = ws
825        .packages
826        .iter()
827        .enumerate()
828        .map(|(i, p)| {
829            let mut d: Vec<usize> = p
830                .deps
831                .iter()
832                .chain(&p.dev_deps)
833                .filter_map(|n| names.get(n.as_str()).copied())
834                .filter(|&j| j != i)
835                .collect();
836            d.sort_unstable();
837            d.dedup();
838            d
839        })
840        .collect();
841    let order = topological(&deps_of);
842    let mut reports: Vec<PackageReport> = order
843        .iter()
844        .map(|&i| {
845            let p = &ws.packages[i];
846            PackageReport {
847                name: p.name.clone(),
848                dir: p.dir.clone(),
849                order: 0,
850                runtime: if node_packages.contains(&i) {
851                    "node"
852                } else {
853                    "portable"
854                },
855                workspace_deps: deps_of[i]
856                    .iter()
857                    .map(|&j| ws.packages[j].name.clone())
858                    .collect(),
859                test_files: package_tests[i],
860                units: units
861                    .iter()
862                    .filter(|u| u.package == p.name)
863                    .map(|u| u.id.clone())
864                    .collect(),
865            }
866        })
867        .filter(|p| !p.units.is_empty())
868        .collect();
869    for (position, report) in reports.iter_mut().enumerate() {
870        report.order = position + 1;
871    }
872    reports
873}
874
875fn dependency_reports(units: &[UnitReport], lang: Lang) -> Vec<DependencyReport> {
876    let mut used: BTreeMap<&str, usize> = BTreeMap::new();
877    for unit in units.iter().filter(|u| u.status != Status::Keep) {
878        for dep in &unit.external_deps {
879            *used.entry(dep).or_default() += 1;
880        }
881    }
882    let mut out: Vec<DependencyReport> = used
883        .into_iter()
884        .map(|(name, used_by)| {
885            let found = crate_for(lang, name);
886            DependencyReport {
887                name: name.to_string(),
888                used_by,
889                crates: found.map(|m| m.crates),
890                fit: match found.map(|m| m.fit) {
891                    Some(Fit::Good) => "good",
892                    Some(Fit::Partial) => "partial",
893                    Some(Fit::None) => "none",
894                    None => "unknown",
895                },
896                note: found.map_or("", |m| m.note),
897            }
898        })
899        .collect();
900    let rank = |fit: &str| match fit {
901        "none" => 0,
902        "unknown" => 1,
903        "partial" => 2,
904        _ => 3,
905    };
906    out.sort_by(|a, b| {
907        rank(a.fit)
908            .cmp(&rank(b.fit))
909            .then(b.used_by.cmp(&a.used_by))
910    });
911    out
912}
913
914/// Readiness balanced with how much a port would gain.
915fn priority(
916    readiness: f64,
917    density: f64,
918    loc: usize,
919    direct_tests: usize,
920    package_tests: usize,
921) -> u32 {
922    let compute = (density * 4.0).min(50.0);
923    let tests = if direct_tests > 0 {
924        30.0
925    } else if package_tests > 0 {
926        15.0
927    } else {
928        0.0
929    };
930    // Below ~80 lines a port rarely pays for its bridge; past ~600 it is too big for a first step.
931    let size = match loc {
932        0..80 => loc as f64 / 4.0,
933        80..600 => 20.0,
934        _ => 10.0,
935    };
936    let value = compute + tests + size;
937    (readiness * 0.5 + value * 0.5).round().clamp(0.0, 100.0) as u32
938}
939
940/// For each node, whether it or anything reachable from it is flagged.
941fn reaches(edges: &[Vec<usize>], flagged: &[bool]) -> Vec<bool> {
942    let mut out = flagged.to_vec();
943    let mut changed = true;
944    while changed {
945        changed = false;
946        for v in 0..edges.len() {
947            if !out[v] && edges[v].iter().any(|&w| out[w]) {
948                out[v] = true;
949                changed = true;
950            }
951        }
952    }
953    out
954}
955
956/// The unit id for a file: its folder, or the file itself when it sits at the source root.
957fn unit_id(package: &Package, path: &str) -> String {
958    let base =
959        if !package.src_root.is_empty() && path.starts_with(&format!("{}/", package.src_root)) {
960            &package.src_root
961        } else {
962            &package.dir
963        };
964    let rel = if base.is_empty() {
965        path
966    } else {
967        &path[base.len() + 1..]
968    };
969    match rel.rsplit_once('/') {
970        Some((parent, _)) => format!("{}/", discover::join(base, parent)),
971        None => path.to_string(),
972    }
973}
974
975/// Resolves `./x`, `../x.js` and folder imports the way TS bundler resolution does.
976fn resolve_relative(from: &str, spec: &str, index: &HashMap<&str, usize>) -> Option<usize> {
977    let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
978    resolve_base(&normalize(&discover::join(dir, spec))?, index)
979}
980
981/// A root-relative import target, with the extensions and index files bundlers try.
982fn resolve_base(base: &str, index: &HashMap<&str, usize>) -> Option<usize> {
983    let base = base.to_string();
984    let mut candidates = vec![base.clone()];
985    for (js, ts) in [
986        (".js", ".ts"),
987        (".js", ".tsx"),
988        (".jsx", ".tsx"),
989        (".mjs", ".mts"),
990        (".cjs", ".cts"),
991    ] {
992        if let Some(stem) = base.strip_suffix(js) {
993            candidates.push(format!("{stem}{ts}"));
994        }
995    }
996    for ext in [
997        "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "vue", "svelte", "astro",
998    ] {
999        candidates.push(format!("{base}.{ext}"));
1000        candidates.push(format!("{base}/index.{ext}"));
1001    }
1002    candidates
1003        .iter()
1004        .find_map(|c| index.get(c.as_str()).copied())
1005}
1006
1007/// Collapses `.` and `..` segments; `None` when the path leaves the root.
1008fn normalize(path: &str) -> Option<String> {
1009    let mut parts: Vec<&str> = Vec::new();
1010    for part in path.split('/') {
1011        match part {
1012            "" | "." => {}
1013            ".." => {
1014                parts.pop()?;
1015            }
1016            _ => parts.push(part),
1017        }
1018    }
1019    Some(parts.join("/"))
1020}
1021
1022/// Port waves from strongly connected components: a unit comes after everything it imports.
1023/// Returns each node's wave and the members of its component.
1024pub(crate) fn waves(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<Vec<usize>>) {
1025    struct Tarjan<'e> {
1026        edges: &'e [Vec<usize>],
1027        index: Vec<Option<usize>>,
1028        low: Vec<usize>,
1029        on_stack: Vec<bool>,
1030        stack: Vec<usize>,
1031        next: usize,
1032        components: Vec<Vec<usize>>,
1033    }
1034    fn visit(t: &mut Tarjan, v: usize) {
1035        t.index[v] = Some(t.next);
1036        t.low[v] = t.next;
1037        t.next += 1;
1038        t.stack.push(v);
1039        t.on_stack[v] = true;
1040        let edges = t.edges;
1041        for &w in &edges[v] {
1042            match t.index[w] {
1043                None => {
1044                    visit(t, w);
1045                    t.low[v] = t.low[v].min(t.low[w]);
1046                }
1047                Some(iw) if t.on_stack[w] => t.low[v] = t.low[v].min(iw),
1048                Some(_) => {}
1049            }
1050        }
1051        if t.index[v] == Some(t.low[v]) {
1052            let mut component = Vec::new();
1053            while let Some(w) = t.stack.pop() {
1054                t.on_stack[w] = false;
1055                component.push(w);
1056                if w == v {
1057                    break;
1058                }
1059            }
1060            t.components.push(component);
1061        }
1062    }
1063    let n = edges.len();
1064    let mut t = Tarjan {
1065        edges,
1066        index: vec![None; n],
1067        low: vec![0; n],
1068        on_stack: vec![false; n],
1069        stack: Vec::new(),
1070        next: 0,
1071        components: Vec::new(),
1072    };
1073    for v in 0..n {
1074        if t.index[v].is_none() {
1075            visit(&mut t, v);
1076        }
1077    }
1078    // Tarjan emits components after everything they reach, so dependencies come first.
1079    let mut wave = vec![0usize; n];
1080    let mut members = vec![Vec::new(); n];
1081    for component in &t.components {
1082        let w = component
1083            .iter()
1084            .flat_map(|&v| edges[v].iter())
1085            .filter(|w| !component.contains(w))
1086            .map(|&w| wave[w] + 1)
1087            .max()
1088            .unwrap_or(0);
1089        for &v in component {
1090            wave[v] = w;
1091            members[v] = component.clone();
1092        }
1093    }
1094    (wave, members)
1095}
1096
1097/// Kahn's algorithm; nodes in cycles are appended in index order.
1098fn topological(deps_of: &[Vec<usize>]) -> Vec<usize> {
1099    let n = deps_of.len();
1100    let mut remaining: Vec<usize> = deps_of.iter().map(Vec::len).collect();
1101    let mut order = Vec::with_capacity(n);
1102    let mut done = vec![false; n];
1103    while let Some(next) = (0..n).find(|&i| !done[i] && remaining[i] == 0) {
1104        done[next] = true;
1105        order.push(next);
1106        for (i, deps) in deps_of.iter().enumerate() {
1107            if deps.contains(&next) {
1108                remaining[i] -= 1;
1109            }
1110        }
1111    }
1112    order.extend((0..n).filter(|&i| !done[i]));
1113    order
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118    use super::*;
1119
1120    #[test]
1121    fn normalizes_paths() {
1122        assert_eq!(normalize("a/./b/../c").as_deref(), Some("a/c"));
1123        assert_eq!(normalize("../x"), None);
1124    }
1125
1126    #[test]
1127    fn orders_waves_and_cycles() {
1128        // 0 -> 1 -> 2, 3 <-> 4 -> 2
1129        let edges = vec![vec![1], vec![2], vec![], vec![4], vec![3, 2]];
1130        let (wave, members) = waves(&edges);
1131        assert_eq!(wave, [2, 1, 0, 1, 1]);
1132        assert_eq!(members[3].len(), 2);
1133    }
1134
1135    #[test]
1136    fn sorts_packages_topologically() {
1137        assert_eq!(topological(&[vec![1], vec![], vec![0, 1]]), [1, 0, 2]);
1138    }
1139}