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")) }