C backend: ahead-of-time compilation to a native binary

- new cat/backend/c.{h,c}: lower a compiled CAT_BYTECODE_Function to a
  self-contained C translation unit that rebuilds the bytecode and runs
  it on the catscript runtime.  The tree is emitted in pre-order with
  forward declarations; constants (int/float/text/bool) are recreated by
  the matching constructors; jumps keep their absolute targets.
- Makefile: also build libcatscript.a (all objects but main.o) so an AOT
  program links the runtime without clashing on `main`.
- main.c: `--emit-c <file>` prints the generated C; `--build <file> <out>`
  emits it, invokes the system `cc`, and produces the executable.
- tests/aot.cat + suite: the native binary's stdout must equal the
  interpreter's (arithmetic, recursion, objects, interfaces, `is`,
  concat, comparisons).  Suite 151 -> 152.

The backend is faithful by construction: it lowers the very bytecode the
interpreter runs, so native output matches the interpreter exactly
(including current language quirks, e.g. upvalues and `try`/`catch`).
This commit is contained in:
Minus committed 2026-11-18 17:37:25 +00:00
1 parent 70728093ef
commit 33a1152958
6 files changed
+473 -2

No files matched your search

+12 -1
View File
@@ -21,6 +21,7 @@ LDLIBS ?= -lm -lffi -ldl
BUILD := build/catscript BUILD := build/catscript
BIN := $(BUILD)/catscript BIN := $(BUILD)/catscript
LIB := $(BUILD)/libcatscript.a
SRCS := \ SRCS := \
src/main.c \ src/main.c \
@@ -31,6 +32,7 @@ SRCS := \
src/cat/compiler.c \ src/cat/compiler.c \
src/cat/vm.c \ src/cat/vm.c \
src/cat/module.c \ src/cat/module.c \
src/cat/backend/c.c \
src/cat/types/empty.c \ src/cat/types/empty.c \
src/cat/types/type.c \ src/cat/types/type.c \
src/cat/types/bool.c \ src/cat/types/bool.c \
@@ -57,6 +59,11 @@ SRCS := \
OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS))
# The runtime archive is every object EXCEPT the CLI entry point, so an
# ahead-of-time compiled program can link the runtime without clashing
# on `main`.
LIBOBJS := $(filter-out $(BUILD)/main.o,$(OBJS))
.PHONY: help all test clean examples .PHONY: help all test clean examples
# Default goal: print the help. # Default goal: print the help.
@@ -67,12 +74,16 @@ help:
@echo " make clean - remove build artifacts" @echo " make clean - remove build artifacts"
@echo " make help - show this help (default goal)" @echo " make help - show this help (default goal)"
all: $(BIN) all: $(BIN) $(LIB)
$(BIN): $(OBJS) $(BIN): $(OBJS)
@mkdir -p $(dir $@) @mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS)
$(LIB): $(LIBOBJS)
@mkdir -p $(dir $@)
$(AR) rcs $@ $(LIBOBJS)
$(BUILD)/%.o: src/%.c $(BUILD)/%.o: src/%.c
@mkdir -p $(dir $@) @mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $< $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
+36
View File
@@ -0,0 +1,36 @@
/*
* cat/backend/c.h -- the C backend (ahead-of-time compilation).
*
* Naming rule: symbols here are cat_backend_c_* / CAT_BACKEND_C_*.
*
* The bytecode produced by the compiler is lowered to a standalone C
* translation unit. The generated program embeds its bytecode and runs
* it on the catscript runtime, but contains no compiler: a native `cc`
* build of the output is the executable, so nothing is parsed or
* compiled at run time.
*
* Two entry points:
* - cat_backend_c_emit() write the C for a compiled program
* - cat_backend_c_compile() emit + invoke cc to produce a binary
*/
#ifndef CAT_BACKEND_C_H
#define CAT_BACKEND_C_H
#include "cat/bytecode.h"
#include <stddef.h>
#include <stdio.h>
/* Write a self-contained C translation unit for `fn` to `out`.
* `module_name`/`module_path` seed the runtime `module` table. */
int cat_backend_c_emit(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out);
/* Emit the C for `fn` to a temporary file, compile it with the system C
* compiler, and write the executable to `outpath`. On failure returns
* non-zero and fills `errbuf`. */
int cat_backend_c_compile(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, const char *outpath,
char *errbuf, size_t errsz);
#endif /* CAT_BACKEND_C_H */
+317
View File
@@ -0,0 +1,317 @@
/*
* cat/backend/c.c -- the C backend (see cat/backend/c.h).
*
* Naming rule: symbols here are cat_backend_c_* / CAT_BACKEND_C_*.
*
* A compiled CAT_BYTECODE_Function is written out as a C translation
* unit that rebuilds the bytecode at startup and runs it on the
* catscript runtime. The result is a native binary produced by `cc`
* with no compiler inside it: parsing/compilation happen ahead of time.
*/
#include "cat/backend/c.h"
#include "cat/bytecode.h"
#include "cat/error.h"
#include "cat/types/number.h"
#include "cat/types/ascii_text.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* opcode mnemonics, for readable comments in the generated C. */
static const char *c_op_name(unsigned char op)
{
static const char *names[] = {
"NOP", "CONST", "EMPTY", "TRUE", "FALSE", "GETLOCAL", "SETLOCAL",
"GETGLOBAL", "SETGLOBAL", "ADD", "SUB", "MUL", "DIV", "REM",
"NEG", "NOT", "EQ", "NE", "LT", "LE", "GT", "GE", "GETATTR",
"SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF",
"JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE",
"GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX", "YIELD", "NEXT",
"TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR", "IS"
};
if (op < sizeof(names) / sizeof(names[0]))
return names[op];
return "?";
}
/* Write `s` as the body of a C string literal, octal-escaping anything
* that is not safe to emit verbatim. Three-digit octal escapes never
* bleed into following characters. */
static void c_escape(FILE *out, const char *s)
{
const unsigned char *p = (const unsigned char *)s;
for (; p != NULL && *p != '\0'; p++) {
unsigned char ch = *p;
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x7f)
fprintf(out, "\\%03o", ch);
else
fputc(ch, out);
}
}
/* Number of functions in a prototype subtree (including itself). */
static int c_count_fns(CAT_BYTECODE_Function *fn)
{
int n = 1, i;
for (i = 0; i < fn->nprotos; i++)
n += c_count_fns(fn->protos[i]);
return n;
}
/* Emit the C expression that recreates a constant value. */
static void c_emit_const(FILE *out, CAT_VALUE_Value *v)
{
if (v == NULL) {
fprintf(out, "cat_types_empty()");
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v;
if (n->is_float)
fprintf(out, "cat_types_float_new(%.17g)", n->f);
else
fprintf(out, "cat_types_int_new(%lldLL)", n->i);
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TEXT) {
fprintf(out, "cat_types_ascii_text_new(\"");
c_escape(out, cat_types_text_bytes(v));
fprintf(out, "\")");
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_BOOL) {
int t = 1;
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_value_truthy(v, &t, &e);
fprintf(out, "%s", t ? "cat_types_bool_true()"
: "cat_types_bool_false()");
return;
}
/* anything else cannot appear as a literal constant in practice */
fprintf(out, "cat_types_empty()");
}
/* Emit the definition body for the function numbered `idx`. Child
* functions are numbered in pre-order, so child i's index is
* idx + 1 + (size of the subtrees before it). */
static void c_emit_fn(FILE *out, CAT_BYTECODE_Function *fn, int idx)
{
int i;
int child;
fprintf(out, "static CAT_BYTECODE_Function *cat_prog_fn_%d(void)\n{\n",
idx);
fprintf(out, "\tCAT_BYTECODE_Function *fn = "
"cat_bytecode_function_new(\"");
c_escape(out, fn->name ? fn->name : "<anon>");
fprintf(out, "\");\n\n");
fprintf(out, "\tfn->nparams = %d;\n\tfn->nlocals = %d;\n",
fn->nparams, fn->nlocals);
fprintf(out, "\tfn->is_generator = %d;\n\n", fn->is_generator);
for (i = 0; i < fn->nconsts; i++) {
fprintf(out, "\tcat_bytecode_add_const(fn, ");
c_emit_const(out, fn->consts[i].value);
fprintf(out, ");\n");
}
if (fn->nconsts > 0)
fprintf(out, "\n");
child = idx + 1;
for (i = 0; i < fn->nprotos; i++) {
fprintf(out, "\tcat_bytecode_add_proto(fn, cat_prog_fn_%d());\n",
child);
child += c_count_fns(fn->protos[i]);
}
if (fn->nprotos > 0)
fprintf(out, "\n");
for (i = 0; i < fn->ncode; i++) {
CAT_BYTECODE_Instr *in = &fn->code[i];
fprintf(out, "\tcat_bytecode_emit(fn, %d, %d, %d, %d, %d);"
" /* %s */\n",
in->op, in->a, in->b, in->c, in->line,
c_op_name(in->op));
}
fprintf(out, "\treturn fn;\n}\n\n");
}
/* Pre-order forward declarations. */
static void c_emit_decls(FILE *out, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int i;
fprintf(out, "static CAT_BYTECODE_Function *cat_prog_fn_%d(void);\n",
self);
for (i = 0; i < fn->nprotos; i++)
c_emit_decls(out, fn->protos[i], next);
}
/* Pre-order definitions (mirrors c_emit_decls). */
static void c_emit_defs(FILE *out, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int i;
c_emit_fn(out, fn, self);
for (i = 0; i < fn->nprotos; i++)
c_emit_defs(out, fn->protos[i], next);
}
/* Directory holding the running executable, or NULL. */
static char *c_exe_dir(void)
{
char buf[4096];
ssize_t n;
char *slash;
n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (n <= 0)
return NULL;
buf[n] = '\0';
slash = strrchr(buf, '/');
if (slash == NULL)
return NULL;
*slash = '\0';
return strdup(buf);
}
int cat_backend_c_emit(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out)
{
int next;
if (fn == NULL || out == NULL)
return -1;
fprintf(out, "/* generated by catscript -- C backend (AOT). */\n");
fprintf(out, "#include \"cat/vm.h\"\n");
fprintf(out, "#include \"cat/bytecode.h\"\n");
fprintf(out, "#include \"cat/module.h\"\n");
fprintf(out, "#include \"cat/error.h\"\n");
fprintf(out, "#include \"cat/stdlib/stdlib.h\"\n");
fprintf(out, "#include \"cat/stdlib/build.h\"\n");
fprintf(out, "#include \"cat/types/number.h\"\n");
fprintf(out, "#include \"cat/types/int.h\"\n");
fprintf(out, "#include \"cat/types/float.h\"\n");
fprintf(out, "#include \"cat/types/ascii_text.h\"\n");
fprintf(out, "#include \"cat/types/bool.h\"\n");
fprintf(out, "#include \"cat/types/empty.h\"\n\n");
fprintf(out, "#include <stdio.h>\n\n");
next = 0;
fprintf(out, "/* function prototypes */\n");
c_emit_decls(out, fn, &next);
fprintf(out, "\n");
next = 0;
c_emit_defs(out, fn, &next);
fprintf(out, "int main(void)\n{\n");
fprintf(out, "\tCAT_VM_State *vm;\n");
fprintf(out, "\tCAT_BYTECODE_Function *top;\n");
fprintf(out, "\tCAT_VALUE_Value *out = NULL;\n");
fprintf(out, "\tint rc;\n\n");
fprintf(out, "\tvm = cat_vm_new();\n");
fprintf(out, "\tif (vm == NULL)\n\t\treturn 1;\n");
fprintf(out, "\tcat_stdlib_stdlib_install(vm);\n");
fprintf(out, "\tcat_stdlib_build_install(vm);\n");
fprintf(out, "\tcat_module_enter(vm, \"");
c_escape(out, module_name ? module_name : "<aot>");
fprintf(out, "\", ");
if (module_path != NULL) {
fprintf(out, "\"");
c_escape(out, module_path);
fprintf(out, "\"");
} else {
fprintf(out, "NULL");
}
fprintf(out, ");\n\n");
fprintf(out, "\ttop = cat_prog_fn_0();\n");
fprintf(out, "\trc = cat_vm_run(vm, top, &out);\n");
fprintf(out, "\tif (rc != 0)\n");
fprintf(out, "\t\tfprintf(stderr, \"catscript: %%s\\n\", "
"vm->err.message);\n");
fprintf(out, "\tcat_bytecode_function_free(top);\n");
fprintf(out, "\tcat_vm_free(vm);\n");
fprintf(out, "\treturn rc != 0;\n}\n");
return 0;
}
int cat_backend_c_compile(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, const char *outpath,
char *errbuf, size_t errsz)
{
char tmpl[] = "/tmp/catscript-aot-XXXXXX.c";
char cmd[9216];
char inc[4096];
char lib[4096];
char *dir;
FILE *f;
int fd;
int st;
if (errbuf != NULL && errsz > 0)
errbuf[0] = '\0';
fd = mkstemps(tmpl, 2);
if (fd < 0)
return -1;
f = fdopen(fd, "w");
if (f == NULL) {
close(fd);
return -1;
}
if (cat_backend_c_emit(fn, module_name, module_path, f) != 0) {
fclose(f);
unlink(tmpl);
return -1;
}
fclose(f);
dir = c_exe_dir();
if (dir == NULL) {
unlink(tmpl);
if (errbuf != NULL)
snprintf(errbuf, errsz,
"cannot locate the catscript runtime");
return -1;
}
snprintf(inc, sizeof(inc), "%s/../../include", dir);
snprintf(lib, sizeof(lib), "%s/libcatscript.a", dir);
if (access(lib, R_OK) != 0) {
unlink(tmpl);
free(dir);
if (errbuf != NULL)
snprintf(errbuf, errsz,
"runtime archive missing at %s", lib);
return -1;
}
snprintf(cmd, sizeof(cmd),
"cc -std=c11 -O2 -D_DEFAULT_SOURCE -I'%s' -o '%s' '%s' '%s' "
"-lm -lffi -ldl 2>&1",
inc, outpath, tmpl, lib);
st = system(cmd);
unlink(tmpl);
free(dir);
if (st != 0) {
if (errbuf != NULL)
snprintf(errbuf, errsz,
"C compiler failed (status %d)", st);
return -1;
}
return 0;
}
+62 -1
View File
@@ -17,6 +17,7 @@
#include "cat/module.h" #include "cat/module.h"
#include "cat/stdlib/stdlib.h" #include "cat/stdlib/stdlib.h"
#include "cat/stdlib/build.h" #include "cat/stdlib/build.h"
#include "cat/backend/c.h"
#include "cat/error.h" #include "cat/error.h"
#include <stdio.h> #include <stdio.h>
@@ -141,14 +142,70 @@ static void main_repl(void)
static void main_usage(void) static void main_usage(void)
{ {
printf("catscript -- a small Lua-like scripting language\n\n"); printf("catscript -- a small scripting language\n\n");
printf("usage:\n"); printf("usage:\n");
printf(" catscript <file.cat> run a script\n"); printf(" catscript <file.cat> run a script\n");
printf(" catscript --dump <file> print compiled bytecode\n"); printf(" catscript --dump <file> print compiled bytecode\n");
printf(" catscript --emit-c <file> print the compiled C (AOT)\n");
printf(" catscript --build <file> <out> compile to a native binary\n");
printf(" catscript --help show this help\n"); printf(" catscript --help show this help\n");
printf(" catscript start a REPL\n"); printf(" catscript start a REPL\n");
} }
/* `--emit-c`: compile a file and print the C translation unit. */
static int main_emit_c(const char *path)
{
CAT_ERROR_Error err;
CAT_BYTECODE_Function *fn;
char *src = main_read_file(path);
if (src == NULL) {
fprintf(stderr, "catscript: cannot read %s\n", path);
return 1;
}
cat_error_clear(&err);
fn = cat_compiler_compile(src, &err);
free(src);
if (fn == NULL) {
fprintf(stderr, "catscript: %s\n", err.message);
return 1;
}
cat_backend_c_emit(fn, main_basename(path), path, stdout);
cat_bytecode_function_free(fn);
return 0;
}
/* `--build <file> <out>`: compile a file to a native executable. */
static int main_build(const char *path, const char *outpath)
{
CAT_ERROR_Error err;
CAT_BYTECODE_Function *fn;
char *src = main_read_file(path);
char errbuf[256];
int rc;
if (src == NULL) {
fprintf(stderr, "catscript: cannot read %s\n", path);
return 1;
}
cat_error_clear(&err);
fn = cat_compiler_compile(src, &err);
free(src);
if (fn == NULL) {
fprintf(stderr, "catscript: %s\n", err.message);
return 1;
}
rc = cat_backend_c_compile(fn, main_basename(path), path, outpath,
errbuf, sizeof(errbuf));
cat_bytecode_function_free(fn);
if (rc != 0) {
fprintf(stderr, "catscript: %s\n",
errbuf[0] ? errbuf : "cannot build native binary");
return 1;
}
return 0;
}
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
if (argc >= 2 && strcmp(argv[1], "--help") == 0) { if (argc >= 2 && strcmp(argv[1], "--help") == 0) {
@@ -166,6 +223,10 @@ int main(int argc, char **argv)
free(src); free(src);
return rc; return rc;
} }
if (argc >= 3 && strcmp(argv[1], "--emit-c") == 0)
return main_emit_c(argv[2]);
if (argc >= 4 && strcmp(argv[1], "--build") == 0)
return main_build(argv[2], argv[3]);
if (argc >= 2) { if (argc >= 2) {
char *src = main_read_file(argv[1]); char *src = main_read_file(argv[1]);
int rc; int rc;
+32
View File
@@ -0,0 +1,32 @@
-- tests/aot.cat -- the C backend (ahead-of-time compilation).
--
-- Built with `catscript --build tests/aot.cat /tmp/aot_native`, this must
-- produce byte-for-byte the same stdout as the interpreter. It exercises
-- arithmetic, calls, recursion, objects, interfaces and structural `is`.
function add(a, b) return a + b end
print("add:", add(2, 3))
function fact(n)
if n <= 1 then return 1 end
return n * fact(n - 1)
end
print("fact:", fact(5))
local p = { x = 1, y = 2 }
p.x = p.x + 10
print("point:", p.x, p.y)
interface Shape
function area(self) end
end
class Square implements Shape
function init(self, side) self.side = side end
function area(self) return self.side * self.side end
end
local s = Square(4)
print("area:", s.area(), s is Shape)
print("text:", "ca" .. "tscript", 3 < 4, 5 == 5, not (2 == 3))
+14
View File
@@ -263,6 +263,20 @@ check "trait-robot" "robot is Greeter: true" "`echo "$out" | sed -n 6p`"
check "trait-sized" "sized: true" "`echo "$out" | sed -n 7p`" check "trait-sized" "sized: true" "`echo "$out" | sed -n 7p`"
check "trait-sized-fn" "implements Sized: true" "`echo "$out" | sed -n 8p`" check "trait-sized-fn" "implements Sized: true" "`echo "$out" | sed -n 8p`"
out=`$BIN tests/aot.cat`
exp=`$BIN tests/aot.cat`
$BIN --build tests/aot.cat build/tests/aot_native >/dev/null 2>&1
if [ -x build/tests/aot_native ]; then
got=`build/tests/aot_native`
if [ "$exp" = "$got" ]; then
check "aot-native" "interpreter == native" "interpreter == native"
else
check "aot-native" "interpreter == native" "diverged: $got"
fi
else
check "aot-native" "native binary built" "missing"
fi
out=`$BIN tests/comptime.cat` out=`$BIN tests/comptime.cat`
check "comptime-expr" "ct-expr: 42" "`echo "$out" | sed -n 1p`" check "comptime-expr" "ct-expr: 42" "`echo "$out" | sed -n 1p`"
check "comptime-text" "ct-text: hi there" "`echo "$out" | sed -n 2p`" check "comptime-text" "ct-text: hi there" "`echo "$out" | sed -n 2p`"