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.
669 lines
21 KiB
Go
669 lines
21 KiB
Go
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 + ")"
|
|
}
|