stage1 重构代码新增c后端

This commit is contained in:
zzy committed 2026-10-13 13:14:48 +08:00
1 parent fc2d8f8db4
commit 3714c2d142
24 files changed
+1539 -593

No files matched your search

+30 -5
View File
@@ -16,6 +16,7 @@
#include "spl_ast.h"
#include "spl_ast2ir.h"
#include "spl_diag.h"
#include "spl_ir2c.h"
#include "spl_ir2vm.h"
#include "spl_lexer.h"
#include "spl_parser.h"
@@ -29,6 +30,7 @@ typedef enum {
DUMP_SEMA,
DUMP_IR,
DUMP_VM,
DUMP_C,
} dump_t;
typedef struct {
@@ -72,8 +74,7 @@ static char *read_file(const char *path, long *out_len) {
return buf;
}
/* 注意:按值接收,内部 vec_free 释放与调用方共享的 data 指针。
调用后原 vec 视为已消费,不要再使用。 */
/* 按值接收并 vec_free 内部 data 指针;调用后原 vec 视为已消费。 */
static void dump_tokens(spl_tok_vec_t toks) {
printf("tokens got (%zu)\n", toks.size);
for (usize i = 0; i < toks.size; i++) {
@@ -338,10 +339,31 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
goto cleanup;
}
/* 类型已全部就绪:解析 layout,供 ir2vm 的 size/align/offset 使用。 */
/* 类型已全部就绪:解析 layout,供 ir2vm/ir2c 的 size/align/offset 使用。 */
spl_layout_resolve(&layout, &lang_type.ir);
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &lang_type.ir, &layout, &attr, opt);
/* C 后端:IR -> C99 写入缓冲,再落盘,不经 VM。 */
if (dump == DUMP_C) {
spl_ir2c_buf_t cbuf;
vec_init(cbuf);
bool cok = spl_ir2c_run(&a2ir.ir->ir, &lang_type.ir, &layout, &attr, &cbuf);
FILE *cf = fopen(outpath, "wb");
if (!cf) {
LOG_FATAL("cannot open C output file `%s`", outpath);
vec_free(cbuf);
rc = 1;
goto cleanup;
}
fwrite(cbuf.data, 1, cbuf.size, cf);
fclose(cf);
vec_free(cbuf);
if (!cok)
LOG_ERROR("ir2c: unsupported IR, see `%s`", outpath);
rc = cok ? 0 : 1;
goto cleanup;
}
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &lang_type.ir, &layout, &attr);
ir2vm_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_IR2VM);
ir2vm.diag = &diag;
@@ -350,6 +372,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_diag_summary(&diag);
goto cleanup;
}
if (dump == DUMP_VM) {
spl_prog_dump(&ir2vm.prog);
goto cleanup;
@@ -437,10 +460,12 @@ int main(int argc, char **argv) {
dump = DUMP_IR;
} else if (strcmp(flags, "vm") == 0) {
dump = DUMP_VM;
} else if (strcmp(flags, "c") == 0) {
dump = DUMP_C;
} else if (strcmp(flags, "none") == 0) {
dump = DUMP_NONE;
} else {
LOG_FATAL("splc0: --dump takes one of lex|ast|sema|ir|vm|none, got `%s`", flags);
LOG_FATAL("splc0: --dump takes one of lex|ast|sema|ir|vm|c|none, got `%s`", flags);
return 1;
}
argi += 2;