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 run_call = if args.is_empty() && f.fallible {
925            format!("run(port::{})", f.rust_name)
926        } else if f.fallible {
927            format!("run(|| {call})")
928        } else {
929            format!("run(|| Ok({call}))")
930        };
931        let ok = match rt.as_ref().map(|t| t.c) {
932            Some("string") => "{\n            let bytes = value.as_bytes();\n            \
933                // SAFETY: Go passes a buffer of `out_cap` bytes and a valid `out_len`.\n            \
934                unsafe {\n                *out_len = bytes.len();\n                if bytes.len() > out_cap {\n                    \
935                return 2;\n                }\n                std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());\n            }\n            0\n        }".to_string(),
936            Some(_) => "{\n            // SAFETY: Go passes a valid `out`.\n            unsafe { *out = value };\n            0\n        }".to_string(),
937            None => "{\n            let () = value;\n            0\n        }".to_string(),
938        };
939        let _ = writeln!(
940            out,
941            "\n/// `{proto}`: a typed call.\n///\n/// # Safety\n///\n/// Called by the generated Go wrapper with valid pointers.\n\
942             // SAFETY: exported unmangled under a name only rust-anything defines.\n#[unsafe(no_mangle)]\n\
943             // SAFETY: callers uphold the contract under `# Safety`.\n\
944             pub unsafe extern \"C\" fn rust_anything_t_{name}({params}) -> i32 {{\n{convert}    \
945             match {run_call} {{\n        Ok(value) => {ok}\n        \
946             // SAFETY: Go passes a valid `err`.\n        Err(message) => unsafe {{ fail(err, message) }},\n    }}\n}}",
947            proto = e.prototype.as_deref().unwrap_or(&e.name),
948            name = f.js_name,
949            params = params.join(", "),
950        );
951    }
952    out
953}
954
955// ---- the binary wire: lists, maps, structs and several results, without JSON ----------------
956
957use crate::wire::Ty;
958
959/// The wire type of a Go type; `None` for types the wire does not carry.
960fn go_ty(go: &str, sources: &[String], depth: usize) -> Option<Ty> {
961    let go = go.trim();
962    if depth > 8 {
963        return None;
964    }
965    if let Some(t) = typed_type(go) {
966        return Some(match t.c {
967            "int64_t" => Ty::I64(go.into()),
968            "double" => Ty::F64(go.into()),
969            "bool" => Ty::Bool,
970            _ => Ty::Str,
971        });
972    }
973    if let Some(item) = go.strip_prefix("[]") {
974        return Some(Ty::List {
975            item: Box::new(go_ty(item, sources, depth + 1)?),
976            native: go.into(),
977            array: false,
978        });
979    }
980    if let Some(rest) = go.strip_prefix("map[string]") {
981        return Some(Ty::Map {
982            value: Box::new(go_ty(rest, sources, depth + 1)?),
983            native: go.into(),
984        });
985    }
986    if go.starts_with(char::is_uppercase) && !go.contains(['.', '[', '*']) {
987        let fields = crate::lang::go::struct_fields(sources, go)?;
988        let fields = fields
989            .into_iter()
990            .map(|(f, t, key)| Some((f, key, go_ty(&t, sources, depth + 1)?)))
991            .collect::<Option<Vec<_>>>()?;
992        return Some(Ty::Struct {
993            name: go.into(),
994            fields,
995        });
996    }
997    None
998}
999
1000/// The parameter and result wire types of an export, when the wire carries all of them.
1001/// A wire export: the export, its parameter and result wire types, and its Rust code.
1002type WireFn<'m> = (&'m ExportedFn, Vec<(String, Ty)>, Option<Ty>, String);
1003
1004/// Wire types of an export's parameters, and of its result.
1005type WireSig = (Vec<(String, Ty)>, Option<Ty>);
1006
1007fn wire_sig(e: &ExportedFn, sources: &[String]) -> Option<WireSig> {
1008    let params = e
1009        .params
1010        .iter()
1011        .map(|p| {
1012            Some((
1013                p.name.clone(),
1014                go_ty(p.native_type.as_deref()?, sources, 0)?,
1015            ))
1016        })
1017        .collect::<Option<Vec<_>>>()?;
1018    let (results, _) = results(e);
1019    let result = match results.len() {
1020        0 => None,
1021        1 => Some(go_ty(&results[0], sources, 0)?),
1022        _ => Some(Ty::Tuple(
1023            results
1024                .iter()
1025                .map(|r| go_ty(r, sources, 0))
1026                .collect::<Option<Vec<_>>>()?,
1027        )),
1028    };
1029    Some((params, result))
1030}
1031
1032/// Go statements appending `expr` of type `t` to the byte slice `b`.
1033fn go_enc(expr: &str, t: &Ty, depth: usize) -> String {
1034    let v = format!("v{depth}");
1035    match t {
1036        Ty::I64(_) => format!("cwb = cwI64(cwb, int64({expr}))\n"),
1037        Ty::F64(_) => format!("cwb = cwF64(cwb, float64({expr}))\n"),
1038        Ty::Bool => format!("cwb = cwBool(cwb, {expr})\n"),
1039        Ty::Str => format!("cwb = cwStr(cwb, {expr})\n"),
1040        Ty::List { item, .. } => format!(
1041            "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",
1042            go_enc(&v, item, depth + 1)
1043        ),
1044        Ty::Map { value, .. } => format!(
1045            "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",
1046            go_enc(&v, value, depth + 1)
1047        ),
1048        Ty::Struct { fields, .. } => {
1049            let mut out = String::from("cwb = append(cwb, 1)\n");
1050            for (field, _, ft) in fields {
1051                out.push_str(&go_enc(&format!("{expr}.{field}"), ft, depth + 1));
1052            }
1053            out
1054        }
1055        Ty::Opt { inner, .. } => go_enc(expr, inner, depth),
1056        // Tuples are handled by the caller; JS-only types never come from Go.
1057        _ => String::new(),
1058    }
1059}
1060
1061/// Go statements decoding a value of type `t` from reader `r` into `target`.
1062fn go_dec(target: &str, t: &Ty, depth: usize) -> String {
1063    match t {
1064        Ty::I64(native) => format!("{target} = {native}(cwr.i64())\n"),
1065        Ty::F64(native) => format!("{target} = {native}(cwr.f64())\n"),
1066        Ty::Bool => format!("{target} = cwr.bool()\n"),
1067        Ty::Str => format!("{target} = cwr.str()\n"),
1068        Ty::List { item, native, .. } => format!(
1069            "if cwr.u8() == 1 {{\nn{depth} := cwr.u32()\n{target} = make({native}, n{depth})\nfor i{depth} := range {target} {{\n{}}}\n}}\n",
1070            go_dec(&format!("{target}[i{depth}]"), item, depth + 1)
1071        ),
1072        Ty::Map { value, native } => {
1073            let item = native.strip_prefix("map[string]").unwrap_or("any");
1074            format!(
1075                "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",
1076                go_dec(&format!("v{depth}"), value, depth + 1)
1077            )
1078        }
1079        Ty::Struct { fields, .. } => {
1080            let mut out = String::from("if cwr.u8() == 1 {\n");
1081            for (field, _, ft) in fields {
1082                out.push_str(&go_dec(&format!("{target}.{field}"), ft, depth + 1));
1083            }
1084            out.push_str("}\n");
1085            out
1086        }
1087        Ty::Opt { inner, .. } => go_dec(target, inner, depth),
1088        // Tuples are handled by the caller; JS-only types never come from Go.
1089        _ => String::new(),
1090    }
1091}
1092
1093const WIRE_HELPERS_GO: &str = r#"
1094// The binary wire: little endian; strings, slices, maps and structs start with 0 for nil.
1095func cwU32(b []byte, n int) []byte { return binary.LittleEndian.AppendUint32(b, uint32(n)) }
1096func cwI64(b []byte, v int64) []byte { return binary.LittleEndian.AppendUint64(b, uint64(v)) }
1097func cwF64(b []byte, v float64) []byte {
1098	return binary.LittleEndian.AppendUint64(b, math.Float64bits(v))
1099}
1100func cwBool(b []byte, v bool) []byte {
1101	if v {
1102		return append(b, 1)
1103	}
1104	return append(b, 0)
1105}
1106func cwStr(b []byte, s string) []byte {
1107	b = append(b, 1)
1108	b = cwU32(b, len(s))
1109	return append(b, s...)
1110}
1111
1112type cwReader struct {
1113	b []byte
1114	i int
1115}
1116
1117func (r *cwReader) u8() byte {
1118	v := r.b[r.i]
1119	r.i++
1120	return v
1121}
1122func (r *cwReader) u32() int {
1123	v := binary.LittleEndian.Uint32(r.b[r.i:])
1124	r.i += 4
1125	return int(v)
1126}
1127func (r *cwReader) i64() int64 {
1128	v := binary.LittleEndian.Uint64(r.b[r.i:])
1129	r.i += 8
1130	return int64(v)
1131}
1132func (r *cwReader) f64() float64 { return math.Float64frombits(uint64(r.i64())) }
1133func (r *cwReader) bool() bool   { return r.u8() != 0 }
1134func (r *cwReader) str() string {
1135	if r.u8() == 0 {
1136		return ""
1137	}
1138	n := r.u32()
1139	s := string(r.b[r.i : r.i+n])
1140	r.i += n
1141	return s
1142}
1143
1144func cwPtr(b []byte) *C.uint8_t {
1145	if len(b) == 0 {
1146		return nil
1147	}
1148	return (*C.uint8_t)(unsafe.Pointer(&b[0]))
1149}
1150"#;
1151
1152/// The Go wrapper function of a wire export: encode the arguments, one cgo call, decode.
1153fn wire_go(e: &ExportedFn, params: &[(String, Ty)], result: Option<&Ty>) -> String {
1154    let (results, fallible) = results(e);
1155    let sig_params = wrapper_params(e);
1156    let mut sig_results = results.clone();
1157    if fallible {
1158        sig_results.push("error".into());
1159    }
1160    let ret = match sig_results.len() {
1161        0 => String::new(),
1162        1 => format!(" {}", sig_results[0]),
1163        _ => format!(" ({})", sig_results.join(", ")),
1164    };
1165    let mut body = String::from("\tcwb := make([]byte, 0, 128)\n");
1166    for (index, (_, t)) in params.iter().enumerate() {
1167        body.push_str(&go_enc(&wrapper_arg(index), t, 0));
1168    }
1169    let names: Vec<String> = (0..results.len()).map(|i| format!("r{i}")).collect();
1170    for (i, r) in results.iter().enumerate() {
1171        let _ = writeln!(body, "\tvar r{i} {r}");
1172    }
1173    let call = |buf: &str| {
1174        format!(
1175            "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)",
1176            e.name
1177        )
1178    };
1179    let _ = writeln!(
1180        body,
1181        "\tvar cwStack [512]byte\n\tcwOut := cwStack[:]\n\tvar n C.size_t\n\tvar errp *C.char\n\tstatus := {}\n\
1182         \tif status == 2 {{\n\t\tcwOut = make([]byte, int(n))\n\t\tstatus = {}\n\t}}",
1183        call("cwOut"),
1184        call("cwOut")
1185    );
1186    let mut fail_ret: Vec<String> = names.clone();
1187    if fallible {
1188        fail_ret.push("rustAnythingToErr(rustAnythingErr(errp))".into());
1189        let _ = writeln!(
1190            body,
1191            "\tif status == 1 {{\n\t\treturn {}\n\t}}",
1192            fail_ret.join(", ")
1193        );
1194    } else {
1195        body.push_str("\tif status == 1 {\n\t\tpanic(rustAnythingErr(errp))\n\t}\n");
1196    }
1197    if !results.is_empty() {
1198        body.push_str("\tcwr := &cwReader{b: cwOut[:n]}\n");
1199        match result {
1200            Some(Ty::Tuple(items)) => {
1201                for (i, t) in items.iter().enumerate() {
1202                    body.push_str(&go_dec(&format!("r{i}"), t, 0));
1203                }
1204            }
1205            Some(t) => body.push_str(&go_dec("r0", t, 0)),
1206            None => {}
1207        }
1208    }
1209    let mut ok = names;
1210    if fallible {
1211        ok.push("nil".into());
1212    }
1213    if !ok.is_empty() {
1214        let _ = writeln!(body, "\treturn {}", ok.join(", "));
1215    }
1216    format!(
1217        "\n// {} is the Rust port of `{}` (`{}:{}`): binary wire, no JSON.\nfunc {}({}){ret} {{\n{body}}}\n",
1218        e.name,
1219        e.prototype.as_deref().unwrap_or(&e.name),
1220        e.file,
1221        e.line,
1222        e.name,
1223        sig_params
1224    )
1225}
1226
1227/// The exports that cross the binary wire (not typed, but every type fits the wire and the port).
1228fn wire_fns<'m>(m: &'m Manifest, api: &crate::codegen::PortApi) -> Vec<WireFn<'m>> {
1229    let sources = unit_sources(m);
1230    let mut out = Vec::new();
1231    for f in &api.functions {
1232        if typed(m, f).is_some() {
1233            continue;
1234        }
1235        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
1236            continue;
1237        };
1238        let Some((params, result)) = wire_sig(e, &sources) else {
1239            continue;
1240        };
1241        if params.len() != f.params.len() {
1242            continue;
1243        }
1244        if let Some(code) = wire_rs_fn(f, e, &params, result.as_ref()) {
1245            out.push((e, params, result, code));
1246        }
1247    }
1248    out
1249}
1250
1251/// The Rust `extern "C"` function of a wire export, with its schema statics.
1252fn wire_rs_fn(
1253    f: &crate::codegen::PortFn,
1254    e: &ExportedFn,
1255    params: &[(String, Ty)],
1256    result: Option<&Ty>,
1257) -> Option<String> {
1258    let mut statics = String::new();
1259    let prefix = format!("S_{}", f.js_name.to_uppercase());
1260    let bindings: Vec<_> = f
1261        .params
1262        .iter()
1263        .enumerate()
1264        .map(|(index, (_, ty))| (format!("ra_arg{index}"), ty.clone()))
1265        .collect();
1266    let reads = crate::wire::rust_read_args(params, &bindings, &prefix, &mut statics)?;
1267    let args: Vec<&str> = bindings.iter().map(|(n, _)| n.as_str()).collect();
1268    let call = format!("port::{}({})", f.rust_name, args.join(", "));
1269    let call = if f.fallible { format!("{call}?") } else { call };
1270    let write = match result {
1271        None => {
1272            if f.ret != "()" {
1273                return None;
1274            }
1275            format!("        let () = {call};\n")
1276        }
1277        Some(t) => {
1278            let schema = format!("{prefix}_OUT");
1279            let w = crate::wire::rust_write(t, &f.ret, "out", &schema, 0)?;
1280            if w.contains(&schema) {
1281                let _ = writeln!(
1282                    statics,
1283                    "static {schema}: wire::Schema = {};",
1284                    crate::wire::schema_expr(t)
1285                );
1286            }
1287            format!("        let out = &{call};\n        {w}\n")
1288        }
1289    };
1290    Some(format!(
1291        "\n{statics}\n/// `{proto}`: binary wire.\n///\n/// # Safety\n///\n/// Called by the generated Go wrapper with valid pointers.\n\
1292         // SAFETY: exported unmangled under a name only rust-anything defines.\n#[unsafe(no_mangle)]\n\
1293         // SAFETY: callers uphold the contract under `# Safety`.\n\
1294         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    \
1295         let input: &[u8] = if in_len == 0 {{\n        &[]\n    }} else {{\n        \
1296         // SAFETY: Go passes its buffer and length.\n        unsafe {{ std::slice::from_raw_parts(in_ptr, in_len) }}\n    }};\n    \
1297         let result = run(|| {{\n        let r = &mut wire::Reader::new(input);\n{reads}        let w = &mut wire::Writer::default();\n{write}        \
1298         Ok(std::mem::take(&mut w.0))\n    }});\n    \
1299         match result {{\n        Ok(bytes) => {{\n            \
1300         // SAFETY: Go passes a buffer of `out_cap` bytes and a valid `out_len`.\n            unsafe {{\n                \
1301         *out_len = bytes.len();\n                if bytes.len() > out_cap {{\n                    return 2;\n                }}\n                \
1302         std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());\n            }}\n            0\n        }}\n        \
1303         // SAFETY: Go passes a valid `err`.\n        Err(message) => unsafe {{ fail(err, message) }},\n    }}\n}}",
1304        proto = e.prototype.as_deref().unwrap_or(&e.name),
1305        name = f.js_name,
1306    ))
1307}
1308
1309/// Rust code of every wire export, for `lib.rs`.
1310pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1311    wire_fns(m, api)
1312        .into_iter()
1313        .map(|(_, _, _, code)| code)
1314        .collect()
1315}
1316
1317/// A `main` package that calls `import_path`'s functions by name: record, diff and bench.
1318pub fn driver(m: &Manifest, import_path: &str) -> String {
1319    let mut cases = String::new();
1320    let mut prepares = String::new();
1321    for f in &m.exports {
1322        let (results, fallible) = results(f);
1323        let _ = writeln!(cases, "\tcase \"{}\":", f.name);
1324        let mut args = Vec::new();
1325        for (i, p) in f.params.iter().enumerate() {
1326            let t = qualify(p.native_type.as_deref().unwrap_or("any"));
1327            let _ = writeln!(
1328                cases,
1329                "\t\tvar a{i} {t}\n\t\tif rustAnythingDecode(argAt(args, {i}), &a{i}) != nil {{\n\t\t\treturn invalid\n\t\t}}"
1330            );
1331            args.push(format!("a{i}"));
1332        }
1333        let _ = writeln!(prepares, "\tcase \"{}\":", f.name);
1334        for (i, p) in f.params.iter().enumerate() {
1335            let t = qualify(p.native_type.as_deref().unwrap_or("any"));
1336            let _ = writeln!(
1337                prepares,
1338                "\t\tvar a{i} {t}\n\t\tif rustAnythingDecode(argAt(args, {i}), &a{i}) != nil {{\n\t\t\treturn nil\n\t\t}}"
1339            );
1340        }
1341        let _ = writeln!(
1342            prepares,
1343            "\t\treturn func() {{ pkg.{}({}) }}",
1344            f.name,
1345            args.join(", ")
1346        );
1347        let mut lhs: Vec<String> = (0..results.len()).map(|i| format!("r{i}")).collect();
1348        if fallible {
1349            lhs.push("err".into());
1350        }
1351        let call = format!("pkg.{}({})", f.name, args.join(", "));
1352        if lhs.is_empty() {
1353            let _ = writeln!(cases, "\t\t{call}");
1354        } else {
1355            let _ = writeln!(cases, "\t\t{} := {call}", lhs.join(", "));
1356        }
1357        if fallible {
1358            cases.push_str(
1359                "\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",
1360            );
1361        }
1362        let ok = match results.len() {
1363            0 => "nil".to_string(),
1364            1 => "rustAnythingEncode(r0)".to_string(),
1365            n => format!(
1366                "[]any{{{}}}",
1367                (0..n)
1368                    .map(|i| format!("rustAnythingEncode(r{i})"))
1369                    .collect::<Vec<_>>()
1370                    .join(", ")
1371            ),
1372        };
1373        let _ = writeln!(cases, "\t\treturn map[string]any{{\"ok\": {ok}}}");
1374    }
1375    let sentinels = crate::lang::go::sentinel_errors(&sentinel_sources(m));
1376    let mut sentinel_fn = String::from("func rustAnythingSentinelName(err error) string {\n");
1377    for s in &sentinels {
1378        let name_q = serde_json::to_string(&s.name).unwrap_or_else(|_| format!("{:?}", s.name));
1379        let _ = writeln!(
1380            sentinel_fn,
1381            "\tif errors.Is(err, pkg.{}) {{\n\t\treturn {name_q}\n\t}}",
1382            s.name
1383        );
1384    }
1385    sentinel_fn.push_str("\treturn \"\"\n}\n");
1386    DRIVER_GO
1387        .replace("IMPORT_PATH", import_path)
1388        .replace("// CASES\n", &cases)
1389        .replace("// PREPARES\n", &prepares)
1390        .replace("// SENTINELS\n", &sentinel_fn)
1391        .replace("// HELPERS\n", HELPERS_GO)
1392}
1393
1394const DRIVER_GO: &str = r#"// Generated by rust-anything: calls the package's functions by name.
1395package main
1396
1397import (
1398	"bufio"
1399	"bytes"
1400	"encoding/json"
1401	"errors"
1402	"fmt"
1403	"math"
1404	"os"
1405	"strings"
1406	"time"
1407
1408	pkg "IMPORT_PATH"
1409)
1410
1411var _ = errors.New
1412
1413// SENTINELS
1414
1415// HELPERS
1416
1417var invalid = map[string]any{"invalid": true}
1418
1419func argAt(args []json.RawMessage, i int) json.RawMessage {
1420	if i < len(args) {
1421		return args[i]
1422	}
1423	return nil
1424}
1425
1426func call(name string, args []json.RawMessage) (out map[string]any) {
1427	defer func() {
1428		if r := recover(); r != nil {
1429			out = map[string]any{"panic": fmt.Sprint(r)}
1430		}
1431	}()
1432	switch name {
1433	// CASES
1434	}
1435	return map[string]any{"missing": name}
1436}
1437
1438// prepare decodes a case's arguments once and returns the bare call; nil if they do not fit.
1439func prepare(name string, args []json.RawMessage) func() {
1440	switch name {
1441	// PREPARES
1442	}
1443	return nil
1444}
1445
1446type input struct {
1447	Fn   string            `json:"fn"`
1448	Args []json.RawMessage `json:"args"`
1449}
1450
1451// canon re-encodes a JSON value with exact numbers, so equal values compare equal as text.
1452func canon(v any) string {
1453	text, err := json.Marshal(v)
1454	if err != nil {
1455		return "unencodable: " + err.Error()
1456	}
1457	d := json.NewDecoder(bytes.NewReader(text))
1458	d.UseNumber()
1459	var x any
1460	if err := d.Decode(&x); err != nil {
1461		return string(text)
1462	}
1463	out, _ := json.Marshal(x)
1464	return string(out)
1465}
1466
1467func record(inputs, out string) {
1468	data, err := os.ReadFile(inputs)
1469	if err != nil {
1470		panic(err)
1471	}
1472	var cases []input
1473	if err := json.Unmarshal(data, &cases); err != nil {
1474		panic(err)
1475	}
1476	f, err := os.Create(out)
1477	if err != nil {
1478		panic(err)
1479	}
1480	defer f.Close()
1481	w := bufio.NewWriter(f)
1482	defer w.Flush()
1483	progress := os.Getenv("RUST_ANYTHING_PROGRESS")
1484	for index, c := range cases {
1485		if progress != "" {
1486			if p, err := os.OpenFile(progress, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
1487				fmt.Fprintln(p, index)
1488				p.Close()
1489			}
1490		}
1491		result := call(c.Fn, c.Args)
1492		if result["invalid"] != nil {
1493			continue
1494		}
1495		line := map[string]any{"fn": c.Fn, "args": c.Args}
1496		for k, v := range result {
1497			line[k] = v
1498		}
1499		text, err := json.Marshal(line)
1500		if err != nil {
1501			continue
1502		}
1503		w.Write(text)
1504		w.WriteByte('\n')
1505		w.Flush()
1506	}
1507}
1508
1509func readCases(path string) []map[string]json.RawMessage {
1510	data, err := os.ReadFile(path)
1511	if err != nil {
1512		panic(err)
1513	}
1514	var out []map[string]json.RawMessage
1515	for _, line := range bytes.Split(data, []byte("\n")) {
1516		if len(bytes.TrimSpace(line)) == 0 {
1517			continue
1518		}
1519		var c map[string]json.RawMessage
1520		if err := json.Unmarshal(line, &c); err != nil {
1521			panic(err)
1522		}
1523		out = append(out, c)
1524	}
1525	return out
1526}
1527
1528func argsOf(c map[string]json.RawMessage) (string, []json.RawMessage) {
1529	var name string
1530	var args []json.RawMessage
1531	json.Unmarshal(c["fn"], &name)
1532	json.Unmarshal(c["args"], &args)
1533	return name, args
1534}
1535
1536func diff(cases, out string) {
1537	summary := map[string]any{"total": 0, "passed": 0, "failed": 0}
1538	missing := []string{}
1539	mismatches := []any{}
1540	total, passed, failed := 0, 0, 0
1541	for _, c := range readCases(cases) {
1542		total++
1543		name, args := argsOf(c)
1544		got := call(name, args)
1545		if got["missing"] != nil {
1546			failed++
1547			missing = append(missing, name)
1548			continue
1549		}
1550		expected := map[string]any{}
1551		for _, k := range []string{"ok", "error", "sentinel", "panic"} {
1552			if raw, ok := c[k]; ok {
1553				expected[k] = raw
1554			}
1555		}
1556		if _, ok := c["sentinel"]; !ok {
1557			delete(got, "sentinel")
1558		}
1559		same := false
1560		if p, ok := got["panic"]; ok && strings.Contains(fmt.Sprint(p), "Rust panic:") {
1561			same = false
1562		} else if _, ok := expected["panic"]; ok {
1563			// Panic messages differ between Go and Rust; that it panicked is the behavior.
1564			_, same = got["panic"]
1565		} else {
1566			same = canon(expected) == canon(got)
1567		}
1568		if same {
1569			passed++
1570		} else {
1571			failed++
1572			mismatches = append(mismatches, map[string]any{"fn": name, "args": args, "expected": expected, "actual": got})
1573		}
1574	}
1575	summary["total"], summary["passed"], summary["failed"] = total, passed, failed
1576	summary["missing"], summary["mismatches"] = missing, mismatches
1577	text, _ := json.Marshal(summary)
1578	os.WriteFile(out, text, 0o644)
1579}
1580
1581func bench(cases, out string, minMs int) {
1582	groups := map[string][][]json.RawMessage{}
1583	order := []string{}
1584	for _, c := range readCases(cases) {
1585		name, args := argsOf(c)
1586		if _, ok := groups[name]; !ok {
1587			order = append(order, name)
1588		}
1589		groups[name] = append(groups[name], args)
1590	}
1591	result := map[string]any{}
1592	for _, name := range order {
1593		// Arguments are decoded once: only the calls are timed.
1594		var calls []func()
1595		for _, args := range groups[name] {
1596			if f := prepare(name, args); f != nil {
1597				calls = append(calls, f)
1598			}
1599		}
1600		if len(calls) == 0 {
1601			continue
1602		}
1603		once := func() {
1604			for _, f := range calls {
1605				func() {
1606					defer func() { recover() }()
1607					f()
1608				}()
1609			}
1610		}
1611		once()
1612		passes, start := 0, time.Now()
1613		for {
1614			once()
1615			passes++
1616			if elapsed := time.Since(start); elapsed.Milliseconds() >= int64(minMs) {
1617				result[name] = map[string]any{"cases": len(calls), "ns": float64(elapsed.Nanoseconds()) / float64(passes*len(calls))}
1618				break
1619			}
1620		}
1621	}
1622	text, _ := json.Marshal(result)
1623	os.WriteFile(out, text, 0o644)
1624}
1625
1626func main() {
1627	switch os.Args[1] {
1628	case "record":
1629		record(os.Args[2], os.Args[3])
1630	case "diff":
1631		diff(os.Args[2], os.Args[3])
1632	case "bench":
1633		var ms int
1634		fmt.Sscan(os.Args[4], &ms)
1635		bench(os.Args[2], os.Args[3], ms)
1636	}
1637}
1638"#;
1639
1640/// A shadow package with the original's API: each call runs the original and the Rust port
1641/// (through the wrapper), returns the original's results and logs mismatches.
1642/// `RUST_ANYTHING_MODE=old` runs the original only, `new` the port only.
1643pub fn shadow(m: &Manifest, original: &str) -> String {
1644    let wrapper = crate::harness_go::wrapper_module(m);
1645    let sentinels = crate::lang::go::sentinel_errors(&sentinel_sources(m));
1646    let remap_sentinels = !sentinels.is_empty() && m.exports.iter().any(|f| results(f).1);
1647    let extra_imports = if remap_sentinels {
1648        "\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n"
1649    } else {
1650        ""
1651    };
1652    let mut out = format!(
1653        "// Package {pkg} runs the Go original and the Rust port of `{unit}` side by side. Generated\n\
1654         // by rust-anything: import it in place of {original}. RUST_ANYTHING_MODE=old|shadow|new.\n\
1655         package {pkg}\n\n\
1656         import (\n\t\"encoding/json\"\n{extra_imports}\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"sync/atomic\"\n\n\
1657         \torig \"{original}\"\n\tport \"{wrapper}\"\n)\n\n\
1658         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\
1659         // Calls and Mismatches count shadowed calls.\nvar Calls, Mismatches atomic.Int64\n\n\
1660         // convert moves a value between the original's and the wrapper's identical types.\n\
1661         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\
1662         func compare(name string, expected, actual []any) {{\n\tCalls.Add(1)\n\tif !reflect.DeepEqual(expected, actual) {{\n\
1663         \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",
1664        pkg = package_name(m),
1665        unit = m.unit,
1666    );
1667    for t in used_types(m) {
1668        let _ = write!(
1669            out,
1670            "\n// {t} is the original's type.\ntype {t} = orig.{t}\n"
1671        );
1672    }
1673    for s in &sentinels {
1674        let _ = write!(
1675            out,
1676            "\n// {} is the original's sentinel error.\nvar {} = orig.{}\n",
1677            s.name, s.name, s.name
1678        );
1679    }
1680    if remap_sentinels {
1681        out.push_str(
1682            "\nfunc remapErr(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n",
1683        );
1684        for s in &sentinels {
1685            let n = &s.name;
1686            let _ = write!(
1687                out,
1688                "\tif err == port.{n} {{\n\t\treturn orig.{n}\n\t}}\n\
1689                 \tif errors.Is(err, port.{n}) {{\n\
1690                 \t\tmsg := err.Error()\n\
1691                 \t\ttext := port.{n}.Error()\n\
1692                 \t\tif prefix := text + \": \"; strings.HasPrefix(msg, prefix) {{\n\
1693                 \t\t\treturn fmt.Errorf(\"%w: %s\", orig.{n}, strings.TrimPrefix(msg, prefix))\n\
1694                 \t\t}}\n\
1695                 \t\tif suffix := \": \" + text; strings.HasSuffix(msg, suffix) {{\n\
1696                 \t\t\treturn fmt.Errorf(\"%s: %w\", strings.TrimSuffix(msg, suffix), orig.{n})\n\
1697                 \t\t}}\n\
1698                 \t\treturn orig.{n}\n\
1699                 \t}}\n"
1700            );
1701        }
1702        out.push_str("\treturn err\n}\n");
1703    }
1704    for f in &m.exports {
1705        let (results, fallible) = results(f);
1706        let params: Vec<String> = f
1707            .params
1708            .iter()
1709            .map(|p| format!("{} {}", p.name, p.native_type.as_deref().unwrap_or("any")))
1710            .collect();
1711        let mut all: Vec<String> = results.clone();
1712        if fallible {
1713            all.push("error".into());
1714        }
1715        let ret = match all.len() {
1716            0 => String::new(),
1717            1 => format!(" {}", all[0]),
1718            _ => format!(" ({})", all.join(", ")),
1719        };
1720        let names: Vec<String> = (0..all.len()).map(|i| format!("o{i}")).collect();
1721        let rust_names: Vec<String> = (0..all.len()).map(|i| format!("n{i}")).collect();
1722        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
1723        let port_args: Vec<String> = f
1724            .params
1725            .iter()
1726            .map(|p| {
1727                let t = p.native_type.as_deref().unwrap_or("any");
1728                if local_types(t).is_empty() {
1729                    p.name.clone()
1730                } else {
1731                    format!(
1732                        "convert[{}]({})",
1733                        qualify(t).replace("pkg.", "port."),
1734                        p.name
1735                    )
1736                }
1737            })
1738            .collect();
1739        let lhs = |v: &[String]| {
1740            if v.is_empty() {
1741                String::new()
1742            } else {
1743                format!("{} := ", v.join(", "))
1744            }
1745        };
1746        let back: Vec<String> = all
1747            .iter()
1748            .zip(&rust_names)
1749            .map(|(t, n)| {
1750                if t == "error" && remap_sentinels {
1751                    format!("remapErr({n})")
1752                } else if local_types(t).is_empty() {
1753                    n.clone()
1754                } else {
1755                    format!("convert[{t}]({n})")
1756                }
1757            })
1758            .collect();
1759        let errors_text = |v: &[String]| -> Vec<String> {
1760            v.iter()
1761                .zip(&all)
1762                .map(|(n, t)| {
1763                    if t == "error" {
1764                        format!("errText({n})")
1765                    } else {
1766                        n.clone()
1767                    }
1768                })
1769                .collect()
1770        };
1771        let _ = writeln!(
1772            out,
1773            "\n// {} shadows the original `{}`.\nfunc {}({}){ret} {{",
1774            f.name,
1775            f.name,
1776            f.name,
1777            params.join(", ")
1778        );
1779        let ret_new = if all.is_empty() {
1780            String::new()
1781        } else {
1782            format!("return {}", back.join(", "))
1783        };
1784        let _ = writeln!(
1785            out,
1786            "\tif mode == \"new\" {{\n\t\t{}port.{}({})\n\t\t{ret_new}\n\t}}",
1787            lhs(&rust_names),
1788            f.name,
1789            port_args.join(", ")
1790        );
1791        let _ = writeln!(out, "\t{}orig.{}({})", lhs(&names), f.name, args.join(", "));
1792        let ret_old = if all.is_empty() {
1793            "return".to_string()
1794        } else {
1795            format!("return {}", names.join(", "))
1796        };
1797        let _ = writeln!(
1798            out,
1799            "\tif mode != \"old\" {{\n\t\tfunc() {{\n\t\t\tdefer func() {{\n\t\t\t\tif r := recover(); r != nil {{\n\
1800             \t\t\t\t\tcompare(\"{name}\", []any{{\"no panic\"}}, []any{{r}})\n\t\t\t\t}}\n\t\t\t}}()\n\
1801             \t\t\t{}port.{name}({})\n\t\t\tcompare(\"{name}\", []any{{{}}}, []any{{{}}})\n\t\t}}()\n\t}}\n\t{ret_old}\n}}",
1802            lhs(&rust_names),
1803            port_args.join(", "),
1804            errors_text(&names).join(", "),
1805            errors_text(&back).join(", "),
1806            name = f.name,
1807        );
1808    }
1809    out.push_str("\nfunc errText(err error) any {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn err.Error()\n}\n");
1810    out
1811}
1812
1813#[cfg(test)]
1814mod tests {
1815    use super::*;
1816
1817    #[test]
1818    fn go_codegen_reserves_its_own_bindings() {
1819        let exports = crate::lang::go::exports(
1820            "names.go",
1821            r#"package names
1822func Typed(out int, C string) int { return out + len(C) }
1823func Wire(cwb []int, r []int) []int { return append(cwb, r...) }
1824func Json(raw uint64) uint64 { return raw }"#,
1825        );
1826        let manifest = Manifest {
1827            schema: String::new(),
1828            root: std::path::PathBuf::new(),
1829            root_written: None,
1830            unit: "names.go".into(),
1831            language: crate::lang::Lang::Go,
1832            kind: crate::bridge::Kind::Ffi,
1833            crate_name: "names-rs".into(),
1834            exports,
1835            classes: vec![],
1836            js_only: vec![],
1837            batches: vec![],
1838            allocator: Default::default(),
1839            float_tolerance: None,
1840            ignore_key_order: false,
1841        };
1842        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
1843        crate::bridge::match_export_names(&manifest, &mut api);
1844        let go = wrapper(&manifest, &api);
1845        assert!(go.contains("func Typed(raArg0 int, raArg1 string) int {"));
1846        assert!(go.contains("C.rust_anything_t_Typed(C.int64_t(raArg0),"));
1847        assert!(go.contains("int64_t ra_arg0, const uint8_t *ra_arg1_ptr"));
1848        assert!(go.contains("func Wire(raArg0 []int, raArg1 []int) []int {"));
1849        assert!(go.contains("C.rust_anything_w_Wire(cwPtr(cwb)"));
1850        assert!(go.contains("func Json(raArg0 uint64) uint64 {"));
1851        assert!(go.contains(r#"raw, err := rustAnythingCall("Json", raArg0)"#));
1852        let typed = typed_rs(&manifest, &api);
1853        assert!(typed.contains("port::typed(ra_arg0, ra_arg1)"));
1854        let wire = wire_rs(&manifest, &api);
1855        assert!(wire.contains("port::wire(ra_arg0, ra_arg1)"));
1856    }
1857
1858    #[test]
1859    fn qualifies_local_types() {
1860        assert_eq!(qualify("[]Point"), "[]pkg.Point");
1861        assert_eq!(qualify("map[string]Point"), "map[string]pkg.Point");
1862        assert_eq!(qualify("time.Duration"), "time.Duration");
1863        assert_eq!(local_types("map[string][]Point"), ["Point"]);
1864    }
1865
1866    #[test]
1867    fn maps_sentinel_errors_in_wrapper_driver_and_shadow() {
1868        let dir =
1869            std::env::temp_dir().join(format!("rust-anything-go-sentinels-{}", std::process::id()));
1870        let _ = std::fs::remove_dir_all(&dir);
1871        std::fs::create_dir_all(dir.join("store")).unwrap();
1872        let src = r#"package store
1873
1874import "errors"
1875
1876var (
1877	ErrNotFound = errors.New("not found")
1878	ErrAlias    error = ErrNotFound
1879	ErrBadInput = errors.New("bad input")
1880)
1881
1882func Lookup(id int) (string, error) {
1883	if id < 0 {
1884		return "", ErrBadInput
1885	}
1886	return "", ErrNotFound
1887}
1888"#;
1889        std::fs::write(dir.join("store/store.go"), src).unwrap();
1890        // Platform-specific file for another OS must be excluded from sentinel discovery.
1891        let other_os = if host_goos() == "windows" {
1892            "linux"
1893        } else {
1894            "windows"
1895        };
1896        std::fs::write(
1897            dir.join(format!("store/errors_{other_os}.go")),
1898            "package store\nimport \"errors\"\nvar ErrOtherOS = errors.New(\"other\")\n",
1899        )
1900        .unwrap();
1901        let exports = crate::lang::go::exports("store/store.go", src);
1902        let manifest = Manifest {
1903            schema: String::new(),
1904            root: dir.clone(),
1905            root_written: None,
1906            unit: "store/".into(),
1907            language: crate::lang::Lang::Go,
1908            kind: crate::bridge::Kind::Ffi,
1909            crate_name: "store-rs".into(),
1910            exports,
1911            classes: vec![],
1912            js_only: vec![],
1913            batches: vec![],
1914            allocator: Default::default(),
1915            float_tolerance: None,
1916            ignore_key_order: false,
1917        };
1918        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
1919        crate::bridge::match_export_names(&manifest, &mut api);
1920
1921        let w = wrapper(&manifest, &api);
1922        assert!(
1923            w.contains("var ErrNotFound = errors.New(\"not found\")"),
1924            "{w}"
1925        );
1926        assert!(w.contains("var ErrAlias = ErrNotFound"), "{w}");
1927        assert!(
1928            w.contains("var ErrBadInput = errors.New(\"bad input\")"),
1929            "{w}"
1930        );
1931        assert!(!w.contains("ErrOtherOS"), "{w}");
1932        assert!(w.contains("hasText: true"), "{w}");
1933        assert!(
1934            w.contains("func rustAnythingToErr(msg string) error"),
1935            "{w}"
1936        );
1937        assert!(w.contains("fmt.Errorf(\"%w: %s\""), "{w}");
1938        assert!(
1939            w.contains("rustAnythingToErr(rustAnythingErr(errp))"),
1940            "{w}"
1941        );
1942        assert!(!w.contains("errors.New(rustAnythingErr(errp))"), "{w}");
1943
1944        let d = driver(&manifest, "example.com/app/store");
1945        assert!(d.contains("errors.Is(err, pkg.ErrNotFound)"), "{d}");
1946        assert!(!d.contains("ErrOtherOS"), "{d}");
1947        assert!(d.contains("res[\"sentinel\"] = s"), "{d}");
1948        assert!(d.contains("delete(got, \"sentinel\")"), "{d}");
1949
1950        let s = shadow(&manifest, "example.com/app/store");
1951        assert!(s.contains("var ErrNotFound = orig.ErrNotFound"), "{s}");
1952        assert!(s.contains("func remapErr(err error) error"), "{s}");
1953        assert!(s.contains("remapErr(n1)"), "{s}");
1954
1955        let _ = std::fs::remove_dir_all(&dir);
1956    }
1957
1958    #[test]
1959    fn diff_handles_legacy_cases_without_sentinel_and_rejects_plain_error() {
1960        if std::process::Command::new("go")
1961            .arg("version")
1962            .output()
1963            .is_err()
1964        {
1965            return;
1966        }
1967        let dir = std::env::temp_dir().join(format!(
1968            "rust-anything-go-sentinel-diff-{}",
1969            std::process::id()
1970        ));
1971        let _ = std::fs::remove_dir_all(&dir);
1972        std::fs::create_dir_all(dir.join("store")).unwrap();
1973        std::fs::create_dir_all(dir.join("drv")).unwrap();
1974
1975        let src = r#"package store
1976
1977import "errors"
1978
1979var ErrNotFound = errors.New("not found")
1980
1981func Lookup(id int) (string, error) {
1982	if id == 1 {
1983		return "", ErrNotFound
1984	}
1985	return "", errors.New("not found")
1986}
1987"#;
1988        std::fs::write(dir.join("go.mod"), "module example.com/app\n\ngo 1.22\n").unwrap();
1989        std::fs::write(dir.join("store/store.go"), src).unwrap();
1990
1991        let exports = crate::lang::go::exports("store/store.go", src);
1992        let manifest = Manifest {
1993            schema: String::new(),
1994            root: dir.clone(),
1995            root_written: None,
1996            unit: "store/".into(),
1997            language: crate::lang::Lang::Go,
1998            kind: crate::bridge::Kind::Ffi,
1999            crate_name: "store-rs".into(),
2000            exports,
2001            classes: vec![],
2002            js_only: vec![],
2003            batches: vec![],
2004            allocator: Default::default(),
2005            float_tolerance: None,
2006            ignore_key_order: false,
2007        };
2008        let drv = driver(&manifest, "example.com/app/store");
2009        std::fs::write(dir.join("drv/main.go"), drv).unwrap();
2010
2011        // 1) Legacy case (no "sentinel" key) passes even though Lookup(1) returns ErrNotFound.
2012        // 2) Recorded sentinel case passes when Lookup(1) returns ErrNotFound.
2013        // 3) Recorded sentinel case fails when Lookup(2) returns a plain error with the same text.
2014        let cases_path = dir.join("cases.jsonl");
2015        let out_path = dir.join("out.json");
2016        std::fs::write(
2017            &cases_path,
2018            concat!(
2019                "{\"fn\":\"Lookup\",\"args\":[1],\"error\":\"not found\"}\n",
2020                "{\"fn\":\"Lookup\",\"args\":[1],\"error\":\"not found\",\"sentinel\":\"ErrNotFound\"}\n",
2021                "{\"fn\":\"Lookup\",\"args\":[2],\"error\":\"not found\",\"sentinel\":\"ErrNotFound\"}\n",
2022            ),
2023        )
2024        .unwrap();
2025
2026        let status = std::process::Command::new("go")
2027            .current_dir(&dir)
2028            .args([
2029                "run",
2030                "./drv",
2031                "diff",
2032                cases_path.to_str().unwrap(),
2033                out_path.to_str().unwrap(),
2034            ])
2035            .status()
2036            .unwrap();
2037        assert!(status.success(), "go driver diff failed to run");
2038
2039        let summary: serde_json::Value =
2040            serde_json::from_str(&std::fs::read_to_string(&out_path).unwrap()).unwrap();
2041        assert_eq!(summary["total"], 3, "{summary}");
2042        assert_eq!(summary["passed"], 2, "{summary}");
2043        assert_eq!(summary["failed"], 1, "{summary}");
2044        let mismatches = summary["mismatches"].as_array().unwrap();
2045        assert_eq!(mismatches.len(), 1, "{summary}");
2046        assert_eq!(mismatches[0]["args"], serde_json::json!([2]), "{summary}");
2047        assert_eq!(
2048            mismatches[0]["expected"]["sentinel"], "ErrNotFound",
2049            "{summary}"
2050        );
2051        assert!(
2052            mismatches[0]["actual"].get("sentinel").is_none(),
2053            "{summary}"
2054        );
2055
2056        let _ = std::fs::remove_dir_all(&dir);
2057    }
2058
2059    #[test]
2060    fn typed_rs_avoids_redundant_closure_for_zero_arg_fallible_functions() {
2061        let src = r#"package ping
2062
2063func Pong() (string, error) { return "pong", nil }
2064func PurePong() string { return "pong" }
2065func Echo(s string) (string, error) { return s, nil }
2066"#;
2067        let exports = crate::lang::go::exports("ping.go", src);
2068        let manifest = Manifest {
2069            schema: String::new(),
2070            root: std::path::PathBuf::new(),
2071            root_written: None,
2072            unit: "ping".into(),
2073            language: crate::lang::Lang::Go,
2074            kind: crate::bridge::Kind::Ffi,
2075            crate_name: "ping-rs".into(),
2076            exports,
2077            classes: vec![],
2078            js_only: vec![],
2079            batches: vec![],
2080            allocator: Default::default(),
2081            float_tolerance: None,
2082            ignore_key_order: false,
2083        };
2084        let mut api = crate::codegen::parse_port(
2085            "pub fn pong() -> Result<String, String> { Ok(\"pong\".into()) }\n\
2086             pub fn pure_pong() -> String { \"pong\".into() }\n\
2087             pub fn echo(s: String) -> Result<String, String> { Ok(s) }\n",
2088        );
2089        crate::bridge::match_export_names(&manifest, &mut api);
2090        let rs = typed_rs(&manifest, &api);
2091        assert!(rs.contains("match run(port::pong)"), "{rs}");
2092        assert!(!rs.contains("run(|| port::pong())"), "{rs}");
2093        assert!(rs.contains("match run(|| Ok(port::pure_pong()))"), "{rs}");
2094        assert!(rs.contains("match run(|| port::echo(ra_arg0))"), "{rs}");
2095    }
2096}