dymokomi/luce-base
Source of release 0.44.0
0.44.0 / src / back / c / header.lucb
#==============================================================================================
#
# header - The exported surface of a program as a C header
#
# DESCRIPTION:
# `luce build --lib` produces a library and this header (base.md §17.6): every
# `export` function and method of the program's own modules as a C prototype, after
# the C definitions of the records their signatures mention, in dependency order.
# Types are spelled as the header's reader expects them: `int32_t`, `size_t`, `bool`,
# a struct by its Base name, an integer-backed enum as its backing integer with its
# cases as constants. A signature that C cannot express is an error here.
#
#==============================================================================================
import back.names
import front.ast
import sema.check
import sema.types
import support.buffer
import support.list
# mark: The C header ==========================================================================
## An exported declaration has no C representation.
pub let not_representable: ErrorCode = ErrorCode.package(16)
## The header text for the exported surface of the program `c` holds.
pub func write(checker: check.Checker*, out: buffer.Buffer*) -> !:
var writer = Header(c = checker, out = out, defined = try list.List[u32].create(16), functions = try list.List[u32].create(8))
try out.put("/* generated by luce-base: the exported surface of the program */\n")
try out.put("#pragma once\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n\n")
var i: usize = 0
while i < checker.modules.count:
let m = checker.modules.get(i)
if not m.is_prelude:
try writer.records_of(m.tree)
i += 1
i = 0
while i < checker.modules.count:
let m = checker.modules.get(i)
if not m.is_prelude:
try writer.error_codes_of(m.tree)
i += 1
i = 0
while i < checker.modules.count:
let m = checker.modules.get(i)
if not m.is_prelude:
try writer.prototypes_of(m.tree)
i += 1
struct Header:
var c: check.Checker*
var out: buffer.Buffer*
## The record types already defined, so each is written once.
var defined: list.List[u32]
## The function types given a typedef, `luce_fn_N` by position, so a function pointer
## parameter or field has a name C can read.
var functions: list.List[u32]
# -- records ---------------------------------------------------------------------------
## The records every export of `tree` mentions, defined before the prototypes.
func records_of(tree: ast.Node*) -> !:
var cursor = tree.body
while let d = cursor:
if d.kind == ast.Kind.func_ and d.has(ast.flag_export):
try self.records_in(d)
elif d.kind == ast.Kind.struct_:
var member = d.body
while let m = member:
if m.kind == ast.Kind.func_ and m.has(ast.flag_export):
try self.define(d.type_id)
try self.records_in(m)
member = m.next
cursor = d.next
## The package's error codes (§11.3), each as the `int` a fallible export's status
## carries: `#define prefix_name ((int)CODEu)`, the identity in the high half.
func error_codes_of(tree: ast.Node*) -> !:
var cursor = tree.body
while let d = cursor:
if d.kind == ast.Kind.constant and d.has(ast.flag_pub) and d.type_id == types.error_code_id:
if let init = d.left:
if init.kind == ast.Kind.call:
if let argument = init.body:
if let v = argument.left:
if v.kind == ast.Kind.literal:
try self.out.put("#define ")
try self.out.put(names.export_prefix)
try self.out.put(d.text)
try self.out.put(" ((int)")
try self.out.put(v.text)
try self.out.put("u)\n")
cursor = d.next
## The records a signature mentions.
func records_in(f: ast.Node*) -> !:
let ft = self.c.table.get(f.type_id)
var i: usize = 0
while i < ft.args.length:
try self.define(ft.args[i])
i += 1
try self.define(ft.elem)
## Define the record behind `id`, its fields' records first; a pointer's pointee and a
## span's element count, and a function type becomes a typedef of a pointer to it.
func define(id: u32) -> !:
let t = self.c.table.get(id)
if t.kind == types.Kind.pointer or t.kind == types.Kind.optional or t.kind == types.Kind.span or t.kind == types.Kind.array or t.kind == types.Kind.fallible:
return try self.define(t.elem)
if t.kind == types.Kind.func_:
return try self.define_function(id)
if t.kind != types.Kind.struct_ and t.kind != types.Kind.union_ and t.kind != types.Kind.enum_:
return
if self.is_defined(id):
return
try self.defined.push(id)
let d = t.decl else return error(not_representable, "a record without a declaration")
if t.kind == types.Kind.enum_:
return try self.enum_definition(d, id)
# the name first, so that a record may point at itself, or at one defined after it
let keyword = "union" if t.kind == types.Kind.union_ else "struct"
try self.out.put("typedef ")
try self.out.put(keyword)
try self.out.put(" ")
try self.out.put(d.text)
try self.out.put(" ")
try self.out.put(d.text)
try self.out.put(";\n")
var member = d.body
while let m = member:
if m.kind == ast.Kind.field:
try self.define(m.type_id)
member = m.next
try self.out.put(keyword)
if d.has(ast.flag_packed):
try self.out.put(" __attribute__((packed))")
if let layout = d.right:
if layout.kind == ast.Kind.literal:
try self.out.put(" __attribute__((aligned(")
try self.out.put(layout.text)
try self.out.put(")))")
try self.out.put(" ")
try self.out.put(d.text)
try self.out.put(" {\n")
member = d.body
while let m = member:
if m.kind == ast.Kind.field:
try self.out.put(" ")
try self.field(m)
try self.out.put(";\n")
member = m.next
try self.out.put("};\n\n")
## `typedef R (*luce_fn_N)(A, B);` for a function type, its own records defined first.
func define_function(id: u32) -> !:
if self.function_index(id) != 0:
return
let t = self.c.table.get(id)
for a in t.args:
try self.define(a)
try self.define(t.elem)
try self.functions.push(id)
let n = self.functions.count
try self.out.put("typedef ")
try self.spell(t.elem)
try self.out.put(" (*luce_fn_")
try self.out.put_u64((u64)n)
try self.out.put(")(")
if t.args.length == 0:
try self.out.put("void")
var i: usize = 0
while i < t.args.length:
if i > 0:
try self.out.put(", ")
try self.spell(t.args[i])
i += 1
try self.out.put(");\n\n")
## The typedef's number of a function type, 0 when it has none yet.
func function_index(id: u32) -> usize:
var i: usize = 0
while i < self.functions.count:
if self.functions.get(i) == id:
return i + 1
i += 1
return 0
## One field: its type and name, an array's length after the name as C wants it, and
## `align(N)` as the attribute C needs to lay the record out as Base does (§5.11).
func field(m: ast.Node*) -> !:
let t = self.c.table.get(m.type_id)
if t.kind == types.Kind.array:
try self.spell(t.elem)
try self.out.put(" ")
try self.out.put(m.text)
try self.out.put("[")
try self.out.put_u64(t.length)
try self.out.put("]")
else:
try self.spell(m.type_id)
try self.out.put(" ")
try self.out.put(m.text)
if let layout = m.right:
if layout.kind == ast.Kind.literal:
try self.out.put(" __attribute__((aligned(")
try self.out.put(layout.text)
try self.out.put(")))")
## `typedef uint32_t Flags;` and one constant per case (§17.6).
func enum_definition(d: ast.Node*, id: u32) -> !:
if not self.c.is_backed_enum(id):
return error(not_representable, "an enum with payloads cannot be exported")
let backing = check.enum_backing(&self.c.table, id)
try self.out.put("typedef ")
try self.spell(backing)
try self.out.put(" ")
try self.out.put(d.text)
try self.out.put(";\nenum {\n")
var member = d.body
while let m = member:
if m.kind == ast.Kind.enum_case:
try self.out.put(" ")
try self.out.put(d.text)
try self.out.put("_")
try self.out.put(m.text)
try self.out.put(" = ")
try self.out.put_u64(types.case_value(d, m))
try self.out.put(",\n")
member = m.next
try self.out.put("};\n\n")
func is_defined(id: u32) -> bool:
var i: usize = 0
while i < self.defined.count:
if self.defined.get(i) == id:
return true
i += 1
return false
# -- prototypes ------------------------------------------------------------------------
## Every `export` function and method of `tree`.
func prototypes_of(tree: ast.Node*) -> !:
var cursor = tree.body
while let d = cursor:
if d.kind == ast.Kind.func_ and d.has(ast.flag_export):
try self.prototype(d, none)
elif d.kind == ast.Kind.struct_:
var member = d.body
while let m = member:
if m.kind == ast.Kind.func_ and m.has(ast.flag_export):
try self.prototype(m, d)
member = m.next
cursor = d.next
## `Result name(Params);`, a method as `Owner_name` with `self` first (§17.6). A span
## parameter is a pointer and a `size_t` length. A fallible function is in its status
## form: `int` is 0 or the error's code, and the value is written through a final
## out-pointer.
func prototype(f: ast.Node*, owner: ast.Node*?) -> !:
let ft = self.c.table.get(f.type_id)
let fallible = self.c.table.kind(ft.elem) == types.Kind.fallible
let payload = self.c.table.get(ft.elem).elem if fallible else ft.elem
if fallible:
try self.out.put("/* 0, or the error's code")
if payload != types.unit_id:
try self.out.put("; the value is written through `out`")
try self.out.put(" */\nint")
else:
try self.spell(ft.elem)
try self.out.put(" ")
try self.out.put(names.export_prefix)
if let o = owner:
try self.out.put(o.text)
try self.out.put("_")
try self.out.put(f.text)
try self.out.put("(")
var first = true
if let o = owner:
if not f.has(ast.flag_static):
if not (f.has(ast.flag_mutating) or f.text == "init"):
try self.out.put("const ")
try self.out.put(o.text)
try self.out.put("* self")
first = false
var cursor = f.right
while let p = cursor:
if not first:
try self.out.put(", ")
first = false
let pt = self.c.table.get(p.type_id)
if pt.kind == types.Kind.span:
if pt.is_const:
try self.out.put("const ")
try self.spell(pt.elem)
try self.out.put("* ")
try self.out.put(p.text)
try self.out.put(", size_t ")
try self.out.put(p.text)
try self.out.put("_len")
else:
try self.spell(p.type_id)
try self.out.put(" ")
try self.out.put(p.text)
cursor = p.next
if fallible and payload != types.unit_id:
if not first:
try self.out.put(", ")
first = false
try self.spell(payload)
try self.out.put("* out")
if first:
try self.out.put("void")
try self.out.put(");\n")
# -- types -----------------------------------------------------------------------------
## The C spelling of a C-representable type (§17.6); anything else is refused.
func spell(id: u32) -> !:
let t = self.c.table.get(id)
match t.kind:
.unit_, .void_: try self.out.put("void")
.bool_: try self.out.put("bool")
.i8_: try self.out.put("int8_t" if id != types.c_char_id else "char")
.i16_: try self.out.put("int16_t")
.i32_: try self.out.put("int32_t" if id != types.c_wchar_id else "wchar_t")
.i64_: try self.out.put("int64_t" if id != types.c_long_id else "long")
.isize_: try self.out.put("intptr_t")
.u8_: try self.out.put("uint8_t")
.u16_: try self.out.put("uint16_t")
.u32_: try self.out.put("uint32_t")
.u64_: try self.out.put("uint64_t" if id != types.c_ulong_id else "unsigned long")
.usize_: try self.out.put("size_t")
.f16_: try self.out.put("_Float16")
.f32_: try self.out.put("float")
.f64_: try self.out.put("double")
.char_: try self.out.put("uint32_t")
.cstr_: try self.out.put("char*")
.pointer:
if id == types.c_va_list_id:
try self.out.put("va_list")
return
# `const (T*)*` is C's `T* const*`: the qualifier follows the inner star (§5.3)
let inner_is_pointer = self.c.table.kind(t.elem) == types.Kind.pointer or self.c.table.is_nullable_pointer(t.elem)
if t.is_const and not inner_is_pointer:
try self.out.put("const ")
if t.elem == types.void_id:
try self.out.put("void")
else:
try self.spell(t.elem)
if t.is_const and inner_is_pointer:
try self.out.put(" const")
try self.out.put("*")
if self.c.table.is_nullable_pointer(id):
try self.out.put(" /* may be null */")
.struct_, .union_:
let d = t.decl else return error(not_representable, "a record without a declaration")
try self.out.put(d.text)
.enum_:
let d = t.decl else return error(not_representable, "an enum without a declaration")
if not self.c.is_backed_enum(id):
return error(not_representable, "an enum with payloads cannot be exported")
try self.out.put(d.text)
.optional:
if self.c.table.is_nullable_pointer(id):
try self.spell(t.elem)
try self.out.put(" /* may be null */")
else:
return error(not_representable, "an optional other than a pointer cannot be exported")
.func_:
let n = self.function_index(id)
if n == 0:
return error(not_representable, "a function type the header did not define")
try self.out.put("luce_fn_")
try self.out.put_u64((u64)n)
_:
return error(not_representable, "this type has no C spelling; an export takes scalars, pointers, and records of them")