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