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