package nativegen import ( "bytes" "fmt" "go/format" "maps" "regexp" "slices" "sort" "strings" ) const goHeader = "// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.\n" // SourceLine is the line of a generated file that names the declarations // it came from, which `mygo build` compares with the package's. func SourceLine(hash string) string { return "mygo:native " + Version + " " + hash } // GenerateGo writes the Go side: the module's description, a constructor // per entry point and the values that call the implementation, which is // in the languages langs; sp are the platforms of its Swift. func GenerateGo(m *Module, langs []string, sp SwiftPlatforms) ([]byte, error) { var b bytes.Buffer g := &goGen{m: m, b: &b, w: newWire(m)} fmt.Fprintf(&b, "%s// %s\n\npackage %s\n\nIMPORTS\n", goHeader, SourceLine(m.Hash), m.Package) var errs, deps []string for _, e := range m.Errors { errs = append(errs, e.Name) } for _, path := range slices.Sorted(maps.Keys(m.Deps)) { deps = append(deps, fmt.Sprintf("%q", m.Deps[path].Name)) } kotlin := "" if slices.Contains(langs, "kotlin") { kotlin = KotlinClass(m.ImportPath) } if !slices.Contains(langs, "swift") { sp = SwiftPlatforms{} } fmt.Fprintf(&b, ` // _module describes the module to the runtime. var _module = &_native.Module{Name: %q, Symbol: %q, Langs: []string{%s}, SwiftOS: []string{%s}, MinMacOS: %q, MinIOS: %q, Kotlin: %q, Dir: _dir(), Errors: []*_native.Error{%s}, Deps: []string{%s}} // _dir returns the package's directory when the binary knows it, where // mygo dev builds the implementation for go test and go run. func _dir() string { _, file, _, ok := _runtime.Caller(0) if !ok || !_filepath.IsAbs(file) { return "" } return _filepath.Dir(file) } `, m.Name, m.Package, quoteAll(langs), quoteAll(sp.OS), sp.MinMacOS, sp.MinIOS, kotlin, strings.Join(errs, ", "), strings.Join(deps, ", ")) // The values of the platform's interfaces, which other modules wrap // by name. var wraps []string for _, it := range m.Interfaces { if !it.ByGo { wraps = append(wraps, fmt.Sprintf("%q: {Flags: %s, Wrap: func(o *_native.Object) any { return &%s{o} }},", it.Name, flagsOf(it.MainThread), proxyName(it))) } } fmt.Fprintf(&b, "\nfunc init() {\n\t_native.Register(_module, map[string]_native.Wrapper{\n%s\n\t})\n}\n", strings.Join(wraps, "\n")) foreign := map[string]*Type{} for _, it := range m.Interfaces { for _, me := range it.Methods { if t := me.Result; t != nil && t.Kind == InterfaceType && t.Pkg != nil { foreign[wrapName(t)] = t } } } for _, name := range slices.Sorted(maps.Keys(foreign)) { t := foreign[name] fmt.Fprintf(&b, "\n// %s wraps an object of the native module %s.\nfunc %s(h uint64) %s {\n\tv, _ := _native.Wrap(h, %q, %q).(%s)\n\treturn v\n}\n", name, t.Pkg.Name, name, t.Go, t.Pkg.Name, t.Name, t.Go) } for _, it := range m.Interfaces { if it.ByGo { g.dispatch(it) } else { g.proxy(it) } } g.w.goFuncs(g.p) out := b.String() var imports []string for path, mod := range g.w.extra { imports = append(imports, fmt.Sprintf("_%s %q", mod.Package, path)) } uses := func(pkg string) bool { return regexp.MustCompile(`(^|[^A-Za-z0-9_.])` + pkg + `\.`).MatchString(out) } for path, qual := range m.Quals { if path[strings.LastIndex(path, "/")+1:] == qual { imports = append(imports, fmt.Sprintf("%q", path)) } else { imports = append(imports, fmt.Sprintf("%s %q", qual, path)) } } // What the signatures name, under the names the interface uses. for path, used := range map[string]bool{ nativePath: uses("native"), "context": uses("context"), "iter": uses("iter"), "io": uses("io"), "time": uses("time"), mygoPath: uses("mygo"), uiPath: uses("ui"), } { if used { imports = append(imports, fmt.Sprintf("%q", path)) } } // What the generated code calls, under names no parameter takes. for path, alias := range map[string]string{ nativePath: "_native", "runtime": "_runtime", "path/filepath": "_filepath", "context": "_context", "fmt": "_fmt", } { if strings.Contains(out, alias+".") { imports = append(imports, fmt.Sprintf("%s %q", alias, path)) } } sort.Slice(imports, func(i, j int) bool { return importKey(imports[i]) < importKey(imports[j]) }) var std, other []string for _, imp := range imports { if strings.Contains(imp, ".") { other = append(other, imp) } else { std = append(std, imp) } } out = strings.Replace(out, "IMPORTS", "import (\n"+strings.Join(std, "\n")+"\n\n"+strings.Join(other, "\n")+"\n)", 1) src, err := format.Source([]byte(out)) if err != nil { return nil, fmt.Errorf("nativegen: formatting the Go of %s: %v\n%s", m.Package, err, out) } return src, nil } func quoteAll(list []string) string { var q []string for _, s := range list { q = append(q, fmt.Sprintf("%q", s)) } return strings.Join(q, ", ") } type goGen struct { m *Module b *bytes.Buffer w *wire } func (g *goGen) p(format string, args ...any) { fmt.Fprintf(g.b, format, args...) } func proxyName(it *Interface) string { return "_" + it.Name } // wrapName is the function that wraps a handle of an interface type. func wrapName(t *Type) string { if t.Pkg != nil { return "_wrap" + t.Pkg.Name + "_" + t.Name } return "_wrap" + t.Name } // importKey sorts an import line by its path. func importKey(s string) string { return s[strings.Index(s, `"`):] } func flagsOf(mt bool) string { if mt { return "_native.MainThread" } return "0" } // signature writes a method's Go signature, as the interface declares it. func signature(m *Method) string { var ps []string if m.Ctx { ps = append(ps, "_ctx context.Context") } for _, p := range m.Params { ps = append(ps, p.Name+" "+p.Type.Go) } res := "" switch { case m.Stream == 1: res = " iter.Seq[" + m.Result.Go + "]" case m.Stream == 2: res = " iter.Seq2[" + m.Result.Go + ", error]" case m.Closer: res = " io.Closer" case m.Result != nil && m.Err: res = " (" + m.Result.Go + ", error)" case m.Result != nil: res = " " + m.Result.Go case m.Err: res = " error" } return m.Name + "(" + strings.Join(ps, ", ") + ")" + res } func (g *goGen) proxy(it *Interface) { name := proxyName(it) if it.Entry { g.p("\n// New%s makes the implementation of %s on this platform. It returns\n// errors.ErrUnsupported where the module has none, or the system lacks\n// what it needs.\nfunc New%s() (%s, error) {\n", it.Name, it.Name, it.Name, it.Name) g.p("\to, err := _module.New(%q, %s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &%s{o}, nil\n}\n", it.Name, flagsOf(it.MainThread), name) } g.p("\n// %s calls the platform's implementation of %s.\ntype %s struct{ o *_native.Object }\n", name, it.Name, name) g.p("\n// NativeObject returns the platform's object.\nfunc (x *%s) NativeObject() *_native.Object { return x.o }\n", name) if it.View { g.p("\n// NativeView returns the platform's view, or 0 once closed.\nfunc (x *%s) NativeView() uintptr { return x.o.View() }\n", name) } g.p("\n// %s wraps a handle of the platform's, or returns nil.\nfunc _wrap%s(h uint64) %s {\n\tif h == 0 {\n\t\treturn nil\n\t}\n\treturn &%s{_module.Object(h, %s)}\n}\n", "_wrap"+it.Name, it.Name, it.Name, name, flagsOf(it.MainThread)) for _, m := range it.Methods { g.method(it, m) } } // The generated methods name their own identifiers with a leading // underscore, which the parser keeps out of the interface's parameter // names, so that none clashes: the receiver _x, the context _ctx, the // locals _err, _r, _h, _fN and _gN, and the packages they call, imported // as _native, _runtime, _context and _fmt. The signatures keep the // interface's own names and packages. // keptAlive reports whether an argument of type t is a value of Go's that // stands for memory or an object of the platform's, which must stay // reachable until the platform is done with it. func keptAlive(t *Type) bool { switch t.Kind { case Buffer, View: return true case InterfaceType: return !t.Iface.ByGo } return false } // argExprs returns the statements that write a call's arguments to the // encoder _e, with the statements that prepare them, the handles of its // callbacks and values of Go's, and the arguments to keep alive. func (g *goGen) argExprs(m *Method) (pre []string, enc []string, funcs []string, keep []string) { for i, p := range m.Params { if keptAlive(p.Type) { keep = append(keep, p.Name) } switch p.Type.Kind { case Func: v := fmt.Sprintf("_f%d", i) pre = append(pre, fmt.Sprintf("var %s uint64\n\tif %s != nil {\n\t\t%s = _native.Func(%s, %v)\n\t}", v, p.Name, v, g.funcWrapper(p.Name, p.Type), notifies(p.Type))) enc = append(enc, "_e.Uint("+v+")") funcs = append(funcs, v) case InterfaceType: if p.Type.Iface.ByGo { v := fmt.Sprintf("_g%d", i) pre = append(pre, fmt.Sprintf("var %s uint64\n\tif %s != nil {\n\t\t%s = _native.Export(_module, %s, func(_c _context.Context, _m int, _d *_native.Decoder, _e *_native.Encoder) error { return _dispatch%s(%s, _c, _m, _d, _e) })\n\t}", v, p.Name, v, p.Name, p.Type.Iface.Name, p.Name)) enc = append(enc, "_e.Uint("+v+")") funcs = append(funcs, v) } else { enc = append(enc, g.w.goEnc(ref{p.Type, g.m}, p.Name)) } default: enc = append(enc, g.w.goEnc(ref{p.Type, g.m}, p.Name)) } } return } func notifies(t *Type) bool { return t.Result == nil && !t.Err } // decodeParams writes the statements that read params from _d into _p0, // _p1 …, and returns their names. func (g *goGen) decodeParams(b *strings.Builder, params []*Param) []string { var names []string for i, p := range params { fmt.Fprintf(b, "_p%d := %s\n", i, g.w.goDec(ref{p.Type, g.m})) names = append(names, fmt.Sprintf("_p%d", i)) } if len(params) > 0 { b.WriteString("if _err := _d.Err(); _err != nil {\nreturn _err\n}\n") } return names } // returnResult writes the statements that call c, which returns a value // of t (or none) and an error if err, write its value to _e, and return // its error. func (g *goGen) returnResult(b *strings.Builder, c string, t *Type, err bool) { switch { case t != nil && err: fmt.Fprintf(b, "_r, _err := %s\nif _err != nil {\nreturn _err\n}\n%s\nreturn nil\n", c, g.w.goEnc(ref{t, g.m}, "_r")) case t != nil: fmt.Fprintf(b, "_r := %s\n%s\nreturn nil\n", c, g.w.goEnc(ref{t, g.m}, "_r")) case err: b.WriteString("return " + c + "\n") default: b.WriteString(c + "\nreturn nil\n") } } // funcWrapper returns a function that calls the Go function fn, of type // t, with the arguments in _d, and writes its result to _e. func (g *goGen) funcWrapper(fn string, t *Type) string { var b strings.Builder b.WriteString("func(_d *_native.Decoder, _e *_native.Encoder) error {\n") call := g.decodeParams(&b, t.Params) g.returnResult(&b, fn+"("+strings.Join(call, ", ")+")", t.Result, t.Err) b.WriteString("}") return b.String() } func (g *goGen) method(it *Interface, m *Method) { name := proxyName(it) g.p("\nfunc (_x *%s) %s {\n", name, signature(m)) sym := it.Name + "_" + m.Name flags := flagsOf(m.MainThread) if m.Close { g.p("\treturn _x.NativeObject().Close()\n}\n") return } if direct(m) { g.direct(sym, m) return } pre, enc, funcs, keep := g.argExprs(m) args := "nil" encode := "" if len(enc) > 0 { args = "_e" encode = "_e := _native.NewEncoder()\n" + strings.Join(enc, "\n") + "\n" } if m.Stream != 0 { // The arguments are made as the loop starts the stream, which // holds what it is given until it ends. funcList := "nil" if len(funcs) > 0 { funcList = "[]uint64{" + strings.Join(funcs, ", ") + "}" } prepare := "func() (*_native.Encoder, []uint64) {\n" for _, s := range pre { prepare += s + "\n" } prepare += encode + "return " + args + ", " + funcList + "\n}" T := g.w.goType(ref{m.Result, g.m}) dec := g.w.goDec(ref{m.Result, g.m}) if m.Result.Kind == InterfaceType { dec = wrapName(m.Result) + "(" + dec + ")" } expr := fmt.Sprintf("_native.Stream(_ctx, _x.NativeObject(), %q, %s, %s, func(_d *_native.Decoder) %s { return %s }%s)", sym, flags, prepare, T, dec, prefixComma(keep)) if m.Stream == 1 { expr = "_native.Seq(" + expr + ")" } g.p("\treturn %s\n}\n", expr) return } for _, s := range pre { g.p("\t%s\n", s) } for _, k := range keep { g.p("\tdefer _runtime.KeepAlive(%s)\n", k) } g.p("%s", encode) forget := "" if len(funcs) > 0 { forget = "\t\t_native.Forget(" + strings.Join(funcs, ", ") + ")\n" } if m.Closer { g.p("\treturn _x.NativeObject().Subscribe(%q, %s, %s%s)\n}\n", sym, flags, args, prefixComma(funcs)) return } call := fmt.Sprintf("_x.NativeObject().Call(%q, %s, %s)", sym, flags, args) if m.Ctx { call = fmt.Sprintf("_x.NativeObject().CallContext(_ctx, %q, %s, %s)", sym, flags, args) } ret := func(v string) string { if m.Err { return "return " + v + ", _err" } return "return " + v } switch { case m.Result == nil: g.p("\t_d, _err := %s\n\tif _err == nil {\n\t\t_err = _d.Close()\n\t}\n", call) if forget != "" { g.p("\tif _err != nil {\n%s\t}\n", forget) } if m.Err { g.p("\treturn _err\n") } else if forget == "" { g.p("\t_ = _err\n") } case m.Result.Kind == InterfaceType: g.p("\tvar _h uint64\n\t_d, _err := %s\n\tif _err == nil {\n\t\t_h = _d.Uint()\n\t\t_err = _d.Close()\n\t}\n", call) g.p("\tif _err != nil {\n%s\t\t%s\n\t}\n", forget, ret("nil")) if m.Err { g.p("\treturn %s(_h), nil\n", wrapName(m.Result)) } else { g.p("\treturn %s(_h)\n", wrapName(m.Result)) } default: g.p("\tvar _r %s\n\t_d, _err := %s\n\tif _err == nil {\n\t\t_r = %s\n\t\t_err = _d.Close()\n\t}\n", m.Result.Go, call, g.w.goDec(ref{m.Result, g.m})) if forget != "" { g.p("\tif _err != nil {\n%s\t}\n", forget) } if !m.Err { g.p("\t_ = _err\n") } g.p("\t%s\n", ret("_r")) } g.p("}\n") } // direct writes the body of a method of numbers, which calls the C // function of the implementation with them. func (g *goGen) direct(sym string, m *Method) { var args []string for _, p := range m.Params { switch p.Type.Kind { case Bool: args = append(args, "_native.BoolArg("+p.Name+")") case Float: args = append(args, "_native.FloatArg(float64("+p.Name+"))") default: args = append(args, "uintptr("+p.Name+")") } } call := fmt.Sprintf("_x.NativeObject().Direct(%q%s)", sym+"_direct", prefixComma(args)) switch { case m.Result == nil: g.p("\t%s\n}\n", call) case m.Result.Kind == Bool: g.p("\treturn %s != 0\n}\n", call) case m.Result.Kind == Float: g.p("\treturn %s(_native.FloatResult(%s))\n}\n", m.Result.Go, call) default: g.p("\treturn %s(%s)\n}\n", m.Result.Go, call) } } func prefixComma(s []string) string { if len(s) == 0 { return "" } return ", " + strings.Join(s, ", ") } // dispatch writes the function the platform calls the methods of a Go // value of an interface Go implements through. func (g *goGen) dispatch(it *Interface) { g.p("\n// _dispatch%s calls the method number _m of _v for the platform, with\n// the arguments in _d, and writes its result to _e.\nfunc _dispatch%s(_v %s, _ctx _context.Context, _m int, _d *_native.Decoder, _e *_native.Encoder) error {\n\tswitch _m {\n", it.Name, it.Name, it.Name) for i, m := range it.Methods { g.p("\tcase %d:\n", i) var b strings.Builder call := g.decodeParams(&b, m.Params) if m.Ctx { call = append([]string{"_ctx"}, call...) } g.returnResult(&b, "_v."+m.Name+"("+strings.Join(call, ", ")+")", m.Result, m.Err) g.p("%s", b.String()) } g.p("\t}\n\treturn _fmt.Errorf(\"native: %s has no method %%d\", _m)\n}\n", it.Name) }