Skip to main content

rust_anything/
codegen_go.rs

1//! Go: the cgo wrapper package (the original API over the Rust library), and the driver that
2//! calls a package's functions by name for record, diff and bench.
3
4use std::fmt::Write as _;
5use std::path::Path;
6
7use crate::bridge::Manifest;
8use crate::ts::exports::ExportedFn;
9
10/// The result types of a Go function, without the trailing `error`, and whether it has one.
11pub fn results(f: &ExportedFn) -> (Vec<String>, bool) {
12    let text = f.native_return.as_deref().unwrap_or("()");
13    let inner = text.trim().trim_start_matches('(').trim_end_matches(')');
14    let mut parts = split_top(inner);
15    let fallible = parts.last().is_some_and(|p| p == "error");
16    if fallible {
17        parts.pop();
18    }
19    (parts, fallible)
20}
21
22/// The port type of a Go type whose range `i64` cannot hold (`uint64`, `uint`, `uintptr`), alone
23/// or as the items of a slice; `None` for every other type.
24pub fn unsigned_port_type(go: &str) -> Option<String> {
25    match go.trim() {
26        "uint64" | "uint" => Some("u64".into()),
27        "uintptr" => Some("usize".into()),
28        go => go
29            .strip_prefix("[]")
30            .and_then(unsigned_port_type)
31            .map(|item| format!("Vec<{item}>")),
32    }
33}
34
35fn split_top(text: &str) -> Vec<String> {
36    let mut out = Vec::new();
37    let mut depth = 0i32;
38    let mut current = String::new();
39    for c in text.chars() {
40        match c {
41            '[' | '(' | '{' => depth += 1,
42            ']' | ')' | '}' => depth -= 1,
43            ',' if depth == 0 => {
44                out.push(current.trim().to_string());
45                current.clear();
46                continue;
47            }
48            _ => {}
49        }
50        current.push(c);
51    }
52    if !current.trim().is_empty() {
53        out.push(current.trim().to_string());
54    }
55    out
56}
57
58/// Exported identifiers in a Go type: the package's own named types.
59fn local_types(t: &str) -> Vec<String> {
60    let mut out = Vec::new();
61    let mut word = String::new();
62    let mut prev = ' ';
63    for c in t.chars().chain(std::iter::once(' ')) {
64        if c.is_alphanumeric() || c == '_' {
65            word.push(c);
66            continue;
67        }
68        if !word.is_empty() {
69            if word.starts_with(char::is_uppercase) && prev != '.' {
70                out.push(std::mem::take(&mut word));
71            }
72            word.clear();
73        }
74        prev = c;
75    }
76    out
77}
78
79/// `t` with the package's named types qualified as `pkg.Name`.
80fn qualify(t: &str) -> String {
81    let mut out = String::new();
82    let mut word = String::new();
83    let mut prev = ' ';
84    for c in t.chars().chain(std::iter::once('\0')) {
85        if c.is_alphanumeric() || c == '_' {
86            word.push(c);
87            continue;
88        }
89        if !word.is_empty() {
90            if word.starts_with(char::is_uppercase) && prev != '.' {
91                out.push_str("pkg.");
92            }
93            out.push_str(&word);
94            word.clear();
95        }
96        if c != '\0' {
97            out.push(c);
98        }
99        prev = c;
100    }
101    out
102}
103
104/// Every named type the exported signatures use.
105pub fn used_types(m: &Manifest) -> Vec<String> {
106    let mut names: Vec<String> = m
107        .exports
108        .iter()
109        .flat_map(|f| {
110            f.params
111                .iter()
112                .filter_map(|p| p.native_type.clone())
113                .chain(results(f).0)
114                .collect::<Vec<_>>()
115        })
116        .flat_map(|t| local_types(&t))
117        .collect();
118    names.sort();
119    names.dedup();
120    names
121}
122
123/// The Go sources of the unit (not tests).
124pub fn unit_sources(m: &Manifest) -> Vec<String> {
125    let dir = m.root.join(m.unit.trim_end_matches('/'));
126    let dir = if dir.is_file() {
127        dir.parent().map(Path::to_path_buf).unwrap_or(dir)
128    } else {
129        dir
130    };
131    let mut files: Vec<_> = std::fs::read_dir(&dir)
132        .into_iter()
133        .flatten()
134        .flatten()
135        .map(|e| e.path())
136        .filter(|p| {
137            p.extension().is_some_and(|e| e == "go") && !p.to_string_lossy().ends_with("_test.go")
138        })
139        .collect();
140    files.sort();
141    files
142        .iter()
143        .filter_map(|p| std::fs::read_to_string(p).ok())
144        .collect()
145}
146
147pub fn package_name(m: &Manifest) -> String {
148    unit_sources(m)
149        .iter()
150        .find_map(|s| crate::lang::go::package_name(s))
151        .unwrap_or_else(|| "port".into())
152}
153
154/// The Go sources of the unit selected for the active Go build target (excludes other-OS/arch
155/// files such as `errors_windows.go` on Linux so generated sentinel references always compile).
156fn sentinel_sources(m: &Manifest) -> Vec<String> {
157    let dir = m.root.join(m.unit.trim_end_matches('/'));
158    let dir = if dir.is_file() {
159        dir.parent().map(Path::to_path_buf).unwrap_or(dir)
160    } else {
161        dir
162    };
163    let mut files: Vec<_> = std::fs::read_dir(&dir)
164        .into_iter()
165        .flatten()
166        .flatten()
167        .map(|e| e.path())
168        .filter(|p| {
169            p.extension().is_some_and(|e| e == "go")
170                && !p.to_string_lossy().ends_with("_test.go")
171                && go_file_matches_host(p)
172        })
173        .collect();
174    files.sort();
175    files
176        .iter()
177        .filter_map(|p| std::fs::read_to_string(p).ok())
178        .filter(|src| go_build_tag_matches_host(src))
179        .collect()
180}
181
182fn host_goos() -> &'static str {
183    match std::env::consts::OS {
184        "macos" => "darwin",
185        other => other,
186    }
187}
188
189fn host_goarch() -> &'static str {
190    match std::env::consts::ARCH {
191        "x86_64" => "amd64",
192        "aarch64" => "arm64",
193        "x86" => "386",
194        other => other,
195    }
196}
197
198fn go_file_matches_host(path: &Path) -> bool {
199    const KNOWN_GOOS: &[&str] = &[
200        "aix",
201        "android",
202        "darwin",
203        "dragonfly",
204        "freebsd",
205        "hurd",
206        "illumos",
207        "ios",
208        "js",
209        "linux",
210        "netbsd",
211        "openbsd",
212        "plan9",
213        "solaris",
214        "wasip1",
215        "windows",
216    ];
217    const KNOWN_GOARCH: &[&str] = &[
218        "386", "amd64", "arm", "arm64", "loong64", "mips", "mips64", "mips64le", "mipsle", "ppc64",
219        "ppc64le", "riscv64", "s390x", "wasm",
220    ];
221    let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
222        return true;
223    };
224    let mut parts: Vec<&str> = stem.split('_').collect();
225    if parts.len() < 2 {
226        return true;
227    }
228    if let Some(&last) = parts.last()
229        && KNOWN_GOARCH.contains(&last)
230    {
231        if last != host_goarch() {
232            return false;
233        }
234        parts.pop();
235    }
236    if parts.len() >= 2
237        && let Some(&last) = parts.last()
238        && KNOWN_GOOS.contains(&last)
239        && last != host_goos()
240    {
241        return false;
242    }
243    true
244}
245
246fn go_build_tag_matches_host(source: &str) -> bool {
247    let host_os = host_goos();
248    let is_unix = matches!(
249        host_os,
250        "darwin" | "dragonfly" | "freebsd" | "linux" | "netbsd" | "openbsd" | "solaris"
251    );
252    for line in source.lines() {
253        let trimmed = line.trim();
254        if trimmed.starts_with("package ") {
255            break;
256        }
257        if let Some(expr) = trimmed.strip_prefix("//go:build ") {
258            let expr = expr.trim();
259            if matches!(
260                expr,
261                "linux" | "windows" | "darwin" | "freebsd" | "openbsd" | "netbsd" | "plan9"
262            ) {
263                return expr == host_os;
264            }
265            if expr == "unix" {
266                return is_unix;
267            }
268            if let Some(neg) = expr.strip_prefix('!') {
269                let neg = neg.trim();
270                if matches!(
271                    neg,
272                    "linux" | "windows" | "darwin" | "freebsd" | "openbsd" | "netbsd"
273                ) {
274                    return neg != host_os;
275                }
276                if neg == "unix" {
277                    return !is_unix;
278                }
279            }
280        }
281    }
282    true
283}
284
285/// Re-declares exported sentinel errors and emits `rustAnythingToErr` so `errors.Is` and `==`
286/// match the package's own error values.
287fn emit_sentinel_lookup(out: &mut String, sentinels: &[crate::lang::go::SentinelError]) {
288    if sentinels.is_empty() {
289        out.push_str("\nfunc rustAnythingToErr(msg string) error {\n\treturn errors.New(msg)\n}\n");
290        return;
291    }
292    out.push('\n');
293    for s in sentinels {
294        if let Some(target) = &s.alias_of {
295            let _ = writeln!(out, "var {} = {target}", s.name);
296        } else {
297            let text = s.message.as_deref().unwrap_or(&s.name);
298            let quoted = serde_json::to_string(text).unwrap_or_else(|_| format!("{text:?}"));
299            let _ = writeln!(out, "var {} = errors.New({quoted})", s.name);
300        }
301    }
302    out.push_str(
303        "\ntype rustAnythingWrappedErr struct {\n\tsentinel error\n\tmsg      string\n}\n\n\
304         func (e *rustAnythingWrappedErr) Error() string { return e.msg }\n\
305         func (e *rustAnythingWrappedErr) Unwrap() error { return e.sentinel }\n\n\
306         type rustAnythingSentinel struct {\n\tname    string\n\ttext    string\n\thasText bool\n\terr     error\n}\n\n\
307         var rustAnythingSentinels = []rustAnythingSentinel{\n",
308    );
309    for s in sentinels {
310        let name_q = serde_json::to_string(&s.name).unwrap_or_else(|_| format!("{:?}", s.name));
311        let (has_text, text_q) = match &s.message {
312            Some(t) => (
313                "true",
314                serde_json::to_string(t).unwrap_or_else(|_| format!("{t:?}")),
315            ),
316            None => ("false", "\"\"".into()),
317        };
318        let _ = writeln!(
319            out,
320            "\t{{name: {name_q}, text: {text_q}, hasText: {has_text}, err: {}}},",
321            s.name
322        );
323    }
324    out.push_str(
325        r#"}
326
327func rustAnythingToErr(msg string) error {
328	for _, s := range rustAnythingSentinels {
329		if msg == s.name || (s.hasText && msg == s.text) {
330			return s.err
331		}
332	}
333	for _, s := range rustAnythingSentinels {
334		if prefix := s.name + ": "; strings.HasPrefix(msg, prefix) {
335			rest := strings.TrimPrefix(msg, prefix)
336			if !s.hasText {
337				return &rustAnythingWrappedErr{sentinel: s.err, msg: rest}
338			}
339			return fmt.Errorf("%w: %s", s.err, rest)
340		}
341		if s.hasText && s.text != "" {
342			if prefix := s.text + ": "; strings.HasPrefix(msg, prefix) {
343				return fmt.Errorf("%w: %s", s.err, strings.TrimPrefix(msg, prefix))
344			}
345			if suffix := ": " + s.text; strings.HasSuffix(msg, suffix) {
346				return fmt.Errorf("%s: %w", strings.TrimSuffix(msg, suffix), s.err)
347			}
348		}
349	}
350	return errors.New(msg)
351}
352"#,
353    );
354}
355
356/// JSON helpers shared by the wrapper and the driver.
357const HELPERS_GO: &str = r#"
358// rustAnythingDecode decodes JSON into target; floats may be {"$num": "NaN" | "Infinity" | ...}.
359func rustAnythingDecode(raw json.RawMessage, target any) error {
360	if f, ok := target.(*float64); ok && len(raw) > 0 && raw[0] == '{' {
361		var marker map[string]string
362		if err := json.Unmarshal(raw, &marker); err != nil {
363			return err
364		}
365		switch marker["$num"] {
366		case "NaN":
367			*f = math.NaN()
368		case "Infinity":
369			*f = math.Inf(1)
370		case "-Infinity":
371			*f = math.Inf(-1)
372		case "-0":
373			*f = math.Copysign(0, -1)
374		default:
375			return errors.New("not a number")
376		}
377		return nil
378	}
379	if len(raw) == 0 {
380		raw = json.RawMessage("null")
381	}
382	return json.Unmarshal(raw, target)
383}
384
385// rustAnythingEncode marks the floats JSON cannot carry.
386func rustAnythingEncode(v any) any {
387	var f float64
388	switch x := v.(type) {
389	case float64:
390		f = x
391	case float32:
392		f = float64(x)
393	default:
394		return v
395	}
396	switch {
397	case math.IsNaN(f):
398		return map[string]string{"$num": "NaN"}
399	case math.IsInf(f, 1):
400		return map[string]string{"$num": "Infinity"}
401	case math.IsInf(f, -1):
402		return map[string]string{"$num": "-Infinity"}
403	case f == 0 && math.Signbit(f):
404		return map[string]string{"$num": "-0"}
405	}
406	return v
407}
408"#;
409
410/// The wrapper package: the original package's API, each function calling the Rust library.
411pub fn wrapper(m: &Manifest, api: &crate::codegen::PortApi) -> String {
412    let lib = m.lib_name();
413    let sources = unit_sources(m);
414    let types = crate::lang::go::type_decls(&sources, &used_types(m));
415    let sentinels = crate::lang::go::sentinel_errors(&sentinel_sources(m));
416    let extra_imports = if sentinels.is_empty() {
417        ""
418    } else {
419        "\t\"fmt\"\n\t\"strings\"\n"
420    };
421    let mut out = format!(
422        "// Package {pkg} is the Rust port of `{unit}`, generated by rust-anything: the same API, each\n\
423         // function calling the Rust library. Regenerate with `rust-anything refresh`.\n\
424         package {pkg}\n\n\
425         /*\n#cgo LDFLAGS: -L${{SRCDIR}}/../target/release -l{lib} -Wl,-rpath,${{SRCDIR}}/../target/release\n\
426         #include <stdbool.h>\n#include <stdint.h>\n#include <stdlib.h>\n\
427         char *rust_anything_call(const char *name, const char *args);\n\
428         void rust_anything_free(char *ptr);\n{typed_c}*/\nimport \"C\"\n\n\
429         import (\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"errors\"\n{extra_imports}\t\"math\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\nvar _ = binary.LittleEndian\nvar _ = runtime.KeepAlive\n",
430        pkg = package_name(m),
431        unit = m.unit,
432        typed_c = typed_prototypes(m, api),
433    );
434    for t in types {
435        let _ = write!(out, "\n{t}\n");
436    }
437    emit_sentinel_lookup(&mut out, &sentinels);
438    out.push_str(HELPERS_GO);
439    out.push_str(
440        r#"
441type rustAnythingAnswer struct {
442	Ok    json.RawMessage `json:"ok"`
443	Error *string         `json:"error"`
444	Panic *string         `json:"panic"`
445}
446
447func rustAnythingCall(name string, args ...any) (json.RawMessage, error) {
448	for i, a := range args {
449		args[i] = rustAnythingEncode(a)
450	}
451	encoded, err := json.Marshal(args)
452	if err != nil {
453		panic(err)
454	}
455	cName := C.CString(name)
456	defer C.free(unsafe.Pointer(cName))
457	cArgs := C.CString(string(encoded))
458	defer C.free(unsafe.Pointer(cArgs))
459	answer := C.rust_anything_call(cName, cArgs)
460	defer C.rust_anything_free(answer)
461	var a rustAnythingAnswer
462	if err := json.Unmarshal([]byte(C.GoString(answer)), &a); err != nil {
463		panic(err)
464	}
465	if a.Panic != nil {
466		panic(*a.Panic)
467	}
468	if a.Error != nil {
469		return nil, rustAnythingToErr(*a.Error)
470	}
471	return a.Ok, nil
472}
473
474func rustAnythingMust(err error) {
475	if err != nil {
476		panic(err)
477	}
478}
479"#,
480    );
481    let typed_fns: Vec<&str> = api
482        .functions
483        .iter()
484        .filter(|f| typed(m, f).is_some())
485        .map(|f| f.js_name.as_str())
486        .collect();
487    let wired = wire_fns(m, api);
488    if !typed_fns.is_empty() || !wired.is_empty() || !m.batches.is_empty() {
489        out.push_str(TYPED_HELPERS_GO);
490    }
491    if !wired.is_empty() {
492        out.push_str(WIRE_HELPERS_GO);
493    }
494    for f in &m.exports {
495        if typed_fns.contains(&f.name.as_str()) {
496            out.push_str(&typed_go(f));
497            continue;
498        }
499        if let Some((e, params, result, _)) = wired.iter().find(|(e, ..)| e.name == f.name) {
500            out.push_str(&wire_go(e, params, result.as_ref()));
501            continue;
502        }
503        let (results, fallible) = results(f);
504        let params = wrapper_params(f);
505        let mut all_results = results.clone();
506        if fallible {
507            all_results.push("error".into());
508        }
509        let ret = match all_results.len() {
510            0 => String::new(),
511            1 => format!(" {}", all_results[0]),
512            _ => format!(" ({})", all_results.join(", ")),
513        };
514        let args: Vec<String> = (0..f.params.len()).map(wrapper_arg).collect();
515        let call_args = if args.is_empty() {
516            String::new()
517        } else {
518            format!(", {}", args.join(", "))
519        };
520        let _ = writeln!(
521            out,
522            "\n// {} is the Rust port of `{}` (`{}:{}`).\nfunc {}({}){ret} {{",
523            f.name,
524            f.prototype.as_deref().unwrap_or(&f.name),
525            f.file,
526            f.line,
527            f.name,
528            params
529        );
530        let names: Vec<String> = (0..results.len()).map(|i| format!("r{i}")).collect();
531        let decls: String = results
532            .iter()
533            .enumerate()
534            .map(|(i, t)| format!("\tvar r{i} {t}\n"))
535            .collect();
536        let raw = if results.is_empty() { "_" } else { "raw" };
537        let _ = writeln!(
538            out,
539            "\t{raw}, err := rustAnythingCall(\"{}\"{call_args})",
540            f.name
541        );
542        if fallible {
543            let _ = writeln!(out, "\tif err != nil {{\n{decls}\t\treturn {}\n\t}}", {
544                let mut r = names.clone();
545                r.push("err".into());
546                r.join(", ")
547            });
548        } else {
549            out.push_str("\trustAnythingMust(err)\n");
550        }
551        out.push_str(&decls);
552        match results.len() {
553            0 => {}
554            1 => out.push_str("\trustAnythingMust(rustAnythingDecode(raw, &r0))\n"),
555            n => {
556                let _ = writeln!(
557                    out,
558                    "\tvar parts []json.RawMessage\n\trustAnythingMust(json.Unmarshal(raw, &parts))\n\
559                     \tif len(parts) != {n} {{\n\t\tpanic(\"rust-anything: expected {n} results\")\n\t}}"
560                );
561                for i in 0..n {
562                    let _ = writeln!(
563                        out,
564                        "\trustAnythingMust(rustAnythingDecode(parts[{i}], &r{i}))"
565                    );
566                }
567            }
568        }
569        let mut r = names;
570        if fallible {
571            r.push("nil".into());
572        }
573        if r.is_empty() {
574            out.push_str("}\n");
575        } else {
576            let _ = writeln!(out, "\treturn {}\n}}", r.join(", "));
577        }
578    }
579    // Validated with the Rust side in `ffi_bindings`.
580    out.push_str(&crate::codegen_batch_native::go_wrapper(m, api).unwrap_or_default());
581    out
582}
583
584// ---- typed calls: numbers, booleans and strings cross cgo without JSON ----------------------
585
586/// A Go type that crosses cgo directly: its C type, the port type it must match, the Rust
587/// parameter type, and how Go converts it back from C.
588pub(crate) struct Typed {
589    pub c: &'static str,
590    pub port: &'static str,
591    pub rust: &'static str,
592}
593
594pub(crate) fn typed_type(go: &str) -> Option<Typed> {
595    Some(match go.trim() {
596        "int" | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "byte"
597        | "rune" => Typed {
598            c: "int64_t",
599            port: "i64",
600            rust: "i64",
601        },
602        "float64" | "float32" => Typed {
603            c: "double",
604            port: "f64",
605            rust: "f64",
606        },
607        "bool" => Typed {
608            c: "bool",
609            port: "bool",
610            rust: "bool",
611        },
612        "string" => Typed {
613            c: "string",
614            port: "String",
615            rust: "String",
616        },
617        _ => return None,
618    })
619}
620
621/// Whether a function crosses as a typed cgo call: typed parameters, and no result, one typed
622/// result, or one with a trailing `error`; the port kept the matching Rust types.
623fn typed<'m>(m: &'m Manifest, f: &crate::codegen::PortFn) -> Option<&'m ExportedFn> {
624    let e = m.exports.iter().find(|e| e.name == f.js_name)?;
625    if e.params.len() != f.params.len() {
626        return None;
627    }
628    for (p, (_, port)) in e.params.iter().zip(&f.params) {
629        if typed_type(p.native_type.as_deref()?)?.port != port {
630            return None;
631        }
632    }
633    let (results, _) = results(e);
634    match results.as_slice() {
635        [] => (f.ret == "()").then_some(e),
636        [r] => (typed_type(r)?.port == f.ret).then_some(e),
637        _ => None,
638    }
639}
640
641/// C prototypes of the typed functions, for the cgo preamble.
642fn typed_prototypes(m: &Manifest, api: &crate::codegen::PortApi) -> String {
643    let mut out = String::new();
644    for f in &api.functions {
645        let Some(e) = typed(m, f) else { continue };
646        let mut params: Vec<String> = Vec::new();
647        for (index, p) in e.params.iter().enumerate() {
648            let name = format!("ra_arg{index}");
649            let t = typed_type(p.native_type.as_deref().unwrap_or_default()).expect("typed");
650            if t.c == "string" {
651                params.push(format!("const uint8_t *{name}_ptr, size_t {name}_len"));
652            } else {
653                params.push(format!("{} {name}", t.c));
654            }
655        }
656        match results(e).0.first().and_then(|r| typed_type(r)) {
657            Some(t) if t.c == "string" => {
658                params.push("uint8_t *out, size_t out_cap, size_t *out_len".into())
659            }
660            Some(t) => params.push(format!("{} *out", t.c)),
661            None => {}
662        }
663        params.push("char **err".into());
664        let _ = writeln!(
665            out,
666            "int rust_anything_t_{}({});",
667            f.js_name,
668            params.join(", ")
669        );
670    }
671    out.push_str(&crate::codegen_batch_native::go_prototypes(m, api));
672    for (e, ..) in wire_fns(m, api) {
673        let _ = writeln!(
674            out,
675            "int rust_anything_w_{}(const uint8_t *in, size_t in_len, uint8_t *out, size_t out_cap, size_t *out_len, char **err);",
676            e.name
677        );
678    }
679    out
680}
681
682const TYPED_HELPERS_GO: &str = r#"
683// rustAnythingStr is a string's bytes for C, without copying; nil for "".
684func rustAnythingStr(s string) *C.uint8_t {
685	if len(s) == 0 {
686		return nil
687	}
688	return (*C.uint8_t)(unsafe.Pointer(unsafe.StringData(s)))
689}
690
691// rustAnythingErr takes the error message the Rust side allocated.
692func rustAnythingErr(p *C.char) string {
693	msg := C.GoString(p)
694	C.rust_anything_free(p)
695	return msg
696}
697"#;
698
699fn wrapper_arg(index: usize) -> String {
700    format!("raArg{index}")
701}
702
703fn wrapper_params(export: &ExportedFn) -> String {
704    export
705        .params
706        .iter()
707        .enumerate()
708        .map(|(index, param)| {
709            format!(
710                "{} {}",
711                wrapper_arg(index),
712                param.native_type.as_deref().unwrap_or("any")
713            )
714        })
715        .collect::<Vec<_>>()
716        .join(", ")
717}
718
719/// The Go wrapper function of a typed export: one cgo call, retried once with a bigger buffer
720/// when a string result does not fit.
721fn typed_go(e: &ExportedFn) -> String {
722    let (results, fallible) = results(e);
723    let result = results.first().cloned();
724    let params = wrapper_params(e);
725    let mut sig_results: Vec<String> = result.iter().cloned().collect();
726    if fallible {
727        sig_results.push("error".into());
728    }
729    let ret = match sig_results.len() {
730        0 => String::new(),
731        1 => format!(" {}", sig_results[0]),
732        _ => format!(" ({})", sig_results.join(", ")),
733    };
734    let mut args: Vec<String> = Vec::new();
735    for (index, p) in e.params.iter().enumerate() {
736        let name = wrapper_arg(index);
737        let t = typed_type(p.native_type.as_deref().unwrap_or_default()).expect("typed");
738        match t.c {
739            "string" => {
740                args.push(format!("rustAnythingStr({name})"));
741                args.push(format!("C.size_t(len({name}))"));
742            }
743            "int64_t" => args.push(format!("C.int64_t({name})")),
744            "double" => args.push(format!("C.double({name})")),
745            _ => args.push(format!("C.bool({name})")),
746        }
747    }
748    let rt = result.as_deref().and_then(typed_type);
749    let mut body = String::new();
750    let zero = match (&result, rt.as_ref().map(|t| t.c)) {
751        (_, Some("string")) => "\"\"".to_string(),
752        (_, Some("bool")) => "false".to_string(),
753        (Some(_), _) => "0".to_string(),
754        _ => String::new(),
755    };
756    let fail = |body: &mut String| {
757        if fallible {
758            let ret = if zero.is_empty() {
759                "rustAnythingToErr(rustAnythingErr(errp))".to_string()
760            } else {
761                format!("{zero}, rustAnythingToErr(rustAnythingErr(errp))")
762            };
763            let _ = writeln!(body, "\tif status == 1 {{\n\t\treturn {ret}\n\t}}");
764        } else {
765            let _ = writeln!(
766                body,
767                "\tif status == 1 {{\n\t\tpanic(rustAnythingErr(errp))\n\t}}"
768            );
769        }
770    };
771    body.push_str("\tvar errp *C.char\n");
772    let ok_tail = if fallible { ", nil" } else { "" };
773    match rt.as_ref().map(|t| t.c) {
774        Some("string") => {
775            let call = |buf: &str| {
776                let mut a = args.clone();
777                a.push(format!("(*C.uint8_t)(unsafe.Pointer(&{buf}[0]))"));
778                a.push(format!("C.size_t(len({buf}))"));
779                a.push("&n".into());
780                a.push("&errp".into());
781                format!("C.rust_anything_t_{}({})", e.name, a.join(", "))
782            };
783            let _ = writeln!(
784                body,
785                "\tvar stack [256]byte\n\tbuf := stack[:]\n\tvar n C.size_t\n\tstatus := {}",
786                call("buf")
787            );
788            let _ = writeln!(
789                body,
790                "\tif status == 2 {{\n\t\tbuf = make([]byte, int(n))\n\t\tstatus = {}\n\t}}",
791                call("buf")
792            );
793            fail(&mut body);
794            let _ = writeln!(body, "\treturn string(buf[:n]){ok_tail}");
795        }
796        Some(c) => {
797            let ty = match c {
798                "int64_t" => "C.int64_t",
799                "double" => "C.double",
800                _ => "C.bool",
801            };
802            let mut a = args.clone();
803            a.push("&out".into());
804            a.push("&errp".into());
805            let _ = writeln!(
806                body,
807                "\tvar out {ty}\n\tstatus := C.rust_anything_t_{}({})",
808                e.name,
809                a.join(", ")
810            );
811            fail(&mut body);
812            let _ = writeln!(
813                body,
814                "\treturn {}(out){ok_tail}",
815                result.as_deref().unwrap_or_default()
816            );
817        }
818        None => {
819            let mut a = args.clone();
820            a.push("&errp".into());
821            let _ = writeln!(
822                body,
823                "\tstatus := C.rust_anything_t_{}({})",
824                e.name,
825                a.join(", ")
826            );
827            fail(&mut body);
828            if fallible {
829                body.push_str("\treturn nil\n");
830            }
831        }
832    }
833    format!(
834        "\n// {} is the Rust port of `{}` (`{}:{}`): a typed call, no JSON.\nfunc {}({}){ret} {{\n{body}}}\n",
835        e.name,
836        e.prototype.as_deref().unwrap_or(&e.name),
837        e.file,
838        e.line,
839        e.name,
840        params
841    )
842}
843
844/// The typed `extern "C"` functions for `lib.rs`. Status: 0 ok, 1 error (message in `err`,
845/// freed with `rust_anything_free`), 2 the string result needs `*out_len` bytes.
846pub fn typed_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
847    let mut out = String::from(
848        r#"
849/// The port's result, or its error message; a panic becomes an error.
850#[allow(dead_code)]
851fn run<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
852    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
853        let text = panic
854            .downcast_ref::<&str>()
855            .map(ToString::to_string)
856            .or_else(|| panic.downcast_ref::<String>().cloned())
857            .unwrap_or_default();
858        Err(format!("Rust panic: {text}"))
859    })
860}
861
862/// A Go string argument.
863///
864/// # Safety
865///
866/// `ptr` points at `len` readable bytes, or `len` is 0.
867#[allow(dead_code)]
868// SAFETY: unsafe to call; callers uphold the contract above.
869unsafe fn go_str(ptr: *const u8, len: usize) -> String {
870    if len == 0 {
871        return String::new();
872    }
873    // SAFETY: the caller passes a Go string's bytes and its length (see above).
874    String::from_utf8_lossy(unsafe { std::slice::from_raw_parts(ptr, len) }).into_owned()
875}
876
877/// Reports an error through `err`.
878///
879/// # Safety
880///
881/// `err` is a valid pointer to write to.
882#[allow(dead_code)]
883// SAFETY: unsafe to call; callers uphold the contract above.
884unsafe fn fail(err: *mut *mut c_char, message: String) -> i32 {
885    let message = CString::new(message.replace('\0', " ")).unwrap_or_default();
886    // SAFETY: `err` is a valid out-pointer (see above).
887    unsafe { *err = message.into_raw() };
888    1
889}
890"#,
891    );
892    for f in &api.functions {
893        let Some(e) = typed(m, f) else { continue };
894        let mut params = Vec::new();
895        let mut convert = String::new();
896        let mut args = Vec::new();
897        for (index, p) in e.params.iter().enumerate() {
898            let name = format!("ra_arg{index}");
899            let t = typed_type(p.native_type.as_deref().unwrap_or_default()).expect("typed");
900            if t.c == "string" {
901                params.push(format!("{name}_ptr: *const u8, {name}_len: usize"));
902                let _ = writeln!(
903                    convert,
904                    "    // SAFETY: Go passes the string's bytes and length.\n    let {name} = unsafe {{ go_str({name}_ptr, {name}_len) }};"
905                );
906            } else {
907                params.push(format!("{name}: {}", t.rust));
908            }
909            args.push(name);
910        }
911        let rt = results(e).0.first().and_then(|r| typed_type(r));
912        match rt.as_ref().map(|t| t.c) {
913            Some("string") => {
914                params.push("out: *mut u8, out_cap: usize, out_len: *mut usize".into())
915            }
916            Some(_) => params.push(format!(
917                "out: *mut {}",
918                rt.as_ref().map_or("i64", |t| t.rust)
919            )),
920            None => {}
921        }
922        params.push("err: *mut *mut c_char".into());
923        let call = format!("port::{}({})", f.rust_name, args.join(", "));
924        let call = if f.fallible {
925            call
926        } else {
927            format!("Ok({call})")
928        };
929        let ok = match rt.as_ref().map(|t| t.c) {
930            Some("string") => "{\n            let bytes = value.as_bytes();\n            \
931                // SAFETY: Go passes a buffer of `out_cap` bytes and a valid `out_len`.\n            \
932                unsafe {\n                *out_len = bytes.len();\n                if bytes.len() > out_cap {\n                    \
933                return 2;\n                }\n                std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());\n            }\n            0\n        }".to_string(),
934            Some(_) => "{\n            // SAFETY: Go passes a valid `out`.\n            unsafe { *out = value };\n            0\n        }".to_string(),
935            None => "{\n            let () = value;\n            0\n        }".to_string(),
936        };
937        let _ = writeln!(
938            out,
939            "\n/// `{proto}`: a typed call.\n///\n/// # Safety\n///\n/// Called by the generated Go wrapper with valid pointers.\n\
940             // SAFETY: exported unmangled under a name only rust-anything defines.\n#[unsafe(no_mangle)]\n\
941             // SAFETY: callers uphold the contract under `# Safety`.\n\
942             pub unsafe extern \"C\" fn rust_anything_t_{name}({params}) -> i32 {{\n{convert}    \
943             match run(|| {call}) {{\n        Ok(value) => {ok}\n        \
944             // SAFETY: Go passes a valid `err`.\n        Err(message) => unsafe {{ fail(err, message) }},\n    }}\n}}",
945            proto = e.prototype.as_deref().unwrap_or(&e.name),
946            name = f.js_name,
947            params = params.join(", "),
948        );
949    }
950    out
951}
952
953// ---- the binary wire: lists, maps, structs and several results, without JSON ----------------
954
955use crate::wire::Ty;
956
957/// The wire type of a Go type; `None` for types the wire does not carry.
958fn go_ty(go: &str, sources: &[String], depth: usize) -> Option<Ty> {
959    let go = go.trim();
960    if depth > 8 {
961        return None;
962    }
963    if let Some(t) = typed_type(go) {
964        return Some(match t.c {
965            "int64_t" => Ty::I64(go.into()),
966            "double" => Ty::F64(go.into()),
967            "bool" => Ty::Bool,
968            _ => Ty::Str,
969        });
970    }
971    if let Some(item) = go.strip_prefix("[]") {
972        return Some(Ty::List {
973            item: Box::new(go_ty(item, sources, depth + 1)?),
974            native: go.into(),
975            array: false,
976        });
977    }
978    if let Some(rest) = go.strip_prefix("map[string]") {
979        return Some(Ty::Map {
980            value: Box::new(go_ty(rest, sources, depth + 1)?),
981            native: go.into(),
982        });
983    }
984    if go.starts_with(char::is_uppercase) && !go.contains(['.', '[', '*']) {
985        let fields = crate::lang::go::struct_fields(sources, go)?;
986        let fields = fields
987            .into_iter()
988            .map(|(f, t, key)| Some((f, key, go_ty(&t, sources, depth + 1)?)))
989            .collect::<Option<Vec<_>>>()?;
990        return Some(Ty::Struct {
991            name: go.into(),
992            fields,
993        });
994    }
995    None
996}
997
998/// The parameter and result wire types of an export, when the wire carries all of them.
999/// A wire export: the export, its parameter and result wire types, and its Rust code.
1000type WireFn<'m> = (&'m ExportedFn, Vec<(String, Ty)>, Option<Ty>, String);
1001
1002/// Wire types of an export's parameters, and of its result.
1003type WireSig = (Vec<(String, Ty)>, Option<Ty>);
1004
1005fn wire_sig(e: &ExportedFn, sources: &[String]) -> Option<WireSig> {
1006    let params = e
1007        .params
1008        .iter()
1009        .map(|p| {
1010            Some((
1011                p.name.clone(),
1012                go_ty(p.native_type.as_deref()?, sources, 0)?,
1013            ))
1014        })
1015        .collect::<Option<Vec<_>>>()?;
1016    let (results, _) = results(e);
1017    let result = match results.len() {
1018        0 => None,
1019        1 => Some(go_ty(&results[0], sources, 0)?),
1020        _ => Some(Ty::Tuple(
1021            results
1022                .iter()
1023                .map(|r| go_ty(r, sources, 0))
1024                .collect::<Option<Vec<_>>>()?,
1025        )),
1026    };
1027    Some((params, result))
1028}
1029
1030/// Go statements appending `expr` of type `t` to the byte slice `b`.
1031fn go_enc(expr: &str, t: &Ty, depth: usize) -> String {
1032    let v = format!("v{depth}");
1033    match t {
1034        Ty::I64(_) => format!("cwb = cwI64(cwb, int64({expr}))\n"),
1035        Ty::F64(_) => format!("cwb = cwF64(cwb, float64({expr}))\n"),
1036        Ty::Bool => format!("cwb = cwBool(cwb, {expr})\n"),
1037        Ty::Str => format!("cwb = cwStr(cwb, {expr})\n"),
1038        Ty::List { item, .. } => format!(
1039            "if {expr} == nil {{\ncwb = append(cwb, 0)\n}} else {{\ncwb = append(cwb, 1)\ncwb = cwU32(cwb, len({expr}))\nfor _, {v} := range {expr} {{\n{}}}\n}}\n",
1040            go_enc(&v, item, depth + 1)
1041        ),
1042        Ty::Map { value, .. } => format!(
1043            "if {expr} == nil {{\ncwb = append(cwb, 0)\n}} else {{\ncwb = append(cwb, 1)\ncwb = cwU32(cwb, len({expr}))\nfor k{depth}, {v} := range {expr} {{\ncwb = cwStr(cwb, k{depth})\n{}}}\n}}\n",
1044            go_enc(&v, value, depth + 1)
1045        ),
1046        Ty::Struct { fields, .. } => {
1047            let mut out = String::from("cwb = append(cwb, 1)\n");
1048            for (field, _, ft) in fields {
1049                out.push_str(&go_enc(&format!("{expr}.{field}"), ft, depth + 1));
1050            }
1051            out
1052        }
1053        Ty::Opt { inner, .. } => go_enc(expr, inner, depth),
1054        // Tuples are handled by the caller; JS-only types never come from Go.
1055        _ => String::new(),
1056    }
1057}
1058
1059/// Go statements decoding a value of type `t` from reader `r` into `target`.
1060fn go_dec(target: &str, t: &Ty, depth: usize) -> String {
1061    match t {
1062        Ty::I64(native) => format!("{target} = {native}(cwr.i64())\n"),
1063        Ty::F64(native) => format!("{target} = {native}(cwr.f64())\n"),
1064        Ty::Bool => format!("{target} = cwr.bool()\n"),
1065        Ty::Str => format!("{target} = cwr.str()\n"),
1066        Ty::List { item, native, .. } => format!(
1067            "if cwr.u8() == 1 {{\nn{depth} := cwr.u32()\n{target} = make({native}, n{depth})\nfor i{depth} := range {target} {{\n{}}}\n}}\n",
1068            go_dec(&format!("{target}[i{depth}]"), item, depth + 1)
1069        ),
1070        Ty::Map { value, native } => {
1071            let item = native.strip_prefix("map[string]").unwrap_or("any");
1072            format!(
1073                "if cwr.u8() == 1 {{\nn{depth} := cwr.u32()\n{target} = make({native}, n{depth})\nfor j{depth} := 0; j{depth} < n{depth}; j{depth}++ {{\nk{depth} := cwr.str()\nvar v{depth} {item}\n{}{target}[k{depth}] = v{depth}\n}}\n}}\n",
1074                go_dec(&format!("v{depth}"), value, depth + 1)
1075            )
1076        }
1077        Ty::Struct { fields, .. } => {
1078            let mut out = String::from("if cwr.u8() == 1 {\n");
1079            for (field, _, ft) in fields {
1080                out.push_str(&go_dec(&format!("{target}.{field}"), ft, depth + 1));
1081            }
1082            out.push_str("}\n");
1083            out
1084        }
1085        Ty::Opt { inner, .. } => go_dec(target, inner, depth),
1086        // Tuples are handled by the caller; JS-only types never come from Go.
1087        _ => String::new(),
1088    }
1089}
1090
1091const WIRE_HELPERS_GO: &str = r#"
1092// The binary wire: little endian; strings, slices, maps and structs start with 0 for nil.
1093func cwU32(b []byte, n int) []byte { return binary.LittleEndian.AppendUint32(b, uint32(n)) }
1094func cwI64(b []byte, v int64) []byte { return binary.LittleEndian.AppendUint64(b, uint64(v)) }
1095func cwF64(b []byte, v float64) []byte {
1096	return binary.LittleEndian.AppendUint64(b, math.Float64bits(v))
1097}
1098func cwBool(b []byte, v bool) []byte {
1099	if v {
1100		return append(b, 1)
1101	}
1102	return append(b, 0)
1103}
1104func cwStr(b []byte, s string) []byte {
1105	b = append(b, 1)
1106	b = cwU32(b, len(s))
1107	return append(b, s...)
1108}
1109
1110type cwReader struct {
1111	b []byte
1112	i int
1113}
1114
1115func (r *cwReader) u8() byte {
1116	v := r.b[r.i]
1117	r.i++
1118	return v
1119}
1120func (r *cwReader) u32() int {
1121	v := binary.LittleEndian.Uint32(r.b[r.i:])
1122	r.i += 4
1123	return int(v)
1124}
1125func (r *cwReader) i64() int64 {
1126	v := binary.LittleEndian.Uint64(r.b[r.i:])
1127	r.i += 8
1128	return int64(v)
1129}
1130func (r *cwReader) f64() float64 { return math.Float64frombits(uint64(r.i64())) }
1131func (r *cwReader) bool() bool   { return r.u8() != 0 }
1132func (r *cwReader) str() string {
1133	if r.u8() == 0 {
1134		return ""
1135	}
1136	n := r.u32()
1137	s := string(r.b[r.i : r.i+n])
1138	r.i += n
1139	return s
1140}
1141
1142func cwPtr(b []byte) *C.uint8_t {
1143	if len(b) == 0 {
1144		return nil
1145	}
1146	return (*C.uint8_t)(unsafe.Pointer(&b[0]))
1147}
1148"#;
1149
1150/// The Go wrapper function of a wire export: encode the arguments, one cgo call, decode.
1151fn wire_go(e: &ExportedFn, params: &[(String, Ty)], result: Option<&Ty>) -> String {
1152    let (results, fallible) = results(e);
1153    let sig_params = wrapper_params(e);
1154    let mut sig_results = results.clone();
1155    if fallible {
1156        sig_results.push("error".into());
1157    }
1158    let ret = match sig_results.len() {
1159        0 => String::new(),
1160        1 => format!(" {}", sig_results[0]),
1161        _ => format!(" ({})", sig_results.join(", ")),
1162    };
1163    let mut body = String::from("\tcwb := make([]byte, 0, 128)\n");
1164    for (index, (_, t)) in params.iter().enumerate() {
1165        body.push_str(&go_enc(&wrapper_arg(index), t, 0));
1166    }
1167    let names: Vec<String> = (0..results.len()).map(|i| format!("r{i}")).collect();
1168    for (i, r) in results.iter().enumerate() {
1169        let _ = writeln!(body, "\tvar r{i} {r}");
1170    }
1171    let call = |buf: &str| {
1172        format!(
1173            "C.rust_anything_w_{}(cwPtr(cwb), C.size_t(len(cwb)), (*C.uint8_t)(unsafe.Pointer(&{buf}[0])), C.size_t(len({buf})), &n, &errp)",
1174            e.name
1175        )
1176    };
1177    let _ = writeln!(
1178        body,
1179        "\tvar cwStack [512]byte\n\tcwOut := cwStack[:]\n\tvar n C.size_t\n\tvar errp *C.char\n\tstatus := {}\n\
1180         \tif status == 2 {{\n\t\tcwOut = make([]byte, int(n))\n\t\tstatus = {}\n\t}}",
1181        call("cwOut"),
1182        call("cwOut")
1183    );
1184    let mut fail_ret: Vec<String> = names.clone();
1185    if fallible {
1186        fail_ret.push("rustAnythingToErr(rustAnythingErr(errp))".into());
1187        let _ = writeln!(
1188            body,
1189            "\tif status == 1 {{\n\t\treturn {}\n\t}}",
1190            fail_ret.join(", ")
1191        );
1192    } else {
1193        body.push_str("\tif status == 1 {\n\t\tpanic(rustAnythingErr(errp))\n\t}\n");
1194    }
1195    if !results.is_empty() {
1196        body.push_str("\tcwr := &cwReader{b: cwOut[:n]}\n");
1197        match result {
1198            Some(Ty::Tuple(items)) => {
1199                for (i, t) in items.iter().enumerate() {
1200                    body.push_str(&go_dec(&format!("r{i}"), t, 0));
1201                }
1202            }
1203            Some(t) => body.push_str(&go_dec("r0", t, 0)),
1204            None => {}
1205        }
1206    }
1207    let mut ok = names;
1208    if fallible {
1209        ok.push("nil".into());
1210    }
1211    if !ok.is_empty() {
1212        let _ = writeln!(body, "\treturn {}", ok.join(", "));
1213    }
1214    format!(
1215        "\n// {} is the Rust port of `{}` (`{}:{}`): binary wire, no JSON.\nfunc {}({}){ret} {{\n{body}}}\n",
1216        e.name,
1217        e.prototype.as_deref().unwrap_or(&e.name),
1218        e.file,
1219        e.line,
1220        e.name,
1221        sig_params
1222    )
1223}
1224
1225/// The exports that cross the binary wire (not typed, but every type fits the wire and the port).
1226fn wire_fns<'m>(m: &'m Manifest, api: &crate::codegen::PortApi) -> Vec<WireFn<'m>> {
1227    let sources = unit_sources(m);
1228    let mut out = Vec::new();
1229    for f in &api.functions {
1230        if typed(m, f).is_some() {
1231            continue;
1232        }
1233        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
1234            continue;
1235        };
1236        let Some((params, result)) = wire_sig(e, &sources) else {
1237            continue;
1238        };
1239        if params.len() != f.params.len() {
1240            continue;
1241        }
1242        if let Some(code) = wire_rs_fn(f, e, &params, result.as_ref()) {
1243            out.push((e, params, result, code));
1244        }
1245    }
1246    out
1247}
1248
1249/// The Rust `extern "C"` function of a wire export, with its schema statics.
1250fn wire_rs_fn(
1251    f: &crate::codegen::PortFn,
1252    e: &ExportedFn,
1253    params: &[(String, Ty)],
1254    result: Option<&Ty>,
1255) -> Option<String> {
1256    let mut statics = String::new();
1257    let prefix = format!("S_{}", f.js_name.to_uppercase());
1258    let bindings: Vec<_> = f
1259        .params
1260        .iter()
1261        .enumerate()
1262        .map(|(index, (_, ty))| (format!("ra_arg{index}"), ty.clone()))
1263        .collect();
1264    let reads = crate::wire::rust_read_args(params, &bindings, &prefix, &mut statics)?;
1265    let args: Vec<&str> = bindings.iter().map(|(n, _)| n.as_str()).collect();
1266    let call = format!("port::{}({})", f.rust_name, args.join(", "));
1267    let call = if f.fallible { format!("{call}?") } else { call };
1268    let write = match result {
1269        None => {
1270            if f.ret != "()" {
1271                return None;
1272            }
1273            format!("        let () = {call};\n")
1274        }
1275        Some(t) => {
1276            let schema = format!("{prefix}_OUT");
1277            let w = crate::wire::rust_write(t, &f.ret, "out", &schema, 0)?;
1278            if w.contains(&schema) {
1279                let _ = writeln!(
1280                    statics,
1281                    "static {schema}: wire::Schema = {};",
1282                    crate::wire::schema_expr(t)
1283                );
1284            }
1285            format!("        let out = &{call};\n        {w}\n")
1286        }
1287    };
1288    Some(format!(
1289        "\n{statics}\n/// `{proto}`: binary wire.\n///\n/// # Safety\n///\n/// Called by the generated Go wrapper with valid pointers.\n\
1290         // SAFETY: exported unmangled under a name only rust-anything defines.\n#[unsafe(no_mangle)]\n\
1291         // SAFETY: callers uphold the contract under `# Safety`.\n\
1292         pub unsafe extern \"C\" fn rust_anything_w_{name}(in_ptr: *const u8, in_len: usize, out: *mut u8, out_cap: usize, out_len: *mut usize, err: *mut *mut c_char) -> i32 {{\n    \
1293         let input: &[u8] = if in_len == 0 {{\n        &[]\n    }} else {{\n        \
1294         // SAFETY: Go passes its buffer and length.\n        unsafe {{ std::slice::from_raw_parts(in_ptr, in_len) }}\n    }};\n    \
1295         let result = run(|| {{\n        let r = &mut wire::Reader::new(input);\n{reads}        let w = &mut wire::Writer::default();\n{write}        \
1296         Ok(std::mem::take(&mut w.0))\n    }});\n    \
1297         match result {{\n        Ok(bytes) => {{\n            \
1298         // SAFETY: Go passes a buffer of `out_cap` bytes and a valid `out_len`.\n            unsafe {{\n                \
1299         *out_len = bytes.len();\n                if bytes.len() > out_cap {{\n                    return 2;\n                }}\n                \
1300         std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());\n            }}\n            0\n        }}\n        \
1301         // SAFETY: Go passes a valid `err`.\n        Err(message) => unsafe {{ fail(err, message) }},\n    }}\n}}",
1302        proto = e.prototype.as_deref().unwrap_or(&e.name),
1303        name = f.js_name,
1304    ))
1305}
1306
1307/// Rust code of every wire export, for `lib.rs`.
1308pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1309    wire_fns(m, api)
1310        .into_iter()
1311        .map(|(_, _, _, code)| code)
1312        .collect()
1313}
1314
1315/// A `main` package that calls `import_path`'s functions by name: record, diff and bench.
1316pub fn driver(m: &Manifest, import_path: &str) -> String {
1317    let mut cases = String::new();
1318    let mut prepares = String::new();
1319    for f in &m.exports {
1320        let (results, fallible) = results(f);
1321        let _ = writeln!(cases, "\tcase \"{}\":", f.name);
1322        let mut args = Vec::new();
1323        for (i, p) in f.params.iter().enumerate() {
1324            let t = qualify(p.native_type.as_deref().unwrap_or("any"));
1325            let _ = writeln!(
1326                cases,
1327                "\t\tvar a{i} {t}\n\t\tif rustAnythingDecode(argAt(args, {i}), &a{i}) != nil {{\n\t\t\treturn invalid\n\t\t}}"
1328            );
1329            args.push(format!("a{i}"));
1330        }
1331        let _ = writeln!(prepares, "\tcase \"{}\":", f.name);
1332        for (i, p) in f.params.iter().enumerate() {
1333            let t = qualify(p.native_type.as_deref().unwrap_or("any"));
1334            let _ = writeln!(
1335                prepares,
1336                "\t\tvar a{i} {t}\n\t\tif rustAnythingDecode(argAt(args, {i}), &a{i}) != nil {{\n\t\t\treturn nil\n\t\t}}"
1337            );
1338        }
1339        let _ = writeln!(
1340            prepares,
1341            "\t\treturn func() {{ pkg.{}({}) }}",
1342            f.name,
1343            args.join(", ")
1344        );
1345        let mut lhs: Vec<String> = (0..results.len()).map(|i| format!("r{i}")).collect();
1346        if fallible {
1347            lhs.push("err".into());
1348        }
1349        let call = format!("pkg.{}({})", f.name, args.join(", "));
1350        if lhs.is_empty() {
1351            let _ = writeln!(cases, "\t\t{call}");
1352        } else {
1353            let _ = writeln!(cases, "\t\t{} := {call}", lhs.join(", "));
1354        }
1355        if fallible {
1356            cases.push_str(
1357                "\t\tif err != nil {\n\t\t\tres := map[string]any{\"error\": err.Error()}\n\t\t\tif s := rustAnythingSentinelName(err); s != \"\" {\n\t\t\t\tres[\"sentinel\"] = s\n\t\t\t}\n\t\t\treturn res\n\t\t}\n",
1358            );
1359        }
1360        let ok = match results.len() {
1361            0 => "nil".to_string(),
1362            1 => "rustAnythingEncode(r0)".to_string(),
1363            n => format!(
1364                "[]any{{{}}}",
1365                (0..n)
1366                    .map(|i| format!("rustAnythingEncode(r{i})"))
1367                    .collect::<Vec<_>>()
1368                    .join(", ")
1369            ),
1370        };
1371        let _ = writeln!(cases, "\t\treturn map[string]any{{\"ok\": {ok}}}");
1372    }
1373    let sentinels = crate::lang::go::sentinel_errors(&sentinel_sources(m));
1374    let mut sentinel_fn = String::from("func rustAnythingSentinelName(err error) string {\n");
1375    for s in &sentinels {
1376        let name_q = serde_json::to_string(&s.name).unwrap_or_else(|_| format!("{:?}", s.name));
1377        let _ = writeln!(
1378            sentinel_fn,
1379            "\tif errors.Is(err, pkg.{}) {{\n\t\treturn {name_q}\n\t}}",
1380            s.name
1381        );
1382    }
1383    sentinel_fn.push_str("\treturn \"\"\n}\n");
1384    DRIVER_GO
1385        .replace("IMPORT_PATH", import_path)
1386        .replace("// CASES\n", &cases)
1387        .replace("// PREPARES\n", &prepares)
1388        .replace("// SENTINELS\n", &sentinel_fn)
1389        .replace("// HELPERS\n", HELPERS_GO)
1390}
1391
1392const DRIVER_GO: &str = r#"// Generated by rust-anything: calls the package's functions by name.
1393package main
1394
1395import (
1396	"bufio"
1397	"bytes"
1398	"encoding/json"
1399	"errors"
1400	"fmt"
1401	"math"
1402	"os"
1403	"strings"
1404	"time"
1405
1406	pkg "IMPORT_PATH"
1407)
1408
1409var _ = errors.New
1410
1411// SENTINELS
1412
1413// HELPERS
1414
1415var invalid = map[string]any{"invalid": true}
1416
1417func argAt(args []json.RawMessage, i int) json.RawMessage {
1418	if i < len(args) {
1419		return args[i]
1420	}
1421	return nil
1422}
1423
1424func call(name string, args []json.RawMessage) (out map[string]any) {
1425	defer func() {
1426		if r := recover(); r != nil {
1427			out = map[string]any{"panic": fmt.Sprint(r)}
1428		}
1429	}()
1430	switch name {
1431	// CASES
1432	}
1433	return map[string]any{"missing": name}
1434}
1435
1436// prepare decodes a case's arguments once and returns the bare call; nil if they do not fit.
1437func prepare(name string, args []json.RawMessage) func() {
1438	switch name {
1439	// PREPARES
1440	}
1441	return nil
1442}
1443
1444type input struct {
1445	Fn   string            `json:"fn"`
1446	Args []json.RawMessage `json:"args"`
1447}
1448
1449// canon re-encodes a JSON value with exact numbers, so equal values compare equal as text.
1450func canon(v any) string {
1451	text, err := json.Marshal(v)
1452	if err != nil {
1453		return "unencodable: " + err.Error()
1454	}
1455	d := json.NewDecoder(bytes.NewReader(text))
1456	d.UseNumber()
1457	var x any
1458	if err := d.Decode(&x); err != nil {
1459		return string(text)
1460	}
1461	out, _ := json.Marshal(x)
1462	return string(out)
1463}
1464
1465func record(inputs, out string) {
1466	data, err := os.ReadFile(inputs)
1467	if err != nil {
1468		panic(err)
1469	}
1470	var cases []input
1471	if err := json.Unmarshal(data, &cases); err != nil {
1472		panic(err)
1473	}
1474	f, err := os.Create(out)
1475	if err != nil {
1476		panic(err)
1477	}
1478	defer f.Close()
1479	w := bufio.NewWriter(f)
1480	defer w.Flush()
1481	progress := os.Getenv("RUST_ANYTHING_PROGRESS")
1482	for index, c := range cases {
1483		if progress != "" {
1484			if p, err := os.OpenFile(progress, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
1485				fmt.Fprintln(p, index)
1486				p.Close()
1487			}
1488		}
1489		result := call(c.Fn, c.Args)
1490		if result["invalid"] != nil {
1491			continue
1492		}
1493		line := map[string]any{"fn": c.Fn, "args": c.Args}
1494		for k, v := range result {
1495			line[k] = v
1496		}
1497		text, err := json.Marshal(line)
1498		if err != nil {
1499			continue
1500		}
1501		w.Write(text)
1502		w.WriteByte('\n')
1503		w.Flush()
1504	}
1505}
1506
1507func readCases(path string) []map[string]json.RawMessage {
1508	data, err := os.ReadFile(path)
1509	if err != nil {
1510		panic(err)
1511	}
1512	var out []map[string]json.RawMessage
1513	for _, line := range bytes.Split(data, []byte("\n")) {
1514		if len(bytes.TrimSpace(line)) == 0 {
1515			continue
1516		}
1517		var c map[string]json.RawMessage
1518		if err := json.Unmarshal(line, &c); err != nil {
1519			panic(err)
1520		}
1521		out = append(out, c)
1522	}
1523	return out
1524}
1525
1526func argsOf(c map[string]json.RawMessage) (string, []json.RawMessage) {
1527	var name string
1528	var args []json.RawMessage
1529	json.Unmarshal(c["fn"], &name)
1530	json.Unmarshal(c["args"], &args)
1531	return name, args
1532}
1533
1534func diff(cases, out string) {
1535	summary := map[string]any{"total": 0, "passed": 0, "failed": 0}
1536	missing := []string{}
1537	mismatches := []any{}
1538	total, passed, failed := 0, 0, 0
1539	for _, c := range readCases(cases) {
1540		total++
1541		name, args := argsOf(c)
1542		got := call(name, args)
1543		if got["missing"] != nil {
1544			failed++
1545			missing = append(missing, name)
1546			continue
1547		}
1548		expected := map[string]any{}
1549		for _, k := range []string{"ok", "error", "sentinel", "panic"} {
1550			if raw, ok := c[k]; ok {
1551				expected[k] = raw
1552			}
1553		}
1554		if _, ok := c["sentinel"]; !ok {
1555			delete(got, "sentinel")
1556		}
1557		same := false
1558		if p, ok := got["panic"]; ok && strings.Contains(fmt.Sprint(p), "Rust panic:") {
1559			same = false
1560		} else if _, ok := expected["panic"]; ok {
1561			// Panic messages differ between Go and Rust; that it panicked is the behavior.
1562			_, same = got["panic"]
1563		} else {
1564			same = canon(expected) == canon(got)
1565		}
1566		if same {
1567			passed++
1568		} else {
1569			failed++
1570			mismatches = append(mismatches, map[string]any{"fn": name, "args": args, "expected": expected, "actual": got})
1571		}
1572	}
1573	summary["total"], summary["passed"], summary["failed"] = total, passed, failed
1574	summary["missing"], summary["mismatches"] = missing, mismatches
1575	text, _ := json.Marshal(summary)
1576	os.WriteFile(out, text, 0o644)
1577}
1578
1579func bench(cases, out string, minMs int) {
1580	groups := map[string][][]json.RawMessage{}
1581	order := []string{}
1582	for _, c := range readCases(cases) {
1583		name, args := argsOf(c)
1584		if _, ok := groups[name]; !ok {
1585			order = append(order, name)
1586		}
1587		groups[name] = append(groups[name], args)
1588	}
1589	result := map[string]any{}
1590	for _, name := range order {
1591		// Arguments are decoded once: only the calls are timed.
1592		var calls []func()
1593		for _, args := range groups[name] {
1594			if f := prepare(name, args); f != nil {
1595				calls = append(calls, f)
1596			}
1597		}
1598		if len(calls) == 0 {
1599			continue
1600		}
1601		once := func() {
1602			for _, f := range calls {
1603				func() {
1604					defer func() { recover() }()
1605					f()
1606				}()
1607			}
1608		}
1609		once()
1610		passes, start := 0, time.Now()
1611		for {
1612			once()
1613			passes++
1614			if elapsed := time.Since(start); elapsed.Milliseconds() >= int64(minMs) {
1615				result[name] = map[string]any{"cases": len(calls), "ns": float64(elapsed.Nanoseconds()) / float64(passes*len(calls))}
1616				break
1617			}
1618		}
1619	}
1620	text, _ := json.Marshal(result)
1621	os.WriteFile(out, text, 0o644)
1622}
1623
1624func main() {
1625	switch os.Args[1] {
1626	case "record":
1627		record(os.Args[2], os.Args[3])
1628	case "diff":
1629		diff(os.Args[2], os.Args[3])
1630	case "bench":
1631		var ms int
1632		fmt.Sscan(os.Args[4], &ms)
1633		bench(os.Args[2], os.Args[3], ms)
1634	}
1635}
1636"#;
1637
1638/// A shadow package with the original's API: each call runs the original and the Rust port
1639/// (through the wrapper), returns the original's results and logs mismatches.
1640/// `RUST_ANYTHING_MODE=old` runs the original only, `new` the port only.
1641pub fn shadow(m: &Manifest, original: &str) -> String {
1642    let wrapper = crate::harness_go::wrapper_module(m);
1643    let sentinels = crate::lang::go::sentinel_errors(&sentinel_sources(m));
1644    let remap_sentinels = !sentinels.is_empty() && m.exports.iter().any(|f| results(f).1);
1645    let extra_imports = if remap_sentinels {
1646        "\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n"
1647    } else {
1648        ""
1649    };
1650    let mut out = format!(
1651        "// Package {pkg} runs the Go original and the Rust port of `{unit}` side by side. Generated\n\
1652         // by rust-anything: import it in place of {original}. RUST_ANYTHING_MODE=old|shadow|new.\n\
1653         package {pkg}\n\n\
1654         import (\n\t\"encoding/json\"\n{extra_imports}\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"sync/atomic\"\n\n\
1655         \torig \"{original}\"\n\tport \"{wrapper}\"\n)\n\n\
1656         var mode = func() string {{\n\tif m := os.Getenv(\"RUST_ANYTHING_MODE\"); m != \"\" {{\n\t\treturn m\n\t}}\n\treturn \"shadow\"\n}}()\n\n\
1657         // Calls and Mismatches count shadowed calls.\nvar Calls, Mismatches atomic.Int64\n\n\
1658         // convert moves a value between the original's and the wrapper's identical types.\n\
1659         func convert[T any](v any) T {{\n\tvar out T\n\tif text, err := json.Marshal(v); err == nil {{\n\t\t_ = json.Unmarshal(text, &out)\n\t}}\n\treturn out\n}}\n\n\
1660         func compare(name string, expected, actual []any) {{\n\tCalls.Add(1)\n\tif !reflect.DeepEqual(expected, actual) {{\n\
1661         \t\tif Mismatches.Add(1) <= 10 {{\n\t\t\tlog.Printf(\"[rust-anything] mismatch in %s: expected %v, got %v\", name, expected, actual)\n\t\t}}\n\t}}\n}}\n",
1662        pkg = package_name(m),
1663        unit = m.unit,
1664    );
1665    for t in used_types(m) {
1666        let _ = write!(
1667            out,
1668            "\n// {t} is the original's type.\ntype {t} = orig.{t}\n"
1669        );
1670    }
1671    for s in &sentinels {
1672        let _ = write!(
1673            out,
1674            "\n// {} is the original's sentinel error.\nvar {} = orig.{}\n",
1675            s.name, s.name, s.name
1676        );
1677    }
1678    if remap_sentinels {
1679        out.push_str(
1680            "\nfunc remapErr(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n",
1681        );
1682        for s in &sentinels {
1683            let n = &s.name;
1684            let _ = write!(
1685                out,
1686                "\tif err == port.{n} {{\n\t\treturn orig.{n}\n\t}}\n\
1687                 \tif errors.Is(err, port.{n}) {{\n\
1688                 \t\tmsg := err.Error()\n\
1689                 \t\ttext := port.{n}.Error()\n\
1690                 \t\tif prefix := text + \": \"; strings.HasPrefix(msg, prefix) {{\n\
1691                 \t\t\treturn fmt.Errorf(\"%w: %s\", orig.{n}, strings.TrimPrefix(msg, prefix))\n\
1692                 \t\t}}\n\
1693                 \t\tif suffix := \": \" + text; strings.HasSuffix(msg, suffix) {{\n\
1694                 \t\t\treturn fmt.Errorf(\"%s: %w\", strings.TrimSuffix(msg, suffix), orig.{n})\n\
1695                 \t\t}}\n\
1696                 \t\treturn orig.{n}\n\
1697                 \t}}\n"
1698            );
1699        }
1700        out.push_str("\treturn err\n}\n");
1701    }
1702    for f in &m.exports {
1703        let (results, fallible) = results(f);
1704        let params: Vec<String> = f
1705            .params
1706            .iter()
1707            .map(|p| format!("{} {}", p.name, p.native_type.as_deref().unwrap_or("any")))
1708            .collect();
1709        let mut all: Vec<String> = results.clone();
1710        if fallible {
1711            all.push("error".into());
1712        }
1713        let ret = match all.len() {
1714            0 => String::new(),
1715            1 => format!(" {}", all[0]),
1716            _ => format!(" ({})", all.join(", ")),
1717        };
1718        let names: Vec<String> = (0..all.len()).map(|i| format!("o{i}")).collect();
1719        let rust_names: Vec<String> = (0..all.len()).map(|i| format!("n{i}")).collect();
1720        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
1721        let port_args: Vec<String> = f
1722            .params
1723            .iter()
1724            .map(|p| {
1725                let t = p.native_type.as_deref().unwrap_or("any");
1726                if local_types(t).is_empty() {
1727                    p.name.clone()
1728                } else {
1729                    format!(
1730                        "convert[{}]({})",
1731                        qualify(t).replace("pkg.", "port."),
1732                        p.name
1733                    )
1734                }
1735            })
1736            .collect();
1737        let lhs = |v: &[String]| {
1738            if v.is_empty() {
1739                String::new()
1740            } else {
1741                format!("{} := ", v.join(", "))
1742            }
1743        };
1744        let back: Vec<String> = all
1745            .iter()
1746            .zip(&rust_names)
1747            .map(|(t, n)| {
1748                if t == "error" && remap_sentinels {
1749                    format!("remapErr({n})")
1750                } else if local_types(t).is_empty() {
1751                    n.clone()
1752                } else {
1753                    format!("convert[{t}]({n})")
1754                }
1755            })
1756            .collect();
1757        let errors_text = |v: &[String]| -> Vec<String> {
1758            v.iter()
1759                .zip(&all)
1760                .map(|(n, t)| {
1761                    if t == "error" {
1762                        format!("errText({n})")
1763                    } else {
1764                        n.clone()
1765                    }
1766                })
1767                .collect()
1768        };
1769        let _ = writeln!(
1770            out,
1771            "\n// {} shadows the original `{}`.\nfunc {}({}){ret} {{",
1772            f.name,
1773            f.name,
1774            f.name,
1775            params.join(", ")
1776        );
1777        let ret_new = if all.is_empty() {
1778            String::new()
1779        } else {
1780            format!("return {}", back.join(", "))
1781        };
1782        let _ = writeln!(
1783            out,
1784            "\tif mode == \"new\" {{\n\t\t{}port.{}({})\n\t\t{ret_new}\n\t}}",
1785            lhs(&rust_names),
1786            f.name,
1787            port_args.join(", ")
1788        );
1789        let _ = writeln!(out, "\t{}orig.{}({})", lhs(&names), f.name, args.join(", "));
1790        let ret_old = if all.is_empty() {
1791            "return".to_string()
1792        } else {
1793            format!("return {}", names.join(", "))
1794        };
1795        let _ = writeln!(
1796            out,
1797            "\tif mode != \"old\" {{\n\t\tfunc() {{\n\t\t\tdefer func() {{\n\t\t\t\tif r := recover(); r != nil {{\n\
1798             \t\t\t\t\tcompare(\"{name}\", []any{{\"no panic\"}}, []any{{r}})\n\t\t\t\t}}\n\t\t\t}}()\n\
1799             \t\t\t{}port.{name}({})\n\t\t\tcompare(\"{name}\", []any{{{}}}, []any{{{}}})\n\t\t}}()\n\t}}\n\t{ret_old}\n}}",
1800            lhs(&rust_names),
1801            port_args.join(", "),
1802            errors_text(&names).join(", "),
1803            errors_text(&back).join(", "),
1804            name = f.name,
1805        );
1806    }
1807    out.push_str("\nfunc errText(err error) any {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn err.Error()\n}\n");
1808    out
1809}
1810
1811#[cfg(test)]
1812mod tests {
1813    use super::*;
1814
1815    #[test]
1816    fn go_codegen_reserves_its_own_bindings() {
1817        let exports = crate::lang::go::exports(
1818            "names.go",
1819            r#"package names
1820func Typed(out int, C string) int { return out + len(C) }
1821func Wire(cwb []int, r []int) []int { return append(cwb, r...) }
1822func Json(raw uint64) uint64 { return raw }"#,
1823        );
1824        let manifest = Manifest {
1825            schema: String::new(),
1826            root: std::path::PathBuf::new(),
1827            root_written: None,
1828            unit: "names.go".into(),
1829            language: crate::lang::Lang::Go,
1830            kind: crate::bridge::Kind::Ffi,
1831            crate_name: "names-rs".into(),
1832            exports,
1833            classes: vec![],
1834            js_only: vec![],
1835            batches: vec![],
1836            allocator: Default::default(),
1837            float_tolerance: None,
1838            ignore_key_order: false,
1839        };
1840        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
1841        crate::bridge::match_export_names(&manifest, &mut api);
1842        let go = wrapper(&manifest, &api);
1843        assert!(go.contains("func Typed(raArg0 int, raArg1 string) int {"));
1844        assert!(go.contains("C.rust_anything_t_Typed(C.int64_t(raArg0),"));
1845        assert!(go.contains("int64_t ra_arg0, const uint8_t *ra_arg1_ptr"));
1846        assert!(go.contains("func Wire(raArg0 []int, raArg1 []int) []int {"));
1847        assert!(go.contains("C.rust_anything_w_Wire(cwPtr(cwb)"));
1848        assert!(go.contains("func Json(raArg0 uint64) uint64 {"));
1849        assert!(go.contains(r#"raw, err := rustAnythingCall("Json", raArg0)"#));
1850        let typed = typed_rs(&manifest, &api);
1851        assert!(typed.contains("port::typed(ra_arg0, ra_arg1)"));
1852        let wire = wire_rs(&manifest, &api);
1853        assert!(wire.contains("port::wire(ra_arg0, ra_arg1)"));
1854    }
1855
1856    #[test]
1857    fn qualifies_local_types() {
1858        assert_eq!(qualify("[]Point"), "[]pkg.Point");
1859        assert_eq!(qualify("map[string]Point"), "map[string]pkg.Point");
1860        assert_eq!(qualify("time.Duration"), "time.Duration");
1861        assert_eq!(local_types("map[string][]Point"), ["Point"]);
1862    }
1863
1864    #[test]
1865    fn maps_sentinel_errors_in_wrapper_driver_and_shadow() {
1866        let dir =
1867            std::env::temp_dir().join(format!("rust-anything-go-sentinels-{}", std::process::id()));
1868        let _ = std::fs::remove_dir_all(&dir);
1869        std::fs::create_dir_all(dir.join("store")).unwrap();
1870        let src = r#"package store
1871
1872import "errors"
1873
1874var (
1875	ErrNotFound = errors.New("not found")
1876	ErrAlias    error = ErrNotFound
1877	ErrBadInput = errors.New("bad input")
1878)
1879
1880func Lookup(id int) (string, error) {
1881	if id < 0 {
1882		return "", ErrBadInput
1883	}
1884	return "", ErrNotFound
1885}
1886"#;
1887        std::fs::write(dir.join("store/store.go"), src).unwrap();
1888        // Platform-specific file for another OS must be excluded from sentinel discovery.
1889        let other_os = if host_goos() == "windows" {
1890            "linux"
1891        } else {
1892            "windows"
1893        };
1894        std::fs::write(
1895            dir.join(format!("store/errors_{other_os}.go")),
1896            "package store\nimport \"errors\"\nvar ErrOtherOS = errors.New(\"other\")\n",
1897        )
1898        .unwrap();
1899        let exports = crate::lang::go::exports("store/store.go", src);
1900        let manifest = Manifest {
1901            schema: String::new(),
1902            root: dir.clone(),
1903            root_written: None,
1904            unit: "store/".into(),
1905            language: crate::lang::Lang::Go,
1906            kind: crate::bridge::Kind::Ffi,
1907            crate_name: "store-rs".into(),
1908            exports,
1909            classes: vec![],
1910            js_only: vec![],
1911            batches: vec![],
1912            allocator: Default::default(),
1913            float_tolerance: None,
1914            ignore_key_order: false,
1915        };
1916        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
1917        crate::bridge::match_export_names(&manifest, &mut api);
1918
1919        let w = wrapper(&manifest, &api);
1920        assert!(
1921            w.contains("var ErrNotFound = errors.New(\"not found\")"),
1922            "{w}"
1923        );
1924        assert!(w.contains("var ErrAlias = ErrNotFound"), "{w}");
1925        assert!(
1926            w.contains("var ErrBadInput = errors.New(\"bad input\")"),
1927            "{w}"
1928        );
1929        assert!(!w.contains("ErrOtherOS"), "{w}");
1930        assert!(w.contains("hasText: true"), "{w}");
1931        assert!(
1932            w.contains("func rustAnythingToErr(msg string) error"),
1933            "{w}"
1934        );
1935        assert!(w.contains("fmt.Errorf(\"%w: %s\""), "{w}");
1936        assert!(
1937            w.contains("rustAnythingToErr(rustAnythingErr(errp))"),
1938            "{w}"
1939        );
1940        assert!(!w.contains("errors.New(rustAnythingErr(errp))"), "{w}");
1941
1942        let d = driver(&manifest, "example.com/app/store");
1943        assert!(d.contains("errors.Is(err, pkg.ErrNotFound)"), "{d}");
1944        assert!(!d.contains("ErrOtherOS"), "{d}");
1945        assert!(d.contains("res[\"sentinel\"] = s"), "{d}");
1946        assert!(d.contains("delete(got, \"sentinel\")"), "{d}");
1947
1948        let s = shadow(&manifest, "example.com/app/store");
1949        assert!(s.contains("var ErrNotFound = orig.ErrNotFound"), "{s}");
1950        assert!(s.contains("func remapErr(err error) error"), "{s}");
1951        assert!(s.contains("remapErr(n1)"), "{s}");
1952
1953        let _ = std::fs::remove_dir_all(&dir);
1954    }
1955
1956    #[test]
1957    fn diff_handles_legacy_cases_without_sentinel_and_rejects_plain_error() {
1958        if std::process::Command::new("go")
1959            .arg("version")
1960            .output()
1961            .is_err()
1962        {
1963            return;
1964        }
1965        let dir = std::env::temp_dir().join(format!(
1966            "rust-anything-go-sentinel-diff-{}",
1967            std::process::id()
1968        ));
1969        let _ = std::fs::remove_dir_all(&dir);
1970        std::fs::create_dir_all(dir.join("store")).unwrap();
1971        std::fs::create_dir_all(dir.join("drv")).unwrap();
1972
1973        let src = r#"package store
1974
1975import "errors"
1976
1977var ErrNotFound = errors.New("not found")
1978
1979func Lookup(id int) (string, error) {
1980	if id == 1 {
1981		return "", ErrNotFound
1982	}
1983	return "", errors.New("not found")
1984}
1985"#;
1986        std::fs::write(dir.join("go.mod"), "module example.com/app\n\ngo 1.22\n").unwrap();
1987        std::fs::write(dir.join("store/store.go"), src).unwrap();
1988
1989        let exports = crate::lang::go::exports("store/store.go", src);
1990        let manifest = Manifest {
1991            schema: String::new(),
1992            root: dir.clone(),
1993            root_written: None,
1994            unit: "store/".into(),
1995            language: crate::lang::Lang::Go,
1996            kind: crate::bridge::Kind::Ffi,
1997            crate_name: "store-rs".into(),
1998            exports,
1999            classes: vec![],
2000            js_only: vec![],
2001            batches: vec![],
2002            allocator: Default::default(),
2003            float_tolerance: None,
2004            ignore_key_order: false,
2005        };
2006        let drv = driver(&manifest, "example.com/app/store");
2007        std::fs::write(dir.join("drv/main.go"), drv).unwrap();
2008
2009        // 1) Legacy case (no "sentinel" key) passes even though Lookup(1) returns ErrNotFound.
2010        // 2) Recorded sentinel case passes when Lookup(1) returns ErrNotFound.
2011        // 3) Recorded sentinel case fails when Lookup(2) returns a plain error with the same text.
2012        let cases_path = dir.join("cases.jsonl");
2013        let out_path = dir.join("out.json");
2014        std::fs::write(
2015            &cases_path,
2016            concat!(
2017                "{\"fn\":\"Lookup\",\"args\":[1],\"error\":\"not found\"}\n",
2018                "{\"fn\":\"Lookup\",\"args\":[1],\"error\":\"not found\",\"sentinel\":\"ErrNotFound\"}\n",
2019                "{\"fn\":\"Lookup\",\"args\":[2],\"error\":\"not found\",\"sentinel\":\"ErrNotFound\"}\n",
2020            ),
2021        )
2022        .unwrap();
2023
2024        let status = std::process::Command::new("go")
2025            .current_dir(&dir)
2026            .args([
2027                "run",
2028                "./drv",
2029                "diff",
2030                cases_path.to_str().unwrap(),
2031                out_path.to_str().unwrap(),
2032            ])
2033            .status()
2034            .unwrap();
2035        assert!(status.success(), "go driver diff failed to run");
2036
2037        let summary: serde_json::Value =
2038            serde_json::from_str(&std::fs::read_to_string(&out_path).unwrap()).unwrap();
2039        assert_eq!(summary["total"], 3, "{summary}");
2040        assert_eq!(summary["passed"], 2, "{summary}");
2041        assert_eq!(summary["failed"], 1, "{summary}");
2042        let mismatches = summary["mismatches"].as_array().unwrap();
2043        assert_eq!(mismatches.len(), 1, "{summary}");
2044        assert_eq!(mismatches[0]["args"], serde_json::json!([2]), "{summary}");
2045        assert_eq!(
2046            mismatches[0]["expected"]["sentinel"], "ErrNotFound",
2047            "{summary}"
2048        );
2049        assert!(
2050            mismatches[0]["actual"].get("sentinel").is_none(),
2051            "{summary}"
2052        );
2053
2054        let _ = std::fs::remove_dir_all(&dir);
2055    }
2056}