1use std::collections::{BTreeMap, HashSet};
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15use anyhow::{Context, Result, bail};
16use serde_json::Value;
17
18use crate::bridge::Manifest;
19use crate::lang::Lang;
20use crate::walk::Canonical;
21
22const PER_FUNCTION: usize = 1000;
24pub const TEST_INPUTS: &str = "test-inputs.jsonl";
25const BACKUP: &str = ".rust-anything-backup";
26
27#[derive(Debug)]
28pub struct Capture {
29 pub inputs: PathBuf,
32 pub per_function: BTreeMap<String, usize>,
33 pub skipped: Vec<String>,
35 pub tests_passed: bool,
36}
37
38pub fn capture(crate_dir: &Path, command: &[String]) -> Result<Capture> {
39 let m = Manifest::load(crate_dir)?;
40 let Some((program, args)) = command.split_first() else {
41 bail!("--from-tests needs the test command after `--`, e.g. `-- npx jest`");
42 };
43 let raw = std::path::absolute(crate_dir.join("test-calls.raw.jsonl"))?;
44 let _ = std::fs::remove_file(&raw);
45 let mut cmd = Command::new(program);
46 cmd.args(args)
47 .current_dir(&m.root)
48 .stdout(std::io::stderr())
49 .env("RUST_ANYTHING_CAPTURE", &raw)
50 .env("CI", "1");
51 let mut skipped = Vec::new();
52 let status = match m.language {
53 Lang::Ts => {
54 let guard = instrument_js(&m, &mut skipped)?;
55 let status = crate::process::status(&mut cmd, crate::process::TESTS);
56 drop(guard);
57 status
58 }
59 Lang::Python => {
60 let hook = crate_dir.join("target").join("from-tests");
61 std::fs::create_dir_all(&hook)?;
62 std::fs::write(hook.join("sitecustomize.py"), python_hook())?;
63 let mut want: BTreeMap<String, Vec<String>> = BTreeMap::new();
64 for f in &m.exports {
65 let path = m.root.join(&f.file).canonical()?;
66 want.entry(path.to_string_lossy().into_owned())
67 .or_default()
68 .push(f.name.clone());
69 }
70 let path = std::env::join_paths(
71 std::iter::once(std::path::absolute(&hook)?).chain(
72 std::env::var_os("PYTHONPATH")
73 .map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
74 .unwrap_or_default(),
75 ),
76 )?;
77 cmd.env("PYTHONPATH", path)
78 .env("RUST_ANYTHING_CAPTURE_FUNCS", serde_json::to_string(&want)?)
79 .env("PYTHONDONTWRITEBYTECODE", "1");
80 crate::process::status(&mut cmd, crate::process::TESTS)
81 }
82 other => bail!(
83 "--from-tests captures TS/JS and Python test suites; this unit is {}",
84 other.name()
85 ),
86 }
87 .with_context(|| format!("running `{}`", command.join(" ")))?;
88
89 let text = std::fs::read_to_string(&raw).unwrap_or_default();
90 let _ = std::fs::remove_file(&raw);
91 let exported: HashSet<&str> = m.exports.iter().map(|f| f.name.as_str()).collect();
92 let mut seen = HashSet::new();
93 let mut per_function: BTreeMap<String, usize> = BTreeMap::new();
94 let mut out = String::new();
95 for line in text.lines() {
96 let Ok(call) = serde_json::from_str::<Value>(line) else {
97 continue;
98 };
99 let Some(name) = call["fn"].as_str() else {
100 continue;
101 };
102 if !exported.contains(name) || !call["args"].is_array() || !seen.insert(line.to_string()) {
103 continue;
104 }
105 let n = per_function.entry(name.to_string()).or_default();
106 if *n >= PER_FUNCTION {
107 continue;
108 }
109 *n += 1;
110 out.push_str(line);
111 out.push('\n');
112 }
113 let inputs = crate_dir.join(TEST_INPUTS);
114 std::fs::write(&inputs, out).with_context(|| format!("writing {}", inputs.display()))?;
115 Ok(Capture {
116 inputs,
117 per_function,
118 skipped,
119 tests_passed: status.success(),
120 })
121}
122
123pub fn with_own_inputs(crate_dir: &Path, own: Option<&Path>, captured: &Path) -> Result<PathBuf> {
125 let Some(own) = own else {
126 return Ok(captured.to_path_buf());
127 };
128 let mut text =
129 std::fs::read_to_string(own).with_context(|| format!("reading {}", own.display()))?;
130 if !text.is_empty() && !text.ends_with('\n') {
131 text.push('\n');
132 }
133 text += &std::fs::read_to_string(captured)?;
134 let combined = crate_dir.join("target").join("record-inputs.jsonl");
135 std::fs::create_dir_all(crate_dir.join("target"))?;
136 std::fs::write(&combined, text)?;
137 Ok(combined)
138}
139
140struct Restore(Vec<PathBuf>);
142
143impl Drop for Restore {
144 fn drop(&mut self) {
145 for file in &self.0 {
146 restore(file);
147 }
148 }
149}
150
151fn backup_of(file: &Path) -> PathBuf {
152 let mut name = file.as_os_str().to_owned();
153 name.push(BACKUP);
154 PathBuf::from(name)
155}
156
157fn restore(file: &Path) {
158 let backup = backup_of(file);
159 if std::fs::copy(&backup, file).is_ok() {
160 let _ = std::fs::remove_file(backup);
161 }
162}
163
164fn instrument_js(m: &Manifest, skipped: &mut Vec<String>) -> Result<Restore> {
165 let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
166 for f in &m.exports {
167 by_file.entry(&f.file).or_default().push(&f.name);
168 }
169 let mut guard = Restore(Vec::new());
170 let capture = JS_CAPTURE.replace("__CODEC__", &js_codec());
171 for (file, names) in by_file {
172 let path = m.root.join(file);
173 restore(&path);
174 let text = std::fs::read_to_string(&path)
175 .with_context(|| format!("reading {}", path.display()))?;
176 let wrappable: Vec<&str> = names
177 .into_iter()
178 .filter(|name| {
179 let declared = regex::Regex::new(&format!(
180 r"\bfunction\s*\*?\s*{}\s*[<(]",
181 regex::escape(name)
182 ))
183 .is_ok_and(|re| re.is_match(&text));
184 if !declared {
185 skipped.push(format!(
186 "{name} ({file}): not a function declaration, so its binding cannot be wrapped"
187 ));
188 }
189 declared
190 })
191 .collect();
192 if wrappable.is_empty() {
193 continue;
194 }
195 std::fs::copy(&path, backup_of(&path))
196 .with_context(|| format!("backing up {}", path.display()))?;
197 guard.0.push(path.clone());
198 let ts = file.ends_with(".ts") || file.ends_with(".tsx") || file.ends_with(".mts");
199 let wraps: String = wrappable
200 .iter()
201 .map(|n| format!(" {n} = __raWrap('{n}', {n})\n"))
202 .collect();
203 let instrumented = format!(
204 "{}{text}\n{}",
205 if ts { "// @ts-nocheck\n" } else { "" },
206 capture.replace("__WRAPS__", &wraps)
207 );
208 std::fs::write(&path, instrumented)
209 .with_context(|| format!("instrumenting {}", path.display()))?;
210 }
211 Ok(guard)
212}
213
214const JS_CAPTURE: &str = r#"// rust-anything record --from-tests: removed when the tests finish.
215/* c8 ignore start */
216/* istanbul ignore next */
217{
218 const __raFs = globalThis.process?.getBuiltinModule?.('node:fs')
219 const __raOut = globalThis.process?.env?.RUST_ANYTHING_CAPTURE
220 const __raCount = new globalThis.Map()
221 // The built-in name of a typed array, which a subclass cannot change.
222 const __raTypedName = globalThis.Object.getOwnPropertyDescriptor(globalThis.Object.getPrototypeOf(globalThis.Uint8Array.prototype), globalThis.Symbol.toStringTag).get
223__CODEC__
224 const __raWrap = (name, orig) => {
225 if (!__raFs || !__raOut || typeof orig !== 'function') return orig
226 const wrapped = function (...args) {
227 const n = __raCount.get(name) ?? 0
228 if (n < 5000) {
229 __raCount.set(name, n + 1)
230 try { __raFs.appendFileSync(__raOut, globalThis.JSON.stringify({ fn: name, args: globalThis.Array.from(args, a => __raEnc(a)) }) + '\n') } catch {}
231 }
232 return new.target ? globalThis.Reflect.construct(orig, args, new.target) : orig.apply(this, args)
233 }
234 if (typeof exports === 'object' && exports !== null) {
235 for (const key of [name, 'default']) if (exports[key] === orig) exports[key] = wrapped
236 }
237 return wrapped
238 }
239__WRAPS__}
240/* c8 ignore stop */
241"#;
242
243const JS_CAPTURE_ENC: &[(&str, &str)] = &[
251 ("return { $function: v.name }", NOT_DATA),
252 ("return { $symbol: String(v.description) }", NOT_DATA),
253 ("return { $cycle: true }", NOT_DATA),
254 ("return { $regexp: String(v) }", NOT_DATA),
255 ("return { $error: v.message }", NOT_DATA),
256 (
257 "if (Array.isArray(v)) return v.map(x => enc(x, next))",
258 "if (Array.isArray(v)) return Array.from(v, x => enc(x, next))",
259 ),
260 ("kind: v.constructor.name,", "kind: __raTypedName.call(v),"),
261 (
262 "const plain = Object.fromEntries(",
263 "if (Object.prototype.toString.call(v) !== '[object Object]' || typeof v.toJSON === 'function') throw new Error('not data')\n const plain = Object.fromEntries(",
264 ),
265];
266
267const NOT_DATA: &str = "throw new Error('not data')";
268
269fn js_codec() -> String {
275 let codec = crate::harness::CODEC_JS;
276 let end = codec.find("\nconst dec = ").unwrap_or(codec.len());
277 let enc = JS_CAPTURE_ENC
278 .iter()
279 .fold(codec[..end].to_string(), |enc, (from, to)| {
280 enc.replace(from, to)
281 });
282 js_names()
283 .replace_all(&enc, |c: ®ex::Captures| {
284 match c.get(1).map(|m| m.as_str()) {
285 None => c[0].to_string(),
286 Some("enc") => "__raEnc".to_string(),
287 Some("MARKERS") => "__raMarkers".to_string(),
288 Some("looksLikeMarker") => "__raLooksLikeMarker".to_string(),
289 Some(global) => format!("globalThis.{global}"),
290 }
291 })
292 .into_owned()
293}
294
295const JS_GLOBALS: &str =
297 "Array|ArrayBuffer|Buffer|DataView|Date|Error|Map|Number|Object|RegExp|Set|String|Uint8Array";
298
299fn js_names() -> regex::Regex {
302 regex::Regex::new(&format!(
303 r"'[^']*'|//[^\n]*|\b(enc|MARKERS|looksLikeMarker|{JS_GLOBALS})\b"
304 ))
305 .expect("valid regex")
306}
307
308fn python_hook() -> String {
309 let driver = crate::harness_py::DRIVER_PY;
310 let enc = driver
311 .find("def enc(")
312 .and_then(|start| {
313 driver[start..]
314 .find("\ndef dec(")
315 .map(|end| &driver[start..start + end])
316 })
317 .unwrap_or("def enc(v, stack=()):\n return v\n");
318 format!("{PY_HOOK_HEAD}\n{enc}\n{PY_HOOK_TAIL}")
319}
320
321const PY_HOOK_HEAD: &str = r#"# rust-anything record --from-tests: wraps the unit's functions when their module loads.
322import functools
323import importlib.abc
324import importlib.machinery
325import inspect
326import json
327import math
328import os
329import sys
330
331BIG = 2 ** 53
332"#;
333
334const PY_HOOK_TAIL: &str = r#"
335_OUT = os.environ.get("RUST_ANYTHING_CAPTURE")
336_WANT = json.loads(os.environ.get("RUST_ANYTHING_CAPTURE_FUNCS") or "{}")
337_COUNT = {}
338
339
340def _wrap(name, orig):
341 try:
342 sig = inspect.signature(orig)
343 except (TypeError, ValueError):
344 sig = None
345
346 @functools.wraps(orig)
347 def wrapped(*args, **kwargs):
348 n = _COUNT.get(name, 0)
349 if n < 5000 and sig is not None:
350 try:
351 bound = sig.bind(*args, **kwargs)
352 case = {"fn": name, "args": enc(list(bound.args))}
353 # Keyword-only arguments, and those named after a skipped default.
354 if bound.kwargs:
355 case["kwargs"] = {k: enc(v) for k, v in bound.kwargs.items()}
356 line = json.dumps(case, ensure_ascii=False, allow_nan=False)
357 with open(_OUT, "a", encoding="utf-8") as f:
358 f.write(line + "\n")
359 _COUNT[name] = n + 1
360 except Exception:
361 pass
362 return orig(*args, **kwargs)
363
364 return wrapped
365
366
367class _Loader(importlib.abc.Loader):
368 def __init__(self, inner, names):
369 self.inner = inner
370 self.names = names
371
372 def create_module(self, spec):
373 return self.inner.create_module(spec)
374
375 def exec_module(self, module):
376 self.inner.exec_module(module)
377 for name in self.names:
378 orig = getattr(module, name, None)
379 if callable(orig):
380 setattr(module, name, _wrap(name, orig))
381
382
383class _Finder(importlib.abc.MetaPathFinder):
384 def find_spec(self, fullname, path, target=None):
385 spec = importlib.machinery.PathFinder.find_spec(fullname, path)
386 if spec is None or spec.origin is None or spec.loader is None:
387 return None
388 names = _WANT.get(os.path.realpath(spec.origin))
389 if not names:
390 return None
391 spec.loader = _Loader(spec.loader, names)
392 return spec
393
394
395if _OUT and _WANT:
396 sys.meta_path.insert(0, _Finder())
397"#;
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
405 fn the_capture_codec_is_the_record_codec_with_its_changes() {
406 let codec = crate::harness::CODEC_JS;
407 let end = codec.find("\nconst dec = ").expect("CODEC_JS defines dec");
408 for (from, _) in JS_CAPTURE_ENC {
409 let found = codec[..end].matches(from).count();
410 assert_eq!(found, 1, "enc no longer has {from:?}");
411 }
412 let capture = js_codec();
413 for marker in ["$function", "$symbol", "$cycle", "$regexp", "$error"] {
414 assert!(!capture.contains(marker), "{marker} is written:\n{capture}");
415 }
416 let declared: Vec<&str> = capture
418 .lines()
419 .filter_map(|l| l.strip_prefix("const "))
420 .filter_map(|l| l.split([' ', '=']).next())
421 .collect();
422 let prefixed = ["__raEnc", "__raMarkers", "__raLooksLikeMarker"];
423 assert_eq!(declared, prefixed, "{capture}");
424 let globals = regex::Regex::new(&format!(
426 r"'[^']*'|//[^\n]*|(globalThis\.)?\b(enc|{JS_GLOBALS})\b"
427 ))
428 .unwrap();
429 for c in globals.captures_iter(&capture) {
430 let bare = c.get(2).is_some() && c.get(1).is_none();
431 assert!(!bare, "bare {}:\n{capture}", &c[0]);
432 }
433 assert!(capture.contains("'[object Object]'"), "{capture}");
434 }
435}