1use 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
18pub const SCHEMA: &str = "rust-anything/analyze@1";
20const SAMPLES_PER_RISK: usize = 3;
21const 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 Ready,
29 Caution,
31 Blocked,
33 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 KeepInJs,
55 Pyo3,
56 CAbi,
58 Cgo,
60 Fiddle,
62 Jni,
63 PhpFfi,
65 DotnetFfi,
66 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 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
103pub 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 pub start_here: Vec<String>,
121 pub dependencies: Vec<DependencyReport>,
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub whole_app: Option<crate::whole_app::WholeApp>,
125 #[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 pub order: usize,
151 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 pub wave: usize,
166 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 pub direct_tests: usize,
177 pub fan_in: usize,
179 pub density: f64,
181 pub priority: u32,
184 pub exports: usize,
186 pub bridgeable: usize,
187 pub notes: Vec<String>,
188 #[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 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 pub fit: &'static str,
209 pub note: &'static str,
210}
211
212enum 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
240const 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 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
343fn 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 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 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 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 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 let node_reach = reaches(
598 &edges,
599 &units
600 .iter()
601 .map(|u| u.platforms.contains(&Platform::Node))
602 .collect::<Vec<_>>(),
603 );
604 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 {}. {}",
656 crate::report::count(compiled, "compiled or packaged file"),
657 compiled_hint()
658 ));
659 }
660 if hidden > 0 {
661 warnings.push(format!(
662 "no source files were analyzed, but {} under {} {} excluded by \
663 ignore rules (.gitignore or .ignore files in this repository); the plan is empty \
664 because of them, not because there is nothing to port",
665 crate::report::count(hidden, &format!("{} file", lang.name())),
666 root.display(),
667 if hidden == 1 { "is" } else { "are" },
668 ));
669 }
670 if hidden == 0
671 && compiled == 0
672 && requested_lang.is_none()
673 && Lang::detect_optional(root).is_none()
674 {
675 warnings.push(format!(
676 "no source files of a supported language (TS/JS, Python, C, Go, Ruby, Java, Kotlin, PHP, C#, PowerShell) under {}",
677 root.display()
678 ));
679 }
680 }
681 Report {
682 schema: SCHEMA,
683 language: lang,
684 summary,
685 packages,
686 units: reports,
687 start_here,
688 dependencies,
689 whole_app: None,
690 warnings,
691 }
692}
693
694struct Ctx<'a> {
695 lang: Lang,
696 ws: &'a Workspace,
697 units: &'a [UnitBuild],
698 package_tests: &'a [usize],
699 node_packages: &'a BTreeSet<usize>,
700 node_reach: &'a [bool],
701 waves: &'a [usize],
702 cycles: &'a [Vec<usize>],
703}
704
705fn score(u: usize, ctx: &Ctx) -> UnitReport {
706 let unit = &ctx.units[u];
707 let all = ctx.units;
708 let ws = ctx.ws;
709 let packages = &ws.packages;
710 let package_tests = ctx.package_tests[unit.package];
711 let wave = ctx.waves[u];
712 let cycle = &ctx.cycles[u];
713 let mut notes = Vec::new();
714 let keep = unit.ui
715 || unit.platforms.contains(&Platform::Ui)
716 || unit.platforms.contains(&Platform::Editor);
717 let blocking_deps: Vec<&String> = unit
718 .external_deps
719 .iter()
720 .filter(|d| crate_for(ctx.lang, d).is_some_and(|m| m.fit == Fit::None))
721 .collect();
722 let unknown_deps = unit
723 .external_deps
724 .iter()
725 .filter(|d| crate_for(ctx.lang, d).is_none())
726 .count();
727
728 let risk_points: f64 = unit
729 .risks
730 .iter()
731 .map(|(risk, (count, _))| risk.severity().weight() * (1.0 + *count as f64).ln())
732 .sum();
733 let size_penalty = unit.loc as f64 / 40.0;
734 let fan_in_penalty = (unit.fan_in as f64 * 1.5).min(15.0);
735 let dep_penalty = blocking_deps.len() as f64 * 12.0 + unknown_deps as f64 * 4.0;
736 let test_bonus = if unit.direct_tests > 0 {
737 10.0
738 } else if package_tests > 0 {
739 4.0
740 } else {
741 0.0
742 };
743 let readiness = (100.0 - risk_points - size_penalty - fan_in_penalty - dep_penalty
744 + test_bonus)
745 .clamp(0.0, 100.0);
746
747 let platform = unit.risks.contains_key(&Risk::PlatformSpecific);
748 let status = if platform {
749 notes.push(
750 "Depends on the target (hardware registers, memory layout, inline assembly): keep in \
751 C, since a recording on this machine cannot vouch for the target."
752 .to_string(),
753 );
754 Status::Keep
755 } else if keep {
756 notes.push(if unit.platforms.contains(&Platform::Editor) {
757 "Runs in the editor's extension host: keep in TS.".to_string()
758 } else {
759 "UI code: keep in the original language.".to_string()
760 });
761 Status::Keep
762 } else if !blocking_deps.is_empty() || unit.risks.contains_key(&Risk::DynamicCode) {
763 for dep in &blocking_deps {
764 notes.push(format!("`{dep}` has no Rust equivalent."));
765 }
766 if unit.risks.contains_key(&Risk::DynamicCode) {
767 notes.push("Uses dynamic code (eval, new Function or computed imports).".into());
768 }
769 Status::Blocked
770 } else if readiness < 50.0 || unit.parse_errors > 0 {
771 Status::Caution
772 } else {
773 Status::Ready
774 };
775 let reasons = notes.clone();
776 if unit.parse_errors > 0 {
777 notes.push(format!(
778 "{}: results for this unit are partial.",
779 crate::report::count(unit.parse_errors, "parse error")
780 ));
781 }
782 if unknown_deps > 0 {
783 let reg = ctx.lang.registry();
784 notes.push(if unknown_deps == 1 {
785 format!("1 {reg} dependency not in the crate table: check it by hand.")
786 } else {
787 format!("{unknown_deps} {reg} dependencies not in the crate table: check them by hand.")
788 });
789 }
790 if unit.unresolved > 0 {
791 notes.push(if unit.unresolved == 1 {
792 "1 import uses aliases or virtual modules and was not followed.".into()
793 } else {
794 format!(
795 "{} imports use aliases or virtual modules and were not followed.",
796 unit.unresolved
797 )
798 });
799 }
800 if cycle.len() > 1 {
801 let others: Vec<&str> = cycle
802 .iter()
803 .map(|&v| all[v].id.as_str())
804 .filter(|id| *id != unit.id)
805 .collect();
806 notes.push(format!(
807 "Import cycle with {}: port them together.",
808 others.join(", ")
809 ));
810 }
811 if !keep && !unit.deps.is_empty() {
812 let names: Vec<String> = unit
814 .deps
815 .iter()
816 .map(|&v| format!("`{}`", all[v].id))
817 .collect();
818 notes.push(format!(
819 "Imports {}: port {} first, or port them together.",
820 names.join(", "),
821 if names.len() == 1 { "it" } else { "them" }
822 ));
823 } else if unit.deps.is_empty() && !keep {
824 if unit.workspace_deps.is_empty() {
825 notes.push("Leaf: imports no other unit.".into());
826 } else {
827 let names: Vec<String> = unit
828 .workspace_deps
829 .iter()
830 .map(|d| format!("`{d}`"))
831 .collect();
832 notes.push(format!(
833 "Imports {} from another workspace package: port {} first.",
834 names.join(", "),
835 if names.len() == 1 {
836 "that package"
837 } else {
838 "those packages"
839 }
840 ));
841 }
842 }
843 if unit.direct_tests > 0 {
844 notes.push(if unit.direct_tests == 1 {
845 "1 test file imports it directly.".to_string()
846 } else {
847 format!("{} test files import it directly.", unit.direct_tests)
848 });
849 } else if package_tests == 0 && !keep {
850 notes.push(
851 "No tests found: write characterization tests against the original code first.".into(),
852 );
853 }
854
855 let string_ops = unit.risks.get(&Risk::StringOffsets).map_or(0, |r| r.0);
856 let density = if unit.loc == 0 {
857 0.0
858 } else {
859 ((unit.loops + string_ops) as f64 * 100.0 / unit.loc as f64 * 10.0).round() / 10.0
860 };
861 let bridge = if keep {
862 Bridge::KeepInJs
863 } else if ctx.lang != Lang::Ts {
864 Bridge::for_lang(ctx.lang)
865 } else if ctx.node_reach[u] || ctx.node_packages.contains(&unit.package) {
866 Bridge::NapiRs
867 } else {
868 Bridge::WasmBindgen
869 };
870 if bridge == Bridge::WasmBindgen {
871 notes.push(
872 "Portable code: wasm-bindgen keeps it running in browsers and Node. It needs the \
873 wasm32-unknown-unknown target and wasm-bindgen; `bridge --kind napi` runs with what \
874 Node already has."
875 .into(),
876 );
877 }
878
879 let mut files: Vec<String> = unit
880 .files
881 .iter()
882 .map(|&i| ws.files[i].path.clone())
883 .collect();
884 files.sort();
885 let mut risks: Vec<RiskReport> = unit
886 .risks
887 .iter()
888 .map(|(risk, (count, samples))| RiskReport {
889 risk: *risk,
890 severity: risk.severity(),
891 count: *count,
892 samples: samples.clone(),
893 })
894 .collect();
895 risks.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.count.cmp(&a.count)));
896
897 UnitReport {
898 id: unit.id.clone(),
899 package: packages[unit.package].name.clone(),
900 files,
901 loc: unit.loc,
902 wave,
903 readiness: readiness.round() as u32,
904 status,
905 bridge,
906 platforms: unit.platforms.iter().copied().collect(),
907 risks,
908 internal_deps: unit.deps.iter().map(|&v| all[v].id.clone()).collect(),
909 workspace_deps: unit.workspace_deps.iter().cloned().collect(),
910 external_deps: unit.external_deps.iter().cloned().collect(),
911 direct_tests: unit.direct_tests,
912 fan_in: unit.fan_in,
913 density,
914 priority: priority(
915 readiness,
916 density,
917 unit.loc,
918 unit.direct_tests,
919 package_tests,
920 ),
921 exports: 0,
922 bridgeable: 0,
923 notes,
924 reasons,
925 }
926}
927
928fn start_here(units: &[UnitReport]) -> Vec<String> {
929 let pick = |statuses: &[Status], min_loc: usize| -> Vec<&UnitReport> {
930 let mut list: Vec<&UnitReport> = units
931 .iter()
932 .filter(|u| statuses.contains(&u.status) && u.loc >= min_loc && u.bridgeable > 0)
933 .collect();
934 list.sort_by(|a, b| {
935 b.priority
936 .cmp(&a.priority)
937 .then(b.readiness.cmp(&a.readiness))
938 .then(a.wave.cmp(&b.wave))
939 .then(b.density.total_cmp(&a.density))
940 .then(a.id.cmp(&b.id))
941 });
942 list
943 };
944 let mut list = pick(&[Status::Ready], MIN_CANDIDATE_LOC);
945 if list.len() < 3 {
946 list = pick(&[Status::Ready, Status::Caution], MIN_CANDIDATE_LOC);
947 }
948 if list.is_empty() {
949 list = pick(&[Status::Ready, Status::Caution], 1);
951 }
952 list.into_iter().take(10).map(|u| u.id.clone()).collect()
953}
954
955fn package_reports(
956 ws: &Workspace,
957 units: &[UnitReport],
958 package_tests: &[usize],
959 node_packages: &BTreeSet<usize>,
960) -> Vec<PackageReport> {
961 let names: HashMap<&str, usize> = ws
962 .packages
963 .iter()
964 .enumerate()
965 .map(|(i, p)| (p.name.as_str(), i))
966 .collect();
967 let deps_of: Vec<Vec<usize>> = ws
968 .packages
969 .iter()
970 .enumerate()
971 .map(|(i, p)| {
972 let mut d: Vec<usize> = p
973 .deps
974 .iter()
975 .chain(&p.dev_deps)
976 .filter_map(|n| names.get(n.as_str()).copied())
977 .filter(|&j| j != i)
978 .collect();
979 d.sort_unstable();
980 d.dedup();
981 d
982 })
983 .collect();
984 let order = topological(&deps_of);
985 let mut reports: Vec<PackageReport> = order
986 .iter()
987 .map(|&i| {
988 let p = &ws.packages[i];
989 PackageReport {
990 name: p.name.clone(),
991 dir: p.dir.clone(),
992 order: 0,
993 runtime: if node_packages.contains(&i) {
994 "node"
995 } else {
996 "portable"
997 },
998 workspace_deps: deps_of[i]
999 .iter()
1000 .map(|&j| ws.packages[j].name.clone())
1001 .collect(),
1002 test_files: package_tests[i],
1003 units: units
1004 .iter()
1005 .filter(|u| u.package == p.name)
1006 .map(|u| u.id.clone())
1007 .collect(),
1008 }
1009 })
1010 .filter(|p| !p.units.is_empty())
1011 .collect();
1012 for (position, report) in reports.iter_mut().enumerate() {
1013 report.order = position + 1;
1014 }
1015 reports
1016}
1017
1018fn dependency_reports(units: &[UnitReport], lang: Lang) -> Vec<DependencyReport> {
1019 let mut used: BTreeMap<&str, usize> = BTreeMap::new();
1020 for unit in units.iter().filter(|u| u.status != Status::Keep) {
1021 for dep in &unit.external_deps {
1022 *used.entry(dep).or_default() += 1;
1023 }
1024 }
1025 let mut out: Vec<DependencyReport> = used
1026 .into_iter()
1027 .map(|(name, used_by)| {
1028 let found = crate_for(lang, name);
1029 DependencyReport {
1030 name: name.to_string(),
1031 used_by,
1032 crates: found.map(|m| m.crates),
1033 fit: match found.map(|m| m.fit) {
1034 Some(Fit::Good) => "good",
1035 Some(Fit::Partial) => "partial",
1036 Some(Fit::None) => "none",
1037 None => "unknown",
1038 },
1039 note: found.map_or("", |m| m.note),
1040 }
1041 })
1042 .collect();
1043 let rank = |fit: &str| match fit {
1044 "none" => 0,
1045 "unknown" => 1,
1046 "partial" => 2,
1047 _ => 3,
1048 };
1049 out.sort_by(|a, b| {
1050 rank(a.fit)
1051 .cmp(&rank(b.fit))
1052 .then(b.used_by.cmp(&a.used_by))
1053 });
1054 out
1055}
1056
1057fn priority(
1059 readiness: f64,
1060 density: f64,
1061 loc: usize,
1062 direct_tests: usize,
1063 package_tests: usize,
1064) -> u32 {
1065 let compute = (density * 4.0).min(50.0);
1066 let tests = if direct_tests > 0 {
1067 30.0
1068 } else if package_tests > 0 {
1069 15.0
1070 } else {
1071 0.0
1072 };
1073 let size = match loc {
1075 0..80 => loc as f64 / 4.0,
1076 80..600 => 20.0,
1077 _ => 10.0,
1078 };
1079 let value = compute + tests + size;
1080 (readiness * 0.5 + value * 0.5).round().clamp(0.0, 100.0) as u32
1081}
1082
1083fn reaches(edges: &[Vec<usize>], flagged: &[bool]) -> Vec<bool> {
1085 let mut out = flagged.to_vec();
1086 let mut changed = true;
1087 while changed {
1088 changed = false;
1089 for v in 0..edges.len() {
1090 if !out[v] && edges[v].iter().any(|&w| out[w]) {
1091 out[v] = true;
1092 changed = true;
1093 }
1094 }
1095 }
1096 out
1097}
1098
1099fn unit_id(package: &Package, path: &str) -> String {
1101 let base =
1102 if !package.src_root.is_empty() && path.starts_with(&format!("{}/", package.src_root)) {
1103 &package.src_root
1104 } else {
1105 &package.dir
1106 };
1107 let rel = if base.is_empty() {
1108 path
1109 } else {
1110 &path[base.len() + 1..]
1111 };
1112 match rel.rsplit_once('/') {
1113 Some((parent, _)) => format!("{}/", discover::join(base, parent)),
1114 None => path.to_string(),
1115 }
1116}
1117
1118fn resolve_relative(from: &str, spec: &str, index: &HashMap<&str, usize>) -> Option<usize> {
1120 let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
1121 resolve_base(&normalize(&discover::join(dir, spec))?, index)
1122}
1123
1124fn resolve_base(base: &str, index: &HashMap<&str, usize>) -> Option<usize> {
1126 let base = base.to_string();
1127 let mut candidates = vec![base.clone()];
1128 for (js, ts) in [
1129 (".js", ".ts"),
1130 (".js", ".tsx"),
1131 (".jsx", ".tsx"),
1132 (".mjs", ".mts"),
1133 (".cjs", ".cts"),
1134 ] {
1135 if let Some(stem) = base.strip_suffix(js) {
1136 candidates.push(format!("{stem}{ts}"));
1137 }
1138 }
1139 let extensions = [
1140 "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "vue", "svelte", "astro",
1141 ];
1142 candidates.extend(extensions.iter().map(|ext| format!("{base}.{ext}")));
1143 candidates.extend(extensions.iter().map(|ext| format!("{base}/index.{ext}")));
1144 candidates
1145 .iter()
1146 .find_map(|c| index.get(c.as_str()).copied())
1147}
1148
1149fn normalize(path: &str) -> Option<String> {
1151 let mut parts: Vec<&str> = Vec::new();
1152 for part in path.split('/') {
1153 match part {
1154 "" | "." => {}
1155 ".." => {
1156 parts.pop()?;
1157 }
1158 _ => parts.push(part),
1159 }
1160 }
1161 Some(parts.join("/"))
1162}
1163
1164pub(crate) fn waves(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<Vec<usize>>) {
1167 struct Tarjan<'e> {
1168 edges: &'e [Vec<usize>],
1169 index: Vec<Option<usize>>,
1170 low: Vec<usize>,
1171 on_stack: Vec<bool>,
1172 stack: Vec<usize>,
1173 next: usize,
1174 components: Vec<Vec<usize>>,
1175 }
1176 fn visit(t: &mut Tarjan, v: usize) {
1177 t.index[v] = Some(t.next);
1178 t.low[v] = t.next;
1179 t.next += 1;
1180 t.stack.push(v);
1181 t.on_stack[v] = true;
1182 let edges = t.edges;
1183 for &w in &edges[v] {
1184 match t.index[w] {
1185 None => {
1186 visit(t, w);
1187 t.low[v] = t.low[v].min(t.low[w]);
1188 }
1189 Some(iw) if t.on_stack[w] => t.low[v] = t.low[v].min(iw),
1190 Some(_) => {}
1191 }
1192 }
1193 if t.index[v] == Some(t.low[v]) {
1194 let mut component = Vec::new();
1195 while let Some(w) = t.stack.pop() {
1196 t.on_stack[w] = false;
1197 component.push(w);
1198 if w == v {
1199 break;
1200 }
1201 }
1202 t.components.push(component);
1203 }
1204 }
1205 let n = edges.len();
1206 let mut t = Tarjan {
1207 edges,
1208 index: vec![None; n],
1209 low: vec![0; n],
1210 on_stack: vec![false; n],
1211 stack: Vec::new(),
1212 next: 0,
1213 components: Vec::new(),
1214 };
1215 for v in 0..n {
1216 if t.index[v].is_none() {
1217 visit(&mut t, v);
1218 }
1219 }
1220 let mut wave = vec![0usize; n];
1222 let mut members = vec![Vec::new(); n];
1223 for component in &t.components {
1224 let w = component
1225 .iter()
1226 .flat_map(|&v| edges[v].iter())
1227 .filter(|w| !component.contains(w))
1228 .map(|&w| wave[w] + 1)
1229 .max()
1230 .unwrap_or(0);
1231 for &v in component {
1232 wave[v] = w;
1233 members[v] = component.clone();
1234 }
1235 }
1236 (wave, members)
1237}
1238
1239fn topological(deps_of: &[Vec<usize>]) -> Vec<usize> {
1241 let n = deps_of.len();
1242 let mut remaining: Vec<usize> = deps_of.iter().map(Vec::len).collect();
1243 let mut order = Vec::with_capacity(n);
1244 let mut done = vec![false; n];
1245 while let Some(next) = (0..n).find(|&i| !done[i] && remaining[i] == 0) {
1246 done[next] = true;
1247 order.push(next);
1248 for (i, deps) in deps_of.iter().enumerate() {
1249 if deps.contains(&next) {
1250 remaining[i] -= 1;
1251 }
1252 }
1253 }
1254 order.extend((0..n).filter(|&i| !done[i]));
1255 order
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260 use super::*;
1261
1262 #[test]
1263 fn status_labels_match_analyze() {
1264 assert_eq!(Status::Ready.label(), "ready");
1265 assert_eq!(Status::Caution.label(), "caution");
1266 assert_eq!(Status::Blocked.label(), "blocked");
1267 assert_eq!(Status::Keep.label(), "keep");
1268 }
1269
1270 #[test]
1271 fn resolves_sibling_file_before_directory_index() {
1272 let mut index = HashMap::from([("choice.js", 0), ("choice/index.ts", 1)]);
1273 assert_eq!(resolve_base("choice", &index), Some(0));
1274 index.remove("choice.js");
1275 assert_eq!(resolve_base("choice", &index), Some(1));
1276 }
1277
1278 #[test]
1279 fn normalizes_paths() {
1280 assert_eq!(normalize("a/./b/../c").as_deref(), Some("a/c"));
1281 assert_eq!(normalize("../x"), None);
1282 }
1283
1284 #[test]
1285 fn orders_waves_and_cycles() {
1286 let edges = vec![vec![1], vec![2], vec![], vec![4], vec![3, 2]];
1288 let (wave, members) = waves(&edges);
1289 assert_eq!(wave, [2, 1, 0, 1, 1]);
1290 assert_eq!(members[3].len(), 2);
1291 }
1292
1293 #[test]
1294 fn only_the_verdict_notes_are_reasons() {
1295 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
1296 let report = analyze_lang(&root, Lang::Ts).unwrap();
1297 let svelte = report
1298 .units
1299 .iter()
1300 .find(|u| u.id == "packages/a/src/svelte.ts")
1301 .unwrap();
1302 assert_eq!(svelte.status, Status::Blocked);
1303 assert!(
1304 svelte.notes.len() > svelte.reasons.len(),
1305 "{:?}",
1306 svelte.notes
1307 );
1308 assert_eq!(svelte.reasons, ["`svelte` has no Rust equivalent."]);
1309 let ready = report
1310 .units
1311 .iter()
1312 .find(|u| u.status == Status::Ready)
1313 .unwrap();
1314 assert!(ready.reasons.is_empty(), "{:?}", ready.reasons);
1315 }
1316
1317 #[test]
1318 fn a_unit_that_imports_a_sibling_says_which_one() {
1319 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
1322 let report = analyze_lang(&root, Lang::Ts).unwrap();
1323 let fs = report
1324 .units
1325 .iter()
1326 .find(|u| u.id.ends_with("fs.ts"))
1327 .expect("fixture has packages/a/src/fs.ts");
1328 assert_eq!(fs.internal_deps, ["packages/a/src/util.ts"]);
1329 assert!(
1330 fs.notes
1331 .iter()
1332 .any(|n| n
1333 == "Imports `packages/a/src/util.ts`: port it first, or port them together."),
1334 "{:?}",
1335 fs.notes
1336 );
1337 let leaf = report
1339 .units
1340 .iter()
1341 .find(|u| u.id.ends_with("parse/"))
1342 .expect("fixture has packages/a/src/parse/");
1343 assert!(
1344 leaf.notes
1345 .iter()
1346 .any(|n| n == "Leaf: imports no other unit."),
1347 "{:?}",
1348 leaf.notes
1349 );
1350 }
1351
1352 #[test]
1353 fn sorts_packages_topologically() {
1354 assert_eq!(topological(&[vec![1], vec![], vec![0, 1]]), [1, 0, 2]);
1355 }
1356
1357 #[test]
1358 fn unit_notes_use_singular_for_one_parse_error_unknown_dep_or_unresolved_import() {
1359 let root = std::env::temp_dir().join(format!("ra-unit-notes-{}", std::process::id()));
1360 let _ = std::fs::remove_dir_all(&root);
1361 std::fs::create_dir_all(root.join("src/errs")).unwrap();
1362 for (path, text) in [
1363 ("package.json", r#"{"name":"t"}"#),
1364 ("src/err1.ts", "export const x = (\n"),
1365 ("src/errs/a.ts", "export const a = (\n"),
1366 ("src/errs/b.ts", "export const b = (\n"),
1367 (
1368 "src/one.ts",
1369 "import 'mystery-pkg-1'\nimport 'virtual:mod-1'\nexport const x = 1\n",
1370 ),
1371 (
1372 "src/two.ts",
1373 "import 'mystery-pkg-1'\nimport 'mystery-pkg-2'\nimport 'virtual:mod-1'\nimport 'virtual:mod-2'\nexport const y = 2\n",
1374 ),
1375 ] {
1376 std::fs::write(root.join(path), text).unwrap();
1377 }
1378 let report = analyze(&root).unwrap();
1379 std::fs::remove_dir_all(&root).unwrap();
1380 for (id, expected) in [
1381 (
1382 "src/err1.ts",
1383 "1 parse error: results for this unit are partial.",
1384 ),
1385 (
1386 "src/errs/",
1387 "2 parse errors: results for this unit are partial.",
1388 ),
1389 (
1390 "src/one.ts",
1391 "1 npm dependency not in the crate table: check it by hand.",
1392 ),
1393 (
1394 "src/one.ts",
1395 "1 import uses aliases or virtual modules and was not followed.",
1396 ),
1397 (
1398 "src/two.ts",
1399 "2 npm dependencies not in the crate table: check them by hand.",
1400 ),
1401 (
1402 "src/two.ts",
1403 "2 imports use aliases or virtual modules and were not followed.",
1404 ),
1405 ] {
1406 let notes = &report.units.iter().find(|u| u.id == id).unwrap().notes;
1407 assert!(notes.iter().any(|n| n == expected), "{id}: {notes:?}");
1408 }
1409 }
1410}