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;
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}
53
54impl Bridge {
55    pub fn label(self) -> &'static str {
56        match self {
57            Self::NapiRs => "napi-rs",
58            Self::WasmBindgen => "wasm-bindgen",
59            Self::KeepInJs => "keep",
60            Self::Pyo3 => "PyO3",
61            Self::CAbi => "C ABI",
62            Self::Cgo => "cgo",
63            Self::Fiddle => "Fiddle (C ABI)",
64            Self::Jni => "JNI",
65        }
66    }
67
68    /// The bridge a language uses for code that can move.
69    pub fn for_lang(lang: Lang) -> Self {
70        match lang {
71            Lang::Ts => Self::NapiRs,
72            Lang::Python => Self::Pyo3,
73            Lang::C => Self::CAbi,
74            Lang::Go => Self::Cgo,
75            Lang::Ruby => Self::Fiddle,
76            Lang::Java => Self::Jni,
77        }
78    }
79}
80
81/// The Rust counterpart of a dependency, from the language's table.
82pub fn crate_for(lang: Lang, name: &str) -> Option<deps::CrateMatch> {
83    match lang {
84        Lang::Ts => deps::lookup(name),
85        Lang::Python => crate::lang::python::lookup(name),
86        _ => crate::lang::lookup(lang, name),
87    }
88}
89
90#[derive(Debug, Serialize)]
91pub struct Report {
92    pub schema: &'static str,
93    pub language: Lang,
94    pub summary: Summary,
95    pub packages: Vec<PackageReport>,
96    pub units: Vec<UnitReport>,
97    /// Unit ids suggested as the first ports, best first.
98    pub start_here: Vec<String>,
99    pub dependencies: Vec<DependencyReport>,
100    /// `analyze --whole-app`: entry points, every dependency, pieces and decisions.
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub whole_app: Option<crate::whole_app::WholeApp>,
103}
104
105#[derive(Debug, Default, Serialize)]
106pub struct Summary {
107    pub packages: usize,
108    pub source_files: usize,
109    pub test_files: usize,
110    pub ui_files: usize,
111    pub loc: usize,
112    pub units: usize,
113    pub ready: usize,
114    pub caution: usize,
115    pub blocked: usize,
116    pub keep: usize,
117    pub parse_errors: usize,
118}
119
120#[derive(Debug, Serialize)]
121pub struct PackageReport {
122    pub name: String,
123    pub dir: String,
124    /// Position in dependency order: packages come after the workspace packages they use.
125    pub order: usize,
126    /// `node` when any of its code uses Node APIs, else `portable`.
127    pub runtime: &'static str,
128    pub workspace_deps: Vec<String>,
129    pub test_files: usize,
130    pub units: Vec<String>,
131}
132
133#[derive(Debug, Serialize)]
134pub struct UnitReport {
135    pub id: String,
136    pub package: String,
137    pub files: Vec<String>,
138    pub loc: usize,
139    /// Port order inside the repo: a unit's dependencies are in earlier waves.
140    pub wave: usize,
141    /// 0-100: how safe and easy a port looks from the code alone.
142    pub readiness: u32,
143    pub status: Status,
144    pub bridge: Bridge,
145    pub platforms: Vec<Platform>,
146    pub risks: Vec<RiskReport>,
147    pub internal_deps: Vec<String>,
148    pub workspace_deps: Vec<String>,
149    pub external_deps: Vec<String>,
150    /// Test files that import this unit directly.
151    pub direct_tests: usize,
152    /// Units that import this one.
153    pub fan_in: usize,
154    /// Loops and string-offset operations per 100 lines: a rough hint of compute-heavy code.
155    pub density: f64,
156    /// 0-100: readiness balanced with value (compute-heavy, tested, big enough to matter).
157    /// `start_here` is ordered by it.
158    pub priority: u32,
159    /// Exported functions and classes, and how many of them can cross a bridge unchanged.
160    pub exports: usize,
161    pub bridgeable: usize,
162    pub notes: Vec<String>,
163}
164
165#[derive(Debug, Serialize)]
166pub struct RiskReport {
167    pub risk: Risk,
168    pub severity: Severity,
169    pub count: usize,
170    /// `path:line` of the first occurrences.
171    pub samples: Vec<String>,
172}
173
174#[derive(Debug, Serialize)]
175pub struct DependencyReport {
176    pub name: String,
177    pub used_by: usize,
178    pub crates: Option<&'static str>,
179    /// `good`, `partial`, `none`, or `unknown` when the table has no entry.
180    pub fit: &'static str,
181    pub note: &'static str,
182}
183
184/// What an import specifier points at.
185enum Target {
186    File(usize),
187    Workspace(String),
188    External(String),
189    Platform,
190    Unresolved,
191}
192
193#[derive(Default)]
194struct UnitBuild {
195    id: String,
196    package: usize,
197    files: Vec<usize>,
198    ui: bool,
199    loc: usize,
200    loops: usize,
201    risks: BTreeMap<Risk, (usize, Vec<String>)>,
202    platforms: BTreeSet<Platform>,
203    deps: BTreeSet<usize>,
204    workspace_deps: BTreeSet<String>,
205    external_deps: BTreeSet<String>,
206    unresolved: usize,
207    parse_errors: usize,
208    direct_tests: usize,
209    fan_in: usize,
210}
211
212pub fn analyze(root: &Path) -> Result<Report> {
213    analyze_lang(root, Lang::detect(root))
214}
215
216pub fn analyze_lang(root: &Path, lang: Lang) -> Result<Report> {
217    let ws = match lang {
218        Lang::Ts => discover::discover(root)?,
219        _ => crate::lang::discover(lang, root)?,
220    };
221    let facts: Vec<Option<FileFacts>> = ws
222        .files
223        .iter()
224        .map(|file| {
225            let text = std::fs::read_to_string(root.join(&file.path)).ok()?;
226            if lang != Lang::Ts {
227                return Some(crate::lang::scan(lang, &file.path, &text));
228            }
229            let code = crate::ts::script_of(&file.path, &text);
230            let is_sfc = [".vue", ".svelte", ".astro"]
231                .iter()
232                .any(|e| file.path.ends_with(e));
233            let parse_as = if is_sfc { "sfc.ts" } else { file.path.as_str() };
234            Some(scan::scan(parse_as, &code))
235        })
236        .collect();
237    let mut report = build(root, &ws, &facts, lang);
238    check_bridgeable(root, &mut report, lang);
239    Ok(report)
240}
241
242/// Counts each unit's exports that can cross a bridge, with the rules `bridge` applies. A unit
243/// whose exports are all JS-shaped (plugin objects, callbacks) cannot be ported without an API
244/// change: it is marked `caution` and left out of `start_here`.
245fn check_bridgeable(root: &Path, report: &mut Report, lang: Lang) {
246    use crate::ts::exports::{exported_classes, exported_functions};
247    for unit in &mut report.units {
248        if matches!(unit.status, Status::Keep | Status::Blocked) {
249            continue;
250        }
251        let (mut exports, mut bridgeable) = (0, 0);
252        for file in &unit.files {
253            let Ok(text) = std::fs::read_to_string(root.join(file)) else {
254                continue;
255            };
256            let types = crate::bridge::types_in_scope(root, file, &text);
257            if lang != Lang::Ts {
258                let (functions, classes) = crate::lang::exports(lang, file, &text);
259                exports += functions.len() + classes.len();
260                bridgeable += functions
261                    .iter()
262                    .filter(|f| crate::bridge::js_only_reason(f, &[]).is_none())
263                    .count();
264                bridgeable += classes.iter().filter(|c| c.blocker.is_none()).count();
265                continue;
266            }
267            for mut f in exported_functions(file, &text) {
268                exports += 1;
269                crate::bridge::substitute_constraints(&mut f, &types);
270                bridgeable += usize::from(crate::bridge::js_only_reason(&f, &types).is_none());
271            }
272            for class in exported_classes(file, &text) {
273                exports += 1;
274                bridgeable += usize::from(class.blocker.is_none());
275            }
276        }
277        unit.exports = exports;
278        unit.bridgeable = bridgeable;
279        if exports > 0 && bridgeable == 0 {
280            unit.status = Status::Caution;
281            unit.notes.insert(
282                0,
283                "Every export is JS-shaped (functions, plugin objects, iterators): porting the logic \
284                 means adding a data-only function, an API change."
285                    .into(),
286            );
287        }
288    }
289    let summary = &mut report.summary;
290    (
291        summary.ready,
292        summary.caution,
293        summary.blocked,
294        summary.keep,
295    ) = (0, 0, 0, 0);
296    for u in &report.units {
297        match u.status {
298            Status::Ready => summary.ready += 1,
299            Status::Caution => summary.caution += 1,
300            Status::Blocked => summary.blocked += 1,
301            Status::Keep => summary.keep += 1,
302        }
303    }
304    report.start_here = start_here(&report.units);
305}
306
307fn build(root: &Path, ws: &Workspace, facts: &[Option<FileFacts>], lang: Lang) -> Report {
308    let file_index: HashMap<&str, usize> = ws
309        .files
310        .iter()
311        .enumerate()
312        .map(|(i, f)| (f.path.as_str(), i))
313        .collect();
314    let workspace_names: HashSet<&str> = ws.packages.iter().map(|p| p.name.as_str()).collect();
315    let alias_cache: std::cell::RefCell<HashMap<String, crate::ts::tsconfig::PathAliases>> =
316        std::cell::RefCell::new(HashMap::new());
317    let classify = |from: &str, spec: &str| -> Target {
318        if lang != Lang::Ts {
319            return match crate::lang::resolve(lang, from, spec, &file_index, ws) {
320                crate::lang::Resolution::File(i) => Target::File(i),
321                crate::lang::Resolution::External(name) => Target::External(name),
322                crate::lang::Resolution::Stdlib => Target::Platform,
323                crate::lang::Resolution::Unresolved => Target::Unresolved,
324            };
325        }
326        if spec.starts_with("./") || spec.starts_with("../") || spec == "." || spec == ".." {
327            return resolve_relative(from, spec, &file_index)
328                .map_or(Target::Unresolved, Target::File);
329        }
330        if scan::platform_of(spec).is_some() {
331            return Target::Platform;
332        }
333        // tsconfig `paths` (`~/utils`, `@/lib`), from the tsconfig nearest the importing file.
334        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
335        let aliases = alias_cache
336            .borrow_mut()
337            .entry(dir.to_string())
338            .or_insert_with(|| crate::ts::tsconfig::PathAliases::nearest(root, dir))
339            .clone();
340        let candidates = aliases.candidates(spec);
341        if !candidates.is_empty() {
342            return candidates
343                .iter()
344                .find_map(|base| resolve_base(base, &file_index))
345                .map_or(Target::Unresolved, Target::File);
346        }
347        if spec.starts_with('#')
348            || spec.starts_with('~')
349            || spec.starts_with("@/")
350            || spec.contains(':')
351        {
352            return Target::Unresolved;
353        }
354        let name = deps::package_name(spec);
355        if workspace_names.contains(name) {
356            Target::Workspace(name.to_string())
357        } else {
358            Target::External(name.to_string())
359        }
360    };
361
362    // Group source and UI files into units.
363    let mut units: Vec<UnitBuild> = Vec::new();
364    let mut unit_ids: HashMap<String, usize> = HashMap::new();
365    let mut unit_of: Vec<Option<usize>> = vec![None; ws.files.len()];
366    for (i, file) in ws.files.iter().enumerate() {
367        if file.kind == FileKind::Test {
368            continue;
369        }
370        let id = unit_id(&ws.packages[file.package], &file.path);
371        let u = *unit_ids.entry(id.clone()).or_insert_with(|| {
372            units.push(UnitBuild {
373                id,
374                package: file.package,
375                ..UnitBuild::default()
376            });
377            units.len() - 1
378        });
379        units[u].files.push(i);
380        units[u].ui |= file.kind == FileKind::Ui;
381        unit_of[i] = Some(u);
382    }
383
384    // Aggregate facts and imports per unit; credit tests to what they import.
385    let mut package_tests = vec![0usize; ws.packages.len()];
386    let mut summary = Summary {
387        packages: ws.packages.len(),
388        ..Summary::default()
389    };
390    for (i, file) in ws.files.iter().enumerate() {
391        match file.kind {
392            FileKind::Source => summary.source_files += 1,
393            FileKind::Test => summary.test_files += 1,
394            FileKind::Ui => summary.ui_files += 1,
395        }
396        let Some(f) = &facts[i] else { continue };
397        summary.parse_errors += usize::from(f.parse_errors > 0);
398        if file.kind == FileKind::Test {
399            package_tests[file.package] += 1;
400            let mut hit_units = BTreeSet::new();
401            let mut hit_packages = BTreeSet::new();
402            for import in &f.imports {
403                match classify(&file.path, &import.specifier) {
404                    Target::File(j) => hit_units.extend(unit_of[j]),
405                    Target::Workspace(name) => {
406                        hit_packages.extend(ws.packages.iter().position(|p| p.name == name));
407                    }
408                    _ => {}
409                }
410            }
411            for u in hit_units {
412                units[u].direct_tests += 1;
413            }
414            for p in hit_packages.into_iter().filter(|&p| p != file.package) {
415                package_tests[p] += 1;
416            }
417            continue;
418        }
419        let Some(u) = unit_of[i] else { continue };
420        summary.loc += f.loc;
421        let unit = &mut units[u];
422        unit.loc += f.loc;
423        unit.loops += f.loops;
424        unit.parse_errors += f.parse_errors;
425        unit.platforms.extend(f.platforms.iter().copied());
426        for (risk, lines) in &f.risks {
427            let entry = unit.risks.entry(*risk).or_default();
428            entry.0 += lines.len();
429            for line in lines {
430                if entry.1.len() < SAMPLES_PER_RISK {
431                    entry.1.push(format!("{}:{line}", file.path));
432                }
433            }
434        }
435        for import in &f.imports {
436            match classify(&file.path, &import.specifier) {
437                Target::File(j) => {
438                    if let Some(v) = unit_of[j].filter(|&v| v != u) {
439                        units[u].deps.insert(v);
440                    }
441                }
442                Target::Workspace(name) => {
443                    if name != ws.packages[units[u].package].name {
444                        units[u].workspace_deps.insert(name);
445                    }
446                }
447                Target::External(name) if !import.type_only => {
448                    units[u].external_deps.insert(name);
449                }
450                Target::Unresolved if !import.type_only => units[u].unresolved += 1,
451                Target::Unresolved => {}
452                Target::External(_) | Target::Platform => {}
453            }
454        }
455    }
456    for u in 0..units.len() {
457        for v in units[u].deps.clone() {
458            units[v].fan_in += 1;
459        }
460    }
461
462    let edges: Vec<Vec<usize>> = units
463        .iter()
464        .map(|u| u.deps.iter().copied().collect())
465        .collect();
466    let (waves, cycles) = waves(&edges);
467    // A unit needs Node when it, or anything it imports, uses Node APIs.
468    let node_reach = reaches(
469        &edges,
470        &units
471            .iter()
472            .map(|u| u.platforms.contains(&Platform::Node))
473            .collect::<Vec<_>>(),
474    );
475    // A package is Node-only when its source root needs Node; build scripts beside it do not count.
476    let node_packages: BTreeSet<usize> = units
477        .iter()
478        .enumerate()
479        .filter(|(u, unit)| {
480            let src = &ws.packages[unit.package].src_root;
481            node_reach[*u] && (src.is_empty() || unit.id.starts_with(&format!("{src}/")))
482        })
483        .map(|(_, unit)| unit.package)
484        .collect();
485    let ctx = Ctx {
486        lang,
487        ws,
488        units: &units,
489        package_tests: &package_tests,
490        node_packages: &node_packages,
491        node_reach: &node_reach,
492        waves: &waves,
493        cycles: &cycles,
494    };
495    let mut reports: Vec<UnitReport> = (0..units.len()).map(|u| score(u, &ctx)).collect();
496    reports.sort_by(|a, b| a.id.cmp(&b.id));
497    for r in &reports {
498        match r.status {
499            Status::Ready => summary.ready += 1,
500            Status::Caution => summary.caution += 1,
501            Status::Blocked => summary.blocked += 1,
502            Status::Keep => summary.keep += 1,
503        }
504    }
505    summary.units = reports.len();
506
507    let start_here = start_here(&reports);
508    let packages = package_reports(ws, &reports, &package_tests, &node_packages);
509    let dependencies = dependency_reports(&reports, lang);
510    Report {
511        schema: SCHEMA,
512        language: lang,
513        summary,
514        packages,
515        units: reports,
516        start_here,
517        dependencies,
518        whole_app: None,
519    }
520}
521
522struct Ctx<'a> {
523    lang: Lang,
524    ws: &'a Workspace,
525    units: &'a [UnitBuild],
526    package_tests: &'a [usize],
527    node_packages: &'a BTreeSet<usize>,
528    node_reach: &'a [bool],
529    waves: &'a [usize],
530    cycles: &'a [Vec<usize>],
531}
532
533fn score(u: usize, ctx: &Ctx) -> UnitReport {
534    let unit = &ctx.units[u];
535    let all = ctx.units;
536    let ws = ctx.ws;
537    let packages = &ws.packages;
538    let package_tests = ctx.package_tests[unit.package];
539    let wave = ctx.waves[u];
540    let cycle = &ctx.cycles[u];
541    let mut notes = Vec::new();
542    let keep = unit.ui
543        || unit.platforms.contains(&Platform::Ui)
544        || unit.platforms.contains(&Platform::Editor);
545    let blocking_deps: Vec<&String> = unit
546        .external_deps
547        .iter()
548        .filter(|d| crate_for(ctx.lang, d).is_some_and(|m| m.fit == Fit::None))
549        .collect();
550    let unknown_deps = unit
551        .external_deps
552        .iter()
553        .filter(|d| crate_for(ctx.lang, d).is_none())
554        .count();
555
556    let risk_points: f64 = unit
557        .risks
558        .iter()
559        .map(|(risk, (count, _))| risk.severity().weight() * (1.0 + *count as f64).ln())
560        .sum();
561    let size_penalty = unit.loc as f64 / 40.0;
562    let fan_in_penalty = (unit.fan_in as f64 * 1.5).min(15.0);
563    let dep_penalty = blocking_deps.len() as f64 * 12.0 + unknown_deps as f64 * 4.0;
564    let test_bonus = if unit.direct_tests > 0 {
565        10.0
566    } else if package_tests > 0 {
567        4.0
568    } else {
569        0.0
570    };
571    let readiness = (100.0 - risk_points - size_penalty - fan_in_penalty - dep_penalty
572        + test_bonus)
573        .clamp(0.0, 100.0);
574
575    let status = if keep {
576        notes.push(if unit.platforms.contains(&Platform::Editor) {
577            "Runs in the editor's extension host: keep in TS.".to_string()
578        } else {
579            "UI code: keep in the original language.".to_string()
580        });
581        Status::Keep
582    } else if !blocking_deps.is_empty() || unit.risks.contains_key(&Risk::DynamicCode) {
583        for dep in &blocking_deps {
584            notes.push(format!("`{dep}` has no Rust equivalent."));
585        }
586        if unit.risks.contains_key(&Risk::DynamicCode) {
587            notes.push("Uses dynamic code (eval, new Function or computed imports).".into());
588        }
589        Status::Blocked
590    } else if readiness < 50.0 || unit.parse_errors > 0 {
591        Status::Caution
592    } else {
593        Status::Ready
594    };
595    if unit.parse_errors > 0 {
596        notes.push(format!(
597            "{} parse errors: results for this unit are partial.",
598            unit.parse_errors
599        ));
600    }
601    if unknown_deps > 0 {
602        notes.push(format!(
603            "{unknown_deps} npm dependencies not in the crate table: check them by hand."
604        ));
605    }
606    if unit.unresolved > 0 {
607        notes.push(format!(
608            "{} imports use aliases or virtual modules and were not followed.",
609            unit.unresolved
610        ));
611    }
612    if cycle.len() > 1 {
613        let others: Vec<&str> = cycle
614            .iter()
615            .map(|&v| all[v].id.as_str())
616            .filter(|id| *id != unit.id)
617            .collect();
618        notes.push(format!(
619            "Import cycle with {}: port them together.",
620            others.join(", ")
621        ));
622    }
623    if unit.deps.is_empty() && !keep {
624        notes.push("Leaf: imports no other unit.".into());
625    }
626    if unit.direct_tests > 0 {
627        notes.push(format!(
628            "{} test files import it directly.",
629            unit.direct_tests
630        ));
631    } else if package_tests == 0 && !keep {
632        notes.push(
633            "No tests found: write characterization tests against the original code first.".into(),
634        );
635    }
636
637    let string_ops = unit.risks.get(&Risk::StringOffsets).map_or(0, |r| r.0);
638    let density = if unit.loc == 0 {
639        0.0
640    } else {
641        ((unit.loops + string_ops) as f64 * 100.0 / unit.loc as f64 * 10.0).round() / 10.0
642    };
643    let bridge = if keep {
644        Bridge::KeepInJs
645    } else if ctx.lang != Lang::Ts {
646        Bridge::for_lang(ctx.lang)
647    } else if ctx.node_reach[u] || ctx.node_packages.contains(&unit.package) {
648        Bridge::NapiRs
649    } else {
650        Bridge::WasmBindgen
651    };
652    if bridge == Bridge::WasmBindgen {
653        notes.push("Portable code: wasm-bindgen keeps it running in browsers and Node.".into());
654    }
655
656    let mut files: Vec<String> = unit
657        .files
658        .iter()
659        .map(|&i| ws.files[i].path.clone())
660        .collect();
661    files.sort();
662    let mut risks: Vec<RiskReport> = unit
663        .risks
664        .iter()
665        .map(|(risk, (count, samples))| RiskReport {
666            risk: *risk,
667            severity: risk.severity(),
668            count: *count,
669            samples: samples.clone(),
670        })
671        .collect();
672    risks.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.count.cmp(&a.count)));
673
674    UnitReport {
675        id: unit.id.clone(),
676        package: packages[unit.package].name.clone(),
677        files,
678        loc: unit.loc,
679        wave,
680        readiness: readiness.round() as u32,
681        status,
682        bridge,
683        platforms: unit.platforms.iter().copied().collect(),
684        risks,
685        internal_deps: unit.deps.iter().map(|&v| all[v].id.clone()).collect(),
686        workspace_deps: unit.workspace_deps.iter().cloned().collect(),
687        external_deps: unit.external_deps.iter().cloned().collect(),
688        direct_tests: unit.direct_tests,
689        fan_in: unit.fan_in,
690        density,
691        priority: priority(
692            readiness,
693            density,
694            unit.loc,
695            unit.direct_tests,
696            package_tests,
697        ),
698        exports: 0,
699        bridgeable: 0,
700        notes,
701    }
702}
703
704fn start_here(units: &[UnitReport]) -> Vec<String> {
705    let pick = |statuses: &[Status], min_loc: usize| -> Vec<&UnitReport> {
706        let mut list: Vec<&UnitReport> = units
707            .iter()
708            .filter(|u| statuses.contains(&u.status) && u.loc >= min_loc && u.bridgeable > 0)
709            .collect();
710        list.sort_by(|a, b| {
711            b.priority
712                .cmp(&a.priority)
713                .then(b.readiness.cmp(&a.readiness))
714                .then(a.wave.cmp(&b.wave))
715                .then(b.density.total_cmp(&a.density))
716                .then(a.id.cmp(&b.id))
717        });
718        list
719    };
720    let mut list = pick(&[Status::Ready], MIN_CANDIDATE_LOC);
721    if list.len() < 3 {
722        list = pick(&[Status::Ready, Status::Caution], MIN_CANDIDATE_LOC);
723    }
724    if list.is_empty() {
725        // Small repos: every unit is under the size floor.
726        list = pick(&[Status::Ready, Status::Caution], 1);
727    }
728    list.into_iter().take(10).map(|u| u.id.clone()).collect()
729}
730
731fn package_reports(
732    ws: &Workspace,
733    units: &[UnitReport],
734    package_tests: &[usize],
735    node_packages: &BTreeSet<usize>,
736) -> Vec<PackageReport> {
737    let names: HashMap<&str, usize> = ws
738        .packages
739        .iter()
740        .enumerate()
741        .map(|(i, p)| (p.name.as_str(), i))
742        .collect();
743    let deps_of: Vec<Vec<usize>> = ws
744        .packages
745        .iter()
746        .enumerate()
747        .map(|(i, p)| {
748            let mut d: Vec<usize> = p
749                .deps
750                .iter()
751                .chain(&p.dev_deps)
752                .filter_map(|n| names.get(n.as_str()).copied())
753                .filter(|&j| j != i)
754                .collect();
755            d.sort_unstable();
756            d.dedup();
757            d
758        })
759        .collect();
760    let order = topological(&deps_of);
761    let mut reports: Vec<PackageReport> = order
762        .iter()
763        .map(|&i| {
764            let p = &ws.packages[i];
765            PackageReport {
766                name: p.name.clone(),
767                dir: p.dir.clone(),
768                order: 0,
769                runtime: if node_packages.contains(&i) {
770                    "node"
771                } else {
772                    "portable"
773                },
774                workspace_deps: deps_of[i]
775                    .iter()
776                    .map(|&j| ws.packages[j].name.clone())
777                    .collect(),
778                test_files: package_tests[i],
779                units: units
780                    .iter()
781                    .filter(|u| u.package == p.name)
782                    .map(|u| u.id.clone())
783                    .collect(),
784            }
785        })
786        .filter(|p| !p.units.is_empty())
787        .collect();
788    for (position, report) in reports.iter_mut().enumerate() {
789        report.order = position + 1;
790    }
791    reports
792}
793
794fn dependency_reports(units: &[UnitReport], lang: Lang) -> Vec<DependencyReport> {
795    let mut used: BTreeMap<&str, usize> = BTreeMap::new();
796    for unit in units.iter().filter(|u| u.status != Status::Keep) {
797        for dep in &unit.external_deps {
798            *used.entry(dep).or_default() += 1;
799        }
800    }
801    let mut out: Vec<DependencyReport> = used
802        .into_iter()
803        .map(|(name, used_by)| {
804            let found = crate_for(lang, name);
805            DependencyReport {
806                name: name.to_string(),
807                used_by,
808                crates: found.map(|m| m.crates),
809                fit: match found.map(|m| m.fit) {
810                    Some(Fit::Good) => "good",
811                    Some(Fit::Partial) => "partial",
812                    Some(Fit::None) => "none",
813                    None => "unknown",
814                },
815                note: found.map_or("", |m| m.note),
816            }
817        })
818        .collect();
819    let rank = |fit: &str| match fit {
820        "none" => 0,
821        "unknown" => 1,
822        "partial" => 2,
823        _ => 3,
824    };
825    out.sort_by(|a, b| {
826        rank(a.fit)
827            .cmp(&rank(b.fit))
828            .then(b.used_by.cmp(&a.used_by))
829    });
830    out
831}
832
833/// Readiness balanced with how much a port would gain.
834fn priority(
835    readiness: f64,
836    density: f64,
837    loc: usize,
838    direct_tests: usize,
839    package_tests: usize,
840) -> u32 {
841    let compute = (density * 4.0).min(50.0);
842    let tests = if direct_tests > 0 {
843        30.0
844    } else if package_tests > 0 {
845        15.0
846    } else {
847        0.0
848    };
849    // Below ~80 lines a port rarely pays for its bridge; past ~600 it is too big for a first step.
850    let size = match loc {
851        0..80 => loc as f64 / 4.0,
852        80..600 => 20.0,
853        _ => 10.0,
854    };
855    let value = compute + tests + size;
856    (readiness * 0.5 + value * 0.5).round().clamp(0.0, 100.0) as u32
857}
858
859/// For each node, whether it or anything reachable from it is flagged.
860fn reaches(edges: &[Vec<usize>], flagged: &[bool]) -> Vec<bool> {
861    let mut out = flagged.to_vec();
862    let mut changed = true;
863    while changed {
864        changed = false;
865        for v in 0..edges.len() {
866            if !out[v] && edges[v].iter().any(|&w| out[w]) {
867                out[v] = true;
868                changed = true;
869            }
870        }
871    }
872    out
873}
874
875/// The unit id for a file: its folder, or the file itself when it sits at the source root.
876fn unit_id(package: &Package, path: &str) -> String {
877    let base =
878        if !package.src_root.is_empty() && path.starts_with(&format!("{}/", package.src_root)) {
879            &package.src_root
880        } else {
881            &package.dir
882        };
883    let rel = if base.is_empty() {
884        path
885    } else {
886        &path[base.len() + 1..]
887    };
888    match rel.rsplit_once('/') {
889        Some((parent, _)) => format!("{}/", discover::join(base, parent)),
890        None => path.to_string(),
891    }
892}
893
894/// Resolves `./x`, `../x.js` and folder imports the way TS bundler resolution does.
895fn resolve_relative(from: &str, spec: &str, index: &HashMap<&str, usize>) -> Option<usize> {
896    let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
897    resolve_base(&normalize(&discover::join(dir, spec))?, index)
898}
899
900/// A root-relative import target, with the extensions and index files bundlers try.
901fn resolve_base(base: &str, index: &HashMap<&str, usize>) -> Option<usize> {
902    let base = base.to_string();
903    let mut candidates = vec![base.clone()];
904    for (js, ts) in [
905        (".js", ".ts"),
906        (".js", ".tsx"),
907        (".jsx", ".tsx"),
908        (".mjs", ".mts"),
909        (".cjs", ".cts"),
910    ] {
911        if let Some(stem) = base.strip_suffix(js) {
912            candidates.push(format!("{stem}{ts}"));
913        }
914    }
915    for ext in [
916        "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "vue", "svelte", "astro",
917    ] {
918        candidates.push(format!("{base}.{ext}"));
919        candidates.push(format!("{base}/index.{ext}"));
920    }
921    candidates
922        .iter()
923        .find_map(|c| index.get(c.as_str()).copied())
924}
925
926/// Collapses `.` and `..` segments; `None` when the path leaves the root.
927fn normalize(path: &str) -> Option<String> {
928    let mut parts: Vec<&str> = Vec::new();
929    for part in path.split('/') {
930        match part {
931            "" | "." => {}
932            ".." => {
933                parts.pop()?;
934            }
935            _ => parts.push(part),
936        }
937    }
938    Some(parts.join("/"))
939}
940
941/// Port waves from strongly connected components: a unit comes after everything it imports.
942/// Returns each node's wave and the members of its component.
943pub(crate) fn waves(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<Vec<usize>>) {
944    struct Tarjan<'e> {
945        edges: &'e [Vec<usize>],
946        index: Vec<Option<usize>>,
947        low: Vec<usize>,
948        on_stack: Vec<bool>,
949        stack: Vec<usize>,
950        next: usize,
951        components: Vec<Vec<usize>>,
952    }
953    fn visit(t: &mut Tarjan, v: usize) {
954        t.index[v] = Some(t.next);
955        t.low[v] = t.next;
956        t.next += 1;
957        t.stack.push(v);
958        t.on_stack[v] = true;
959        let edges = t.edges;
960        for &w in &edges[v] {
961            match t.index[w] {
962                None => {
963                    visit(t, w);
964                    t.low[v] = t.low[v].min(t.low[w]);
965                }
966                Some(iw) if t.on_stack[w] => t.low[v] = t.low[v].min(iw),
967                Some(_) => {}
968            }
969        }
970        if t.index[v] == Some(t.low[v]) {
971            let mut component = Vec::new();
972            while let Some(w) = t.stack.pop() {
973                t.on_stack[w] = false;
974                component.push(w);
975                if w == v {
976                    break;
977                }
978            }
979            t.components.push(component);
980        }
981    }
982    let n = edges.len();
983    let mut t = Tarjan {
984        edges,
985        index: vec![None; n],
986        low: vec![0; n],
987        on_stack: vec![false; n],
988        stack: Vec::new(),
989        next: 0,
990        components: Vec::new(),
991    };
992    for v in 0..n {
993        if t.index[v].is_none() {
994            visit(&mut t, v);
995        }
996    }
997    // Tarjan emits components after everything they reach, so dependencies come first.
998    let mut wave = vec![0usize; n];
999    let mut members = vec![Vec::new(); n];
1000    for component in &t.components {
1001        let w = component
1002            .iter()
1003            .flat_map(|&v| edges[v].iter())
1004            .filter(|w| !component.contains(w))
1005            .map(|&w| wave[w] + 1)
1006            .max()
1007            .unwrap_or(0);
1008        for &v in component {
1009            wave[v] = w;
1010            members[v] = component.clone();
1011        }
1012    }
1013    (wave, members)
1014}
1015
1016/// Kahn's algorithm; nodes in cycles are appended in index order.
1017fn topological(deps_of: &[Vec<usize>]) -> Vec<usize> {
1018    let n = deps_of.len();
1019    let mut remaining: Vec<usize> = deps_of.iter().map(Vec::len).collect();
1020    let mut order = Vec::with_capacity(n);
1021    let mut done = vec![false; n];
1022    while let Some(next) = (0..n).find(|&i| !done[i] && remaining[i] == 0) {
1023        done[next] = true;
1024        order.push(next);
1025        for (i, deps) in deps_of.iter().enumerate() {
1026            if deps.contains(&next) {
1027                remaining[i] -= 1;
1028            }
1029        }
1030    }
1031    order.extend((0..n).filter(|&i| !done[i]));
1032    order
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use super::*;
1038
1039    #[test]
1040    fn normalizes_paths() {
1041        assert_eq!(normalize("a/./b/../c").as_deref(), Some("a/c"));
1042        assert_eq!(normalize("../x"), None);
1043    }
1044
1045    #[test]
1046    fn orders_waves_and_cycles() {
1047        // 0 -> 1 -> 2, 3 <-> 4 -> 2
1048        let edges = vec![vec![1], vec![2], vec![], vec![4], vec![3, 2]];
1049        let (wave, members) = waves(&edges);
1050        assert_eq!(wave, [2, 1, 0, 1, 1]);
1051        assert_eq!(members[3].len(), 2);
1052    }
1053
1054    #[test]
1055    fn sorts_packages_topologically() {
1056        assert_eq!(topological(&[vec![1], vec![], vec![0, 1]]), [1, 0, 2]);
1057    }
1058}