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

+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 */