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