Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
go: port functions that return a value and an error
Mohit Mishra14327dee39e6
diff --git a/src/golang.rs b/src/golang.rsindex 7ed9fa6..ed78920 100644--- a/src/golang.rs+++ b/src/golang.rs@@ -348,8 +348,17 @@ fn arg_list(hs: &Hotspot) -> String {hs.params.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", ")}+/// The function's value type, and whether it also returns an error: "(T, error)" (see describe.go).+fn ret_parts(hs: &Hotspot) -> (String, bool) {+ let r = hs.returns.clone().unwrap_or_default();+ match r.strip_prefix('(').and_then(|t| t.strip_suffix(", error)")) {+ Some(t) => (t.to_string(), true),+ None => (r, false),+ }+}+fn ret(hs: &Hotspot) -> String {- hs.returns.clone().unwrap_or_default()+ ret_parts(hs).0}pub fn record(ctx: &Ctx, go: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {@@ -363,13 +372,22 @@ pub fn record(ctx: &Ctx, go: &str, args: &[String], hs: &Hotspot, out: &Path, li.enumerate().map(|(i, p)| format!("a[{i}].({})", p.annotation.as_deref().unwrap_or("any"))).collect();- let prologue = format!(- "if !fastAnythingRecInside {{\n\treturn fastAnythingRec([]any{{{args}}}, func(a []any) any {{ return {name}({casts}) }}).({ret})\n}}",- args = arg_list(hs),- name = hs.name,- casts = casts.join(", "),- ret = ret(hs),- );+ let (value, errors) = ret_parts(hs);+ let prologue = if errors {+ format!(+ "if !fastAnythingRecInside {{\n\tfaP := fastAnythingRec([]any{{{args}}}, func(a []any) any {{\n\t\tfaV, faErr := {name}({casts})\n\t\treturn fastAnythingRecPair{{faV, faErr}}\n\t}}).(fastAnythingRecPair)\n\tfaV, _ := faP.V.({value})\n\treturn faV, faP.Err\n}}",+ args = arg_list(hs),+ name = hs.name,+ casts = casts.join(", "),+ )+ } else {+ format!(+ "if !fastAnythingRecInside {{\n\treturn fastAnythingRec([]any{{{args}}}, func(a []any) any {{ return {name}({casts}) }}).({value})\n}}",+ args = arg_list(hs),+ name = hs.name,+ casts = casts.join(", "),+ )+ };let patched =native::insert_in_body(&text, "//", &format!("recording {}", hs.id), &prologue, find_body(&hs.name, hs.line))?;let rec = REC.replace("/*PKG*/", &pkg_name(ctx, hs)?).replace("/*ID*/", &hs.id);@@ -403,6 +421,10 @@ pub fn record(ctx: &Ctx, go: &str, args: &[String], hs: &Hotspot, out: &Path, li/// Rust type for a Go type.pub fn rust_type(t: &str) -> Option<String> {let t = t.trim();+ // (T, error): the port returns Result<T, String>, Err for the error+ if let Some(value) = t.strip_prefix('(').and_then(|t| t.strip_suffix(", error)")) {+ return rust_type(value);+ }Some(match t {"int" | "int64" => "i64".into(),"int32" | "rune" => "i32".into(),@@ -436,6 +458,7 @@ pub const FLAVOR: Flavor = Flavor {"Go strings are UTF-8 bytes: `len(s)` and `s[i]` are bytes, `for _, r := range s` and `[]rune(s)` are characters. Do the same in Rust.","A nil slice or map arrives (and may be returned) as an empty Vec or HashMap: fast-anything treats them as equal.","Map iteration order is random in Go: return results in the order the original does when it's deterministic.",+ "A function returning (T, error): return `Err(message)` where it returns a non-nil error (its message is `err.Error()`); enabled, Go gets `errors.New(message)` back, so callers comparing against sentinel errors (`err == io.EOF`, `errors.Is`) won't match.",],};@@ -490,9 +513,14 @@ pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {.replace("/*PARAMS*/", ¶ms.join(", ")).replace("/*ARGS*/", &arg_list(hs)).replace("/*RET*/", &ret(hs))+ .replace("/*ERRORS*/", if ret_parts(hs).1 { "true" } else { "false" }).replace("/*LIB*/", &lib)};- let prologue = format!("if faR, faOK := faFast_{s}({}); faOK {{\n\treturn faR\n}}", arg_list(hs));+ let prologue = if ret_parts(hs).1 {+ format!("if faR, faErr, faOK := faFast_{s}({}); faOK {{\n\treturn faR, faErr\n}}", arg_list(hs))+ } else {+ format!("if faR, _, faOK := faFast_{s}({}); faOK {{\n\treturn faR\n}}", arg_list(hs))+ };let patched = native::insert_in_body(&text, "//", &port.id, &prologue, find_body(&port.func, hs.line))?;for (path, template) in bridge_files(&file, port)?.iter().zip([BRIDGE, BRIDGE_WINDOWS, BRIDGE_UNIX, BRIDGE_NOCGO]) {fs::write(path, fill(template))?;@@ -516,6 +544,100 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {mod tests {use super::*;+ #[test]+ fn the_bridge_returns_the_ports_error() {+ if !Command::new("go").arg("version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no go on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-go-bridge-error-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ let bridge = BRIDGE+ .replace("/*S*/", "t")+ .replace("/*PKG*/", "main")+ .replace("/*ID*/", "m.parse")+ .replace("/*PARAMS*/", "s string")+ .replace("/*ARGS*/", "s")+ .replace("/*RET*/", "int")+ .replace("/*ERRORS*/", "true")+ .replace("/*LIB*/", "\"lib\"");+ // a stand-in for the port: an error for "x", a number otherwise+ let main = r#"package main++import "fmt"++func faLoad_t(path string) bool { return true }++func faInvoke_t(in []byte) []byte {+ if string(in) == `["x"]` {+ return []byte(`{"error":"bad input"}`)+ }+ return []byte(`{"ok":7}`)+}++func main() {+ n, err, ok := faFast_t("x")+ fmt.Println(n, err, ok)+ n, err, ok = faFast_t("7")+ fmt.Println(n, err, ok)+}+"#;+ fs::write(dir.join("go.mod"), "module t\n\ngo 1.22\n").unwrap();+ fs::write(dir.join("bridge.go"), bridge).unwrap();+ fs::write(dir.join("main.go"), main).unwrap();+ let run = Command::new("go").args(["run", "."]).current_dir(&dir).env("CGO_ENABLED", "0").output().unwrap();+ let _ = fs::remove_dir_all(&dir);+ assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));+ assert_eq!(String::from_utf8_lossy(&run.stdout), "0 bad input true\n7 <nil> true\n");+ }++ #[test]+ fn a_value_and_an_error_are_portable_and_recorded() {+ if !Command::new("go").arg("version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no go on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-go-value-error-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("go.mod"), "module demo\n\ngo 1.22\n").unwrap();+ let lib = "package main\n\nimport \"strconv\"\n\nfunc parse(s string) (int, error) {\n\treturn strconv.Atoi(s)\n}\n\nfunc half(n int) (h int, err error) {\n\th = n / 2\n\treturn\n}\n\nfunc split(s string) (int, int) {\n\treturn len(s), 0\n}\n";+ let main = "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tt := 0\n\tfor _, s := range []string{\"1\", \"22\", \"x\", \"333\"} {\n\t\tn, err := parse(s)\n\t\tif err == nil {\n\t\t\tt += n\n\t\t}\n\t}\n\th, _ := half(t)\n\ta, _ := split(\"ab\")\n\tfmt.Println(t, h, a)\n}\n";+ fs::write(dir.join("lib.go"), lib).unwrap();+ fs::write(dir.join("main.go"), main).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let funcs = describe(&ctx, "go").unwrap();+ let find = |n: &str| funcs.iter().find(|f| f.name == n).unwrap();+ assert_eq!(find("parse").returns.as_deref(), Some("(int, error)"));+ assert!(find("parse").blockers.is_empty(), "{:?}", find("parse").blockers);+ assert_eq!(find("half").returns.as_deref(), Some("(int, error)"));+ assert!(find("half").blockers.is_empty(), "named results: {:?}", find("half").blockers);+ assert!(find("split").blockers.iter().any(|b| b.starts_with("returns more than one value")));+ assert_eq!(rust_type("(int, error)").as_deref(), Some("i64"));+ let hs = Hotspot {+ id: "main.parse".into(),+ file: "lib.go".into(),+ line: 5,+ name: "parse".into(),+ qualname: "parse".into(),+ params: vec![Param { name: "s".into(), annotation: Some("string".into()), ..Param::default() }],+ returns: Some("(int, error)".into()),+ ..Hotspot::default()+ };+ let out = dir.join("rec.jsonl");+ let rec = record(&ctx, "go", &["run".into(), ".".into()], &hs, &out, 50);+ let lines = fs::read_to_string(&out).unwrap_or_default();+ let after = fs::read_to_string(dir.join("lib.go")).unwrap();+ let _ = fs::remove_dir_all(&dir);+ assert_eq!(rec.unwrap().calls, 4);+ assert!(lines.contains(r#"{"args":["22"],"result":22}"#), "{lines}");+ assert!(lines.contains(r#"{"args":["x"],"raises":"strconv.Atoi: parsing \"x\": invalid syntax"}"#), "{lines}");+ assert!(+ lines.contains(r#""raises":"strconv.Atoi: parsing \"\": invalid syntax","derived":"edge"}"#),+ "{lines}"+ );+ assert_eq!(after, lib);+ }+#[test]fn go_commands_and_profiles() {let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();diff --git a/src/golang/bridge.go b/src/golang/bridge.goindex 474f731..ffef658 100644--- a/src/golang/bridge.go+++ b/src/golang/bridge.go@@ -21,15 +21,16 @@ var (faOn_/*S*/ bool)-func faFast_/*S*/(/*PARAMS*/) (/*RET*/, bool) {+// The port's answer, the error it gives where the original returns (T, error), and whether it answered.+func faFast_/*S*/(/*PARAMS*/) (/*RET*/, error, bool) {var zero /*RET*/faOnce_/*S*/.Do(func() { faOn_/*S*/ = os.Getenv("FAST_ANYTHING_DISABLE") == "" && faLoad_/*S*/(/*LIB*/) })if !faOn_/*S*/ {- return zero, false+ return zero, nil, false}in, err := faJSON_/*S*/([]any{/*ARGS*/})if err != nil {- return zero, false // NaN, Inf or non-UTF-8 input: let Go handle it+ return zero, nil, false // NaN, Inf or non-UTF-8 input: let Go handle it}var reply struct {Ok json.RawMessage `json:"ok"`@@ -39,13 +40,16 @@ func faFast_/*S*/(/*PARAMS*/) (/*RET*/, bool) {panic("fast-anything: " + err.Error())}if reply.Error != nil {+ if /*ERRORS*/ {+ return zero, errors.New(*reply.Error), true+ }panic("fast-anything: " + *reply.Error)}var out /*RET*/if err := json.Unmarshal(reply.Ok, &out); err != nil {panic("fast-anything: " + err.Error())}- return out, true+ return out, nil, true}func faJSON_/*S*/(v any) (string, error) {diff --git a/src/golang/describe.go b/src/golang/describe.goindex bad9e54..7f68486 100644--- a/src/golang/describe.go+++ b/src/golang/describe.go@@ -178,21 +178,35 @@ func describe(fset *token.FileSet, src []byte, path, pkg, pkgName string, fd *aslocals[n.Name] = true}}- results := fd.Type.Results+ // result types, one per result (named results are locals of the function too)+ var results []string+ if fd.Type.Results != nil {+ for _, field := range fd.Type.Results.List {+ t := types.ExprString(field.Type)+ if len(field.Names) == 0 {+ results = append(results, t)+ }+ for _, n := range field.Names {+ results = append(results, t)+ locals[n.Name] = true+ }+ }+ }switch {- case results == nil || len(results.List) == 0:+ case len(results) == 0:fn.Blockers = append(fn.Blockers, "returns nothing")- case len(results.List) > 1 || len(results.List[0].Names) > 1:- fn.Blockers = append(fn.Blockers, "returns more than one value")- default:- t := types.ExprString(results.List[0].Type)- fn.Returns = &t- if !supported(t) {- fn.Blockers = append(fn.Blockers, "returns a "+t)+ case len(results) == 1 || (len(results) == 2 && results[1] == "error"):+ // a value, or a value and an error: (T, error), which the port gives as Result<T, String>+ t := results[0]+ if len(results) == 2 {+ t = "(" + t + ", error)"}- if len(results.List[0].Names) > 0 {- fn.Blockers = append(fn.Blockers, "has named results")+ fn.Returns = &t+ if !supported(results[0]) {+ fn.Blockers = append(fn.Blockers, "returns a "+results[0])}+ default:+ fn.Blockers = append(fn.Blockers, "returns more than one value (other than a value and an error)")}io, nondet, helpers := []string{}, []string{}, []string{}seen := map[string]bool{}diff --git a/src/golang/rec.go b/src/golang/rec.goindex 358be5b..d30e478 100644--- a/src/golang/rec.go+++ b/src/golang/rec.go@@ -39,6 +39,38 @@ func init() {expvar.Publish("fast_anything_save", expvar.Func(func() any { fastAnythingRecSave(); return nil }))}+// What a function returning (T, error) gave back.+type fastAnythingRecPair struct {+ V any+ Err error+}++// The result as JSON; for a (T, error) function that returned an error, raised is its message.+func fastAnythingRecResult(r any) (enc string, raised *string, err error) {+ if p, ok := r.(fastAnythingRecPair); ok {+ if p.Err != nil {+ msg := p.Err.Error()+ return "", &msg, nil+ }+ r = p.V+ }+ enc, err = fastAnythingRecJSON(r)+ return enc, nil, err+}++// A derived case: its result, or the error a (T, error) function returned (the port must fail too).+func fastAnythingRecDerived(args string, r any, tag string) (string, bool) {+ re, raised, err := fastAnythingRecResult(r)+ if err != nil {+ return "", false+ }+ if raised != nil {+ q, _ := json.Marshal(*raised)+ return `{"args":` + args + `,"raises":` + string(q) + `,"derived":` + tag + "}", true+ }+ return `{"args":` + args + `,"result":` + re + `,"derived":` + tag + "}", true+}+func fastAnythingRec(args []any, fn func([]any) any) any {fastAnythingRecMu.Lock()defer fastAnythingRecMu.Unlock()@@ -67,8 +99,12 @@ func fastAnythingRec(args []any, fn func([]any) any) any {if after, err := fastAnythingRecJSON(args); err == nil && after != enc {fastAnythingRecMutates = true}- if re, err := fastAnythingRecJSON(r); err == nil {+ if re, raised, err := fastAnythingRecResult(r); err == nil {line := `{"args":` + enc + `,"result":` + re + "}"+ if raised != nil {+ q, _ := json.Marshal(*raised)+ line = `{"args":` + enc + `,"raises":` + string(q) + "}"+ }if slot < len(fastAnythingRecKept) {fastAnythingRecKept[slot], fastAnythingRecArgs[slot] = line, copied} else {@@ -352,11 +388,11 @@ func fastAnythingRecSave() {if !ok {return 0, false}- re, err := fastAnythingRecJSON(r)- if err != nil {+ line, ok := fastAnythingRecDerived(enc, r, `"edge"`)+ if !ok {return 0, false}- derived = append(derived, `{"args":`+enc+`,"result":`+re+`,"derived":"edge"}`)+ derived = append(derived, line)return took, true}grown := map[int]bool{}@@ -430,8 +466,8 @@ outer:if !ok {continue}- if re, err := fastAnythingRecJSON(r); err == nil {- derived = append(derived, `{"args":`+enc+`,"result":`+re+`,"derived":true}`)+ if line, ok := fastAnythingRecDerived(enc, r, "true"); ok {+ derived = append(derived, line)}}}