Skip to main content

rust_anything/
shadow.rs

1//! Step 4: a drop-in module that runs the TS original and the Rust port side by side.
2//!
3//! Import the generated module where the app imported the original. Every call returns the
4//! original's result; the Rust result is compared and mismatches are reported. Once production
5//! traffic shows no mismatches, `RUST_ANYTHING_MODE=new` switches to Rust, still without a code change.
6
7use crate::walk::Canonical;
8use std::path::{Component, Path, PathBuf};
9
10use anyhow::{Context, Result, bail};
11use serde::Serialize;
12
13use crate::bridge::Manifest;
14use crate::harness::CODEC_JS;
15
16#[derive(Debug, Serialize)]
17pub struct ShadowOutcome {
18    pub path: PathBuf,
19    pub exports: Vec<String>,
20}
21
22pub fn shadow(crate_dir: &Path, out: Option<&Path>) -> Result<ShadowOutcome> {
23    let crate_dir = crate_dir
24        .canonical()
25        .with_context(|| format!("resolving {}", crate_dir.display()))?;
26    let manifest = Manifest::load(&crate_dir)?;
27    if manifest.language == crate::lang::Lang::Python {
28        return shadow_python(&crate_dir, &manifest, out);
29    }
30    if manifest.kind == crate::bridge::Kind::CAbi {
31        return shadow_c(&crate_dir, &manifest, out);
32    }
33    if matches!(
34        manifest.language,
35        crate::lang::Lang::Java | crate::lang::Lang::Kotlin
36    ) {
37        let dir = out.map_or_else(|| crate_dir.join("java"), Path::to_path_buf);
38        let port = std::fs::read_to_string(crate_dir.join("src/port.rs")).unwrap_or_default();
39        let mut api = crate::codegen::parse_port(&port);
40        crate::bridge::match_export_names(&manifest, &mut api);
41        let files = crate::codegen_java::shadows(&manifest, &api);
42        for (path, _) in &files {
43            let target = dir.join(path.trim_start_matches("shadow/"));
44            if target.exists() {
45                bail!("{} exists; remove it first or pass --out", target.display());
46            }
47        }
48        let mut first = None;
49        for (path, text) in &files {
50            let target = dir.join(path.trim_start_matches("shadow/"));
51            std::fs::create_dir_all(target.parent().context("no folder")?)?;
52            std::fs::write(&target, with_kill_switch(text, &manifest.crate_name))?;
53            first.get_or_insert(target);
54        }
55        return Ok(ShadowOutcome {
56            path: first.context("no class to shadow")?,
57            exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
58        });
59    }
60    if manifest.language == crate::lang::Lang::Php {
61        bail!(
62            "PHP cannot redefine a function once the original is loaded, so there is no shadow \
63             module for PHP yet; once `diff` passes, require {} in place of the original files",
64            crate_dir
65                .join(crate::codegen_php::wrapper_path(&manifest))
66                .display()
67        );
68    }
69    if manifest.language == crate::lang::Lang::Csharp {
70        bail!(
71            "C# binds calls when it compiles, so there is no shadow module for C# yet; once `diff` \
72             passes, compile {} into the project and call the `<namespace>.Rust` classes (or alias \
73             them with `using`), with the built library next to the app",
74            crate_dir
75                .join(crate::codegen_csharp::wrapper_path(&manifest))
76                .display()
77        );
78    }
79    if manifest.language == crate::lang::Lang::Ruby {
80        let path = match out {
81            Some(p) => p.to_path_buf(),
82            None => crate_dir
83                .join("ruby")
84                .join(format!("{}_shadow.rb", manifest.lib_name())),
85        };
86        if path.exists() {
87            bail!("{} exists; remove it first or pass --out", path.display());
88        }
89        std::fs::create_dir_all(path.parent().context("output path has no folder")?)?;
90        std::fs::write(
91            &path,
92            with_kill_switch(
93                &crate::codegen_ruby::shadow(&manifest),
94                &manifest.crate_name,
95            ),
96        )?;
97        return Ok(ShadowOutcome {
98            path,
99            exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
100        });
101    }
102    if manifest.language == crate::lang::Lang::Go {
103        let pkg = crate::codegen_go::package_name(&manifest);
104        let path = match out {
105            Some(p) => p.to_path_buf(),
106            None => crate_dir
107                .join("go")
108                .join("shadow")
109                .join(format!("{pkg}.go")),
110        };
111        if path.exists() {
112            bail!("{} exists; remove it first or pass --out", path.display());
113        }
114        std::fs::create_dir_all(path.parent().context("output path has no folder")?)?;
115        let original = crate::harness_go::import_path(&manifest)?;
116        std::fs::write(
117            &path,
118            with_kill_switch(
119                &crate::codegen_go::shadow(&manifest, &original),
120                &manifest.crate_name,
121            ),
122        )?;
123        let _ = crate::process::output(
124            std::process::Command::new("gofmt").arg("-w").arg(&path),
125            crate::process::QUICK,
126        );
127        return Ok(ShadowOutcome {
128            path,
129            exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
130        });
131    }
132    let mut files: Vec<&str> = manifest
133        .exports
134        .iter()
135        .map(|f| f.file.as_str())
136        .chain(manifest.js_only.iter().map(|j| j.file.as_str()))
137        .chain(manifest.classes.iter().map(|c| c.file.as_str()))
138        .collect();
139    files.sort_unstable();
140    files.dedup();
141    let stem = manifest.crate_name.trim_end_matches("-rs");
142    let path = match out {
143        Some(p) => p.to_path_buf(),
144        None => crate_dir.join("shadow").join(format!("{stem}.shadow.ts")),
145    };
146    if path.exists() {
147        bail!("{} exists; remove it first or pass --out", path.display());
148    }
149    let dir = path.parent().context("output path has no folder")?;
150    std::fs::create_dir_all(dir)?;
151    let dir = dir.canonical()?;
152
153    let mut code = String::from(
154        "// Generated by rust-anything: runs the TS original and the Rust port side by side.\n\
155         // RUST_ANYTHING_MODE=old: original only. shadow (default): original result, Rust compared.\n\
156         // new: Rust only. Report mismatches with `onMismatch`; counts are in `shadowStats`.\n\
157         /* eslint-disable */\n\
158         import { createRequire } from 'node:module'\n",
159    );
160    for (i, file) in files.iter().enumerate() {
161        code.push_str(&format!(
162            "import * as legacy{i} from '{}'\n",
163            relative(&dir, &manifest.root.join(file))
164        ));
165    }
166    code.push_str(&format!(
167        "\ntype Mode = 'old' | 'shadow' | 'new'\n\
168         export interface Mismatch {{ fn: string, args: unknown[], expected: unknown, actual: unknown }}\n\
169         const mode: Mode = ((globalThis as any).process?.env?.RUST_ANYTHING_MODE ?? 'shadow') as Mode\n\
170         let native: any = null\n\
171         if (mode !== 'old') {{\n\
172         \x20 try {{\n\
173         \x20   native = createRequire(import.meta.url)('{native}')\n\
174         \x20 }}\n\
175         \x20 catch (error) {{\n\
176         \x20   if (mode === 'new') throw error\n\
177         \x20   console.warn('[rust-anything] Rust module not loaded, running the original only:', (error as Error).message)\n\
178         \x20 }}\n\
179         }}\n\
180         export const shadowStats = {{ calls: 0, mismatches: 0 }}\n\
181         let report = (m: Mismatch): void => {{\n\
182         \x20 if (shadowStats.mismatches <= 10) console.warn('[rust-anything] mismatch in', m.fn, JSON.stringify(enc(m.args)), 'expected', JSON.stringify(m.expected), 'got', JSON.stringify(m.actual))\n\
183         }}\n\
184         /** Replace the default reporter (console.warn for the first 10 mismatches). */\n\
185         export function onMismatch(handler: (m: Mismatch) => void): void {{\n\
186         \x20 report = handler\n\
187         }}\n\
188         {codec}\n\
189         function compare(name: string, args: unknown[], expected: unknown, actual: unknown): void {{\n\
190         \x20 const want = {{ ok: enc(expected) }}\n\
191         \x20 if (!same(want, actual)) {{\n\
192         \x20   shadowStats.mismatches++\n\
193         \x20   report({{ fn: name, args, expected: want, actual }})\n\
194         \x20 }}\n\
195         }}\n\
196         function check(name: string, args: unknown[], expected: unknown, run: () => unknown): void {{\n\
197         \x20 shadowStats.calls++\n\
198         \x20 let result: unknown\n\
199         \x20 try {{\n\
200         \x20   result = run()\n\
201         \x20 }}\n\
202         \x20 catch (error) {{\n\
203         \x20   return compare(name, args, expected, {{ error: String((error as Error)?.message ?? error) }})\n\
204         \x20 }}\n\
205         \x20 // An async port: compare when it settles; callers never wait for Rust.\n\
206         \x20 if (result && typeof (result as any).then === 'function') {{\n\
207         \x20   (result as Promise<unknown>).then(\n\
208         \x20     value => compare(name, args, expected, {{ ok: enc(value) }}),\n\
209         \x20     error => compare(name, args, expected, {{ error: String(error?.message ?? error) }}),\n\
210         \x20   )\n\
211         \x20   return\n\
212         \x20 }}\n\
213         \x20 compare(name, args, expected, {{ ok: enc(result) }})\n\
214         }}\n\
215         function call(name: string, legacy: any, args: unknown[]): any {{\n\
216         \x20 if (mode === 'old' || !native) return legacy(...args)\n\
217         \x20 if (mode === 'new') return native[name](...args)\n\
218         \x20 // The original's result is always what callers get; it runs first and may throw.\n\
219         \x20 const expected = legacy(...args)\n\
220         \x20 if (expected && typeof (expected as any).then === 'function') {{\n\
221         \x20   return (expected as Promise<unknown>).then((value) => {{\n\
222         \x20     check(name, args, value, () => native[name](...args))\n\
223         \x20     return value\n\
224         \x20   }})\n\
225         \x20 }}\n\
226         \x20 check(name, args, expected, () => native[name](...args))\n\
227         \x20 return expected\n\
228         }}\n",
229        native = relative(&dir, &crate_dir.join("index.cjs")),
230        codec = CODEC_JS.trim().replace("const enc = (v, stack = [])", "const enc = (v: any, stack: any[] = []): any")
231            .replace("const dec = (v)", "const dec = (v: any): any")
232            .replace("const canon = (v, sort)", "const canon = (v: any, sort: boolean): any")
233            .replace("const same = (a, b, sort = false)", "const same = (a: unknown, b: unknown, sort = false): boolean"),
234    ));
235    for f in &manifest.exports {
236        let i = files.iter().position(|file| *file == f.file).unwrap_or(0);
237        code.push_str(&format!(
238            "\nexport const {name}: typeof legacy{i}.{name} = ((...args: unknown[]) => call('{name}', legacy{i}.{name}, args)) as any\n",
239            name = f.name
240        ));
241    }
242    for c in &manifest.classes {
243        let i = files.iter().position(|file| *file == c.file).unwrap_or(0);
244        let methods: String = c
245            .methods
246            .iter()
247            .map(|m| format!("  {name}(...args: any[]): any {{\n    return this.#call('{name}', args)\n  }}\n", name = m.name))
248            .collect();
249        code.push_str(&format!(
250            "\n/** `{name}`: a TS instance and a Rust instance side by side; callers get the TS results. */\n\
251             export class {name} {{\n\
252             \x20 #legacy: any = null\n\
253             \x20 #native: any = null\n\
254             \x20 constructor(...args: any[]) {{\n\
255             \x20   if (mode === 'new' && native) {{\n\
256             \x20     this.#native = new native.{name}(...args)\n\
257             \x20     return\n\
258             \x20   }}\n\
259             \x20   this.#legacy = new (legacy{i} as any).{name}(...args)\n\
260             \x20   if (mode === 'old' || !native) return\n\
261             \x20   try {{\n\
262             \x20     this.#native = new native.{name}(...args)\n\
263             \x20   }}\n\
264             \x20   catch (error) {{\n\
265             \x20     shadowStats.mismatches++\n\
266             \x20     report({{ fn: '{name} constructor', args, expected: {{ ok: true }}, actual: {{ error: String((error as Error)?.message ?? error) }} }})\n\
267             \x20   }}\n\
268             \x20 }}\n\
269             {methods}             \x20 #call(method: string, args: unknown[]): any {{\n\
270             \x20   if (!this.#legacy) return this.#native[method](...args)\n\
271             \x20   if (!this.#native) return this.#legacy[method](...args)\n\
272             \x20   const expected = this.#legacy[method](...args)\n\
273             \x20   check(`{name}.${{method}}`, args, expected, () => this.#native[method](...args))\n\
274             \x20   return expected\n\
275             \x20 }}\n\
276             }}\n",
277            name = c.name
278        ));
279    }
280    for j in &manifest.js_only {
281        let i = files.iter().position(|file| *file == j.file).unwrap_or(0);
282        code.push_str(&format!(
283            "\n/** Stays in TS ({}). */\nexport const {name} = legacy{i}.{name}\n",
284            j.reason,
285            name = j.name
286        ));
287    }
288    std::fs::write(&path, with_kill_switch(&code, &manifest.crate_name))
289        .with_context(|| format!("writing {}", path.display()))?;
290    Ok(ShadowOutcome {
291        path,
292        exports: manifest
293            .exports
294            .iter()
295            .map(|f| f.name.clone())
296            .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
297            .collect(),
298    })
299}
300
301/// An ES import specifier for `to`, relative to the folder `from`.
302/// Makes the shadow honor the unit's kill switch, `RUST_ANYTHING_UNIT_<NAME>=original`, before
303/// `RUST_ANYTHING_MODE`: the original package can send one unit back on its own.
304fn with_kill_switch(text: &str, crate_name: &str) -> String {
305    let switch = crate::front_door::kill_switch(crate_name);
306    text.replacen(
307        "((globalThis as any).process?.env?.RUST_ANYTHING_MODE ?? 'shadow')",
308        &format!(
309            "((globalThis as any).process?.env?.{switch} === 'original' ? 'old' : ((globalThis as any).process?.env?.RUST_ANYTHING_MODE ?? 'shadow'))"
310        ),
311        1,
312    )
313    .replacen(
314        "_MODE = os.environ.get(\"RUST_ANYTHING_MODE\", \"shadow\")",
315        &format!(
316            "_MODE = \"old\" if os.environ.get(\"{switch}\") == \"original\" else os.environ.get(\"RUST_ANYTHING_MODE\", \"shadow\")"
317        ),
318        1,
319    )
320    .replacen(
321        "MODE = ENV.fetch(\"RUST_ANYTHING_MODE\", \"shadow\")",
322        &format!(
323            "MODE = ENV[\"{switch}\"] == \"original\" ? \"old\" : ENV.fetch(\"RUST_ANYTHING_MODE\", \"shadow\")"
324        ),
325        1,
326    )
327    .replacen(
328        "var mode = func() string {\n",
329        &format!(
330            "var mode = func() string {{\n\tif os.Getenv(\"{switch}\") == \"original\" {{\n\t\treturn \"old\"\n\t}}\n"
331        ),
332        1,
333    )
334    .replace(
335        "System.getProperty(\"rust-anything.mode\", \"shadow\")",
336        &format!(
337            "(\"original\".equals(System.getenv(\"{switch}\")) ? \"old\" : System.getProperty(\"rust-anything.mode\", \"shadow\"))"
338        ),
339    )
340}
341
342pub(crate) fn relative(from: &Path, to: &Path) -> String {
343    let from: Vec<Component> = from.components().collect();
344    let to_parts: Vec<Component> = to.components().collect();
345    let common = from
346        .iter()
347        .zip(&to_parts)
348        .take_while(|(a, b)| a == b)
349        .count();
350    let mut parts: Vec<String> =
351        std::iter::repeat_n("..".to_string(), from.len() - common).collect();
352    parts.extend(
353        to_parts[common..]
354            .iter()
355            .map(|c| c.as_os_str().to_string_lossy().into_owned()),
356    );
357    let joined = parts.join("/");
358    if joined.starts_with("..") {
359        joined
360    } else {
361        format!("./{joined}")
362    }
363}
364
365/// The Python shadow module: same functions and classes, original first, Rust compared.
366fn shadow_python(
367    crate_dir: &Path,
368    manifest: &Manifest,
369    out: Option<&Path>,
370) -> Result<ShadowOutcome> {
371    let stem = manifest
372        .crate_name
373        .trim_end_matches("-rs")
374        .replace('-', "_");
375    let path = match out {
376        Some(p) => p.to_path_buf(),
377        None => crate_dir.join("shadow").join(format!("{stem}_shadow.py")),
378    };
379    if path.exists() {
380        bail!("{} exists; remove it first or pass --out", path.display());
381    }
382    std::fs::create_dir_all(path.parent().context("output path has no folder")?)?;
383    let mut files: Vec<&str> = manifest
384        .exports
385        .iter()
386        .map(|f| f.file.as_str())
387        .chain(manifest.classes.iter().map(|c| c.file.as_str()))
388        .chain(manifest.js_only.iter().map(|j| j.file.as_str()))
389        .collect();
390    files.sort_unstable();
391    files.dedup();
392    let module_of = |file: &str| files.iter().position(|f| *f == file).unwrap_or(0);
393    let sources = format!(
394        "[{}]",
395        files
396            .iter()
397            .map(|f| format!("{:?}", manifest.root.join(f).to_string_lossy()))
398            .collect::<Vec<_>>()
399            .join(", ")
400    );
401    let mut code = format!(
402        "\"\"\"Generated by rust-anything: runs the Python original and the Rust port side by side.\n\n\
403         RUST_ANYTHING_MODE=old: original only. shadow (default): original result, Rust compared.\n\
404         new: Rust only. Report mismatches with `on_mismatch`; counts are in `stats`.\n\"\"\"\n\
405         import importlib\nimport json\nimport math\nimport os\nimport sys\n\n\
406         _MODE = os.environ.get(\"RUST_ANYTHING_MODE\", \"shadow\")\n\
407         _SOURCES = {sources}\n\
408         _PACKAGE_DIR = {package_dir:?}\n{driver_helpers}\n\
409         _legacy = [load(p) for p in _SOURCES]\n\
410         _native = None\n\
411         if _MODE != \"old\":\n    try:\n        sys.path.insert(0, _PACKAGE_DIR)\n        _native = importlib.import_module({lib:?})\n\
412         \x20   except ImportError as error:\n        if _MODE == \"new\":\n            raise\n\
413         \x20       print(\"[rust-anything] Rust module not loaded, running the original only:\", error, file=sys.stderr)\n\n\
414         stats = {{\"calls\": 0, \"mismatches\": 0}}\n\n\n\
415         def _default_report(m):\n    if stats[\"mismatches\"] <= 10:\n        print(\"[rust-anything] mismatch in\", m[\"fn\"], m, file=sys.stderr)\n\n\n\
416         _report = _default_report\n\n\n\
417         def on_mismatch(handler):\n    \"\"\"Replace the default reporter (stderr for the first 10 mismatches).\"\"\"\n    global _report\n    _report = handler\n\n\n\
418         def _check(name, args, expected, run):\n    stats[\"calls\"] += 1\n    try:\n        actual = {{\"ok\": enc(run())}}\n\
419         \x20   except (KeyboardInterrupt, SystemExit):\n        raise\n    except BaseException as e:  # noqa: BLE001\n        actual = {{\"error\": error_text(e)}}\n\
420         \x20   want = {{\"ok\": enc(expected)}}\n    if canon(want, False) != canon(actual, False):\n\
421         \x20       stats[\"mismatches\"] += 1\n        _report({{\"fn\": name, \"args\": args, \"expected\": want, \"actual\": actual}})\n\n\n\
422         def _call(module, name, args, kwargs):\n    legacy = getattr(_legacy[module], name)\n    if _native is None:\n        return legacy(*args, **kwargs)\n\
423         \x20   if _MODE == \"new\":\n        return getattr(_native, name)(*args, **kwargs)\n    expected = legacy(*args, **kwargs)\n\
424         \x20   _check(name, list(args), expected, lambda: getattr(_native, name)(*args, **kwargs))\n    return expected\n",
425        sources = sources,
426        package_dir = crate_dir.join("python").to_string_lossy(),
427        lib = manifest.lib_name(),
428        driver_helpers = PY_HELPERS,
429    );
430    for f in &manifest.exports {
431        code.push_str(&format!(
432            "\n\ndef {name}(*args, **kwargs):\n    return _call({m}, {name:?}, args, kwargs)\n",
433            name = f.name,
434            m = module_of(&f.file)
435        ));
436    }
437    for c in &manifest.classes {
438        let methods: String = c
439            .methods
440            .iter()
441            .map(|m| {
442                format!(
443                    "\n    def {name}(self, *args, **kwargs):\n        return self._call({name:?}, args, kwargs)\n",
444                    name = m.name
445                )
446            })
447            .collect();
448        code.push_str(&format!(
449            "\n\nclass {name}:\n    \"\"\"A Python instance and a Rust instance side by side; callers get the Python results.\"\"\"\n\n\
450             \x20   def __init__(self, *args, **kwargs):\n        self._legacy = None\n        self._native = None\n\
451             \x20       if _MODE == \"new\" and _native is not None:\n            self._native = _native.{name}(*args, **kwargs)\n            return\n\
452             \x20       self._legacy = getattr(_legacy[{m}], {name:?})(*args, **kwargs)\n        if _native is None or _MODE == \"old\":\n            return\n\
453             \x20       try:\n            self._native = _native.{name}(*args, **kwargs)\n        except (KeyboardInterrupt, SystemExit):\n            raise\n        except BaseException as e:  # noqa: BLE001\n\
454             \x20           stats[\"mismatches\"] += 1\n            _report({{\"fn\": \"{name} constructor\", \"args\": list(args), \"expected\": {{\"ok\": True}}, \"actual\": {{\"error\": error_text(e)}}}})\n\n\
455             \x20   def _call(self, method, args, kwargs):\n        if self._legacy is None:\n            return getattr(self._native, method)(*args, **kwargs)\n\
456             \x20       if self._native is None:\n            return getattr(self._legacy, method)(*args, **kwargs)\n\
457             \x20       expected = getattr(self._legacy, method)(*args, **kwargs)\n\
458             \x20       _check(f\"{name}.{{method}}\", list(args), expected, lambda: getattr(self._native, method)(*args, **kwargs))\n        return expected\n{methods}",
459            name = c.name,
460            m = module_of(&c.file)
461        ));
462    }
463    for j in &manifest.js_only {
464        code.push_str(&format!(
465            "\n\n# Stays in Python ({}).\n{name} = _legacy[{m}].{name}\n",
466            j.reason,
467            name = j.name,
468            m = module_of(&j.file)
469        ));
470    }
471    std::fs::write(&path, with_kill_switch(&code, &manifest.crate_name))
472        .with_context(|| format!("writing {}", path.display()))?;
473    Ok(ShadowOutcome {
474        path,
475        exports: manifest
476            .exports
477            .iter()
478            .map(|f| f.name.clone())
479            .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
480            .collect(),
481    })
482}
483
484/// `enc`, `canon`, `load` and `error_text` from the Python driver, for the shadow module.
485const PY_HELPERS: &str = {
486    // Kept in one place: the driver defines them first, before its entry points.
487    r#"
488BIG = 2 ** 53
489
490
491def enc(v, stack=()):
492    if v is None or isinstance(v, (bool, str)):
493        return v
494    if isinstance(v, int):
495        return v if -BIG <= v <= BIG else {"$int": str(v)}
496    if isinstance(v, float):
497        if math.isnan(v):
498            return {"$num": "NaN"}
499        if math.isinf(v):
500            return {"$num": "Infinity" if v > 0 else "-Infinity"}
501        if v == 0 and math.copysign(1, v) < 0:
502            return {"$num": "-0"}
503        return {"$float": repr(v)} if v.is_integer() else v
504    if any(v is s for s in stack):
505        return {"$cycle": True}
506    stack = stack + (v,)
507    if isinstance(v, list):
508        return [enc(x, stack) for x in v]
509    if isinstance(v, tuple):
510        return {"$tuple": [enc(x, stack) for x in v]}
511    if isinstance(v, (set, frozenset)):
512        return {"$set": sorted((enc(x, stack) for x in v), key=json.dumps)}
513    if isinstance(v, (bytes, bytearray)):
514        return {"$bytes": list(v)}
515    if isinstance(v, dict):
516        if all(isinstance(k, str) for k in v):
517            return {k: enc(x, stack) for k, x in v.items()}
518        return {"$dict": [[enc(k, stack), enc(x, stack)] for k, x in v.items()]}
519    if hasattr(v, "__dict__"):
520        return {"$object": type(v).__name__, "attrs": enc(vars(v), stack)}
521    return {"$repr": type(v).__name__}
522
523
524def canon(v, sort):
525    return json.dumps(v, sort_keys=sort, ensure_ascii=False)
526
527
528def error_text(e):
529    return f"{type(e).__name__}: {e}"
530
531
532def load(path):
533    path = os.path.abspath(path)
534    directory, filename = os.path.split(path)
535    parts = [os.path.splitext(filename)[0]]
536    while os.path.exists(os.path.join(directory, "__init__.py")):
537        directory, package = os.path.split(directory)
538        parts.insert(0, package)
539    if parts[-1] == "__init__":
540        parts.pop()
541    if directory not in sys.path:
542        sys.path.insert(0, directory)
543    return importlib.import_module(".".join(parts))
544"#
545};
546
547/// C: a shadow translation unit, and the `-D` flags that rename the originals beside it.
548fn shadow_c(crate_dir: &Path, manifest: &Manifest, out: Option<&Path>) -> Result<ShadowOutcome> {
549    let stem = manifest
550        .crate_name
551        .trim_end_matches("-rs")
552        .replace('-', "_");
553    let path = match out {
554        Some(p) => p.to_path_buf(),
555        None => crate_dir.join("shadow").join(format!("{stem}_shadow.c")),
556    };
557    if path.exists() {
558        bail!("{} exists; remove it first or pass --out", path.display());
559    }
560    let dir = path.parent().context("output path has no folder")?;
561    std::fs::create_dir_all(dir)?;
562    std::fs::write(&path, crate::codegen_c::shadow_c(manifest))?;
563    std::fs::write(
564        dir.join("flags.txt"),
565        crate::codegen_c::shadow_flags(manifest),
566    )?;
567    Ok(ShadowOutcome {
568        path,
569        exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
570    })
571}
572
573#[cfg(test)]
574mod tests {
575    use super::relative;
576    use std::path::Path;
577
578    #[test]
579    fn builds_relative_specifiers() {
580        assert_eq!(
581            relative(Path::new("/r/rust/x/shadow"), Path::new("/r/src/a.ts")),
582            "../../../src/a.ts"
583        );
584        assert_eq!(
585            relative(Path::new("/r/rust/x"), Path::new("/r/rust/x/index.cjs")),
586            "./index.cjs"
587        );
588    }
589}