1use std::collections::{BTreeSet, HashSet};
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::Result;
11use serde::{Deserialize, Serialize};
12
13use crate::bridge::Manifest;
14use crate::harness::{self, CASES, DiffOptions};
15
16#[derive(Debug, Serialize)]
17pub struct Check {
18 pub name: &'static str,
19 pub passed: bool,
20 pub detail: String,
21 #[serde(skip_serializing_if = "Option::is_none")]
23 pub fix: Option<String>,
24}
25
26fn spawn_fix(err: &anyhow::Error) -> Option<String> {
28 let spawn = err.downcast_ref::<crate::process::SpawnError>()?;
29 Some(if spawn.missing {
30 match crate::doctor::missing_command(&spawn.program) {
31 Some(install) if !install.contains('\n') => {
32 format!(
33 "install `{}` with `{install}`, or run `rust-anything doctor`",
34 spawn.program
35 )
36 }
37 _ => format!(
38 "run `rust-anything doctor` for how to install `{}`",
39 spawn.program
40 ),
41 }
42 } else {
43 "run `rust-anything doctor` and check that the build tool can run".into()
44 })
45}
46
47fn fix_for(check: &Check, crate_dir: &Path) -> Option<String> {
49 let c = crate_dir.display();
50 let manifest = format!("--manifest-path {c}/Cargo.toml");
51 Some(match check.name {
52 "fmt" => format!("cargo fmt {manifest}"),
53 "clippy" => {
54 format!("cargo clippy --all-targets {manifest} -- -D warnings, then fix each warning")
55 }
56 "cargo test" => format!("cargo test {manifest}"),
57 "unsafe" => "add a `// SAFETY:` comment above each listed `unsafe`, or remove it".into(),
58 "ported" => {
59 "port the functions still stubbed in src/port.rs, then `rust-anything gate` again"
60 .into()
61 }
62 "size" => "use the crates `rust-anything analyze` lists and fold repeated code".into(),
63 "literals" => "compute these values the way the original does; a constant the original \
64 takes from a library can stay with a `// recorded-literal:` comment"
65 .into(),
66 "tests" => format!(
67 "restore the removed tests or assertions; if the change is intended, delete \
68 `{c}/{TESTS_BASELINE}` and run gate again"
69 ),
70 "build" => format!("fix the compile error above, then `rust-anything build {c}`"),
71 "recording" => format!("rust-anything record {c}"),
72 "behavior" if check.detail.contains("no recorded cases") => {
73 format!("rust-anything record {c}")
74 }
75 "behavior" => format!(
76 "rust-anything diff {c} to see each mismatch; fix the port, or list an intended difference in {}",
77 crate::recording::KNOWN_DIFFS
78 ),
79 "known diffs" => format!(
80 "remove the entries that no longer happen from {c}/{}",
81 crate::recording::KNOWN_DIFFS
82 ),
83 "api" => {
84 format!("export the missing functions from src/port.rs, then `rust-anything build {c}`")
85 }
86 "error cases" | "panics" => {
87 format!("rust-anything diff {c} to see the cases where the port's errors differ")
88 }
89 _ => return None,
90 })
91}
92
93const GENERATED: [&str; 8] = [
95 "lib.rs",
96 "js.rs",
97 "pinned.rs",
98 "pyconv.rs",
99 "pynum.rs",
100 "rbconv.rs",
101 "utf16.rs",
102 "wire.rs",
103];
104
105pub const MAX_GROWTH: f64 = 3.0;
108const ALLOWANCE: f64 = 50.0;
109
110fn files_under(path: &Path, extensions: &[&str]) -> Vec<std::path::PathBuf> {
111 if path.is_file() {
112 return vec![path.to_path_buf()];
113 }
114 crate::walk::builder(path)
115 .build()
116 .flatten()
117 .map(ignore::DirEntry::into_path)
118 .filter(|p| {
119 p.extension()
120 .is_some_and(|e| extensions.contains(&e.to_string_lossy().as_ref()))
121 })
122 .collect()
123}
124
125pub(crate) fn with_local_imports(root: &Path, files: Vec<PathBuf>) -> Vec<PathBuf> {
130 const TRIES: &[&str] = &[
131 "",
132 ".ts",
133 ".tsx",
134 ".mts",
135 ".cts",
136 ".js",
137 ".mjs",
138 ".cjs",
139 "/index.ts",
140 "/index.tsx",
141 "/index.js",
142 "/index.mjs",
143 ];
144 let resolve = |from: &Path, spec: &str| -> Option<PathBuf> {
145 let base = from.parent()?.join(spec);
146 let stem = base.with_extension("");
147 let js_to_ts = matches!(
148 base.extension().and_then(|e| e.to_str()),
149 Some("js" | "mjs" | "cjs")
150 );
151 TRIES
152 .iter()
153 .map(|t| PathBuf::from(format!("{}{t}", base.display())))
154 .chain(js_to_ts.then(|| stem.with_extension("ts")))
155 .find(|p| p.is_file())
156 };
157 let mut seen: std::collections::BTreeSet<PathBuf> = files.into_iter().collect();
158 let mut todo: Vec<PathBuf> = seen.iter().cloned().collect();
159 while let Some(file) = todo.pop() {
160 let Ok(text) = std::fs::read_to_string(&file) else {
161 continue;
162 };
163 for import in crate::ts::scan::scan(&file.to_string_lossy(), &text).imports {
164 if !import.specifier.starts_with('.') || import.type_only {
165 continue;
166 }
167 if let Some(found) = resolve(&file, &import.specifier)
168 && found.starts_with(root)
169 && !found.components().any(|c| c.as_os_str() == "node_modules")
170 && seen.insert(found.clone())
171 {
172 todo.push(found);
173 }
174 }
175 }
176 seen.into_iter().collect()
177}
178
179fn source_files(manifest: &Manifest) -> Vec<PathBuf> {
181 let mut files = files_under(
182 &manifest.root.join(&manifest.unit),
183 manifest.language.extensions(),
184 );
185 if manifest.language == crate::lang::Lang::Ts {
186 files = with_local_imports(&manifest.root, files);
187 }
188 if manifest.language == crate::lang::Lang::C {
189 let ported: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
190 files.extend(crate::lang::c::called_implementations(
191 &manifest.root,
192 &manifest.unit,
193 &ported,
194 ));
195 }
196 files
197}
198
199fn port_files(crate_dir: &Path) -> Vec<PathBuf> {
201 files_under(&crate_dir.join("src"), &["rs"])
202 .into_iter()
203 .filter(|p| {
204 p.file_name()
205 .is_none_or(|n| !GENERATED.contains(&n.to_string_lossy().as_ref()))
206 })
207 .collect()
208}
209
210fn size_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
211 let source: usize = source_files(manifest)
212 .iter()
213 .filter_map(|p| std::fs::read_to_string(p).ok())
214 .map(|t| crate::lang::syntax::loc(&t, manifest.language))
215 .sum();
216 if source == 0 {
217 return None;
218 }
219 let rust: usize = port_files(crate_dir)
220 .iter()
221 .filter_map(|p| std::fs::read_to_string(p).ok())
222 .map(|t| crate::lang::syntax::code_lines(&t, &["//"]))
223 .sum();
224 let growth = rust as f64 / source as f64;
225 let passed = rust as f64 <= MAX_GROWTH * source as f64 + ALLOWANCE;
226 Some(Check {
227 fix: None,
228 name: "size",
229 passed,
230 detail: format!(
231 "{} of Rust for {} of {} ({growth:.1}x){}",
232 crate::report::count(rust, "line"),
233 crate::report::count(source, "line"),
234 manifest.language.name(),
235 if passed {
236 String::new()
237 } else {
238 format!(
239 "; over {MAX_GROWTH}x usually means code a crate already provides, or a case \
240 handled one by one: use the crates `analyze` lists and fold repeated code"
241 )
242 }
243 ),
244 })
245}
246
247const RECORDING_FILES: [&str; 3] = [
249 CASES,
250 crate::recording::KNOWN_DIFFS,
251 crate::recording::RECORDED_FROM,
252];
253const MIN_STRING: usize = 8;
255const MIN_DIGITS: usize = 5;
257const LITERALS_FAIL: usize = 3;
259const TESTS_BASELINE: &str = ".rust-anything/tests.json";
261
262#[derive(Default)]
264struct Scan {
265 code: String,
266 strings: Vec<(usize, String)>,
267 numbers: Vec<(usize, String)>,
268 marked: BTreeSet<usize>,
270}
271
272fn starts(chars: &[char], i: usize, s: &str) -> bool {
273 s.chars()
274 .enumerate()
275 .all(|(k, c)| chars.get(i + k) == Some(&c))
276}
277
278fn scan_rust(text: &str, stop_at_tests: bool) -> Scan {
282 let chars: Vec<char> = text.chars().collect();
283 let ident = |c: char| c.is_alphanumeric() || c == '_';
284 let digits = |chars: &[char], mut i: usize| {
285 while chars
286 .get(i)
287 .is_some_and(|c| c.is_ascii_digit() || *c == '_')
288 {
289 i += 1;
290 }
291 i
292 };
293 let mut scan = Scan::default();
294 let mut line = 1;
295 let mut i = 0;
296 while i < chars.len() {
297 let c = chars[i];
298 let free = i == 0 || !ident(chars[i - 1]);
299 if stop_at_tests && starts(&chars, i, "#[cfg(test)]") {
300 break;
301 }
302 if starts(&chars, i, "//") {
303 let end = chars[i..]
304 .iter()
305 .position(|&c| c == '\n')
306 .map_or(chars.len(), |p| i + p);
307 if chars[i..end]
308 .iter()
309 .collect::<String>()
310 .contains("recorded-literal:")
311 {
312 scan.marked.insert(line);
313 }
314 i = end;
315 continue;
316 }
317 if starts(&chars, i, "/*") {
318 let mut depth = 0usize;
319 while i < chars.len() {
320 if starts(&chars, i, "/*") {
321 depth += 1;
322 i += 2;
323 } else if starts(&chars, i, "*/") {
324 depth -= 1;
325 i += 2;
326 if depth == 0 {
327 break;
328 }
329 } else {
330 if chars[i] == '\n' {
331 line += 1;
332 scan.code.push('\n');
333 }
334 i += 1;
335 }
336 }
337 continue;
338 }
339 let raw = match c {
340 'r' if free => Some(i + 1),
341 'b' | 'c' if free && chars.get(i + 1) == Some(&'r') => Some(i + 2),
342 _ => None,
343 }
344 .and_then(|j| {
345 let hashes = chars[j..].iter().take_while(|&&h| h == '#').count();
346 (chars.get(j + hashes) == Some(&'"')).then_some((j + hashes + 1, hashes))
347 });
348 if let Some((start, hashes)) = raw {
349 let close = format!("\"{}", "#".repeat(hashes));
350 let end = (start..chars.len())
351 .find(|&k| starts(&chars, k, &close))
352 .unwrap_or(chars.len());
353 let value: String = chars[start..end].iter().collect();
354 scan.strings.push((line, value.clone()));
355 line += value.matches('\n').count();
356 scan.code.push_str("\"\"");
357 i = end + close.len();
358 continue;
359 }
360 let quoted = if c == '"' {
361 Some(i + 1)
362 } else if free && matches!(c, 'b' | 'c') && chars.get(i + 1) == Some(&'"') {
363 Some(i + 2)
364 } else {
365 None
366 };
367 if let Some(mut j) = quoted {
368 let at = line;
369 let mut value = String::new();
370 while j < chars.len() && chars[j] != '"' {
371 if chars[j] != '\\' {
372 if chars[j] == '\n' {
373 line += 1;
374 }
375 value.push(chars[j]);
376 j += 1;
377 continue;
378 }
379 let escaped = chars.get(j + 1).copied().unwrap_or('\\');
380 j += 2;
381 match escaped {
382 'n' => value.push('\n'),
383 't' => value.push('\t'),
384 'r' => value.push('\r'),
385 '0' => value.push('\0'),
386 'x' => {
387 let hex: String = chars[j..(j + 2).min(chars.len())].iter().collect();
388 value.extend(u8::from_str_radix(&hex, 16).ok().map(char::from));
389 j += 2;
390 }
391 'u' if chars.get(j) == Some(&'{') => {
392 let end = (j..chars.len())
393 .find(|&k| chars[k] == '}')
394 .unwrap_or(chars.len());
395 let hex: String = chars[j + 1..end].iter().filter(|c| **c != '_').collect();
396 value.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32));
397 j = end + 1;
398 }
399 '\n' => {
400 line += 1;
401 while j < chars.len() && chars[j].is_whitespace() {
402 if chars[j] == '\n' {
403 line += 1;
404 }
405 j += 1;
406 }
407 }
408 other => value.push(other),
409 }
410 }
411 scan.strings.push((at, value));
412 scan.code.push_str("\"\"");
413 i = j + 1;
414 continue;
415 }
416 if c == '\'' {
417 let end = if chars.get(i + 1) == Some(&'\\') {
418 (i + 3..chars.len()).find(|&k| chars[k] == '\'')
419 } else {
420 (chars.get(i + 2) == Some(&'\'')).then_some(i + 2)
421 };
422 if let Some(end) = end {
423 scan.code.push_str("' '");
424 i = end + 1;
425 continue;
426 }
427 }
428 let after_range = i >= 2 && chars[i - 1] == '.' && chars[i - 2] == '.';
429 if c.is_ascii_digit() && free && (i == 0 || chars[i - 1] != '.' || after_range) {
430 let start = i;
431 if c == '0' && matches!(chars.get(i + 1), Some('x' | 'o' | 'b')) {
432 while i < chars.len() && ident(chars[i]) {
433 i += 1;
434 }
435 scan.code.extend(&chars[start..i]);
436 continue;
437 }
438 i = digits(&chars, i);
439 if chars.get(i) == Some(&'.') && chars.get(i + 1).is_some_and(char::is_ascii_digit) {
440 i = digits(&chars, i + 1);
441 }
442 if matches!(chars.get(i), Some('e' | 'E')) {
443 let sign = usize::from(matches!(chars.get(i + 1), Some('+' | '-')));
444 if chars.get(i + 1 + sign).is_some_and(char::is_ascii_digit) {
445 i = digits(&chars, i + 1 + sign);
446 }
447 }
448 let number: String = chars[start..i].iter().filter(|c| **c != '_').collect();
449 while i < chars.len() && ident(chars[i]) {
450 i += 1;
451 }
452 scan.code.extend(&chars[start..i]);
453 scan.numbers.push((line, number));
454 continue;
455 }
456 if c == '\n' {
457 line += 1;
458 }
459 scan.code.push(c);
460 i += 1;
461 }
462 scan
463}
464
465fn significant_digits(number: &str) -> usize {
467 let mantissa = number.split(['e', 'E']).next().unwrap_or(number);
468 let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
469 digits.trim_start_matches('0').trim_end_matches('0').len()
470}
471
472fn well_known(number: &str) -> bool {
475 if number.chars().all(|c| c.is_ascii_digit()) {
476 let Ok(n) = number.parse::<u128>() else {
477 return false;
478 };
479 let mut ten = n;
480 while ten >= 10 && ten % 10 == 0 {
481 ten /= 10;
482 }
483 return ten == 1
484 || n == u128::MAX
485 || [Some(n), n.checked_add(1), n.checked_sub(1)]
486 .into_iter()
487 .flatten()
488 .any(u128::is_power_of_two);
489 }
490 let Ok(v) = number.parse::<f64>() else {
491 return false;
492 };
493 [
494 f64::MAX,
495 f64::MIN_POSITIVE,
496 f64::EPSILON,
497 f64::from(f32::MAX),
498 f64::from(f32::MIN_POSITIVE),
499 f64::from(f32::EPSILON),
500 ]
501 .iter()
502 .any(|k| ((v - k) / k).abs() < 1e-6)
503}
504
505#[derive(Default)]
507struct Recorded {
508 strings: HashSet<String>,
509 numbers: HashSet<u64>,
510}
511
512impl Recorded {
513 fn add(&mut self, value: &serde_json::Value) {
514 match value {
515 serde_json::Value::String(s) if s.chars().count() >= MIN_STRING => {
516 self.strings.insert(s.clone());
517 }
518 serde_json::Value::Number(n) => {
519 if let Some(f) = n.as_f64() {
520 self.numbers.insert((f + 0.0).to_bits());
521 }
522 }
523 serde_json::Value::Array(items) => items.iter().for_each(|v| self.add(v)),
524 serde_json::Value::Object(o) => o.values().for_each(|v| self.add(v)),
525 _ => {}
526 }
527 }
528}
529
530fn recorded_values(crate_dir: &Path) -> Option<Recorded> {
531 let text = std::fs::read_to_string(crate_dir.join(CASES)).ok()?;
532 let mut recorded = Recorded::default();
533 for line in text.lines().filter(|l| !l.trim().is_empty()) {
534 let Ok(serde_json::Value::Object(case)) = serde_json::from_str(line) else {
535 continue;
536 };
537 for (key, value) in &case {
538 if !matches!(key.as_str(), "fn" | "class" | "module") {
539 recorded.add(value);
540 }
541 }
542 }
543 Some(recorded)
544}
545
546pub fn literals_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
551 let recorded = recorded_values(crate_dir)?;
552 let original: String = source_files(manifest)
553 .iter()
554 .filter_map(|p| std::fs::read_to_string(p).ok())
555 .collect::<Vec<_>>()
556 .join("\n");
557 let in_original = |text: &str| {
558 original.contains(text)
559 || serde_json::to_string(text)
560 .is_ok_and(|j| original.contains(&j[1..j.len().saturating_sub(1)]))
561 };
562 let mut found: Vec<(String, String, String)> = Vec::new();
563 let mut reads = Vec::new();
564 for file in port_files(crate_dir) {
565 let Ok(text) = std::fs::read_to_string(&file) else {
566 continue;
567 };
568 let scan = scan_rust(&text, true);
569 let name = file
570 .strip_prefix(crate_dir)
571 .unwrap_or(&file)
572 .to_string_lossy()
573 .replace('\\', "/");
574 let mut note = |key: String, shown: String, line: usize| {
575 if !found.iter().any(|(k, _, _)| *k == key) {
576 found.push((key, shown, format!("{name}:{line}")));
577 }
578 };
579 for (line, s) in &scan.strings {
580 if RECORDING_FILES.iter().any(|f| s.contains(f)) {
581 reads.push(format!("{name}:{line}"));
582 }
583 if scan.marked.contains(line) || !recorded.strings.contains(s) || in_original(s) {
584 continue;
585 }
586 let shown: String = if s.chars().count() > 40 {
587 s.chars().take(37).chain("...".chars()).collect()
588 } else {
589 s.clone()
590 };
591 note(
592 format!("s{s}"),
593 serde_json::to_string(&shown).unwrap_or_default(),
594 *line,
595 );
596 }
597 for (line, n) in &scan.numbers {
598 if scan.marked.contains(line) || significant_digits(n) < MIN_DIGITS || well_known(n) {
599 continue;
600 }
601 let Ok(v) = n.parse::<f64>() else {
602 continue;
603 };
604 let bits = (v + 0.0).to_bits();
605 if recorded.numbers.contains(&bits) && !original.contains(n.as_str()) {
606 note(format!("n{bits}"), n.clone(), *line);
607 }
608 }
609 }
610 let listed = found
611 .iter()
612 .take(5)
613 .map(|(_, shown, at)| format!("{shown} ({at})"))
614 .chain((found.len() > 5).then(|| format!("{} more", found.len() - 5)))
615 .collect::<Vec<_>>()
616 .join(", ");
617 let (passed, detail) = if !reads.is_empty() {
618 (
619 false,
620 format!(
621 "the port names the recording ({}) at {}: compute results, never look them up",
622 RECORDING_FILES.join(", "),
623 reads.join(", ")
624 ),
625 )
626 } else if found.len() >= LITERALS_FAIL {
627 (
628 false,
629 format!(
630 "{} recorded values are written into the port, and the original spells out none \
631 of them: {listed}",
632 found.len()
633 ),
634 )
635 } else if !found.is_empty() {
636 (
637 true,
638 format!(
639 "{} written into the port that the original never spells out: {listed}; compute \
640 {} unless the original takes {} from a library (then mark the line \
641 `// recorded-literal: <reason>`)",
642 crate::report::count(found.len(), "recorded value"),
643 if found.len() == 1 { "it" } else { "them" },
644 if found.len() == 1 { "it" } else { "them" },
645 ),
646 )
647 } else {
648 (true, "no recorded values written into the port".into())
649 };
650 Some(Check {
651 fix: None,
652 name: "literals",
653 passed,
654 detail,
655 })
656}
657
658#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
660pub struct TestCounts {
661 #[serde(default)]
662 pub tests: usize,
663 #[serde(default)]
664 pub asserts: usize,
665 #[serde(default)]
666 pub ignored: usize,
667 #[serde(default)]
668 pub should_panic: usize,
669}
670
671pub fn test_counts(crate_dir: &Path) -> TestCounts {
672 let patterns = [
673 r"#\[\s*(?:\w+::)*test\s*\]",
674 r"\b(?:debug_)?assert(?:_\w+)?!",
675 r"#\[\s*ignore\b",
676 r"#\[\s*should_panic\b",
677 ]
678 .map(|p| regex::Regex::new(p).ok());
679 let tests = crate_dir.join("tests");
680 let mut files = port_files(crate_dir);
681 if tests.is_dir() {
682 files.extend(files_under(&tests, &["rs"]));
683 }
684 let mut n = [0usize; 4];
685 for file in files {
686 let Ok(text) = std::fs::read_to_string(&file) else {
687 continue;
688 };
689 let code = scan_rust(&text, false).code;
690 for (count, re) in n.iter_mut().zip(&patterns) {
691 *count += re.as_ref().map_or(0, |re| re.find_iter(&code).count());
692 }
693 }
694 let [tests, asserts, ignored, should_panic] = n;
695 TestCounts {
696 tests,
697 asserts,
698 ignored,
699 should_panic,
700 }
701}
702
703pub fn save_tests_baseline(crate_dir: &Path) -> Result<()> {
705 let path = crate_dir.join(TESTS_BASELINE);
706 if let Some(dir) = path.parent() {
707 std::fs::create_dir_all(dir)?;
708 }
709 std::fs::write(
710 &path,
711 serde_json::to_string_pretty(&test_counts(crate_dir))? + "\n",
712 )?;
713 Ok(())
714}
715
716pub fn tests_check(crate_dir: &Path) -> Check {
719 let now = test_counts(crate_dir);
720 let counts = format!(
721 "{}, {}",
722 crate::report::count(now.tests, "test"),
723 crate::report::count(now.asserts, "assertion")
724 );
725 let baseline: Option<TestCounts> = std::fs::read_to_string(crate_dir.join(TESTS_BASELINE))
726 .ok()
727 .and_then(|t| serde_json::from_str(&t).ok());
728 let Some(before) = baseline else {
729 return Check {
730 fix: None,
731 name: "tests",
732 passed: true,
733 detail: format!("{counts}; saved as the baseline once gate passes"),
734 };
735 };
736 let mut worse = Vec::new();
737 if now.tests < before.tests {
738 worse.push(format!("tests {} -> {}", before.tests, now.tests));
739 }
740 if now.asserts < before.asserts {
741 worse.push(format!("assertions {} -> {}", before.asserts, now.asserts));
742 }
743 if now.ignored > before.ignored {
744 worse.push(format!("ignored {} -> {}", before.ignored, now.ignored));
745 }
746 Check {
747 fix: None,
748 name: "tests",
749 passed: worse.is_empty(),
750 detail: if worse.is_empty() {
751 format!("{counts}, none removed since the last passing gate")
752 } else {
753 format!("{} since the last passing gate", worse.join(", "))
754 },
755 }
756}
757
758#[derive(Debug, Serialize)]
759pub struct GateOutcome {
760 pub passed: bool,
761 pub checks: Vec<Check>,
762}
763
764pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
765 let manifest = Manifest::load(crate_dir)?;
766 let lockfile = lockfile_check(crate_dir);
767 let mut checks = rust_checks(crate_dir, &crate::cache::target_for(crate_dir)?.dir);
768 checks.extend(lockfile);
769 checks.extend(advisories_check(crate_dir));
770 checks.push(ported_check(crate_dir));
771
772 checks.extend(size_check(crate_dir, &manifest));
773 checks.extend(literals_check(crate_dir, &manifest));
774 checks.push(tests_check(crate_dir));
775 checks.extend(crate::error_paths::checks(crate_dir, &manifest));
776 let built = harness::build(crate_dir);
777 let built_ok = built.is_ok();
778 let (build_detail, build_fix) = match built {
779 Ok(path) => (format!("built {}", path.display()), None),
780 Err(e) => (last_lines(&format!("{e:#}"), 15), spawn_fix(&e)),
781 };
782 checks.push(Check {
783 fix: build_fix,
784 name: "build",
785 passed: built_ok,
786 detail: build_detail,
787 });
788
789 if let Some(why) = crate::recording::stale(crate_dir, &manifest) {
790 checks.push(Check {
791 fix: None,
792 name: "recording",
793 passed: false,
794 detail: why,
795 });
796 }
797 if let Some(why) = crate::recording::cases_tampered(crate_dir) {
798 checks.push(Check {
799 fix: None,
800 name: "recording",
801 passed: false,
802 detail: why,
803 });
804 }
805
806 if let Some(line) = crate::recording::saved_coverage(crate_dir)
807 .and_then(|c| crate::recording::coverage_line(&c))
808 {
809 checks.push(Check {
810 fix: None,
811 name: "coverage",
812 passed: true,
813 detail: line,
814 });
815 }
816
817 if !crate_dir.join(CASES).exists() {
818 checks.push(Check {
819 fix: None,
820 name: "behavior",
821 passed: false,
822 detail: "no recorded cases: run `rust-anything record` first".into(),
823 });
824 } else if built_ok {
825 match harness::diff(&DiffOptions {
826 crate_dir,
827 module: None,
828 ignore_key_order: false,
829 float_tolerance: None,
830 node_args,
831 }) {
832 Ok(d) => {
833 checks.push(Check {
834 fix: None,
835 name: "api",
836 passed: d.missing.is_empty(),
837 detail: if d.missing.is_empty() {
838 format!(
839 "exports {}",
840 manifest
841 .exports
842 .iter()
843 .map(|f| f.name.clone())
844 .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
845 .collect::<Vec<_>>()
846 .join(", ")
847 )
848 } else {
849 format!("missing exports: {}", d.missing.join(", "))
850 },
851 });
852 checks.push(Check {
853 fix: None,
854 name: "behavior",
855 passed: d.failed == 0,
856 detail: if d.accepted > 0 {
857 format!(
858 "{}/{} recorded cases match ({} by {})",
859 d.passed,
860 d.total,
861 d.accepted,
862 crate::recording::KNOWN_DIFFS
863 )
864 } else {
865 format!("{}/{} recorded cases match", d.passed, d.total)
866 },
867 });
868 if !d.stale_known.is_empty() {
869 checks.push(Check {
870 fix: None,
871 name: "known diffs",
872 passed: false,
873 detail: format!(
874 "{} entr{} of {} no longer differ{}: remove {}",
875 d.stale_known.len(),
876 if d.stale_known.len() == 1 { "y" } else { "ies" },
877 crate::recording::KNOWN_DIFFS,
878 if d.stale_known.len() == 1 { "s" } else { "" },
879 d.stale_known
880 .iter()
881 .map(|e| format!(
882 "{}({})",
883 e["fn"].as_str().unwrap_or("?"),
884 e["args"]
885 ))
886 .collect::<Vec<_>>()
887 .join(", ")
888 ),
889 });
890 }
891 }
892 Err(e) => checks.push(Check {
893 fix: None,
894 name: "behavior",
895 passed: false,
896 detail: format!("{e:#}"),
897 }),
898 }
899 }
900
901 for check in checks.iter_mut().filter(|c| !c.passed && c.fix.is_none()) {
902 check.fix = fix_for(check, crate_dir);
903 }
904 let passed = checks.iter().all(|c| c.passed);
905 if passed {
906 save_tests_baseline(crate_dir)?;
907 }
908 Ok(GateOutcome { passed, checks })
909}
910
911fn lockfile_check(crate_dir: &Path) -> Option<Check> {
912 if !crate_dir.join("Cargo.lock").exists() {
913 return Some(Check {
914 fix: None,
915 name: "lockfile",
916 passed: true,
917 detail: "warning: no Cargo.lock yet; keep the one the build writes, so builds are reproducible".into(),
918 });
919 }
920 let mut cmd = Command::new("cargo");
921 cmd.args([
922 "metadata",
923 "--locked",
924 "--offline",
925 "--format-version",
926 "1",
927 "--manifest-path",
928 ])
929 .arg(crate_dir.join("Cargo.toml"));
930 let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
931 let stderr = String::from_utf8_lossy(&out.stderr);
932 let stale = !out.status.success() && stderr.contains("--locked");
933 Some(Check {
934 fix: None,
935 name: "lockfile",
936 passed: true,
937 detail: if stale {
938 "warning: Cargo.lock is out of date with Cargo.toml; keep the refreshed one the build wrote".into()
939 } else {
940 "Cargo.lock matches Cargo.toml".into()
941 },
942 })
943}
944
945fn advisories_check(crate_dir: &Path) -> Option<Check> {
946 let manifest = crate_dir.join("Cargo.toml");
947 let attempts: [(&str, Vec<std::ffi::OsString>); 2] = [
948 (
949 "cargo-deny",
950 vec![
951 "deny".into(),
952 "--manifest-path".into(),
953 manifest.clone().into(),
954 "check".into(),
955 "advisories".into(),
956 ],
957 ),
958 (
959 "cargo-audit",
960 vec![
961 "audit".into(),
962 "--file".into(),
963 crate_dir.join("Cargo.lock").into(),
964 ],
965 ),
966 ];
967 for (tool, args) in attempts {
968 if !crate::setup::on_path(tool) {
969 continue;
970 }
971 let mut cmd = Command::new("cargo");
972 cmd.args(&args);
973 let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
974 let text = format!(
975 "{}{}",
976 String::from_utf8_lossy(&out.stdout),
977 String::from_utf8_lossy(&out.stderr)
978 );
979 return Some(Check {
980 fix: None,
981 name: "advisories",
982 passed: true,
983 detail: if out.status.success() {
984 format!("no known advisories ({tool})")
985 } else {
986 format!(
987 "warning: {tool} reports advisories\n{}",
988 last_lines(&text, 15)
989 )
990 },
991 });
992 }
993 None
994}
995
996pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
999 let cargo = |args: &[&str]| -> (bool, String, Option<String>) {
1000 let mut cmd = Command::new("cargo");
1001 cmd.args(args)
1002 .arg("--manifest-path")
1003 .arg(crate_dir.join("Cargo.toml"))
1004 .env("CARGO_TARGET_DIR", target_dir);
1005 match crate::process::output(&mut cmd, crate::process::BUILD) {
1007 Ok(o) => (
1008 o.status.success(),
1009 last_lines(&String::from_utf8_lossy(&o.stderr), 15),
1010 None,
1011 ),
1012 Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
1013 }
1014 };
1015 let mut checks = Vec::new();
1016
1017 let (ok, out, fix) = cargo(&["fmt", "--check"]);
1018 checks.push(Check {
1019 name: "fmt",
1020 passed: ok,
1021 detail: if ok {
1022 "formatted".into()
1023 } else if fix.is_some() {
1024 out
1025 } else {
1026 format!("run `cargo fmt`\n{out}")
1027 },
1028 fix,
1029 });
1030
1031 let mut clippy = Command::new("cargo");
1032 clippy
1033 .args(["clippy", "--all-targets", "--manifest-path"])
1034 .arg(crate_dir.join("Cargo.toml"))
1035 .args(["--", "-D", "warnings"])
1036 .env("CARGO_TARGET_DIR", target_dir);
1037 let (ok, out, fix) = match crate::process::output(&mut clippy, crate::process::BUILD) {
1038 Ok(o) => (
1039 o.status.success(),
1040 last_lines(&String::from_utf8_lossy(&o.stderr), 15),
1041 None,
1042 ),
1043 Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
1044 };
1045 checks.push(Check {
1046 fix,
1047 name: "clippy",
1048 passed: ok,
1049 detail: if ok { "no warnings".into() } else { out },
1050 });
1051
1052 let (ok, out, fix) = cargo(&["test", "--quiet"]);
1053 checks.push(Check {
1054 fix,
1055 name: "cargo test",
1056 passed: ok,
1057 detail: if ok { "passed".into() } else { out },
1058 });
1059
1060 let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
1061 checks.push(Check {
1062 fix: None,
1063 name: "unsafe",
1064 passed: unexplained.is_empty(),
1065 detail: if unexplained.is_empty() {
1066 format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
1067 } else {
1068 format!(
1069 "unsafe without a `// SAFETY:` comment: {}",
1070 unexplained.join(", ")
1071 )
1072 },
1073 });
1074
1075 checks
1076}
1077
1078pub fn ported_check(crate_dir: &Path) -> Check {
1080 let path = crate_dir.join("src/port.rs");
1081 let port = match std::fs::read_to_string(&path) {
1082 Ok(port) => port,
1083 Err(error) => {
1084 return Check {
1085 fix: None,
1086 name: "ported",
1087 passed: false,
1088 detail: format!("cannot read {}: {error}", path.display()),
1089 };
1090 }
1091 };
1092 let todo = stubs(&port);
1093 Check {
1094 fix: None,
1095 name: "ported",
1096 passed: todo == 0,
1097 detail: if todo == 0 {
1098 "nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`".into()
1099 } else {
1100 format!(
1101 "{todo} place(s) in port.rs still `unimplemented!`, `todo!` or a function that only panics"
1102 )
1103 },
1104 }
1105}
1106
1107fn stubs(port: &str) -> usize {
1109 let code: String = port
1110 .lines()
1111 .map(|l| l.split("//").next().unwrap_or_default())
1112 .collect::<Vec<_>>()
1113 .join("\n");
1114 let macros = code.matches("unimplemented!(").count() + code.matches("todo!(").count();
1115 let panics = regex::Regex::new(r"\bfn\s+\w+[^{;]*\{\s*panic!\([^;{}]*\)\s*;?\s*\}")
1116 .map(|re| re.find_iter(&code).count())
1117 .unwrap_or(0);
1118 macros + panics
1119}
1120
1121fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
1123 let mut unexplained = Vec::new();
1124 let mut explained = 0;
1125 let mut stack = vec![src.to_path_buf()];
1126 while let Some(dir) = stack.pop() {
1127 let Ok(entries) = std::fs::read_dir(&dir) else {
1128 continue;
1129 };
1130 for entry in entries.flatten() {
1131 let path = entry.path();
1132 if path.is_dir() {
1133 stack.push(path);
1134 continue;
1135 }
1136 if path.extension().is_none_or(|e| e != "rs") {
1137 continue;
1138 }
1139 let text = std::fs::read_to_string(&path).unwrap_or_default();
1140 let lines: Vec<&str> = text.lines().collect();
1141 for (i, line) in lines.iter().enumerate() {
1142 let code = strip_code(line);
1143 let uses_unsafe = code
1144 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
1145 .any(|word| word == "unsafe");
1146 if !uses_unsafe {
1147 continue;
1148 }
1149 let has_safety = lines[..i]
1150 .iter()
1151 .rev()
1152 .take_while(|l| l.trim_start().starts_with("//"))
1153 .any(|l| l.contains("SAFETY:"));
1154 if has_safety {
1155 explained += 1;
1156 } else {
1157 unexplained.push(format!("{}:{}", path.display(), i + 1));
1158 }
1159 }
1160 }
1161 }
1162 (unexplained, explained)
1163}
1164
1165fn last_lines(text: &str, n: usize) -> String {
1166 let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
1167 lines[lines.len().saturating_sub(n)..].join("\n")
1168}
1169
1170fn strip_code(line: &str) -> String {
1173 let bytes = line.as_bytes();
1174 let mut out = String::with_capacity(line.len());
1175 let mut i = 0;
1176 while i < bytes.len() {
1177 if bytes[i..].starts_with(b"//") {
1179 break;
1180 }
1181
1182 if bytes[i..].starts_with(b"/*") {
1184 i += 2;
1185 while i < bytes.len() && !bytes[i..].starts_with(b"*/") {
1186 i += 1;
1187 }
1188 if i < bytes.len() {
1189 i += 2;
1190 }
1191 out.push(' ');
1192 continue;
1193 }
1194
1195 let prev_is_ident = i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
1197 let mut j = i;
1198 if !prev_is_ident
1199 && (bytes[j] == b'b' || bytes[j] == b'c')
1200 && j + 1 < bytes.len()
1201 && bytes[j + 1] == b'r'
1202 {
1203 j += 1;
1204 }
1205 if !prev_is_ident && bytes[j] == b'r' {
1206 let mut k = j + 1;
1207 while k < bytes.len() && bytes[k] == b'#' {
1208 k += 1;
1209 }
1210 if k < bytes.len() && bytes[k] == b'"' {
1211 let hashes = k - (j + 1);
1212 i = k + 1;
1213 while i < bytes.len() {
1214 if bytes[i] == b'"' {
1215 let rest = &bytes[i + 1..];
1216 if rest.len() >= hashes && rest[..hashes].iter().all(|&b| b == b'#') {
1217 i += 1 + hashes;
1218 break;
1219 }
1220 }
1221 i += 1;
1222 }
1223 out.push(' ');
1224 continue;
1225 }
1226 }
1227
1228 let is_byte_or_c_str = !prev_is_ident
1230 && (bytes[i] == b'b' || bytes[i] == b'c')
1231 && i + 1 < bytes.len()
1232 && bytes[i + 1] == b'"';
1233 if bytes[i] == b'"' || is_byte_or_c_str {
1234 if is_byte_or_c_str {
1235 i += 1;
1236 }
1237 i += 1; while i < bytes.len() {
1239 if bytes[i] == b'\\' {
1240 i += if i + 1 < bytes.len() { 2 } else { 1 };
1241 } else if bytes[i] == b'"' {
1242 i += 1;
1243 break;
1244 } else {
1245 i += 1;
1246 }
1247 }
1248 out.push(' ');
1249 continue;
1250 }
1251
1252 let is_byte_char =
1254 !prev_is_ident && bytes[i] == b'b' && i + 1 < bytes.len() && bytes[i + 1] == b'\'';
1255 if bytes[i] == b'\'' || is_byte_char {
1256 let quote_pos = if is_byte_char { i + 1 } else { i };
1257 let rest = &line[quote_pos + 1..];
1258 if let Some(close_rel) = rest.find('\'')
1259 && close_rel <= 8
1260 && !rest[..close_rel].contains(' ')
1261 {
1262 i = quote_pos + 1 + close_rel + 1;
1263 out.push(' ');
1264 continue;
1265 }
1266 }
1267
1268 out.push(bytes[i] as char);
1269 i += 1;
1270 }
1271 out
1272}
1273
1274#[cfg(test)]
1275mod tests {
1276 use super::{CASES, Check, fix_for, spawn_fix, stubs, unsafe_blocks};
1277
1278 #[test]
1279 fn counts_every_kind_of_stub() {
1280 let port = "pub fn a() -> u8 { todo!() }\n\
1281 pub fn b() -> u8 { unimplemented!(\"later\") }\n\
1282 pub fn c(x: u8) -> u8 {\n panic!(\"not ported\")\n}\n\
1283 pub fn d(x: u8) -> u8 { if x > 1 { panic!(\"big\") } x }\n\
1284 // todo!() in a comment\n";
1285 assert_eq!(stubs(port), 3);
1286 assert_eq!(stubs("pub fn ok() -> u8 { 1 }"), 0);
1287 }
1288
1289 #[test]
1290 fn failed_checks_say_what_to_run() {
1291 let check = |name, detail: &str| Check {
1292 fix: None,
1293 name,
1294 passed: false,
1295 detail: detail.into(),
1296 };
1297 let dir = std::path::Path::new("port");
1298 assert_eq!(
1299 fix_for(&check("recording", "changed"), dir).as_deref(),
1300 Some("rust-anything record port")
1301 );
1302 assert_eq!(
1303 fix_for(&check("behavior", "no recorded cases: run"), dir).as_deref(),
1304 Some("rust-anything record port")
1305 );
1306 assert!(fix_for(&check("fmt", ""), dir).is_some_and(|f| f.starts_with("cargo fmt")));
1307 assert_eq!(fix_for(&check("coverage", ""), dir), None);
1308
1309 let mut missing_cmd = std::process::Command::new("cargo");
1310 missing_cmd.env_remove("PATH");
1311 let missing_err = crate::process::spawn_error(
1312 &missing_cmd,
1313 "cargo build",
1314 std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
1315 );
1316 let missing_fix = spawn_fix(&missing_err).unwrap();
1317 assert!(
1318 !missing_fix.contains("fix the compile error above"),
1319 "{missing_fix}"
1320 );
1321 assert!(missing_fix.contains("cargo"), "{missing_fix}");
1322 assert!(
1323 missing_fix.contains("rust-anything doctor"),
1324 "{missing_fix}"
1325 );
1326 assert!(!missing_fix.contains('\n'), "{missing_fix}");
1327
1328 let denied_err = crate::process::spawn_error(
1329 &std::process::Command::new("cargo"),
1330 "cargo build",
1331 std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
1332 );
1333 let spawn_hint = spawn_fix(&denied_err).unwrap();
1334 assert!(
1335 !spawn_hint.contains("fix the compile error above"),
1336 "{spawn_hint}"
1337 );
1338 assert!(spawn_hint.contains("rust-anything doctor"), "{spawn_hint}");
1339
1340 let compile_err =
1341 anyhow::anyhow!("cargo build failed (exit status: 101)\n\"not found on PATH\"");
1342 assert!(spawn_fix(&compile_err).is_none());
1343 let compile_fix = fix_for(&check("build", &compile_err.to_string()), dir).unwrap();
1344 assert!(
1345 compile_fix.starts_with("fix the compile error above"),
1346 "{compile_fix}"
1347 );
1348 }
1349
1350 #[test]
1351 fn requires_safety_comments() {
1352 let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
1353 std::fs::create_dir_all(&dir).unwrap();
1354 std::fs::write(
1355 dir.join("a.rs"),
1356 "#![forbid(unsafe_code)]\n\
1357 // SAFETY: checked above\n\
1358 unsafe { x() }\n\
1359 let y = unsafe { z() };\n\
1360 // unsafe in a comment\n\
1361 let _err = Err(\"RangeError: unsafe input\".into());\n\
1362 let _raw = r#\"unsafe \"quoted\" string\"#;\n\
1363 let _with_real = \"a string with unsafe\"; unsafe { real_work() };\n",
1364 )
1365 .unwrap();
1366 let (unexplained, explained) = unsafe_blocks(&dir);
1367 std::fs::remove_dir_all(&dir).unwrap();
1368 assert_eq!(explained, 1);
1369 assert_eq!(unexplained.len(), 2);
1370 assert!(unexplained[0].ends_with("a.rs:4"), "{}", unexplained[0]);
1371 assert!(unexplained[1].ends_with("a.rs:8"), "{}", unexplained[1]);
1372 }
1373
1374 #[test]
1375 fn strip_code_removes_strings_chars_and_comments() {
1376 assert_eq!(super::strip_code("// unsafe comment").trim(), "");
1377 assert_eq!(
1378 super::strip_code("let s = \"unsafe inside string\";"),
1379 "let s = ;"
1380 );
1381 assert_eq!(
1382 super::strip_code("let s = r#\"unsafe in raw\"#;"),
1383 "let s = ;"
1384 );
1385 assert_eq!(
1386 super::strip_code("let s = \"unsafe\"; unsafe { }"),
1387 "let s = ; unsafe { }"
1388 );
1389 assert_eq!(
1390 super::strip_code("let s = \"http://example.com\"; unsafe { }"),
1391 "let s = ; unsafe { }"
1392 );
1393 }
1394
1395 #[test]
1396 fn missing_port_source_fails_the_ported_check() {
1397 let dir = crate::app::temp_dir("gate-port").unwrap();
1398 let check = super::ported_check(&dir);
1399 std::fs::remove_dir(dir).unwrap();
1400 assert!(!check.passed);
1401 assert!(check.detail.contains("cannot read"));
1402 assert!(check.detail.contains("port.rs"));
1403 }
1404
1405 #[test]
1406 fn scan_finds_literals_outside_comments_and_tests() {
1407 let port = "// \"a comment string\" 123456\n\
1408 /* 987654 /* nested */ \"no\" */\n\
1409 pub fn f(x: &str) -> u64 { if x == \"tab\\there\\u{e9}\" { 1_234_567u64 } else { 0x123456 } }\n\
1410 pub fn g<'a>(c: char) -> &'a str { if c == '\"' { r#\"say \"hi\" now\"# } else { b\"bytes!!!\"; \"x\" } }\n\
1411 pub fn h() -> f64 { 3.14159e-2 + (0..100000).count() as f64 } // recorded-literal: pi\n\
1412 pub fn i() -> f64 { t.0 + 2.5f32 as f64 }\n\
1413 #[cfg(test)]\nmod tests { const X: &str = \"only in tests\"; }\n";
1414 let scan = super::scan_rust(port, true);
1415 let strings: Vec<(usize, &str)> =
1416 scan.strings.iter().map(|(l, s)| (*l, s.as_str())).collect();
1417 assert_eq!(
1418 strings,
1419 [
1420 (3, "tab\there\u{e9}"),
1421 (4, "say \"hi\" now"),
1422 (4, "bytes!!!"),
1423 (4, "x")
1424 ]
1425 );
1426 let numbers: Vec<(usize, &str)> =
1427 scan.numbers.iter().map(|(l, n)| (*l, n.as_str())).collect();
1428 assert_eq!(
1429 numbers,
1430 [
1431 (3, "1234567"),
1432 (5, "3.14159e-2"),
1433 (5, "0"),
1434 (5, "100000"),
1435 (6, "2.5")
1436 ]
1437 );
1438 assert!(scan.marked.contains(&5) && scan.marked.len() == 1);
1439 assert!(!scan.code.contains("comment") && !scan.code.contains("only in tests"));
1440 let all = super::scan_rust(port, false);
1441 assert_eq!(all.strings.last().unwrap().1, "only in tests");
1442 }
1443
1444 #[test]
1445 fn common_numbers_are_never_suspicious() {
1446 use super::{significant_digits, well_known};
1447 assert_eq!(significant_digits("1234500"), 5);
1448 assert_eq!(significant_digits("0.00012345"), 5);
1449 assert_eq!(significant_digits("1.25e10"), 3);
1450 for n in [
1451 "65536",
1452 "65535",
1453 "4294967295",
1454 "2147483647",
1455 "9007199254740991",
1456 "18446744073709551615",
1457 "1000000",
1458 "1.7976931348623157e308",
1459 "3.4028235e38",
1460 "2.220446049250313e-16",
1461 ] {
1462 assert!(well_known(n), "{n}");
1463 }
1464 for n in ["12345", "4294967299", "3.14159", "99999"] {
1465 assert!(!well_known(n), "{n}");
1466 }
1467 }
1468
1469 #[test]
1470 fn literals_fail_from_three_recorded_values_the_original_does_not_spell() {
1471 let dir = crate::app::temp_dir("gate-literals").unwrap();
1472 std::fs::create_dir_all(dir.join("src")).unwrap();
1473 std::fs::write(
1474 dir.join("lib.ts"),
1475 "export const greet = (n: string) => `hello there, ${n}` + \"spelled out\" + 31337\n",
1476 )
1477 .unwrap();
1478 std::fs::write(
1479 dir.join(CASES),
1480 "{\"fn\":\"greet\",\"args\":[\"somebody else\"],\"ok\":\"hello there, somebody else\"}\n\
1481 {\"fn\":\"greet\",\"args\":[\"x\"],\"ok\":[\"spelled out\",\"second answer\",31337,271828,\"third answer\"]}\n",
1482 )
1483 .unwrap();
1484 let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
1485 "schema": crate::bridge::SCHEMA,
1486 "root": dir,
1487 "unit": "lib.ts",
1488 "crate_name": "demo",
1489 "kind": "napi",
1490 "exports": [],
1491 }))
1492 .unwrap();
1493 let check = |port: &str| {
1494 std::fs::write(dir.join("src/port.rs"), port).unwrap();
1495 super::literals_check(&dir, &manifest).unwrap()
1496 };
1497 let honest = check(
1498 "pub fn greet(n: &str) -> String { format!(\"hello there, {n}\") + \"spelled out\" }\n",
1499 );
1500 assert!(honest.passed, "{honest:?}");
1501 assert_eq!(honest.detail, "no recorded values written into the port");
1502
1503 let two = check(
1504 "pub fn greet(n: &str) -> String {\n if n == \"somebody else\" { return \"second answer\".into() }\n String::new()\n}\n",
1505 );
1506 assert!(two.passed, "{two:?}");
1507 assert!(
1508 two.detail.starts_with("2 recorded values"),
1509 "{}",
1510 two.detail
1511 );
1512 assert!(
1513 two.detail.contains("\"somebody else\" (src/port.rs:2)"),
1514 "{}",
1515 two.detail
1516 );
1517
1518 let three = check(
1519 "pub fn greet(n: &str) -> String {\n if n == \"somebody else\" { return \"second answer\".into() }\n let _ = 271_828;\n String::new()\n}\n",
1520 );
1521 assert!(!three.passed, "{three:?}");
1522 assert!(
1523 three.detail.contains("271828 (src/port.rs:3)"),
1524 "{}",
1525 three.detail
1526 );
1527
1528 let marked = check(
1529 "pub fn greet(n: &str) -> String {\n if n == \"somebody else\" { return \"second answer\".into() }\n let _ = 271_828; // recorded-literal: e from a table\n String::new()\n}\n",
1530 );
1531 assert!(marked.passed, "{marked:?}");
1532
1533 let reads = check("const C: &str = include_str!(\"../cases.jsonl\");\n");
1534 assert!(!reads.passed, "{reads:?}");
1535 assert!(reads.detail.contains("src/port.rs:1"), "{}", reads.detail);
1536 std::fs::remove_dir_all(dir).unwrap();
1537 }
1538
1539 #[test]
1540 fn size_check_says_1_line_for_singular_source() {
1541 let dir = crate::app::temp_dir("gate-size").unwrap();
1542 let src_dir = dir.join("src");
1543 std::fs::create_dir_all(&src_dir).unwrap();
1544 std::fs::write(src_dir.join("add.ts"), "export const add = 1;\n").unwrap();
1545 std::fs::write(src_dir.join("port.rs"), "pub fn add() -> i32 { 1 }\n").unwrap();
1546 let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
1547 "schema": crate::bridge::SCHEMA,
1548 "root": dir,
1549 "unit": "src",
1550 "crate_name": "demo",
1551 "kind": "napi",
1552 "exports": [],
1553 }))
1554 .unwrap();
1555 let check = super::size_check(&dir, &manifest).unwrap();
1556 std::fs::remove_dir_all(dir).unwrap();
1557 assert!(
1558 check
1559 .detail
1560 .contains("1 line of Rust for 1 line of TypeScript/JavaScript"),
1561 "{}",
1562 check.detail
1563 );
1564 }
1565}