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