Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.45.0

0.45.0 / src / back / c / emit / text.lucb

#==============================================================================================
#
#   emit/text - Text and interfaces
#
#   DESCRIPTION:
#       Formatted text and string literals, and interface views over pointers (§14).
#
#==============================================================================================
extend Emitter:
    # mark: Text ===============================================================================

    ## Append one value to the format buffer temporary `prefix n`.
    func display(n: u32, prefix: str, v: ast.Node*) -> !:
        if v.has(ast.flag_format_sink):
            # `value.display(__sink)` at a scalar or text: a `Display` parameter instantiated
            # at a type the compiler displays itself (§14.4)
            if let receiver = calls.sink_receiver(v):
                if self.kind(try self.map(receiver.type_id)) != types.Kind.struct_:
                    try self.display(n, prefix, receiver)
                    return
            # `value.display(__sink)`: the sink is this buffer
            let saved_prefix = self.sink_prefix
            let saved_index = self.sink_index
            self.sink_prefix = prefix
            self.sink_index = n
            try self.expr(v)
            self.sink_prefix = saved_prefix
            self.sink_index = saved_index
            return
        var t = try self.ty(v)
        if self.is_atomic(t):
            t = self.elem(t)
        if t == types.bool_id:
            try self.put("lb_fmtbuf_bool(&")
            try self.put_tmp(prefix, n)
            try self.put(", ")
            try self.expr(v)
            try self.put(")")
            return
        if t == types.char_id:
            try self.put("lb_fmtbuf_char(&")
            try self.put_tmp(prefix, n)
            try self.put(", ")
            try self.expr(v)
            try self.put(")")
            return
        if t == types.str_id or t == types.fmt_id:
            let k = self.tmp()
            try self.put("({ lb_str ")
            try self.put_tmp("ds", k)
            try self.put(" = ")
            try self.expr(v)
            try self.put("; lb_fmtbuf_put(&")
            try self.put_tmp(prefix, n)
            try self.put(", ")
            try self.put_tmp("ds", k)
            try self.put(".data, ")
            try self.put_tmp("ds", k)
            try self.put(".length); })")
            return
        if self.is_float(t) or t == types.untyped_float_id:
            # core's own text, the native backend's (§14): an f32 or f16 shows the f32's digits
            let single = t == types.f32_id or t == types.f16_id
            try self.put("lb_core_10format_f32((struct lb_core_FormatBuffer*)&" if single else "lb_core_10format_f64((struct lb_core_FormatBuffer*)&")
            try self.put_tmp(prefix, n)
            try self.put(", (float)(" if single else ", (double)(")
            try self.expr(v)
            try self.put("))")
            return
        if self.is_ptr(t):
            try self.put("lb_fmtbuf_u64(&")
            try self.put_tmp(prefix, n)
            try self.put(", (uint64_t)(uintptr_t)(")
            try self.expr(v)
            try self.put("))")
            return
        if (self.is_int(t) and not self.is_signed(t)) or t == types.char_id or (self.c.is_backed_enum(t) and not self.signed_of(t)) or t == types.error_code_id:
            try self.put("lb_fmtbuf_u64(&")
            try self.put_tmp(prefix, n)
            try self.put(", (uint64_t)(")
            try self.expr(v)
            try self.put("))")
            return
        try self.put("lb_fmtbuf_i64(&")
        try self.put_tmp(prefix, n)
        try self.put(", (int64_t)(")
        try self.expr(v)
        try self.put("))")

    ## `a == b` for two C expressions of type `t`, member by member (§7.4): padding bytes
    ## and the bytes of an inactive payload never take part, as they would in a `memcmp`.
    func same_value(t: u32, a: str, b: str) -> !:
        let k = self.kind(t)
        if t == types.str_id or t == types.fmt_id:
            try self.same_text(a, b)
        elif self.is_tagged_opt(t):
            try self.same_optional(t, a, b)
        elif k == types.Kind.array:
            try self.same_array(t, a, b)
        elif k == types.Kind.span:
            try self.same_span(t, a, b)
        elif k == types.Kind.tuple:
            try self.same_tuple(t, a, b)
        elif k == types.Kind.struct_:
            try self.same_record(t, a, b)
        elif k == types.Kind.enum_ and not self.c.is_backed_enum(t):
            try self.same_payload_enum(t, a, b)
        else:
            try self.put("(")
            try self.put(a)
            try self.put(" == ")
            try self.put(b)
            try self.put(")")

    ## Equal text: the same length and the same bytes.
    func same_text(a: str, b: str) -> !:
        try self.put("(")
        try self.put(a)
        try self.put(".length == ")
        try self.put(b)
        try self.put(".length && (")
        try self.put(a)
        try self.put(".length == 0 || memcmp(")
        try self.put(a)
        try self.put(".data, ")
        try self.put(b)
        try self.put(".data, ")
        try self.put(a)
        try self.put(".length) == 0))")

    ## Equal optionals: both absent, or both present with equal values.
    func same_optional(t: u32, a: str, b: str) -> !:
        try self.put("(")
        try self.put(a)
        try self.put(".present == ")
        try self.put(b)
        try self.put(".present && (!")
        try self.put(a)
        try self.put(".present || ")
        try self.same_value(self.elem(t), try c_path(a, ".value"), try c_path(b, ".value"))
        try self.put("))")

    ## Equal arrays: a loop over the elements that stops at the first difference.
    func same_array(t: u32, a: str, b: str) -> !:
        let n = self.tmp()
        let i = try tmp_name("i", n)
        let eq = try tmp_name("eq", n)
        try self.put("({ bool ")
        try self.put(eq)
        try self.put(" = true; for (size_t ")
        try self.put(i)
        try self.put(" = 0; ")
        try self.put(i)
        try self.put(" < ")
        try self.put_u64(self.c.table.get(t).length)
        try self.put("ULL && ")
        try self.put(eq)
        try self.put("; ")
        try self.put(i)
        try self.put("++) { ")
        try self.put(eq)
        try self.put(" = ")
        var index_bytes = try new u8[i.length + 5] ---
        let index = try strings.format(index_bytes, f".d[{i}]")
        try self.same_value(self.elem(t), try c_path(a, index), try c_path(b, index))
        try self.put("; } ")
        try self.put(eq)
        try self.put("; })")

    ## Equal spans: the same length, then a loop over the elements that stops at the first
    ## difference (§7.4).
    func same_span(t: u32, a: str, b: str) -> !:
        let n = self.tmp()
        let i = try tmp_name("i", n)
        let eq = try tmp_name("eq", n)
        let pa = try tmp_name("pa", n)
        let pb = try tmp_name("pb", n)
        let et = self.elem(t)
        try self.put("({ bool ")
        try self.put(eq)
        try self.put(" = ")
        try self.put(a)
        try self.put(".length == ")
        try self.put(b)
        try self.put(".length; const ")
        try self.put_type(et)
        try self.put("* ")
        try self.put(pa)
        try self.put(" = (const void*)")
        try self.put(a)
        try self.put(".data; const ")
        try self.put_type(et)
        try self.put("* ")
        try self.put(pb)
        try self.put(" = (const void*)")
        try self.put(b)
        try self.put(".data; for (size_t ")
        try self.put(i)
        try self.put(" = 0; ")
        try self.put(eq)
        try self.put(" && ")
        try self.put(i)
        try self.put(" < ")
        try self.put(a)
        try self.put(".length; ")
        try self.put(i)
        try self.put("++) { ")
        try self.put(eq)
        try self.put(" = ")
        var index_bytes = try new u8[i.length + 4] ---
        let index = try strings.format(index_bytes, f"[{i}]")
        try self.same_value(et, try c_path(pa, index), try c_path(pb, index))
        try self.put("; } ")
        try self.put(eq)
        try self.put("; })")

    ## Equal tuples: every member equal; the empty tuple is always.
    func same_tuple(t: u32, a: str, b: str) -> !:
        let members = self.c.table.get(t).args
        try self.put("(")
        var j: usize = 0
        while j < members.length:
            if j > 0:
                try self.put(" && ")
            var member_bytes = try new u8[16] ---
            let member = try strings.format(member_bytes, f".a{j}")
            try self.same_value(members[j], try c_path(a, member), try c_path(b, member))
            j += 1
        if members.length == 0:
            try self.put("true")
        try self.put(")")

    ## Equal records: every field equal, at the record's type arguments.
    func same_record(t: u32, a: str, b: str) -> !:
        let record = self.c.table.get(t)
        let d = record.decl else return try self.put("true")
        try self.put("(")
        var any = false
        var cursor = d.body
        while let m = cursor:
            if m.kind == ast.Kind.field:
                if any:
                    try self.put(" && ")
                any = true
                var ft = m.type_id
                if record.args.length > 0:
                    ft = try self.c.substitute(ft, d, record.args)
                let member = try c_path(".", try c_field_name(m.text))
                try self.same_value(ft, try c_path(a, member), try c_path(b, member))
            cursor = m.next
        if not any:
            try self.put("true")
        try self.put(")")

    ## Equal enums with payloads: the same tag, and under it, a switch comparing the active
    ## case's payload members.
    func same_payload_enum(t: u32, a: str, b: str) -> !:
        let record = self.c.table.get(t)
        let d = record.decl else return try self.put("true")
        let n = self.tmp()
        let eq = try tmp_name("eq", n)
        try self.put("({ bool ")
        try self.put(eq)
        try self.put(" = ")
        try self.put(a)
        try self.put(".tag == ")
        try self.put(b)
        try self.put(".tag; if (")
        try self.put(eq)
        try self.put(") switch ((int)")
        try self.put(a)
        try self.put(".tag) { ")
        var cursor = d.body
        while let case_decl = cursor:
            if case_decl.kind == ast.Kind.enum_case and case_decl.body != none:
                try self.put("case ")
                try self.put_u64((u64)instances.case_tag(d, case_decl))
                try self.put(": ")
                try self.put(eq)
                try self.put(" = (")
                try self.same_payload(record.args, d, case_decl, a, b)
                try self.put("); break; ")
            cursor = case_decl.next
        try self.put("default: break; } ")
        try self.put(eq)
        try self.put("; })")

    ## The payload members of `case_decl` in `a` and `b` all equal, joined by `&&`.
    func same_payload(args: u32[], d: ast.Node*, case_decl: ast.Node*, a: str, b: str) -> !:
        var first = true
        var param = case_decl.body
        while let p = param:
            if not first:
                try self.put(" && ")
            first = false
            var pt = p.type_id
            if args.length > 0:
                pt = try self.c.substitute(pt, d, args)
            let case_name = try c_field_name(case_decl.text)
            let payload_name = try c_field_name(p.text)
            var member_bytes = try new u8[case_name.length + payload_name.length + 4] ---
            let member = try strings.format(member_bytes, f".u.{case_name}.{payload_name}")
            try self.same_value(pt, try c_path(a, member), try c_path(b, member))
            param = p.next

    ## The pieces of a formatted string appended to buffer `prefix n`.
    func pieces(n: u32, prefix: str, f: ast.Node*) -> !:
        var part = f.body
        while let p = part:
            if p.kind == ast.Kind.format_text:
                let text = literals.unescape_braces(literals.decode_text(p.text))
                try self.put("(void)lb_fmtbuf_put(&")
                try self.put_tmp(prefix, n)
                try self.put(", ")
                try self.put_c_string(text)
                try self.put(", ")
                try self.put_u64((u64)text.length)
                try self.put("); ")
            elif p.kind == ast.Kind.format_field:
                let v = p.left else return
                try self.put("(void)")
                try self.display(n, prefix, v)
                try self.put("; ")
            part = p.next

    ## A formatted string as an `lb_str` in one of the function's format buffers: the
    ## buffer is declared at the function's top (`function`), so the text outlives the
    ## expression, as the value it is passed to may read it after the expression ends.
    ## The buffer grows onto the heap past its 1024 bytes; what it took is freed when the
    ## expression is written again or the function returns.
    func formatted_value(f: ast.Node*) -> !:
        let n = try self.growing_format_buffer(f)
        try self.pieces(n, "ff", f)
        try self.put("lb_fmtbuf_finish(&")
        try self.put_tmp("ff", n)
        try self.put("); })")

    ## A fresh format buffer of the function being written; its declaration is the
    ## function's, not the expression's.
    func format_buffer(at: ast.Node*) -> u32!:
        if self.target != to_scratch:
            var room: u8[96] = ---
            let message = try strings.format(room, f"line {at.line}: a formatted text outside a function body")
            return error(check.unsupported, try strings.copy(message))
        let n = self.tmp()
        try self.formats.push(n)
        return n

    ## A formatted string as `lb_cspan` for a `Writer`, in a format buffer of the function
    ## that grows as `formatted_value`'s.
    func formatted_bytes(f: ast.Node*) -> !:
        let n = try self.growing_format_buffer(f)
        try self.pieces(n, "ff", f)
        try self.put("(lb_cspan){ (void*)(")
        try self.put_tmp("ff", n)
        try self.put(".data), ")
        try self.put_tmp("ff", n)
        try self.put(".used }; })")

    ## Open a statement expression that starts a growing format buffer of the function;
    ## the buffer's number.
    func growing_format_buffer(f: ast.Node*) -> u32!:
        let n = try self.format_buffer(f)
        try self.put("({ lb_fmtbuf_begin(&")
        try self.put_tmp("ff", n)
        try self.put(", ")
        try self.put_tmp("fb", n)
        try self.put(", 1024); ")
        return n

    ## A formatted string written piece by piece, so no buffer bounds it: to standard output
    ## through C's `stdout`, or to the diagnostic (a trap's message) through `core`, which
    ## also writes it into a crash report. Text and `str` fields go as they are, and each
    ## other field is displayed alone into one format buffer of the function, which the
    ## pieces share. The pieces go through a buffer of their own that goes out as it passes
    ## half full and at the end (`lb_stream_put`, `core.stream_put`), as a native build
    ## streams them: a field that prints writes before the line it is part of.
    func stream_formatted(f: ast.Node*, diagnostic: bool) -> !:
        let line = self.tmp()
        try self.put("({ char ")
        try self.put_tmp("sb", line)
        try self.put("[1024]; lb_fmtbuf ")
        try self.put_tmp("sf", line)
        try self.put(" = { ")
        try self.put_tmp("sb", line)
        try self.put(", 1024, 0 }; ")
        var n: u32 = 0
        var buffered = false
        var part = f.body
        while let p = part:
            part = p.next
            if p.kind == ast.Kind.format_text:
                let text = literals.unescape_braces(literals.decode_text(p.text))
                try self.stream_call("put", line, diagnostic)
                try self.put_c_string(text)
                try self.put(", ")
                try self.put_u64((u64)text.length)
                try self.put(", ")
                try self.put("2" if diagnostic else "stdout")
                try self.put("); ")
                continue
            if p.kind != ast.Kind.format_field:
                continue
            let v = p.left else return
            var t = types.none_id if v.has(ast.flag_format_sink) else try self.ty(v)
            let k = self.tmp()
            try self.put("{ lb_str ")
            try self.put_tmp("ps", k)
            try self.put(" = ")
            if t == types.str_id or t == types.fmt_id:
                try self.expr(v)
            else:
                if not buffered:
                    n = try self.format_buffer(f)
                    buffered = true
                try self.put("({ ")
                try self.put_tmp("ff", n)
                try self.put(" = (lb_fmtbuf){ ")
                try self.put_tmp("fb", n)
                try self.put(", 1024, 0 }; (void)")
                try self.display(n, "ff", v)
                try self.put("; lb_fmtbuf_finish(&")
                try self.put_tmp("ff", n)
                try self.put("); })")
            try self.put("; ")
            try self.stream_call("put", line, diagnostic)
            try self.put_tmp("ps", k)
            try self.put(".data, ")
            try self.put_tmp("ps", k)
            try self.put(".length, ")
            try self.put("2" if diagnostic else "stdout")
            try self.put("); } ")
        try self.stream_call("flush", line, diagnostic)
        try self.put("2" if diagnostic else "stdout")
        try self.put("); (void)0; })")

    ## The start of a call that streams through buffer `line`, `put` or `flush`, up to
    ## its next argument: the runtime's for `stdout`, `core`'s for the diagnostic.
    func stream_call(which: str, line: u32, diagnostic: bool) -> !:
        if diagnostic:
            try self.put("lb_core_10stream_put((struct lb_core_FormatBuffer*)&" if which == "put" else "lb_core_12stream_flush((struct lb_core_FormatBuffer*)&")
        else:
            try self.put("lb_stream_put(&" if which == "put" else "lb_stream_flush(&")
        try self.put_tmp("sf", line)
        try self.put(", (const uint8_t*)" if diagnostic and which == "put" else ", ")

    ## `strings.format(buffer, text)` into the caller's bytes, yielding `str!`.
    func format_call(buf: ast.Node*, msg: ast.Node*) -> !:
        let n = self.tmp()
        let res = try self.c.table.fallible(types.str_id)
        try self.note(res)
        try self.put("({ lb_span ")
        try self.put_tmp("ds", n)
        try self.put(" = ")
        try self.value(buf, try self.c.table.span(types.u8_id, false))
        try self.put("; lb_fmtbuf ")
        try self.put_tmp("fb", n)
        try self.put(" = { (char*)")
        try self.put_tmp("ds", n)
        try self.put(".data, ")
        try self.put_tmp("ds", n)
        try self.put(".length, 0 }; ")
        if msg.kind == ast.Kind.formatted:
            try self.pieces(n, "fb", msg)
        else:
            try self.put("(void)")
            try self.display(n, "fb", msg)
            try self.put("; ")
        try self.put("lb_r_str ")
        try self.put_tmp("out", n)
        try self.put("; if (")
        try self.put_tmp("fb", n)
        try self.put(".used > ")
        try self.put_tmp("fb", n)
        try self.put(".cap) { ")
        try self.put_tmp("out", n)
        try self.put(" = ((lb_r_str){ .error = { .code = ")
        try self.put_u64(check.exhausted_code())
        try self.put(", .message = (lb_str){\"memory.exhausted: the formatted text does not fit its buffer\", 60}, .at = lb_here() }, .failed = true }); } else { ")
        try self.put_tmp("out", n)
        try self.put(" = ((lb_r_str){ .value = lb_fmtbuf_finish(&")
        try self.put_tmp("fb", n)
        try self.put("), .failed = false }); } ")
        try self.put_tmp("out", n)
        try self.put("; })")

    ## `value.hash()` (§7.4) over the runtime's mixer.
    ## `v.hash()` (§14.4): equal values hash the same, so a record, tuple, array, or optional
    ## hashes its members in the order `==` compares them, text hashes its bytes, a float its
    ## bits with both zeros as one, and a pointer its address.
    func hash_of(t: u32, v: ast.Node*) -> !:
        let n = self.tmp()
        let value = try tmp_name("hv", n)
        try self.put("({ ")
        try self.put_type(t)
        try self.put(" ")
        try self.put(value)
        try self.put(" = ")
        try self.expr(v)
        try self.put("; ")
        try self.hash_value(t, value, "lb_hash_seed()")
        try self.put("; })")

    ## The hash of the C value `a` of type `t` folded onto the hash `seed`, as one expression.
    func hash_value(t: u32, a: str, seed: str) -> !:
        let k = self.kind(t)
        if t == types.str_id or t == types.fmt_id:
            try self.put_all("lb_hash_bytes(", seed, ", ")
            try self.put_all(a, ".data, ", a)
            try self.put(".length)")
        elif t == types.bool_id:
            try self.put_all("lb_hash_mix(", seed, ", (uint64_t)(")
            try self.put_all(a, " ? 1 : 0))", "")
        elif self.is_float(t):
            let bits = try tmp_name("hb", self.tmp())
            try self.put_all("({ uint64_t ", bits, " = 0; if (")
            try self.put_all(a, " != 0) memcpy(&", bits)
            try self.put_all(", &", a, ", sizeof(")
            try self.put_all(a, ")); lb_hash_mix(", seed)
            try self.put_all(", ", bits, "); })")
        elif self.is_ptr(t) or t == types.cstr_id:
            try self.put_all("lb_hash_mix(", seed, ", (uint64_t)(uintptr_t)(")
            try self.put_all(a, "))", "")
        elif self.is_tagged_opt(t):
            let present = try c_path(a, ".present")
            try self.put_all("(", present, " ? ")
            var inner = try new u8[seed.length + 20] ---
            try self.hash_value(self.elem(t), try c_path(a, ".value"), try strings.format(inner, f"lb_hash_mix({seed}, 1)"))
            try self.put_all(" : lb_hash_mix(", seed, ", 0))")
        elif k == types.Kind.array or k == types.Kind.tuple or k == types.Kind.struct_ or (k == types.Kind.enum_ and not self.c.is_backed_enum(t)):
            try self.hash_members(t, a, seed)
        else:
            try self.put_all("lb_hash_mix(", seed, ", (uint64_t)(")
            try self.put_all(a, "))", "")

    ## An aggregate's hash: `seed` folded through every member in order, in a running
    ## variable, so the members' hashes nest no deeper than the members do.
    func hash_members(t: u32, a: str, seed: str) -> !:
        let k = self.kind(t)
        let n = self.tmp()
        let h = try tmp_name("h", n)
        try self.put_all("({ uint64_t ", h, " = ")
        if k == types.Kind.array:
            let i = try tmp_name("i", n)
            try self.put_all(seed, "; for (size_t ", i)
            try self.put_all(" = 0; ", i, " < ")
            try self.put_u64(self.c.table.get(t).length)
            try self.put_all("ULL; ", i, "++) ")
            try self.put_all(h, " = ", "")
            var index_bytes = try new u8[i.length + 5] ---
            try self.hash_value(self.elem(t), try c_path(a, try strings.format(index_bytes, f".d[{i}]")), h)
            try self.put(";")
        elif k == types.Kind.tuple:
            try self.put_all(seed, ";", "")
            let members = self.c.table.get(t).args
            var j: usize = 0
            while j < members.length:
                var member_bytes = try new u8[16] ---
                try self.hash_member(members[j], try c_path(a, try strings.format(member_bytes, f".a{j}")), h)
                j += 1
        elif k == types.Kind.struct_:
            try self.put_all(seed, ";", "")
            let record = self.c.table.get(t)
            if let d = record.decl:
                var cursor = d.body
                while let m = cursor:
                    if m.kind == ast.Kind.field:
                        var ft = m.type_id
                        if record.args.length > 0:
                            ft = try self.c.substitute(ft, d, record.args)
                        try self.hash_member(ft, try c_path(a, try c_path(".", try c_field_name(m.text))), h)
                    cursor = m.next
        else:
            # a payload enum: the tag, then the payload of the case it carries
            try self.put_all("lb_hash_mix(", seed, ", (uint64_t)")
            try self.put_all(a, ".tag); switch ((int)", a)
            try self.put(".tag) { ")
            let record = self.c.table.get(t)
            if let d = record.decl:
                var cursor = d.body
                while let case_decl = cursor:
                    if case_decl.kind == ast.Kind.enum_case and case_decl.body != none:
                        try self.put("case ")
                        try self.put_u64((u64)instances.case_tag(d, case_decl))
                        try self.put(": ")
                        var param = case_decl.body
                        while let p = param:
                            var pt = p.type_id
                            if record.args.length > 0:
                                pt = try self.c.substitute(pt, d, record.args)
                            let case_name = try c_field_name(case_decl.text)
                            let payload_name = try c_field_name(p.text)
                            var member_bytes = try new u8[case_name.length + payload_name.length + 4] ---
                            try self.hash_member(pt, try c_path(a, try strings.format(member_bytes, f".u.{case_name}.{payload_name}")), h)
                            param = p.next
                        try self.put("break; ")
                    cursor = case_decl.next
            try self.put("default: break; }")
        try self.put_all(" ", h, "; })")

    ## `h = hash of member;` folding one member onto the running hash `h`.
    func hash_member(t: u32, member: str, h: str) -> !:
        try self.put_all(" ", h, " = ")
        try self.hash_value(t, member, h)
        try self.put(";")

    ## Three pieces of text in a row.
    func put_all(a: str, b: str, c: str) -> !:
        try self.put(a)
        try self.put(b)
        try self.put(c)

    # mark: Interfaces =========================================================================

    ## Remember that a witness table for `record` as `iface` is needed.
    func note_vtable(record: u32, iface: u32) -> !:
        var i: usize = 0
        while i < self.vtables.count:
            let v = self.vtables.get(i)
            if v.record == record and v.iface == iface:
                return
            i += 1
        try self.vtables.push(Witness(record = record, iface = iface))
        try self.note(record)
        # the methods the table points at must be emitted
        let d = self.decl_of(record) else return
        let t = self.c.table.get(record)
        let i_decl = self.decl_of(iface) else return
        for m in (try instances.witnessed(d, i_decl)).span():
            _ = try self.add_func(m, try types.no_args(), d, t.args)

    ## `typedef struct lb_vt_Name { ... } lb_vt_Name;` for a user interface.
    func interface_typedef(d: ast.Node*) -> !:
        try self.line("typedef struct lb_vt_")
        try self.put(d.text)
        try self.put(" {")
        self.indent += 1
        var m = d.body
        while let f = m:
            if f.kind == ast.Kind.func_:
                try self.line("")
                try self.put_result_type(f)
                try self.put(" (*")
                try self.put(f.text)
                try self.put(")(void* self")
                var p = f.right
                while let q = p:
                    try self.put(", ")
                    try self.put_type(try self.map(q.type_id))
                    p = q.next
                try self.put(");")
            m = f.next
        self.indent -= 1
        try self.line("} lb_vt_")
        try self.put(d.text)
        try self.put(";")

    ## A type-correct erased-receiver adapter. Calling a concrete `Record*` method
    ## through a `void*` function-pointer cast is ABI-compatible on common hosts but
    ## undefined C and is correctly rejected by Clang's function sanitizer.
    func witness_wrapper(w: Witness, requirement: ast.Node*, implementation: ast.Node*) -> !:
        let record = self.decl_of(w.record) else return
        let instance = self.c.table.get(w.record)
        try self.line("static ")
        try self.put_result_type(requirement)
        try self.put(" lb_witness_")
        try self.put_mangled(w.record)
        try self.put("_")
        let iface = self.decl_of(w.iface) else return
        try self.put(iface.text)
        try self.put("_")
        try self.put_ident(requirement.text)
        try self.put("(void* self")
        var parameter = requirement.right
        while let p = parameter:
            try self.put(", ")
            try self.put_type(try self.map(p.type_id))
            try self.put(" ")
            try self.put_ident(p.text)
            parameter = p.next
        try self.put(") {")
        self.indent += 1
        let function_type = self.c.table.get(try self.map(requirement.type_id))
        let returns = requirement.has(ast.flag_fallible) or (function_type.elem != types.unit_id and function_type.elem != types.never_id)
        try self.line("return " if returns else "")
        try self.put_func_name(implementation, try types.no_args(), record, instance.args)
        try self.put("((")
        try self.put_type(w.record)
        try self.put("*)self")
        parameter = requirement.right
        var concrete = implementation.right
        while let p = parameter:
            try self.put(", ")
            let actual = concrete else return error(backend, "an interface witness has different parameters")
            let erased_type = try self.map(p.type_id)
            let actual_type = try self.map(actual.type_id)
            if erased_type != actual_type:
                # Equatable and Comparable erase their concrete `other` value to
                # `void*`; the call site passes its address in the witness ABI.
                try self.put("*(")
                try self.put_type(actual_type)
                try self.put("*)")
            try self.put_ident(p.text)
            parameter = p.next
            concrete = actual.next
        try self.put(");")
        self.indent -= 1
        try self.line("}")

    ## The witness table of one record for one interface.
    func vtable(w: Witness) -> !:
        let d = self.decl_of(w.record) else return
        let i = self.decl_of(w.iface) else return
        var adapter = i.body
        while let requirement = adapter:
            if requirement.kind == ast.Kind.func_:
                if let implementation = check.witness_member(d, requirement.text):
                    try self.witness_wrapper(w, requirement, implementation)
            adapter = requirement.next
        try self.line("static const lb_vt_")
        try self.put(i.text)
        try self.put(" lb_vt_")
        try self.put_mangled(w.record)
        try self.put("_")
        try self.put(i.text)
        try self.put(" __attribute__((unused)) = {")
        self.indent += 1
        var req = i.body
        while let r = req:
            if r.kind == ast.Kind.func_:
                try self.line(".")
                try self.put(r.text)
                try self.put(" = ")
                if let m = check.witness_member(d, r.text):
                    _ = m
                    try self.put("lb_witness_")
                    try self.put_mangled(w.record)
                    try self.put("_")
                    try self.put(i.text)
                    try self.put("_")
                    try self.put_ident(r.text)
                else:
                    try self.put("NULL")
                try self.put(",")
            req = r.next
        self.indent -= 1
        try self.line("};")

    ## The type an allocator answers: `u8[]?`.
    func put_block_type() -> !:
        let block = try self.c.table.optional(try self.c.table.span(types.u8_id, false))
        try self.put_type(block)

    ## The calls `new`, `alloc`, `free`, and `grow` make on an allocator view.
    func allocator_glue() -> !:
        let block = try self.c.table.optional(try self.c.table.span(types.u8_id, false))
        try self.line("static inline __attribute__((unused)) ")
        try self.put_type(block)
        try self.put(" lb_alloc_call(lb_iface a, size_t size, size_t alignment) { if (a.vtable == NULL) lb_trap(\"memory.unset\"); return ((const lb_vt_Allocator*)a.vtable)->allocate(a.data, size, alignment); }")
        try self.line("static inline bool __attribute__((unused)) lb_resize_call(lb_iface a, lb_span block, size_t size) { if (a.vtable == NULL) lb_trap(\"memory.unset\"); return ((const lb_vt_Allocator*)a.vtable)->resize(a.data, block, size); }")
        try self.line("static inline void __attribute__((unused)) lb_release_call(lb_iface a, lb_span block) { if (a.vtable == NULL) return; ((const lb_vt_Allocator*)a.vtable)->release(a.data, block); }")

## A field or a payload name as C spells it: the name, unless C reserves it, when an
## underscore follows; Base names are free to be `unsigned` or `int`.
func c_field_name(name: str) -> str!:
    if not is_c_keyword(name):
        return name
    let room = try new u8[name.length + 1] ---
    return try strings.format(room, f"{name}_")

## `a` followed by `suffix`, as one C expression text.
func c_path(a: str, suffix: str) -> str!:
    var bytes = try new u8[a.length + suffix.length + 1] ---
    return try strings.format(bytes, f"{a}{suffix}")

## The text `put_tmp(prefix, n)` writes.
func tmp_name(prefix: str, n: u32) -> str!:
    var bytes = try new u8[prefix.length + 16] ---
    return try strings.format(bytes, f"_lb_{prefix}{n}")