Skip to main content

rust_anything/
analyze.rs

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