feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+465
@@ -0,0 +1,465 @@
|
||||
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)
|
||||
}
|
||||
+668
@@ -0,0 +1,668 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// KotlinFile is the name of the generated Kotlin file of a module.
|
||||
func KotlinFile(m *Module) string { return m.Name + ".mygo.kt" }
|
||||
|
||||
// KotlinDir is the directory of a module's Kotlin sources: its package's.
|
||||
func KotlinDir(m *Module) string {
|
||||
return filepath.Join(append([]string{m.Dir, "kotlin", "src", "main", "kotlin"}, strings.Split(KotlinPackage(m.ImportPath), ".")...)...)
|
||||
}
|
||||
|
||||
// KotlinPackage is the package of a module's Kotlin, which its own Kotlin
|
||||
// is in too: its import path's host reversed, then its path, as
|
||||
// github.com/acme/go-battery gives com.github.acme.go_battery.
|
||||
func KotlinPackage(importPath string) string {
|
||||
parts := strings.Split(importPath, "/")
|
||||
var segs []string
|
||||
if strings.Contains(parts[0], ".") {
|
||||
host := strings.Split(parts[0], ".")
|
||||
for i := len(host) - 1; i >= 0; i-- {
|
||||
segs = append(segs, host[i])
|
||||
}
|
||||
parts = parts[1:]
|
||||
}
|
||||
segs = append(segs, parts...)
|
||||
for i, s := range segs {
|
||||
var b strings.Builder
|
||||
for _, c := range strings.ToLower(s) {
|
||||
if c < 128 && (unicode.IsLetter(c) || unicode.IsDigit(c)) {
|
||||
b.WriteRune(c)
|
||||
} else {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
s = b.String()
|
||||
if s == "" || unicode.IsDigit(rune(s[0])) {
|
||||
s = "_" + s
|
||||
}
|
||||
if kotlinKeywords[s] || javaKeywords[s] {
|
||||
s += "_"
|
||||
}
|
||||
segs[i] = s
|
||||
}
|
||||
return strings.Join(segs, ".")
|
||||
}
|
||||
|
||||
// KotlinClass is the class of a module's generated object, which Android
|
||||
// loads it by.
|
||||
func KotlinClass(importPath string) string { return KotlinPackage(importPath) + ".MygoModule" }
|
||||
|
||||
// KotlinNamespace is the Android namespace of a module's Gradle library.
|
||||
func KotlinNamespace(importPath string) string { return KotlinPackage(importPath) }
|
||||
|
||||
var kotlinKeywords = wordSet("as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while")
|
||||
|
||||
var javaKeywords = wordSet("abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while")
|
||||
|
||||
func wordSet(s string) map[string]bool {
|
||||
m := map[string]bool{}
|
||||
for _, w := range strings.Fields(s) {
|
||||
m[w] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// kotlinIdent escapes a Kotlin keyword used as a name.
|
||||
func kotlinIdent(s string) string {
|
||||
if kotlinKeywords[s] {
|
||||
return "`" + s + "`"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// upperSnake is a Go name in upper snake case, the name of a Kotlin enum
|
||||
// constant: ModeFast → MODE_FAST, URLFor → URL_FOR.
|
||||
func upperSnake(s string) string {
|
||||
r := []rune(s)
|
||||
var b strings.Builder
|
||||
for i, c := range r {
|
||||
if i > 0 && unicode.IsUpper(c) && (unicode.IsLower(r[i-1]) || unicode.IsDigit(r[i-1]) || i+1 < len(r) && unicode.IsLower(r[i+1]) && unicode.IsUpper(r[i-1])) {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
b.WriteRune(unicode.ToUpper(c))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// modulePath returns the import path of the package in dir, from the
|
||||
// go.mod above it, or "" when there is none.
|
||||
func modulePath(dir string) string {
|
||||
for d := dir; ; d = filepath.Dir(d) {
|
||||
f, err := os.Open(filepath.Join(d, "go.mod"))
|
||||
if err == nil {
|
||||
defer f.Close()
|
||||
s := bufio.NewScanner(f)
|
||||
for s.Scan() {
|
||||
line := strings.TrimSpace(s.Text())
|
||||
if mod, ok := strings.CutPrefix(line, "module "); ok {
|
||||
mod = strings.Trim(strings.TrimSpace(mod), `"`)
|
||||
rel, err := filepath.Rel(d, dir)
|
||||
if err != nil || rel == "." {
|
||||
return mod
|
||||
}
|
||||
return mod + "/" + filepath.ToSlash(rel)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if filepath.Dir(d) == d {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const kotlinHeader = "// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.\n"
|
||||
|
||||
// GenerateKotlin writes the Kotlin side: the interfaces the implementation
|
||||
// implements, the data classes and enums of the Go side, the errors, and
|
||||
// the object Go calls.
|
||||
func GenerateKotlin(m *Module) ([]byte, error) {
|
||||
if err := portable(m, "Kotlin"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var b bytes.Buffer
|
||||
g := &kotlinGen{m: m, b: &b, w: newWire(m)}
|
||||
g.p("%s// %s\n//\n// The declarations of package %s, which the implementation implements,\n// and the object Go calls. See docs/native-modules.md.\n\n", kotlinHeader, SourceLine(m.Hash), m.Package)
|
||||
g.p("@file:Suppress(\"unused\", \"UNUSED_PARAMETER\", \"UNUSED_VARIABLE\", \"RedundantVisibilityModifier\", \"FunctionName\", \"ClassName\", \"LocalVariableName\")\n\n")
|
||||
g.p("package %s\n\nimport dev.mygo.GoFunc\nimport dev.mygo.NativeBuffer\nimport dev.mygo.NativeCodedError\nimport dev.mygo.NativeModule\nimport dev.mygo.NativeReader\nimport dev.mygo.NativeWireException\nimport dev.mygo.NativeWriter\nimport kotlinx.coroutines.flow.Flow\n", KotlinPackage(m.ImportPath))
|
||||
for _, it := range m.Interfaces {
|
||||
g.iface(it)
|
||||
}
|
||||
for _, s := range m.Structs {
|
||||
g.structDecl(s)
|
||||
}
|
||||
for _, e := range m.Enums {
|
||||
g.enumDecl(e)
|
||||
}
|
||||
g.errorsDecl()
|
||||
g.module()
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
g.goProxy(it)
|
||||
}
|
||||
}
|
||||
g.funcs()
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
type kotlinGen struct {
|
||||
m *Module
|
||||
b *bytes.Buffer
|
||||
w *wire
|
||||
}
|
||||
|
||||
func (g *kotlinGen) p(format string, args ...any) { fmt.Fprintf(g.b, format, args...) }
|
||||
|
||||
func kdoc(doc, indent string) string {
|
||||
if doc == "" {
|
||||
return ""
|
||||
}
|
||||
doc = strings.ReplaceAll(strings.TrimRight(doc, "\n"), "*/", "* /")
|
||||
var b strings.Builder
|
||||
b.WriteString(indent + "/**\n")
|
||||
for line := range strings.Lines(doc) {
|
||||
line = strings.TrimRight(line, "\n")
|
||||
if line == "" {
|
||||
b.WriteString(indent + " *\n")
|
||||
} else {
|
||||
b.WriteString(indent + " * " + line + "\n")
|
||||
}
|
||||
}
|
||||
b.WriteString(indent + " */\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// kt is the Kotlin spelling of a type.
|
||||
func (g *kotlinGen) kt(r ref) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return "Boolean"
|
||||
case Int:
|
||||
var s string
|
||||
switch t.Bits {
|
||||
case 8:
|
||||
s = "Byte"
|
||||
case 16:
|
||||
s = "Short"
|
||||
case 32:
|
||||
s = "Int"
|
||||
default:
|
||||
s = "Long"
|
||||
}
|
||||
if t.Unsigned {
|
||||
return "U" + s
|
||||
}
|
||||
return s
|
||||
case Float:
|
||||
if t.Bits == 32 {
|
||||
return "Float"
|
||||
}
|
||||
return "Double"
|
||||
case String:
|
||||
return "String"
|
||||
case Bytes:
|
||||
return "ByteArray"
|
||||
case Time:
|
||||
return "java.time.Instant"
|
||||
case Duration:
|
||||
return "kotlin.time.Duration"
|
||||
case Slice:
|
||||
return "List<" + g.kt(r.elem()) + ">"
|
||||
case Map:
|
||||
return "Map<String, " + g.kt(r.elem()) + ">"
|
||||
case Pointer:
|
||||
return strings.TrimSuffix(g.kt(r.elem()), "?") + "?"
|
||||
case StructType, EnumType:
|
||||
if mod := r.module(); mod != g.m {
|
||||
return KotlinPackage(mod.ImportPath) + "." + t.Name
|
||||
}
|
||||
return t.Name
|
||||
case InterfaceType:
|
||||
return t.Name
|
||||
case Window, View:
|
||||
return "android.view.View"
|
||||
case Rect:
|
||||
return "android.graphics.RectF"
|
||||
case Buffer:
|
||||
return "NativeBuffer"
|
||||
case Func:
|
||||
var ps []string
|
||||
for _, p := range t.Params {
|
||||
ps = append(ps, g.kt(ref{p.Type, r.owner}))
|
||||
}
|
||||
res := "kotlin.Unit" // qualified: a type of the package may be named Unit
|
||||
if t.Result != nil {
|
||||
res = g.kt(ref{t.Result, r.owner})
|
||||
}
|
||||
return "(" + strings.Join(ps, ", ") + ") -> " + res
|
||||
}
|
||||
return "Nothing"
|
||||
}
|
||||
|
||||
func (g *kotlinGen) typ(t *Type) string { return g.kt(ref{t, g.m}) }
|
||||
|
||||
// ktDefault is what a Go nil decodes to, for the types Go encodes as empty
|
||||
// when nil: the default of a data class's property.
|
||||
func ktDefault(t *Type) string {
|
||||
switch t.Kind {
|
||||
case Slice:
|
||||
return "emptyList()"
|
||||
case Map:
|
||||
return "emptyMap()"
|
||||
case Bytes:
|
||||
return "ByteArray(0)"
|
||||
case Pointer:
|
||||
return "null"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func ktMethodName(m *Method) string { return kotlinIdent(lowerCamel(m.Name)) }
|
||||
|
||||
func (g *kotlinGen) signature(m *Method) string {
|
||||
var ps []string
|
||||
for _, p := range m.Params {
|
||||
ps = append(ps, kotlinIdent(p.Name)+": "+g.typ(p.Type))
|
||||
}
|
||||
s := "fun " + ktMethodName(m) + "(" + strings.Join(ps, ", ") + ")"
|
||||
switch {
|
||||
case m.Stream != 0:
|
||||
return s + ": Flow<" + g.typ(m.Result) + ">"
|
||||
case m.Closer:
|
||||
return s + ": AutoCloseable"
|
||||
}
|
||||
if m.Ctx {
|
||||
s = "suspend " + s
|
||||
}
|
||||
if m.Result != nil {
|
||||
s += ": " + g.typ(m.Result)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (g *kotlinGen) iface(it *Interface) {
|
||||
doc := it.Doc
|
||||
note := ""
|
||||
switch {
|
||||
case it.ByGo:
|
||||
note = "Go implements it: the module's Kotlin calls it."
|
||||
case it.View:
|
||||
note = "Its implementations are android.view.Views."
|
||||
}
|
||||
if it.MainThread {
|
||||
note = strings.TrimSpace(note + " Its methods run on the main thread.")
|
||||
}
|
||||
if note != "" {
|
||||
if doc != "" {
|
||||
doc += "\n"
|
||||
}
|
||||
doc += note
|
||||
}
|
||||
g.p("\n%s", kdoc(doc, ""))
|
||||
super := ""
|
||||
if it.Closer {
|
||||
super = " : AutoCloseable"
|
||||
}
|
||||
g.p("interface %s%s {\n", it.Name, super)
|
||||
for _, m := range it.Methods {
|
||||
if m.Close {
|
||||
continue
|
||||
}
|
||||
doc := m.Doc
|
||||
if m.MainThread && !it.MainThread {
|
||||
doc = strings.TrimSpace(doc + "\nIt runs on the main thread.")
|
||||
}
|
||||
g.p("%s %s\n", kdoc(doc, " "), g.signature(m))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
func (g *kotlinGen) structDecl(s *Struct) {
|
||||
g.p("\n%s", kdoc(s.Doc, ""))
|
||||
if len(s.Fields) == 0 {
|
||||
g.p("class %s {\n override fun equals(other: Any?): Boolean = other is %s\n override fun hashCode(): Int = 0\n}\n", s.Name, s.Name)
|
||||
return
|
||||
}
|
||||
g.p("data class %s(\n", s.Name)
|
||||
for _, f := range s.Fields {
|
||||
def := ktDefault(f.Type)
|
||||
if def != "" {
|
||||
def = " = " + def
|
||||
}
|
||||
g.p("%s val %s: %s%s,\n", kdoc(f.Doc, " "), kotlinIdent(lowerCamel(f.Name)), g.typ(f.Type), def)
|
||||
}
|
||||
g.p(")\n")
|
||||
}
|
||||
|
||||
func (g *kotlinGen) enumDecl(e *Enum) {
|
||||
raw, lit := "String", func(v string) string { return v }
|
||||
if !e.String {
|
||||
raw, lit = "Long", func(v string) string { return v + "L" }
|
||||
}
|
||||
g.p("\n%senum class %s(val value: %s) {\n", kdoc(e.Doc, ""), e.Name, raw)
|
||||
for _, c := range e.Cases {
|
||||
g.p("%s %s(%s),\n", kdoc(c.Doc, " "), upperSnake(c.Name), lit(c.Value))
|
||||
}
|
||||
g.p(" ;\n\n companion object {\n /** The constant of a value, which Go sent. */\n fun of(value: %s): %s = entries.firstOrNull { it.value == value } ?: throw NativeWireException(\"native: %s has no constant $value\")\n }\n}\n", raw, e.Name, e.Name)
|
||||
}
|
||||
|
||||
func (g *kotlinGen) errorsDecl() {
|
||||
n := g.m.Name
|
||||
g.p("\n/**\n * The errors package %s declares, with native.NewError: throw\n * %sException(%sError.X) for Go to get that error, which errors.Is\n * compares.\n */\nenum class %sError(val code: String) {\n", g.m.Package, n, n, n)
|
||||
for _, e := range g.m.Errors {
|
||||
g.p("%s %s(%q),\n", kdoc(e.Doc, " "), upperSnake(strings.TrimPrefix(e.Name, "Err")), e.Code)
|
||||
}
|
||||
g.p(" ;\n}\n\n/** An error package %s declares. */\nclass %sException(val error: %sError, message: String = error.code) : Exception(message), NativeCodedError {\n override val nativeCode: String get() = error.code\n}\n", g.m.Package, n, n)
|
||||
}
|
||||
|
||||
// readArgs returns the statements that read a method's arguments, as _p0,
|
||||
// _p1 …, and the expressions the implementation takes them as.
|
||||
func (g *kotlinGen) readArgs(m *Method) (stmts, vals []string) {
|
||||
if len(m.Params) > 0 {
|
||||
stmts = append(stmts, "val _a = NativeReader(args)")
|
||||
}
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("_p%d", i)
|
||||
stmts = append(stmts, "val "+v+" = "+g.w.kotlinRead(g, ref{p.Type, g.m}, "_a"))
|
||||
switch p.Type.Kind {
|
||||
case InterfaceType:
|
||||
if p.Type.Iface.ByGo {
|
||||
v = fmt.Sprintf("_Go%s(%s)", p.Type.Iface.Name, v)
|
||||
} else {
|
||||
v = fmt.Sprintf("obj<%s>(%s)", p.Type.Name, v)
|
||||
}
|
||||
case Window:
|
||||
v = fmt.Sprintf("window(%s)", v)
|
||||
case View:
|
||||
v = fmt.Sprintf("obj<android.view.View>(%s)", v)
|
||||
case Rect:
|
||||
for j, q := range m.Params {
|
||||
if q.Type.Kind == Window {
|
||||
v = fmt.Sprintf("pixels(%s, window(_p%d))", v, j)
|
||||
break
|
||||
}
|
||||
}
|
||||
case Func:
|
||||
f := fmt.Sprintf("_f%d", i)
|
||||
gf := fmt.Sprintf("_g%d", i)
|
||||
stmts = append(stmts, "val "+gf+" = goFunc("+v+")")
|
||||
stmts = append(stmts, "val "+f+": "+g.typ(p.Type)+" = "+g.closure(gf, p.Type))
|
||||
v = f
|
||||
}
|
||||
vals = append(vals, v)
|
||||
}
|
||||
return stmts, vals
|
||||
}
|
||||
|
||||
// closure is a Kotlin lambda calling the Go function f.
|
||||
func (g *kotlinGen) closure(f string, t *Type) string {
|
||||
var names []string
|
||||
body := []string{"val _cw = NativeWriter()"}
|
||||
for i, p := range t.Params {
|
||||
n := fmt.Sprintf("q%d", i)
|
||||
names = append(names, n)
|
||||
body = append(body, g.w.kotlinWrite(g, ref{p.Type, g.m}, "_cw", n))
|
||||
}
|
||||
switch {
|
||||
case t.Result == nil && !t.Err:
|
||||
body = append(body, f+".notify(_cw)")
|
||||
case t.Result == nil:
|
||||
body = append(body, f+".ask(_cw) { }")
|
||||
default:
|
||||
body = append(body, f+".ask(_cw) { _r -> "+g.w.kotlinRead(g, ref{t.Result, g.m}, "_r")+" }")
|
||||
}
|
||||
params := ""
|
||||
if len(names) > 0 {
|
||||
params = " " + strings.Join(names, ", ") + " ->"
|
||||
}
|
||||
return "{" + params + "\n " + strings.Join(body, "\n ") + "\n }"
|
||||
}
|
||||
|
||||
func (g *kotlinGen) module() {
|
||||
g.p("\n/** What Go calls: the functions of the module, by name. */\nobject MygoModule : NativeModule() {\n")
|
||||
g.p(" override fun invoke(sym: String, h: Long, args: ByteArray, call: Long): ByteArray = when (sym) {\n")
|
||||
var directs []string
|
||||
for _, it := range g.m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
if it.Entry {
|
||||
g.p(" %q -> answer { _w -> _w.u64(retain(make%s())) }\n", "new_"+it.Name, it.Name)
|
||||
}
|
||||
for _, m := range it.Methods {
|
||||
if m.Close {
|
||||
continue
|
||||
}
|
||||
if direct(m) {
|
||||
directs = append(directs, g.direct(it, m))
|
||||
}
|
||||
g.entry(it, m)
|
||||
}
|
||||
}
|
||||
g.p(" \"close\" -> answer { close(h) }\n else -> unknown(sym)\n }\n")
|
||||
if len(directs) > 0 {
|
||||
g.p("\n override fun direct(sym: String, h: Long, args: LongArray): Long = try {\n when (sym) {\n%s else -> 0L\n }\n } catch (e: Throwable) {\n 0L\n }\n", strings.Join(directs, ""))
|
||||
}
|
||||
g.p("\n override fun error(code: String): Throwable? = %sError.entries.firstOrNull { it.code == code }?.let { %sException(it) }\n", g.m.Name, g.m.Name)
|
||||
g.p("\n /** A handle of an object of the implementation, which Go holds. */\n fun handle(v: Any): Long = retain(v)\n}\n")
|
||||
}
|
||||
|
||||
func (g *kotlinGen) entry(it *Interface, m *Method) {
|
||||
sym := it.Name + "_" + m.Name
|
||||
stmts, vals := g.readArgs(m)
|
||||
call := "_o." + ktMethodName(m) + "(" + strings.Join(vals, ", ") + ")"
|
||||
prelude := fmt.Sprintf(" val _o: %s = obj(h)\n", it.Name)
|
||||
for _, s := range stmts {
|
||||
prelude += " " + s + "\n"
|
||||
}
|
||||
main := "false"
|
||||
if m.MainThread {
|
||||
main = "true"
|
||||
}
|
||||
switch {
|
||||
case m.Stream != 0:
|
||||
g.p(" %q -> start {\n%s stream(call, %s, { %s }) { _w, _r -> %s }\n }\n", sym, prelude, main, call, g.w.kotlinWrite(g, ref{m.Result, g.m}, "_w", "_r"))
|
||||
case m.Async():
|
||||
body := call
|
||||
if m.Result != nil {
|
||||
body = "val _r = " + call + "\n " + g.w.kotlinWrite(g, ref{m.Result, g.m}, "_w", "_r")
|
||||
}
|
||||
g.p(" %q -> start {\n%s task(call, %s) { _w ->\n %s\n }\n }\n", sym, prelude, main, body)
|
||||
default:
|
||||
g.p(" %q -> answer { _w ->\n%s", sym, prelude)
|
||||
switch {
|
||||
case m.Closer:
|
||||
g.p(" _w.u64(retain(%s))\n", call)
|
||||
case m.Result != nil:
|
||||
g.p(" val _r = %s\n %s\n", call, g.w.kotlinWrite(g, ref{m.Result, g.m}, "_w", "_r"))
|
||||
default:
|
||||
g.p(" %s\n", call)
|
||||
}
|
||||
g.p(" }\n")
|
||||
}
|
||||
}
|
||||
|
||||
// direct returns the case of the direct function of a method of numbers,
|
||||
// whose arguments and result are their bits: integers as themselves,
|
||||
// floats as a Double's, bools as 0 or 1.
|
||||
func (g *kotlinGen) direct(it *Interface, m *Method) string {
|
||||
var vals []string
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("args[%d]", i)
|
||||
t := p.Type
|
||||
switch {
|
||||
case t.Kind == Bool:
|
||||
v += " != 0L"
|
||||
case t.Kind == Float && t.Bits == 32:
|
||||
v = "Double.fromBits(" + v + ").toFloat()"
|
||||
case t.Kind == Float:
|
||||
v = "Double.fromBits(" + v + ")"
|
||||
default:
|
||||
v += ktFromLong(g.typ(t))
|
||||
}
|
||||
vals = append(vals, v)
|
||||
}
|
||||
call := "obj<" + it.Name + ">(h)." + ktMethodName(m) + "(" + strings.Join(vals, ", ") + ")"
|
||||
t := m.Result
|
||||
var body string
|
||||
switch {
|
||||
case t == nil:
|
||||
body = call + "\n 0L"
|
||||
case t.Kind == Bool:
|
||||
body = "if (" + call + ") 1L else 0L"
|
||||
case t.Kind == Float:
|
||||
body = call + ".toDouble().toRawBits()"
|
||||
default:
|
||||
body = call + ".toLong()"
|
||||
}
|
||||
return fmt.Sprintf(" %q -> {\n %s\n }\n", it.Name+"_"+m.Name+"_direct", body)
|
||||
}
|
||||
|
||||
// ktFromLong converts a Long to the integer type t.
|
||||
func ktFromLong(t string) string {
|
||||
if t == "Long" {
|
||||
return ""
|
||||
}
|
||||
return ".to" + t + "()"
|
||||
}
|
||||
|
||||
// goProxy writes the class through which the implementation calls a value
|
||||
// of an interface Go implements.
|
||||
func (g *kotlinGen) goProxy(it *Interface) {
|
||||
g.p("\n/** Calls a Go value implementing %s. */\ninternal class _Go%s(private val _id: Long) : %s {\n init {\n if (_id == 0L) throw NativeWireException(\"%s: Go passed nil for %s\")\n MygoModule.releaseWith(this, _id)\n }\n", it.Name, it.Name, it.Name, g.m.Name, it.Name)
|
||||
for i, m := range it.Methods {
|
||||
lines := []string{"val _w = NativeWriter()", fmt.Sprintf("_w.i64(%d)", i)}
|
||||
for _, p := range m.Params {
|
||||
lines = append(lines, g.w.kotlinWrite(g, ref{p.Type, g.m}, "_w", kotlinIdent(p.Name)))
|
||||
}
|
||||
read := "{ }"
|
||||
if m.Result != nil {
|
||||
read = "{ _r -> " + g.w.kotlinRead(g, ref{m.Result, g.m}, "_r") + " }"
|
||||
}
|
||||
fn := "invokeGo"
|
||||
if m.Ctx {
|
||||
fn = "invokeGoAsync"
|
||||
}
|
||||
call := "MygoModule." + fn + "(_id, _w) " + read
|
||||
if m.Result != nil {
|
||||
call = "return " + call
|
||||
}
|
||||
lines = append(lines, call)
|
||||
g.p(" override %s {\n %s\n }\n", g.signature(m), strings.Join(lines, "\n "))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
// funcs writes the functions that read and write the composite types.
|
||||
func (g *kotlinGen) funcs() {
|
||||
w := g.w
|
||||
for _, name := range w.names() {
|
||||
r := w.types[name]
|
||||
T := g.kt(r)
|
||||
var read, write string
|
||||
switch r.t.Kind {
|
||||
case Slice:
|
||||
read = fmt.Sprintf(" val n = r.count()\n return List(n) { %s }", w.kotlinRead(g, r.elem(), "r"))
|
||||
write = fmt.Sprintf(" w.count(v.size)\n for (x in v) %s", w.kotlinWrite(g, r.elem(), "w", "x"))
|
||||
case Map:
|
||||
read = fmt.Sprintf(" val n = r.count()\n val v = LinkedHashMap<String, %s>(n)\n repeat(n) {\n val k = r.string()\n v[k] = %s\n }\n return v", g.kt(r.elem()), w.kotlinRead(g, r.elem(), "r"))
|
||||
write = fmt.Sprintf(" w.count(v.size)\n for ((k, x) in v) {\n w.string(k)\n %s\n }", w.kotlinWrite(g, r.elem(), "w", "x"))
|
||||
case Pointer:
|
||||
read = fmt.Sprintf(" return if (r.bool()) %s else null", w.kotlinRead(g, r.elem(), "r"))
|
||||
write = fmt.Sprintf(" if (v == null) {\n w.bool(false)\n } else {\n w.bool(true)\n %s\n }", w.kotlinWrite(g, r.elem(), "w", "v"))
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
s := mod.structNamed(r.t.Name)
|
||||
if len(s.Fields) == 0 {
|
||||
read, write = " r.bool()\n return "+T+"()", " w.bool(false)"
|
||||
break
|
||||
}
|
||||
var rs, ws []string
|
||||
for _, f := range s.Fields {
|
||||
fr := ref{f.Type, mod}
|
||||
n := kotlinIdent(lowerCamel(f.Name))
|
||||
rs = append(rs, " "+n+" = "+w.kotlinRead(g, fr, "r"))
|
||||
ws = append(ws, " "+w.kotlinWrite(g, fr, "w", "v."+n))
|
||||
}
|
||||
read = " return " + T + "(\n" + strings.Join(rs, ",\n") + ",\n )"
|
||||
write = strings.Join(ws, "\n")
|
||||
case EnumType:
|
||||
e := r.module().enumNamed(r.t.Name)
|
||||
if e.String {
|
||||
read, write = " return "+T+".of(r.string())", " w.string(v.value)"
|
||||
} else {
|
||||
read, write = " return "+T+".of(r.i64())", " w.i64(v.value)"
|
||||
}
|
||||
}
|
||||
g.p("\nprivate fun _read_%s(r: NativeReader): %s {\n%s\n}\n", name, T, read)
|
||||
g.p("\nprivate fun _write_%s(w: NativeWriter, v: %s) {\n%s\n}\n", name, T, write)
|
||||
}
|
||||
}
|
||||
|
||||
// kotlinRead is the Kotlin expression that reads a value of type r from
|
||||
// the reader rv.
|
||||
func (w *wire) kotlinRead(g *kotlinGen, r ref, rv string) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return rv + ".bool()"
|
||||
case Int:
|
||||
return rv + ".i64()" + ktFromLong(g.kt(r))
|
||||
case Float:
|
||||
if r.t.Bits == 32 {
|
||||
return rv + ".double().toFloat()"
|
||||
}
|
||||
return rv + ".double()"
|
||||
case String:
|
||||
return rv + ".string()"
|
||||
case Bytes:
|
||||
return rv + ".data()"
|
||||
case Time:
|
||||
return rv + ".time()"
|
||||
case Duration:
|
||||
return rv + ".duration()"
|
||||
case Rect:
|
||||
return rv + ".rect()"
|
||||
case Buffer:
|
||||
return rv + ".buffer()"
|
||||
case InterfaceType, Window, View, Func:
|
||||
return rv + ".u64()"
|
||||
}
|
||||
return "_read_" + w.name(r) + "(" + rv + ")"
|
||||
}
|
||||
|
||||
// kotlinWrite is the Kotlin statement that writes v, of type r, to the
|
||||
// writer wv.
|
||||
func (w *wire) kotlinWrite(g *kotlinGen, r ref, wv, v string) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return wv + ".bool(" + v + ")"
|
||||
case Int:
|
||||
return wv + ".i64(" + v + ".toLong())"
|
||||
case Float:
|
||||
return wv + ".double(" + v + ".toDouble())"
|
||||
case String:
|
||||
return wv + ".string(" + v + ")"
|
||||
case Bytes:
|
||||
return wv + ".data(" + v + ")"
|
||||
case Time:
|
||||
return wv + ".time(" + v + ")"
|
||||
case Duration:
|
||||
return wv + ".duration(" + v + ")"
|
||||
case Rect:
|
||||
return wv + ".rect(" + v + ")"
|
||||
case InterfaceType, View:
|
||||
return wv + ".u64(MygoModule.handle(" + v + "))"
|
||||
}
|
||||
return "_write_" + w.name(r) + "(" + wv + ", " + v + ")"
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
// Package nativegen reads the Go side of a native module, an interface
|
||||
// that a platform's own language implements, and writes what each side
|
||||
// needs from it: the Go constructors and proxies (<package>_native.go),
|
||||
// for Apple's platforms the Swift protocols, types and the @_cdecl
|
||||
// functions Go calls (<Module>.mygo.swift), for Android the Kotlin
|
||||
// interfaces, types and the object Go calls (<Module>.mygo.kt), and the
|
||||
// same for Rust and Zig. See docs/native-modules.md.
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"go/token"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Version changes when the generated code changes for the same interface,
|
||||
// so that `mygo build` regenerates what an older generator wrote.
|
||||
const Version = "3"
|
||||
|
||||
// Module is the Go package of a native module.
|
||||
type Module struct {
|
||||
Dir string // the package's directory
|
||||
Package string // the Go package name: language
|
||||
// ImportPath is the package's import path, from its go.mod, which
|
||||
// names its Kotlin package.
|
||||
ImportPath string
|
||||
Name string // the Swift module: Language
|
||||
// Files are the package's own Go files, without the generated one.
|
||||
Files []string
|
||||
// Hash identifies the declarations the generated files came from.
|
||||
Hash string
|
||||
|
||||
Interfaces []*Interface
|
||||
Structs []*Struct
|
||||
Enums []*Enum
|
||||
Errors []*ErrorVar
|
||||
|
||||
// Imports are the packages the generated Go imports, besides native.
|
||||
Imports map[string]bool
|
||||
// Deps are the other native modules whose types the module uses, by
|
||||
// the paths it imports them at, and Quals the names it imports them
|
||||
// under.
|
||||
Deps map[string]*Module
|
||||
Quals map[string]string
|
||||
}
|
||||
|
||||
// Interface is an interface of the module.
|
||||
type Interface struct {
|
||||
Name string
|
||||
Doc string
|
||||
Pos token.Position
|
||||
Entry bool // //mygo:native: the package gets NewName
|
||||
MainThread bool // //mygo:mainthread: every method runs on the main thread
|
||||
View bool // embeds native.View
|
||||
Closer bool // embeds io.Closer or has Close() error
|
||||
// ByGo is set for an interface that methods only take: Go implements
|
||||
// it, and the platform calls it.
|
||||
ByGo bool
|
||||
Methods []*Method
|
||||
returned bool // a method of the module returns it
|
||||
taken bool // a method of the module takes it
|
||||
}
|
||||
|
||||
// Method is a method of an interface.
|
||||
type Method struct {
|
||||
Name string
|
||||
Doc string
|
||||
Pos token.Position
|
||||
Ctx bool // takes a context.Context first
|
||||
MainThread bool
|
||||
Params []*Param
|
||||
// Result is the value it returns, nil for none. For a stream it is
|
||||
// the element.
|
||||
Result *Type
|
||||
Err bool // returns an error, last
|
||||
Stream int // 1: iter.Seq[Result]; 2: iter.Seq2[Result, error]
|
||||
Closer bool // returns an io.Closer
|
||||
// Close is the Close() error of an interface that is closed.
|
||||
Close bool
|
||||
}
|
||||
|
||||
// Async reports whether the method is asynchronous on the platform's side.
|
||||
func (m *Method) Async() bool { return m.Ctx && m.Stream == 0 }
|
||||
|
||||
// Param is a parameter of a method or a callback.
|
||||
type Param struct {
|
||||
Name string
|
||||
Type *Type
|
||||
}
|
||||
|
||||
// Kind is the kind of a type that crosses between Go and the platform.
|
||||
type Kind int
|
||||
|
||||
const (
|
||||
Bool Kind = iota
|
||||
Int
|
||||
Float
|
||||
String
|
||||
Bytes
|
||||
Time
|
||||
Duration
|
||||
Slice
|
||||
Map
|
||||
Pointer
|
||||
StructType
|
||||
EnumType
|
||||
InterfaceType
|
||||
Func
|
||||
Window
|
||||
Rect
|
||||
View
|
||||
Buffer
|
||||
Texture
|
||||
Closer
|
||||
)
|
||||
|
||||
// Type is a type of a parameter, a result or a field.
|
||||
type Type struct {
|
||||
Kind Kind
|
||||
// Go is the Go spelling: int64, []string, *Token.
|
||||
Go string
|
||||
// Bits and Unsigned describe Int and Float.
|
||||
Bits int
|
||||
Unsigned bool
|
||||
Elem *Type // Slice, Map, Pointer
|
||||
Name string // StructType, EnumType, InterfaceType
|
||||
Iface *Interface // InterfaceType
|
||||
Enum *Enum // EnumType
|
||||
// Pkg is the other native module a StructType, EnumType or
|
||||
// InterfaceType is of, nil for the module's own.
|
||||
Pkg *Module
|
||||
// Func's parameters and results.
|
||||
Params []*Param
|
||||
Result *Type
|
||||
Err bool
|
||||
}
|
||||
|
||||
// Struct is a struct type of the package.
|
||||
type Struct struct {
|
||||
Name string
|
||||
Doc string
|
||||
Pos token.Position
|
||||
Fields []*Field
|
||||
}
|
||||
|
||||
// Field is an exported field of a struct.
|
||||
type Field struct {
|
||||
Name string // the Go name
|
||||
JSON string // its key in JSON
|
||||
Doc string
|
||||
Type *Type
|
||||
}
|
||||
|
||||
// Enum is a named string or integer type with constants.
|
||||
type Enum struct {
|
||||
Name string
|
||||
Doc string
|
||||
Pos token.Position
|
||||
String bool
|
||||
Basic string // the underlying Go type: string, int, uint8 …
|
||||
Cases []*EnumCase
|
||||
}
|
||||
|
||||
// EnumCase is one constant of an Enum.
|
||||
type EnumCase struct {
|
||||
Name string // the Go name
|
||||
Value string // its value, as a Go literal: "word", 3
|
||||
Doc string
|
||||
}
|
||||
|
||||
// ErrorVar is an error of the package, made with native.NewError.
|
||||
type ErrorVar struct {
|
||||
Name string // ErrNoEmbedding
|
||||
Code string // no_embedding
|
||||
Doc string
|
||||
}
|
||||
|
||||
// SwiftName is the Swift name of an error's case: ErrNoEmbedding →
|
||||
// noEmbedding.
|
||||
func (e *ErrorVar) SwiftName() string {
|
||||
return swiftIdent(lowerCamel(strings.TrimPrefix(e.Name, "Err")))
|
||||
}
|
||||
|
||||
// lowerCamel lowers the first word of a Go name: DetectLanguage →
|
||||
// detectLanguage, URLFor → urlFor, ID → id.
|
||||
func lowerCamel(s string) string {
|
||||
r := []rune(s)
|
||||
n := 0
|
||||
for n < len(r) && unicode.IsUpper(r[n]) {
|
||||
n++
|
||||
}
|
||||
switch {
|
||||
case n == 0:
|
||||
return s
|
||||
case n == len(r):
|
||||
return strings.ToLower(s)
|
||||
case n > 1 && unicode.IsLower(r[n]):
|
||||
n-- // the last capital starts the next word
|
||||
}
|
||||
for i := range n {
|
||||
r[i] = unicode.ToLower(r[i])
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
|
||||
// UpperCamel is the name of a package in upper camel case, the name of
|
||||
// its Swift module: language → Language, media_player → MediaPlayer.
|
||||
func UpperCamel(s string) string {
|
||||
var b strings.Builder
|
||||
up := true
|
||||
for _, r := range s {
|
||||
if r == '_' || r == '-' {
|
||||
up = true
|
||||
continue
|
||||
}
|
||||
if up {
|
||||
r = unicode.ToUpper(r)
|
||||
up = false
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
var swiftKeywords = map[string]bool{
|
||||
"associatedtype": true, "class": true, "deinit": true, "enum": true, "extension": true,
|
||||
"fileprivate": true, "func": true, "import": true, "init": true, "inout": true,
|
||||
"internal": true, "let": true, "open": true, "operator": true, "private": true,
|
||||
"precedencegroup": true, "protocol": true, "public": true, "rethrows": true,
|
||||
"static": true, "struct": true, "subscript": true, "typealias": true, "var": true,
|
||||
"break": true, "case": true, "catch": true, "continue": true, "default": true,
|
||||
"defer": true, "do": true, "else": true, "fallthrough": true, "for": true,
|
||||
"guard": true, "if": true, "in": true, "repeat": true, "return": true, "throw": true,
|
||||
"switch": true, "where": true, "while": true, "Any": true, "as": true, "await": true,
|
||||
"false": true, "is": true, "nil": true, "self": true, "Self": true, "super": true,
|
||||
"throws": true, "true": true, "try": true, "Type": true, "Protocol": true,
|
||||
}
|
||||
|
||||
// swiftIdent escapes a Swift keyword used as a name.
|
||||
func swiftIdent(s string) string {
|
||||
if swiftKeywords[s] {
|
||||
return "`" + s + "`"
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const example = "../../examples/native-module/modules/language"
|
||||
|
||||
func TestLoadExample(t *testing.T) {
|
||||
m, err := Load(example)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Package != "language" || m.Name != "Language" {
|
||||
t.Fatalf("module %s, %s", m.Package, m.Name)
|
||||
}
|
||||
byName := map[string]*Interface{}
|
||||
for _, it := range m.Interfaces {
|
||||
byName[it.Name] = it
|
||||
}
|
||||
if a := byName["Analyzer"]; a == nil || !a.Entry || a.ByGo {
|
||||
t.Errorf("Analyzer: %+v", a)
|
||||
}
|
||||
if e := byName["Embedding"]; e == nil || e.Entry || e.ByGo || !e.Closer {
|
||||
t.Errorf("Embedding, which the module returns and takes back: %+v", e)
|
||||
}
|
||||
if r := byName["Ranker"]; r == nil || !r.ByGo {
|
||||
t.Errorf("Ranker, which the module only takes: %+v", r)
|
||||
}
|
||||
if len(m.Errors) != 2 || m.Errors[1].Code != "no_embedding" || m.Errors[1].SwiftName() != "noEmbedding" {
|
||||
t.Errorf("errors: %+v", m.Errors)
|
||||
}
|
||||
if len(m.Enums) != 1 || len(m.Enums[0].Cases) != 3 || len(m.Structs) != 1 {
|
||||
t.Errorf("enums %+v, structs %+v", m.Enums, m.Structs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleUsingAnother(t *testing.T) {
|
||||
m, err := Load("../../examples/native-module/modules/places")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dep := m.Deps["github.com/egoist/mygo/examples/native-module/modules/language"]
|
||||
if dep == nil || dep.Name != "Language" {
|
||||
t.Fatalf("deps %v", m.Deps)
|
||||
}
|
||||
swift := string(GenerateSwift(m))
|
||||
for _, want := range []string{"import Language\n", "a: any Language.Analyzer", "public protocol Map: NativeView"} {
|
||||
if !strings.Contains(swift, want) {
|
||||
t.Errorf("the Swift lacks %q", want)
|
||||
}
|
||||
}
|
||||
src, err := GenerateGo(m, nil, SwiftPlatforms{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(src), `Deps: []string{"Language"}`) {
|
||||
t.Errorf("the Go does not load Language first:\n%s", src)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExampleUpToDate checks that the example's generated files are those
|
||||
// the generator writes now.
|
||||
func TestExampleUpToDate(t *testing.T) {
|
||||
stale, err := Stale(example)
|
||||
for _, m := range []string{"places", "motion"} {
|
||||
more, err := Stale("../../examples/native-module/modules/" + m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale = append(stale, more...)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, _ := Load(example)
|
||||
src, err := GenerateGo(m, ModuleLangs(m.Dir), SwiftPlatformsOf(m.Dir))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
have, _ := os.ReadFile(filepath.Join(m.Dir, GeneratedGo(m.Package)))
|
||||
swift, _ := os.ReadFile(filepath.Join(SwiftDir(m), SwiftFile(m)))
|
||||
if len(stale) > 0 || string(have) != string(src) || string(swift) != string(GenerateSwift(m)) {
|
||||
t.Fatalf("the example's generated files are out of date (%v): run go run ./cmd/mygo generate examples/native-module", stale)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNames(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"DetectLanguage": "detectLanguage", "URLFor": "urlFor", "ID": "id",
|
||||
"HTTPServer": "httpServer", "X": "x", "already": "already",
|
||||
} {
|
||||
if got := lowerCamel(in); got != want {
|
||||
t.Errorf("lowerCamel(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
if got := UpperCamel("media_player"); got != "MediaPlayer" {
|
||||
t.Errorf("UpperCamel = %q", got)
|
||||
}
|
||||
if got := swiftIdent("default"); got != "`default`" {
|
||||
t.Errorf("swiftIdent = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnostics(t *testing.T) {
|
||||
const head = "package bad\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"iter\"\n\t\"net/http\"\n)\n\nvar _ = context.Background\nvar _ io.Reader\nvar _ iter.Seq[int]\nvar _ http.Header\n\n"
|
||||
for _, c := range []struct{ src, want string }{
|
||||
{"type A interface{ M() }\n", "has no entry point"},
|
||||
{"//mygo:native\ntype A interface{ M(ch chan int) }\n", "bad.go:16: A.M uses chan int, which an implementation cannot use: return iter.Seq2[T, error]"},
|
||||
{"//mygo:native\ntype A interface{ M(v any) }\n", "uses any"},
|
||||
{"//mygo:native\ntype A interface{ M(h http.Header) }\n", "a type of another package"},
|
||||
{"//mygo:native\ntype A interface{ M(s string, ctx context.Context) }\n", "takes a context.Context after other parameters"},
|
||||
{"//mygo:native\ntype A interface{ M(ctx context.Context) iter.Seq2[int, string] }\n", "a stream's second value is its error"},
|
||||
{"//mygo:native\ntype A interface{ M() iter.Seq[int] }\n", "without taking a context.Context"},
|
||||
{"//mygo:native\ntype A interface{ M() (int, string) }\n", "the second not an error"},
|
||||
{"//mygo:native\ntype A interface{ M(m map[int]string) }\n", "maps have string keys"},
|
||||
{"//mygo:native\ntype A interface{ M(u U) }\ntype U string\n", "U has no constants"},
|
||||
{"//mygo:native\ntype A interface{ M(s S) }\ntype S struct{ Next *S }\n", "S contains itself"},
|
||||
{"//mygo:native\ntype A interface{ M(g G) }\ntype G interface{ N(f func()) }\n", "Go implements G"},
|
||||
{"//mygo:frob\ntype A interface{ M() }\n", "unknown directive //mygo:frob"},
|
||||
{"//mygo:native\ntype A interface{ M(_x int) }\n", "names a parameter _x: the generated code keeps names starting with _"},
|
||||
{"//mygo:native\ntype A interface{ M() }\nvar ErrX = native.NewError(\"\")\n", ""},
|
||||
} {
|
||||
dir := t.TempDir()
|
||||
src := head + c.src
|
||||
if strings.Contains(c.src, "native.") {
|
||||
src = strings.Replace(src, "import (\n", "import (\n\t\"github.com/egoist/mygo/native\"\n", 1)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "bad.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := Load(dir)
|
||||
if c.want == "" {
|
||||
if err == nil {
|
||||
t.Errorf("%q: no error", c.src)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Errorf("%q: error %v, want %q", c.src, err, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestScaffoldBuilds makes a module with its Swift package, whose stub
|
||||
// implementation must compile against the generated declarations.
|
||||
func TestScaffoldBuilds(t *testing.T) {
|
||||
if runtime.GOOS != "darwin" || testing.Short() {
|
||||
t.Skip("builds a Swift package, on macOS")
|
||||
}
|
||||
if _, err := exec.LookPath("swift"); err != nil {
|
||||
t.Skip("no Swift")
|
||||
}
|
||||
dir := filepath.Join(t.TempDir(), "greeting")
|
||||
if err := Scaffold(dir, "greeting", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Every kind of method, in the stub and the glue.
|
||||
example, err := os.ReadFile(filepath.Join(example, "language.go"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := strings.Replace(string(example), "package language", "package greeting", 1)
|
||||
os.Remove(filepath.Join(dir, "greeting.go"))
|
||||
if err := os.WriteFile(filepath.Join(dir, "greeting.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := AddLang(dir, "swift"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := exec.Command("swift", "build", "--package-path", filepath.Join(dir, "swift")).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("swift build: %v\n%s", err, out)
|
||||
}
|
||||
if strings.Contains(string(out), "warning:") {
|
||||
t.Errorf("swift build warns:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScaffoldBuildsRustZig makes modules in Rust and Zig, a new one's
|
||||
// and one whose names clash with the generated code's, whose stub
|
||||
// implementations must compile against the generated declarations.
|
||||
func TestScaffoldBuildsRustZig(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("builds a crate and a Zig package")
|
||||
}
|
||||
clash, err := os.ReadFile("testdata/clash/clash.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, lang := range []string{"rust", "zig"} {
|
||||
tool := map[string]string{"rust": "cargo", "zig": "zig"}[lang]
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
t.Logf("no %s", tool)
|
||||
continue
|
||||
}
|
||||
for _, src := range []string{"", string(clash)} {
|
||||
dir := filepath.Join(t.TempDir(), "greeting")
|
||||
if err := Scaffold(dir, "greeting", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if src != "" {
|
||||
src = regexp.MustCompile(`(?m)^package \w+`).ReplaceAllString(src, "package greeting")
|
||||
if err := os.WriteFile(filepath.Join(dir, "greeting.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := AddLang(dir, lang); err != nil {
|
||||
t.Fatalf("%s: %v", lang, err)
|
||||
}
|
||||
cache := t.TempDir()
|
||||
var cmd *exec.Cmd
|
||||
if lang == "rust" {
|
||||
cmd = exec.Command("cargo", "build", "--manifest-path", filepath.Join(dir, "rust", "Cargo.toml"))
|
||||
cmd.Env = append(os.Environ(), "CARGO_TARGET_DIR="+cache)
|
||||
} else {
|
||||
cmd = exec.Command("zig", "build", "--prefix", filepath.Join(cache, "out"), "--cache-dir", filepath.Join(cache, "zig"))
|
||||
cmd.Dir = filepath.Join(dir, "zig")
|
||||
}
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Errorf("%s build of %q: %v\n%s", lang, firstLine(src), err, out)
|
||||
} else if strings.Contains(string(out), "warning") {
|
||||
t.Errorf("%s build of %q warns:\n%s", lang, firstLine(src), out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func firstLine(s string) string {
|
||||
l, _, _ := strings.Cut(s, "\n")
|
||||
return l
|
||||
}
|
||||
|
||||
// TestNamesDontClash generates a module whose parameters are named as the
|
||||
// generated code names its own identifiers and packages: its Go must vet,
|
||||
// and its Swift build, where Swift is.
|
||||
func TestNamesDontClash(t *testing.T) {
|
||||
dir, err := os.MkdirTemp("testdata", "clash-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
src, err := os.ReadFile("testdata/clash/clash.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "clash.go"), src, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Generate(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := exec.Command("go", "vet", "./"+dir).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("go vet of the generated Go: %v\n%s", err, out)
|
||||
}
|
||||
if runtime.GOOS != "darwin" || testing.Short() {
|
||||
return
|
||||
}
|
||||
if _, err := exec.LookPath("swift"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := AddLang(dir, "swift"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err = exec.Command("swift", "build", "--package-path", filepath.Join(dir, "swift")).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("swift build: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKotlinNames(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"github.com/acme/go-battery": "com.github.acme.go_battery",
|
||||
"github.com/egoist/mygo/native/x": "com.github.egoist.mygo.native_.x",
|
||||
"example.com/2d/package": "com.example._2d.package_",
|
||||
"local/Mixed.Case": "local.mixed_case",
|
||||
"github.com/egoist/mygo/plugins/sqlite/internal/sqlitecore": "com.github.egoist.mygo.plugins.sqlite.internal.sqlitecore",
|
||||
} {
|
||||
if got := KotlinPackage(in); got != want {
|
||||
t.Errorf("KotlinPackage(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
if got := kotlinIdent("object"); got != "`object`" {
|
||||
t.Errorf("kotlinIdent = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKotlinUpToDate checks the committed Kotlin of the modules that have
|
||||
// it, which no test compiles here: CI builds it into an app.
|
||||
func TestKotlinUpToDate(t *testing.T) {
|
||||
for _, dir := range []string{"../../native/internal/roundtrip", "../../plugins/sqlite/internal/sqlitecore"} {
|
||||
m, err := Load(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := GenerateKotlin(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
have, err := os.ReadFile(filepath.Join(KotlinDir(m), KotlinFile(m)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(have) != string(want) {
|
||||
t.Errorf("%s: the generated Kotlin is out of date: run go run ./cmd/mygo native check %s", dir, dir)
|
||||
}
|
||||
if !strings.Contains(string(want), "package "+KotlinPackage(m.ImportPath)+"\n") || !strings.Contains(string(want), "object MygoModule") {
|
||||
t.Errorf("%s: the Kotlin is not in its package, or has no MygoModule", dir)
|
||||
}
|
||||
}
|
||||
}
|
||||
+1106
File diff suppressed because it is too large.
Load diff
+860
@@ -0,0 +1,860 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"maps"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// RustFile is the generated Rust of a module, a module of its crate that
|
||||
// the crate's lib.rs declares (mod mygo;).
|
||||
const RustFile = "mygo.rs"
|
||||
|
||||
// RustDir is the directory of a module's Rust sources.
|
||||
func RustDir(m *Module) string { return m.Dir + "/rust/src" }
|
||||
|
||||
// GenerateRust writes the Rust side: the traits the implementation
|
||||
// implements, the structs, enums and errors of the Go side, and the
|
||||
// functions Go calls, which call the factories of the crate's root
|
||||
// (make_<entry point>).
|
||||
func GenerateRust(m *Module) ([]byte, error) {
|
||||
if err := portable(m, "Rust"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var b bytes.Buffer
|
||||
g := &rustGen{m: m, b: &b, w: newWire(m)}
|
||||
g.p("%s// %s\n//\n// The declarations of package %s, which the implementation implements,\n// and the functions Go calls. See docs/native-modules.md.\n\n", goHeader, SourceLine(m.Hash), m.Package)
|
||||
g.p("#![allow(dead_code, unused_imports, unused_variables, unused_mut, unused_parens, non_snake_case, non_camel_case_types, clippy::all)]\n\n")
|
||||
g.p("use std::collections::HashMap;\nuse std::sync::Arc;\nuse std::time::{Duration, SystemTime};\n")
|
||||
for _, it := range m.Interfaces {
|
||||
g.trait(it)
|
||||
}
|
||||
for _, s := range m.Structs {
|
||||
g.structDecl(s, m)
|
||||
}
|
||||
for _, e := range m.Enums {
|
||||
g.enumDecl(e)
|
||||
}
|
||||
g.errorsDecl()
|
||||
g.foreign()
|
||||
g.p("\n// The functions Go calls.\n")
|
||||
g.p("\n#[no_mangle]\npub unsafe extern \"C\" fn %s(cb: Callback, id_base: u64, malloc: Malloc, free: Free) {\n let _ = RUNTIME.set(Runtime { cb, id_base, malloc, free });\n}\n", g.sym("init"))
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
g.goProxy(it)
|
||||
continue
|
||||
}
|
||||
if it.Entry {
|
||||
g.factory(it)
|
||||
}
|
||||
for _, me := range it.Methods {
|
||||
if !me.Close {
|
||||
g.entry(it, me)
|
||||
}
|
||||
}
|
||||
}
|
||||
g.objects()
|
||||
g.common()
|
||||
g.funcs()
|
||||
g.p("%s", strings.ReplaceAll(rustSupport, "MODULEError", m.Name+"Error"))
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// portable reports what of the module the implementation in lang, which
|
||||
// runs on every platform, cannot take: what only Apple's platforms have,
|
||||
// and the interfaces of other modules.
|
||||
func portable(m *Module, lang string) error {
|
||||
var problems []string
|
||||
var check func(t *Type, where string)
|
||||
check = func(t *Type, where string) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
switch t.Kind {
|
||||
case Window, View:
|
||||
if lang != "Kotlin" {
|
||||
problems = append(problems, fmt.Sprintf("%s uses %s, which only Swift and Kotlin implement", where, t.Go))
|
||||
}
|
||||
case Texture:
|
||||
problems = append(problems, fmt.Sprintf("%s uses %s, which only Swift implements", where, t.Go))
|
||||
case InterfaceType:
|
||||
if t.Pkg != nil {
|
||||
problems = append(problems, fmt.Sprintf("%s uses %s, an interface of another native module, which only Swift implements", where, t.Go))
|
||||
}
|
||||
}
|
||||
check(t.Elem, where)
|
||||
check(t.Result, where)
|
||||
for _, p := range t.Params {
|
||||
check(p.Type, where)
|
||||
}
|
||||
}
|
||||
var noBuffer func(t *Type, where string)
|
||||
noBuffer = func(t *Type, where string) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
if t.Kind == Buffer {
|
||||
problems = append(problems, fmt.Sprintf("%s returns a *native.Buffer, which only Swift implementations return: take one as a parameter", where))
|
||||
}
|
||||
noBuffer(t.Elem, where)
|
||||
}
|
||||
for _, it := range m.Interfaces {
|
||||
if it.View && lang != "Kotlin" {
|
||||
problems = append(problems, fmt.Sprintf("%s is a view, which only Swift and Kotlin implement", it.Name))
|
||||
}
|
||||
for _, me := range it.Methods {
|
||||
where := it.Name + "." + me.Name
|
||||
check(me.Result, where)
|
||||
noBuffer(me.Result, where)
|
||||
for _, p := range me.Params {
|
||||
check(p.Type, where)
|
||||
if p.Type.Kind == Func {
|
||||
for _, q := range p.Type.Params {
|
||||
noBuffer(q.Type, where)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, s := range m.Structs {
|
||||
for _, f := range s.Fields {
|
||||
check(f.Type, s.Name+"."+f.Name)
|
||||
noBuffer(f.Type, s.Name+"."+f.Name)
|
||||
}
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
slices.Sort(problems)
|
||||
return fmt.Errorf("%s/: %s", strings.ToLower(lang), strings.Join(slices.Compact(problems), "\n"+strings.ToLower(lang)+"/: "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type rustGen struct {
|
||||
m *Module
|
||||
b *bytes.Buffer
|
||||
w *wire
|
||||
// stub names parameters as unused, for the stub implementation.
|
||||
stub bool
|
||||
}
|
||||
|
||||
func (g *rustGen) p(format string, args ...any) { fmt.Fprintf(g.b, format, args...) }
|
||||
|
||||
func (g *rustGen) sym(name string) string { return "mygo_" + g.m.Package + "_" + name }
|
||||
|
||||
// snake is the snake case of a Go name: DetectLanguage → detect_language,
|
||||
// URLFor → url_for.
|
||||
func snake(name string) string {
|
||||
r := []rune(name)
|
||||
var b strings.Builder
|
||||
for i, c := range r {
|
||||
if unicode.IsUpper(c) {
|
||||
if i > 0 && (unicode.IsLower(r[i-1]) || unicode.IsDigit(r[i-1]) || i+1 < len(r) && unicode.IsLower(r[i+1]) && unicode.IsUpper(r[i-1])) {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
b.WriteRune(unicode.ToLower(c))
|
||||
continue
|
||||
}
|
||||
b.WriteRune(c)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
var rustKeywords = map[string]bool{
|
||||
"as": true, "break": true, "const": true, "continue": true, "else": true, "enum": true,
|
||||
"extern": true, "false": true, "fn": true, "for": true, "if": true, "impl": true, "in": true,
|
||||
"let": true, "loop": true, "match": true, "mod": true, "move": true, "mut": true, "pub": true,
|
||||
"ref": true, "return": true, "static": true, "struct": true, "trait": true, "true": true,
|
||||
"type": true, "unsafe": true, "use": true, "where": true, "while": true, "async": true,
|
||||
"await": true, "dyn": true, "abstract": true, "become": true, "box": true, "do": true,
|
||||
"final": true, "macro": true, "override": true, "priv": true, "typeof": true, "unsized": true,
|
||||
"virtual": true, "yield": true, "try": true, "gen": true,
|
||||
}
|
||||
|
||||
// rustIdent is the Rust name of a Go field, method or parameter.
|
||||
func rustIdent(name string) string {
|
||||
s := snake(name)
|
||||
switch {
|
||||
case s == "self" || s == "super" || s == "crate":
|
||||
return s + "_"
|
||||
case rustKeywords[s]:
|
||||
return "r#" + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func rustDoc(doc, indent string) string { return docComment(doc, indent) }
|
||||
|
||||
// typ is the Rust spelling of a type.
|
||||
func (g *rustGen) typ(r ref) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return "bool"
|
||||
case Int:
|
||||
if t.Unsigned {
|
||||
return fmt.Sprintf("u%d", t.Bits)
|
||||
}
|
||||
return fmt.Sprintf("i%d", t.Bits)
|
||||
case Float:
|
||||
return fmt.Sprintf("f%d", t.Bits)
|
||||
case String:
|
||||
return "String"
|
||||
case Bytes:
|
||||
return "Vec<u8>"
|
||||
case Time:
|
||||
return "SystemTime"
|
||||
case Duration:
|
||||
return "Duration"
|
||||
case Slice:
|
||||
return "Vec<" + g.typ(r.elem()) + ">"
|
||||
case Map:
|
||||
return "HashMap<String, " + g.typ(r.elem()) + ">"
|
||||
case Pointer:
|
||||
return "Option<" + g.typ(r.elem()) + ">"
|
||||
case StructType, EnumType:
|
||||
if mod := r.module(); mod != g.m {
|
||||
return mod.Package + "::" + t.Name
|
||||
}
|
||||
return t.Name
|
||||
case InterfaceType:
|
||||
return "Arc<dyn " + t.Name + ">"
|
||||
case Rect:
|
||||
return "Rect"
|
||||
case Buffer:
|
||||
return "Buffer"
|
||||
case Func:
|
||||
return "Arc<dyn " + g.fnSig(r) + " + Send + Sync>"
|
||||
}
|
||||
return "()"
|
||||
}
|
||||
|
||||
// fnSig is the Fn trait of a function type.
|
||||
func (g *rustGen) fnSig(r ref) string {
|
||||
var ps []string
|
||||
for _, p := range r.t.Params {
|
||||
ps = append(ps, g.typ(ref{p.Type, r.owner}))
|
||||
}
|
||||
return "Fn(" + strings.Join(ps, ", ") + ")" + g.ret(r.t.Result, r.t.Err, r.owner)
|
||||
}
|
||||
|
||||
// ret is the return type of a function or method: " -> T", or a Result.
|
||||
func (g *rustGen) ret(t *Type, err bool, owner *Module) string {
|
||||
v := "()"
|
||||
if t != nil {
|
||||
v = g.typ(ref{t, owner})
|
||||
}
|
||||
switch {
|
||||
case err:
|
||||
return " -> Result<" + v + ", Error>"
|
||||
case t == nil:
|
||||
return ""
|
||||
}
|
||||
return " -> " + v
|
||||
}
|
||||
|
||||
// signature is the signature of a method of a trait.
|
||||
func (g *rustGen) signature(m *Method) string {
|
||||
ps := []string{"&self"}
|
||||
name := rustIdent
|
||||
if g.stub {
|
||||
name = func(s string) string { return "_" + strings.TrimPrefix(rustIdent(s), "r#") }
|
||||
}
|
||||
if m.Ctx {
|
||||
ps = append(ps, name("ctx")+": &Context")
|
||||
}
|
||||
for _, p := range m.Params {
|
||||
ps = append(ps, name(p.Name)+": "+g.typ(ref{p.Type, g.m}))
|
||||
}
|
||||
s := "fn " + rustIdent(m.Name) + "(" + strings.Join(ps, ", ") + ")"
|
||||
switch {
|
||||
case m.Close:
|
||||
return "fn close(&self) -> Result<(), Error>"
|
||||
case m.Stream == 1:
|
||||
return s + " -> Stream<" + g.typ(ref{m.Result, g.m}) + ">"
|
||||
case m.Stream == 2:
|
||||
return s + " -> Stream<Result<" + g.typ(ref{m.Result, g.m}) + ", Error>>"
|
||||
case m.Closer:
|
||||
return s + " -> Box<dyn Closer>"
|
||||
}
|
||||
return s + g.ret(m.Result, m.Err, g.m)
|
||||
}
|
||||
|
||||
func (g *rustGen) trait(it *Interface) {
|
||||
g.p("\n%s", rustDoc(it.Doc, ""))
|
||||
if it.ByGo {
|
||||
g.p("///\n/// Go implements it: the values the methods take call Go.\n")
|
||||
}
|
||||
g.p("pub trait %s: Send + Sync {\n", it.Name)
|
||||
for _, m := range it.Methods {
|
||||
g.p("%s %s;\n", rustDoc(m.Doc, " "), g.signature(m))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
// defaultable reports whether a type has a Default.
|
||||
func defaultable(r ref) bool {
|
||||
switch r.t.Kind {
|
||||
case Time, Buffer, InterfaceType, Func:
|
||||
return false
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
for _, f := range mod.structNamed(r.t.Name).Fields {
|
||||
if !defaultable(ref{f.Type, mod}) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
case Slice, Map:
|
||||
return true
|
||||
case Pointer:
|
||||
return true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func comparable(r ref) bool {
|
||||
switch r.t.Kind {
|
||||
case Buffer, InterfaceType, Func:
|
||||
return false
|
||||
case Slice, Map, Pointer:
|
||||
return comparable(r.elem())
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
for _, f := range mod.structNamed(r.t.Name).Fields {
|
||||
if !comparable(ref{f.Type, mod}) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (g *rustGen) structDecl(s *Struct, mod *Module) {
|
||||
r := ref{&Type{Kind: StructType, Name: s.Name}, mod}
|
||||
derive := []string{"Debug", "Clone"}
|
||||
if comparable(r) {
|
||||
derive = append(derive, "PartialEq")
|
||||
}
|
||||
if defaultable(r) {
|
||||
derive = append(derive, "Default")
|
||||
}
|
||||
g.p("\n%s#[derive(%s)]\npub struct %s {\n", rustDoc(s.Doc, ""), strings.Join(derive, ", "), s.Name)
|
||||
for _, f := range s.Fields {
|
||||
g.p("%s pub %s: %s,\n", rustDoc(f.Doc, " "), rustIdent(f.Name), g.typFor(ref{f.Type, mod}))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
// typFor is the spelling of a type of a struct of the module mod, from
|
||||
// the declarations of mod: within the module of mod's foreign types, a
|
||||
// type of g.m is named as one of its own.
|
||||
func (g *rustGen) typFor(r ref) string {
|
||||
if r.owner == g.m {
|
||||
return g.typ(r)
|
||||
}
|
||||
// In the module of a foreign module's types, the types of that module
|
||||
// are its own, and others are siblings.
|
||||
s := g.typ(r)
|
||||
pre := r.owner.Package + "::"
|
||||
s = strings.ReplaceAll(s, pre, "")
|
||||
return s
|
||||
}
|
||||
|
||||
func (g *rustGen) enumDecl(e *Enum) {
|
||||
g.p("\n%s#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]\npub enum %s {\n", rustDoc(e.Doc, ""), e.Name)
|
||||
for i, c := range e.Cases {
|
||||
def := ""
|
||||
if i == 0 {
|
||||
def = "#[default]\n "
|
||||
}
|
||||
g.p("%s %s%s,\n", rustDoc(c.Doc, " "), def, c.Name)
|
||||
}
|
||||
g.p("}\n")
|
||||
vt := "&'static str"
|
||||
if !e.String {
|
||||
vt = "i64"
|
||||
}
|
||||
g.p("\nimpl %s {\n /// The value of the case in Go.\n pub fn value(&self) -> %s {\n match self {\n", e.Name, vt)
|
||||
for _, c := range e.Cases {
|
||||
g.p(" %s::%s => %s,\n", e.Name, c.Name, c.Value)
|
||||
}
|
||||
at := "i64"
|
||||
if e.String {
|
||||
at = "&str"
|
||||
}
|
||||
g.p(" }\n }\n\n /// The case of a value of Go's.\n pub fn from_value(v: %s) -> Option<Self> {\n match v {\n", at)
|
||||
for _, c := range e.Cases {
|
||||
g.p(" %s => Some(%s::%s),\n", c.Value, e.Name, c.Name)
|
||||
}
|
||||
g.p(" _ => None,\n }\n }\n}\n")
|
||||
}
|
||||
|
||||
func (g *rustGen) errorsDecl() {
|
||||
name := g.m.Name + "Error"
|
||||
g.p("\n/// The errors package %s declares, with native.NewError, which Go\n/// compares with errors.Is. Return one as Err(%s::…into()).\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub enum %s {\n", g.m.Package, name, name)
|
||||
for _, e := range g.m.Errors {
|
||||
g.p("%s %s,\n", rustDoc(e.Doc, " "), strings.TrimPrefix(e.Name, "Err"))
|
||||
}
|
||||
g.p("}\n\nimpl %s {\n /// The error's code, which Go knows it by.\n pub fn code(&self) -> &'static str {\n match *self {\n", name)
|
||||
for _, e := range g.m.Errors {
|
||||
g.p(" %s::%s => %q,\n", name, strings.TrimPrefix(e.Name, "Err"), e.Code)
|
||||
}
|
||||
g.p(" }\n }\n\n fn from_code(code: &str) -> Option<Self> {\n match code {\n")
|
||||
for _, e := range g.m.Errors {
|
||||
g.p(" %q => Some(%s::%s),\n", e.Code, name, strings.TrimPrefix(e.Name, "Err"))
|
||||
}
|
||||
g.p(" _ => None,\n }\n }\n}\n\nimpl From<%s> for Error {\n fn from(e: %s) -> Self { Error::Module(e) }\n}\n", name, name)
|
||||
}
|
||||
|
||||
// foreign declares the structs and enums of other native modules that the
|
||||
// module uses, in a module of each's name.
|
||||
func (g *rustGen) foreign() {
|
||||
byMod := map[*Module][]ref{}
|
||||
for _, n := range g.w.names() {
|
||||
r := g.w.types[n]
|
||||
if (r.t.Kind == StructType || r.t.Kind == EnumType) && r.module() != g.m {
|
||||
byMod[r.module()] = append(byMod[r.module()], r)
|
||||
}
|
||||
}
|
||||
mods := slices.SortedFunc(maps.Keys(byMod), func(a, b *Module) int { return strings.Compare(a.Package, b.Package) })
|
||||
for _, mod := range mods {
|
||||
g.p("\n/// The types of the native module %s that %s uses.\npub mod %s {\n use super::*;\n", mod.Package, g.m.Package, mod.Package)
|
||||
var inner bytes.Buffer
|
||||
sub := &rustGen{m: g.m, b: &inner, w: g.w}
|
||||
for _, r := range byMod[mod] {
|
||||
if r.t.Kind == StructType {
|
||||
sub.structDecl(mod.structNamed(r.t.Name), mod)
|
||||
} else {
|
||||
sub.enumDecl(mod.enumNamed(r.t.Name))
|
||||
}
|
||||
}
|
||||
for line := range strings.Lines(inner.String()) {
|
||||
if strings.TrimSpace(line) == "" {
|
||||
g.p("\n")
|
||||
} else {
|
||||
g.p(" %s", line)
|
||||
}
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
}
|
||||
|
||||
// read is the Rust expression reading a value of type r from the reader
|
||||
// rv, a &mut Reader.
|
||||
func (g *rustGen) read(r ref, rv string) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return rv + ".bool()?"
|
||||
case Int:
|
||||
return rv + ".i64()? as " + g.typ(r)
|
||||
case Float:
|
||||
if t.Bits == 32 {
|
||||
return rv + ".f64()? as f32"
|
||||
}
|
||||
return rv + ".f64()?"
|
||||
case String:
|
||||
return rv + ".string()?"
|
||||
case Bytes:
|
||||
return rv + ".bytes()?"
|
||||
case Time:
|
||||
return rv + ".time()?"
|
||||
case Duration:
|
||||
return rv + ".duration()?"
|
||||
case Rect:
|
||||
return rv + ".rect()?"
|
||||
case Buffer:
|
||||
return rv + ".buffer()?"
|
||||
case InterfaceType, Func:
|
||||
return rv + ".u64()?"
|
||||
}
|
||||
return "dec_" + g.w.name(r) + "(" + rv + ")?"
|
||||
}
|
||||
|
||||
// write is the Rust statement writing v, an expression of a &T of type
|
||||
// r, to the writer wv, a &mut Writer.
|
||||
func (g *rustGen) write(r ref, wv, v string) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return wv + ".bool(*" + v + ");"
|
||||
case Int:
|
||||
return wv + ".i64(*" + v + " as i64);"
|
||||
case Float:
|
||||
if t.Bits == 32 {
|
||||
return wv + ".f64(*" + v + " as f64);"
|
||||
}
|
||||
return wv + ".f64(*" + v + ");"
|
||||
case String:
|
||||
return wv + ".string(" + v + ");"
|
||||
case Bytes:
|
||||
return wv + ".bytes(" + v + ");"
|
||||
case Time:
|
||||
return wv + ".time(" + v + ");"
|
||||
case Duration:
|
||||
return wv + ".duration(" + v + ");"
|
||||
case Rect:
|
||||
return wv + ".rect(" + v + ");"
|
||||
case Buffer:
|
||||
return wv + ".buffer(" + v + ");"
|
||||
case InterfaceType:
|
||||
return wv + ".u64(retain(Obj::" + t.Name + "(Arc::clone(" + v + "))));"
|
||||
}
|
||||
return "enc_" + g.w.name(r) + "(" + wv + ", " + v + ");"
|
||||
}
|
||||
|
||||
// funcs writes the functions that encode and decode composite types.
|
||||
func (g *rustGen) funcs() {
|
||||
g.p("\n// Encoding.\n")
|
||||
for _, name := range g.w.names() {
|
||||
r := g.w.types[name]
|
||||
T := g.typ(r)
|
||||
var enc, dec string
|
||||
switch r.t.Kind {
|
||||
case Slice:
|
||||
enc = fmt.Sprintf(" w.count(v.len());\n for x in v.iter() {\n %s\n }", g.write(r.elem(), "w", "x"))
|
||||
dec = fmt.Sprintf(" let n = r.count()?;\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n v.push(%s);\n }\n Ok(v)", g.read(r.elem(), "r"))
|
||||
case Map:
|
||||
enc = fmt.Sprintf(" w.count(v.len());\n for (k, x) in v.iter() {\n w.string(k);\n %s\n }", g.write(r.elem(), "w", "x"))
|
||||
dec = fmt.Sprintf(" let n = r.count()?;\n let mut v = HashMap::with_capacity(n);\n for _ in 0..n {\n let k = r.string()?;\n v.insert(k, %s);\n }\n Ok(v)", g.read(r.elem(), "r"))
|
||||
case Pointer:
|
||||
enc = fmt.Sprintf(" match v {\n Some(x) => {\n w.bool(true);\n %s\n }\n None => w.bool(false),\n }", g.write(r.elem(), "w", "x"))
|
||||
dec = fmt.Sprintf(" if r.bool()? {\n Ok(Some(%s))\n } else {\n Ok(None)\n }", g.read(r.elem(), "r"))
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
s := mod.structNamed(r.t.Name)
|
||||
if len(s.Fields) == 0 {
|
||||
enc, dec = " w.bool(false);", " r.bool()?;\n Ok("+T+" {})"
|
||||
break
|
||||
}
|
||||
var es, ds []string
|
||||
for _, f := range s.Fields {
|
||||
fr := ref{f.Type, mod}
|
||||
n := rustIdent(f.Name)
|
||||
es = append(es, " "+g.write(fr, "w", "&v."+n))
|
||||
ds = append(ds, " "+n+": "+g.read(fr, "r")+",")
|
||||
}
|
||||
enc = strings.Join(es, "\n")
|
||||
dec = " Ok(" + T + " {\n" + strings.Join(ds, "\n") + "\n })"
|
||||
case EnumType:
|
||||
e := r.module().enumNamed(r.t.Name)
|
||||
if e.String {
|
||||
enc = " w.string(v.value());"
|
||||
dec = fmt.Sprintf(" let raw = r.string()?;\n %s::from_value(&raw).ok_or_else(|| Error::Go(format!(\"%s has no value {:?}\", raw)))", T, T)
|
||||
} else {
|
||||
enc = " w.i64(v.value());"
|
||||
dec = fmt.Sprintf(" let raw = r.i64()?;\n %s::from_value(raw).ok_or_else(|| Error::Go(format!(\"%s has no value {}\", raw)))", T, T)
|
||||
}
|
||||
}
|
||||
g.p("\nfn enc_%s(w: &mut Writer, v: &%s) {\n%s\n}\n", name, T, enc)
|
||||
g.p("\nfn dec_%s(r: &mut Reader) -> Result<%s, Error> {\n%s\n}\n", name, T, dec)
|
||||
}
|
||||
}
|
||||
|
||||
// readArgs returns the statements reading a method's arguments from the
|
||||
// reader _a, as _p0, _p1 …, and the expressions the implementation takes
|
||||
// them as.
|
||||
func (g *rustGen) readArgs(params []*Param) (stmts, vals []string) {
|
||||
if len(params) > 0 {
|
||||
stmts = append(stmts, "let _a = &mut Reader::new(args, n);")
|
||||
}
|
||||
for i, p := range params {
|
||||
v := fmt.Sprintf("_p%d", i)
|
||||
stmts = append(stmts, "let "+v+" = "+g.read(ref{p.Type, g.m}, "_a")+";")
|
||||
switch p.Type.Kind {
|
||||
case InterfaceType:
|
||||
if p.Type.Iface.ByGo {
|
||||
v = fmt.Sprintf("Arc::new(Go%s::new(%s)?) as Arc<dyn %s>", p.Type.Name, v, p.Type.Name)
|
||||
} else {
|
||||
v = fmt.Sprintf("obj_%s(%s)?", snake(p.Type.Name), v)
|
||||
}
|
||||
case Func:
|
||||
f := fmt.Sprintf("_f%d", i)
|
||||
stmts = append(stmts, "let "+f+": "+g.typ(ref{p.Type, g.m})+" = "+g.closure(v, p.Type)+";")
|
||||
v = f
|
||||
}
|
||||
vals = append(vals, v)
|
||||
}
|
||||
return stmts, vals
|
||||
}
|
||||
|
||||
// closure is a Rust closure calling the Go function whose handle is h.
|
||||
func (g *rustGen) closure(h string, t *Type) string {
|
||||
var names, body []string
|
||||
for i, p := range t.Params {
|
||||
n := fmt.Sprintf("q%d", i)
|
||||
names = append(names, n+": "+g.typ(ref{p.Type, g.m}))
|
||||
body = append(body, g.write(ref{p.Type, g.m}, "(&mut _cw)", "&"+n))
|
||||
}
|
||||
read := "|_| Ok(())"
|
||||
if t.Result != nil {
|
||||
read = "|_r| Ok(" + g.read(ref{t.Result, g.m}, "_r") + ")"
|
||||
}
|
||||
switch {
|
||||
case t.Result == nil && !t.Err:
|
||||
body = append(body, "f.notify(_cw)")
|
||||
case t.Err:
|
||||
body = append(body, "f.ask(_cw, "+read+")")
|
||||
default:
|
||||
body = append(body, "f.ask(_cw, "+read+").unwrap_or_else(|e| panic!(\"Go failed to answer: {}\", e))")
|
||||
}
|
||||
return "{\n let f = GoFunc::new(" + h + ");\n Arc::new(move |" + strings.Join(names, ", ") + "| {\n let mut _cw = Writer::new();\n " + strings.Join(body, "\n ") + "\n })\n }"
|
||||
}
|
||||
|
||||
func (g *rustGen) factory(it *Interface) {
|
||||
g.p("\n#[no_mangle]\npub unsafe extern \"C\" fn %s(obj: u64, args: *const u8, n: usize, call: u64) -> *mut u8 {\n", g.sym("new_"+it.Name))
|
||||
g.p(" run(|_w| {\n let v: Arc<dyn %s> = crate::make_%s()?;\n _w.u64(retain(Obj::%s(v)));\n Ok(())\n })\n}\n", it.Name, snake(it.Name), it.Name)
|
||||
}
|
||||
|
||||
func (g *rustGen) entry(it *Interface, m *Method) {
|
||||
name := it.Name + "_" + m.Name
|
||||
if direct(m) {
|
||||
g.direct(it, m)
|
||||
return
|
||||
}
|
||||
g.p("\n#[no_mangle]\npub unsafe extern \"C\" fn %s(obj: u64, args: *const u8, n: usize, call: u64) -> *mut u8 {\n", g.sym(name))
|
||||
stmts, vals := g.readArgs(m.Params)
|
||||
prelude := fmt.Sprintf(" let _o = obj_%s(obj)?;\n", snake(it.Name))
|
||||
for _, s := range stmts {
|
||||
prelude += " " + s + "\n"
|
||||
}
|
||||
args := strings.Join(vals, ", ")
|
||||
call := "_o." + rustIdent(m.Name) + "("
|
||||
if m.Ctx {
|
||||
call += "_ctx"
|
||||
if args != "" {
|
||||
call += ", "
|
||||
}
|
||||
}
|
||||
call += args + ")"
|
||||
switch {
|
||||
case m.Stream != 0:
|
||||
make := call
|
||||
if m.Stream == 1 {
|
||||
make = "Box::new(" + call + ".map(Ok))"
|
||||
}
|
||||
g.p(" start(|| {\n%s stream(call, move |_ctx| %s, |_w, _r| { %s });\n Ok(())\n })\n}\n", prelude, make, g.write(ref{m.Result, g.m}, "_w", "_r"))
|
||||
return
|
||||
case m.Async():
|
||||
q := ""
|
||||
if m.Err {
|
||||
q = "?"
|
||||
}
|
||||
body := call + q + ";"
|
||||
if m.Result != nil {
|
||||
body = "let _r = " + call + q + ";\n " + g.write(ref{m.Result, g.m}, "_w", "&_r")
|
||||
}
|
||||
g.p(" start(|| {\n%s task(call, move |_ctx, _w| {\n %s\n Ok(())\n });\n Ok(())\n })\n}\n", prelude, body)
|
||||
return
|
||||
}
|
||||
q := ""
|
||||
if m.Err {
|
||||
q = "?"
|
||||
}
|
||||
g.p(" run(|_w| {\n%s", prelude)
|
||||
switch {
|
||||
case m.Closer:
|
||||
g.p(" let _r = %s;\n _w.u64(retain(Obj::Closer(Arc::from(_r))));\n", call)
|
||||
case m.Result != nil:
|
||||
g.p(" let _r = %s%s;\n %s\n", call, q, g.write(ref{m.Result, g.m}, "_w", "&_r"))
|
||||
default:
|
||||
g.p(" %s%s;\n", call, q)
|
||||
}
|
||||
g.p(" Ok(())\n })\n}\n")
|
||||
}
|
||||
|
||||
// direct writes the C function of a method of numbers (see direct).
|
||||
func (g *rustGen) direct(it *Interface, m *Method) {
|
||||
name := it.Name + "_" + m.Name + "_direct"
|
||||
var params, vals []string
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("_p%d", i)
|
||||
params = append(params, v+": u64")
|
||||
switch {
|
||||
case p.Type.Kind == Bool:
|
||||
v += " != 0"
|
||||
case p.Type.Kind == Float && p.Type.Bits == 32:
|
||||
v = "f64::from_bits(" + v + ") as f32"
|
||||
case p.Type.Kind == Float:
|
||||
v = "f64::from_bits(" + v + ")"
|
||||
default:
|
||||
v += " as " + g.typ(ref{p.Type, g.m})
|
||||
}
|
||||
vals = append(vals, v)
|
||||
}
|
||||
g.p("\n#[no_mangle]\npub unsafe extern \"C\" fn %s(obj: u64%s) -> u64 {\n", g.sym(name), prefixComma(params))
|
||||
call := "_o." + rustIdent(m.Name) + "(" + strings.Join(vals, ", ") + ")"
|
||||
t := m.Result
|
||||
var ret string
|
||||
switch {
|
||||
case t == nil:
|
||||
ret = call + ";\n 0"
|
||||
case t.Kind == Bool:
|
||||
ret = call + " as u64"
|
||||
case t.Kind == Float && t.Bits == 32:
|
||||
ret = "(" + call + " as f64).to_bits()"
|
||||
case t.Kind == Float:
|
||||
ret = call + ".to_bits()"
|
||||
default:
|
||||
ret = call + " as u64"
|
||||
}
|
||||
g.p(" guard(|| {\n let _o = match obj_%s(obj) {\n Ok(o) => o,\n Err(_) => return 0,\n };\n %s\n })\n .unwrap_or(0)\n}\n", snake(it.Name), ret)
|
||||
}
|
||||
|
||||
// goProxy writes the type through which the implementation calls a value
|
||||
// of an interface Go implements.
|
||||
func (g *rustGen) goProxy(it *Interface) {
|
||||
g.p("\n/// Calls a Go value implementing %s.\nstruct Go%s {\n id: u64,\n}\n\nimpl Go%s {\n fn new(id: u64) -> Result<Self, Error> {\n if id == 0 {\n return Err(Error::Go(\"Go passed nil for %s\".into()));\n }\n Ok(Go%s { id })\n }\n}\n\nimpl Drop for Go%s {\n fn drop(&mut self) {\n send(KIND_RELEASE, self.id, 0, None);\n }\n}\n", it.Name, it.Name, it.Name, it.Name, it.Name, it.Name)
|
||||
g.p("\nimpl %s for Go%s {\n", it.Name, it.Name)
|
||||
for i, m := range it.Methods {
|
||||
lines := []string{"let mut _w = Writer::new();", fmt.Sprintf("_w.i64(%d);", i)}
|
||||
for _, p := range m.Params {
|
||||
lines = append(lines, g.write(ref{p.Type, g.m}, "(&mut _w)", "&"+rustIdent(p.Name)))
|
||||
}
|
||||
read := "|_| Ok(())"
|
||||
if m.Result != nil {
|
||||
read = "|_r| Ok(" + g.read(ref{m.Result, g.m}, "_r") + ")"
|
||||
}
|
||||
var call string
|
||||
if m.Ctx {
|
||||
call = "invoke_async(self.id, ctx, _w, " + read + ")"
|
||||
} else {
|
||||
call = "invoke(self.id, _w, " + read + ")"
|
||||
}
|
||||
switch {
|
||||
case m.Err:
|
||||
case m.Result == nil && m.Ctx:
|
||||
call = "let _ = " + call + ";"
|
||||
default:
|
||||
call += ".unwrap_or_else(|e| panic!(\"Go failed to answer: {}\", e))"
|
||||
}
|
||||
lines = append(lines, call)
|
||||
g.p(" %s {\n %s\n }\n", g.signature(m), strings.Join(lines, "\n "))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
// objects writes the objects of the implementation that Go holds, by
|
||||
// their handles.
|
||||
func (g *rustGen) objects() {
|
||||
g.p("\n/// An object of the implementation that Go holds, by its handle.\nenum Obj {\n")
|
||||
var closers []string
|
||||
for _, it := range g.m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
g.p(" %s(Arc<dyn %s>),\n", it.Name, it.Name)
|
||||
if it.Closer {
|
||||
closers = append(closers, it.Name)
|
||||
}
|
||||
}
|
||||
g.p(" Closer(Arc<dyn Closer>),\n}\n")
|
||||
for _, it := range g.m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
g.p("\nfn obj_%s(h: u64) -> Result<Arc<dyn %s>, Error> {\n match object(h)? {\n Obj::%s(o) => Ok(Arc::clone(o)),\n _ => Err(Error::Go(\"Go passed an object that is not a %s\".into())),\n }\n}\n", snake(it.Name), it.Name, it.Name, it.Name)
|
||||
}
|
||||
g.p("\nfn close_obj(o: &Obj) -> Result<(), Error> {\n match o {\n")
|
||||
for _, n := range closers {
|
||||
g.p(" Obj::%s(o) => o.close(),\n", n)
|
||||
}
|
||||
g.p(" Obj::Closer(o) => o.close(),\n _ => Ok(()),\n }\n}\n")
|
||||
}
|
||||
|
||||
func (g *rustGen) common() {
|
||||
g.p(`
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn %s(obj: u64, args: *const u8, n: usize, call: u64) -> *mut u8 {
|
||||
run(|_| close_obj(object(obj)?))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn %s(obj: u64) {
|
||||
if obj != 0 {
|
||||
let _ = guard(|| drop(Box::from_raw(obj as *mut Obj)));
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn %s(call: u64) {
|
||||
let _ = guard(|| cancel(call));
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn %s(call: u64) {
|
||||
let _ = guard(|| demand(call));
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn %s(cont: u64, block: *mut u8) {
|
||||
let _ = guard(|| resume(cont, block));
|
||||
}
|
||||
`, g.sym("close"), g.sym("release"), g.sym("cancel"), g.sym("next"), g.sym("resume"))
|
||||
}
|
||||
|
||||
// stubRust is an implementation in Rust whose every method says it is
|
||||
// unsupported, to fill in one at a time.
|
||||
func stubRust(m *Module) []byte {
|
||||
var b bytes.Buffer
|
||||
g := &rustGen{m: m, b: &b, w: newWire(m), stub: true}
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
class := "Native" + it.Name
|
||||
if it.Entry {
|
||||
g.p("\npub fn make_%s() -> Result<Arc<dyn %s>, Error> {\n Ok(Arc::new(%s))\n}\n", snake(it.Name), it.Name, class)
|
||||
}
|
||||
g.p("\nstruct %s;\n\nimpl %s for %s {\n", class, it.Name, class)
|
||||
for _, me := range it.Methods {
|
||||
var body string
|
||||
switch {
|
||||
case me.Close:
|
||||
body = "Ok(())"
|
||||
case me.Stream == 1:
|
||||
body = "stream_of(std::iter::empty())"
|
||||
case me.Stream == 2:
|
||||
body = "stream_of(std::iter::once(Err(Error::Unsupported)))"
|
||||
case me.Closer:
|
||||
body = "closer(|| {})"
|
||||
case me.Err:
|
||||
body = "Err(Error::Unsupported)"
|
||||
case me.Result == nil:
|
||||
body = ""
|
||||
default:
|
||||
body = "unimplemented!(\"" + it.Name + "." + me.Name + "\")"
|
||||
}
|
||||
g.p(" %s {\n", g.signature(me))
|
||||
if body != "" {
|
||||
g.p(" %s\n", body)
|
||||
}
|
||||
g.p(" }\n")
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
// The imports the signatures use.
|
||||
body := b.String()
|
||||
uses := []string{"use mygo::*;"}
|
||||
if strings.Contains(body, "HashMap<") {
|
||||
uses = append(uses, "use std::collections::HashMap;")
|
||||
}
|
||||
uses = append(uses, "use std::sync::Arc;")
|
||||
var times []string
|
||||
for _, t := range []string{"Duration", "SystemTime"} {
|
||||
if regexp.MustCompile(`\b` + t + `\b`).MatchString(body) {
|
||||
times = append(times, t)
|
||||
}
|
||||
}
|
||||
switch len(times) {
|
||||
case 1:
|
||||
uses = append(uses, "use std::time::"+times[0]+";")
|
||||
case 2:
|
||||
uses = append(uses, "use std::time::{Duration, SystemTime};")
|
||||
}
|
||||
head := fmt.Sprintf("//! The implementation of package %s in Rust. Implement the methods one\n//! at a time: each says it is unsupported until it does.\n\nmod mygo;\n\n%s\n", m.Package, strings.Join(uses, "\n"))
|
||||
return append([]byte(head), body...)
|
||||
}
|
||||
+760
@@ -0,0 +1,760 @@
|
||||
package nativegen
|
||||
|
||||
// rustSupport is the part of the generated Rust that is the same for every
|
||||
// module, MODULEError replaced by the module's errors: the types the
|
||||
// implementation uses (Error, Context, Stream, Closer, Rect, Buffer) and
|
||||
// the runtime of the glue, with the standard library only.
|
||||
const rustSupport = `
|
||||
// Types for the implementation.
|
||||
|
||||
/// The values a method yields, which Go asks for one at a time, on a thread
|
||||
/// of their own.
|
||||
pub type Stream<T> = Box<dyn Iterator<Item = T> + Send>;
|
||||
|
||||
/// Makes a Stream of an iterator.
|
||||
pub fn stream_of<I>(it: I) -> Stream<I::Item>
|
||||
where
|
||||
I: Iterator + Send + 'static,
|
||||
{
|
||||
Box::new(it)
|
||||
}
|
||||
|
||||
/// An error an implementation returns, or Go did.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Error {
|
||||
/// One the module declares, which Go compares with errors.Is.
|
||||
Module(MODULEError),
|
||||
/// Reaches Go as errors.ErrUnsupported: the system lacks what the
|
||||
/// implementation needs.
|
||||
Unsupported,
|
||||
/// Reaches Go as native.ErrClosed.
|
||||
Closed,
|
||||
/// The call was canceled: Go's context is done.
|
||||
Canceled,
|
||||
/// An error a Go function or method returned.
|
||||
Go(String),
|
||||
/// Any other error, which Go reports with its message.
|
||||
Other {
|
||||
domain: String,
|
||||
number: i64,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// An error that says what message does.
|
||||
pub fn other(message: impl std::fmt::Display) -> Self {
|
||||
Error::Other {
|
||||
domain: String::new(),
|
||||
number: 0,
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Error::Module(e) => f.write_str(e.code()),
|
||||
Error::Unsupported => f.write_str("unsupported"),
|
||||
Error::Closed => f.write_str("closed"),
|
||||
Error::Canceled => f.write_str("canceled"),
|
||||
Error::Go(m) => f.write_str(m),
|
||||
Error::Other { domain, number, message } => {
|
||||
if message.is_empty() {
|
||||
write!(f, "{} error {}", domain, number)
|
||||
} else {
|
||||
f.write_str(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// What stops what a method started, as Go's io.Closer.
|
||||
pub trait Closer: Send + Sync {
|
||||
fn close(&self) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
struct FnCloser(std::sync::Mutex<Option<Box<dyn FnOnce() + Send>>>);
|
||||
|
||||
impl Closer for FnCloser {
|
||||
fn close(&self) -> Result<(), Error> {
|
||||
let f = self.0.lock().unwrap().take();
|
||||
if let Some(f) = f {
|
||||
f();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Closer that runs f, once.
|
||||
pub fn closer(f: impl FnOnce() + Send + 'static) -> Box<dyn Closer> {
|
||||
Box::new(FnCloser(std::sync::Mutex::new(Some(Box::new(f)))))
|
||||
}
|
||||
|
||||
/// The context of a method that takes one in Go: Go cancels it.
|
||||
pub struct Context {
|
||||
canceled: std::sync::Mutex<bool>,
|
||||
cond: std::sync::Condvar,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
fn new() -> Self {
|
||||
Context {
|
||||
canceled: std::sync::Mutex::new(false),
|
||||
cond: std::sync::Condvar::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
*self.canceled.lock().unwrap() = true;
|
||||
self.cond.notify_all();
|
||||
}
|
||||
|
||||
/// Reports whether Go canceled the call.
|
||||
pub fn is_canceled(&self) -> bool {
|
||||
*self.canceled.lock().unwrap()
|
||||
}
|
||||
|
||||
/// Returns Err(Error::Canceled) once Go canceled the call.
|
||||
pub fn check(&self) -> Result<(), Error> {
|
||||
if self.is_canceled() {
|
||||
Err(Error::Canceled)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits d, or until Go cancels the call, which returns
|
||||
/// Err(Error::Canceled).
|
||||
pub fn sleep(&self, d: Duration) -> Result<(), Error> {
|
||||
let deadline = std::time::Instant::now() + d;
|
||||
let mut canceled = self.canceled.lock().unwrap();
|
||||
loop {
|
||||
if *canceled {
|
||||
return Err(Error::Canceled);
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
if now >= deadline {
|
||||
return Ok(());
|
||||
}
|
||||
canceled = self.cond.wait_timeout(canceled, deadline - now).unwrap().0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle of native UI: a ui.Rect.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
/// Memory of Go's that the implementation fills: a *native.Buffer, valid
|
||||
/// during the call that takes it.
|
||||
#[derive(Debug)]
|
||||
pub struct Buffer {
|
||||
p: *mut u8,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
unsafe impl Send for Buffer {}
|
||||
unsafe impl Sync for Buffer {}
|
||||
|
||||
impl Buffer {
|
||||
pub fn len(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.n == 0
|
||||
}
|
||||
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
if self.p.is_null() {
|
||||
return &[];
|
||||
}
|
||||
unsafe { std::slice::from_raw_parts(self.p, self.n) }
|
||||
}
|
||||
|
||||
pub fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
if self.p.is_null() {
|
||||
return &mut [];
|
||||
}
|
||||
unsafe { std::slice::from_raw_parts_mut(self.p, self.n) }
|
||||
}
|
||||
}
|
||||
|
||||
// The runtime of the glue.
|
||||
|
||||
type Callback = unsafe extern "C" fn(u64, u64, i64, *const u8, usize) -> *mut u8;
|
||||
type Malloc = unsafe extern "C" fn(usize) -> *mut u8;
|
||||
type Free = unsafe extern "C" fn(*mut u8);
|
||||
|
||||
struct Runtime {
|
||||
cb: Callback,
|
||||
id_base: u64,
|
||||
malloc: Malloc,
|
||||
free: Free,
|
||||
}
|
||||
|
||||
static RUNTIME: std::sync::OnceLock<Runtime> = std::sync::OnceLock::new();
|
||||
|
||||
fn rt() -> &'static Runtime {
|
||||
RUNTIME.get().expect("the module is not initialized: Go loads it")
|
||||
}
|
||||
|
||||
const KIND_RESULT: u64 = 1;
|
||||
const KIND_ITEM: u64 = 2;
|
||||
const KIND_NOTIFY: u64 = 3;
|
||||
const KIND_ASK: u64 = 4;
|
||||
const KIND_RELEASE: u64 = 5;
|
||||
const KIND_INVOKE: u64 = 6;
|
||||
const KIND_INVOKE_ASYNC: u64 = 7;
|
||||
const KIND_CANCEL: u64 = 8;
|
||||
|
||||
const STATUS_OK: i64 = 0;
|
||||
const STATUS_ERROR: i64 = 1;
|
||||
const STATUS_PENDING: i64 = 2;
|
||||
const STATUS_END: i64 = 3;
|
||||
|
||||
// Values cross in a binary encoding, which package native describes, in
|
||||
// the order of the declarations: every integer as 8 bytes, little-endian,
|
||||
// floats as f64, bools as a byte, strings, bytes, vectors and maps as their
|
||||
// length then their contents, options as a bool then the value, structs as
|
||||
// their fields, enums as their values.
|
||||
|
||||
/// Writes values for Go, after the 16 bytes of a block's head: its status
|
||||
/// and its length.
|
||||
struct Writer {
|
||||
b: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
fn new() -> Self {
|
||||
let mut b = Vec::with_capacity(128);
|
||||
b.resize(16, 0);
|
||||
Writer { b }
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.b.truncate(16);
|
||||
}
|
||||
|
||||
fn data(&self) -> &[u8] {
|
||||
&self.b[16..]
|
||||
}
|
||||
|
||||
fn u64(&mut self, v: u64) {
|
||||
self.b.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
fn u8(&mut self, v: u8) {
|
||||
self.b.push(v);
|
||||
}
|
||||
|
||||
fn i64(&mut self, v: i64) {
|
||||
self.u64(v as u64);
|
||||
}
|
||||
|
||||
fn bool(&mut self, v: bool) {
|
||||
self.u8(v as u8);
|
||||
}
|
||||
|
||||
fn f64(&mut self, v: f64) {
|
||||
self.u64(v.to_bits());
|
||||
}
|
||||
|
||||
fn count(&mut self, n: usize) {
|
||||
self.i64(n as i64);
|
||||
}
|
||||
|
||||
fn string(&mut self, s: &str) {
|
||||
self.count(s.len());
|
||||
self.b.extend_from_slice(s.as_bytes());
|
||||
}
|
||||
|
||||
fn bytes(&mut self, b: &[u8]) {
|
||||
self.count(b.len());
|
||||
self.b.extend_from_slice(b);
|
||||
}
|
||||
|
||||
fn time(&mut self, t: &SystemTime) {
|
||||
let (s, ns) = match t.duration_since(SystemTime::UNIX_EPOCH) {
|
||||
Ok(d) => (d.as_secs() as i64, d.subsec_nanos() as i64),
|
||||
Err(e) => {
|
||||
let d = e.duration();
|
||||
let (mut s, mut ns) = (-(d.as_secs() as i64), d.subsec_nanos() as i64);
|
||||
if ns > 0 {
|
||||
s -= 1;
|
||||
ns = 1_000_000_000 - ns;
|
||||
}
|
||||
(s, ns)
|
||||
}
|
||||
};
|
||||
self.i64(s);
|
||||
self.i64(ns);
|
||||
}
|
||||
|
||||
fn duration(&mut self, d: &Duration) {
|
||||
self.i64(d.as_nanos().min(i64::MAX as u128) as i64);
|
||||
}
|
||||
|
||||
fn rect(&mut self, r: &Rect) {
|
||||
self.f64(r.x as f64);
|
||||
self.f64(r.y as f64);
|
||||
self.f64(r.w as f64);
|
||||
self.f64(r.h as f64);
|
||||
}
|
||||
|
||||
fn buffer(&mut self, b: &Buffer) {
|
||||
self.u64(b.p as u64);
|
||||
self.count(b.n);
|
||||
}
|
||||
|
||||
/// Gives the values to Go as a block, in memory Go frees.
|
||||
fn block(&mut self, status: i64) -> *mut u8 {
|
||||
let n = self.b.len() - 16;
|
||||
self.b[..8].copy_from_slice(&status.to_le_bytes());
|
||||
self.b[8..16].copy_from_slice(&(n as i64).to_le_bytes());
|
||||
unsafe {
|
||||
let p = (rt().malloc)(self.b.len());
|
||||
if !p.is_null() {
|
||||
std::ptr::copy_nonoverlapping(self.b.as_ptr(), p, self.b.len());
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the values Go wrote.
|
||||
struct Reader<'a> {
|
||||
b: &'a [u8],
|
||||
}
|
||||
|
||||
fn short() -> Error {
|
||||
Error::Go("a value from Go ends early".into())
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
unsafe fn new(p: *const u8, n: usize) -> Reader<'a> {
|
||||
if p.is_null() || n == 0 {
|
||||
return Reader { b: &[] };
|
||||
}
|
||||
Reader {
|
||||
b: std::slice::from_raw_parts(p, n),
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, k: usize) -> Result<&'a [u8], Error> {
|
||||
if k > self.b.len() {
|
||||
return Err(short());
|
||||
}
|
||||
let (v, rest) = self.b.split_at(k);
|
||||
self.b = rest;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn u64(&mut self) -> Result<u64, Error> {
|
||||
let b = self.take(8)?;
|
||||
Ok(u64::from_le_bytes(b.try_into().unwrap()))
|
||||
}
|
||||
|
||||
fn u8(&mut self) -> Result<u8, Error> {
|
||||
Ok(self.take(1)?[0])
|
||||
}
|
||||
|
||||
fn i64(&mut self) -> Result<i64, Error> {
|
||||
Ok(self.u64()? as i64)
|
||||
}
|
||||
|
||||
fn bool(&mut self) -> Result<bool, Error> {
|
||||
Ok(self.u8()? != 0)
|
||||
}
|
||||
|
||||
fn f64(&mut self) -> Result<f64, Error> {
|
||||
Ok(f64::from_bits(self.u64()?))
|
||||
}
|
||||
|
||||
/// Reads the length of a vector or a map, whose elements take a byte
|
||||
/// each at least.
|
||||
fn count(&mut self) -> Result<usize, Error> {
|
||||
let n = self.i64()?;
|
||||
if n < 0 || n as u64 > self.b.len() as u64 {
|
||||
return Err(short());
|
||||
}
|
||||
Ok(n as usize)
|
||||
}
|
||||
|
||||
fn string(&mut self) -> Result<String, Error> {
|
||||
let n = self.count()?;
|
||||
Ok(String::from_utf8_lossy(self.take(n)?).into_owned())
|
||||
}
|
||||
|
||||
fn bytes(&mut self) -> Result<Vec<u8>, Error> {
|
||||
let n = self.count()?;
|
||||
Ok(self.take(n)?.to_vec())
|
||||
}
|
||||
|
||||
fn time(&mut self) -> Result<SystemTime, Error> {
|
||||
let s = self.i64()?;
|
||||
let ns = self.i64()?.clamp(0, 999_999_999) as u32;
|
||||
let t = if s >= 0 {
|
||||
SystemTime::UNIX_EPOCH.checked_add(Duration::new(s as u64, ns))
|
||||
} else {
|
||||
SystemTime::UNIX_EPOCH
|
||||
.checked_sub(Duration::new(s.unsigned_abs(), 0))
|
||||
.and_then(|t| t.checked_add(Duration::new(0, ns)))
|
||||
};
|
||||
Ok(t.unwrap_or(SystemTime::UNIX_EPOCH))
|
||||
}
|
||||
|
||||
/// Reads a time.Duration, which is zero when negative.
|
||||
fn duration(&mut self) -> Result<Duration, Error> {
|
||||
Ok(Duration::from_nanos(self.i64()?.max(0) as u64))
|
||||
}
|
||||
|
||||
fn rect(&mut self) -> Result<Rect, Error> {
|
||||
Ok(Rect {
|
||||
x: self.f64()? as f32,
|
||||
y: self.f64()? as f32,
|
||||
w: self.f64()? as f32,
|
||||
h: self.f64()? as f32,
|
||||
})
|
||||
}
|
||||
|
||||
fn buffer(&mut self) -> Result<Buffer, Error> {
|
||||
let p = self.u64()? as *mut u8;
|
||||
let n = self.i64()?.max(0) as usize;
|
||||
Ok(Buffer { p, n })
|
||||
}
|
||||
}
|
||||
|
||||
// The kinds of errors, as they cross both ways: the kind, then the code,
|
||||
// domain, number and message.
|
||||
const ERR_OTHER: u8 = 0;
|
||||
const ERR_CODE: u8 = 1;
|
||||
const ERR_UNSUPPORTED: u8 = 2;
|
||||
const ERR_CLOSED: u8 = 3;
|
||||
const ERR_CANCELED: u8 = 4;
|
||||
const ERR_GO: u8 = 5;
|
||||
|
||||
fn write_error(w: &mut Writer, e: &Error) {
|
||||
let (kind, code, domain, number, message) = match e {
|
||||
Error::Module(c) => (ERR_CODE, c.code(), "", 0, String::new()),
|
||||
Error::Unsupported => (ERR_UNSUPPORTED, "", "", 0, String::new()),
|
||||
Error::Closed => (ERR_CLOSED, "", "", 0, String::new()),
|
||||
Error::Canceled => (ERR_CANCELED, "", "", 0, String::new()),
|
||||
Error::Go(m) => (ERR_GO, "", "", 0, m.clone()),
|
||||
Error::Other { domain, number, message } => (ERR_OTHER, "", domain.as_str(), *number, message.clone()),
|
||||
};
|
||||
w.u8(kind);
|
||||
w.string(code);
|
||||
w.string(domain);
|
||||
w.i64(number);
|
||||
w.string(&message);
|
||||
}
|
||||
|
||||
fn read_error(r: &mut Reader) -> Error {
|
||||
let mut read = || -> Result<Error, Error> {
|
||||
let kind = r.u8()?;
|
||||
let code = r.string()?;
|
||||
let domain = r.string()?;
|
||||
let number = r.i64()?;
|
||||
let message = r.string()?;
|
||||
Ok(match kind {
|
||||
ERR_CODE => MODULEError::from_code(&code).map(Error::Module).unwrap_or(Error::Go(message)),
|
||||
ERR_UNSUPPORTED => Error::Unsupported,
|
||||
ERR_CLOSED => Error::Closed,
|
||||
ERR_CANCELED => Error::Canceled,
|
||||
ERR_OTHER if !domain.is_empty() => Error::Other { domain, number, message },
|
||||
_ => Error::Go(message),
|
||||
})
|
||||
};
|
||||
read().unwrap_or_else(|_| Error::Go("an error of Go's that does not decode".into()))
|
||||
}
|
||||
|
||||
fn panic_error(p: Box<dyn std::any::Any + Send>) -> Error {
|
||||
let msg = if let Some(s) = p.downcast_ref::<&str>() {
|
||||
s.to_string()
|
||||
} else if let Some(s) = p.downcast_ref::<String>() {
|
||||
s.clone()
|
||||
} else {
|
||||
"a panic".to_string()
|
||||
};
|
||||
Error::Other {
|
||||
domain: "panic".into(),
|
||||
number: 0,
|
||||
message: msg,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs f, catching a panic, which must not unwind into Go.
|
||||
fn guard<R>(f: impl FnOnce() -> R) -> Result<R, Error> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_error)
|
||||
}
|
||||
|
||||
/// Runs what returns at once, which writes its result to the writer.
|
||||
fn run(body: impl FnOnce(&mut Writer) -> Result<(), Error>) -> *mut u8 {
|
||||
let mut w = Writer::new();
|
||||
match guard(|| body(&mut w)).and_then(|r| r) {
|
||||
Ok(()) => w.block(STATUS_OK),
|
||||
Err(e) => {
|
||||
w.reset();
|
||||
write_error(&mut w, &e);
|
||||
w.block(STATUS_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs what starts an asynchronous call or a stream: Go waits for its
|
||||
/// results through the callback.
|
||||
fn start(body: impl FnOnce() -> Result<(), Error>) -> *mut u8 {
|
||||
let mut w = Writer::new();
|
||||
match guard(body).and_then(|r| r) {
|
||||
Ok(()) => w.block(STATUS_PENDING),
|
||||
Err(e) => {
|
||||
write_error(&mut w, &e);
|
||||
w.block(STATUS_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells Go something, with the values w holds, and returns its answer, a
|
||||
/// block to read with answer, if any.
|
||||
fn send(kind: u64, id: u64, status: i64, w: Option<&Writer>) -> *mut u8 {
|
||||
let rt = rt();
|
||||
unsafe {
|
||||
match w {
|
||||
Some(w) if !w.data().is_empty() => (rt.cb)(kind, id, status, w.data().as_ptr(), w.data().len()),
|
||||
_ => (rt.cb)(kind, id, status, std::ptr::null(), 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a block Go answered with, and frees it.
|
||||
fn answer<R>(p: *mut u8, read: impl FnOnce(&mut Reader) -> Result<R, Error>) -> Result<R, Error> {
|
||||
if p.is_null() {
|
||||
return Err(Error::Closed);
|
||||
}
|
||||
unsafe {
|
||||
let head = std::slice::from_raw_parts(p, 16);
|
||||
let status = i64::from_le_bytes(head[..8].try_into().unwrap());
|
||||
let n = i64::from_le_bytes(head[8..].try_into().unwrap()) as usize;
|
||||
let mut r = Reader::new(p.add(16), n);
|
||||
let v = if status == STATUS_ERROR {
|
||||
Err(read_error(&mut r))
|
||||
} else {
|
||||
read(&mut r)
|
||||
};
|
||||
(rt().free)(p);
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
fn retain(o: Obj) -> u64 {
|
||||
Box::into_raw(Box::new(o)) as u64
|
||||
}
|
||||
|
||||
fn object<'a>(h: u64) -> Result<&'a Obj, Error> {
|
||||
if h == 0 {
|
||||
return Err(Error::Closed);
|
||||
}
|
||||
Ok(unsafe { &*(h as *const Obj) })
|
||||
}
|
||||
|
||||
struct Table<V> {
|
||||
m: std::sync::Mutex<Option<HashMap<u64, V>>>,
|
||||
}
|
||||
|
||||
impl<V> Table<V> {
|
||||
const fn new() -> Self {
|
||||
Table {
|
||||
m: std::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn put(&self, k: u64, v: V) {
|
||||
self.m.lock().unwrap().get_or_insert_with(HashMap::new).insert(k, v);
|
||||
}
|
||||
|
||||
fn remove(&self, k: u64) -> Option<V> {
|
||||
self.m.lock().unwrap().as_mut().and_then(|m| m.remove(&k))
|
||||
}
|
||||
|
||||
fn with<R>(&self, k: u64, f: impl FnOnce(&V) -> R) -> Option<R> {
|
||||
self.m.lock().unwrap().as_ref().and_then(|m| m.get(&k)).map(f)
|
||||
}
|
||||
}
|
||||
|
||||
/// The contexts of asynchronous calls and streams, by their call, which
|
||||
/// Go cancels.
|
||||
static TASKS: Table<Arc<Context>> = Table::new();
|
||||
/// Go's demands for the next values of streams.
|
||||
static DEMANDS: Table<std::sync::mpsc::Sender<()>> = Table::new();
|
||||
/// The calls waiting for Go to answer, by their continuation.
|
||||
static CONTS: Table<std::sync::mpsc::Sender<usize>> = Table::new();
|
||||
|
||||
static LAST_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// The id of a continuation: the module's index, from Go, in its high bits
|
||||
/// makes it unique among modules.
|
||||
fn next_id() -> u64 {
|
||||
rt().id_base | (LAST_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1)
|
||||
}
|
||||
|
||||
fn cancel(call: u64) {
|
||||
TASKS.with(call, |c| c.cancel());
|
||||
// A stream waiting for Go's next demand stops.
|
||||
DEMANDS.remove(call);
|
||||
}
|
||||
|
||||
fn demand(call: u64) {
|
||||
DEMANDS.with(call, |d| {
|
||||
let _ = d.send(());
|
||||
});
|
||||
}
|
||||
|
||||
fn resume(cont: u64, block: *mut u8) {
|
||||
match CONTS.remove(cont) {
|
||||
Some(c) => {
|
||||
let _ = c.send(block as usize);
|
||||
}
|
||||
None => unsafe { (rt().free)(block) },
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an asynchronous call on a thread of its own, which reports its
|
||||
/// result through the callback.
|
||||
fn task(call: u64, body: impl FnOnce(&Context, &mut Writer) -> Result<(), Error> + Send + 'static) {
|
||||
let ctx = Arc::new(Context::new());
|
||||
TASKS.put(call, Arc::clone(&ctx));
|
||||
std::thread::spawn(move || {
|
||||
let mut w = Writer::new();
|
||||
let status = match guard(|| body(&ctx, &mut w)).and_then(|r| r) {
|
||||
Ok(()) => STATUS_OK,
|
||||
Err(e) => {
|
||||
w.reset();
|
||||
write_error(&mut w, &e);
|
||||
STATUS_ERROR
|
||||
}
|
||||
};
|
||||
TASKS.remove(call);
|
||||
send(KIND_RESULT, call, status, Some(&w));
|
||||
});
|
||||
}
|
||||
|
||||
/// Runs a stream on a thread of its own, which yields a value each time Go
|
||||
/// asks for one.
|
||||
fn stream<T: 'static>(
|
||||
call: u64,
|
||||
make: impl FnOnce(&Context) -> Stream<Result<T, Error>> + Send + 'static,
|
||||
enc: fn(&mut Writer, &T),
|
||||
) {
|
||||
let ctx = Arc::new(Context::new());
|
||||
let (tx, rx) = std::sync::mpsc::channel::<()>();
|
||||
TASKS.put(call, Arc::clone(&ctx));
|
||||
DEMANDS.put(call, tx);
|
||||
std::thread::spawn(move || {
|
||||
let mut w = Writer::new();
|
||||
let mut it = match guard(|| make(&ctx)) {
|
||||
Ok(it) => Some(it),
|
||||
Err(e) => {
|
||||
write_error(&mut w, &e);
|
||||
None
|
||||
}
|
||||
};
|
||||
while rx.recv().is_ok() {
|
||||
let Some(s) = it.as_mut() else {
|
||||
send(KIND_ITEM, call, STATUS_ERROR, Some(&w));
|
||||
break;
|
||||
};
|
||||
w.reset();
|
||||
match guard(|| s.next()) {
|
||||
Ok(None) => {
|
||||
send(KIND_ITEM, call, STATUS_END, None);
|
||||
break;
|
||||
}
|
||||
Ok(Some(Ok(v))) => {
|
||||
enc(&mut w, &v);
|
||||
send(KIND_ITEM, call, STATUS_OK, Some(&w));
|
||||
}
|
||||
Ok(Some(Err(e))) | Err(e) => {
|
||||
write_error(&mut w, &e);
|
||||
send(KIND_ITEM, call, STATUS_ERROR, Some(&w));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
DEMANDS.remove(call);
|
||||
TASKS.remove(call);
|
||||
});
|
||||
}
|
||||
|
||||
/// A Go function the implementation calls: a notification, or a question
|
||||
/// Go answers at once.
|
||||
struct GoFunc {
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl GoFunc {
|
||||
fn new(id: u64) -> Self {
|
||||
GoFunc { id }
|
||||
}
|
||||
|
||||
fn notify(&self, w: Writer) {
|
||||
if self.id != 0 {
|
||||
send(KIND_NOTIFY, self.id, 0, Some(&w));
|
||||
}
|
||||
}
|
||||
|
||||
fn ask<R>(&self, w: Writer, read: impl FnOnce(&mut Reader) -> Result<R, Error>) -> Result<R, Error> {
|
||||
if self.id == 0 {
|
||||
return Err(Error::Closed);
|
||||
}
|
||||
answer(send(KIND_ASK, self.id, 0, Some(&w)), read)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for GoFunc {
|
||||
fn drop(&mut self) {
|
||||
if self.id != 0 {
|
||||
send(KIND_RELEASE, self.id, 0, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the method of a value of Go's that w names, with the arguments
|
||||
/// after it.
|
||||
fn invoke<R>(id: u64, w: Writer, read: impl FnOnce(&mut Reader) -> Result<R, Error>) -> Result<R, Error> {
|
||||
answer(send(KIND_INVOKE, id, 0, Some(&w)), read)
|
||||
}
|
||||
|
||||
/// Calls a method of Go's that takes a context, which ctx cancels, and
|
||||
/// waits for its answer.
|
||||
fn invoke_async<R>(id: u64, ctx: &Context, w: Writer, read: impl FnOnce(&mut Reader) -> Result<R, Error>) -> Result<R, Error> {
|
||||
let cont = next_id();
|
||||
let (tx, rx) = std::sync::mpsc::channel::<usize>();
|
||||
CONTS.put(cont, tx);
|
||||
send(KIND_INVOKE_ASYNC, id, cont as i64, Some(&w));
|
||||
let mut canceled = false;
|
||||
let p = loop {
|
||||
match rx.recv_timeout(Duration::from_millis(10)) {
|
||||
Ok(p) => break p,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
if !canceled && ctx.is_canceled() {
|
||||
canceled = true;
|
||||
send(KIND_CANCEL, cont, 0, None);
|
||||
}
|
||||
}
|
||||
Err(_) => break 0,
|
||||
}
|
||||
};
|
||||
answer(p as *mut u8, read)
|
||||
}
|
||||
`
|
||||
+719
@@ -0,0 +1,719 @@
|
||||
package nativegen
|
||||
|
||||
// swiftSupport is the part of the generated Swift that is the same for
|
||||
// every module, MODULE replaced by its name: the types the implementation
|
||||
// uses (NativeError, Closer, NativeCloser, NativeBuffer) and the glue Go
|
||||
// calls through.
|
||||
const swiftSupport = `
|
||||
// MARK: - Types for the implementation
|
||||
|
||||
/// Errors an implementation throws that are not the module's own.
|
||||
public enum NativeError: Error, Sendable {
|
||||
/// Reaches Go as errors.ErrUnsupported: the system lacks what the
|
||||
/// implementation needs, such as a framework of a newer version.
|
||||
case unsupported
|
||||
/// Reaches Go as native.ErrClosed.
|
||||
case closed
|
||||
/// An error a Go function or method returned.
|
||||
case go(String)
|
||||
}
|
||||
|
||||
/// What stops what a method started, as Go's io.Closer.
|
||||
public protocol Closer: AnyObject {
|
||||
func close() throws
|
||||
}
|
||||
|
||||
/// A Closer that runs a closure, once.
|
||||
public final class NativeCloser: Closer, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var fn: (() -> Void)?
|
||||
|
||||
public init(_ fn: @escaping () -> Void) { self.fn = fn }
|
||||
|
||||
public func close() {
|
||||
lock.lock()
|
||||
let f = fn
|
||||
fn = nil
|
||||
lock.unlock()
|
||||
f?()
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory that Go and the implementation both use: a *native.Buffer.
|
||||
public final class NativeBuffer: @unchecked Sendable {
|
||||
/// The buffer's memory, valid as long as the buffer.
|
||||
public let bytes: UnsafeMutableRawBufferPointer
|
||||
private let owned: Bool
|
||||
/// The pool the buffer goes back to once Go is done with it.
|
||||
fileprivate weak var pool: NativeBufferPool?
|
||||
|
||||
/// Makes a buffer of count bytes, which the implementation may yield
|
||||
/// from a stream: Go reads it until its loop asks for the next value.
|
||||
public init(count: Int) {
|
||||
bytes = .allocate(byteCount: Swift.max(count, 1), alignment: 16)
|
||||
owned = true
|
||||
}
|
||||
|
||||
public var count: Int { bytes.count }
|
||||
|
||||
/// The buffer of Go's at p.
|
||||
init(p: UInt64, count: Int) {
|
||||
bytes = UnsafeMutableRawBufferPointer(start: UnsafeMutableRawPointer(bitPattern: UInt(p)), count: count)
|
||||
owned = false
|
||||
}
|
||||
|
||||
deinit {
|
||||
if owned { bytes.deallocate() }
|
||||
}
|
||||
|
||||
/// Gives the buffer back to its pool, as Go's loop moved on.
|
||||
fileprivate func recycle() { pool?.put(self) }
|
||||
}
|
||||
|
||||
/// Buffers of one size that a stream yields, each reused once Go's loop
|
||||
/// moves on from it, so that a stream of buffers allocates none once it
|
||||
/// runs: get one, fill it, yield it.
|
||||
public final class NativeBufferPool: @unchecked Sendable {
|
||||
/// The size of the pool's buffers.
|
||||
public let size: Int
|
||||
private let lock = NSLock()
|
||||
private var free: [NativeBuffer] = []
|
||||
|
||||
public init(size: Int) { self.size = size }
|
||||
|
||||
/// Returns a buffer Go is done with, or a new one.
|
||||
public func get() -> NativeBuffer {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if let b = free.popLast() { return b }
|
||||
let b = NativeBuffer(count: size)
|
||||
b.pool = self
|
||||
return b
|
||||
}
|
||||
|
||||
fileprivate func put(_ b: NativeBuffer) {
|
||||
lock.lock()
|
||||
free.append(b)
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/// An image on the GPU that native UI shows: a *native.Texture. Present
|
||||
/// frames into it, IOSurfaces or CVPixelBuffers backed by them, which show
|
||||
/// in the next frame of the windows showing it.
|
||||
public final class NativeTexture: @unchecked Sendable {
|
||||
let id: UInt64
|
||||
|
||||
init(id: UInt64) { self.id = id }
|
||||
|
||||
#if canImport(IOSurface)
|
||||
/// The attributes of the pixel buffers native UI draws without
|
||||
/// converting them: 32-bit BGRA, backed by IOSurfaces, for Metal.
|
||||
public var pixelBufferAttributes: [String: Any] {
|
||||
[
|
||||
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
|
||||
kCVPixelBufferIOSurfacePropertiesKey as String: [String: Any](),
|
||||
kCVPixelBufferMetalCompatibilityKey as String: true,
|
||||
]
|
||||
}
|
||||
|
||||
/// Shows surface, 32-bit BGRA, in the next frame. Native UI keeps it
|
||||
/// until another one replaces it: draw the next frame into another
|
||||
/// surface, as a pool of pixel buffers gives.
|
||||
public func present(_ surface: IOSurfaceRef) {
|
||||
let p = Unmanaged.passRetained(surface).toOpaque()
|
||||
_mygoSend(_mygoKindPresent, id, Int64(Int(bitPattern: p)), nil)
|
||||
}
|
||||
|
||||
/// Shows the IOSurface backing buffer in the next frame.
|
||||
public func present(_ buffer: CVPixelBuffer) {
|
||||
guard let s = CVPixelBufferGetIOSurface(buffer)?.takeUnretainedValue() else { return }
|
||||
present(s)
|
||||
}
|
||||
|
||||
#endif
|
||||
#if os(macOS)
|
||||
/// Calls f on each refresh of the display, with the host time the
|
||||
/// frame will show at, in seconds (as CACurrentMediaTime counts),
|
||||
/// until the link is invalidated.
|
||||
public func displayLink(_ f: @escaping @Sendable (CFTimeInterval) -> Void) -> NativeDisplayLink {
|
||||
NativeDisplayLink(f)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
/// Calls back on each refresh of the display, until invalidated.
|
||||
public final class NativeDisplayLink: @unchecked Sendable {
|
||||
private var link: CVDisplayLink?
|
||||
|
||||
init(_ f: @escaping @Sendable (CFTimeInterval) -> Void) {
|
||||
CVDisplayLinkCreateWithActiveCGDisplays(&link)
|
||||
guard let link else { return }
|
||||
let frequency = CVGetHostClockFrequency()
|
||||
CVDisplayLinkSetOutputHandler(link) { _, _, out, _, _ in
|
||||
f(Double(out.pointee.hostTime) / frequency)
|
||||
return kCVReturnSuccess
|
||||
}
|
||||
CVDisplayLinkStart(link)
|
||||
}
|
||||
|
||||
/// Stops the callbacks.
|
||||
public func invalidate() {
|
||||
if let link { CVDisplayLinkStop(link) }
|
||||
link = nil
|
||||
}
|
||||
|
||||
deinit { invalidate() }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Glue
|
||||
|
||||
public typealias _MygoCallback = @convention(c) (UInt64, UInt64, Int64, UnsafeRawPointer?, Int) -> UnsafeMutableRawPointer?
|
||||
|
||||
nonisolated(unsafe) var _mygoCallback: _MygoCallback?
|
||||
|
||||
let _mygoKindResult: UInt64 = 1
|
||||
let _mygoKindItem: UInt64 = 2
|
||||
let _mygoKindNotify: UInt64 = 3
|
||||
let _mygoKindAsk: UInt64 = 4
|
||||
let _mygoKindRelease: UInt64 = 5
|
||||
let _mygoKindInvoke: UInt64 = 6
|
||||
let _mygoKindInvokeAsync: UInt64 = 7
|
||||
let _mygoKindCancel: UInt64 = 8
|
||||
let _mygoKindPresent: UInt64 = 9
|
||||
|
||||
// Values cross in a binary encoding, which package native describes, in
|
||||
// the order of the declarations: every integer as 8 bytes, little-endian,
|
||||
// floats as Double, bools as a byte, strings, Data, arrays and
|
||||
// dictionaries as their count then their contents, optionals as a Bool
|
||||
// then the value, structs as their fields, enums as their raw values.
|
||||
|
||||
/// Writes values for Go, after the 16 bytes of a block's head: its status
|
||||
/// and its length.
|
||||
struct _MygoWriter {
|
||||
private(set) var p: UnsafeMutableRawPointer
|
||||
private var cap: Int
|
||||
private(set) var n = 16
|
||||
|
||||
init() {
|
||||
cap = 128
|
||||
p = malloc(cap)!
|
||||
}
|
||||
|
||||
private mutating func reserve(_ k: Int) {
|
||||
if n + k <= cap { return }
|
||||
cap = Swift.max(cap * 2, n + k)
|
||||
p = realloc(p, cap)!
|
||||
}
|
||||
|
||||
mutating func raw(_ b: UnsafeRawBufferPointer) {
|
||||
guard let base = b.baseAddress, b.count > 0 else { return }
|
||||
reserve(b.count)
|
||||
(p + n).copyMemory(from: base, byteCount: b.count)
|
||||
n += b.count
|
||||
}
|
||||
|
||||
mutating func u64(_ v: UInt64) {
|
||||
reserve(8)
|
||||
p.storeBytes(of: v.littleEndian, toByteOffset: n, as: UInt64.self)
|
||||
n += 8
|
||||
}
|
||||
|
||||
mutating func u8(_ v: UInt8) {
|
||||
reserve(1)
|
||||
p.storeBytes(of: v, toByteOffset: n, as: UInt8.self)
|
||||
n += 1
|
||||
}
|
||||
|
||||
mutating func i64(_ v: Int64) { u64(UInt64(bitPattern: v)) }
|
||||
mutating func bool(_ v: Bool) { u8(v ? 1 : 0) }
|
||||
mutating func double(_ v: Double) { u64(v.bitPattern) }
|
||||
mutating func count(_ c: Int) { i64(Int64(c)) }
|
||||
|
||||
mutating func string(_ s: String) {
|
||||
var s = s
|
||||
s.withUTF8 { b in
|
||||
self.count(b.count)
|
||||
self.raw(UnsafeRawBufferPointer(b))
|
||||
}
|
||||
}
|
||||
|
||||
mutating func data(_ d: Data) {
|
||||
count(d.count)
|
||||
d.withUnsafeBytes { self.raw($0) }
|
||||
}
|
||||
|
||||
mutating func date(_ d: Date) {
|
||||
let t = d.timeIntervalSince1970
|
||||
var s = t.rounded(.down)
|
||||
var ns = ((t - s) * 1e9).rounded()
|
||||
if ns >= 1e9 {
|
||||
s += 1
|
||||
ns -= 1e9
|
||||
}
|
||||
i64(Int64(s))
|
||||
i64(Int64(ns))
|
||||
}
|
||||
|
||||
mutating func rect(_ r: CGRect) {
|
||||
double(Double(r.minX))
|
||||
double(Double(r.minY))
|
||||
double(Double(r.width))
|
||||
double(Double(r.height))
|
||||
}
|
||||
|
||||
mutating func buffer(_ b: NativeBuffer) {
|
||||
u64(UInt64(UInt(bitPattern: b.bytes.baseAddress)))
|
||||
count(b.count)
|
||||
}
|
||||
|
||||
mutating func texture(_ t: NativeTexture) { u64(t.id) }
|
||||
|
||||
/// The values written, without the head.
|
||||
var bytes: UnsafeRawBufferPointer { UnsafeRawBufferPointer(start: p + 16, count: n - 16) }
|
||||
|
||||
/// Forgets what was written.
|
||||
mutating func reset() { n = 16 }
|
||||
|
||||
/// Gives the values to Go as a block, which Go frees.
|
||||
func block(_ status: Int64) -> UnsafeMutableRawPointer {
|
||||
p.storeBytes(of: status, as: Int64.self)
|
||||
p.storeBytes(of: Int64(n - 16), toByteOffset: 8, as: Int64.self)
|
||||
return p
|
||||
}
|
||||
|
||||
/// Frees the writer, which a block Go was given does not need.
|
||||
func free() { Foundation.free(p) }
|
||||
}
|
||||
|
||||
enum _MygoWireError: Error {
|
||||
case short
|
||||
case value(String, String)
|
||||
}
|
||||
|
||||
/// Reads the values Go wrote.
|
||||
struct _MygoReader {
|
||||
let p: UnsafeRawPointer?
|
||||
let n: Int
|
||||
var i = 0
|
||||
|
||||
init(_ p: UnsafeRawPointer?, _ n: Int) {
|
||||
self.p = p
|
||||
self.n = n
|
||||
}
|
||||
|
||||
mutating func take(_ k: Int) throws -> UnsafeRawPointer {
|
||||
guard k >= 0, k <= n - i, let p else { throw _MygoWireError.short }
|
||||
defer { i += k }
|
||||
return p + i
|
||||
}
|
||||
|
||||
mutating func u64() throws -> UInt64 { UInt64(littleEndian: try take(8).loadUnaligned(as: UInt64.self)) }
|
||||
mutating func u8() throws -> UInt8 { try take(1).load(as: UInt8.self) }
|
||||
mutating func i64() throws -> Int64 { Int64(bitPattern: try u64()) }
|
||||
mutating func bool() throws -> Bool { try u8() != 0 }
|
||||
mutating func double() throws -> Double { Double(bitPattern: try u64()) }
|
||||
|
||||
/// Reads the count of an array or a dictionary, whose elements take a
|
||||
/// byte each at least.
|
||||
mutating func count() throws -> Int {
|
||||
let c = try i64()
|
||||
guard c >= 0, c <= Int64(n - i) else { throw _MygoWireError.short }
|
||||
return Int(c)
|
||||
}
|
||||
|
||||
mutating func string() throws -> String {
|
||||
let c = try count()
|
||||
return String(decoding: UnsafeRawBufferPointer(start: try take(c), count: c), as: UTF8.self)
|
||||
}
|
||||
|
||||
mutating func data() throws -> Data {
|
||||
let c = try count()
|
||||
return Data(bytes: try take(c), count: c)
|
||||
}
|
||||
|
||||
mutating func date() throws -> Date {
|
||||
let s = try i64()
|
||||
let ns = try i64()
|
||||
return Date(timeIntervalSince1970: Double(s) + Double(ns) / 1e9)
|
||||
}
|
||||
|
||||
mutating func rect() throws -> CGRect {
|
||||
CGRect(x: try double(), y: try double(), width: try double(), height: try double())
|
||||
}
|
||||
|
||||
mutating func buffer() throws -> NativeBuffer {
|
||||
let p = try u64()
|
||||
return NativeBuffer(p: p, count: Int(try i64()))
|
||||
}
|
||||
|
||||
mutating func texture() throws -> NativeTexture { NativeTexture(id: try u64()) }
|
||||
}
|
||||
|
||||
/// Tells Go something, with the values w holds, and returns its answer, a
|
||||
/// block to read with _mygoAnswer, if any.
|
||||
@discardableResult
|
||||
func _mygoSend(_ kind: UInt64, _ id: UInt64, _ status: Int64, _ w: _MygoWriter?) -> UnsafeMutableRawPointer? {
|
||||
guard let cb = _mygoCallback else { return nil }
|
||||
guard let w, w.n > 16 else { return cb(kind, id, status, nil, 0) }
|
||||
return cb(kind, id, status, w.p + 16, w.n - 16)
|
||||
}
|
||||
|
||||
/// Reads a block Go answered with, and frees it.
|
||||
func _mygoAnswer<R>(_ p: UnsafeMutableRawPointer?, _ read: (inout _MygoReader) throws -> R) throws -> R {
|
||||
guard let p else { throw NativeError.closed }
|
||||
defer { free(p) }
|
||||
let st = p.loadUnaligned(as: Int64.self)
|
||||
var r = _MygoReader(p + 16, Int(p.loadUnaligned(fromByteOffset: 8, as: Int64.self)))
|
||||
if st == 1 { throw _mygoReadError(&r) }
|
||||
return try read(&r)
|
||||
}
|
||||
|
||||
/// Runs what returns at once, which writes its result to w.
|
||||
func _mygoRun(_ body: (inout _MygoWriter) throws -> Void) -> UnsafeMutableRawPointer? {
|
||||
var w = _MygoWriter()
|
||||
do {
|
||||
try body(&w)
|
||||
return w.block(0)
|
||||
} catch {
|
||||
w.reset()
|
||||
_mygoWriteError(&w, error)
|
||||
return w.block(1)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoRunMain(_ body: @MainActor (inout _MygoWriter) throws -> Void) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { w in try MainActor.assumeIsolated { try body(&w) } }
|
||||
}
|
||||
|
||||
/// Runs what starts an asynchronous call or a stream: Go waits for its
|
||||
/// results through the callback.
|
||||
func _mygoStart(_ body: () throws -> Void) -> UnsafeMutableRawPointer? {
|
||||
var w = _MygoWriter()
|
||||
do {
|
||||
try body()
|
||||
return w.block(2)
|
||||
} catch {
|
||||
_mygoWriteError(&w, error)
|
||||
return w.block(1)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoCall<T>(_ f: () throws -> T) rethrows -> T { try f() }
|
||||
|
||||
@MainActor func _mygoCallMain<T>(_ f: @MainActor () throws -> T) rethrows -> T { try f() }
|
||||
|
||||
func _mygoMust<T>(_ f: () throws -> T) -> T {
|
||||
do {
|
||||
return try f()
|
||||
} catch {
|
||||
fatalError("MODULE: Go failed to answer: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoFail<T>() -> T { fatalError("MODULE: Go failed to answer") }
|
||||
|
||||
// The kinds of errors, as they cross both ways: the kind, then the code,
|
||||
// domain, number and message.
|
||||
let _mygoErrOther: UInt8 = 0
|
||||
let _mygoErrCode: UInt8 = 1
|
||||
let _mygoErrUnsupported: UInt8 = 2
|
||||
let _mygoErrClosed: UInt8 = 3
|
||||
let _mygoErrCanceled: UInt8 = 4
|
||||
let _mygoErrGo: UInt8 = 5
|
||||
|
||||
func _mygoWriteError(_ w: inout _MygoWriter, _ error: any Error) {
|
||||
var kind = _mygoErrOther
|
||||
var code = "", domain = "", message = ""
|
||||
var number = 0
|
||||
switch error {
|
||||
case let e as MODULEError:
|
||||
kind = _mygoErrCode
|
||||
code = e.rawValue
|
||||
case NativeError.unsupported:
|
||||
kind = _mygoErrUnsupported
|
||||
case NativeError.closed:
|
||||
kind = _mygoErrClosed
|
||||
case NativeError.go(let m):
|
||||
kind = _mygoErrGo
|
||||
message = m
|
||||
case is CancellationError:
|
||||
kind = _mygoErrCanceled
|
||||
default:
|
||||
let ns = error as NSError
|
||||
if type(of: error) is NSError.Type {
|
||||
domain = ns.domain
|
||||
message = ns.localizedDescription
|
||||
} else {
|
||||
let name = String(describing: type(of: error))
|
||||
domain = name
|
||||
message = (error as? LocalizedError)?.errorDescription ?? "\(name).\(error)"
|
||||
}
|
||||
number = ns.code
|
||||
}
|
||||
w.u8(kind)
|
||||
w.string(code)
|
||||
w.string(domain)
|
||||
w.i64(Int64(number))
|
||||
w.string(message)
|
||||
}
|
||||
|
||||
func _mygoReadError(_ r: inout _MygoReader) -> any Error {
|
||||
guard let kind = try? r.u8(), let code = try? r.string(), (try? r.string()) != nil, (try? r.i64()) != nil, let message = try? r.string() else {
|
||||
return NativeError.go("an error of Go's that does not decode")
|
||||
}
|
||||
switch kind {
|
||||
case _mygoErrCode: return MODULEError(rawValue: code) ?? NativeError.go(message)
|
||||
case _mygoErrUnsupported: return NativeError.unsupported
|
||||
case _mygoErrClosed: return NativeError.closed
|
||||
case _mygoErrCanceled: return CancellationError()
|
||||
default: return NativeError.go(message)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoRetain(_ v: AnyObject) -> UInt64 {
|
||||
UInt64(UInt(bitPattern: Unmanaged.passRetained(v).toOpaque()))
|
||||
}
|
||||
|
||||
func _mygoAnyObject(_ h: UInt64) -> AnyObject {
|
||||
guard let p = UnsafeRawPointer(bitPattern: UInt(h)) else { fatalError("MODULE: Go passed nil for an object") }
|
||||
return Unmanaged<AnyObject>.fromOpaque(p).takeUnretainedValue()
|
||||
}
|
||||
|
||||
func _mygoObject<T>(_ h: UInt64) -> T {
|
||||
guard let v = _mygoAnyObject(h) as? T else { fatalError("MODULE: Go passed an object of the wrong type for \(T.self)") }
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoRelease(_ h: UInt64) {
|
||||
guard let p = UnsafeRawPointer(bitPattern: UInt(h)) else { return }
|
||||
Unmanaged<AnyObject>.fromOpaque(p).release()
|
||||
}
|
||||
|
||||
#if canImport(AppKit)
|
||||
/// The views of native UI's windows, which views of the module are, and
|
||||
/// the windows methods take: AppKit's on macOS, UIKit's on iOS, where a
|
||||
/// window is its view controller.
|
||||
public typealias NativeView = NSView
|
||||
public typealias NativeWindow = NSWindow
|
||||
|
||||
@MainActor func _mygoWindow(_ h: UInt64) -> NSWindow {
|
||||
let w: NSWindow = _mygoObject(h)
|
||||
return w
|
||||
}
|
||||
|
||||
/// Turns a rectangle of native UI, whose origin is the window's top-left,
|
||||
/// into the coordinates of the window's content view.
|
||||
@MainActor func _mygoFlip(_ r: CGRect, in w: NSWindow) -> CGRect {
|
||||
guard let v = w.contentView, !v.isFlipped else { return r }
|
||||
return CGRect(x: r.minX, y: v.bounds.height - r.minY - r.height, width: r.width, height: r.height)
|
||||
}
|
||||
#elseif canImport(UIKit)
|
||||
public typealias NativeView = UIView
|
||||
public typealias NativeWindow = UIViewController
|
||||
|
||||
/// The view controller of a window of the app, which the host keeps by its
|
||||
/// number: Go's handle of it.
|
||||
@MainActor func _mygoWindow(_ h: UInt64) -> UIViewController {
|
||||
guard let windows = NSClassFromString("MyGoWindows") as? NSObject.Type,
|
||||
let c = windows.perform(NSSelectorFromString("controller:"), with: NSNumber(value: h))?.takeUnretainedValue() as? UIViewController else {
|
||||
fatalError("MODULE: the window Go passed is gone")
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
/// UIKit's coordinates are native UI's: from the top-left.
|
||||
@MainActor func _mygoFlip(_ r: CGRect, in w: UIViewController) -> CGRect { r }
|
||||
#endif
|
||||
|
||||
final class _MygoTable<V>: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var values: [UInt64: V] = [:]
|
||||
func put(_ k: UInt64, _ v: V) { lock.lock(); values[k] = v; lock.unlock() }
|
||||
func get(_ k: UInt64) -> V? { lock.lock(); defer { lock.unlock() }; return values[k] }
|
||||
@discardableResult func remove(_ k: UInt64) -> V? { lock.lock(); defer { lock.unlock() }; return values.removeValue(forKey: k) }
|
||||
}
|
||||
|
||||
/// The tasks of asynchronous calls and streams, by their call, which Go
|
||||
/// cancels.
|
||||
final class _MygoTasks: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var tasks: [UInt64: Task<Void, Never>] = [:]
|
||||
private var done: Set<UInt64> = []
|
||||
private var canceled: Set<UInt64> = []
|
||||
|
||||
func put(_ call: UInt64, _ t: Task<Void, Never>) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if done.remove(call) != nil { return }
|
||||
if canceled.remove(call) != nil { t.cancel() }
|
||||
tasks[call] = t
|
||||
}
|
||||
|
||||
func finish(_ call: UInt64) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if tasks.removeValue(forKey: call) == nil { done.insert(call) }
|
||||
canceled.remove(call)
|
||||
}
|
||||
|
||||
func cancel(_ call: UInt64) {
|
||||
lock.lock()
|
||||
let t = tasks.removeValue(forKey: call)
|
||||
if t == nil, done.remove(call) == nil { canceled.insert(call) }
|
||||
lock.unlock()
|
||||
t?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
let _mygoTasks = _MygoTasks()
|
||||
let _mygoDemands = _MygoTable<AsyncStream<Void>.Continuation>()
|
||||
let _mygoConts = _MygoTable<CheckedContinuation<_MygoBlock, Never>>()
|
||||
|
||||
/// A block Go answered with, for a continuation.
|
||||
struct _MygoBlock: @unchecked Sendable {
|
||||
let p: UnsafeMutableRawPointer?
|
||||
}
|
||||
|
||||
private let _mygoIDLock = NSLock()
|
||||
nonisolated(unsafe) private var _mygoLastID: UInt64 = 0
|
||||
/// The module's index, from Go, in the high bits of every id, which makes
|
||||
/// the ids of continuations unique among modules.
|
||||
nonisolated(unsafe) var _mygoIDBase: UInt64 = 0
|
||||
|
||||
func _mygoNextID() -> UInt64 {
|
||||
_mygoIDLock.lock()
|
||||
defer { _mygoIDLock.unlock() }
|
||||
_mygoLastID += 1
|
||||
return _mygoIDBase | _mygoLastID
|
||||
}
|
||||
|
||||
func _mygoFinish(_ call: UInt64, _ body: (inout _MygoWriter) async throws -> Void) async {
|
||||
var w = _MygoWriter()
|
||||
var status: Int64 = 0
|
||||
do {
|
||||
try await body(&w)
|
||||
} catch {
|
||||
w.reset()
|
||||
_mygoWriteError(&w, error)
|
||||
status = 1
|
||||
}
|
||||
_mygoTasks.finish(call)
|
||||
_mygoSend(_mygoKindResult, call, status, w)
|
||||
w.free()
|
||||
}
|
||||
|
||||
func _mygoTask(_ call: UInt64, _ body: @escaping (inout _MygoWriter) async throws -> Void) {
|
||||
_mygoTasks.put(call, Task { await _mygoFinish(call, body) })
|
||||
}
|
||||
|
||||
func _mygoTaskMain(_ call: UInt64, _ body: @escaping @MainActor (inout _MygoWriter) async throws -> Void) {
|
||||
_mygoTasks.put(call, Task { @MainActor in await _mygoFinish(call, body) })
|
||||
}
|
||||
|
||||
func _mygoIterate<S: AsyncSequence & Sendable>(_ call: UInt64, _ s: S, _ demand: AsyncStream<Void>, _ enc: (inout _MygoWriter, S.Element) -> Void) async {
|
||||
var it = s.makeAsyncIterator()
|
||||
var lent: S.Element? = nil
|
||||
var w = _MygoWriter()
|
||||
for await _ in demand {
|
||||
// Go is done with what the previous value lent.
|
||||
(lent as? NativeBuffer)?.recycle()
|
||||
lent = nil
|
||||
w.reset()
|
||||
do {
|
||||
guard let v = try await it.next() else {
|
||||
_mygoSend(_mygoKindItem, call, 3, nil)
|
||||
break
|
||||
}
|
||||
lent = v
|
||||
enc(&w, v)
|
||||
_mygoSend(_mygoKindItem, call, 0, w)
|
||||
} catch {
|
||||
_mygoWriteError(&w, error)
|
||||
_mygoSend(_mygoKindItem, call, 1, w)
|
||||
break
|
||||
}
|
||||
}
|
||||
w.free()
|
||||
withExtendedLifetime(lent) {}
|
||||
_mygoDemands.remove(call)
|
||||
_mygoTasks.finish(call)
|
||||
}
|
||||
|
||||
func _mygoDemand(_ call: UInt64) -> AsyncStream<Void> {
|
||||
var cont: AsyncStream<Void>.Continuation!
|
||||
let demand = AsyncStream<Void>(bufferingPolicy: .unbounded) { cont = $0 }
|
||||
_mygoDemands.put(call, cont)
|
||||
return demand
|
||||
}
|
||||
|
||||
func _mygoStream<S: AsyncSequence & Sendable>(_ call: UInt64, _ make: @escaping () -> S, _ enc: @escaping (inout _MygoWriter, S.Element) -> Void) {
|
||||
let demand = _mygoDemand(call)
|
||||
_mygoTasks.put(call, Task { await _mygoIterate(call, make(), demand, enc) })
|
||||
}
|
||||
|
||||
func _mygoStreamMain<S: AsyncSequence & Sendable>(_ call: UInt64, _ make: @escaping @MainActor () -> S, _ enc: @escaping (inout _MygoWriter, S.Element) -> Void) {
|
||||
let demand = _mygoDemand(call)
|
||||
_mygoTasks.put(call, Task { @MainActor in await _mygoIterate(call, make(), demand, enc) })
|
||||
}
|
||||
|
||||
/// A Go function the implementation calls: a notification, or a question
|
||||
/// Go answers at once. Both take the writer of the arguments, and free it.
|
||||
final class _MygoGoFunc: @unchecked Sendable {
|
||||
let id: UInt64
|
||||
init(_ id: UInt64) { self.id = id }
|
||||
deinit { if id != 0 { _mygoSend(_mygoKindRelease, id, 0, nil) } }
|
||||
|
||||
func notify(_ w: _MygoWriter) {
|
||||
if id != 0 { _mygoSend(_mygoKindNotify, id, 0, w) }
|
||||
w.free()
|
||||
}
|
||||
|
||||
func ask<R>(_ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) throws -> R {
|
||||
defer { w.free() }
|
||||
guard id != 0 else { throw NativeError.closed }
|
||||
return try _mygoAnswer(_mygoSend(_mygoKindAsk, id, 0, w), read)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the method of a value of Go's that w names, with the arguments
|
||||
/// after it, and frees w.
|
||||
func _mygoInvoke<R>(_ id: UInt64, _ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) throws -> R {
|
||||
defer { w.free() }
|
||||
return try _mygoAnswer(_mygoSend(_mygoKindInvoke, id, 0, w), read)
|
||||
}
|
||||
|
||||
func _mygoInvokeAsync<R>(_ id: UInt64, _ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) async throws -> R {
|
||||
let cont = _mygoNextID()
|
||||
let b = await withTaskCancellationHandler {
|
||||
await withCheckedContinuation { (c: CheckedContinuation<_MygoBlock, Never>) in
|
||||
_mygoConts.put(cont, c)
|
||||
_mygoSend(_mygoKindInvokeAsync, id, Int64(bitPattern: cont), w)
|
||||
w.free()
|
||||
}
|
||||
} onCancel: {
|
||||
_mygoSend(_mygoKindCancel, cont, 0, nil)
|
||||
}
|
||||
return try _mygoAnswer(b.p, read)
|
||||
}
|
||||
`
|
||||
|
||||
// swiftNanos reads and writes time.Duration, for modules that use it:
|
||||
// Duration needs macOS 13.
|
||||
const swiftNanos = `
|
||||
@available(macOS 13, iOS 16, *)
|
||||
extension _MygoReader {
|
||||
/// Reads a time.Duration: nanoseconds.
|
||||
mutating func duration() throws -> Duration { .nanoseconds(try i64()) }
|
||||
}
|
||||
|
||||
@available(macOS 13, iOS 16, *)
|
||||
extension _MygoWriter {
|
||||
mutating func duration(_ d: Duration) {
|
||||
let c = d.components
|
||||
i64(c.seconds * 1_000_000_000 + c.attoseconds / 1_000_000_000)
|
||||
}
|
||||
}
|
||||
`
|
||||
+615
@@ -0,0 +1,615 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SwiftFile is the name of the generated Swift file of a module.
|
||||
func SwiftFile(m *Module) string { return m.Name + ".mygo.swift" }
|
||||
|
||||
const swiftHeader = "// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.\n"
|
||||
|
||||
// GenerateSwift writes the Swift side: the protocols the implementation
|
||||
// conforms to, the structs and enums of the Go side, the errors, and the
|
||||
// functions Go calls.
|
||||
func GenerateSwift(m *Module) []byte {
|
||||
var b bytes.Buffer
|
||||
g := &swiftGen{m: m, b: &b, w: newWire(m)}
|
||||
g.p("%s// %s\n//\n// The declarations of package %s, which the implementation conforms to,\n// and the functions Go calls. See docs/native-modules.md.\n\n", swiftHeader, SourceLine(m.Hash), m.Package)
|
||||
g.p("import Foundation\n#if canImport(IOSurface)\nimport CoreVideo\nimport IOSurface\n#endif\n#if canImport(AppKit)\nimport AppKit\n#elseif canImport(UIKit)\nimport UIKit\n#endif\n")
|
||||
imports := map[string]bool{}
|
||||
for _, d := range m.Deps {
|
||||
imports[d.Name] = true
|
||||
}
|
||||
// The modules of the types of the modules' structs, which the
|
||||
// functions that read and write them name.
|
||||
for _, r := range g.w.types {
|
||||
if mod := r.module(); mod != m {
|
||||
imports[mod.Name] = true
|
||||
}
|
||||
}
|
||||
for _, name := range slices.Sorted(maps.Keys(imports)) {
|
||||
g.p("import %s\n", name)
|
||||
}
|
||||
g.p("\n// MARK: - Declarations\n")
|
||||
for _, it := range m.Interfaces {
|
||||
g.protocol(it)
|
||||
}
|
||||
for _, s := range m.Structs {
|
||||
g.structDecl(s)
|
||||
}
|
||||
for _, e := range m.Enums {
|
||||
g.enumDecl(e)
|
||||
}
|
||||
g.errorsDecl()
|
||||
g.p("\n// MARK: - What Go calls\n")
|
||||
g.p("\n@_cdecl(%q)\npublic func _mygo_init(_ cb: _MygoCallback, _ idBase: UInt64, _ malloc: UnsafeRawPointer?, _ free: UnsafeRawPointer?) {\n _mygoCallback = cb\n _mygoIDBase = idBase\n}\n", g.sym("init"))
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
g.goProxy(it)
|
||||
continue
|
||||
}
|
||||
if it.Entry {
|
||||
g.factory(it)
|
||||
}
|
||||
for _, m := range it.Methods {
|
||||
if !m.Close {
|
||||
g.entry(it, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
g.common()
|
||||
g.p("\n// MARK: - Encoding\n")
|
||||
g.w.swiftFuncs(g.p)
|
||||
g.p("%s", strings.ReplaceAll(swiftSupport, "MODULE", m.Name))
|
||||
if usesDuration(m) {
|
||||
g.p("%s", swiftNanos)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
type swiftGen struct {
|
||||
m *Module
|
||||
b *bytes.Buffer
|
||||
w *wire
|
||||
}
|
||||
|
||||
func (g *swiftGen) p(format string, args ...any) { fmt.Fprintf(g.b, format, args...) }
|
||||
|
||||
func (g *swiftGen) sym(name string) string { return "mygo_" + g.m.Package + "_" + name }
|
||||
|
||||
func usesDuration(m *Module) bool {
|
||||
var has func(t *Type) bool
|
||||
has = func(t *Type) bool {
|
||||
if t == nil {
|
||||
return false
|
||||
}
|
||||
if t.Kind == Duration || has(t.Elem) || has(t.Result) {
|
||||
return true
|
||||
}
|
||||
for _, p := range t.Params {
|
||||
if has(p.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, it := range m.Interfaces {
|
||||
for _, me := range it.Methods {
|
||||
if has(me.Result) {
|
||||
return true
|
||||
}
|
||||
for _, p := range me.Params {
|
||||
if has(p.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, st := range m.Structs {
|
||||
for _, f := range st.Fields {
|
||||
if has(f.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func docComment(doc, indent string) string {
|
||||
if doc == "" {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
for line := range strings.Lines(doc) {
|
||||
line = strings.TrimRight(line, "\n")
|
||||
if line == "" {
|
||||
b.WriteString(indent + "///\n")
|
||||
} else {
|
||||
b.WriteString(indent + "/// " + line + "\n")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// swiftType is the Swift spelling of a type.
|
||||
func swiftType(t *Type) string {
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return "Bool"
|
||||
case Int:
|
||||
u := ""
|
||||
if t.Unsigned {
|
||||
u = "U"
|
||||
}
|
||||
switch t.Go {
|
||||
case "int", "uint":
|
||||
return u + "Int"
|
||||
}
|
||||
return fmt.Sprintf("%sInt%d", u, t.Bits)
|
||||
case Float:
|
||||
if t.Bits == 32 {
|
||||
return "Float"
|
||||
}
|
||||
return "Double"
|
||||
case String:
|
||||
return "String"
|
||||
case Bytes:
|
||||
return "Data"
|
||||
case Time:
|
||||
return "Date"
|
||||
case Duration:
|
||||
return "Duration"
|
||||
case Slice:
|
||||
return "[" + swiftType(t.Elem) + "]"
|
||||
case Map:
|
||||
return "[String: " + swiftType(t.Elem) + "]"
|
||||
case Pointer:
|
||||
return swiftType(t.Elem) + "?"
|
||||
case StructType, EnumType:
|
||||
return qualified(t)
|
||||
case InterfaceType:
|
||||
return "any " + qualified(t)
|
||||
case Window:
|
||||
return "NativeWindow"
|
||||
case View:
|
||||
return "NativeView"
|
||||
case Rect:
|
||||
return "CGRect"
|
||||
case Buffer:
|
||||
return "NativeBuffer"
|
||||
case Texture:
|
||||
return "NativeTexture"
|
||||
case Func:
|
||||
var ps []string
|
||||
for _, p := range t.Params {
|
||||
ps = append(ps, swiftType(p.Type))
|
||||
}
|
||||
s := "@escaping @Sendable (" + strings.Join(ps, ", ") + ")"
|
||||
if t.Err {
|
||||
s += " throws"
|
||||
}
|
||||
if t.Result != nil {
|
||||
return s + " -> " + swiftType(t.Result)
|
||||
}
|
||||
return s + " -> Void"
|
||||
}
|
||||
return "Never"
|
||||
}
|
||||
|
||||
// qualified is the Swift name of a type of the module, or of another
|
||||
// native module's, after its Swift module.
|
||||
func qualified(t *Type) string {
|
||||
if t.Pkg != nil {
|
||||
return t.Pkg.Name + "." + t.Name
|
||||
}
|
||||
return t.Name
|
||||
}
|
||||
|
||||
// nilDefault is what a Go nil decodes to, for the types Go encodes as
|
||||
// null when empty.
|
||||
func nilDefault(t *Type) string {
|
||||
switch t.Kind {
|
||||
case Slice, Bytes:
|
||||
if t.Kind == Bytes {
|
||||
return "Data()"
|
||||
}
|
||||
return "[]"
|
||||
case Map:
|
||||
return "[:]"
|
||||
case Pointer:
|
||||
return "nil"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func methodName(m *Method) string { return swiftIdent(lowerCamel(m.Name)) }
|
||||
|
||||
func (g *swiftGen) requirement(it *Interface, m *Method) string {
|
||||
var ps []string
|
||||
for _, p := range m.Params {
|
||||
ps = append(ps, swiftIdent(p.Name)+": "+swiftType(p.Type))
|
||||
}
|
||||
s := "func " + methodName(m) + "(" + strings.Join(ps, ", ") + ")"
|
||||
if m.MainThread && !it.MainThread {
|
||||
s = "@MainActor " + s
|
||||
}
|
||||
switch {
|
||||
case m.Stream == 1:
|
||||
return s + " -> AsyncStream<" + swiftType(m.Result) + ">"
|
||||
case m.Stream == 2:
|
||||
return s + " -> AsyncThrowingStream<" + swiftType(m.Result) + ", Error>"
|
||||
case m.Closer:
|
||||
return s + " -> any Closer"
|
||||
}
|
||||
if m.Ctx {
|
||||
s += " async"
|
||||
}
|
||||
if m.Err {
|
||||
s += " throws"
|
||||
}
|
||||
if m.Result != nil {
|
||||
s += " -> " + swiftType(m.Result)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (g *swiftGen) protocol(it *Interface) {
|
||||
g.p("\n%s", docComment(it.Doc, ""))
|
||||
inherits := "AnyObject"
|
||||
if it.View {
|
||||
inherits = "NativeView"
|
||||
}
|
||||
if it.Closer {
|
||||
inherits += ", Closer"
|
||||
}
|
||||
if it.ByGo {
|
||||
inherits += ", Sendable"
|
||||
}
|
||||
attr := ""
|
||||
if it.MainThread {
|
||||
attr = "@MainActor "
|
||||
}
|
||||
g.p("%spublic protocol %s: %s {\n", attr, it.Name, inherits)
|
||||
for _, m := range it.Methods {
|
||||
if m.Close {
|
||||
continue
|
||||
}
|
||||
g.p("%s %s\n", docComment(m.Doc, " "), g.requirement(it, m))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
func hashable(t *Type) bool {
|
||||
switch t.Kind {
|
||||
case Rect:
|
||||
return false
|
||||
case Slice, Map, Pointer:
|
||||
return hashable(t.Elem)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (g *swiftGen) structDecl(s *Struct) {
|
||||
conf := "Sendable"
|
||||
h := true
|
||||
for _, f := range s.Fields {
|
||||
h = h && hashable(f.Type)
|
||||
}
|
||||
if h {
|
||||
conf = "Sendable, Hashable"
|
||||
}
|
||||
g.p("\n%spublic struct %s: %s {\n", docComment(s.Doc, ""), s.Name, conf)
|
||||
var params, assigns []string
|
||||
for _, f := range s.Fields {
|
||||
name := swiftIdent(lowerCamel(f.Name))
|
||||
def := nilDefault(f.Type)
|
||||
g.p("%s public var %s: %s\n", docComment(f.Doc, " "), name, swiftType(f.Type))
|
||||
p := name + ": " + swiftType(f.Type)
|
||||
if def != "" {
|
||||
p += " = " + def
|
||||
}
|
||||
params = append(params, p)
|
||||
assigns = append(assigns, " self."+name+" = "+name)
|
||||
}
|
||||
g.p("\n public init(%s) {\n%s\n }\n}\n", strings.Join(params, ", "), strings.Join(assigns, "\n"))
|
||||
}
|
||||
|
||||
func (g *swiftGen) enumDecl(e *Enum) {
|
||||
raw := "String"
|
||||
if !e.String {
|
||||
raw = swiftType(basics[e.Basic])
|
||||
}
|
||||
g.p("\n%spublic enum %s: %s, Sendable, Hashable, CaseIterable {\n", docComment(e.Doc, ""), e.Name, raw)
|
||||
for _, c := range e.Cases {
|
||||
g.p("%s case %s = %s\n", docComment(c.Doc, " "), swiftIdent(lowerCamel(c.Name)), c.Value)
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
func (g *swiftGen) errorsDecl() {
|
||||
if len(g.m.Errors) == 0 {
|
||||
g.p("\n/// The errors package %s declares, with native.NewError: none.\npublic struct %sError: Error, Sendable, RawRepresentable {\n public let rawValue: String\n public init?(rawValue: String) { return nil }\n}\n", g.m.Package, g.m.Name)
|
||||
return
|
||||
}
|
||||
g.p("\n/// The errors package %s declares, with native.NewError. Go compares\n/// them with errors.Is.\npublic enum %sError: String, Error, Sendable, CaseIterable {\n", g.m.Package, g.m.Name)
|
||||
for _, e := range g.m.Errors {
|
||||
g.p("%s case %s = %q\n", docComment(e.Doc, " "), e.SwiftName(), e.Code)
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
func (g *swiftGen) factory(it *Interface) {
|
||||
run, call := "_mygoRun", "_mygoCall"
|
||||
if it.MainThread {
|
||||
run, call = "_mygoRunMain", "_mygoCallMain"
|
||||
}
|
||||
g.p("\n@_cdecl(%q)\npublic func _mygo_new_%s(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {\n", g.sym("new_"+it.Name), it.Name)
|
||||
g.p(" %s { _w in\n let v: any %s = try %s(make%s)\n _w.u64(_mygoRetain(v))\n }\n}\n", run, it.Name, call, it.Name)
|
||||
}
|
||||
|
||||
// readArgs returns the statements that read a method's arguments from the
|
||||
// reader _a, as _p0, _p1 …, and the expressions the implementation takes
|
||||
// them as.
|
||||
func (g *swiftGen) readArgs(m *Method) (stmts []string, vals []string) {
|
||||
if len(m.Params) > 0 {
|
||||
stmts = append(stmts, "var _a = _MygoReader(args, n)")
|
||||
}
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("_p%d", i)
|
||||
stmts = append(stmts, "let "+v+" = "+g.w.swiftRead(ref{p.Type, g.m}, "_a"))
|
||||
switch p.Type.Kind {
|
||||
case InterfaceType:
|
||||
if p.Type.Iface.ByGo {
|
||||
v = fmt.Sprintf("_Go%s(%s)", p.Type.Iface.Name, v)
|
||||
} else {
|
||||
v = fmt.Sprintf("(_mygoObject(%s) as any %s)", v, qualified(p.Type))
|
||||
}
|
||||
case Window:
|
||||
v = fmt.Sprintf("_mygoWindow(%s)", v)
|
||||
case View:
|
||||
v = fmt.Sprintf("(_mygoObject(%s) as NativeView)", v)
|
||||
case Rect:
|
||||
for j, q := range m.Params {
|
||||
if q.Type.Kind == Window {
|
||||
v = fmt.Sprintf("_mygoFlip(%s, in: _mygoWindow(_p%d))", v, j)
|
||||
break
|
||||
}
|
||||
}
|
||||
case Func:
|
||||
f := fmt.Sprintf("_f%d", i)
|
||||
stmts = append(stmts, "let "+f+": "+strings.TrimPrefix(swiftType(p.Type), "@escaping ")+" = "+g.closure(v, p.Type))
|
||||
v = f
|
||||
}
|
||||
vals = append(vals, swiftIdent(p.Name)+": "+v)
|
||||
}
|
||||
return stmts, vals
|
||||
}
|
||||
|
||||
// closure is a Swift closure calling the Go function whose handle is h.
|
||||
func (g *swiftGen) closure(h string, t *Type) string {
|
||||
var names []string
|
||||
var body []string
|
||||
decl := "let"
|
||||
if len(t.Params) > 0 {
|
||||
decl = "var"
|
||||
}
|
||||
body = append(body, decl+" _cw = _MygoWriter()")
|
||||
for i, p := range t.Params {
|
||||
n := fmt.Sprintf("q%d", i)
|
||||
names = append(names, n)
|
||||
body = append(body, g.w.swiftWrite(ref{p.Type, g.m}, "_cw", n))
|
||||
}
|
||||
switch {
|
||||
case t.Result == nil && !t.Err:
|
||||
body = append(body, "f.notify(_cw)")
|
||||
case t.Result == nil:
|
||||
body = append(body, "try f.ask(_cw) { _ in () }")
|
||||
case t.Err:
|
||||
body = append(body, "return try f.ask(_cw) { _r in "+g.w.swiftRead(ref{t.Result, g.m}, "_r")+" }")
|
||||
default:
|
||||
body = append(body, "return _mygoMust { try f.ask(_cw) { _r in "+g.w.swiftRead(ref{t.Result, g.m}, "_r")+" } }")
|
||||
}
|
||||
params := ""
|
||||
if len(names) > 0 {
|
||||
params = " " + strings.Join(names, ", ") + " in"
|
||||
} else {
|
||||
params = " in"
|
||||
}
|
||||
return "{ [f = _MygoGoFunc(" + h + ")]" + params + "\n " + strings.Join(body, "\n ") + "\n }"
|
||||
}
|
||||
|
||||
// writeResult is the statement that writes the result r of a method to
|
||||
// the writer _w.
|
||||
func (g *swiftGen) writeResult(t *Type) string {
|
||||
return g.w.swiftWrite(ref{t, g.m}, "_w", "_r")
|
||||
}
|
||||
|
||||
func (g *swiftGen) entry(it *Interface, m *Method) {
|
||||
name := it.Name + "_" + m.Name
|
||||
if direct(m) {
|
||||
g.direct(it, m)
|
||||
return
|
||||
}
|
||||
g.p("\n@_cdecl(%q)\npublic func _mygo_%s(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {\n", g.sym(name), name)
|
||||
stmts, vals := g.readArgs(m)
|
||||
callExpr := "_o." + methodName(m) + "(" + strings.Join(vals, ", ") + ")"
|
||||
prelude := fmt.Sprintf(" let _o: any %s = _mygoObject(obj)\n", it.Name)
|
||||
for _, s := range stmts {
|
||||
prelude += " " + s + "\n"
|
||||
}
|
||||
switch {
|
||||
case m.Stream != 0:
|
||||
enc := "{ _w, _r in " + g.writeResult(m.Result) + " }"
|
||||
fn := "_mygoStream"
|
||||
if m.MainThread {
|
||||
fn = "_mygoStreamMain"
|
||||
}
|
||||
g.p(" _mygoStart {\n%s %s(call, { %s }, %s)\n }\n}\n", prelude, fn, callExpr, enc)
|
||||
return
|
||||
case m.Async():
|
||||
tryAwait := "await "
|
||||
if m.Err {
|
||||
tryAwait = "try await "
|
||||
}
|
||||
w := "_"
|
||||
body := tryAwait + callExpr
|
||||
if m.Result != nil {
|
||||
w = "_w"
|
||||
body = "let _r = " + tryAwait + callExpr + "\n " + g.writeResult(m.Result)
|
||||
}
|
||||
fn := "_mygoTask"
|
||||
if m.MainThread {
|
||||
fn = "_mygoTaskMain"
|
||||
}
|
||||
g.p(" _mygoStart {\n%s %s(call) { %s in\n %s\n }\n }\n}\n", prelude, fn, w, body)
|
||||
return
|
||||
}
|
||||
run := "_mygoRun"
|
||||
if m.MainThread {
|
||||
run = "_mygoRunMain"
|
||||
}
|
||||
try := ""
|
||||
if m.Err {
|
||||
try = "try "
|
||||
}
|
||||
w := "_w"
|
||||
if m.Result == nil && !m.Closer {
|
||||
w = "_"
|
||||
}
|
||||
g.p(" %s { %s in\n%s", run, w, prelude)
|
||||
switch {
|
||||
case m.Closer:
|
||||
g.p(" let _r = %s\n _w.u64(_mygoRetain(_r))\n", callExpr)
|
||||
case m.Result != nil:
|
||||
g.p(" let _r = %s%s\n %s\n", try, callExpr, g.writeResult(m.Result))
|
||||
default:
|
||||
g.p(" %s%s\n", try, callExpr)
|
||||
}
|
||||
g.p(" }\n}\n")
|
||||
}
|
||||
|
||||
// direct writes the C function of a method of numbers, which takes and
|
||||
// returns them as registers: integers as their bits, floats as those of
|
||||
// a Double, bools as 0 or 1.
|
||||
func (g *swiftGen) direct(it *Interface, m *Method) {
|
||||
name := it.Name + "_" + m.Name + "_direct"
|
||||
var params, vals []string
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("_p%d", i)
|
||||
params = append(params, "_ "+v+": UInt64")
|
||||
switch {
|
||||
case p.Type.Kind == Bool:
|
||||
v += " != 0"
|
||||
case p.Type.Kind == Float && p.Type.Bits == 32:
|
||||
v = "Float(Double(bitPattern: " + v + "))"
|
||||
case p.Type.Kind == Float:
|
||||
v = "Double(bitPattern: " + v + ")"
|
||||
default:
|
||||
v = swiftType(p.Type) + "(truncatingIfNeeded: " + v + ")"
|
||||
}
|
||||
vals = append(vals, swiftIdent(p.Name)+": "+v)
|
||||
}
|
||||
g.p("\n@_cdecl(%q)\npublic func _mygo_%s(_ obj: UInt64%s) -> UInt64 {\n", g.sym(name), name, prefixComma(params))
|
||||
g.p(" let _o: any %s = _mygoObject(obj)\n", it.Name)
|
||||
call := "_o." + methodName(m) + "(" + strings.Join(vals, ", ") + ")"
|
||||
t := m.Result
|
||||
switch {
|
||||
case t == nil:
|
||||
g.p(" %s\n return 0\n", call)
|
||||
case t.Kind == Bool:
|
||||
g.p(" return %s ? 1 : 0\n", call)
|
||||
case t.Kind == Float && t.Bits == 32:
|
||||
g.p(" return Double(%s).bitPattern\n", call)
|
||||
case t.Kind == Float:
|
||||
g.p(" return %s.bitPattern\n", call)
|
||||
default:
|
||||
g.p(" return UInt64(truncatingIfNeeded: %s)\n", call)
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
// goProxy writes the class through which the implementation calls a value
|
||||
// of an interface Go implements.
|
||||
func (g *swiftGen) goProxy(it *Interface) {
|
||||
g.p("\n/// Calls a Go value implementing %s.\nfinal class _Go%s: %s, @unchecked Sendable {\n // Named as no parameter of the interface's may be.\n let _mygoID: UInt64\n init(_ id: UInt64) {\n if id == 0 { fatalError(\"%s: Go passed nil for %s\") }\n _mygoID = id\n }\n deinit { _mygoSend(_mygoKindRelease, _mygoID, 0, nil) }\n", it.Name, it.Name, it.Name, g.m.Name, it.Name)
|
||||
for i, m := range it.Methods {
|
||||
lines := []string{"var _w = _MygoWriter()", fmt.Sprintf("_w.i64(%d)", i)}
|
||||
for _, p := range m.Params {
|
||||
lines = append(lines, g.w.swiftWrite(ref{p.Type, g.m}, "_w", swiftIdent(p.Name)))
|
||||
}
|
||||
read := "{ _ in () }"
|
||||
if m.Result != nil {
|
||||
read = "{ _r in " + g.w.swiftRead(ref{m.Result, g.m}, "_r") + " }"
|
||||
}
|
||||
var call string
|
||||
if m.Ctx {
|
||||
call = "try await _mygoInvokeAsync(_mygoID, _w) " + read
|
||||
} else {
|
||||
call = "try _mygoInvoke(_mygoID, _w) " + read
|
||||
}
|
||||
var body string
|
||||
switch {
|
||||
case m.Result == nil && m.Err:
|
||||
body = call
|
||||
case m.Result == nil && m.Ctx:
|
||||
body = "_ = try? " + strings.TrimPrefix(call, "try ")
|
||||
case m.Result == nil:
|
||||
body = "_mygoMust { " + call + " }"
|
||||
case m.Err:
|
||||
body = "return " + call
|
||||
case m.Ctx:
|
||||
body = "return (try? " + strings.TrimPrefix(call, "try ") + ") ?? _mygoFail()"
|
||||
default:
|
||||
body = "return _mygoMust { " + call + " }"
|
||||
}
|
||||
lines = append(lines, body)
|
||||
g.p(" %s {\n %s\n }\n", g.requirement(it, m), strings.Join(lines, "\n "))
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
func (g *swiftGen) common() {
|
||||
g.p(`
|
||||
@_cdecl(%q)
|
||||
public func _mygo_close(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { _ in
|
||||
let o = _mygoAnyObject(obj)
|
||||
if let c = o as? any Closer { try c.close() }
|
||||
#if canImport(AppKit) || canImport(UIKit)
|
||||
// A view closed leaves the windows showing it; Go closes views on
|
||||
// the main thread.
|
||||
if let v = o as? NativeView { MainActor.assumeIsolated { v.removeFromSuperview() } }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl(%q)
|
||||
public func _mygo_release(_ obj: UInt64) {
|
||||
_mygoRelease(obj)
|
||||
}
|
||||
|
||||
@_cdecl(%q)
|
||||
public func _mygo_cancel(_ call: UInt64) {
|
||||
_mygoTasks.cancel(call)
|
||||
}
|
||||
|
||||
@_cdecl(%q)
|
||||
public func _mygo_next(_ call: UInt64) {
|
||||
_mygoDemands.get(call)?.yield(())
|
||||
}
|
||||
|
||||
@_cdecl(%q)
|
||||
public func _mygo_resume(_ cont: UInt64, _ block: UnsafeMutableRawPointer?) {
|
||||
if let c = _mygoConts.remove(cont) {
|
||||
c.resume(returning: _MygoBlock(p: block))
|
||||
} else {
|
||||
free(block)
|
||||
}
|
||||
}
|
||||
`, g.sym("close"), g.sym("release"), g.sym("cancel"), g.sym("next"), g.sym("resume"))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Package clash names its parameters as the generated code names its own
|
||||
// identifiers and packages, which must not clash.
|
||||
package clash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"iter"
|
||||
|
||||
"github.com/egoist/mygo/native"
|
||||
)
|
||||
|
||||
// A takes parameters named as the generated code's identifiers.
|
||||
//
|
||||
//mygo:native
|
||||
type A interface {
|
||||
M(x, err, r, h, a, m, v, o, id, ctx, p0, f0, g0 int) error
|
||||
P(native, runtime, context, fmt, filepath, iter, io int) (int, error)
|
||||
S(ctx context.Context, x int, a func(err string, x int)) iter.Seq2[int, error]
|
||||
C(err int, x func(r int) (int, error)) io.Closer
|
||||
B(native *native.Buffer, x int) (int, error)
|
||||
G(ctx context.Context, id G, x int) error
|
||||
D(ctx context.Context, h B) (B, error)
|
||||
}
|
||||
|
||||
// B is an object the platform returns.
|
||||
type B interface {
|
||||
N(x, err int) int
|
||||
}
|
||||
|
||||
// G is an interface Go implements.
|
||||
type G interface {
|
||||
N(ctx context.Context, id int, self string) (int, error)
|
||||
Q(x, err, a, m, v int) string
|
||||
}
|
||||
+451
@@ -0,0 +1,451 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The binary encoding values cross in (see package native) is written and
|
||||
// read by functions both sides generate for each composite type a module
|
||||
// uses: slices, maps, pointers, structs and enums, named after the type
|
||||
// (wireName), in Go _enc_<name> and _dec_<name>, in Swift
|
||||
// _mygoWrite_<name> and _mygoRead_<name>.
|
||||
|
||||
// ref is a type as the module owner declares it, whose Pkg is relative to
|
||||
// owner: a field of another module's struct names that module's types
|
||||
// without one.
|
||||
type ref struct {
|
||||
t *Type
|
||||
owner *Module
|
||||
}
|
||||
|
||||
func (r ref) elem() ref { return ref{r.t.Elem, r.owner} }
|
||||
|
||||
// module returns the module a struct or an enum is of.
|
||||
func (r ref) module() *Module {
|
||||
if r.t.Pkg != nil {
|
||||
return r.t.Pkg
|
||||
}
|
||||
return r.owner
|
||||
}
|
||||
|
||||
func (m *Module) structNamed(name string) *Struct {
|
||||
for _, s := range m.Structs {
|
||||
if s.Name == name {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Module) enumNamed(name string) *Enum {
|
||||
for _, e := range m.Enums {
|
||||
if e.Name == name {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func composite(t *Type) bool {
|
||||
switch t.Kind {
|
||||
case Slice, Map, Pointer, StructType, EnumType:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// wire is what a module's generated code encodes: its composite types,
|
||||
// and the modules it names that it does not import itself.
|
||||
type wire struct {
|
||||
m *Module
|
||||
types map[string]ref
|
||||
// extra are the modules of types the module uses through another
|
||||
// module's structs, by import path, which it imports too.
|
||||
extra map[string]*Module
|
||||
}
|
||||
|
||||
// newWire collects the composite types the methods of m cross.
|
||||
func newWire(m *Module) *wire {
|
||||
w := &wire{m: m, types: map[string]ref{}, extra: map[string]*Module{}}
|
||||
var add func(t *Type)
|
||||
add = func(t *Type) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
w.add(ref{t, m})
|
||||
add(t.Result)
|
||||
for _, p := range t.Params {
|
||||
add(p.Type)
|
||||
}
|
||||
}
|
||||
for _, it := range m.Interfaces {
|
||||
for _, me := range it.Methods {
|
||||
add(me.Result)
|
||||
for _, p := range me.Params {
|
||||
add(p.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *wire) add(r ref) {
|
||||
if !composite(r.t) {
|
||||
return
|
||||
}
|
||||
n := w.name(r)
|
||||
if _, ok := w.types[n]; ok {
|
||||
return
|
||||
}
|
||||
w.types[n] = r
|
||||
switch r.t.Kind {
|
||||
case Slice, Map, Pointer:
|
||||
w.add(r.elem())
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
for _, f := range mod.structNamed(r.t.Name).Fields {
|
||||
w.add(ref{f.Type, mod})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// names returns the names of the composite types, sorted.
|
||||
func (w *wire) names() []string { return slices.Sorted(maps.Keys(w.types)) }
|
||||
|
||||
// name is the name of a type in the functions that encode it.
|
||||
func (w *wire) name(r ref) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Slice:
|
||||
return "slice_" + w.name(r.elem())
|
||||
case Map:
|
||||
return "map_" + w.name(r.elem())
|
||||
case Pointer:
|
||||
return "ptr_" + w.name(r.elem())
|
||||
case StructType, EnumType:
|
||||
if mod := r.module(); mod != w.m {
|
||||
return mod.Name + "_" + t.Name
|
||||
}
|
||||
return t.Name
|
||||
case Bytes:
|
||||
return "bytes"
|
||||
case Time:
|
||||
return "time"
|
||||
case Duration:
|
||||
return "duration"
|
||||
case Rect:
|
||||
return "rect"
|
||||
case Buffer:
|
||||
return "buffer"
|
||||
case Texture:
|
||||
return "texture"
|
||||
}
|
||||
return t.Go
|
||||
}
|
||||
|
||||
// qual returns the name the generated Go imports the module mod under.
|
||||
func (w *wire) qual(mod *Module) string {
|
||||
for path, d := range w.m.Deps {
|
||||
if d == mod {
|
||||
return w.m.Quals[path]
|
||||
}
|
||||
}
|
||||
// A module of a module it uses.
|
||||
var find func(m *Module, seen map[*Module]bool) string
|
||||
find = func(m *Module, seen map[*Module]bool) string {
|
||||
if seen[m] {
|
||||
return ""
|
||||
}
|
||||
seen[m] = true
|
||||
for path, d := range m.Deps {
|
||||
if d == mod {
|
||||
return path
|
||||
}
|
||||
if p := find(d, seen); p != "" {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if path := find(w.m, map[*Module]bool{}); path != "" {
|
||||
w.extra[path] = mod
|
||||
}
|
||||
return "_" + mod.Package
|
||||
}
|
||||
|
||||
// goType is the Go spelling of a type in the module's generated code.
|
||||
func (w *wire) goType(r ref) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Slice:
|
||||
return "[]" + w.goType(r.elem())
|
||||
case Map:
|
||||
return "map[string]" + w.goType(r.elem())
|
||||
case Pointer:
|
||||
return "*" + w.goType(r.elem())
|
||||
case StructType, EnumType:
|
||||
if mod := r.module(); mod != w.m {
|
||||
return w.qual(mod) + "." + t.Name
|
||||
}
|
||||
return t.Name
|
||||
}
|
||||
return t.Go
|
||||
}
|
||||
|
||||
// swiftType is the Swift spelling of a type in the module's generated
|
||||
// code.
|
||||
func (w *wire) swiftType(r ref) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Slice:
|
||||
return "[" + w.swiftType(r.elem()) + "]"
|
||||
case Map:
|
||||
return "[String: " + w.swiftType(r.elem()) + "]"
|
||||
case Pointer:
|
||||
return w.swiftType(r.elem()) + "?"
|
||||
case StructType, EnumType:
|
||||
if mod := r.module(); mod != w.m {
|
||||
return mod.Name + "." + t.Name
|
||||
}
|
||||
return t.Name
|
||||
}
|
||||
return swiftType(t)
|
||||
}
|
||||
|
||||
// goEnc is the Go statement that writes v, of type r, to the encoder _e.
|
||||
func (w *wire) goEnc(r ref, v string) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return "_e.Bool(" + v + ")"
|
||||
case Int:
|
||||
return "_e.Int(int64(" + v + "))"
|
||||
case Float:
|
||||
return "_e.Float(float64(" + v + "))"
|
||||
case String:
|
||||
return "_e.String(" + v + ")"
|
||||
case Bytes:
|
||||
return "_e.Bytes(" + v + ")"
|
||||
case Time:
|
||||
return "_e.Time(" + v + ")"
|
||||
case Duration:
|
||||
return "_e.Duration(" + v + ")"
|
||||
case Rect:
|
||||
return fmt.Sprintf("_e.Rect(%s.X, %s.Y, %s.W, %s.H)", v, v, v, v)
|
||||
case Buffer:
|
||||
return "_e.Buffer(" + v + ")"
|
||||
case Texture:
|
||||
return "_e.Texture(" + v + ")"
|
||||
case InterfaceType, View:
|
||||
return "_e.Uint(_native.HandleOf(" + v + "))"
|
||||
case Window:
|
||||
return "_e.Uint(_native.WindowHandle(" + v + "))"
|
||||
}
|
||||
return "_enc_" + w.name(r) + "(_e, " + v + ")"
|
||||
}
|
||||
|
||||
// goDec is the Go expression that reads a value of type r from the
|
||||
// decoder _d.
|
||||
func (w *wire) goDec(r ref) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return "_d.Bool()"
|
||||
case Int:
|
||||
return r.t.Go + "(_d.Int())"
|
||||
case Float:
|
||||
return r.t.Go + "(_d.Float())"
|
||||
case String:
|
||||
return "_d.String()"
|
||||
case Bytes:
|
||||
return "_d.Bytes()"
|
||||
case Time:
|
||||
return "_d.Time()"
|
||||
case Duration:
|
||||
return "_d.Duration()"
|
||||
case Rect:
|
||||
return "ui.Rect{X: float32(_d.Float()), Y: float32(_d.Float()), W: float32(_d.Float()), H: float32(_d.Float())}"
|
||||
case Buffer:
|
||||
return "_d.Buffer()"
|
||||
case InterfaceType, Window, View, Func, Texture:
|
||||
return "_d.Uint()"
|
||||
}
|
||||
return "_dec_" + w.name(r) + "(_d)"
|
||||
}
|
||||
|
||||
// goFuncs writes the Go functions that encode and decode the composite
|
||||
// types.
|
||||
func (w *wire) goFuncs(p func(format string, args ...any)) {
|
||||
for _, name := range w.names() {
|
||||
r := w.types[name]
|
||||
T := w.goType(r)
|
||||
var enc, dec string
|
||||
switch r.t.Kind {
|
||||
case Slice:
|
||||
enc = fmt.Sprintf("_e.Len(len(_v))\nfor _, _x := range _v {\n%s\n}", w.goEnc(r.elem(), "_x"))
|
||||
dec = fmt.Sprintf("_n := _d.Len()\nif _n == 0 {\nreturn nil\n}\n_v := make(%s, _n)\nfor _i := range _v {\n_v[_i] = %s\n}\nreturn _v", T, w.goDec(r.elem()))
|
||||
case Map:
|
||||
enc = fmt.Sprintf("_e.Len(len(_v))\nfor _k, _x := range _v {\n_e.String(_k)\n%s\n}", w.goEnc(r.elem(), "_x"))
|
||||
dec = fmt.Sprintf("_n := _d.Len()\nif _n == 0 {\nreturn nil\n}\n_v := make(%s, _n)\nfor range _n {\n_k := _d.String()\n_v[_k] = %s\n}\nreturn _v", T, w.goDec(r.elem()))
|
||||
case Pointer:
|
||||
enc = fmt.Sprintf("if _v == nil {\n_e.Bool(false)\nreturn\n}\n_e.Bool(true)\n%s", w.goEnc(r.elem(), "*_v"))
|
||||
dec = fmt.Sprintf("if !_d.Bool() {\nreturn nil\n}\n_x := %s\nreturn &_x", w.goDec(r.elem()))
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
s := mod.structNamed(r.t.Name)
|
||||
if len(s.Fields) == 0 {
|
||||
// Every value takes a byte at least: see Decoder.Len.
|
||||
enc, dec = "_e.Bool(false)", "_d.Bool()\nreturn "+T+"{}"
|
||||
break
|
||||
}
|
||||
var es, ds []string
|
||||
for _, f := range s.Fields {
|
||||
fr := ref{f.Type, mod}
|
||||
es = append(es, w.goEnc(fr, "_v."+f.Name))
|
||||
ds = append(ds, f.Name+": "+w.goDec(fr)+",")
|
||||
}
|
||||
enc = strings.Join(es, "\n")
|
||||
dec = "return " + T + "{\n" + strings.Join(ds, "\n") + "\n}"
|
||||
case EnumType:
|
||||
e := r.module().enumNamed(r.t.Name)
|
||||
if e.String {
|
||||
enc, dec = "_e.String(string(_v))", "return "+T+"(_d.String())"
|
||||
} else {
|
||||
enc, dec = "_e.Int(int64(_v))", "return "+T+"(_d.Int())"
|
||||
}
|
||||
}
|
||||
p("\nfunc _enc_%s(_e *_native.Encoder, _v %s) {\n%s\n}\n", name, T, enc)
|
||||
p("\nfunc _dec_%s(_d *_native.Decoder) %s {\n%s\n}\n", name, T, dec)
|
||||
}
|
||||
}
|
||||
|
||||
// swiftRead is the Swift expression that reads a value of type r from the
|
||||
// reader rv.
|
||||
func (w *wire) swiftRead(r ref, rv string) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return "try " + rv + ".bool()"
|
||||
case Int:
|
||||
return swiftType(r.t) + "(truncatingIfNeeded: try " + rv + ".i64())"
|
||||
case Float:
|
||||
if r.t.Bits == 32 {
|
||||
return "Float(try " + rv + ".double())"
|
||||
}
|
||||
return "try " + rv + ".double()"
|
||||
case String:
|
||||
return "try " + rv + ".string()"
|
||||
case Bytes:
|
||||
return "try " + rv + ".data()"
|
||||
case Time:
|
||||
return "try " + rv + ".date()"
|
||||
case Duration:
|
||||
return "try " + rv + ".duration()"
|
||||
case Rect:
|
||||
return "try " + rv + ".rect()"
|
||||
case Buffer:
|
||||
return "try " + rv + ".buffer()"
|
||||
case Texture:
|
||||
return "try " + rv + ".texture()"
|
||||
case InterfaceType, Window, View, Func:
|
||||
return "try " + rv + ".u64()"
|
||||
}
|
||||
return "try _mygoRead_" + w.name(r) + "(&" + rv + ")"
|
||||
}
|
||||
|
||||
// swiftWrite is the Swift statement that writes v, of type r, to the
|
||||
// writer wv.
|
||||
func (w *wire) swiftWrite(r ref, wv, v string) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return wv + ".bool(" + v + ")"
|
||||
case Int:
|
||||
return wv + ".i64(Int64(truncatingIfNeeded: " + v + "))"
|
||||
case Float:
|
||||
if r.t.Bits == 32 {
|
||||
return wv + ".double(Double(" + v + "))"
|
||||
}
|
||||
return wv + ".double(" + v + ")"
|
||||
case String:
|
||||
return wv + ".string(" + v + ")"
|
||||
case Bytes:
|
||||
return wv + ".data(" + v + ")"
|
||||
case Time:
|
||||
return wv + ".date(" + v + ")"
|
||||
case Duration:
|
||||
return wv + ".duration(" + v + ")"
|
||||
case Rect:
|
||||
return wv + ".rect(" + v + ")"
|
||||
case Buffer:
|
||||
return wv + ".buffer(" + v + ")"
|
||||
case Texture:
|
||||
return wv + ".texture(" + v + ")"
|
||||
case InterfaceType:
|
||||
return wv + ".u64(_mygoRetain(" + v + "))"
|
||||
}
|
||||
return "_mygoWrite_" + w.name(r) + "(&" + wv + ", " + v + ")"
|
||||
}
|
||||
|
||||
// swiftFuncs writes the Swift functions that read and write the composite
|
||||
// types.
|
||||
func (w *wire) swiftFuncs(p func(format string, args ...any)) {
|
||||
for _, name := range w.names() {
|
||||
r := w.types[name]
|
||||
T := w.swiftType(r)
|
||||
var read, write string
|
||||
switch r.t.Kind {
|
||||
case Slice:
|
||||
read = fmt.Sprintf(" let n = try r.count()\n var v: %s = []\n v.reserveCapacity(n)\n for _ in 0..<n { v.append(%s) }\n return v", T, w.swiftRead(r.elem(), "r"))
|
||||
write = fmt.Sprintf(" w.count(v.count)\n for x in v { %s }", w.swiftWrite(r.elem(), "w", "x"))
|
||||
case Map:
|
||||
read = fmt.Sprintf(" let n = try r.count()\n var v: %s = [:]\n v.reserveCapacity(n)\n for _ in 0..<n {\n let k = try r.string()\n v[k] = %s\n }\n return v", T, w.swiftRead(r.elem(), "r"))
|
||||
write = fmt.Sprintf(" w.count(v.count)\n for (k, x) in v {\n w.string(k)\n %s\n }", w.swiftWrite(r.elem(), "w", "x"))
|
||||
case Pointer:
|
||||
read = fmt.Sprintf(" if try r.bool() { return %s }\n return nil", w.swiftRead(r.elem(), "r"))
|
||||
write = fmt.Sprintf(" if let x = v {\n w.bool(true)\n %s\n } else {\n w.bool(false)\n }", w.swiftWrite(r.elem(), "w", "x"))
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
s := mod.structNamed(r.t.Name)
|
||||
if len(s.Fields) == 0 {
|
||||
read, write = " _ = try r.bool()\n return "+T+"()", " w.bool(false)"
|
||||
break
|
||||
}
|
||||
var rs, ws []string
|
||||
for _, f := range s.Fields {
|
||||
fr := ref{f.Type, mod}
|
||||
n := swiftIdent(lowerCamel(f.Name))
|
||||
rs = append(rs, " "+n+": "+w.swiftRead(fr, "r"))
|
||||
ws = append(ws, " "+w.swiftWrite(fr, "w", "v."+n))
|
||||
}
|
||||
read = " return " + T + "(\n" + strings.Join(rs, ",\n") + "\n )"
|
||||
write = strings.Join(ws, "\n")
|
||||
case EnumType:
|
||||
e := r.module().enumNamed(r.t.Name)
|
||||
if e.String {
|
||||
read = fmt.Sprintf(" let raw = try r.string()\n guard let v = %s(rawValue: raw) else { throw _MygoWireError.value(\"%s\", raw) }\n return v", T, T)
|
||||
write = " w.string(v.rawValue)"
|
||||
} else {
|
||||
raw := swiftType(basics[e.Basic])
|
||||
read = fmt.Sprintf(" let raw = %s(truncatingIfNeeded: try r.i64())\n guard let v = %s(rawValue: raw) else { throw _MygoWireError.value(\"%s\", \"\\(raw)\") }\n return v", raw, T, T)
|
||||
write = " w.i64(Int64(truncatingIfNeeded: v.rawValue))"
|
||||
}
|
||||
}
|
||||
p("\nfunc _mygoRead_%s(_ r: inout _MygoReader) throws -> %s {\n%s\n}\n", name, T, read)
|
||||
p("\nfunc _mygoWrite_%s(_ w: inout _MygoWriter, _ v: %s) {\n%s\n}\n", name, T, write)
|
||||
}
|
||||
}
|
||||
|
||||
// direct reports whether a method's arguments and result are numbers, so
|
||||
// that Go calls it as a C function of them, without encoding them.
|
||||
func direct(m *Method) bool {
|
||||
if m.Ctx || m.Stream != 0 || m.Closer || m.Close || m.Err || m.MainThread || len(m.Params) > 15 {
|
||||
return false
|
||||
}
|
||||
number := func(t *Type) bool { return t.Kind == Bool || t.Kind == Int || t.Kind == Float }
|
||||
for _, p := range m.Params {
|
||||
if !number(p.Type) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return m.Result == nil || number(m.Result)
|
||||
}
|
||||
+503
@@ -0,0 +1,503 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Langs are the languages a module may be implemented in, each in the
|
||||
// directory of its name: a Swift package, a Kotlin Gradle library, a Rust
|
||||
// crate or a Zig package.
|
||||
var Langs = []string{"swift", "kotlin", "rust", "zig"}
|
||||
|
||||
// langManifest is the file that makes a language's directory a package.
|
||||
var langManifest = map[string]string{"swift": "Package.swift", "kotlin": "build.gradle.kts", "rust": "Cargo.toml", "zig": "build.zig"}
|
||||
|
||||
// SwiftDir is the directory of a module's Swift sources.
|
||||
func SwiftDir(m *Module) string { return filepath.Join(m.Dir, "swift", "Sources", m.Name) }
|
||||
|
||||
// HasLang reports whether the module in dir is implemented in lang.
|
||||
func HasLang(dir, lang string) bool {
|
||||
f, ok := langManifest[lang]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
_, err := os.Stat(filepath.Join(dir, lang, f))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// ModuleLangs returns the languages the module in dir is implemented in.
|
||||
func ModuleLangs(dir string) []string {
|
||||
var langs []string
|
||||
for _, l := range Langs {
|
||||
if HasLang(dir, l) {
|
||||
langs = append(langs, l)
|
||||
}
|
||||
}
|
||||
return langs
|
||||
}
|
||||
|
||||
// GeneratedFile is the path of the generated file of a module in lang.
|
||||
func GeneratedFile(m *Module, lang string) string {
|
||||
switch lang {
|
||||
case "swift":
|
||||
return filepath.Join(SwiftDir(m), SwiftFile(m))
|
||||
case "kotlin":
|
||||
return filepath.Join(KotlinDir(m), KotlinFile(m))
|
||||
case "rust":
|
||||
return filepath.Join(m.Dir, "rust", "src", RustFile)
|
||||
}
|
||||
return filepath.Join(m.Dir, "zig", "src", ZigFile)
|
||||
}
|
||||
|
||||
// generate writes the generated file of a module in lang.
|
||||
func generate(m *Module, lang string) ([]byte, error) {
|
||||
switch lang {
|
||||
case "swift":
|
||||
return GenerateSwift(m), nil
|
||||
case "kotlin":
|
||||
return GenerateKotlin(m)
|
||||
case "rust":
|
||||
return GenerateRust(m)
|
||||
}
|
||||
return GenerateZig(m)
|
||||
}
|
||||
|
||||
var (
|
||||
macOSPlatform = regexp.MustCompile(`\.macOS\(\s*(?:\.v(\d+)(?:_(\d+))?|"([\d.]+)")\s*\)`)
|
||||
iOSPlatform = regexp.MustCompile(`\.iOS\(\s*(?:\.v(\d+)(?:_(\d+))?|"([\d.]+)")\s*\)`)
|
||||
)
|
||||
|
||||
// SwiftPlatforms are the systems a module's Swift runs on, from the
|
||||
// platforms of its Package.swift.
|
||||
type SwiftPlatforms struct {
|
||||
// OS are the systems: macos, ios. A package that names neither runs
|
||||
// on macOS.
|
||||
OS []string
|
||||
// MinMacOS and MinIOS are the oldest versions it names, "" for none.
|
||||
MinMacOS, MinIOS string
|
||||
}
|
||||
|
||||
// SwiftPlatformsOf reads the platforms of the Swift package of the module
|
||||
// in dir.
|
||||
func SwiftPlatformsOf(dir string) SwiftPlatforms {
|
||||
data, err := os.ReadFile(filepath.Join(dir, "swift", "Package.swift"))
|
||||
if err != nil {
|
||||
return SwiftPlatforms{}
|
||||
}
|
||||
var sp SwiftPlatforms
|
||||
if v, ok := platformVersion(macOSPlatform, data); ok {
|
||||
sp.OS, sp.MinMacOS = append(sp.OS, "macos"), v
|
||||
}
|
||||
if v, ok := platformVersion(iOSPlatform, data); ok {
|
||||
sp.OS, sp.MinIOS = append(sp.OS, "ios"), v
|
||||
}
|
||||
if len(sp.OS) == 0 {
|
||||
sp.OS = []string{"macos"}
|
||||
}
|
||||
return sp
|
||||
}
|
||||
|
||||
func platformVersion(re *regexp.Regexp, data []byte) (string, bool) {
|
||||
m := re.FindSubmatch(data)
|
||||
switch {
|
||||
case m == nil:
|
||||
return "", false
|
||||
case len(m[3]) > 0:
|
||||
return string(m[3]), true
|
||||
case len(m[2]) > 0:
|
||||
return string(m[1]) + "." + string(m[2]), true
|
||||
}
|
||||
return string(m[1]), true
|
||||
}
|
||||
|
||||
// MinMacOS reads the oldest macOS the Swift package in dir supports from
|
||||
// the platforms of its Package.swift, or "" when it names none.
|
||||
func MinMacOS(dir string) string { return SwiftPlatformsOf(dir).MinMacOS }
|
||||
|
||||
// Result is what Generate wrote.
|
||||
type Result struct {
|
||||
Module *Module
|
||||
Written []string // the files that changed
|
||||
}
|
||||
|
||||
// Generate loads the module in dir and writes its generated files,
|
||||
// leaving those that are up to date.
|
||||
func Generate(dir string) (*Result, error) {
|
||||
m, err := Load(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := &Result{Module: m}
|
||||
langs := ModuleLangs(m.Dir)
|
||||
goSrc, err := GenerateGo(m, langs, SwiftPlatformsOf(m.Dir))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.write(filepath.Join(m.Dir, GeneratedGo(m.Package)), goSrc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, lang := range langs {
|
||||
src, err := generate(m, lang)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.write(GeneratedFile(m, lang), src); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *Result) write(path string, data []byte) error {
|
||||
if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, data) {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Written = append(r.Written, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stale returns the generated files of the module in dir that are older
|
||||
// than its interface, or missing.
|
||||
func Stale(dir string) ([]string, error) {
|
||||
m, err := Load(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
line := SourceLine(m.Hash)
|
||||
var stale []string
|
||||
check := func(path string) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || !bytes.Contains(data, []byte(line)) {
|
||||
stale = append(stale, path)
|
||||
}
|
||||
}
|
||||
check(filepath.Join(m.Dir, GeneratedGo(m.Package)))
|
||||
for _, lang := range ModuleLangs(m.Dir) {
|
||||
check(GeneratedFile(m, lang))
|
||||
}
|
||||
return stale, nil
|
||||
}
|
||||
|
||||
// IsModule reports whether dir holds a native module: a Go package whose
|
||||
// generated file nativegen wrote.
|
||||
func IsModule(dir string) bool {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), "_native.go") && isGenerated(filepath.Join(dir, e.Name())) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Scaffold writes a new module named pkg in dir, implemented in the
|
||||
// languages given.
|
||||
func Scaffold(dir, pkg string, langs []string) error {
|
||||
if !validPackage(pkg) {
|
||||
return fmt.Errorf("%q is not a Go package name: use lower case letters and digits, as language or media", pkg)
|
||||
}
|
||||
if entries, err := os.ReadDir(dir); err == nil && len(entries) > 0 {
|
||||
return fmt.Errorf("%s is not empty", dir)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
name := UpperCamel(pkg)
|
||||
files := map[string]string{
|
||||
pkg + ".go": fmt.Sprintf(goTemplate, pkg, name),
|
||||
"AGENTS.md": strings.ReplaceAll(strings.ReplaceAll(agentsTemplate, "PKG", pkg), "MODULE", name),
|
||||
}
|
||||
for path, content := range files {
|
||||
if err := os.WriteFile(filepath.Join(dir, path), []byte(content), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := Generate(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, l := range langs {
|
||||
if err := AddLang(dir, l); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validPackage(s string) bool {
|
||||
if s == "" || s == "main" || !(s[0] >= 'a' && s[0] <= 'z') {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AddLang adds a language's directory to the module in dir: a package
|
||||
// whose every method says it is unsupported, so the module builds at once.
|
||||
func AddLang(dir, lang string) error {
|
||||
if _, ok := langManifest[lang]; !ok {
|
||||
return fmt.Errorf("unknown language %q: modules are implemented in %s", lang, strings.Join(Langs, ", "))
|
||||
}
|
||||
if HasLang(dir, lang) {
|
||||
return fmt.Errorf("%s already has %s/", dir, lang)
|
||||
}
|
||||
m, err := Load(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pkg := filepath.Join(m.Dir, lang)
|
||||
var files map[string][]byte
|
||||
switch lang {
|
||||
case "swift":
|
||||
files = map[string][]byte{
|
||||
filepath.Join(pkg, "Package.swift"): []byte(strings.ReplaceAll(packageTemplate, "MODULE", m.Name)),
|
||||
filepath.Join(pkg, ".gitignore"): []byte("/.build\n/.swiftpm\n"),
|
||||
filepath.Join(SwiftDir(m), m.Name+".swift"): stubSwift(m),
|
||||
}
|
||||
case "kotlin":
|
||||
if err := portable(m, "Kotlin"); err != nil {
|
||||
return err
|
||||
}
|
||||
if m.ImportPath == "" {
|
||||
return fmt.Errorf("%s is in no Go module, whose path names its Kotlin package: run go mod init", m.Dir)
|
||||
}
|
||||
files = map[string][]byte{
|
||||
filepath.Join(pkg, "build.gradle.kts"): []byte(strings.ReplaceAll(strings.ReplaceAll(gradleTemplate, "PKG", m.Package), "NAMESPACE", KotlinNamespace(m.ImportPath))),
|
||||
filepath.Join(pkg, ".gitignore"): []byte("/build\n"),
|
||||
filepath.Join(KotlinDir(m), m.Name+".kt"): stubKotlin(m),
|
||||
}
|
||||
case "rust":
|
||||
if err := portable(m, "Rust"); err != nil {
|
||||
return err
|
||||
}
|
||||
files = map[string][]byte{
|
||||
filepath.Join(pkg, "Cargo.toml"): []byte(strings.ReplaceAll(cargoTemplate, "PKG", m.Package)),
|
||||
filepath.Join(pkg, ".gitignore"): []byte("/target\n"),
|
||||
filepath.Join(pkg, "src", "lib.rs"): stubRust(m),
|
||||
}
|
||||
case "zig":
|
||||
if err := portable(m, "Zig"); err != nil {
|
||||
return err
|
||||
}
|
||||
files = map[string][]byte{
|
||||
filepath.Join(pkg, "build.zig"): []byte(strings.ReplaceAll(zigBuildTemplate, "MODULE", m.Name)),
|
||||
filepath.Join(pkg, ".gitignore"): []byte("/zig-out\n/.zig-cache\n/zig-pkg\n"),
|
||||
filepath.Join(pkg, "src", m.Package+".zig"): stubZig(m),
|
||||
}
|
||||
}
|
||||
for path, data := range files {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = Generate(dir)
|
||||
return err
|
||||
}
|
||||
|
||||
// stubSwift is an implementation whose every method says it is
|
||||
// unsupported, to fill in one at a time.
|
||||
func stubSwift(m *Module) []byte {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "import Foundation\n#if canImport(AppKit)\nimport AppKit\n#elseif canImport(UIKit)\nimport UIKit\n#endif\n\n// The implementation of package %s on Apple's platforms. Implement the\n// methods one at a time: each says it is unsupported until it does.\n", m.Package)
|
||||
g := &swiftGen{m: m, b: &b}
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
attr := ""
|
||||
if it.MainThread {
|
||||
attr = "@MainActor "
|
||||
}
|
||||
class := "Native" + it.Name
|
||||
if it.Entry {
|
||||
fmt.Fprintf(&b, "\n%sfunc make%s() throws -> any %s { %s() }\n", attr, it.Name, it.Name, class)
|
||||
}
|
||||
base := it.Name
|
||||
if it.View {
|
||||
base = "NativeView, " + it.Name
|
||||
}
|
||||
fmt.Fprintf(&b, "\n%sfinal class %s: %s {\n", attr, class, base)
|
||||
for _, me := range it.Methods {
|
||||
req := g.requirement(it, me)
|
||||
var body string
|
||||
switch {
|
||||
case me.Close:
|
||||
req, body = "func close() throws", ""
|
||||
case me.Stream == 1:
|
||||
body = "AsyncStream { $0.finish() }"
|
||||
case me.Stream == 2:
|
||||
body = "AsyncThrowingStream { $0.finish(throwing: NativeError.unsupported) }"
|
||||
case me.Closer:
|
||||
body = "NativeCloser {}"
|
||||
case me.Err:
|
||||
body = "throw NativeError.unsupported"
|
||||
case me.Result == nil:
|
||||
body = ""
|
||||
default:
|
||||
body = "fatalError(\"" + it.Name + "." + me.Name + " is not implemented\")"
|
||||
}
|
||||
fmt.Fprintf(&b, " %s {\n", req)
|
||||
if body != "" {
|
||||
fmt.Fprintf(&b, " %s\n", body)
|
||||
}
|
||||
b.WriteString(" }\n")
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// stubKotlin is an implementation whose every method says it is
|
||||
// unsupported, to fill in one at a time.
|
||||
func stubKotlin(m *Module) []byte {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "package %s\n\nimport dev.mygo.*\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coroutines.flow.emptyFlow\nimport kotlinx.coroutines.flow.flow\n\n// The implementation of package %s on Android. Implement the methods one\n// at a time: each says it is unsupported until it does.\n", KotlinPackage(m.ImportPath), m.Package)
|
||||
g := &kotlinGen{m: m, b: &b}
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
class := "Android" + it.Name
|
||||
arg, base := "", it.Name
|
||||
if it.View {
|
||||
arg, base = "Native.activity ?: Native.context", "android.view.View(context), "+it.Name
|
||||
class += "(context: android.content.Context)"
|
||||
}
|
||||
name := "Android" + it.Name
|
||||
if it.Entry {
|
||||
fmt.Fprintf(&b, "\nfun make%s(): %s = %s(%s)\n", it.Name, it.Name, name, arg)
|
||||
}
|
||||
fmt.Fprintf(&b, "\nprivate class %s : %s {\n", class, base)
|
||||
for _, me := range it.Methods {
|
||||
if me.Close {
|
||||
b.WriteString(" override fun close() {}\n")
|
||||
continue
|
||||
}
|
||||
var body string
|
||||
switch {
|
||||
case me.Stream == 1:
|
||||
body = " = emptyFlow()"
|
||||
case me.Stream == 2:
|
||||
body = " = flow { throw NativeUnsupportedException() }"
|
||||
case me.Closer:
|
||||
body = " = NativeCloser {}"
|
||||
case me.Err && me.Result == nil:
|
||||
body = " {\n throw NativeUnsupportedException()\n }"
|
||||
case me.Err:
|
||||
body = " = throw NativeUnsupportedException()"
|
||||
case me.Result == nil:
|
||||
body = " {}"
|
||||
default:
|
||||
body = " = TODO(\"" + it.Name + "." + me.Name + " is not implemented\")"
|
||||
}
|
||||
fmt.Fprintf(&b, " override %s%s\n", g.signature(me), body)
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// gradleTemplate is the Gradle library of a module's Kotlin.
|
||||
const gradleTemplate = `// The Kotlin of the native module PKG: an Android library, which mygo
|
||||
// build adds to the app's Gradle build. The build sets its SDK levels, Java
|
||||
// and Kotlin, and its dependency on MyGo's host library (dev.mygo), which
|
||||
// brings coroutines: add only what the implementation uses.
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "NAMESPACE"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
}
|
||||
`
|
||||
|
||||
const goTemplate = `// Package %[1]s is a native module: its interfaces are implemented in
|
||||
// Swift, Kotlin, Rust or Zig, in the directory of the language (see AGENTS.md).
|
||||
package %[1]s
|
||||
|
||||
// Greeter greets.
|
||||
//
|
||||
//mygo:native
|
||||
type Greeter interface {
|
||||
// Greet returns a greeting for name.
|
||||
Greet(name string) (string, error)
|
||||
}
|
||||
`
|
||||
|
||||
const packageTemplate = `// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "MODULE",
|
||||
platforms: [.macOS(.v13)],
|
||||
products: [.library(name: "MODULE", type: .dynamic, targets: ["MODULE"])],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(name: "MODULE"),
|
||||
],
|
||||
swiftLanguageModes: [.v5]
|
||||
)
|
||||
`
|
||||
|
||||
const agentsTemplate = "# Native module PKG\n\n" +
|
||||
"PKG is a native module of MyGo: Go interfaces implemented in Swift, Kotlin,\n" +
|
||||
"Rust or Zig. Read https://mygo.dev/docs/native-modules (docs/native-modules.md)\n" +
|
||||
"before changing it.\n\n" +
|
||||
"- `PKG.go` declares the interfaces, the types they use and the errors\n" +
|
||||
" (`native.NewError`): it is the contract. `//mygo:native` marks an entry point,\n" +
|
||||
" which gets a constructor, `NewT`.\n" +
|
||||
"- `PKG_native.go` and each language's generated file\n" +
|
||||
" (`swift/Sources/MODULE/MODULE.mygo.swift`, `kotlin/src/main/kotlin/.../MODULE.mygo.kt`,\n" +
|
||||
" `rust/src/mygo.rs`, `zig/src/mygo.zig`) are generated: never edit them; `mygo dev`\n" +
|
||||
" regenerates them when the interfaces change.\n" +
|
||||
"- `swift/` is a Swift package, which macOS and iOS use when its\n" +
|
||||
" `Package.swift` names them, for Apple's frameworks: a factory `makeT()`\n" +
|
||||
" per entry point and classes conforming to the generated protocols. Add\n" +
|
||||
" Swift packages and frameworks in `swift/Package.swift`.\n" +
|
||||
"- `kotlin/` is an Android library, which Android uses: a function\n" +
|
||||
" `makeT()` per entry point and classes implementing the generated\n" +
|
||||
" interfaces. Add dependencies in `kotlin/build.gradle.kts`.\n" +
|
||||
"- `rust/` is a Rust crate and `zig/` a Zig package, for every platform: a\n" +
|
||||
" factory per entry point (`make_t` in Rust, `makeT` in Zig) and types\n" +
|
||||
" implementing the generated traits or declarations.\n\n" +
|
||||
"Check the module without opening the app:\n\n" +
|
||||
"```sh\n" +
|
||||
"mygo native check # generate, build and vet: every problem as file:line\n" +
|
||||
"mygo native call Greeter.Greet '{\"name\": \"Ada\"}' # call a method, print its result\n" +
|
||||
"```\n"
|
||||
|
||||
const cargoTemplate = `[package]
|
||||
name = "PKG"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
`
|
||||
+882
@@ -0,0 +1,882 @@
|
||||
package nativegen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"maps"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ZigFile is the generated Zig of a module, the root of its library, which
|
||||
// imports the implementation from src/<package>.zig.
|
||||
const ZigFile = "mygo.zig"
|
||||
|
||||
// GenerateZig writes the Zig side: the interfaces the implementation
|
||||
// implements, as values of a pointer and a table of its methods, the
|
||||
// structs, enums and errors of the Go side, and the functions Go calls,
|
||||
// which call the factories of the implementation (make<Entry point>).
|
||||
func GenerateZig(m *Module) ([]byte, error) {
|
||||
if err := portable(m, "Zig"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var b bytes.Buffer
|
||||
g := &zigGen{m: m, b: &b, w: newWire(m)}
|
||||
g.p("%s// %s\n//\n// The declarations of package %s, which the implementation in %s.zig\n// implements, and the functions Go calls. See docs/native-modules.md.\n\n", goHeader, SourceLine(m.Hash), m.Package, m.Package)
|
||||
g.p("const std = @import(\"std\");\nconst impl = @import(%q);\n\npub const Allocator = std.mem.Allocator;\n", m.Package+".zig")
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
g.goIface(it)
|
||||
} else {
|
||||
g.iface(it)
|
||||
}
|
||||
}
|
||||
for _, s := range m.Structs {
|
||||
g.structDecl(s, m)
|
||||
}
|
||||
for _, e := range m.Enums {
|
||||
g.enumDecl(e)
|
||||
}
|
||||
g.foreign()
|
||||
g.funcTypes()
|
||||
g.errorsDecl()
|
||||
g.p("\n// The functions Go calls.\n")
|
||||
g.p("\nexport fn %s(cb: Callback, id_base: u64, malloc: Malloc, free: Free) void {\n runtime = .{ .cb = cb, .id_base = id_base, .malloc = malloc, .free = free };\n}\n", g.sym("init"))
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
if it.Entry {
|
||||
g.factory(it)
|
||||
}
|
||||
for _, me := range it.Methods {
|
||||
if !me.Close {
|
||||
g.entry(it, me)
|
||||
}
|
||||
}
|
||||
}
|
||||
g.objects()
|
||||
g.common()
|
||||
g.funcs()
|
||||
g.p("%s", zigSupport)
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
type zigGen struct {
|
||||
m *Module
|
||||
b *bytes.Buffer
|
||||
w *wire
|
||||
}
|
||||
|
||||
func (g *zigGen) p(format string, args ...any) { fmt.Fprintf(g.b, format, args...) }
|
||||
|
||||
func (g *zigGen) sym(name string) string { return "mygo_" + g.m.Package + "_" + name }
|
||||
|
||||
// param is the Zig name of a parameter, which may not shadow a method of
|
||||
// the struct it is in: one of the module's methods, or of what the
|
||||
// generated code declares in its structs.
|
||||
func (g *zigGen) param(name string) string {
|
||||
z := zigParam(name)
|
||||
switch z {
|
||||
case "deinit", "of", "keep", "release", "call", "next", "close":
|
||||
return z + "_"
|
||||
}
|
||||
for _, it := range g.m.Interfaces {
|
||||
for _, m := range it.Methods {
|
||||
if zigMethod(m.Name) == z {
|
||||
return z + "_"
|
||||
}
|
||||
}
|
||||
}
|
||||
return z
|
||||
}
|
||||
|
||||
var zigKeywords = map[string]bool{
|
||||
"addrspace": true, "align": true, "allowzero": true, "and": true, "anyframe": true, "anytype": true,
|
||||
"asm": true, "break": true, "callconv": true, "catch": true, "comptime": true, "const": true,
|
||||
"continue": true, "defer": true, "else": true, "enum": true, "errdefer": true, "error": true,
|
||||
"export": true, "extern": true, "fn": true, "for": true, "if": true, "inline": true,
|
||||
"linksection": true, "noalias": true, "noinline": true, "nosuspend": true, "opaque": true,
|
||||
"or": true, "orelse": true, "packed": true, "pub": true, "resume": true, "return": true,
|
||||
"struct": true, "suspend": true, "switch": true, "test": true, "threadlocal": true, "try": true,
|
||||
"union": true, "unreachable": true, "var": true, "volatile": true, "while": true,
|
||||
"bool": true, "void": true, "type": true, "anyerror": true, "anyopaque": true, "usize": true,
|
||||
"isize": true, "noreturn": true, "true": true, "false": true, "null": true, "undefined": true,
|
||||
"comptime_int": true, "comptime_float": true, "f16": true, "f32": true, "f64": true, "f80": true,
|
||||
"f128": true, "c_int": true, "c_uint": true, "c_long": true, "c_ulong": true, "c_short": true,
|
||||
"c_ushort": true, "c_char": true, "c_longlong": true, "c_ulonglong": true, "c_longdouble": true,
|
||||
}
|
||||
|
||||
var zigIntType = regexp.MustCompile(`^[iu][0-9]+$`)
|
||||
|
||||
// zigName escapes a Zig keyword or primitive used as a name.
|
||||
func zigName(s string) string {
|
||||
if zigKeywords[s] || zigIntType.MatchString(s) {
|
||||
return "@\"" + s + "\""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// zigField is the Zig name of a field or an enum case: snake case.
|
||||
func zigField(name string) string { return zigName(snake(name)) }
|
||||
|
||||
// zigMethod is the Zig name of a method: lower camel case.
|
||||
func zigMethod(name string) string { return zigName(lowerCamel(name)) }
|
||||
|
||||
// zigDecls are the declarations of the generated Zig a parameter must not
|
||||
// shadow.
|
||||
var zigDecls = map[string]bool{
|
||||
"allocator": true, "io": true, "fail": true, "failGo": true, "message": true, "checkMethod": true,
|
||||
"runtime": true, "writeError": true, "readError": true, "run": true, "failed": true, "pending": true,
|
||||
"send": true, "answer": true, "retain": true, "object": true, "tasks": true, "cancel": true,
|
||||
"demand": true, "start": true, "stream": true, "invoke": true, "conts": true, "nextId": true,
|
||||
"resumeCall": true, "invokeAsync": true, "bytesOf": true, "setDetail": true, "errorCode": true,
|
||||
"errorOfCode": true, "pointer": true, "arena": true, "ctx": true, "self": true, "mygo": true, "std": true, "impl": true, "o": true, "w": true, "r": true, "a": true, "h": true, "v": true,
|
||||
}
|
||||
|
||||
// zigParam is the Zig name of a parameter.
|
||||
func zigParam(name string) string {
|
||||
if zigDecls[name] || strings.HasPrefix(name, "detail_") || strings.HasPrefix(name, "kind_") || strings.HasPrefix(name, "status_") || strings.HasPrefix(name, "err_") || strings.HasPrefix(name, "enc_") || strings.HasPrefix(name, "dec_") || strings.HasPrefix(name, "obj") {
|
||||
return name + "_"
|
||||
}
|
||||
return zigName(name)
|
||||
}
|
||||
|
||||
// typ is the Zig spelling of a type.
|
||||
func (g *zigGen) typ(r ref) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return "bool"
|
||||
case Int:
|
||||
if t.Unsigned {
|
||||
return fmt.Sprintf("u%d", t.Bits)
|
||||
}
|
||||
return fmt.Sprintf("i%d", t.Bits)
|
||||
case Float:
|
||||
return fmt.Sprintf("f%d", t.Bits)
|
||||
case String, Bytes:
|
||||
return "[]const u8"
|
||||
case Time:
|
||||
return "Time"
|
||||
case Duration:
|
||||
return "i64"
|
||||
case Slice:
|
||||
return "[]const " + g.typ(r.elem())
|
||||
case Map:
|
||||
return "[]const Entry(" + g.typ(r.elem()) + ")"
|
||||
case Pointer:
|
||||
return "?" + g.typ(r.elem())
|
||||
case StructType, EnumType:
|
||||
if mod := r.module(); mod != g.m {
|
||||
return mod.Package + "." + t.Name
|
||||
}
|
||||
return t.Name
|
||||
case InterfaceType:
|
||||
return t.Name
|
||||
case Rect:
|
||||
return "Rect"
|
||||
case Buffer:
|
||||
return "Buffer"
|
||||
}
|
||||
return "void"
|
||||
}
|
||||
|
||||
// typFor is the spelling of a type of a struct of the module mod, from
|
||||
// within the declarations of mod's types.
|
||||
func (g *zigGen) typFor(r ref) string {
|
||||
s := g.typ(r)
|
||||
if r.owner == g.m {
|
||||
return s
|
||||
}
|
||||
return strings.ReplaceAll(s, r.owner.Package+".", "")
|
||||
}
|
||||
|
||||
// funcType is the name of the type of a function parameter, which calls
|
||||
// Go: <Interface><Method><Parameter>.
|
||||
func funcType(it *Interface, m *Method, p *Param) string {
|
||||
return it.Name + m.Name + UpperCamel(p.Name)
|
||||
}
|
||||
|
||||
// ret is the return type of a method.
|
||||
func (g *zigGen) ret(m *Method) string {
|
||||
switch {
|
||||
case m.Close:
|
||||
return "Error!void"
|
||||
case m.Stream != 0:
|
||||
return "Error!Iterator(" + g.typ(ref{m.Result, g.m}) + ")"
|
||||
case m.Closer:
|
||||
return "Error!Closer"
|
||||
}
|
||||
v := "void"
|
||||
if m.Result != nil {
|
||||
v = g.typ(ref{m.Result, g.m})
|
||||
}
|
||||
if m.Err {
|
||||
return "Error!" + v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// params are the types of the parameters of a method after its receiver,
|
||||
// with their names when named.
|
||||
func (g *zigGen) params(it *Interface, m *Method, named bool) []string {
|
||||
if m.Close {
|
||||
return nil
|
||||
}
|
||||
n := func(name, t string) string {
|
||||
if named {
|
||||
return name + ": " + t
|
||||
}
|
||||
return t
|
||||
}
|
||||
ps := []string{n("arena", "Allocator")}
|
||||
if m.Ctx {
|
||||
ps = append(ps, n("ctx", "*Context"))
|
||||
}
|
||||
for _, p := range m.Params {
|
||||
t := g.typ(ref{p.Type, g.m})
|
||||
if p.Type.Kind == Func {
|
||||
t = funcType(it, m, p)
|
||||
}
|
||||
ps = append(ps, n(g.param(p.Name), t))
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
func (g *zigGen) iface(it *Interface) {
|
||||
g.p("\n%s///\n/// Make one of a pointer with %s.of: its type has the methods, which take\n/// an arena, freed once the call returns, for what they allocate.\npub const %s = struct {\n ptr: *anyopaque,\n vtable: *const VTable,\n\n pub const VTable = struct {\n", docComment(it.Doc, ""), it.Name, it.Name)
|
||||
for _, m := range it.Methods {
|
||||
g.p(" %s: *const fn (%s) %s,\n", zigMethod(m.Name), strings.Join(append([]string{"*anyopaque"}, g.params(it, m, false)...), ", "), g.ret(m))
|
||||
}
|
||||
g.p(" deinit: ?*const fn (*anyopaque) void,\n };\n")
|
||||
g.p("\n /// Makes a %s of p, a pointer to a value whose type has its methods\n /// and may have deinit, which Go calls once it lets go of the value.\n pub fn of(pointer: anytype) %s {\n const T = @typeInfo(@TypeOf(pointer)).pointer.child;\n const vt = struct {\n", it.Name, it.Name)
|
||||
for _, m := range it.Methods {
|
||||
ps := g.params(it, m, true)
|
||||
var names []string
|
||||
for _, p := range ps {
|
||||
names = append(names, p[:strings.Index(p, ": ")])
|
||||
}
|
||||
g.p(" fn vt_%s(%s) %s {\n return @as(*T, @ptrCast(@alignCast(o))).%s(%s);\n }\n", strings.Trim(zigMethod(m.Name), "@\""), strings.Join(append([]string{"o: *anyopaque"}, ps...), ", "), g.ret(m), zigMethod(m.Name), strings.Join(names, ", "))
|
||||
}
|
||||
g.p(" fn vt_deinit(o: *anyopaque) void {\n if (@hasDecl(T, \"deinit\")) @as(*T, @ptrCast(@alignCast(o))).deinit();\n }\n const table: VTable = .{\n")
|
||||
for _, m := range it.Methods {
|
||||
g.p(" .%s = vt_%s,\n", zigMethod(m.Name), strings.Trim(zigMethod(m.Name), "@\""))
|
||||
}
|
||||
g.p(" .deinit = if (@hasDecl(T, \"deinit\")) vt_deinit else null,\n };\n };\n comptime {\n")
|
||||
for _, m := range it.Methods {
|
||||
g.p(" checkMethod(T, %q, %q, fn (%s) %s);\n", it.Name, strings.Trim(zigMethod(m.Name), "@\""), strings.Join(append([]string{"*T"}, g.params(it, m, false)...), ", "), g.ret(m))
|
||||
}
|
||||
g.p(" }\n return .{ .ptr = pointer, .vtable = &vt.table };\n }\n")
|
||||
for _, m := range it.Methods {
|
||||
ps := g.params(it, m, true)
|
||||
var names []string
|
||||
for _, p := range ps {
|
||||
names = append(names, p[:strings.Index(p, ": ")])
|
||||
}
|
||||
g.p("\n%s pub fn %s(%s) %s {\n return self.vtable.%s(%s);\n }\n", docComment(m.Doc, " "), zigMethod(m.Name), strings.Join(append([]string{"self: " + it.Name}, ps...), ", "), g.ret(m), zigMethod(m.Name), strings.Join(append([]string{"self.ptr"}, names...), ", "))
|
||||
}
|
||||
g.p("};\n")
|
||||
}
|
||||
|
||||
// goIface writes the type of a value of an interface Go implements, whose
|
||||
// methods call Go.
|
||||
func (g *zigGen) goIface(it *Interface) {
|
||||
g.p("\n%s///\n/// Go implements it. A value the implementation is given is released once\n/// the call that gives it returns, unless the implementation keeps it.\npub const %s = struct {\n f: *GoFunc,\n\n /// Keeps the value past the call that gave it, until release.\n pub fn keep(self: %s) %s {\n self.f.retain();\n return self;\n }\n\n pub fn release(self: %s) void {\n self.f.release();\n }\n", docComment(it.Doc, ""), it.Name, it.Name, it.Name, it.Name)
|
||||
for i, m := range it.Methods {
|
||||
ps := g.params(it, m, true)
|
||||
lines := []string{"var w = Writer.init();", "defer w.deinit();", fmt.Sprintf("w.int(%d);", i)}
|
||||
for _, p := range m.Params {
|
||||
lines = append(lines, g.write(ref{p.Type, g.m}, "(&w)", g.param(p.Name)))
|
||||
}
|
||||
R := "void"
|
||||
read := "struct {\n fn read(_: *Reader) Error!void {}\n }.read"
|
||||
if m.Result != nil {
|
||||
R = g.typ(ref{m.Result, g.m})
|
||||
read = "struct {\n fn read(r: *Reader) Error!" + R + " {\n return " + g.read(ref{m.Result, g.m}, "r") + ";\n }\n }.read"
|
||||
}
|
||||
call := "invoke(self.f.id, arena, &w, " + R + ", " + read + ")"
|
||||
if m.Ctx {
|
||||
call = "invokeAsync(self.f.id, arena, ctx, &w, " + R + ", " + read + ")"
|
||||
}
|
||||
if m.Err {
|
||||
lines = append(lines, "return "+call+";")
|
||||
} else {
|
||||
lines = append(lines, "return "+call+" catch @panic(\"Go failed to answer\");")
|
||||
}
|
||||
g.p("\n%s pub fn %s(%s) %s {\n %s\n }\n", docComment(m.Doc, " "), zigMethod(m.Name), strings.Join(append([]string{"self: " + it.Name}, ps...), ", "), g.ret(m), strings.Join(lines, "\n "))
|
||||
}
|
||||
g.p("};\n")
|
||||
}
|
||||
|
||||
// funcTypes writes the types of the functions methods take, which call Go.
|
||||
func (g *zigGen) funcTypes() {
|
||||
for _, it := range g.m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
for _, m := range it.Methods {
|
||||
for _, p := range m.Params {
|
||||
if p.Type.Kind == Func {
|
||||
g.funcType(funcType(it, m, p), p.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *zigGen) funcType(name string, t *Type) {
|
||||
g.p("\n/// A function of Go's. The value a method is given is released once the\n/// call returns, unless the implementation keeps it.\npub const %s = struct {\n f: *GoFunc,\n\n /// Keeps the function past the call that gave it, until release.\n pub fn keep(self: %s) %s {\n self.f.retain();\n return self;\n }\n\n pub fn release(self: %s) void {\n self.f.release();\n }\n", name, name, name, name)
|
||||
var ps []string
|
||||
if t.Result != nil {
|
||||
ps = append(ps, "arena: Allocator")
|
||||
}
|
||||
lines := []string{"var w = Writer.init();", "defer w.deinit();"}
|
||||
for i, p := range t.Params {
|
||||
n := fmt.Sprintf("p%d", i)
|
||||
ps = append(ps, n+": "+g.typ(ref{p.Type, g.m}))
|
||||
lines = append(lines, g.write(ref{p.Type, g.m}, "(&w)", n))
|
||||
}
|
||||
R := "void"
|
||||
if t.Result != nil {
|
||||
R = g.typ(ref{t.Result, g.m})
|
||||
}
|
||||
ret := R
|
||||
switch {
|
||||
case t.Result == nil && !t.Err:
|
||||
lines = append(lines, "self.f.notify(&w);")
|
||||
default:
|
||||
read := "struct {\n fn read(_: *Reader) Error!void {}\n }.read"
|
||||
if t.Result != nil {
|
||||
read = "struct {\n fn read(r: *Reader) Error!" + R + " {\n return " + g.read(ref{t.Result, g.m}, "r") + ";\n }\n }.read"
|
||||
}
|
||||
arena := "arena"
|
||||
if t.Result == nil {
|
||||
arena = "std.heap.c_allocator"
|
||||
}
|
||||
call := "self.f.ask(" + arena + ", &w, " + R + ", " + read + ")"
|
||||
if t.Err {
|
||||
ret = "Error!" + R
|
||||
lines = append(lines, "return "+call+";")
|
||||
} else {
|
||||
lines = append(lines, "return "+call+" catch @panic(\"Go failed to answer\");")
|
||||
}
|
||||
}
|
||||
g.p("\n /// Calls the function.\n pub fn call(%s) %s {\n %s\n }\n};\n", strings.Join(append([]string{"self: " + name}, ps...), ", "), ret, strings.Join(lines, "\n "))
|
||||
}
|
||||
|
||||
func (g *zigGen) structDecl(s *Struct, mod *Module) {
|
||||
g.p("\n%spub const %s = struct {\n", docComment(s.Doc, ""), s.Name)
|
||||
for _, f := range s.Fields {
|
||||
r := ref{f.Type, mod}
|
||||
g.p("%s %s: %s%s,\n", docComment(f.Doc, " "), zigField(f.Name), g.typFor(r), zigDefault(r))
|
||||
}
|
||||
g.p("};\n")
|
||||
}
|
||||
|
||||
// zigDefault is the default of a field, " = …", for the types that have
|
||||
// one.
|
||||
func zigDefault(r ref) string {
|
||||
switch r.t.Kind {
|
||||
case Bool:
|
||||
return " = false"
|
||||
case Int, Float, Duration:
|
||||
return " = 0"
|
||||
case String, Bytes, Slice, Map:
|
||||
return " = &.{}"
|
||||
case Pointer:
|
||||
return " = null"
|
||||
case Time, Rect:
|
||||
return " = .{}"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (g *zigGen) enumDecl(e *Enum) {
|
||||
tag := ""
|
||||
if !e.String {
|
||||
tag = "(" + g.typ(ref{basics[e.Basic], g.m}) + ")"
|
||||
}
|
||||
g.p("\n%spub const %s = enum%s {\n", docComment(e.Doc, ""), e.Name, tag)
|
||||
for _, c := range e.Cases {
|
||||
if e.String {
|
||||
g.p("%s %s,\n", docComment(c.Doc, " "), zigField(c.Name))
|
||||
} else {
|
||||
g.p("%s %s = %s,\n", docComment(c.Doc, " "), zigField(c.Name), c.Value)
|
||||
}
|
||||
}
|
||||
vt := "[]const u8"
|
||||
if !e.String {
|
||||
vt = "i64"
|
||||
}
|
||||
g.p("\n /// The value of the case in Go.\n pub fn value(self: %s) %s {\n", e.Name, vt)
|
||||
if e.String {
|
||||
g.p(" return switch (self) {\n")
|
||||
for _, c := range e.Cases {
|
||||
g.p(" .%s => %s,\n", zigField(c.Name), c.Value)
|
||||
}
|
||||
g.p(" };\n }\n")
|
||||
} else {
|
||||
g.p(" return @intFromEnum(self);\n }\n")
|
||||
}
|
||||
g.p("\n /// The case of a value of Go's.\n pub fn fromValue(v: %s) ?%s {\n", vt, e.Name)
|
||||
for _, c := range e.Cases {
|
||||
if e.String {
|
||||
g.p(" if (std.mem.eql(u8, v, %s)) return .%s;\n", c.Value, zigField(c.Name))
|
||||
} else {
|
||||
g.p(" if (v == %s) return .%s;\n", c.Value, zigField(c.Name))
|
||||
}
|
||||
}
|
||||
g.p(" return null;\n }\n};\n")
|
||||
}
|
||||
|
||||
func (g *zigGen) errorsDecl() {
|
||||
var names []string
|
||||
for _, e := range g.m.Errors {
|
||||
names = append(names, strings.TrimPrefix(e.Name, "Err"))
|
||||
}
|
||||
g.p("\n/// The errors an implementation returns: those package %s declares, with\n/// native.NewError, which Go compares with errors.Is, and the others: see\n/// fail and failGo for their messages.\npub const Error = error{ %s };\n", g.m.Package, strings.Join(append(names, "Unsupported", "Closed", "Canceled", "Go", "Other", "OutOfMemory"), ", "))
|
||||
g.p("\n/// The code of an error the module declares.\nfn errorCode(e: Error) ?[]const u8 {\n return switch (e) {\n")
|
||||
for _, e := range g.m.Errors {
|
||||
g.p(" error.%s => %q,\n", strings.TrimPrefix(e.Name, "Err"), e.Code)
|
||||
}
|
||||
g.p(" else => null,\n };\n}\n\nfn errorOfCode(code: []const u8) ?Error {\n")
|
||||
for _, e := range g.m.Errors {
|
||||
g.p(" if (std.mem.eql(u8, code, %q)) return error.%s;\n", e.Code, strings.TrimPrefix(e.Name, "Err"))
|
||||
}
|
||||
if len(g.m.Errors) == 0 {
|
||||
g.p(" _ = code;\n")
|
||||
}
|
||||
g.p(" return null;\n}\n")
|
||||
}
|
||||
|
||||
// foreign declares the structs and enums of other native modules that the
|
||||
// module uses, in a namespace of each's name.
|
||||
func (g *zigGen) foreign() {
|
||||
byMod := map[*Module][]ref{}
|
||||
for _, n := range g.w.names() {
|
||||
r := g.w.types[n]
|
||||
if (r.t.Kind == StructType || r.t.Kind == EnumType) && r.module() != g.m {
|
||||
byMod[r.module()] = append(byMod[r.module()], r)
|
||||
}
|
||||
}
|
||||
mods := slices.SortedFunc(maps.Keys(byMod), func(a, b *Module) int { return strings.Compare(a.Package, b.Package) })
|
||||
for _, mod := range mods {
|
||||
g.p("\n/// The types of the native module %s that %s uses.\npub const %s = struct {\n", mod.Package, g.m.Package, mod.Package)
|
||||
var inner bytes.Buffer
|
||||
sub := &zigGen{m: g.m, b: &inner, w: g.w}
|
||||
for _, r := range byMod[mod] {
|
||||
if r.t.Kind == StructType {
|
||||
sub.structDecl(mod.structNamed(r.t.Name), mod)
|
||||
} else {
|
||||
sub.enumDecl(mod.enumNamed(r.t.Name))
|
||||
}
|
||||
}
|
||||
for line := range strings.Lines(inner.String()) {
|
||||
if strings.TrimSpace(line) == "" {
|
||||
g.p("\n")
|
||||
} else {
|
||||
g.p(" %s", line)
|
||||
}
|
||||
}
|
||||
g.p("};\n")
|
||||
}
|
||||
}
|
||||
|
||||
// read is the Zig expression reading a value of type r from the reader rv,
|
||||
// a *Reader.
|
||||
func (g *zigGen) read(r ref, rv string) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return "try " + rv + ".boolean()"
|
||||
case Int:
|
||||
switch {
|
||||
case t.Bits == 64 && t.Unsigned:
|
||||
return "try " + rv + ".uint()"
|
||||
case t.Bits == 64:
|
||||
return "try " + rv + ".int()"
|
||||
case t.Unsigned:
|
||||
return "@as(" + g.typ(r) + ", @truncate(try " + rv + ".uint()))"
|
||||
}
|
||||
return "@as(" + g.typ(r) + ", @truncate(try " + rv + ".int()))"
|
||||
case Float:
|
||||
if t.Bits == 32 {
|
||||
return "@as(f32, @floatCast(try " + rv + ".float()))"
|
||||
}
|
||||
return "try " + rv + ".float()"
|
||||
case String, Bytes:
|
||||
return "try " + rv + ".string()"
|
||||
case Time:
|
||||
return "try " + rv + ".time()"
|
||||
case Duration:
|
||||
return "try " + rv + ".int()"
|
||||
case Rect:
|
||||
return "try " + rv + ".rect()"
|
||||
case Buffer:
|
||||
return "try " + rv + ".buffer()"
|
||||
case InterfaceType, Func:
|
||||
return "try " + rv + ".uint()"
|
||||
}
|
||||
return "try dec_" + g.w.name(r) + "(" + rv + ")"
|
||||
}
|
||||
|
||||
// write is the Zig statement writing v, of type r, to the writer wv, a
|
||||
// *Writer.
|
||||
func (g *zigGen) write(r ref, wv, v string) string {
|
||||
t := r.t
|
||||
switch t.Kind {
|
||||
case Bool:
|
||||
return wv + ".boolean(" + v + ");"
|
||||
case Int:
|
||||
if t.Unsigned {
|
||||
return wv + ".uint(@intCast(" + v + "));"
|
||||
}
|
||||
return wv + ".int(@intCast(" + v + "));"
|
||||
case Float:
|
||||
if t.Bits == 32 {
|
||||
return wv + ".float(@floatCast(" + v + "));"
|
||||
}
|
||||
return wv + ".float(" + v + ");"
|
||||
case String, Bytes:
|
||||
return wv + ".string(" + v + ");"
|
||||
case Time:
|
||||
return wv + ".time(" + v + ");"
|
||||
case Duration:
|
||||
return wv + ".int(" + v + ");"
|
||||
case Rect:
|
||||
return wv + ".rect(" + v + ");"
|
||||
case Buffer:
|
||||
return wv + ".buffer(" + v + ");"
|
||||
case InterfaceType:
|
||||
return wv + ".uint(try retain(.{ ." + t.Name + " = " + v + " }));"
|
||||
}
|
||||
return "enc_" + g.w.name(r) + "(" + wv + ", " + v + ");"
|
||||
}
|
||||
|
||||
// funcs writes the functions that encode and decode composite types.
|
||||
func (g *zigGen) funcs() {
|
||||
g.p("\n// Encoding.\n")
|
||||
for _, name := range g.w.names() {
|
||||
r := g.w.types[name]
|
||||
T := g.typ(r)
|
||||
var enc, dec string
|
||||
switch r.t.Kind {
|
||||
case Slice:
|
||||
enc = fmt.Sprintf(" w.count(v.len);\n for (v) |x| {\n %s\n }", g.write(r.elem(), "w", "x"))
|
||||
dec = fmt.Sprintf(" const v = try r.arena.alloc(%s, try r.count());\n for (v) |*x| x.* = %s;\n return v;", g.typ(r.elem()), g.read(r.elem(), "r"))
|
||||
case Map:
|
||||
enc = fmt.Sprintf(" w.count(v.len);\n for (v) |e| {\n w.string(e.key);\n %s\n }", g.write(r.elem(), "w", "e.value"))
|
||||
dec = fmt.Sprintf(" const v = try r.arena.alloc(Entry(%s), try r.count());\n for (v) |*e| {\n e.key = try r.string();\n e.value = %s;\n }\n return v;", g.typ(r.elem()), g.read(r.elem(), "r"))
|
||||
case Pointer:
|
||||
enc = fmt.Sprintf(" if (v) |x| {\n w.boolean(true);\n %s\n } else {\n w.boolean(false);\n }", g.write(r.elem(), "w", "x"))
|
||||
dec = fmt.Sprintf(" if (!try r.boolean()) return null;\n return %s;", g.read(r.elem(), "r"))
|
||||
case StructType:
|
||||
mod := r.module()
|
||||
s := mod.structNamed(r.t.Name)
|
||||
if len(s.Fields) == 0 {
|
||||
enc, dec = " _ = v;\n w.boolean(false);", " _ = try r.boolean();\n return .{};"
|
||||
break
|
||||
}
|
||||
var es, ds []string
|
||||
for _, f := range s.Fields {
|
||||
fr := ref{f.Type, mod}
|
||||
n := zigField(f.Name)
|
||||
es = append(es, " "+g.write(fr, "w", "v."+n))
|
||||
ds = append(ds, " ."+n+" = "+g.read(fr, "r")+",")
|
||||
}
|
||||
enc = strings.Join(es, "\n")
|
||||
dec = " return .{\n" + strings.Join(ds, "\n") + "\n };"
|
||||
case EnumType:
|
||||
e := r.module().enumNamed(r.t.Name)
|
||||
if e.String {
|
||||
enc = " w.string(v.value());"
|
||||
dec = fmt.Sprintf(" return %s.fromValue(try r.string()) orelse error.Go;", T)
|
||||
} else {
|
||||
enc = " w.int(v.value());"
|
||||
dec = fmt.Sprintf(" return %s.fromValue(try r.int()) orelse error.Go;", T)
|
||||
}
|
||||
}
|
||||
g.p("\nfn enc_%s(w: *Writer, v: %s) void {\n%s\n}\n", name, T, enc)
|
||||
g.p("\nfn dec_%s(r: *Reader) Error!%s {\n%s\n}\n", name, T, dec)
|
||||
}
|
||||
}
|
||||
|
||||
// readArgs returns the statements reading a method's arguments from the
|
||||
// reader a, as p0, p1 …, the expressions the implementation takes them as,
|
||||
// and the statements releasing them once the call returns.
|
||||
func (g *zigGen) readArgs(it *Interface, m *Method) (stmts, vals, after []string) {
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("p%d", i)
|
||||
stmts = append(stmts, "const "+v+" = "+g.read(ref{p.Type, g.m}, "a")+";")
|
||||
switch p.Type.Kind {
|
||||
case InterfaceType:
|
||||
if p.Type.Iface.ByGo {
|
||||
f := fmt.Sprintf("f%d", i)
|
||||
stmts = append(stmts, "const "+f+": "+p.Type.Name+" = .{ .f = try GoFunc.new("+v+") };")
|
||||
after = append(after, f+".release();")
|
||||
v = f
|
||||
} else {
|
||||
v = "try obj" + p.Type.Name + "(" + v + ")"
|
||||
}
|
||||
case Func:
|
||||
f := fmt.Sprintf("f%d", i)
|
||||
stmts = append(stmts, "const "+f+": "+funcType(it, m, p)+" = .{ .f = try GoFunc.new("+v+") };")
|
||||
after = append(after, f+".release();")
|
||||
v = f
|
||||
}
|
||||
vals = append(vals, v)
|
||||
}
|
||||
return stmts, vals, after
|
||||
}
|
||||
|
||||
func (g *zigGen) factory(it *Interface) {
|
||||
g.p("\nexport fn %s(obj: u64, args: ?[*]const u8, n: usize, call: u64) ?[*]u8 {\n _ = call;\n return run(obj, args, n, struct {\n fn body(arena: Allocator, w: *Writer, h: u64, a: *Reader) Error!void {\n _ = arena;\n _ = h;\n _ = a;\n const v: %s = try impl.make%s();\n w.uint(try retain(.{ .%s = v }));\n }\n }.body);\n}\n", g.sym("new_"+it.Name), it.Name, it.Name, it.Name)
|
||||
}
|
||||
|
||||
func (g *zigGen) entry(it *Interface, m *Method) {
|
||||
name := it.Name + "_" + m.Name
|
||||
if direct(m) {
|
||||
g.direct(it, m)
|
||||
return
|
||||
}
|
||||
stmts, vals, after := g.readArgs(it, m)
|
||||
head := []string{"const o = try obj" + it.Name + "(h);"}
|
||||
head = append(head, stmts...)
|
||||
for _, a := range after {
|
||||
head = append(head, "defer "+a)
|
||||
}
|
||||
if len(m.Params) == 0 {
|
||||
head = append(head, "_ = a;")
|
||||
}
|
||||
args := append([]string{"arena"}, vals...)
|
||||
if m.Ctx {
|
||||
args = append([]string{"arena", "ctx"}, vals...)
|
||||
}
|
||||
call := "o." + zigMethod(m.Name) + "(" + strings.Join(args, ", ") + ")"
|
||||
g.p("\nexport fn %s(obj: u64, args: ?[*]const u8, n: usize, call: u64) ?[*]u8 {\n", g.sym(name))
|
||||
indent := "\n "
|
||||
switch {
|
||||
case m.Stream != 0:
|
||||
E := g.typ(ref{m.Result, g.m})
|
||||
if !m.Ctx {
|
||||
head = append(head, "_ = ctx;")
|
||||
}
|
||||
g.p(" return stream(%s, call, obj, args, n, struct {\n fn make(arena: Allocator, ctx: *Context, h: u64, a: *Reader) Error!Iterator(%s) {%s%s\n return %s;\n }\n }.make, struct {\n fn enc(w: *Writer, v: %s) void {\n %s\n }\n }.enc);\n}\n", E, E, indent, strings.Join(head, indent), call, E, g.streamEnc(m.Result))
|
||||
return
|
||||
case m.Async():
|
||||
body := "_ = try " + call + ";"
|
||||
if !m.Err {
|
||||
body = "_ = " + call + ";"
|
||||
}
|
||||
if m.Result != nil {
|
||||
q := "try "
|
||||
if !m.Err {
|
||||
q = ""
|
||||
}
|
||||
body = "const r = " + q + call + ";" + indent + g.write(ref{m.Result, g.m}, "w", "r")
|
||||
} else {
|
||||
body += indent + "_ = w;"
|
||||
}
|
||||
g.p(" return start(call, obj, args, n, struct {\n fn body(arena: Allocator, ctx: *Context, w: *Writer, h: u64, a: *Reader) Error!void {%s%s%s%s\n }\n }.body);\n}\n", indent, strings.Join(head, indent), indent, body)
|
||||
return
|
||||
}
|
||||
q := ""
|
||||
if m.Err {
|
||||
q = "try "
|
||||
}
|
||||
var body string
|
||||
switch {
|
||||
case m.Closer:
|
||||
body = "const r = try " + call + ";" + indent + "w.uint(try retain(.{ .Closer = r }));"
|
||||
case m.Result != nil:
|
||||
body = "const r = " + q + call + ";" + indent + g.write(ref{m.Result, g.m}, "w", "r")
|
||||
default:
|
||||
body = "_ = w;" + indent + q + call + ";"
|
||||
if !m.Err {
|
||||
body = "_ = w;" + indent + call + ";"
|
||||
}
|
||||
}
|
||||
g.p(" _ = call;\n return run(obj, args, n, struct {\n fn body(arena: Allocator, w: *Writer, h: u64, a: *Reader) Error!void {%s%s%s%s\n }\n }.body);\n}\n", indent, strings.Join(head, indent), indent, body)
|
||||
}
|
||||
|
||||
// streamEnc is the statement writing v, a value of a stream, to w, in a
|
||||
// function that returns nothing.
|
||||
func (g *zigGen) streamEnc(t *Type) string {
|
||||
if t.Kind == InterfaceType {
|
||||
return "w.uint(retain(.{ ." + t.Name + " = v }) catch 0);"
|
||||
}
|
||||
return g.write(ref{t, g.m}, "w", "v")
|
||||
}
|
||||
|
||||
// direct writes the C function of a method of numbers (see direct).
|
||||
func (g *zigGen) direct(it *Interface, m *Method) {
|
||||
name := it.Name + "_" + m.Name + "_direct"
|
||||
var params, vals []string
|
||||
for i, p := range m.Params {
|
||||
v := fmt.Sprintf("p%d", i)
|
||||
params = append(params, v+": u64")
|
||||
t := p.Type
|
||||
switch {
|
||||
case t.Kind == Bool:
|
||||
v += " != 0"
|
||||
case t.Kind == Float && t.Bits == 32:
|
||||
v = "@as(f32, @floatCast(@as(f64, @bitCast(" + v + "))))"
|
||||
case t.Kind == Float:
|
||||
v = "@as(f64, @bitCast(" + v + "))"
|
||||
case t.Unsigned:
|
||||
v = "@as(" + g.typ(ref{t, g.m}) + ", @truncate(" + v + "))"
|
||||
default:
|
||||
v = "@as(" + g.typ(ref{t, g.m}) + ", @truncate(@as(i64, @bitCast(" + v + "))))"
|
||||
}
|
||||
vals = append(vals, v)
|
||||
}
|
||||
g.p("\nexport fn %s(obj: u64%s) u64 {\n const o = obj%s(obj) catch return 0;\n var state = std.heap.ArenaAllocator.init(allocator);\n defer state.deinit();\n", g.sym(name), prefixComma(params), it.Name)
|
||||
call := "o." + zigMethod(m.Name) + "(" + strings.Join(append([]string{"state.allocator()"}, vals...), ", ") + ")"
|
||||
t := m.Result
|
||||
switch {
|
||||
case t == nil:
|
||||
g.p(" %s;\n return 0;\n", call)
|
||||
case t.Kind == Bool:
|
||||
g.p(" return @intFromBool(%s);\n", call)
|
||||
case t.Kind == Float && t.Bits == 32:
|
||||
g.p(" return @bitCast(@as(f64, %s));\n", call)
|
||||
case t.Kind == Float:
|
||||
g.p(" return @bitCast(%s);\n", call)
|
||||
case t.Unsigned:
|
||||
g.p(" return @as(u64, %s);\n", call)
|
||||
default:
|
||||
g.p(" return @bitCast(@as(i64, %s));\n", call)
|
||||
}
|
||||
g.p("}\n")
|
||||
}
|
||||
|
||||
// objects writes the objects of the implementation that Go holds, by
|
||||
// their handles.
|
||||
func (g *zigGen) objects() {
|
||||
g.p("\n/// An object of the implementation that Go holds, by its handle.\nconst Obj = union(enum) {\n")
|
||||
for _, it := range g.m.Interfaces {
|
||||
if !it.ByGo {
|
||||
g.p(" %s: %s,\n", it.Name, it.Name)
|
||||
}
|
||||
}
|
||||
g.p(" Closer: Closer,\n\n fn deinit(o: Obj) void {\n switch (o) {\n inline else => |v| if (v.vtable.deinit) |d| d(v.ptr),\n }\n }\n\n fn close(o: Obj) Error!void {\n switch (o) {\n")
|
||||
for _, it := range g.m.Interfaces {
|
||||
if !it.ByGo && it.Closer {
|
||||
g.p(" .%s => |v| try v.close(),\n", it.Name)
|
||||
}
|
||||
}
|
||||
g.p(" .Closer => |v| try v.close(),\n else => {},\n }\n }\n};\n")
|
||||
for _, it := range g.m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
g.p("\nfn obj%s(h: u64) Error!%s {\n return switch ((try object(h)).*) {\n .%s => |v| v,\n else => error.Go,\n };\n}\n", it.Name, it.Name, it.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *zigGen) common() {
|
||||
g.p(`
|
||||
export fn %s(obj: u64, args: ?[*]const u8, n: usize, call: u64) ?[*]u8 {
|
||||
_ = call;
|
||||
return run(obj, args, n, struct {
|
||||
fn body(arena: Allocator, w: *Writer, h: u64, a: *Reader) Error!void {
|
||||
_ = arena;
|
||||
_ = w;
|
||||
_ = a;
|
||||
try (try object(h)).close();
|
||||
}
|
||||
}.body);
|
||||
}
|
||||
|
||||
export fn %s(obj: u64) void {
|
||||
const o = object(obj) catch return;
|
||||
o.deinit();
|
||||
allocator.destroy(o);
|
||||
}
|
||||
|
||||
export fn %s(call: u64) void {
|
||||
cancel(call);
|
||||
}
|
||||
|
||||
export fn %s(call: u64) void {
|
||||
demand(call);
|
||||
}
|
||||
|
||||
export fn %s(cont: u64, block: ?[*]u8) void {
|
||||
resumeCall(cont, block);
|
||||
}
|
||||
`, g.sym("close"), g.sym("release"), g.sym("cancel"), g.sym("next"), g.sym("resume"))
|
||||
}
|
||||
|
||||
// stubZig is an implementation in Zig whose every method says it is
|
||||
// unsupported, to fill in one at a time.
|
||||
func stubZig(m *Module) []byte {
|
||||
var b bytes.Buffer
|
||||
g := &zigGen{m: m, b: &b, w: newWire(m)}
|
||||
g.p("//! The implementation of package %s in Zig. Implement the methods one at\n//! a time: each says it is unsupported until it does.\n\nconst std = @import(\"std\");\nconst mygo = @import(\"mygo.zig\");\nconst Allocator = std.mem.Allocator;\n", m.Package)
|
||||
for _, it := range m.Interfaces {
|
||||
if it.ByGo {
|
||||
continue
|
||||
}
|
||||
class := "Native" + it.Name
|
||||
if it.Entry {
|
||||
g.p("\npub fn make%s() mygo.Error!mygo.%s {\n const v = try mygo.allocator.create(%s);\n v.* = .{};\n return mygo.%s.of(v);\n}\n", it.Name, it.Name, class, it.Name)
|
||||
}
|
||||
g.p("\nconst %s = struct {\n pub fn deinit(self: *%s) void {\n mygo.allocator.destroy(self);\n }\n", class, class)
|
||||
for _, me := range it.Methods {
|
||||
ps := g.params(it, me, true)
|
||||
var unused []string
|
||||
for _, p := range ps {
|
||||
unused = append(unused, "_ = "+p[:strings.Index(p, ": ")]+";")
|
||||
}
|
||||
for i := range ps {
|
||||
ps[i] = qualify(ps[i])
|
||||
}
|
||||
ret := qualify(g.ret(me))
|
||||
var body string
|
||||
switch {
|
||||
case me.Close:
|
||||
body = ""
|
||||
case me.Stream != 0, me.Closer, me.Err:
|
||||
body = "return error.Unsupported;"
|
||||
case me.Result == nil:
|
||||
body = ""
|
||||
default:
|
||||
body = "@panic(\"" + it.Name + "." + me.Name + " is not implemented\");"
|
||||
}
|
||||
g.p("\n pub fn %s(%s) %s {\n _ = self;\n", zigMethod(me.Name), strings.Join(append([]string{"self: *" + class}, ps...), ", "), ret)
|
||||
for _, u := range unused {
|
||||
g.p(" %s\n", u)
|
||||
}
|
||||
if body != "" {
|
||||
g.p(" %s\n", body)
|
||||
}
|
||||
g.p(" }\n")
|
||||
}
|
||||
g.p("};\n")
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
var zigTypeName = regexp.MustCompile(`\b([A-Z][A-Za-z0-9_]*)\b`)
|
||||
|
||||
// qualify names the declarations of mygo.zig in a type, from the
|
||||
// implementation.
|
||||
func qualify(s string) string {
|
||||
return zigTypeName.ReplaceAllStringFunc(s, func(n string) string { return "mygo." + n })
|
||||
}
|
||||
|
||||
const zigBuildTemplate = `const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
const module = b.createModule(.{
|
||||
.root_source_file = b.path("src/mygo.zig"),
|
||||
.target = b.standardTargetOptions(.{}),
|
||||
.optimize = b.standardOptimizeOption(.{}),
|
||||
.link_libc = true,
|
||||
});
|
||||
b.installArtifact(b.addLibrary(.{ .name = "MODULE", .linkage = .dynamic, .root_module = module }));
|
||||
}
|
||||
`
|
||||
+755
@@ -0,0 +1,755 @@
|
||||
package nativegen
|
||||
|
||||
// zigSupport is the part of the generated Zig that is the same for every
|
||||
// module: the types the implementation uses (Time, Rect, Buffer, Entry,
|
||||
// Iterator, Closer, Context) and the runtime of the glue, with the
|
||||
// standard library only.
|
||||
const zigSupport = `
|
||||
// Types for the implementation.
|
||||
|
||||
/// The allocator of what outlives a call: the C library's.
|
||||
pub const allocator = std.heap.c_allocator;
|
||||
|
||||
/// The Io the implementation sleeps and waits with.
|
||||
pub fn io() std.Io {
|
||||
return std.Io.Threaded.global_single_threaded.io();
|
||||
}
|
||||
|
||||
/// A time: Unix seconds and nanoseconds, as a time.Time.
|
||||
pub const Time = struct {
|
||||
sec: i64 = 0,
|
||||
nsec: i64 = 0,
|
||||
|
||||
/// The time plus ns nanoseconds.
|
||||
pub fn add(t: Time, ns: i64) Time {
|
||||
const total = @as(i128, t.sec) * std.time.ns_per_s + t.nsec + ns;
|
||||
return .{ .sec = @intCast(@divFloor(total, std.time.ns_per_s)), .nsec = @intCast(@mod(total, std.time.ns_per_s)) };
|
||||
}
|
||||
};
|
||||
|
||||
/// A rectangle of native UI: a ui.Rect.
|
||||
pub const Rect = struct {
|
||||
x: f32 = 0,
|
||||
y: f32 = 0,
|
||||
w: f32 = 0,
|
||||
h: f32 = 0,
|
||||
};
|
||||
|
||||
/// Memory of Go's that the implementation fills: a *native.Buffer, valid
|
||||
/// during the call that takes it.
|
||||
pub const Buffer = struct {
|
||||
ptr: ?[*]u8,
|
||||
len: usize,
|
||||
|
||||
pub fn bytes(b: Buffer) []u8 {
|
||||
const p = b.ptr orelse return &.{};
|
||||
return p[0..b.len];
|
||||
}
|
||||
};
|
||||
|
||||
/// An entry of a map of Go's, whose keys are strings.
|
||||
pub fn Entry(comptime V: type) type {
|
||||
return struct {
|
||||
key: []const u8,
|
||||
value: V,
|
||||
};
|
||||
}
|
||||
|
||||
/// The values a method yields, which Go asks for one at a time, on a thread
|
||||
/// of their own. Make one of a pointer with of: its type has
|
||||
///
|
||||
/// pub fn next(self: *T, arena: Allocator) Error!?V
|
||||
///
|
||||
/// which returns null at the end, and may have deinit, which runs once Go
|
||||
/// is done with the values, for what the method allocated with allocator.
|
||||
pub fn Iterator(comptime V: type) type {
|
||||
return struct {
|
||||
ptr: *anyopaque,
|
||||
nextFn: *const fn (*anyopaque, Allocator) Error!?V,
|
||||
deinitFn: ?*const fn (*anyopaque) void,
|
||||
|
||||
pub fn of(pointer: anytype) @This() {
|
||||
const T = @typeInfo(@TypeOf(pointer)).pointer.child;
|
||||
const vt = struct {
|
||||
fn vt_next(o: *anyopaque, arena: Allocator) Error!?V {
|
||||
return @as(*T, @ptrCast(@alignCast(o))).next(arena);
|
||||
}
|
||||
fn vt_deinit(o: *anyopaque) void {
|
||||
if (@hasDecl(T, "deinit")) @as(*T, @ptrCast(@alignCast(o))).deinit();
|
||||
}
|
||||
};
|
||||
comptime checkMethod(T, "Iterator", "next", fn (*T, Allocator) Error!?V);
|
||||
return .{ .ptr = pointer, .nextFn = vt.vt_next, .deinitFn = if (@hasDecl(T, "deinit")) vt.vt_deinit else null };
|
||||
}
|
||||
|
||||
pub fn next(self: @This(), arena: Allocator) Error!?V {
|
||||
return self.nextFn(self.ptr, arena);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// What stops what a method started, as Go's io.Closer. Make one of a
|
||||
/// pointer with of: its type has
|
||||
///
|
||||
/// pub fn close(self: *T) Error!void
|
||||
///
|
||||
/// and may have deinit, which runs once Go lets go of the Closer.
|
||||
pub const Closer = struct {
|
||||
ptr: *anyopaque,
|
||||
vtable: *const VTable,
|
||||
|
||||
pub const VTable = struct {
|
||||
close: *const fn (*anyopaque) Error!void,
|
||||
deinit: ?*const fn (*anyopaque) void,
|
||||
};
|
||||
|
||||
pub fn of(pointer: anytype) Closer {
|
||||
const T = @typeInfo(@TypeOf(pointer)).pointer.child;
|
||||
const vt = struct {
|
||||
fn vt_close(o: *anyopaque) Error!void {
|
||||
return @as(*T, @ptrCast(@alignCast(o))).close();
|
||||
}
|
||||
fn vt_deinit(o: *anyopaque) void {
|
||||
if (@hasDecl(T, "deinit")) @as(*T, @ptrCast(@alignCast(o))).deinit();
|
||||
}
|
||||
const table: VTable = .{ .close = vt_close, .deinit = if (@hasDecl(T, "deinit")) vt_deinit else null };
|
||||
};
|
||||
comptime checkMethod(T, "Closer", "close", fn (*T) Error!void);
|
||||
return .{ .ptr = pointer, .vtable = &vt.table };
|
||||
}
|
||||
|
||||
pub fn close(self: Closer) Error!void {
|
||||
return self.vtable.close(self.ptr);
|
||||
}
|
||||
};
|
||||
|
||||
/// The context of a method that takes one in Go: Go cancels it.
|
||||
pub const Context = struct {
|
||||
canceled: std.atomic.Value(bool) = .init(false),
|
||||
|
||||
/// Reports whether Go canceled the call.
|
||||
pub fn isCanceled(c: *Context) bool {
|
||||
return c.canceled.load(.acquire);
|
||||
}
|
||||
|
||||
/// Returns error.Canceled once Go canceled the call.
|
||||
pub fn check(c: *Context) Error!void {
|
||||
if (c.isCanceled()) return error.Canceled;
|
||||
}
|
||||
|
||||
/// Waits ns nanoseconds, or until Go cancels the call, which returns
|
||||
/// error.Canceled.
|
||||
pub fn sleep(c: *Context, ns: i64) Error!void {
|
||||
var left = ns;
|
||||
while (left > 0) {
|
||||
try c.check();
|
||||
const step = @min(left, 2 * std.time.ns_per_ms);
|
||||
io().sleep(.fromNanoseconds(step), .awake) catch {};
|
||||
left -= step;
|
||||
}
|
||||
try c.check();
|
||||
}
|
||||
};
|
||||
|
||||
threadlocal var detail_domain: [256]u8 = undefined;
|
||||
threadlocal var detail_domain_len: usize = 0;
|
||||
threadlocal var detail_message: [1024]u8 = undefined;
|
||||
threadlocal var detail_message_len: usize = 0;
|
||||
threadlocal var detail_number: i64 = 0;
|
||||
|
||||
fn setDetail(domain: []const u8, number: i64, msg: []const u8) void {
|
||||
detail_domain_len = @min(domain.len, detail_domain.len);
|
||||
@memcpy(detail_domain[0..detail_domain_len], domain[0..detail_domain_len]);
|
||||
detail_message_len = @min(msg.len, detail_message.len);
|
||||
@memcpy(detail_message[0..detail_message_len], msg[0..detail_message_len]);
|
||||
detail_number = number;
|
||||
}
|
||||
|
||||
/// Returns error.Other, which Go reports with the domain, number and message
|
||||
/// given.
|
||||
pub fn fail(domain: []const u8, number: i64, msg: []const u8) Error {
|
||||
setDetail(domain, number, msg);
|
||||
return error.Other;
|
||||
}
|
||||
|
||||
/// Returns error.Go, which Go reports with the message given.
|
||||
pub fn failGo(msg: []const u8) Error {
|
||||
setDetail("", 0, msg);
|
||||
return error.Go;
|
||||
}
|
||||
|
||||
/// The message of the last error.Go or error.Other of this thread, as a
|
||||
/// function of Go's returned it.
|
||||
pub fn message() []const u8 {
|
||||
return detail_message[0..detail_message_len];
|
||||
}
|
||||
|
||||
/// Checks at compile time that T has the method name of type Want.
|
||||
pub fn checkMethod(comptime T: type, comptime iface: []const u8, comptime name: []const u8, comptime Want: type) void {
|
||||
if (!@hasDecl(T, name)) {
|
||||
@compileError(@typeName(T) ++ " implements " ++ iface ++ " without pub fn " ++ name ++ ": " ++ @typeName(Want));
|
||||
}
|
||||
const Have = @TypeOf(@field(T, name));
|
||||
if (Have != Want) {
|
||||
@compileError(@typeName(T) ++ "." ++ name ++ " is " ++ @typeName(Have) ++ ", but " ++ iface ++ " wants " ++ @typeName(Want));
|
||||
}
|
||||
}
|
||||
|
||||
// The runtime of the glue.
|
||||
|
||||
const Callback = *const fn (u64, u64, i64, ?[*]const u8, usize) callconv(.c) ?[*]u8;
|
||||
const Malloc = *const fn (usize) callconv(.c) ?[*]u8;
|
||||
const Free = *const fn (?[*]u8) callconv(.c) void;
|
||||
|
||||
var runtime: struct {
|
||||
cb: ?Callback = null,
|
||||
id_base: u64 = 0,
|
||||
malloc: ?Malloc = null,
|
||||
free: ?Free = null,
|
||||
} = .{};
|
||||
|
||||
const kind_result: u64 = 1;
|
||||
const kind_item: u64 = 2;
|
||||
const kind_notify: u64 = 3;
|
||||
const kind_ask: u64 = 4;
|
||||
const kind_release: u64 = 5;
|
||||
const kind_invoke: u64 = 6;
|
||||
const kind_invoke_async: u64 = 7;
|
||||
const kind_cancel: u64 = 8;
|
||||
|
||||
const status_ok: i64 = 0;
|
||||
const status_error: i64 = 1;
|
||||
const status_pending: i64 = 2;
|
||||
const status_end: i64 = 3;
|
||||
|
||||
// Values cross in a binary encoding, which package native describes, in
|
||||
// the order of the declarations: every integer as 8 bytes, little-endian,
|
||||
// floats as f64, bools as a byte, strings, slices and maps as their length
|
||||
// then their contents, optionals as a bool then the value, structs as their
|
||||
// fields, enums as their values.
|
||||
|
||||
/// Writes values for Go, after the 16 bytes of a block's head: its status
|
||||
/// and its length.
|
||||
const Writer = struct {
|
||||
b: std.ArrayList(u8) = .empty,
|
||||
|
||||
fn init() Writer {
|
||||
var w: Writer = .{};
|
||||
w.b.appendNTimes(allocator, 0, 16) catch @panic("out of memory");
|
||||
return w;
|
||||
}
|
||||
|
||||
fn deinit(w: *Writer) void {
|
||||
w.b.deinit(allocator);
|
||||
}
|
||||
|
||||
fn reset(w: *Writer) void {
|
||||
w.b.shrinkRetainingCapacity(16);
|
||||
}
|
||||
|
||||
fn data(w: *Writer) []const u8 {
|
||||
return w.b.items[16..];
|
||||
}
|
||||
|
||||
fn raw(w: *Writer, v: []const u8) void {
|
||||
w.b.appendSlice(allocator, v) catch @panic("out of memory");
|
||||
}
|
||||
|
||||
fn uint(w: *Writer, v: u64) void {
|
||||
var buf: [8]u8 = undefined;
|
||||
std.mem.writeInt(u64, &buf, v, .little);
|
||||
w.raw(&buf);
|
||||
}
|
||||
|
||||
fn int(w: *Writer, v: i64) void {
|
||||
w.uint(@bitCast(v));
|
||||
}
|
||||
|
||||
fn byte(w: *Writer, v: u8) void {
|
||||
w.raw(&.{v});
|
||||
}
|
||||
|
||||
fn boolean(w: *Writer, v: bool) void {
|
||||
w.byte(@intFromBool(v));
|
||||
}
|
||||
|
||||
fn float(w: *Writer, v: f64) void {
|
||||
w.uint(@bitCast(v));
|
||||
}
|
||||
|
||||
fn count(w: *Writer, n: usize) void {
|
||||
w.int(@intCast(n));
|
||||
}
|
||||
|
||||
fn string(w: *Writer, s: []const u8) void {
|
||||
w.count(s.len);
|
||||
w.raw(s);
|
||||
}
|
||||
|
||||
fn time(w: *Writer, t: Time) void {
|
||||
w.int(t.sec);
|
||||
w.int(t.nsec);
|
||||
}
|
||||
|
||||
fn rect(w: *Writer, r: Rect) void {
|
||||
w.float(r.x);
|
||||
w.float(r.y);
|
||||
w.float(r.w);
|
||||
w.float(r.h);
|
||||
}
|
||||
|
||||
fn buffer(w: *Writer, b: Buffer) void {
|
||||
w.uint(@intFromPtr(b.ptr));
|
||||
w.count(b.len);
|
||||
}
|
||||
|
||||
/// Gives the values to Go as a block, in memory Go frees.
|
||||
fn block(w: *Writer, status: i64) ?[*]u8 {
|
||||
const items = w.b.items;
|
||||
std.mem.writeInt(i64, items[0..8], status, .little);
|
||||
std.mem.writeInt(i64, items[8..16], @intCast(items.len - 16), .little);
|
||||
const p = runtime.malloc.?(items.len) orelse return null;
|
||||
@memcpy(p[0..items.len], items);
|
||||
return p;
|
||||
}
|
||||
};
|
||||
|
||||
/// Reads the values Go wrote, into the arena.
|
||||
const Reader = struct {
|
||||
b: []const u8,
|
||||
arena: Allocator,
|
||||
|
||||
fn take(r: *Reader, n: usize) Error![]const u8 {
|
||||
if (n > r.b.len) return failGo("a value from Go ends early");
|
||||
const v = r.b[0..n];
|
||||
r.b = r.b[n..];
|
||||
return v;
|
||||
}
|
||||
|
||||
fn uint(r: *Reader) Error!u64 {
|
||||
return std.mem.readInt(u64, (try r.take(8))[0..8], .little);
|
||||
}
|
||||
|
||||
fn int(r: *Reader) Error!i64 {
|
||||
return @bitCast(try r.uint());
|
||||
}
|
||||
|
||||
fn byte(r: *Reader) Error!u8 {
|
||||
return (try r.take(1))[0];
|
||||
}
|
||||
|
||||
fn boolean(r: *Reader) Error!bool {
|
||||
return try r.byte() != 0;
|
||||
}
|
||||
|
||||
fn float(r: *Reader) Error!f64 {
|
||||
return @bitCast(try r.uint());
|
||||
}
|
||||
|
||||
/// Reads the length of a slice or a map, whose elements take a byte
|
||||
/// each at least.
|
||||
fn count(r: *Reader) Error!usize {
|
||||
const n = try r.int();
|
||||
if (n < 0 or n > r.b.len) return failGo("a value from Go ends early");
|
||||
return @intCast(n);
|
||||
}
|
||||
|
||||
fn string(r: *Reader) Error![]const u8 {
|
||||
return r.arena.dupe(u8, try r.take(try r.count()));
|
||||
}
|
||||
|
||||
fn time(r: *Reader) Error!Time {
|
||||
return .{ .sec = try r.int(), .nsec = try r.int() };
|
||||
}
|
||||
|
||||
fn rect(r: *Reader) Error!Rect {
|
||||
return .{
|
||||
.x = @floatCast(try r.float()),
|
||||
.y = @floatCast(try r.float()),
|
||||
.w = @floatCast(try r.float()),
|
||||
.h = @floatCast(try r.float()),
|
||||
};
|
||||
}
|
||||
|
||||
fn buffer(r: *Reader) Error!Buffer {
|
||||
const p = try r.uint();
|
||||
const n = try r.int();
|
||||
return .{ .ptr = @ptrFromInt(p), .len = @intCast(@max(n, 0)) };
|
||||
}
|
||||
};
|
||||
|
||||
fn bytesOf(p: ?[*]const u8, n: usize) []const u8 {
|
||||
const q = p orelse return &.{};
|
||||
return q[0..n];
|
||||
}
|
||||
|
||||
// The kinds of errors, as they cross both ways: the kind, then the code,
|
||||
// domain, number and message.
|
||||
const err_other: u8 = 0;
|
||||
const err_code: u8 = 1;
|
||||
const err_unsupported: u8 = 2;
|
||||
const err_closed: u8 = 3;
|
||||
const err_canceled: u8 = 4;
|
||||
const err_go: u8 = 5;
|
||||
|
||||
fn writeError(w: *Writer, e: Error) void {
|
||||
var kind = err_other;
|
||||
var code: []const u8 = "";
|
||||
var domain: []const u8 = "";
|
||||
var msg: []const u8 = "";
|
||||
var number: i64 = 0;
|
||||
if (errorCode(e)) |c| {
|
||||
kind = err_code;
|
||||
code = c;
|
||||
} else switch (e) {
|
||||
error.Unsupported => kind = err_unsupported,
|
||||
error.Closed => kind = err_closed,
|
||||
error.Canceled => kind = err_canceled,
|
||||
error.Go => {
|
||||
kind = err_go;
|
||||
msg = message();
|
||||
},
|
||||
error.OutOfMemory => msg = "out of memory",
|
||||
else => {
|
||||
domain = detail_domain[0..detail_domain_len];
|
||||
number = detail_number;
|
||||
msg = message();
|
||||
},
|
||||
}
|
||||
w.byte(kind);
|
||||
w.string(code);
|
||||
w.string(domain);
|
||||
w.int(number);
|
||||
w.string(msg);
|
||||
}
|
||||
|
||||
fn readError(r: *Reader) Error {
|
||||
const kind = r.byte() catch return failGo("an error of Go's that does not decode");
|
||||
const code = r.string() catch return failGo("an error of Go's that does not decode");
|
||||
const domain = r.string() catch return failGo("an error of Go's that does not decode");
|
||||
const number = r.int() catch return failGo("an error of Go's that does not decode");
|
||||
const msg = r.string() catch return failGo("an error of Go's that does not decode");
|
||||
return switch (kind) {
|
||||
err_code => errorOfCode(code) orelse failGo(msg),
|
||||
err_unsupported => error.Unsupported,
|
||||
err_closed => error.Closed,
|
||||
err_canceled => error.Canceled,
|
||||
err_other => if (domain.len > 0) fail(domain, number, msg) else failGo(msg),
|
||||
else => failGo(msg),
|
||||
};
|
||||
}
|
||||
|
||||
const Body = fn (arena: Allocator, w: *Writer, h: u64, a: *Reader) Error!void;
|
||||
|
||||
/// Runs what returns at once, which writes its result to the writer.
|
||||
fn run(h: u64, args: ?[*]const u8, n: usize, comptime body: Body) ?[*]u8 {
|
||||
var state = std.heap.ArenaAllocator.init(allocator);
|
||||
defer state.deinit();
|
||||
var w = Writer.init();
|
||||
defer w.deinit();
|
||||
var r: Reader = .{ .b = bytesOf(args, n), .arena = state.allocator() };
|
||||
body(state.allocator(), &w, h, &r) catch |e| {
|
||||
w.reset();
|
||||
writeError(&w, e);
|
||||
return w.block(status_error);
|
||||
};
|
||||
return w.block(status_ok);
|
||||
}
|
||||
|
||||
/// The answer of a call that failed to start.
|
||||
fn failed(e: Error) ?[*]u8 {
|
||||
var w = Writer.init();
|
||||
defer w.deinit();
|
||||
writeError(&w, e);
|
||||
return w.block(status_error);
|
||||
}
|
||||
|
||||
fn pending() ?[*]u8 {
|
||||
var w = Writer.init();
|
||||
defer w.deinit();
|
||||
return w.block(status_pending);
|
||||
}
|
||||
|
||||
/// Tells Go something, with the values w holds, and returns its answer, a
|
||||
/// block to read with answer, if any.
|
||||
fn send(kind: u64, id: u64, status: i64, w: ?*Writer) ?[*]u8 {
|
||||
const cb = runtime.cb orelse return null;
|
||||
if (w) |v| {
|
||||
const d = v.data();
|
||||
if (d.len > 0) return cb(kind, id, status, d.ptr, d.len);
|
||||
}
|
||||
return cb(kind, id, status, null, 0);
|
||||
}
|
||||
|
||||
/// Reads a block Go answered with, into the arena, and frees it.
|
||||
fn answer(p: ?[*]u8, arena: Allocator, comptime R: type, comptime read: fn (*Reader) Error!R) Error!R {
|
||||
const b = p orelse return error.Closed;
|
||||
defer runtime.free.?(b);
|
||||
const status = std.mem.readInt(i64, b[0..8], .little);
|
||||
const n: usize = @intCast(std.mem.readInt(i64, b[8..16], .little));
|
||||
var r: Reader = .{ .b = b[16 .. 16 + n], .arena = arena };
|
||||
if (status == status_error) return readError(&r);
|
||||
return read(&r);
|
||||
}
|
||||
|
||||
fn retain(o: Obj) Error!u64 {
|
||||
const p = try allocator.create(Obj);
|
||||
p.* = o;
|
||||
return @intFromPtr(p);
|
||||
}
|
||||
|
||||
fn object(h: u64) Error!*Obj {
|
||||
if (h == 0) return error.Closed;
|
||||
return @ptrFromInt(h);
|
||||
}
|
||||
|
||||
/// A table of what Go refers to by an id, as calls by their call.
|
||||
fn Table(comptime V: type) type {
|
||||
return struct {
|
||||
mutex: std.Io.Mutex = .init,
|
||||
map: std.AutoHashMapUnmanaged(u64, V) = .empty,
|
||||
|
||||
fn put(t: *@This(), k: u64, v: V) Error!void {
|
||||
t.mutex.lockUncancelable(io());
|
||||
defer t.mutex.unlock(io());
|
||||
try t.map.put(allocator, k, v);
|
||||
}
|
||||
|
||||
fn remove(t: *@This(), k: u64) ?V {
|
||||
t.mutex.lockUncancelable(io());
|
||||
defer t.mutex.unlock(io());
|
||||
const kv = t.map.fetchRemove(k) orelse return null;
|
||||
return kv.value;
|
||||
}
|
||||
|
||||
/// Runs f with the value of k, if any, holding the table.
|
||||
fn with(t: *@This(), k: u64, comptime f: fn (V) void) void {
|
||||
t.mutex.lockUncancelable(io());
|
||||
defer t.mutex.unlock(io());
|
||||
if (t.map.get(k)) |v| f(v);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// An asynchronous call or a stream, running on a thread of its own.
|
||||
const Task = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
ctx: Context = .{},
|
||||
demand: std.Io.Semaphore = .{},
|
||||
call: u64,
|
||||
h: u64,
|
||||
args: []const u8 = &.{},
|
||||
|
||||
fn new(call: u64, h: u64, args: ?[*]const u8, n: usize) Error!*Task {
|
||||
const t = try allocator.create(Task);
|
||||
t.* = .{ .arena = .init(allocator), .call = call, .h = h };
|
||||
errdefer t.free();
|
||||
// The arguments are Go's during the call that starts the task only.
|
||||
t.args = try t.arena.allocator().dupe(u8, bytesOf(args, n));
|
||||
return t;
|
||||
}
|
||||
|
||||
fn free(t: *Task) void {
|
||||
t.arena.deinit();
|
||||
allocator.destroy(t);
|
||||
}
|
||||
};
|
||||
|
||||
/// The tasks of asynchronous calls and streams, by their call, which Go
|
||||
/// cancels.
|
||||
var tasks: Table(*Task) = .{};
|
||||
|
||||
fn cancel(call: u64) void {
|
||||
tasks.with(call, struct {
|
||||
fn f(t: *Task) void {
|
||||
t.ctx.canceled.store(true, .release);
|
||||
t.demand.post(io());
|
||||
}
|
||||
}.f);
|
||||
}
|
||||
|
||||
fn demand(call: u64) void {
|
||||
tasks.with(call, struct {
|
||||
fn f(t: *Task) void {
|
||||
t.demand.post(io());
|
||||
}
|
||||
}.f);
|
||||
}
|
||||
|
||||
const TaskBody = fn (arena: Allocator, ctx: *Context, w: *Writer, h: u64, a: *Reader) Error!void;
|
||||
|
||||
/// Starts an asynchronous call on a thread of its own, which reports its
|
||||
/// result through the callback.
|
||||
fn start(call: u64, h: u64, args: ?[*]const u8, n: usize, comptime body: TaskBody) ?[*]u8 {
|
||||
const t = Task.new(call, h, args, n) catch |e| return failed(e);
|
||||
tasks.put(call, t) catch |e| {
|
||||
t.free();
|
||||
return failed(e);
|
||||
};
|
||||
const th = std.Thread.spawn(.{}, struct {
|
||||
fn main(task: *Task) void {
|
||||
var w = Writer.init();
|
||||
defer w.deinit();
|
||||
var r: Reader = .{ .b = task.args, .arena = task.arena.allocator() };
|
||||
var status = status_ok;
|
||||
body(task.arena.allocator(), &task.ctx, &w, task.h, &r) catch |e| {
|
||||
w.reset();
|
||||
writeError(&w, e);
|
||||
status = status_error;
|
||||
};
|
||||
_ = tasks.remove(task.call);
|
||||
_ = send(kind_result, task.call, status, &w);
|
||||
task.free();
|
||||
}
|
||||
}.main, .{t}) catch {
|
||||
_ = tasks.remove(call);
|
||||
t.free();
|
||||
return failed(failGo("no thread for the call"));
|
||||
};
|
||||
th.detach();
|
||||
return pending();
|
||||
}
|
||||
|
||||
/// Starts a stream on a thread of its own, which yields a value each time
|
||||
/// Go asks for one.
|
||||
fn stream(
|
||||
comptime V: type,
|
||||
call: u64,
|
||||
h: u64,
|
||||
args: ?[*]const u8,
|
||||
n: usize,
|
||||
comptime make: fn (Allocator, *Context, u64, *Reader) Error!Iterator(V),
|
||||
comptime enc: fn (*Writer, V) void,
|
||||
) ?[*]u8 {
|
||||
const t = Task.new(call, h, args, n) catch |e| return failed(e);
|
||||
tasks.put(call, t) catch |e| {
|
||||
t.free();
|
||||
return failed(e);
|
||||
};
|
||||
const th = std.Thread.spawn(.{}, struct {
|
||||
fn main(task: *Task) void {
|
||||
defer task.free();
|
||||
defer _ = tasks.remove(task.call);
|
||||
var w = Writer.init();
|
||||
defer w.deinit();
|
||||
var r: Reader = .{ .b = task.args, .arena = task.arena.allocator() };
|
||||
const it = make(task.arena.allocator(), &task.ctx, task.h, &r) catch |e| {
|
||||
task.demand.waitUncancelable(io());
|
||||
writeError(&w, e);
|
||||
_ = send(kind_item, task.call, status_error, &w);
|
||||
return;
|
||||
};
|
||||
defer if (it.deinitFn) |d| d(it.ptr);
|
||||
var item = std.heap.ArenaAllocator.init(allocator);
|
||||
defer item.deinit();
|
||||
while (true) {
|
||||
task.demand.waitUncancelable(io());
|
||||
if (task.ctx.isCanceled()) return;
|
||||
_ = item.reset(.retain_capacity);
|
||||
w.reset();
|
||||
const v = it.next(item.allocator()) catch |e| {
|
||||
writeError(&w, e);
|
||||
_ = send(kind_item, task.call, status_error, &w);
|
||||
return;
|
||||
} orelse {
|
||||
_ = send(kind_item, task.call, status_end, null);
|
||||
return;
|
||||
};
|
||||
enc(&w, v);
|
||||
_ = send(kind_item, task.call, status_ok, &w);
|
||||
}
|
||||
}
|
||||
}.main, .{t}) catch {
|
||||
_ = tasks.remove(call);
|
||||
t.free();
|
||||
return failed(failGo("no thread for the stream"));
|
||||
};
|
||||
th.detach();
|
||||
return pending();
|
||||
}
|
||||
|
||||
/// A function or a value of Go's that the implementation holds, until the
|
||||
/// last of its holders releases it.
|
||||
const GoFunc = struct {
|
||||
id: u64,
|
||||
refs: std.atomic.Value(u32) = .init(1),
|
||||
|
||||
fn new(id: u64) Error!*GoFunc {
|
||||
if (id == 0) return failGo("Go passed nil for a function or a value");
|
||||
const f = try allocator.create(GoFunc);
|
||||
f.* = .{ .id = id };
|
||||
return f;
|
||||
}
|
||||
|
||||
fn retain(f: *GoFunc) void {
|
||||
_ = f.refs.fetchAdd(1, .monotonic);
|
||||
}
|
||||
|
||||
fn release(f: *GoFunc) void {
|
||||
if (f.refs.fetchSub(1, .acq_rel) == 1) {
|
||||
_ = send(kind_release, f.id, 0, null);
|
||||
allocator.destroy(f);
|
||||
}
|
||||
}
|
||||
|
||||
fn notify(f: *GoFunc, w: *Writer) void {
|
||||
_ = send(kind_notify, f.id, 0, w);
|
||||
}
|
||||
|
||||
fn ask(f: *GoFunc, arena: Allocator, w: *Writer, comptime R: type, comptime read: fn (*Reader) Error!R) Error!R {
|
||||
return answer(send(kind_ask, f.id, 0, w), arena, R, read);
|
||||
}
|
||||
};
|
||||
|
||||
/// Calls the method of a value of Go's that w names, with the arguments
|
||||
/// after it.
|
||||
fn invoke(id: u64, arena: Allocator, w: *Writer, comptime R: type, comptime read: fn (*Reader) Error!R) Error!R {
|
||||
return answer(send(kind_invoke, id, 0, w), arena, R, read);
|
||||
}
|
||||
|
||||
/// A call of a method of Go's that takes a context, waiting for Go's
|
||||
/// answer.
|
||||
const Cont = struct {
|
||||
event: std.Io.Event = .unset,
|
||||
block: ?[*]u8 = null,
|
||||
};
|
||||
|
||||
var conts: Table(*Cont) = .{};
|
||||
var last_id: std.atomic.Value(u64) = .init(0);
|
||||
|
||||
/// The id of a continuation: the module's index, from Go, in its high bits
|
||||
/// makes it unique among modules.
|
||||
fn nextId() u64 {
|
||||
return runtime.id_base | (last_id.fetchAdd(1, .monotonic) + 1);
|
||||
}
|
||||
|
||||
fn resumeCall(id: u64, block: ?[*]u8) void {
|
||||
const c = conts.remove(id) orelse {
|
||||
if (block) |b| runtime.free.?(b);
|
||||
return;
|
||||
};
|
||||
c.block = block;
|
||||
c.event.set(io());
|
||||
}
|
||||
|
||||
/// Calls a method of Go's that takes a context, which ctx cancels, and
|
||||
/// waits for its answer.
|
||||
fn invokeAsync(id: u64, arena: Allocator, ctx: *Context, w: *Writer, comptime R: type, comptime read: fn (*Reader) Error!R) Error!R {
|
||||
var c: Cont = .{};
|
||||
const cont = nextId();
|
||||
try conts.put(cont, &c);
|
||||
_ = send(kind_invoke_async, id, @bitCast(cont), w);
|
||||
var canceled = false;
|
||||
while (true) {
|
||||
c.event.waitTimeout(io(), .{ .duration = .{ .raw = .fromMilliseconds(10), .clock = .awake } }) catch {
|
||||
if (!canceled and ctx.isCanceled()) {
|
||||
canceled = true;
|
||||
_ = send(kind_cancel, cont, 0, null);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
break;
|
||||
}
|
||||
return answer(c.block, arena, R, read);
|
||||
}
|
||||
`
|
||||
Reference in new issue
Block a user