// The generator's emitter for `android/`: a contract's channel → `.gen.kt`, everything of the // Android half that is not the plugin's own work (docs/plans/plugins-plan.md in core) — the twin of // emitSwift.ts, over the same lowered model: // - the contract's types as Kotlin (enum classes, data classes, sealed unions) with their wire codecs; // - `Code`: the codes the channel rejects with; // - `Events`: one function per event; // - `Plugin`: the INTERFACE the plugin implements — one method per call, a typed `Reply`; // - `Channel.register(engine, make)` + the glue that reads a call's arguments, refuses a // malformed one and hands the call over. // A HOST NODE (docs/plans/host-node-plan.md) has its own shape (emitNode below), the twin of // emitSwift's: `NodeEvents`, the interface `NodeInstance : HostNodeInstance` (a typed // setter per prop and per style, the measure, the methods) and `NodeGlue`. // It stands on the host SDK's PluginChannel.kt (Reply, PluginFile, Wire), its gl facade's Entity / // Scene3D (scene/GL.kt) and on the packed form's two ends (PackedReader, PackedWriter). The wire carries VALUES, PACKED, and the codecs read a // class straight out of the buffer and write one straight into it — no tree of org.json's objects // in between. A Uint8Array is a ByteArray, a File the handle of a host buffer; a `Json` member alone // is org.json's objects, because JSON is what a half does with it. // // A READER IS A CURSOR (`r`): a codec takes the value at the cursor and moves past it, so what it // reads is what comes next, in the order it was written — an object's members are met one by one // and told apart by their keys, a union by what the value at hand is. import { EmitError } from "./emitSdk" import { block, indent, text, wrap, writerName } from "./lines" import { channelLabel, propAsText, waysOf, wireClass, type L, type LChannel, type LDecl, type LField, type LNode, type Lowered, type Ways } from "./lower" const KEYWORDS = new Set([ "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", ]) const ident = (name: string): string => KEYWORDS.has(name) ? `\`${name}\`` : name /** A string of the contract as a Kotlin string: `$` would open a template. */ const str = (value: string): string => JSON.stringify(value).replace(/\$/g, "\\$") /** A string of the contract as a Kotlin constant: `"not-asked"`, `"notAsked"` → `NOT_ASKED`. */ const constName = (value: string): string => { const words = value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean) const name = words.map(w => w.toUpperCase()).join("_") return /^[A-Z_]/.test(name) ? name : `_${name}` } const doc = (text: string, indent = ""): string => { if (!text) return "" const lines = text.split("\n").map(l => l.trim()) if (lines.length === 1) return `${indent}/** ${lines[0]} */\n` return `${indent}/**\n${lines.map(l => `${indent} * ${l}`.trimEnd()).join("\n")}\n${indent} */\n` } export const kotlinType = (t: L): string => { switch (t.kind) { case "i32": return "Int" case "f64": return "Double" case "boolean": return "Boolean" case "string": return "String" case "json": return "Any" case "file": return "PluginFile" case "entity": return "Entity" case "scene3d": return "Scene3D" case "bytes": return "ByteArray" case "void": return "Unit" case "enum": case "struct": case "union": return t.name case "list": return `List<${kotlinType(t.of)}>` case "map": return `Map` case "optional": return `${kotlinType(t.of)}?` case "tuple": return `${t.of.length === 2 ? "Pair" : "Triple"}<${t.of.map(kotlinType).join(", ")}>` } } const TUPLE = ["first", "second", "third"] /** The expression of type `T?` that reads the value at the cursor of `r`, as lines: null = it is * not a T. */ const decode = (t: L, depth = 0): string[] => { const v = `v${depth}` switch (t.kind) { case "i32": return [`r.i32()`] case "f64": return [`r.f64()`] case "boolean": return [`r.bool()`] case "string": return [`r.string()`] case "json": return [`r.json()`] case "bytes": return [`r.bytes()`] case "file": return [`Wire.file(r)`] case "entity": return [`Entity.read(r)`] case "scene3d": return [`Scene3D.read(r)`] case "enum": case "struct": case "union": return [`${t.name}.read(r)`] case "list": return block(`r.list {`, decode(t.of, depth + 1), `}`) case "map": return block(`r.map {`, decode(t.of, depth + 1), `}`) case "optional": return decode(t.of, depth) case "tuple": return [ `r.tuple(${t.of.length}) {`, ...indent([ ...t.of.flatMap((m, i) => wrap(`val ${v}_${i} = `, decode(m, depth + 1), ` ?: return@tuple null`)), `${t.of.length === 2 ? "Pair" : "Triple"}(${t.of.map((_, i) => `${v}_${i}`).join(", ")})`, ]), `}`, ] case "void": throw new EmitError("void has no value to read") } } /** The statements that write the value `e` (a `T`) to the wire `w` (a PackedWriter), as lines. */ const encode = (t: L, e: string, w: string, depth = 0): string[] => { const v = `v${depth}` switch (t.kind) { case "i32": return [`${w}.i32(${e})`] case "f64": return [`${w}.f64(${e})`] case "boolean": return [`${w}.bool(${e})`] case "string": return [`${w}.string(${e})`] case "json": return [`${w}.json(${e})`] case "bytes": return [`${w}.bytes(${e})`] case "enum": return [`${w}.string(${e}.wire)`] case "file": case "entity": case "struct": case "union": return [`${e}.write(${w})`] case "scene3d": throw new EmitError("a Scene3D crosses from the app to the host only") case "list": return [`${w}.beginArray()`, ...block(`for (${v} in ${e}) {`, encode(t.of, v, w, depth + 1), `}`), `${w}.end()`] case "map": return [`${w}.beginObject()`, `for ((k${depth}, ${v}) in ${e}) {`, ...indent([`${w}.key(k${depth})`, ...encode(t.of, v, w, depth + 1)]), `}`, `${w}.end()`] case "tuple": return [`${w}.beginArray()`, ...t.of.flatMap((m, i) => encode(m, `${e}.${TUPLE[i]}`, w, depth + 1)), `${w}.end()`] case "optional": { const some = encode(t.of, v, w, depth + 1) const one = `${e}.let { ${v} -> if (${v} != null) ${some[0]} else ${w}.nil() }` return some.length === 1 && one.length <= 100 ? [one] : [`${e}.let { ${v} ->`, ...indent([`if (${v} != null) {`, ...indent(some), `} else {`, ...indent([`${w}.nil()`]), `}`]), `}`] } case "void": throw new EmitError("void has no value to write") } } /** A value under its key: on the key's line when it is one plain statement. */ const keyed = (key: string, value: string[]): string[] => value.length === 1 && !/^for /.test(value[0]!) && !value[0]!.includes(".let {") ? [`${key}; ${value[0]}`] : [key, ...value] /** The statements that write a class's members — an object — to the wire `w`, as lines. */ const encodeFields = (fields: LField[], of: (f: LField) => string, w: string): string[] => [ `${w}.beginObject()`, ...fields.flatMap(f => { const key = `${w}.key(${str(f.name)})` if (f.type.kind !== "optional") return keyed(key, encode(f.type, of(f), w)) // An optional member that is null is left out; a nullable one is written as a null. if (f.omit) return block(`${of(f)}?.let { v ->`, keyed(key, encode(f.type.of, "v", w, 1)), `}`) return keyed(key, encode(f.type, of(f), w)) }), `${w}.end()`, ] /** What PackedReader.kind() answers for a member of a union. */ const readerKind = (t: L): string => { switch (wireClass(t)) { case "number": return "PackedReader.NUMBER" case "string": return "PackedReader.TEXT" case "boolean": return "PackedReader.BOOLEAN" case "object": return "PackedReader.MAP" case "array": return "PackedReader.LIST" default: throw new EmitError(`a union cannot hold ${t.kind}`) } } const unionCase = (m: L): string => { switch (m.kind) { case "f64": return "OfNumber" case "i32": return "OfInteger" case "boolean": return "OfBool" case "string": return "OfString" case "enum": case "struct": return `Of${m.name}` default: return `Of${m.kind.charAt(0).toUpperCase()}${m.kind.slice(1)}` } } const members = (fields: LField[], indent: string): string => fields.map(f => `${doc(f.doc, indent)}${indent}val ${ident(f.name)}: ${kotlinType(f.type)}${f.type.kind === "optional" ? " = null" : ""},`).join("\n") const emitDecl = (d: LDecl, ways: Ways): string => { const read = ways.read.has(d.name) const write = ways.write.has(d.name) if (d.kind === "enum") { const cases = d.values.map(v => ` ${constName(v)}(${str(v)})`) return [ doc(d.doc), `enum class ${d.name}(val wire: String) {\n${cases.join(",\n")};\n`, read ? `\n companion object {\n internal fun read(r: PackedReader): ${d.name}? = r.string()?.let { s -> values().firstOrNull { it.wire == s } }\n }\n` : "", `}\n`, ].join("") } if (d.kind === "union") { const cases = d.members.map(m => ` data class ${unionCase(m)}(val value: ${kotlinType(m)}) : ${d.name}()`) const reads = !read ? [] : d.members.flatMap(m => wrap(`${readerKind(m)} -> `, decode(m, 1), `?.let { ${unionCase(m)}(it) }`)) const writes = !write ? [] : d.members.flatMap(m => { const lines = encode(m, "value", "w", 1) return lines.length === 1 ? [`is ${unionCase(m)} -> ${lines[0]}`] : [`is ${unionCase(m)} -> {`, ...indent(lines), `}`] }) return [ doc(d.doc), `sealed class ${d.name} {\n${cases.join("\n")}\n`, write ? `\n internal fun write(w: PackedWriter) {\n when (this) {\n${text(writes, " ")}\n }\n }\n` : "", read ? `\n companion object {\n internal fun read(r: PackedReader): ${d.name}? = when (r.kind()) {\n${text(reads, " ")}\n else -> null\n }\n }\n` : "", `}\n`, ].join("") } // The members are read into numbered locals and written from `this.`: a member's own name is // never an identifier here, so none can shadow the wire. const locals = !read ? [] : d.fields.map((f, i) => ` var m${i}: ${kotlinType(f.type.kind === "optional" ? f.type : { kind: "optional", of: f.type })} = null`) const reads = !read ? [] : d.fields.flatMap((f, i) => { const key = str(f.name) if (f.type.kind !== "optional") return wrap(`${key} -> m${i} = `, decode(f.type), ` ?: return null`) // An optional member that IS there must read: a wrong type is a malformed value, not an absent one. return wrap(`${key} -> if (r.isNull()) r.skip() else m${i} = `, decode(f.type), ` ?: return null`) }) const made = d.fields.map((f, i) => `${ident(f.name)} = m${i}${f.type.kind === "optional" ? "" : " ?: return null"}`) const body = [ !write ? "" : ` internal fun write(w: PackedWriter) {\n${text(encodeFields(d.fields, f => `this.${ident(f.name)}`, "w"), " ")}\n }\n`, !read ? "" : d.fields.length ? ` companion object {\n internal fun read(r: PackedReader): ${d.name}? {\n val n = r.beginObject()\n if (n < 0) return null\n${locals.join("\n")}\n repeat(n) {\n when (r.key()) {\n${text(reads, " ")}\n else -> r.skip()\n }\n }\n return ${d.name}(${made.join(", ")})\n }\n }\n` : ` companion object {\n internal fun read(r: PackedReader): ${d.name}? {\n if (r.isNull()) return ${d.name}()\n if (r.beginObject() < 0) return null\n return ${d.name}()\n }\n }\n`, ].filter(Boolean).join("\n") // A data class has a member or more: the empty struct is a plain class. const head = d.fields.length ? `data class ${d.name}(\n${members(d.fields, " ")}\n)` : `class ${d.name}` return `${doc(d.doc)}${head}${body ? ` {\n${body}}` : ""}\n` } /** The codes the calls of a channel reject with, as an enum class `name`. */ const codeEnum = (ch: LChannel, name: string): string => `/** The codes the calls of "${ch.name}" reject with. */\nenum class ${name}(override val code: String) : PluginCode {\n${ch.codes.map(c => ` ${constName(c)}(${str(c)})`).join(",\n")},\n}\n` /** One function per event, over the channel's `emit` (the function that takes the packed payload). * A `@lazy` event has its flag before it — set by the glue's `$listen` — and sends nothing while * the app does not listen: the half may call it whenever it has a value. */ const eventFunctions = (ch: LChannel, emit: string): string[] => ch.events.map(e => { const name = ident(e.name) const flag = e.lazy ? ` /** Whether the app listens to \`${e.name}\`, a \`@lazy\` event: while false, \`${e.name}()\` sends nothing. */\n @Volatile\n var ${e.name}Observed: Boolean = false\n internal set\n\n` : "" const guard = e.lazy ? ` if (!${e.name}Observed) return\n` : "" if (e.inline) { const args = e.inline.map(f => `${ident(f.name)}: ${kotlinType(f.type)}${f.type.kind === "optional" ? " = null" : ""}`) const w = writerName(e.inline.map(f => f.name)) return `${flag}${doc(e.doc, " ")} fun ${name}(${args.join(", ")}) {\n${guard} val ${w} = PackedWriter()\n${text(encodeFields(e.inline, f => ident(f.name), w), " ")}\n this.channel.${emit}(${str(e.name)}, ${w}.bytes())\n }` } if (e.payload.kind === "void") { return e.lazy ? `${flag}${doc(e.doc, " ")} fun ${name}() {\n${guard} channel.${emit}(${str(e.name)}, null)\n }` : `${doc(e.doc, " ")} fun ${name}() = channel.${emit}(${str(e.name)}, null)` } return `${flag}${doc(e.doc, " ")} fun ${name}(payload: ${kotlinType(e.payload)}) {\n${guard} val w = PackedWriter()\n${text(encode(e.payload, "payload", "w"), " ")}\n channel.${emit}(${str(e.name)}, w.bytes())\n }` }) /** What the plugin implements for its `@lazy` events: one function each. `end` = what stops * everything without it (the session's close, the instance's destroy). */ const observedSignatures = (ch: LChannel, end: string): string[] => ch.events.filter(e => e.lazy).map(e => `${doc(`The app began (true) or stopped (false) listening to \`${e.name}\`, a \`@lazy\` event: start or stop what\nproduces it. Not called at the end — \`${end}\` stops everything.`, " ")} fun ${e.name}Observed(observed: Boolean)`) /** The glue's case of `$listen(event, on)`, the wrapper's own call: the flag of the event, then the plugin. */ const listenCase = (ch: LChannel, target: string): string[] => { const lazy = ch.events.filter(e => e.lazy) if (lazy.length === 0) return [] return [[ ` ${str("$listen")} -> {`, ` // The wrapper's own call: the app began or stopped listening to a @lazy event.`, ` val event = (if (0 < n) r.string() else null) ?: return settle.reject("bad arguments — \\$listen: event")`, ` val on = (if (1 < n) r.bool() else null) ?: return settle.reject("bad arguments — \\$listen: on")`, ` when (event) {`, ...lazy.map(e => ` ${str(e.name)} -> if (events.${e.name}Observed != on) { events.${e.name}Observed = on; ${target}.${e.name}Observed(on) }`), ` else -> return settle.reject("Unknown event: $event")`, ` }`, ` settle.resolve()`, ` }`, ].join("\n")] } /** The methods as the plugin implements them: one function each, a typed `Reply`. */ const methodSignatures = (ch: LChannel, code: string): string[] => ch.methods.map(m => { const args = [...m.args.map(a => `${ident(a.name)}: ${kotlinType(a.type)}`), `reply: Reply<${kotlinType(m.result)}, ${code}>`] const tags = [ m.doc, m.permissions.length ? `Needs the ${m.permissions.join(" and ")} permission${m.permissions.length > 1 ? "s" : ""}: asked by the glue before the call, DENIED when refused.` : "", m.rejects.length ? `Rejects with ${m.rejects.map(constName).join(" / ")}.` : "", ].filter(Boolean).join("\n") return `${doc(tags, " ")} fun ${ident(m.name)}(${args.join(", ")})` }) /** The glue's `when (method)` cases: a call read off the wire (`r`, `n` arguments) and handed to `target`. */ const callCases = (ch: LChannel, code: string, target: string): string[] => ch.methods.map(m => { // The arguments are read into numbered locals, one after the other as they were written: an // argument's own name is never an identifier here. const lines: string[] = [] m.args.forEach((a, i) => { const bad = `return settle.reject("bad arguments — ${ch.iface}.${m.name}: ${a.name}")` if (a.type.kind !== "optional") { lines.push(...wrap(`val a${i} = (if (${i} < n) `, decode(a.type), ` else null) ?: ${bad}`)) } else { // An argument the app left out, or a null: nothing is read, a null that is there is passed over. lines.push(...wrap(`val a${i} = if (${i} < n && !r.isNull()) (`, decode(a.type), ` ?: ${bad}) else { if (${i} < n) r.skip(); null }`)) } }) const head = `Reply<${kotlinType(m.result)}, ${code}>(settle)` const reply = m.result.kind === "void" ? [`Reply(settle, null)`] : m.result.kind === "optional" // Nothing is written for null: the app's promise resolves with `undefined`. ? block(`${head} { v, w ->`, block(`if (v != null) {`, encode(m.result.of, "v", "w", 2), `}`), `}`) : block(`${head} { v, w ->`, encode(m.result, "v", "w", 1), `}`) if (m.permissions.length) { // The gate: the host's permission service, then the plugin — or DENIED without it. lines.push(...wrap(`val reply = `, reply, ``)) lines.push( `permissions.ensure(listOf(${m.permissions.map(k => `Permissions.Kind.${k.toUpperCase()}`).join(", ")})) { granted ->`, ` if (!granted) reply.reject(${code}.DENIED)`, ` else ${target}.${ident(m.name)}(${m.args.map((_, i) => `a${i}, `).join("")}reply)`, `}`, ) } else { lines.push(...wrap(`${target}.${ident(m.name)}(${m.args.map((_, i) => `a${i}, `).join("")}`, reply, `)`)) } return ` ${str(m.name)} -> {\n${text(lines, " ")}\n }` }) const emitChannel = (ch: LChannel): string => { if (ch.node) return emitNode(ch, ch.node) const isView = ch.kind === "view" const iface = ch.iface const code = ch.codes.length ? `${iface}Code` : "NoCode" const out: string[] = [] if (ch.codes.length) out.push(codeEnum(ch, `${iface}Code`)) // ---- events ---- const events = eventFunctions(ch, "emit") out.push([ `/** The events of "${ch.name}": what the plugin sends the app.${isView ? " From the main thread." : " Any thread."} */\n`, `class ${iface}Events(private val channel: PluginEmit)${events.length ? ` {\n${events.join("\n\n")}\n}` : ""}\n`, ].join("")) // ---- the interface ---- const lazy = ch.events.some(e => e.lazy) const signatures = [...methodSignatures(ch, code), ...observedSignatures(ch, isView ? "destroy()" : "close()")] out.push([ `/**\n * ${(ch.doc || `The ${ch.kind} "${ch.name}".`).split("\n").map(l => l.trim()).join("\n * ")}\n *\n`, ` * What the plugin implements. A call arrives on the main thread; its reply is settled exactly\n * once, now or later.\n */\n`, `interface ${iface}Plugin {\n`, isView ? ` /** The view the host mounts, fullscreen: a View is a destination, never a node of a layout (a node is a UIHostNode). */\n val view: android.view.View\n` : "", signatures.length ? (isView ? "\n" : "") + signatures.join("\n\n") + "\n" : "", isView ? `\n /** The instance goes (the world swapped): release the hardware. */\n fun destroy() {}\n` : `\n /** The session closed (the app's close, the world's teardown): stop what it started. */\n fun close() {}\n`, `}\n`, ].join("")) // ---- registration ---- const gated = ch.methods.some(m => m.permissions.length > 0) // The events reach the glue only for a contract with a @lazy event: its `$listen` sets their flags. const glueArgs = `plugin, ${lazy ? "events, " : ""}${gated ? "engine.permissions, " : ""}` const made = lazy ? ` val events = ${iface}Events { event, packed -> channel.emitPacked(event, packed) }\n val plugin = make(${ch.params}.read(Wire.reader(params)) ?: ${ch.params}(), events)\n` : ` val plugin = make(${ch.params}.read(Wire.reader(params)) ?: ${ch.params}(), ${iface}Events { event, packed -> channel.emitPacked(event, packed) })\n` out.push([ `object ${iface}Channel {\n`, ` /** What the halves register under. */\n const val NAME = ${str(ch.name)}\n\n`, ` /** The contract's version: the highest \`@since\` of its members. */\n const val VERSION = ${ch.version}\n\n`, isView ? ` /** Register the view: \`make\` builds one instance from its params. */\n` : ` /** Register the service: \`make\` builds one session from its params. It must be cheap — no\n * prompt, no I/O: that belongs to the first call that needs it. */\n`, ` fun register(engine: LecodesEngine, make: (params: ${ch.params}, events: ${iface}Events) -> ${iface}Plugin) {\n`, ` engine.register${isView ? "View" : "Service"}(NAME, VERSION) { params, channel ->\n`, made, isView ? ` NativeViews.Instance(plugin.view, onCall = { call -> ${iface}Glue.call(${glueArgs}call.method, call.reader(), call) }, onDestroy = { plugin.destroy() })\n` : ` Services.Instance(onCall = { call -> ${iface}Glue.call(${glueArgs}call.method, call.reader(), call) }, onClose = { plugin.close() })\n`, ` }\n }\n}\n`, ].join("")) // ---- the glue ---- const cases = [...callCases(ch, code, "plugin"), ...listenCase(ch, "plugin")] out.push([ `/** Reads a call off the wire and hands it to the plugin; a malformed call never reaches it. */\n`, `internal object ${iface}Glue {\n`, ` fun call(plugin: ${iface}Plugin, ${lazy ? `events: ${iface}Events, ` : ""}${gated ? "permissions: Permissions, " : ""}method: String, r: PackedReader, settle: ChannelSettle) {\n val n = r.beginArray() // the arguments, in their order\n when (method) {\n`, cases.length ? cases.join("\n") + "\n" : "", ` else -> settle.reject("Unknown method: $method")\n }\n }\n}\n`, ].join("")) return out.join("\n") } const upper = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1) /** A host node, the twin of emitSwift's: the events it sends, the interface its instance implements, * the glue between the holder and the instance. What the holder calls (`setProperty`, `setStyle`, * `measure`, `call`, `paintsSelf` — HostNodeInstance's entry points) the generated interface * implements: the plugin implements the typed side only. A setter is `set` — Kotlin tells * no overload apart by its parameter's name. */ const emitNode = (ch: LChannel, node: LNode): string => { const base = `${ch.iface}Node` const code = ch.codes.length ? `${base}Code` : "NoCode" const glue = `${base}Glue` const out: string[] = [] if (ch.codes.length) out.push(codeEnum(ch, `${base}Code`)) // ---- events ---- const events = eventFunctions(ch, "emitPacked") if (node.measure) events.push(` /** The content changed size: the holder measures the node again before the next frame. */\n fun invalidateSize() = channel.invalidateSize()`) out.push([ `/** The events of the host node "${ch.name}": what the plugin sends the app${node.measure ? " — and `invalidateSize`, what it\n * tells the holder" : ""}. Any thread. */\n`, `class ${base}Events(private val channel: HostNodeChannel)${events.length ? ` {\n${events.join("\n\n")}\n}` : ""}\n`, ].join("")) // ---- the interface ---- const setters = node.props.map(p => `${doc(p.doc, " ")} fun set${upper(p.name)}(value: ${kotlinType(p.type)})`) const styles = node.styles.map(s => `${doc(`The style \`${s.name}\`, as the core resolved it${s.kind === "color" ? " — an ARGB color" : ""}; null when none is set.`, " ")} fun set${upper(s.name)}(value: ${s.kind === "color" ? "Int?" : "Double?"})`) const measure = node.measure ? [` /** The node's size within \`c\` (a null side is unconstrained): asked on a layout, and again after\n * \`invalidateSize()\`. */\n override fun measure(c: HostNodeConstraints): SizeF`] : [] const colors = node.styles.filter(s => s.kind === "color") const numbers = node.styles.filter(s => s.kind === "number") const entries = [ ` override fun setProperty(name: String, value: String?) = ${glue}.setProperty(this, name, value)`, colors.length ? ` override fun setStyle(name: String, color: Int?) = ${glue}.setStyle(this, name, color)` : ` override fun setStyle(name: String, color: Int?) {}`, numbers.length ? ` override fun setStyle(name: String, number: Double?) = ${glue}.setStyle(this, name, number)` : ` override fun setStyle(name: String, number: Double?) {}`, ...(node.measure ? [] : [` /** Never asked: the node's styles size it. */\n override fun measure(c: HostNodeConstraints): SizeF = SizeF(0f, 0f)`]), ` override fun call(method: String, r: PackedReader, settle: ChannelSettle) = ${glue}.call(this, method, r, settle)`, ` /** ${node.paintsSelf ? "The instance paints its background and backdrop (`paints: \"self\"`)." : "The holder paints the whole box."} */\n override val paintsSelf: Boolean get() = ${node.paintsSelf}`, ] const sections = [setters, styles, measure, methodSignatures(ch, code)].filter(x => x.length).map(x => x.join("\n")) out.push([ `/**\n * ${(ch.doc || `The host node "${ch.name}".`).split("\n").map(l => l.trim()).join("\n * ")}\n *\n`, ` * What the plugin implements: one instance per node of the kind, made when the SDK creates the\n * node, called on the main thread. \`view\` is laid out and painted as the node's box; a call's reply\n * is settled exactly once, now or later.${node.paintsSelf ? `\n * \`paints: "self"\`: the instance paints its background and backdrop — the holder does not.` : ""}\n */\n`, `interface ${base}Instance : HostNodeInstance {\n`, sections.length ? sections.join("\n\n") + "\n\n" : "", ` // ---- what the holder (UINodeHost) hands the instance, by name: read by the contract here — the\n // plugin implements none of it ----\n`, entries.join("\n") + "\n", `}\n`, ].join("")) // ---- the glue ---- // A prop is TEXT (sdk/.gen.ts writes it so): decoded by what it is, a value the contract does // not read is dropped with a message — the instance never sees it. const used = new Set() /** The expression that reads `value` (non-null when `present`), null = it is not a T. */ const read = (t: L, present: boolean): string[] | null => { if (!propAsText(t)) { used.add("json") return present ? wrap(`json(value) { r -> `, decode(t), ` }`) : wrap(`value?.let { json(it) { r -> `, decode(t), ` } }`) } const of = t.kind === "optional" ? t.of : t const q = present ? "" : "?" switch (of.kind) { case "boolean": used.add("bool"); return [`bool(value)`] case "f64": return [`value${q}.toDoubleOrNull()`] case "i32": return [`value${q}.toIntOrNull()`] case "enum": return [`${of.name}.values().firstOrNull { it.wire == value }`] default: return null // a string: the text itself } } const props = node.props.map(p => { const set = `i.set${upper(p.name)}(` const optional = p.type.kind === "optional" const e = read(p.type, optional) const lines = e === null ? [`${set}${optional ? "value" : "value ?: return dropped(name)"})`] : optional ? wrap(`${set}if (value == null) null else `, e, ` ?: return dropped(name))`) : wrap(set, e, ` ?: return dropped(name))`) if (lines.some(l => l.includes("dropped("))) used.add("dropped") return lines.length === 1 ? ` ${str(p.name)} -> ${lines[0]}` : ` ${str(p.name)} -> {\n${text(lines, " ")}\n }` }) const styleCases = (list: LNode["styles"], arg: string): string => list.map(s => ` ${str(s.name)} -> i.set${upper(s.name)}(${arg})\n`).join("") const helpers = [ used.has("bool") ? ` private fun bool(text: String?): Boolean? = when (text) { "1" -> true; "0" -> false; else -> null }\n` : "", used.has("json") ? [ ` /** A prop's JSON text, read as the contract's type: null when it is not JSON, or not that type. */\n`, ` private fun json(text: String, read: (PackedReader) -> T?): T? {\n`, ` val value = try { org.json.JSONTokener(text).nextValue() } catch (e: org.json.JSONException) { return null }\n`, ` return read(Wire.reader(value))\n }\n`, ].join("") : "", used.has("dropped") ? ` private fun dropped(prop: String) {\n android.util.Log.w("LeCodes", "the node \\"$NAME\\" dropped a value of $prop its contract does not read")\n }\n` : "", ].filter(Boolean) const cases = callCases(ch, code, "i") out.push([ `/** The host node "${ch.name}": its registration, and the glue between the holder and the instance. */\n`, `object ${glue} {\n`, ` /** What the halves register under: the node's kind. */\n const val NAME = ${str(ch.name)}\n\n`, ` /** The contract's version: the highest \`@since\` of its members. */\n const val VERSION = ${ch.version}\n\n`, ` /** Register the node: \`make\` builds one instance per node of the kind, when the SDK creates one. */\n`, ` fun register(engine: LecodesEngine, make: (events: ${base}Events) -> ${base}Instance) {\n`, ` engine.registerNode(NAME, VERSION) { channel -> make(${base}Events(channel)) }\n }\n\n`, ` /** A prop the SDK wrote: its text, null when it was cleared. */\n`, ` internal fun setProperty(i: ${base}Instance, name: String, value: String?) {\n when (name) {\n`, props.length ? props.join("\n") + "\n" : "", ` else -> {} // \`kind\` (the holder's), or a prop of a newer contract\n }\n }\n`, colors.length ? `\n /** A color style of the contract, as the core resolved it; another is not the node's. */\n internal fun setStyle(i: ${base}Instance, name: String, color: Int?) {\n when (name) {\n${styleCases(colors, "color")} }\n }\n` : "", numbers.length ? `\n /** A number style of the contract, as the core resolved it; another is not the node's. */\n internal fun setStyle(i: ${base}Instance, name: String, number: Double?) {\n when (name) {\n${styleCases(numbers, "number")} }\n }\n` : "", `\n /** A call of the SDK: read off the wire and handed to the instance; a malformed call never reaches it. */\n`, ` internal fun call(i: ${base}Instance, method: String, r: PackedReader, settle: ChannelSettle) {\n val n = r.beginArray() // the arguments, in their order\n when (method) {\n`, cases.length ? cases.join("\n") + "\n" : "", ` else -> settle.reject("Unknown method: $method")\n }\n }\n`, helpers.length ? "\n" + helpers.join("\n") : "", `}\n`, ].join("")) return out.join("\n") } export type KotlinEmitOptions = { id: string /** The package of the plugin's Kotlin: the generated file is a file of it. */ package: string } /** The host's names a generated file may use, by the import that brings each. */ const IMPORTS: [string, string][] = [ ["LecodesEngine", "io.letary.lecodes.LecodesEngine"], ["ChannelSettle", "io.letary.lecodes.services.ChannelSettle"], ["NativeViews", "io.letary.lecodes.services.NativeViews"], ["NoCode", "io.letary.lecodes.services.NoCode"], ["Permissions", "io.letary.lecodes.services.Permissions"], ["PluginCode", "io.letary.lecodes.services.PluginCode"], ["PluginEmit", "io.letary.lecodes.services.PluginEmit"], ["PluginFile", "io.letary.lecodes.services.PluginFile"], ["Entity", "io.letary.lecodes.scene.Entity"], ["Scene3D", "io.letary.lecodes.scene.Scene3D"], ["Reply", "io.letary.lecodes.services.Reply"], ["Services", "io.letary.lecodes.services.Services"], ["Wire", "io.letary.lecodes.services.Wire"], ["PackedReader", "io.letary.lecodes.core.PackedReader"], ["PackedWriter", "io.letary.lecodes.core.PackedWriter"], // A host node's (the host's twins of the Swift names, beside NativeViews). ["HostNodeChannel", "io.letary.lecodes.services.HostNodeChannel"], ["HostNodeConstraints", "io.letary.lecodes.services.HostNodeConstraints"], ["HostNodeInstance", "io.letary.lecodes.services.HostNodeInstance"], ["SizeF", "android.util.SizeF"], ] /** One file per plugin: the types every channel of the contract reaches, then each channel. */ export const emitKotlin = (lowered: Lowered, opts: KotlinEmitOptions): string => { const header = lowered.channels.map(channelLabel).join("; ") const guarded = (what: string, body: () => string): string => { try { return body() } catch (e) { if (e instanceof EmitError) throw new EmitError(`${what}: ${e.message}`) throw e } } const ways = waysOf(lowered) const body = [ `// ---- The contract's types ----\n\n`, lowered.decls.map(d => guarded(d.name, () => emitDecl(d, ways))).join("\n"), ...lowered.channels.map(ch => `\n// ---- ${ch.iface} ----\n\n${guarded(ch.iface, () => emitChannel(ch))}`), ].join("") const imports = IMPORTS.filter(([name]) => new RegExp(`\\b${name}\\b`).test(body)).map(([, path]) => `import ${path}`) return [ `// GENERATED by \`lecodes plugin gen\` from contract.d.ts — do not edit.\n`, `// ${opts.id}: ${header}.\n\n`, `package ${opts.package}\n\n`, `${imports.join("\n")}\n\n`, body, ].join("") }