Compare commits

..
12 Commits
Author SHA1 Message Date
zzy 6c764bb8a0 refactor(stage1 ai): 抽离 IR 类型系统并让 exec 基于 IR 运行
- IR 类型表并入 spl_ir_t,lang_type 改为借用
- 抽出 spl_ir_type / spl_ir_layout,移除前端专用 IR 类型
- lang 聚合改为 nominal 身份,字段与方法回收到 lang_type
- 新增 spl_ir_link,建立 def/lang_type <-> ir_func/ir_type 双向绑定
- exec 去除 CFG 依赖,plan 由 IR 调用图生成
- meta 不再构建 AST CFG,按 IR 函数按需编译
- host ABI 改为 typed value,支持聚合返回
- @sap.view 改为普通 host op,支持动态 handle
- 新增 nominal 聚合与动态 sap.view 回归测试
2026-12-03 12:31:34 +08:00
zzy 480945a92f ai: stage1 unify IR values and globals
- add spl_ir_value_t (INST/CONST/GLOBAL) and global table
- remove mem.global_alloc and global.ref instructions
- dedup byte constants in a program-level pool
- zero-init aggregate literals in ast2ir; honor undefined
- C backend: fix zero-arg main return, extern prototypes/varargs
- fix dangling inline-module method names (0018 flake)
2026-12-02 22:41:20 +08:00
zzy 663adf6cae ai: 实现mod语法 提供namespace框架 2026-12-02 13:02:58 +08:00
zzy e531aab2d3 ai: 重新设计stage1的spl 让ai重构代码 2026-12-02 12:40:36 +08:00
zzy 032102f1d7 ai: 生成代码准备重构前的一次提交 2026-11-30 12:58:19 +08:00
zzy 936a8d0e88 fix ai修复出现的stage2和stage3问题 2026-11-13 22:15:07 +08:00
zzy 50ee126d44 spl 编写编译器基础框架 ai修复出现的stage2和stage3问题并提供新语法 2026-11-07 21:52:02 +08:00
zzy 126b979f72 stage3 ai编写新语法语义 同时提供fflush 2026-11-05 09:48:43 +08:00
zzy bb8761d392 nob 实现最后一步编译框架 移动测试用例 准备for的新语法 2026-11-02 21:41:19 +08:00
zzy c4d1bbae92 nob 修复popen在linux上的错误行为 2026-10-31 11:15:26 +08:00
zzy b4831c8d1c stage3 ai编写并提供测试用例并重构nob 2026-10-31 11:06:00 +08:00
zzy 2c531f23de stage2 ai重构 2026-10-26 12:51:32 +08:00
314 changed files with 32645 additions and 4559 deletions

No files matched your search

+510 -108
View File
@@ -1,6 +1,6 @@
#define COMMON_CFLAGS "-Wall", "-Wextra", "-D_CRT_SECURE_NO_WARNINGS"
#define SPL_CFLAGS COMMON_CFLAGS, "-O0", "-g"
#define COMMON_CFLAGS "-Wall", "-Wextra", "-D_CRT_SECURE_NO_WARNINGS", "-D_CRT_NONSTDC_NO_DEPRECATE"
#define SPL_CFLAGS COMMON_CFLAGS, "-I.", "-Istage1/include", "-O0", "-g"
#define SPL_OPTIMIZATION_FLAG COMMON_CFLAGS, "-O2"
#define nob_cc_flags(cmd) nob_cmd_append(cmd, SPL_CFLAGS)
#undef UNICODE
@@ -19,7 +19,7 @@
#define BUILD_FOLDER "build/"
// Content of the .cflags stamp file; must match SPL_CFLAGS above.
#define CFLAGS_STR "-Wall -Wextra -O0 -g"
#define CFLAGS_STR "-Wall -Wextra -I. -Istage1/include -O0 -g"
// Stamp file whose mtime is refreshed whenever the flags change so that all
// object files get rebuilt.
static const char *CFLAGS_STAMP = BUILD_FOLDER ".cflags";
@@ -88,15 +88,141 @@ typedef struct {
size_t capacity;
} str_da_t;
static const char *path_basename(const char *path) {
const char *base = path;
for (const char *p = path; *p; p += 1) {
if (*p == '/' || *p == '\\')
base = p + 1;
}
return base;
}
// `*` 匹配任意串。只用来比文件名(不含分隔符),所以不需要处理跨目录。
static bool wildcard_match(const char *pat, const char *s) {
const char *star = NULL;
const char *resume = NULL;
while (*s) {
if (*pat == '*') {
star = pat++;
resume = s;
} else if (*pat == *s) {
pat++;
s++;
} else if (star) {
pat = star + 1;
s = ++resume;
} else {
return false;
}
}
while (*pat == '*')
pat++;
return *pat == '\0';
}
// 依赖模式的展开:只支持两种写法
// dir/*.ext —— 只看 dir 的直接子文件
// dir/**/*.ext —— 递归 dir 的子目录
// 不含 '*' 的条目按字面路径原样返回(跨目录的显式依赖用这个)。
typedef struct {
size_t dir_len;
const char *name_pattern;
bool recursive;
str_da_t *out;
} glob_ctx_t;
static bool collect_glob_entry(Nob_Walk_Entry entry) {
if (entry.type != NOB_FILE_REGULAR)
return true;
glob_ctx_t *ctx = (glob_ctx_t *)entry.data;
const char *rel = entry.path + ctx->dir_len;
while (*rel == '/' || *rel == '\\')
rel++;
if (!ctx->recursive) {
for (const char *p = rel; *p; p += 1) {
if (*p == '/' || *p == '\\')
return true;
}
}
if (!wildcard_match(ctx->name_pattern, path_basename(rel)))
return true;
da_append(ctx->out, nob_temp_strdup(entry.path));
return true;
}
// 某个模式一条都没匹配到就报错:依赖悄悄变空比多编一次危险得多。
static bool expand_patterns(const char **patterns, size_t count, str_da_t *out) {
for (size_t i = 0; i < count; i += 1) {
const char *pat = patterns[i];
if (strchr(pat, '*') == NULL) {
da_append(out, pat);
continue;
}
const char *slash = NULL;
for (const char *p = pat; *p; p += 1) {
if (*p == '/' || *p == '\\')
slash = p;
}
if (slash == NULL || slash == pat) {
nob_log(NOB_ERROR, "pattern `%s` needs a directory part", pat);
return false;
}
size_t dir_len = (size_t)(slash - pat);
const char *name_pattern = slash + 1;
bool recursive = false;
if (dir_len >= 2 && pat[dir_len - 1] == '*' && pat[dir_len - 2] == '*') {
recursive = true;
dir_len -= 2;
while (dir_len > 0 && (pat[dir_len - 1] == '/' || pat[dir_len - 1] == '\\'))
dir_len -= 1;
}
if (dir_len == 0) {
nob_log(NOB_ERROR, "pattern `%s` needs a directory part", pat);
return false;
}
char *dir = nob_temp_sprintf("%.*s", (int)dir_len, pat);
glob_ctx_t ctx = {
.dir_len = dir_len,
.name_pattern = name_pattern,
.recursive = recursive,
.out = out,
};
size_t before = out->count;
if (!nob_walk_dir(dir, collect_glob_entry, .data = &ctx))
return false;
if (out->count == before) {
nob_log(NOB_ERROR, "pattern `%s` matched nothing", pat);
return false;
}
}
return true;
}
bool run_target(const char *name, Nob_Cmd *args);
const char *build_target(const char *name);
static const char *build_exe(build_t *target) {
const char *result = NULL;
Nob_Cmd cmd = {0};
str_da_t objs = {0};
str_da_t deps = {0};
for (size_t i = 0; i < target->exe.srcs_count; ++i) {
const char *src = target->exe.srcs[i];
str_da_t srcs = {0};
str_da_t headers = {0};
// srcs/headers 里可以写通配模式(见 expand_patterns),展开一次给后面所有源文件用。
if (!expand_patterns(target->exe.srcs, target->exe.srcs_count, &srcs))
goto defer;
if (!expand_patterns(target->exe.headers, target->exe.headers_count, &headers))
goto defer;
for (size_t i = 0; i < srcs.count; ++i) {
const char *src = srcs.items[i];
const char *obj = obj_path(src);
if (!nob_file_exists(src)) {
nob_log(NOB_ERROR, "source file `%s` does not exist", src);
@@ -107,8 +233,8 @@ static const char *build_exe(build_t *target) {
da_append(&deps, src);
da_append(&deps, CFLAGS_STAMP);
for (size_t j = 0; j < target->exe.headers_count; ++j) {
da_append(&deps, target->exe.headers[j]);
for (size_t j = 0; j < headers.count; ++j) {
da_append(&deps, headers.items[j]);
}
int needs = nob_needs_rebuild(obj, deps.items, deps.count);
@@ -135,8 +261,10 @@ static const char *build_exe(build_t *target) {
int needs = nob_needs_rebuild(exe, objs.items, objs.count);
if (needs < 0)
goto defer;
if (needs == 0)
return exe;
if (needs == 0) {
result = exe;
goto defer;
}
nob_cc(&cmd);
nob_cmd_append(&cmd, SPL_OPTIMIZATION_FLAG);
@@ -144,21 +272,23 @@ static const char *build_exe(build_t *target) {
nob_cc_inputs(&cmd, objs.items[i]);
}
nob_cc_output(&cmd, exe);
if (!nob_cmd_run(&cmd)) {
if (!nob_cmd_run(&cmd))
goto defer;
}
return exe;
result = exe;
defer:
nob_cmd_free(cmd);
da_free(objs);
da_free(deps);
return NULL;
da_free(srcs);
da_free(headers);
return result;
}
const char *build_target(const char *name) {
if (!prepare_build())
return NULL;
const char *splc_libs = "./src/libs";
for (size_t i = 0; i < NOB_ARRAY_LEN(targets); ++i) {
if (name != NULL && strcmp(targets[i].name, name) != 0) {
continue;
@@ -169,9 +299,33 @@ const char *build_target(const char *name) {
case BUILD_EXE: {
return build_exe(target);
}
case BUILD_SPLC_SIR:
case BUILD_SIR: {
Nob_Cmd cmd = {0};
const char *target_sir = sir_path(name);
// 编译器先建好:它的产物也要算进依赖,编译器变了就得重编 .sir。
const char *compiler = build_target(target->sir.compiler);
if (!compiler) {
nob_log(NOB_ERROR, "failed to build `%s`", name);
return NULL;
}
str_da_t deps = {0};
bool ok = expand_patterns(target->sir.deps, target->sir.deps_count, &deps);
if (ok) {
da_append(&deps, target->sir.src);
da_append(&deps, compiler);
}
int needs = ok ? nob_needs_rebuild(target_sir, deps.items, deps.count) : -1;
da_free(deps);
if (needs < 0)
return NULL;
if (needs == 0)
return target_sir;
Nob_Cmd cmd = {0};
if (target->kind == BUILD_SPLC_SIR) {
nob_cmd_append(&cmd, "-I", splc_libs);
}
nob_cmd_append(&cmd, target->sir.src, target_sir);
if (!run_target(target->sir.compiler, &cmd)) {
nob_log(NOB_ERROR, "failed to build `%s`", name);
@@ -181,34 +335,58 @@ const char *build_target(const char *name) {
nob_cmd_free(cmd);
return target_sir;
}
case BUILD_SPLC_NATIVE:
case BUILD_NATIVE: {
Nob_Cmd cmd = {0};
const char *target_exe = exe_path(name);
const char *target_c = c_path(name);
// TODO need_rebuild
int needs = nob_needs_rebuild(target_c, target->native.deps, target->native.deps_count);
if (needs < 0)
const char *compiler = build_target(target->native.compiler);
if (!compiler) {
nob_log(NOB_ERROR, "failed to build `%s`", name);
return NULL;
}
str_da_t deps = {0};
bool ok = expand_patterns(target->native.deps, target->native.deps_count, &deps);
if (ok) {
da_append(&deps, target->native.src);
da_append(&deps, compiler);
}
int needs = ok ? nob_needs_rebuild(target_c, deps.items, deps.count) : -1;
if (needs < 0) {
da_free(deps);
return NULL;
}
if (needs != 0) {
if (target->kind == BUILD_SPLC_NATIVE) {
nob_cmd_append(&cmd, "-I", splc_libs);
}
nob_cmd_append(&cmd, "--dump", "c", target->native.src, target_c);
if (!run_target(target->native.compiler, &cmd)) {
nob_log(NOB_ERROR, "failed to build `%s`", name);
nob_cmd_free(cmd);
da_free(deps);
return NULL;
}
cmd.count = 0;
}
needs = nob_needs_rebuild(target_exe, target->native.crt_deps,
target->native.crt_deps_count);
// exe 的输入:生成的 .c、SPL 依赖、crt 头。
da_append(&deps, target_c);
for (size_t i = 0; i < target->native.crt_deps_count; i += 1)
da_append(&deps, target->native.crt_deps[i]);
needs = nob_needs_rebuild(target_exe, deps.items, deps.count);
da_free(deps);
if (needs < 0)
return NULL;
if (needs == 0)
return target_exe;
nob_cc(&cmd);
nob_cmd_append(&cmd, "-I./stage0", "-O2", "-D_CRT_SECURE_NO_WARNINGS");
/* 生成的 C 里有跨类型指针访问;-O2 严格别名会误优化。 */
nob_cmd_append(&cmd, "-I./stage0", "-O2", "-fno-strict-aliasing",
"-D_CRT_SECURE_NO_WARNINGS", "-D_CRT_NONSTDC_NO_DEPRECATE");
nob_cc_inputs(&cmd, target_c);
nob_cc_output(&cmd, target_exe);
if (!nob_cmd_run(&cmd)) {
@@ -267,13 +445,37 @@ bool run_target(const char *name, Nob_Cmd *args) {
// ---- 测试 ----
// Expect 协议:扫整个文件的注释行找 `// Expect retcode = N`,取第一条命中(注解可以在任意位置)。
// `// Expect compile_error` 表示编译必须失败;后面可跟一个或多个 E#### 错误码。
// `// Expect stdout = ...` 暂不比较,遇到跳过。
// 返回 false 只表示文件读不出来或 retcode 写坏了;没写注解则 has_retcode 为假,由调用方按 0 处理。
// 返回 false 只表示文件读不出来、retcode 写坏或错误码格式非法;没写注解则 has_retcode
// 为假,由调用方按 0 处理。
typedef struct {
bool has_retcode;
int retcode;
bool compile_error;
int error_codes[8];
size_t error_code_count;
bool has_location;
int line;
int col;
bool pending;
} test_expect_t;
static bool test_parse_error_code(Nob_String_View value, int *out) {
value = nob_sv_trim(value);
if (value.count != 5 || value.data[0] != 'E')
return false;
int v = 0;
size_t i = 1;
for (; i < value.count; i += 1) {
if (!isdigit((unsigned char)value.data[i]))
return false;
v = v * 10 + (value.data[i] - '0');
}
*out = v;
return true;
}
static bool test_parse_int(Nob_String_View value, int *out) {
if (value.count == 0)
return false;
@@ -315,10 +517,56 @@ static bool test_parse_expect(const char *fname, test_expect_t *expect) {
continue;
line = nob_sv_trim_left(nob_sv_from_parts(line.data + 6, line.count - 6));
Nob_String_View key = nob_sv_trim(nob_sv_chop_by_delim(&line, '='));
Nob_String_View key = nob_sv_trim(nob_sv_chop_by_delim(&line, ' '));
Nob_String_View value = nob_sv_trim(line);
if (nob_sv_eq(key, nob_sv_from_cstr("compile_error"))) {
expect->compile_error = true;
if (nob_sv_starts_with(value, nob_sv_from_cstr("="))) {
value = nob_sv_trim_left(nob_sv_from_parts(value.data + 1, value.count - 1));
}
while (value.count > 0) {
Nob_String_View code = nob_sv_trim(nob_sv_chop_by_delim(&value, ' '));
if (code.count == 0)
continue;
int parsed_code = 0;
if (expect->error_code_count >= NOB_ARRAY_LEN(expect->error_codes) ||
!test_parse_error_code(code, &parsed_code)) {
malformed = true;
break;
}
expect->error_codes[expect->error_code_count++] = parsed_code;
}
if (malformed)
break;
continue;
}
if (nob_sv_eq(key, nob_sv_from_cstr("pending"))) {
expect->pending = true;
continue;
}
if (nob_sv_eq(key, nob_sv_from_cstr("location"))) {
if (expect->has_location) {
malformed = true;
break;
}
if (nob_sv_starts_with(value, nob_sv_from_cstr("="))) {
value = nob_sv_trim_left(nob_sv_from_parts(value.data + 1, value.count - 1));
}
Nob_String_View line_sv = nob_sv_trim(nob_sv_chop_by_delim(&value, ':'));
Nob_String_View col_sv = nob_sv_trim(value);
if (!test_parse_int(line_sv, &expect->line) || !test_parse_int(col_sv, &expect->col) ||
expect->line <= 0 || expect->col <= 0) {
malformed = true;
break;
}
expect->has_location = true;
continue;
}
if (!nob_sv_eq(key, nob_sv_from_cstr("retcode")) || expect->has_retcode)
continue;
if (nob_sv_starts_with(value, nob_sv_from_cstr("="))) {
value = nob_sv_trim_left(nob_sv_from_parts(value.data + 1, value.count - 1));
}
int parsed = 0;
if (!test_parse_int(value, &parsed)) {
@@ -341,12 +589,16 @@ typedef struct {
static const test_suite_t TEST_SUITES[] = {
{"stage1", "./tests/stage1/"},
{"spl_core", "./tests/spl_core/"},
{"stage2", "./tests/stage2/"},
{"stage3", "./tests/stage3/"},
};
static const char *TEST_MODE_NAMES[] = {"lex", "ast", "sema", "ir", "vm"};
// 可运行的 target 名(来自 nob_data 的 runs[]),main 里填一次。
static const char *RUN_NAMES[NOB_ARRAY_LEN(runs)];
// 复用 runs[] 与 run_target_dry:构建一次,并拿到"怎么把这个 target 跑起来"的 argv 前缀。
// test/diff 每条用例复制这份前缀再补自己的参数,运行语义因此和 `nob run` 完全一致。
static bool build_run_prefix(const char *name, Nob_Cmd *prefix) {
@@ -354,8 +606,8 @@ static bool build_run_prefix(const char *name, Nob_Cmd *prefix) {
return run_target_dry(name, &no_args, prefix);
}
// `--dump <mode> <file>` 之后统一补一个 <out> 占位:splc0 强制要它,splc1 标成可选,splc2 忽略多余参数。
// 参差的是那几个程序自己的 CLI,不是 exe/.sir 的区别。
// `--dump <mode> <file>` 之后统一补一个 <out> 占位:splc0 强制要它,splc1 标成可选,splc2
// 忽略多余参数。 参差的是那几个程序自己的 CLI,不是 exe/.sir 的区别。
static void append_dump_args(Nob_Cmd *cmd, const char *mode, const char *fname) {
nob_cmd_append(cmd, "--dump", mode, fname, BUILD_FOLDER "dump.sir");
}
@@ -376,20 +628,124 @@ typedef struct {
const scc_argparse_list_t *filters; // 按文件名子串过滤,空则全跑
int passed;
int failed;
int pending; // `// Expect pending` 的预期失败数
int no_expect; // 没写 Expect 注解、按 0 期望的文件数
} test_ctx_t;
static void test_compile_and_run(const char *fname, test_ctx_t *ctx) {
static bool test_has_error_code(const Nob_Cmd_Result *result, int code) {
char needle[24] = {0};
snprintf(needle, sizeof(needle), "error[E%04d]", code);
return result->out.items != NULL && strstr(result->out.items, needle) != NULL;
}
static void test_pending_compile_and_run(const char *fname, test_ctx_t *ctx) {
Nob_Cmd compile = {0};
nob_cmd_extend(&compile, &ctx->compiler);
nob_cmd_append(&compile, fname, ctx->out_sir);
bool compiled = nob_cmd_run(&compile);
Nob_Cmd_Result compile_result = {0};
if (!run_capture(&compile, &compile_result)) {
nob_log(NOB_ERROR, "%s: failed to launch compiler", fname);
nob_cmd_free(compile);
if (!compiled) {
nob_log(NOB_ERROR, "%s: compile failed", fname);
ctx->failed += 1;
return;
}
nob_cmd_free(compile);
if (compile_result.exit_code != 0) {
nob_log(NOB_INFO, "%s: pending (compile failed as expected)", fname);
nob_cmd_result_free(compile_result);
ctx->pending += 1;
return;
}
nob_cmd_result_free(compile_result);
Nob_Cmd run = {0};
nob_cmd_extend(&run, &ctx->vm);
nob_cmd_append(&run, ctx->out_sir);
Nob_Cmd_Result result = {0};
if (!run_capture(&run, &result)) {
nob_log(NOB_ERROR, "%s: failed to run", fname);
nob_cmd_free(run);
ctx->failed += 1;
return;
}
nob_cmd_free(run);
if (result.exit_code != 0) {
nob_log(NOB_INFO, "%s: pending (run failed as expected)", fname);
ctx->pending += 1;
} else {
nob_log(NOB_ERROR, "%s: pending test passed unexpectedly; remove `// Expect pending`",
fname);
ctx->failed += 1;
}
nob_cmd_result_free(result);
}
static void test_compile_and_run(const char *fname, test_ctx_t *ctx) {
test_expect_t expect = {0};
if (!test_parse_expect(fname, &expect)) {
nob_log(NOB_ERROR, "%s: broken `// Expect` annotation", fname);
ctx->failed += 1;
return;
}
if (expect.pending) {
test_pending_compile_and_run(fname, ctx);
return;
}
Nob_Cmd compile = {0};
nob_cmd_extend(&compile, &ctx->compiler);
nob_cmd_append(&compile, fname, ctx->out_sir);
Nob_Cmd_Result compile_result = {0};
if (!run_capture(&compile, &compile_result)) {
nob_log(NOB_ERROR, "%s: failed to launch compiler", fname);
nob_cmd_free(compile);
ctx->failed += 1;
return;
}
nob_cmd_free(compile);
bool compiled = compile_result.exit_code == 0;
if (expect.compile_error) {
if (compiled) {
nob_log(NOB_ERROR, "%s: expected compile failure, but it compiled", fname);
ctx->failed += 1;
} else {
size_t i = 0;
bool missing = false;
for (; i < expect.error_code_count; i += 1) {
if (!test_has_error_code(&compile_result, expect.error_codes[i])) {
nob_log(NOB_ERROR, "%s: missing expected error E%04d", fname,
expect.error_codes[i]);
missing = true;
}
}
if (expect.has_location && !missing) {
char needle[64];
snprintf(needle, sizeof(needle), ":%d:%d:", expect.line, expect.col);
if (strstr(compile_result.out.items, needle) == NULL) {
nob_log(NOB_ERROR, "%s: missing expected source location %d:%d", fname,
expect.line, expect.col);
missing = true;
}
}
if (missing) {
nob_log(NOB_ERROR, "%s: compiler output:\n%.*s", fname,
(int)compile_result.out.count, compile_result.out.items);
ctx->failed += 1;
} else {
ctx->passed += 1;
}
}
nob_cmd_result_free(compile_result);
return;
}
if (!compiled) {
nob_log(NOB_ERROR, "%s: compile failed:\n%.*s", fname, (int)compile_result.out.count,
compile_result.out.items);
nob_cmd_result_free(compile_result);
ctx->failed += 1;
return;
}
nob_cmd_result_free(compile_result);
Nob_Cmd run = {0};
nob_cmd_extend(&run, &ctx->vm);
@@ -403,11 +759,6 @@ static void test_compile_and_run(const char *fname, test_ctx_t *ctx) {
}
nob_cmd_free(run);
test_expect_t expect = {0};
if (!test_parse_expect(fname, &expect)) {
nob_log(NOB_ERROR, "%s: broken `// Expect retcode = N`", fname);
ctx->failed += 1;
} else {
if (!expect.has_retcode) {
expect.retcode = 0; // 没写注解的库测试按"跑完退出 0"处理
ctx->no_expect += 1;
@@ -419,7 +770,6 @@ static void test_compile_and_run(const char *fname, test_ctx_t *ctx) {
} else {
ctx->passed += 1;
}
}
nob_cmd_result_free(result);
}
@@ -456,15 +806,6 @@ typedef struct {
void *user_data;
} walk_ctx_t;
static const char *path_basename(const char *path) {
const char *base = path;
for (const char *p = path; *p; p += 1) {
if (*p == '/' || *p == '\\')
base = p + 1;
}
return base;
}
static bool walk_match_filter(const char *path, const scc_argparse_list_t *filters) {
if (filters->count == 0)
return true;
@@ -583,13 +924,51 @@ static bool delete_directory_recursively(const char *dir_path) {
return nob_walk_dir(dir_path, delete_walk_entry, .post_order = true);
}
static void add_opt_choices(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
const char *group, const char **values, int count, int *store,
cbool required) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
opt.group = group;
scc_argparse_spec_setup_choices(&opt.spec, values, count, store);
opt.spec.flag_required = required;
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_opt_list(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
const char *group, scc_argparse_list_t *vec, cbool required) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
opt.group = group;
scc_argparse_spec_setup_list(&opt.spec, vec);
opt.spec.flag_required = required;
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_arg_string(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
const char **store, cbool required) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_string(&arg.spec, store);
arg.spec.flag_required = required;
scc_argparse_cmd_add_arg(cmd, &arg);
}
static void add_arg_list(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
scc_argparse_list_t *vec) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_list(&arg.spec, vec);
scc_argparse_cmd_add_arg(cmd, &arg);
}
typedef struct {
cbool build, run, test, diff, clean, list; // 命中的子命令
scc_argparse_list_t build_targets;
const char *run_target;
scc_argparse_list_t run_args;
int test_suite; // TEST_SUITES 下标
const char *test_target; // 用哪个编译器编,NULL 用 suite 默认
int test_target; // RUN_NAMES 下标,required
int test_mode; // TEST_MODE_NAMES 下标,-1 表示不做 dump
scc_argparse_list_t test_filters;
const char *diff_expect;
@@ -624,7 +1003,7 @@ static int cli_run(nob_cli_t *cli) {
static int cli_test(nob_cli_t *cli) {
const test_suite_t *suite = &TEST_SUITES[cli->test_suite];
const char *target = cli->test_target;
const char *target = RUN_NAMES[cli->test_target];
const char *mode = (cli->test_mode >= 0) ? TEST_MODE_NAMES[cli->test_mode] : NULL;
if (!prepare_build())
@@ -650,11 +1029,11 @@ static int cli_test(nob_cli_t *cli) {
bool walked = walk_spl_files(suite->dir, &cli->test_filters, test_run_file, &ctx);
if (ctx.no_expect > 0)
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed (%d without `// Expect`)", suite->name,
target, ctx.passed, ctx.failed, ctx.no_expect);
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed, %d pending (%d without `// Expect`)",
suite->name, target, ctx.passed, ctx.failed, ctx.pending, ctx.no_expect);
else
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed", suite->name, target, ctx.passed,
ctx.failed);
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed, %d pending", suite->name, target,
ctx.passed, ctx.failed, ctx.pending);
nob_cmd_free(ctx.compiler);
nob_cmd_free(ctx.vm);
@@ -702,9 +1081,66 @@ static int cli_clean(void) {
return 0;
}
// 全部从 nob_data 的 targets[] / runs[] 生成:加目标只需改数据,这里不用动。
static const char *build_kind_name(int kind) {
switch (kind) {
case BUILD_EXE:
return "exe";
case BUILD_EXE_WITH_OPTIMIZATION:
return "exe -O2";
case BUILD_SIR:
return "sir";
case BUILD_NATIVE:
return "native";
default:
return "?";
}
}
// list 显示展开后的真实文件数,而不是"模式条数"。
static size_t count_files(const char **patterns, size_t count) {
str_da_t out = {0};
bool ok = expand_patterns(patterns, count, &out);
size_t n = ok ? out.count : count;
da_free(out);
return n;
}
static int cli_list(void) {
printf("targets (%zu):\n", (size_t)NOB_ARRAY_LEN(targets));
printf(" %-12s %-9s %s\n", "NAME", "KIND", "DETAIL");
for (size_t i = 0; i < NOB_ARRAY_LEN(targets); ++i) {
nob_log(NOB_INFO, "%s:", targets[i].name);
const build_t *t = &targets[i];
const char *kind = build_kind_name(t->kind);
switch (t->kind) {
case BUILD_EXE:
case BUILD_EXE_WITH_OPTIMIZATION:
printf(" %-12s %-9s srcs=%zu headers=%zu\n", t->name, kind,
count_files(t->exe.srcs, t->exe.srcs_count),
count_files(t->exe.headers, t->exe.headers_count));
break;
case BUILD_SPLC_SIR:
case BUILD_SIR:
printf(" %-12s %-9s %s <- %s deps=%zu\n", t->name, kind, t->sir.src, t->sir.compiler,
count_files(t->sir.deps, t->sir.deps_count));
break;
case BUILD_SPLC_NATIVE:
case BUILD_NATIVE:
printf(" %-12s %-9s %s <- %s deps=%zu crt=%zu\n", t->name, kind, t->native.src,
t->native.compiler, count_files(t->native.deps, t->native.deps_count),
t->native.crt_deps_count);
break;
}
}
printf("\nrun targets (%zu):\n", (size_t)NOB_ARRAY_LEN(runs));
printf(" %-12s %s\n", "NAME", "COMMAND");
for (size_t i = 0; i < NOB_ARRAY_LEN(runs); ++i) {
if (runs[i].interpreter)
printf(" %-12s %s %s\n", runs[i].name, exe_path(runs[i].interpreter),
sir_path(runs[i].name));
else
printf(" %-12s %s\n", runs[i].name, exe_path(runs[i].name));
}
return 0;
}
@@ -732,6 +1168,7 @@ int main(int argc, char **argv) {
set_log_handler(nob_cancer_log_handler);
nob_cli_t cli = {0};
cli.test_target = -1;
cli.test_mode = -1;
cli.diff_mode = -1;
@@ -739,27 +1176,20 @@ int main(int argc, char **argv) {
scc_argparse_init(&parser, argv[0], "SPL C-side bootstrap build system (nob)");
scc_argparse_cmd_t *root = scc_argparse_get_root(&parser);
for (size_t i = 0; i < NOB_ARRAY_LEN(runs); i += 1)
RUN_NAMES[i] = runs[i].name;
scc_argparse_cmd_t build_cmd;
scc_argparse_cmd_init(&build_cmd, "build", "build all targets or the given ones");
scc_argparse_cmd_set_triggered(&build_cmd, &cli.build);
scc_argparse_arg_t targets_arg;
scc_argparse_arg_init(&targets_arg, "targets", "target names, default all");
scc_argparse_spec_setup_list(&targets_arg.spec, &cli.build_targets);
scc_argparse_cmd_add_arg(&build_cmd, &targets_arg);
add_arg_list(&build_cmd, "targets", "target names, default all", &cli.build_targets);
scc_argparse_cmd_add_subcmd(root, &build_cmd);
scc_argparse_cmd_t run_cmd;
scc_argparse_cmd_init(&run_cmd, "run", "build and run a target");
scc_argparse_cmd_set_triggered(&run_cmd, &cli.run);
scc_argparse_arg_t run_target_arg;
scc_argparse_arg_init(&run_target_arg, "target", "target name");
scc_argparse_spec_setup_string(&run_target_arg.spec, &cli.run_target);
scc_argparse_spec_set_required(&run_target_arg.spec, true);
scc_argparse_arg_t run_args_arg;
scc_argparse_arg_init(&run_args_arg, "args", "arguments for the target");
scc_argparse_spec_setup_list(&run_args_arg.spec, &cli.run_args);
scc_argparse_cmd_add_arg(&run_cmd, &run_target_arg);
scc_argparse_cmd_add_arg(&run_cmd, &run_args_arg);
add_arg_string(&run_cmd, "target", "target name", &cli.run_target, true);
add_arg_list(&run_cmd, "args", "arguments for the target", &cli.run_args);
scc_argparse_cmd_add_subcmd(root, &run_cmd);
scc_argparse_cmd_t test_cmd;
@@ -768,55 +1198,27 @@ int main(int argc, char **argv) {
const char *suite_names[NOB_ARRAY_LEN(TEST_SUITES)];
for (size_t i = 0; i < NOB_ARRAY_LEN(TEST_SUITES); i += 1)
suite_names[i] = TEST_SUITES[i].name;
scc_argparse_arg_t test_target_arg;
scc_argparse_arg_init(&test_target_arg, "target", "compiler target, e.g. splc0|splc1|splc2");
scc_argparse_spec_setup_string(&test_target_arg.spec, &cli.test_target);
scc_argparse_spec_set_required(&test_target_arg.spec, true);
scc_argparse_cmd_add_arg(&test_cmd, &test_target_arg);
scc_argparse_opt_t suite_opt;
scc_argparse_opt_init(&suite_opt, 's', "suite", "test suite, default stage1");
scc_argparse_spec_setup_choices(&suite_opt.spec, suite_names, (int)NOB_ARRAY_LEN(TEST_SUITES),
&cli.test_suite);
scc_argparse_cmd_add_opt(&test_cmd, &suite_opt);
scc_argparse_opt_t mode_opt;
scc_argparse_opt_init(&mode_opt, 'm', "mode", "dump smoke test through the target");
scc_argparse_spec_setup_choices(&mode_opt.spec, TEST_MODE_NAMES,
(int)NOB_ARRAY_LEN(TEST_MODE_NAMES), &cli.test_mode);
scc_argparse_cmd_add_opt(&test_cmd, &mode_opt);
scc_argparse_opt_t filters_opt;
scc_argparse_opt_init(&filters_opt, 'f', "filter", "file name filter, repeatable");
scc_argparse_spec_setup_list(&filters_opt.spec, &cli.test_filters);
scc_argparse_cmd_add_opt(&test_cmd, &filters_opt);
add_opt_choices(&test_cmd, 't', "target", "compiler target, from nob_data runs[]", NULL,
RUN_NAMES, (int)NOB_ARRAY_LEN(runs), &cli.test_target, true);
add_opt_choices(&test_cmd, 's', "suite", "test suite, default stage1", NULL, suite_names,
(int)NOB_ARRAY_LEN(TEST_SUITES), &cli.test_suite, false);
add_opt_choices(&test_cmd, 'm', "mode", "dump smoke test through the target", "Dump",
TEST_MODE_NAMES, (int)NOB_ARRAY_LEN(TEST_MODE_NAMES), &cli.test_mode, false);
add_opt_list(&test_cmd, 'f', "filter", "file name filter, repeatable", "Filtering",
&cli.test_filters, false);
scc_argparse_cmd_add_subcmd(root, &test_cmd);
scc_argparse_cmd_t diff_cmd;
scc_argparse_cmd_init(&diff_cmd, "diff", "compare two targets' `--dump` output");
scc_argparse_cmd_set_triggered(&diff_cmd, &cli.diff);
scc_argparse_arg_t expect_arg;
scc_argparse_arg_init(&expect_arg, "expect", "reference build target");
scc_argparse_spec_setup_string(&expect_arg.spec, &cli.diff_expect);
scc_argparse_spec_set_required(&expect_arg.spec, true);
scc_argparse_arg_t got_arg;
scc_argparse_arg_init(&got_arg, "got", "build target under test");
scc_argparse_spec_setup_string(&got_arg.spec, &cli.diff_got);
scc_argparse_spec_set_required(&got_arg.spec, true);
scc_argparse_cmd_add_arg(&diff_cmd, &expect_arg);
scc_argparse_cmd_add_arg(&diff_cmd, &got_arg);
scc_argparse_opt_t diff_mode_opt;
scc_argparse_opt_init(&diff_mode_opt, 'm', "mode", "dump mode");
scc_argparse_spec_setup_choices(&diff_mode_opt.spec, TEST_MODE_NAMES,
(int)NOB_ARRAY_LEN(TEST_MODE_NAMES), &cli.diff_mode);
scc_argparse_spec_set_required(&diff_mode_opt.spec, true);
scc_argparse_cmd_add_opt(&diff_cmd, &diff_mode_opt);
scc_argparse_opt_t diff_suite_opt;
scc_argparse_opt_init(&diff_suite_opt, 's', "suite", "test suite, default stage1");
scc_argparse_spec_setup_choices(&diff_suite_opt.spec, suite_names,
(int)NOB_ARRAY_LEN(TEST_SUITES), &cli.diff_suite);
scc_argparse_cmd_add_opt(&diff_cmd, &diff_suite_opt);
scc_argparse_opt_t diff_filter_opt;
scc_argparse_opt_init(&diff_filter_opt, 'f', "filter", "file name filter, repeatable");
scc_argparse_spec_setup_list(&diff_filter_opt.spec, &cli.diff_filters);
scc_argparse_cmd_add_opt(&diff_cmd, &diff_filter_opt);
add_arg_string(&diff_cmd, "expect", "reference build target", &cli.diff_expect, true);
add_arg_string(&diff_cmd, "got", "build target under test", &cli.diff_got, true);
add_opt_choices(&diff_cmd, 'm', "mode", "dump mode", NULL, TEST_MODE_NAMES,
(int)NOB_ARRAY_LEN(TEST_MODE_NAMES), &cli.diff_mode, true);
add_opt_choices(&diff_cmd, 's', "suite", "test suite, default stage1", NULL, suite_names,
(int)NOB_ARRAY_LEN(TEST_SUITES), &cli.diff_suite, false);
add_opt_list(&diff_cmd, 'f', "filter", "file name filter, repeatable", NULL, &cli.diff_filters,
false);
scc_argparse_cmd_add_subcmd(root, &diff_cmd);
scc_argparse_cmd_t clean_cmd;
+408 -87
View File
@@ -96,6 +96,9 @@ typedef struct {
usize capacity;
} scc_argparse_cmd_vec_t;
/**
* @brief 值类型:决定该参数怎么解析、写进 spec.store 的哪个成员。
*/
typedef enum scc_argparse_val_type {
SCC_ARGPARSE_VAL_TYPE_UNKNOWN,
SCC_ARGPARSE_VAL_TYPE_STRING,
@@ -107,39 +110,51 @@ typedef enum scc_argparse_val_type {
SCC_ARGPARSE_VAL_TYPE_COUNT,
} scc_argparse_val_type_t;
/**
* @brief 解析结果码。
* @note 帮助/版本请求也走返回值上报(PNT_DEFAULT),调用方应把它当成功处理。
*/
typedef enum scc_argparse_err {
SCC_ARGPARSE_ERR_NONE,
SCC_ARGPARSE_ERR_UNREACHABLE,
SCC_ARGPARSE_ERR_PNT_DEFAULT,
SCC_ARGPARSE_ERR_UNKNOWN_ERR,
SCC_ARGPARSE_ERR_INVALID_ARG,
SCC_ARGPARSE_ERR_INVALID_VALUE,
SCC_ARGPARSE_ERR_MISSING_ARG,
SCC_ARGPARSE_ERR_MISSING_VALUE,
SCC_ARGPARSE_ERR_UNKNOWN_ARG,
SCC_ARGPARSE_ERR_UNKNOWN_VALUE,
SCC_ARGPARSE_ERR_NONE, ///< 成功
SCC_ARGPARSE_ERR_UNREACHABLE, ///< 内部状态错误,不应出现
SCC_ARGPARSE_ERR_PNT_DEFAULT, ///< -h/--help/--version 已处理,调用方按成功退出
SCC_ARGPARSE_ERR_UNKNOWN_ERR, ///< 底层解析器返回了未映射的错误
SCC_ARGPARSE_ERR_INVALID_ARG, ///< 参数/选项本身非法
SCC_ARGPARSE_ERR_INVALID_VALUE, ///< 值不合法(枚举越界、整数/浮点解析失败等)
SCC_ARGPARSE_ERR_MISSING_ARG, ///< 缺少必需的位置参数或选项
SCC_ARGPARSE_ERR_MISSING_VALUE, ///< 选项缺少值
SCC_ARGPARSE_ERR_UNKNOWN_ARG, ///< 未知参数
SCC_ARGPARSE_ERR_UNKNOWN_VALUE, ///< 未知值
SCC_ARGPARSE_ERR_SUBCMD_TOO_DEEP, ///< 子命令嵌套超过 max_subcmd_depth
} scc_argparse_err_t;
/**
* @brief 字符串列表:LIST 类型的存储,也是 --filter 这类可重复选项的落点。
* @note items 由库 push,调用方负责 free。
*/
typedef struct {
const char **items;
usize count;
usize capacity;
} scc_argparse_list_t;
// 约束规范结构体
/**
* @brief 一条参数/选项的约束与落点:值类型、存储位置、枚举候选、各种标志。
* @note 用 scc_argparse_spec_init 复位,再用 spec_setup_* / spec_set_* 配置。
*/
struct scc_argparse_spec {
scc_argparse_val_type_t value_type; // 值类型
const char *raw_value;
const char *raw_value; // 最近一次收到的原始值(validate 用它判断"给没给")
// 存储位置
// 存储位置(按 value_type 选其一)
union {
cbool *bool_store; // 布尔值存储
int *int_store; // 整数存储
int *int_store; // 整数/计数/枚举下标存储
float *float_store; // 浮点数存储
const char **str_store; // 字符串存储
char **str_alloc_store; // 字符串存储(使用alloc,需要free)
void **ptr_store; // 通用指针存储
scc_argparse_list_t *vec_store; // 新增:指向字符串向量的指针
scc_argparse_list_t *vec_store; // 列表存储
} store;
// 枚举值约束
@@ -149,27 +164,37 @@ struct scc_argparse_spec {
} choices;
// 其他约束标志
cbool flag_required; // 是否必须
cbool flag_store_as_count; // 是否存储为计数(如 -vvv 返回3)
cbool flag_allow_empty; // 是否允许空字符串
cbool flag_hidden; // 是否隐藏(不显示在帮助)
cbool flag_takes_multiple; // 是否接受多个值(如 -I dir1 -I dir2)
cbool flag_parse_complex; // 是否进行复杂解析(如 1K, 2M, 3G)
cbool flag_required; // 必需:缺失报 MISSING_ARG
cbool flag_store_as_count; // 计数模式(-vvv → 3),由 setup_count 自动开启
cbool flag_allow_empty; // 允许 --opt= 这样的空值
cbool flag_hidden; // 不出现在帮助里
cbool flag_takes_multiple; // LIST 一次吃掉后续多个 token;false 表示一次一个值、靠重复出现
cbool flag_parse_complex; // 预留(1K/2M/3G 之类),当前未实现
};
/**
* @brief 位置参数:按添加顺序消费,适合"主语"型输入(文件名、目标名)。
*/
struct scc_argparse_arg {
scc_argparse_spec_t spec;
const char *name;
const char *description;
};
/**
* @brief 选项:短名/长名至少有一个,值怎么解析由 spec 决定。
*/
struct scc_argparse_opt {
scc_argparse_spec_t spec;
char short_name;
const char *long_name;
const char *description;
const char *group; // 帮助里的分组标题;NULL = 归到默认的 "Options" 段
};
/**
* @brief 一条命令或子命令:自身的参数/选项,加上它下面的子命令。
*/
struct scc_argparse_cmd {
const char *name;
const char *description;
@@ -179,6 +204,9 @@ struct scc_argparse_cmd {
scc_argparse_cmd_vec_t subcmds;
};
/**
* @brief 帮助/错误文本的语言。
*/
typedef enum {
SCC_ARGPARSE_LANG_EN,
SCC_ARGPARSE_LANG_ZH,
@@ -187,6 +215,10 @@ typedef enum {
#ifndef __SCC_FMT_H__
#define __SCC_FMT_H__
/**
* @brief 动态 char 数组,用作帮助/错误文本的输出缓冲。
* @note 不是以 '\0' 结尾的 C 字符串;输出时请用 items + count。
*/
typedef struct {
char *items;
usize count;
@@ -399,6 +431,10 @@ void scc_fmt(scc_str_t *out, const char *tpl, ...) {
}
#endif // __SCC_FMT_H__
/**
* @brief 解析器:配置 + 根命令 + 输出缓冲。
* @note 用 scc_argparse_init 初始化;帮助/错误文本落在 out 里,库不负责打印。
*/
typedef struct {
const char *prog_name;
const char *version;
@@ -410,11 +446,12 @@ typedef struct {
char short_prefix; // 短选项前缀,默认 '-'
const char *long_prefix; // 长选项前缀,默认 "--"
const char *separator; // 分隔符,默认 "--";nullptr = 不识别
cbool need_help;
cbool need_version;
cbool need_debug;
cbool need_error_add_help;
cbool need_error_add_usage;
int max_subcmd_depth; // 子命令最大嵌套层数(root 算 0),0 = 不限(默认)
cbool need_help; // 自动挂 -h/--help
cbool need_version; // 自动挂 --version
cbool need_debug; // 每次 parse 打印一条调试行
cbool need_error_add_help; // 报错时附完整帮助
cbool need_error_add_usage; // 报错时附用法行
} scc_argparse_t;
typedef struct {
@@ -423,44 +460,138 @@ typedef struct {
usize capacity;
} scc_optparse_opt_vec_t;
/**
* @brief 一次解析的上下文:当前命令、底层解析器状态、位置参数游标。
* @note 只在 scc_argparse_parse 内部使用,生命周期止于该函数返回。
*/
typedef struct {
scc_argparse_cmd_t *current_cmd; // 当前正在解析的命令
scc_optparse_t optparse; // 底层解析器
scc_optparse_opt_vec_t opts; // 当前命令的选项列表
scc_optparse_result_t result; // 底层解析结果
const void *err_ctx; // 错误上下文(期待的参数或者当前解析的参数)
int depth; // 当前子命令嵌套深度,root = 0
int positional_index; // 当前处理的位置参数索引
cbool parsing_done; // 是否已完成解析
} scc_argparse_context_t;
/**
* @brief 初始化解析器:清零输出缓冲、设置默认前缀/分隔符与语言/开关位。
* @param parser 待初始化的解析器,不必预先清零。
* @param program_name 程序名,用于用法行与 --version。
* @param description 一句话描述,可为 NULL。
*/
void scc_argparse_init(scc_argparse_t *parser, const char *program_name, const char *description);
/**
* @brief 取根命令,用来挂选项、位置参数和子命令。
* @param parser 已初始化的解析器。
* @return 根命令;生命周期与 parser 相同,不要单独释放。
*/
scc_argparse_cmd_t *scc_argparse_get_root(scc_argparse_t *parser);
/**
* @brief 释放解析器持有的所有 vector(含各子命令拷贝里的 args/opts/subcmds)与输出缓冲。
* @param parser 解析器。
* @note 不会释放调用方绑到 store 上的存储。
*/
void scc_argparse_drop(scc_argparse_t *parser);
/**
* @brief 解析 argv。
* @param parser 已配置好的解析器。
* @param argc 参数个数。
* @param argv 参数数组;argv[0] 视为程序名并跳过。
* @return SCC_ARGPARSE_ERR_NONE 成功;SCC_ARGPARSE_ERR_PNT_DEFAULT 表示 -h/--version 已处理
* (应视为成功退出);其余为错误码,具体见 scc_argparse_err_t。
* @note 帮助与错误文本只追加进 parser->out,库从不打印,调用方需自行回显。
*/
int scc_argparse_parse(scc_argparse_t *parser, int argc, const char **argv);
// 选项前缀与分隔符:nullptr = 关闭该项(例如 DOS 风格用 short='/', long="/", separator=nullptr)。
/**
* @brief 配置选项前缀与分隔符,需在 parse 之前调用。
* @param short_prefix 短选项前缀,0 表示不支持短选项。
* @param long_prefix 长选项前缀(长度任意),NULL 表示不支持长选项。
* @param separator 分隔符(整 token 精确匹配),NULL 表示不识别。
* @note DOS 风格可以传 ('/', "/", NULL);短名与长名同前缀时,/x 会先按长名查找。
*/
void scc_argparse_set_prefix(scc_argparse_t *parser, char short_prefix, const char *long_prefix,
const char *separator);
/**
* @brief 限制子命令的最大嵌套层数(root 算第 0 层),需在 parse 之前调用。
* @param parser 解析器。
* @param depth 最大层数:1 表示只允许 root 的直接子命令;0 表示不限(默认)。
* @note 超限时报 SCC_ARGPARSE_ERR_SUBCMD_TOO_DEEP,错误上下文是那个子命令名。
*/
void scc_argparse_set_max_subcmd_depth(scc_argparse_t *parser, int depth);
/**
* @brief 初始化一条命令/子命令。
* @param cmd 待初始化的命令。
* @param name 命令名;NULL 时取 "cmd_name"。
* @param description 描述,可为 NULL。
*/
void scc_argparse_cmd_init(scc_argparse_cmd_t *cmd, const char *name, const char *description);
/**
* @brief 释放命令持有的 vector,并递归到子命令。
* @param cmd 命令。
* @warning 已被 add_subcmd 浅拷贝走全部权的命令,不要再对它调用本函数。
*/
void scc_argparse_cmd_drop(scc_argparse_cmd_t *cmd);
/**
* @brief 绑定"该子命令被命中"的标记。
* @param cmd 子命令。
* @param store 命中时置 true 的存储;NULL 表示不记录。
* @note 库负责路由,调用方解析后只读这些标记就能分派。
*/
static inline void scc_argparse_cmd_set_triggered(scc_argparse_cmd_t *cmd, cbool *store) {
cmd->triggered = store;
}
/**
* @brief 追加一个位置参数,按添加顺序消费。
* @param cmd 命令。
* @param arg 参数描述;按值拷贝,arg 本身可复用。
* @note LIST 类型会吃掉其后所有位置参数;ENUM 类型同样支持 choices 校验。
*/
void scc_argparse_cmd_add_arg(scc_argparse_cmd_t *cmd, const scc_argparse_arg_t *arg);
/**
* @brief 追加一个选项。
* @param cmd 命令。
* @param opt 选项描述;按值拷贝。
*/
void scc_argparse_cmd_add_opt(scc_argparse_cmd_t *cmd, const scc_argparse_opt_t *opt);
/**
* @brief 追加一个子命令。
* @param cmd 父命令。
* @param subcmd 子命令。
* @warning 浅拷贝:subcmd->args / opts / subcmds 的底层 items 所有权转移给 cmd。
* 调用 add_subcmd 之后,不要再对 subcmd 调用 scc_argparse_cmd_drop,
* 也不要再修改 subcmd 及其 vector。parser 销毁时会递归释放。
*/
void scc_argparse_cmd_add_subcmd(scc_argparse_cmd_t *cmd, const scc_argparse_cmd_t *subcmd);
/**
* @brief 把命令的帮助文本追加进 parser->out。
* @param parser 解析器(提供输出缓冲与语言)。
* @param cmd 要打印的命令。
*/
void scc_argparse_print_help(scc_argparse_t *parser, scc_argparse_cmd_t *cmd);
/**
* @brief 把错误文本(含用法行或帮助提示)追加进 parser->out。
* @param ctx 解析上下文,提供出错位置信息。
* @param parser 解析器。
* @param err 错误码。
*/
void scc_argparse_print_error(scc_argparse_context_t *ctx, scc_argparse_t *parser,
scc_argparse_err_t err);
/**
* @brief 把 spec 复位成"字符串值 + 无标志位"的默认状态。
* @param spec 约束。
*/
static inline void scc_argparse_spec_init(scc_argparse_spec_t *spec) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_STRING;
spec->raw_value = nullptr;
@@ -477,14 +608,38 @@ static inline void scc_argparse_spec_init(scc_argparse_spec_t *spec) {
spec->flag_parse_complex = false;
}
/**
* @brief 初始化一个选项,spec 取默认值(字符串类型)。
* @param opt 选项。
* @param short_name 短名,0 表示没有短名。
* @param long_name 长名,NULL 表示没有长名。
* @param desc 帮助描述,可为 NULL。
*/
static inline void scc_argparse_opt_init(scc_argparse_opt_t *opt, char short_name,
const char *long_name, const char *desc) {
opt->short_name = short_name;
opt->long_name = long_name;
opt->description = desc;
opt->group = nullptr;
scc_argparse_spec_init(&opt->spec);
}
/**
* @brief 给选项设置帮助分组标题。
* @param opt 选项。
* @param group 分组名,NULL 表示回到默认的 "Options" 段。
* @note 分组只影响帮助排版;分组按首次声明顺序出现。
*/
static inline void scc_argparse_opt_set_group(scc_argparse_opt_t *opt, const char *group) {
opt->group = group;
}
/**
* @brief 初始化一个位置参数,spec 取默认值(字符串类型)。
* @param arg 位置参数。
* @param name 帮助里显示的名字。
* @param desc 帮助描述,可为 NULL。
*/
static inline void scc_argparse_arg_init(scc_argparse_arg_t *arg, const char *name,
const char *desc) {
arg->name = name;
@@ -492,32 +647,66 @@ static inline void scc_argparse_arg_init(scc_argparse_arg_t *arg, const char *na
scc_argparse_spec_init(&arg->spec);
}
/**
* @brief 设成布尔开关:出现即置 *store = true。
* @param spec 约束。
* @param store 存储;必须非 NULL。
*/
static inline void scc_argparse_spec_setup_bool(scc_argparse_spec_t *spec, cbool *store) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_BOOL;
spec->store.bool_store = store;
}
/**
* @brief 设成计数:每出现一次 *store += 1(-vvv 得到 3)。
* @param spec 约束。
* @param store 存储;必须非 NULL。
*/
static inline void scc_argparse_spec_setup_count(scc_argparse_spec_t *spec, int *store) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_COUNT;
spec->flag_store_as_count = true; // 自动设为计数模式
spec->store.int_store = store;
}
/**
* @brief 设成字符串:*store 直接指向 argv 里的原串。
* @param spec 约束。
* @param store 存储;必须非 NULL。
* @note 不做拷贝,生命周期跟随 argv。
*/
static inline void scc_argparse_spec_setup_string(scc_argparse_spec_t *spec, const char **store) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_STRING;
spec->store.str_store = store;
}
/**
* @brief 设成整数:解析失败报 SCC_ARGPARSE_ERR_INVALID_VALUE。
* @param spec 约束。
* @param store 存储;必须非 NULL。
*/
static inline void scc_argparse_spec_setup_int(scc_argparse_spec_t *spec, int *store) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_INT;
spec->store.int_store = store;
}
/**
* @brief 设成浮点:解析失败报 SCC_ARGPARSE_ERR_INVALID_VALUE。
* @param spec 约束。
* @param store 存储;必须非 NULL。
*/
static inline void scc_argparse_spec_setup_float(scc_argparse_spec_t *spec, float *store) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_FLOAT;
spec->store.float_store = store;
}
/**
* @brief 设成枚举:存命中项在 values 里的下标,非法值报 INVALID_VALUE。
* @param spec 约束。
* @param values 允许值数组,生命周期需覆盖 parse。
* @param count values 的个数。
* @param store 命中下标存储;未命中时被写成 -1。
* @note 选项和位置参数都支持枚举校验。
*/
static inline void scc_argparse_spec_setup_choices(scc_argparse_spec_t *spec, const char **values,
int count, int *store) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_ENUM;
@@ -526,7 +715,13 @@ static inline void scc_argparse_spec_setup_choices(scc_argparse_spec_t *spec, co
spec->store.int_store = store;
}
// 添加设置列表的辅助函数(内联)
/**
* @brief 设成列表:每次出现往 vec 里 push 一个原串。
* @param spec 约束。
* @param vec 目标列表;由库 push,调用方负责释放其 items。
* @note 默认一次一个值(可重复出现);要"一次吃掉后面所有 token"请再调
* scc_argparse_spec_set_takes_multiple(spec, true)。
*/
static inline void scc_argparse_spec_setup_list(scc_argparse_spec_t *spec,
scc_argparse_list_t *vec) {
spec->value_type = SCC_ARGPARSE_VAL_TYPE_LIST;
@@ -534,6 +729,14 @@ static inline void scc_argparse_spec_setup_list(scc_argparse_spec_t *spec,
spec->flag_takes_multiple = false;
}
/**
* @brief 生成 scc_argparse_spec_set_<attr>() 标志位设置函数。
* - required:缺失时报 SCC_ARGPARSE_ERR_MISSING_ARG
* - allow_empty:允许 --opt= 这样的空值
* - hidden:不出现在帮助里
* - takes_multiple:LIST 一次吃掉多个值
* - parse_complex:预留,当前未实现
*/
#define SCC_ARGPARSE_MACRO_SETTER(attr) \
static inline void scc_argparse_spec_set_##attr(scc_argparse_spec_t *spec, cbool flag) { \
spec->flag_##attr = flag; \
@@ -561,6 +764,7 @@ void scc_argparse_init(scc_argparse_t *parser, const char *program_name, const c
parser->short_prefix = '-';
parser->long_prefix = "--";
parser->separator = "--";
parser->max_subcmd_depth = 0;
parser->need_help = true;
parser->need_version = true;
parser->need_debug = false;
@@ -583,6 +787,10 @@ void scc_argparse_set_prefix(scc_argparse_t *parser, char short_prefix, const ch
parser->separator = separator;
}
void scc_argparse_set_max_subcmd_depth(scc_argparse_t *parser, int depth) {
parser->max_subcmd_depth = depth;
}
static inline scc_argparse_cmd_t *is_subcommand(scc_argparse_cmd_t *cmd, const char *name) {
if (!cmd->subcmds.count) {
return nullptr;
@@ -705,6 +913,7 @@ static void init_context(scc_argparse_context_t *ctx, scc_argparse_t *parser, in
scc_vec_init(ctx->opts);
prepare_cmd(&ctx->optparse, &ctx->opts, ctx->current_cmd);
ctx->positional_index = 0;
ctx->depth = 0;
ctx->parsing_done = false;
}
@@ -749,27 +958,91 @@ static int check_choices(const scc_argparse_spec_t *spec, const char *value, int
return SCC_ARGPARSE_ERR_INVALID_VALUE;
}
static int scc_argparse_parse_int(const char *s, usize *out) {
// 手写十进制解析:不接受空白/十六进制,溢出按 int 范围判。
// out 必须是 int*:store.int_store 指向的是 4 字节 int。
static int scc_argparse_parse_int(const char *s, int *out) {
if (!s || !*s)
return SCC_ARGPARSE_ERR_MISSING_VALUE;
char *end = NULL;
// TODO 手动解析整数,避免使用 strtoull
usize v = strtoull(s, &end, 10);
if (end == s || *end != '\0')
const char *p = s;
int negative = 0;
if (*p == '+' || *p == '-') {
negative = *p == '-';
p++;
}
if (*p == '\0')
return SCC_ARGPARSE_ERR_INVALID_VALUE;
*out = v;
// 上限从 unsigned 推出来,不依赖平台宏。
long long limit = (long long)(((unsigned)-1) >> 1) + (negative ? 1 : 0);
long long v = 0;
for (; *p; p++) {
if (*p < '0' || *p > '9')
return SCC_ARGPARSE_ERR_INVALID_VALUE;
v = v * 10 + (*p - '0');
if (v > limit)
return SCC_ARGPARSE_ERR_INVALID_VALUE;
}
*out = (int)(negative ? -v : v);
return SCC_ARGPARSE_ERR_NONE;
}
// 手写浮点解析:[+-]digits[.digits][eE[+-]digits],不支持 inf/nan/十六进制。
static int scc_argparse_parse_float(const char *s, float *out) {
if (!s || !*s)
return SCC_ARGPARSE_ERR_MISSING_VALUE;
char *end = NULL;
// TODO 手动解析浮点数,避免使用 strtof
float v = strtof(s, &end);
if (end == s || *end != '\0')
const char *p = s;
int negative = 0;
if (*p == '+' || *p == '-') {
negative = *p == '-';
p++;
}
double v = 0.0;
int digits = 0;
while (*p >= '0' && *p <= '9') {
v = v * 10.0 + (double)(*p - '0');
p++;
digits++;
}
if (*p == '.') {
p++;
double scale = 0.1;
while (*p >= '0' && *p <= '9') {
v += (double)(*p - '0') * scale;
scale *= 0.1;
p++;
digits++;
}
}
if (digits == 0)
return SCC_ARGPARSE_ERR_INVALID_VALUE;
*out = v;
if (*p == 'e' || *p == 'E') {
p++;
int exp_negative = 0;
if (*p == '+' || *p == '-') {
exp_negative = *p == '-';
p++;
}
if (*p < '0' || *p > '9')
return SCC_ARGPARSE_ERR_INVALID_VALUE;
int exp = 0;
while (*p >= '0' && *p <= '9') {
if (exp < 1000) // 再大只会走到 inf/0,不必继续累加
exp = exp * 10 + (*p - '0');
p++;
}
for (int i = 0; i < exp; i++)
v = exp_negative ? v / 10.0 : v * 10.0;
}
if (*p != '\0')
return SCC_ARGPARSE_ERR_INVALID_VALUE;
*out = (float)(negative ? -v : v);
return SCC_ARGPARSE_ERR_NONE;
}
@@ -795,7 +1068,7 @@ static int scc_argparse_store_value(scc_argparse_spec_t *spec, const char *value
case SCC_ARGPARSE_VAL_TYPE_INT:
if (!spec->store.int_store)
return SCC_ARGPARSE_ERR_INVALID_ARG;
return scc_argparse_parse_int(value, (void *)spec->store.int_store);
return scc_argparse_parse_int(value, spec->store.int_store);
case SCC_ARGPARSE_VAL_TYPE_FLOAT:
if (!spec->store.float_store)
@@ -916,10 +1189,14 @@ static int handle_option(scc_argparse_context_t *ctx, scc_argparse_t *parser) {
}
static int handle_positional_arg(scc_argparse_context_t *ctx, scc_argparse_t *parser) {
(void)parser;
scc_argparse_cmd_t *subcmd = is_subcommand(ctx->current_cmd, ctx->result.value);
if (subcmd != nullptr) {
int next_depth = ctx->depth + 1;
if (parser->max_subcmd_depth > 0 && next_depth > parser->max_subcmd_depth) {
ctx->err_ctx = subcmd->name;
return SCC_ARGPARSE_ERR_SUBCMD_TOO_DEEP;
}
ctx->depth = next_depth;
ctx->current_cmd = subcmd;
if (subcmd->triggered)
*subcmd->triggered = true;
@@ -1037,6 +1314,7 @@ enum {
ARGPARSE_INVALID_VALUE_FOR_OPTION,
ARGPARSE_OPTION_MISSING_VALUE,
ARGPARSE_DID_YOU_MEAN,
ARGPARSE_SUBCMD_TOO_DEEP,
};
static const char *fmt_en[] = {
@@ -1054,6 +1332,7 @@ static const char *fmt_en[] = {
[ARGPARSE_INVALID_VALUE_FOR_OPTION] = "Invalid value for option '{:s}'\n",
[ARGPARSE_OPTION_MISSING_VALUE] = "Option '{:s}' missing value\n",
[ARGPARSE_DID_YOU_MEAN] = "Did you mean: '{:s}'?\n",
[ARGPARSE_SUBCMD_TOO_DEEP] = "Subcommand nesting too deep: '{:s}'\n",
};
static const char *fmt_zh[] = {
@@ -1071,6 +1350,7 @@ static const char *fmt_zh[] = {
[ARGPARSE_INVALID_VALUE_FOR_OPTION] = "无效的选项值 '{:s}'\n",
[ARGPARSE_OPTION_MISSING_VALUE] = "选项 '{:s}' 缺少值\n",
[ARGPARSE_DID_YOU_MEAN] = "您是不是想要输入: '{:s}'?\n",
[ARGPARSE_SUBCMD_TOO_DEEP] = "子命令嵌套过深: '{:s}'\n",
};
/**
@@ -1139,6 +1419,63 @@ static void scc_print_usage(scc_argparse_t *parser, scc_argparse_cmd_t *cmd, scc
scc_fmt(out, "\n\n");
}
// 两个 group 是否同段:NULL 只和 NULL 同段。
static int scc_argparse_same_group(const char *a, const char *b) {
if (!a || !b)
return a == b;
return scc_strcmp(a, b) == 0;
}
// upto 之前是否已经出现过同一个 group(用来保证每组只打一次标题)。
static int scc_argparse_group_seen(const scc_argparse_cmd_t *cmd, usize upto, const char *group) {
for (usize i = 0; i < upto; i += 1) {
if (scc_argparse_same_group(cmd->opts.items[i].group, group))
return 1;
}
return 0;
}
// 选项一行:`-s, --long=<a|b|c>` 加描述,名字列宽 25。
static void scc_argparse_print_one_opt(scc_str_t *out, scc_argparse_opt_t *opt,
const char **lines) {
if (opt->short_name == 'h')
opt->description = lines[ARGPARSE_SHOW_HELP_MSG];
scc_str_t buf = {0};
if (opt->short_name) {
scc_vec_push(&buf, '-');
scc_vec_push(&buf, opt->short_name);
if (opt->long_name) {
scc_vec_push(&buf, ',');
scc_vec_push(&buf, ' ');
}
}
if (opt->long_name) {
scc_vec_push(&buf, '-');
scc_vec_push(&buf, '-');
for (const char *p = opt->long_name; *p; p++)
scc_vec_push(&buf, *p);
}
if (opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_ENUM) {
scc_vec_push(&buf, '=');
scc_vec_push(&buf, '<');
for (int j = 0; j < opt->spec.choices.count; j += 1) {
if (opt->spec.choices.values[j] == 0)
continue;
if (j != 0)
scc_vec_push(&buf, '|');
for (const char *p = opt->spec.choices.values[j]; *p; p++)
scc_vec_push(&buf, *p);
}
scc_vec_push(&buf, '>');
}
scc_vec_push(&buf, '\0');
scc_fmt(out, " {:<25s} {:s}", buf.items, opt->description ? opt->description : "");
scc_fmt(out, "\n");
scc_vec_free(buf);
}
void scc_argparse_print_help(scc_argparse_t *parser, scc_argparse_cmd_t *cmd) {
const char **lines = (parser->lang == SCC_ARGPARSE_LANG_ZH) ? fmt_zh : fmt_en;
scc_str_t *out = &parser->out;
@@ -1160,53 +1497,34 @@ void scc_argparse_print_help(scc_argparse_t *parser, scc_argparse_cmd_t *cmd) {
scc_fmt(out, "\n");
}
if (cmd->opts.count > 0) {
// 按 group 首次出现顺序分段;group==NULL 的进默认 "Options" 段。
for (usize i = 0; i < cmd->opts.count; i += 1) {
const char *group = cmd->opts.items[i].group;
if (scc_argparse_group_seen(cmd, i, group))
continue;
// 整段都被隐藏就不打标题
int visible = 0;
for (usize j = i; j < cmd->opts.count; j += 1) {
if (scc_argparse_same_group(cmd->opts.items[j].group, group) &&
!cmd->opts.items[j].spec.flag_hidden) {
visible = 1;
break;
}
}
if (!visible)
continue;
if (group)
scc_fmt(out, "{:s}:\n", group);
else
scc_fmt(out, lines[ARGPARSE_SHOW_OPT]);
for (usize i = 0; i < cmd->opts.count; i++) {
scc_argparse_opt_t *opt = &cmd->opts.items[i];
if (opt->spec.flag_hidden)
continue;
if (opt->short_name == 'h')
opt->description = lines[ARGPARSE_SHOW_HELP_MSG];
scc_str_t buf = {0};
if (opt->short_name) {
scc_vec_push(&buf, '-');
scc_vec_push(&buf, opt->short_name);
if (opt->long_name) {
scc_vec_push(&buf, ',');
scc_vec_push(&buf, ' ');
}
}
if (opt->long_name) {
scc_vec_push(&buf, '-');
scc_vec_push(&buf, '-');
for (const char *p = opt->long_name; *p; p++) {
scc_vec_push(&buf, *p);
}
}
if (opt->spec.value_type == SCC_ARGPARSE_VAL_TYPE_ENUM) {
scc_vec_push(&buf, '=');
scc_vec_push(&buf, '<');
for (int j = 0; j < opt->spec.choices.count; j += 1) {
if (opt->spec.choices.values[j] == 0) {
continue;
}
if (j != 0) {
scc_vec_push(&buf, '|');
}
for (const char *p = opt->spec.choices.values[j]; *p; p++) {
scc_vec_push(&buf, *p);
}
}
scc_vec_push(&buf, '>');
}
scc_vec_push(&buf, '\0');
scc_fmt(out, " {:<25s} {:s}", buf.items, opt->description ? opt->description : "");
// if (opt->spec.default_value)
// scc_fmt(out, " (default: {:s})", opt->spec.default_value);
scc_fmt(out, "\n");
for (usize j = i; j < cmd->opts.count; j += 1) {
scc_argparse_opt_t *opt = &cmd->opts.items[j];
if (!scc_argparse_same_group(opt->group, group) || opt->spec.flag_hidden)
continue;
scc_argparse_print_one_opt(out, opt, lines);
}
scc_fmt(out, "\n");
}
@@ -1270,6 +1588,9 @@ void scc_argparse_print_error(scc_argparse_context_t *ctx, scc_argparse_t *parse
scc_fmt(out, lines[ARGPARSE_DID_YOU_MEAN], similar_arg);
}
break;
case SCC_ARGPARSE_ERR_SUBCMD_TOO_DEEP:
scc_fmt(out, lines[ARGPARSE_SUBCMD_TOO_DEEP], ctx->err_ctx);
break;
// FACK ERROR
case SCC_ARGPARSE_ERR_PNT_DEFAULT:
return;
+74 -214
View File
@@ -4,188 +4,40 @@
/* clang-format off */
#define VM_SRCS "stage0/spl_mcode.c", "stage0/spl_syscall.c", "stage0/spl_vm.c",
static const char *stage0_headers[] = {
"stage0/spl_asp.h", "stage0/spl_mcode.h", "stage0/spl_syscall.h",
"stage0/spl_vm.h", "stage0/spl_rt_core.h", "stage0/spl_rt.h",
"stage0/spl_vm_embed.h",
};
// 依赖项里可以写通配模式(nob.c 的 expand_patterns 负责展开):
// dir/*.ext 只看直接子文件
// dir/**/*.ext 递归子目录(两个星号)
// 不含 '*' 的条目按字面路径处理;某个模式一条都没匹配到会直接报错。
static const char *stage0_headers[] = {"stage0/*.h"};
/* stage1 头也参与依赖:改结构体布局/枚举值时所有 splc0 对象必须重编,
否则残留旧布局的 .o 与新政 ABI 不一致(生成物随机错乱)。 */
static const char *splc0_headers[] = {
"stage0/spl_asp.h", "stage0/spl_mcode.h", "stage0/spl_syscall.h",
"stage0/spl_vm.h", "stage0/spl_rt_core.h", "stage0/spl_rt.h",
"stage0/spl_vm_embed.h",
"stage1/ir_opt.h", "stage1/vm_opt.h", "stage1/spl_ast.h",
"stage1/spl_ast2ir.h", "stage1/spl_attr.h", "stage1/spl_dbg.h",
"stage1/spl_diag.h", "stage1/spl_fold.h", "stage1/spl_intrin.h",
"stage1/spl_ir.h", "stage1/spl_ir2c.h", "stage1/spl_ir2vm.h",
"stage1/spl_lang_type.h", "stage1/spl_layout.h", "stage1/spl_lexer.h",
"stage1/spl_mpa.h", "stage1/spl_parser.h", "stage1/spl_scope.h",
"stage1/spl_sema.h", "stage1/spl_tok.h", "stage1/spl_type.h",
};
static const char *splc1_headers[] = {"stage0/*.h", "stage1/**/*.h"};
static const char *spl_cli_srcs[] = {"stage0/spl_cli.c", VM_SRCS};
static const char *vm_test_srcs[] = {"stage0/test_spl_vm.c", VM_SRCS};
static const char *splc0_srcs[] = {
"stage1/splc0.c",
"stage1/spl_diag.c",
"stage1/spl_tok.c",
"stage1/spl_lexer.c",
"stage1/spl_ast.c",
"stage1/spl_parser.c",
"stage1/spl_type.c",
"stage1/spl_fold.c",
"stage1/spl_lang_type.c",
"stage1/spl_attr.c",
"stage1/spl_scope.c",
"stage1/spl_sema.c",
"stage1/spl_intrin.c",
"stage1/spl_ir.c",
"stage1/spl_ast2ir.c",
"stage1/spl_layout.c",
"stage1/spl_ir2vm.c",
"stage1/spl_ir2c.c",
"stage1/ir_opt.c",
"stage1/vm_opt.c",
"stage0/spl_mcode.c",
};
static const char *splc1_crt_deps[] ={
"stage0/spl_rt.h",
"stage0/spl_vm_embed.h",
// TODO
};
static const char* splc1_deps[] = {
"stage2/sys/exit.spl",
"stage2/sys/file.spl",
"stage2/sys/mem.spl",
"stage2/sys/time.spl",
"stage2/sys/vm.spl",
"stage2/utils/algorithm.spl",
"stage2/utils/arena.spl",
"stage2/utils/ascii.spl",
"stage2/utils/byte_buffer.spl",
"stage2/utils/byte_view.spl",
"stage2/utils/error.spl",
"stage2/utils/fmt.spl",
"stage2/utils/hash.spl",
"stage2/utils/io.spl",
"stage2/utils/json.spl",
"stage2/utils/log.spl",
"stage2/utils/lsp_frame.spl",
"stage2/utils/map.spl",
"stage2/utils/memory.spl",
"stage2/utils/mp.spl",
"stage2/utils/path.spl",
"stage2/utils/profile.spl",
"stage2/utils/set.spl",
"stage2/utils/source.spl",
"stage2/utils/str.spl",
"stage2/utils/utf8.spl",
"stage2/utils/value.spl",
"stage2/utils/vec.spl",
"stage2/ast.spl",
"stage2/ast2ir.spl",
"stage2/attr.spl",
"stage2/def.spl",
"stage2/diag.spl",
"stage2/eval.spl",
"stage2/intrin.spl",
"stage2/ir.spl",
"stage2/ir2c.spl",
"stage2/ir2vm.spl",
"stage2/ir_builder.spl",
"stage2/lang_type.spl",
"stage2/layout.spl",
"stage2/lexer.spl",
"stage2/mcode.spl",
"stage2/parser.spl",
"stage2/scope.spl",
"stage2/sema.spl",
"stage2/splc1.spl",
"stage2/token.spl",
"stage2/type_table.spl",
};
static const char* splc2_deps[] = {
/* stage2 */
"stage2/sys/exit.spl",
"stage2/sys/file.spl",
"stage2/sys/mem.spl",
"stage2/sys/time.spl",
"stage2/sys/vm.spl",
"stage2/utils/algorithm.spl",
"stage2/utils/arena.spl",
"stage2/utils/ascii.spl",
"stage2/utils/byte_buffer.spl",
"stage2/utils/byte_view.spl",
"stage2/utils/error.spl",
"stage2/utils/fmt.spl",
"stage2/utils/hash.spl",
"stage2/utils/io.spl",
"stage2/utils/json.spl",
"stage2/utils/log.spl",
"stage2/utils/lsp_frame.spl",
"stage2/utils/map.spl",
"stage2/utils/memory.spl",
"stage2/utils/mp.spl",
"stage2/utils/path.spl",
"stage2/utils/profile.spl",
"stage2/utils/set.spl",
"stage2/utils/source.spl",
"stage2/utils/str.spl",
"stage2/utils/utf8.spl",
"stage2/utils/value.spl",
"stage2/utils/vec.spl",
"stage2/ast.spl",
"stage2/ast2ir.spl",
"stage2/attr.spl",
"stage2/def.spl",
"stage2/diag.spl",
"stage2/eval.spl",
"stage2/intrin.spl",
"stage2/ir.spl",
"stage2/ir2c.spl",
"stage2/ir2vm.spl",
"stage2/ir_builder.spl",
"stage2/lang_type.spl",
"stage2/layout.spl",
"stage2/lexer.spl",
"stage2/mcode.spl",
"stage2/parser.spl",
"stage2/scope.spl",
"stage2/sema.spl",
"stage2/splc1.spl",
"stage2/token.spl",
"stage2/type_table.spl",
};
static const char *splc1_srcs[] = {"stage1/**/*.c", "stage0/spl_mcode.c"};
#define CRT_DEPS \
"stage0/spl_rt.h", "stage0/spl_rt_core.h", "stage0/spl_asp.h", \
"stage0/spl_mcode.h", "stage0/spl_vm.h", "stage0/spl_syscall.h", \
"stage0/spl_vm_embed.h",
"stage0/spl_rt.h", "stage0/spl_rt_core.h", "stage0/spl_asp.h", \
"stage0/spl_mcode.h", "stage0/spl_vm.h", "stage0/spl_syscall.h", \
"stage0/spl_vm_embed.h",
static const char *splc2_deps[] = {"stage2/**/*.spl"};
// splc3 既 import 本目录(含 builtins/),也 import ../../stage2 下的一堆文件。
static const char *splc3_deps[] = {"stage3/**/*.spl", "stage2/**/*.spl"};
static const char *splc_deps[] = {"src/**/*.spl"};
static const char *splc2_crt_deps[] = {
CRT_DEPS
};
static const char* splc3_deps[] = {
"stage3/ast2hir.spl",
"stage3/intrinsic.spl",
"stage3/comptime.spl",
"stage3/hir2ir.spl",
"stage3/lang_type.spl",
"stage3/mangling.spl",
"stage3/sema.spl",
"stage3/spl_ir.spl",
"stage3/spl_ir_builder.spl",
"stage3/splc2.spl",
"stage3/tag.spl",
static const char *splc3_crt_deps[] = {
CRT_DEPS
};
static const char *splc3_crt_deps[] = {
static const char *splc_crt_deps[] = {
CRT_DEPS
};
@@ -198,6 +50,8 @@ typedef struct build {
BUILD_EXE_WITH_OPTIMIZATION,
BUILD_SIR,
BUILD_NATIVE,
BUILD_SPLC_SIR,
BUILD_SPLC_NATIVE,
} kind;
union {
struct {
@@ -253,61 +107,43 @@ static build_t targets[] = {
.headers = stage0_headers,
.headers_count = NOB_ARRAY_LEN(stage0_headers)},
},
{
"splc0",
BUILD_EXE,
.exe = {.srcs = splc0_srcs,
.srcs_count = NOB_ARRAY_LEN(splc0_srcs),
.headers = splc0_headers,
.headers_count = NOB_ARRAY_LEN(splc0_headers)},
},
{
"splc1",
BUILD_SIR,
.sir = {.src = "stage2/splc1.spl",
.compiler = "splc0",
.deps = splc1_deps,
.deps_count = NOB_ARRAY_LEN(splc1_deps)},
},
{
"splc1s",
BUILD_SIR,
.sir = {.src = "stage2/splc1.spl",
.compiler = "splc1",
.deps = splc1_deps,
.deps_count = NOB_ARRAY_LEN(splc1_deps)},
},
{
"splc1r",
BUILD_SIR,
.sir = {.src = "stage2/splc1.spl",
.compiler = "splc1s",
.deps = splc1_deps,
.deps_count = NOB_ARRAY_LEN(splc1_deps)},
},
{
"splc1n",
BUILD_NATIVE,
.native = {.src = "stage2/splc1.spl",
.compiler = "splc0",
.deps = splc1_deps,
.deps_count = NOB_ARRAY_LEN(splc1_deps),
.crt_deps = splc1_crt_deps,
.crt_deps_count = NOB_ARRAY_LEN(splc1_crt_deps)},
BUILD_EXE,
.exe = {.srcs = splc1_srcs,
.srcs_count = NOB_ARRAY_LEN(splc1_srcs),
.headers = splc1_headers,
.headers_count = NOB_ARRAY_LEN(splc1_headers)},
},
{
"splc2",
BUILD_SIR,
.sir = {.src = "stage3/splc2.spl",
.compiler = "splc1n",
.sir = {.src = "stage2/splc2.spl",
.compiler = "splc1",
.deps = splc2_deps,
.deps_count = NOB_ARRAY_LEN(splc2_deps)},
},
{
"splc2s",
BUILD_SIR,
.sir = {.src = "stage2/splc2.spl",
.compiler = "splc1",
.deps = splc2_deps,
.deps_count = NOB_ARRAY_LEN(splc2_deps)},
},
{
"splc2r",
BUILD_SIR,
.sir = {.src = "stage2/splc2.spl",
.compiler = "splc2s",
.deps = splc2_deps,
.deps_count = NOB_ARRAY_LEN(splc2_deps)},
},
{
"splc2n",
BUILD_NATIVE,
.native = {.src = "stage3/splc2.spl",
.compiler = "splc1n",
.native = {.src = "stage2/splc2.spl",
.compiler = "splc1",
.deps = splc2_deps,
.deps_count = NOB_ARRAY_LEN(splc2_deps),
.crt_deps = splc2_crt_deps,
@@ -337,12 +173,36 @@ static build_t targets[] = {
.crt_deps_count = NOB_ARRAY_LEN(splc3_crt_deps),
},
},
{
"splc4",
BUILD_SPLC_SIR,
.sir =
{
.src = "src/main.spl",
.compiler = "splc3n",
.deps = splc_deps,
.deps_count = NOB_ARRAY_LEN(splc_deps),
},
},
{
"splc4n",
BUILD_SPLC_NATIVE,
.native =
{
.src = "src/main.spl",
.compiler = "splc3n",
.deps = splc_deps,
.deps_count = NOB_ARRAY_LEN(splc_deps),
.crt_deps = splc_crt_deps,
.crt_deps_count = NOB_ARRAY_LEN(splc_crt_deps),
},
},
};
static run_t runs[] = {
{"spl_cli", NULL}, {"vm_test", NULL}, {"splc0", NULL}, {"splc1", "spl_cli"},
{"splc1r", "spl_cli"}, {"splc1s", "spl_cli"}, {"splc1n", NULL}, {"splc2", "spl_cli"},
{"splc2n", NULL}, {"splc3", "spl_cli"}, {"splc3n", NULL},
{"spl_cli", NULL}, {"vm_test", NULL}, {"splc1", NULL}, {"splc2", "spl_cli"},
{"splc2r", "spl_cli"}, {"splc2s", "spl_cli"}, {"splc2n", NULL}, {"splc3", "spl_cli"},
{"splc3n", NULL}, {"splc4", "spl_cli"}, {"splc4n", NULL}, {"splc", NULL},
};
#endif /* __NOB_DATA_H__ */
+47 -12
View File
@@ -4,7 +4,7 @@
#include "nob.h"
typedef struct {
Nob_String_Builder out; // stdout 内容
Nob_String_Builder out; // stdout + stderr 合并内容
int exit_code; // 实际退出码
bool ok; // 是否成功启动
} Nob_Cmd_Result;
@@ -15,7 +15,7 @@ typedef struct {
int count;
} Nob_Files;
// 运行命令,捕获 stdout(Windows 下会合并 stderr)和真实退出码。
// 运行命令,捕获 stdout 并合并 stderr;返回真实退出码。
// 返回 true 仅表示命令成功启动并完成,不代表 exit_code == 0。
bool nob_cmd_capture_popen(const char *tname, Nob_Cmd_Result *res) {
memset(res, 0, sizeof(*res));
@@ -112,21 +112,56 @@ bool nob_cmd_capture_popen(const char *tname, Nob_Cmd_Result *res) {
CloseHandle(pi.hThread);
#else
// ---------- POSIX: popen ----------
FILE *fp = popen(tname, "r");
if (!fp) {
nob_log(NOB_ERROR, "popen failed: %s", strerror(errno));
// ---------- POSIX: fork + pipe ----------
// stdout/stderr 汇入同一管道,语义与 Windows 分支一致。
Nob_Pipe pp;
if (!nob_pipe_create(&pp)) { return false; }
pid_t pid = fork();
if (pid < 0) {
nob_log(NOB_ERROR, "fork failed: %s", strerror(errno));
nob_fd_close(pp.read);
nob_fd_close(pp.write);
return false;
}
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp)) {
nob_sb_append_cstr(&res->out, buffer);
if (pid == 0) {
// 子进程:把 stdout/stderr 都接到管道写端,再执行 shell 命令。
if (dup2(pp.write, STDOUT_FILENO) < 0 ||
dup2(pp.write, STDERR_FILENO) < 0) {
_exit(127);
}
nob_fd_close(pp.read);
nob_fd_close(pp.write);
execl("/bin/sh", "sh", "-c", tname, (char *)NULL);
_exit(127);
}
int status = pclose(fp);
if (status == -1) {
nob_log(NOB_ERROR, "pclose failed: %s", strerror(errno));
// 父进程:关闭写端,读到 EOF 后回收子进程。
nob_fd_close(pp.write);
char buffer[4096];
while (true) {
ssize_t n = read(pp.read, buffer, sizeof(buffer));
if (n > 0) {
nob_sb_append_buf(&res->out, buffer, (size_t)n);
} else if (n == 0) {
break;
} else if (errno == EINTR) {
continue;
} else {
nob_log(NOB_ERROR, "read failed: %s", strerror(errno));
nob_fd_close(pp.read);
int ignored = 0;
while (waitpid(pid, &ignored, 0) < 0 && errno == EINTR) {}
return false;
}
}
nob_fd_close(pp.read);
int status = 0;
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR) { continue; }
nob_log(NOB_ERROR, "waitpid failed: %s", strerror(errno));
return false;
}
if (WIFEXITED(status))
+79
View File
@@ -0,0 +1,79 @@
type .{ .Vec } = @import("core/vec.spl");
type .{ .Allocator } = @import("core/alloc.spl");
type .{ .String } = @import("core/str.spl");
type .{ .Result } = @import("core/error.spl");
type ptr = @import("core/ptr.spl");
type .{ .File } = @import("compiler/shape.spl");
type SourceId = u32;
pub comptime fn SourceFile(A: Allocator): type {
ret struct {
id: SourceId,
name: @Vec(u8, A),
content: @Vec(u8, A),
line_offsets: @Vec(usize, A),
}
}
type SourceError = enum {
UnknownError,
FileOpenError,
FileAttributeError,
FileReadError,
OutOfMemory,
}
pub comptime fn Source(A: Allocator, F: File): type {
ret struct {
// TODO HashSet 进行去重
files: @Vec(@SourceFile(A), A),
fshape: F,
alloc: A,
pub fn new(alloc: A, fshape: F): @self {
ret .{ .files = @Vec(@SourceFile(A), A).empty(alloc), .alloc = alloc, .fshape = fshape };
}
pub fn add_file(@Self self: *@self, name: []const u8): @Result(SourceId, SourceError) {
var fp = self.fshape.open(name, .Read) catch .Err(_) {
ret .(.Err(.FileOpenError));
};
errdefer { fp.close(); }
var size = fp.size() catch .Err(_) {
ret .(.Err(.FileAttributeError));
};
var content = @Vec(u8, A).with_capacity(self.alloc, size) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
content._set_len(size);
var read_size = fp.read(content.as_slice()) catch .Err(_) {
ret .(.Err(.FileReadError));
};
if read_size != size {
ret .(.Err(.FileReadError));
}
var owned_name = @Vec(u8, A).with_capacity(self.alloc, name.len()) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
owned_name._set_len(name.len());
ptr.copy(owned_name.as_slice().as_ptr(), name.as_ptr(), name.len());
ret self.add_virtual(owned_name, content);
}
pub fn add_virtual(@Self self: *@self, name: @Vec(u8, A), content: @Vec(u8, A)): @Result(SourceId, SourceError) {
var id = self.files.len();
var file: @SourceFile(A) = .{
.id = id as u32,
.name = name,
.content = content,
.line_offsets = @Vec(usize, A).empty(self.alloc),
};
self.files.push(file) catch .Err(e) {
ret .(.Err(.OutOfMemory));
};
ret .(.Ok(id as SourceId));
}
}
}
+30
View File
@@ -0,0 +1,30 @@
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result, .Option } = @import("core/error.spl");
pub type FileMode = enum {
Read,
Write,
Append,
}
pub type File = shape: Writer + Reader {
fn open(path: []const u8, mode: FileMode): @Result(@self, IOError);
fn close(@Self self: *@self): @Result((), IOError);
fn size(@Self self: *@self): @Result(usize, IOError);
}
pub type Time = shape {
}
pub type Memory = shape {
}
pub type Process = shape {
}
pub type VM = shape {
}
+205
View File
@@ -0,0 +1,205 @@
#extern(vm) fn vm_fopen(path: *any, mode: *any): *any;
#extern(vm) fn vm_fclose(f: *any): i32;
#extern(vm) fn vm_fread(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fwrite(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fsize(f: *any): usize;
#extern(vm) fn vm_fflush(f: *any): i32;
#extern(vm) fn vm_stdin(): *any;
#extern(vm) fn vm_stdout(): *any;
#extern(vm) fn vm_stderr(): *any;
#extern(vm) fn vm_putchar(c: i32): i32;
#extern(vm) fn vm_getchar(): i32;
#extern(vm) fn vm_exit(code: i32);
#extern(vm) fn vm_alloc(sz: usize): *any;
#extern(vm) fn vm_free(p: *any);
#extern(vm) fn vm_realloc(p: *any, sz: usize): *any;
#extern(vm) fn vm_memcpy(dst: *any, src: *any, n: usize): *any;
#extern(vm) fn vm_memcmp(a: *any, b: *any, n: usize): isize;
// 时间/参考量接口(原生 vm_timestamp,case 探测风格,不假设一定可用)。
// available() -> 1 = 时间可用;0 = 不可用(其余 time 相关返回值恒为 0)
// sec() -> 当前秒
// ns() -> 当前纳秒部分
// steps() -> VM 已执行指令数(参考量)
// now_ns() -> 完整纳秒时间戳(单次调用;纪元纳秒 < 2^64,无需 i128)
#extern(vm) fn vm_timestamp(kind: usize): usize;
#extern(vm) fn vm_new(): *any;
#extern(vm) fn vm_drop(vm: *any): void;
#extern(vm) fn vm_load(vm: *any, fpath: *u8): void;
#extern(vm) fn vm_load_from_buffer(vm: *any, buf: *any, len: usize): i32;
#extern(vm) fn vm_push(vm: *any, val: spl_vm_val_t): void;
#extern(vm) fn vm_call(vm: *any, name: *u8, nargs: u64): i32;
#extern(vm) fn vm_run(vm: *any): i32;
#extern(vm) fn vm_ret_val(vm: *any): spl_vm_val_t;
#extern(vm) fn vm_mem_alloc(vm: *any, size: usize): spl_vm_val_t;
#extern(vm) fn vm_mem_read(vm: *any, off: spl_vm_val_t, dst: *any, n: usize): i32;
#extern(vm) fn vm_mem_write(vm: *any, off: spl_vm_val_t, src: *any, n: usize): i32;
#extern(vm) fn vm_stack_get(vm: *any, index: usize): spl_vm_val_t;
#extern(vm) fn vm_set_foreign(vm: *any, entry: []u8, ctx: *any): void;
// 把外部处理器名绑定到宿主函数。SIR 后端按名调用宿主 VM 函数,无需登记;
// 原生后端没有名字到地址的运行时表,需要这里先登记函数指针。
#extern(vm) fn vm_bind_foreign(entry: []u8,
handler: fn(*any, u64, u64, *any, u64, u64): u64): void;
type .{ .Allocator, .AllocError, .Layout } = @import("core/alloc.spl");
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result } = @import("core/error.spl");
type .{ .File, .FileMode, .Time, .Memory, .Process, .VM } = @import("./shape.spl");
// type .{} = @import("");
type ptr = @import("core/ptr.spl");
pub fn strlen(str: *const u8): usize {
var len: usize = 0;
while (str[len] != 0) {
len = len + 1;
}
ret len;
}
pub type VMAllocator = struct: Allocator {
pub fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError) {
var res = vm_alloc(layout.size);
if res == null {
ret .(.Err(AllocError.OutOfMemory));
}
ret .(.Ok(res));
}
pub fn dealloc(@Self self: *@self, ptr: *any, layout: Layout) {
vm_free(ptr);
}
}
// pub type VMReader = struct: Reader {
// }
pub type VMWriter = struct: Writer {
file: *any;
pub fn with_file(f: *any): VMWriter {
ret VMWriter { .file = f };
}
pub fn with_stdout(): VMWriter {
ret VMWriter { .file = vm_stdout() };
}
pub fn with_stderr(): VMWriter {
ret VMWriter { .file = vm_stderr() };
}
pub fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMWriter file is null");
var result = vm_fwrite(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn flush(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMWriter file is null");
var result = vm_fflush(f);
if result != 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(()));
}
}
type VMFile = struct: File {
file: *any;
pub fn with_stdout(): @self {
ret .{ .file = vm_stdout() };
}
pub fn with_stderr(): @self {
ret .{ .file = vm_stderr() };
}
pub fn open(path: []const u8, mode: FileMode): @Result(@self, IOError) {
var mode_str: []const u8 = match (mode) {
.Read => {"rb\0"},
.Write => {"wb\0"},
.Append => {"ab\0"},
};
// TODO hack it;
var path_cstr: [1024]u8 = .[];
ptr.copy(path_cstr.as_ptr(), path.as_ptr(), path.len());
path_cstr[path.len()] = 0;
var f = vm_fopen(path_cstr.as_ptr() as *any, mode_str.as_ptr() as *any);
if f == null {
ret .(.Err(IOError.UnknownError));
}
ret .(.Ok(VMFile { .file = f }));
}
pub fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fread(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fwrite(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn size(@Self self: *@self): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
ret .(.Ok(vm_fsize(f)));
}
pub fn flush(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fflush(f);
if result != 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(()));
}
pub fn close(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fclose(f);
if result != 0 {
ret .(.Err(IOError.UnknownError));
}
ret .(.Ok(()));
}
pub fn putchar(@Self _self: *@self, ch: u8): bool {
vm_putchar(ch as i32);
}
}
// type VMFormat = struct: Formatter {
// }
+16
View File
@@ -0,0 +1,16 @@
type .{ .Result } = @import("./error.spl");
pub type Layout = struct {
size: usize;
align: usize;
}
pub type AllocError = enum {
OutOfMemory,
InvalidLayout,
}
pub type Allocator = shape {
fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError);
fn dealloc(@Self self: *@self, ptr: *any, layout: Layout);
}
+59
View File
@@ -0,0 +1,59 @@
pub comptime fn Option(T: type): type {
ret enum {
pub Some: T,
pub None: void,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic("called unwrap on None"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { ret f(); }
// }
// }
};
}
pub comptime fn Result(T: type, E: type): type {
ret enum {
#ok
pub Ok: T,
#error
pub Err: E,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic("called unwrap on Err"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { ret f(); }
// }
// }
};
}
+80
View File
@@ -0,0 +1,80 @@
type .{ .Result } = @import("./error.spl");
pub type Display = shape {
fn fmt(@Self self: *@self, out: @[*Sink]): bool;
};
pub type Debug = shape {
fn debug(@Self self: *@self, out: @[*Sink]): bool;
};
pub type Sink = shape {
fn write_byte(@Self self: *@self, byte: u8): bool;
// TODO shape default value for `fn write_bytes(@Self self: *@self, bytes: []const u8): bool;`
};
pub type Spec = struct {
align: enum { Left, Center, Right },
width: usize,
fill: u8,
// attrs: enum {
// number: struct {},
// }
};
pub type Error = enum {
WriteFailed,
UnclosedLeftBrace,
UnclosedRightBrace,
UnknownSpec,
MissingArg,
TooManyArgs,
};
// not have { and }
pub fn parse_spec(pattern: []const u8): @Result(Spec, Error) {
var res = Spec {
.fill = ' ',
.width = 0,
.align = .Left,
};
ret .Ok(res);
}
pub comptime fn Format(S: Sink): type {
ret struct {
out: S,
pub fn with_sink(out: S): @self {
ret .{ .out = out };
}
fn write(@Self self: *@self, str: []const u8): bool {
var res = true;
for i in str {
res = self.out.write_byte(i);
if (res == false) {
ret false;
}
}
ret res;
}
pub fn format(@Self self: *@self, pattern: []const u8, args: []const DisplayArg): Error {
var starti = 0;
for i in 0..pattern.len() {
var ch = pattern[i];
match pattern[i] {
'{' => {
},
'}' => {
},
_ => { continue; },
}
}
}
};
}
View File
Whitespace-only changes.
+19
View File
@@ -0,0 +1,19 @@
type .{ .Allocator } = @import("./alloc.spl");
type .{ .Result } = @import("./error.spl");
type .{ .static } = @import("./macro.spl");
type IOError = enum {
UnknownError,
OutOfMemory,
BufferTooSmall,
}
pub type Reader = shape {
fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError);
}
pub type Writer = shape {
fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError);
fn flush(@Self self: *@self): @Result((), IOError);
}
+22
View File
@@ -0,0 +1,22 @@
type meta = @import("meta");
type .{ .Ref } = meta;
#hook(param)
macro fn default(callee: Ref, value: Ref, fallback: Ref): Ref {
if value != 0 { ret value; }
if fallback != 0 { @meta.error(704); ret 0; }
// TODO check the same type
ret Ref;
}
#hook(param)
macro fn Self(callee: Ref, value: Ref): Ref {
// TODO value direct not supported
// @meta.
ret @meta.construct(.{ .kind = .Addr(value) });
}
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
pub fn bytes_eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
fn copy(dst: *any, src: *const any, count: usize) {
var _dst = dst as *u8;
var _src = src as *const u8;
var i: usize = 0;
while (i < count) {
_dst[i] = _src[i];
i = i + 1;
}
}
+120
View File
@@ -0,0 +1,120 @@
type .{ .Vec } = @import("./vec.spl");
type .{ .Allocator, .AllocError } = @import("./alloc.spl");
type .{ .Result, .Option } = @import("./error.spl");
type .{ .Format } = @import("./fmt.spl");
type .{ .static } = @import("./macro.spl");
type FromStr = shape {
type Err;
fn from_str(s: []const u8): @Result(@self, Err);
}
pub fn eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
pub fn starts_with(s: []const u8, prefix: []const u8): bool {
if prefix.len() > s.len() { ret false; }
ret eq(s[0..prefix.len()], prefix);
}
pub fn index_byte(s: []const u8, b: u8, from: usize): @Option(usize) {
var i = from;
while i < s.len() {
if s[i] == b { ret .Some(i); }
i = i + 1;
}
ret .None;
}
pub fn is_space(b: u8): bool {
ret b == ' ' || b == '\t' || b == '\r' || b == '\n';
}
pub fn is_digit(b: u8): bool {
ret b >= '0' && b <= '9';
}
pub fn is_hex_digit(b: u8): bool {
ret is_digit(b) || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F');
}
pub fn is_alpha(b: u8): bool {
ret (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z');
}
pub fn is_ident_start(b: u8): bool {
ret is_alpha(b) || b == '_';
}
pub fn is_ident_continue(b: u8): bool {
ret is_ident_start(b) || is_digit(b);
}
pub fn trim_ascii(s: []const u8): []const u8 {
var a: usize = 0;
var b: usize = s.len();
while a < b && is_space(s[a]) { a = a + 1; }
while b > a && is_space(s[b - 1]) { b = b - 1; }
ret s[a..b];
}
pub comptime fn String(A: Allocator): type {
ret struct {
data: @Vec(u8, A),
pub fn new(alloc: A): @self {
ret .{ .data = @Vec(u8, A).empty(alloc) };
}
pub fn from_slice(alloc: A, s: []const u8): @Result(@self, AllocError) {
var out: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try out.push_str(s);
ret .(.Ok(out));
}
pub fn push_str(@Self self: *@self, s: []const u8): @Result((), AllocError) {
var i: usize = 0;
while i < s.len() {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn from_cstr(alloc: A, s: *const u8): @Result(@self, AllocError) {
var res: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try res.push_cstr(s);
ret .(.Ok(res));
}
pub fn push_cstr(@Self self: *@self, s: *const u8): @Result((), AllocError) {
var i: usize = 0;
while s[i] != 0 {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn as_slice(@Self self: *@self): []const u8 {
ret self.data.as_slice();
}
pub fn len(@Self self: *@self): usize {
ret self.data.len();
}
pub fn clear(@Self self: *@self) {
self.data.clear();
}
pub fn drop(@Self self: *@self) {
self.data.drop();
}
};
}
+279
View File
@@ -0,0 +1,279 @@
type .{ .Option, .Result } = @import("./error.spl");
type .{ .Layout, .AllocError, .Allocator } = @import("./alloc.spl");
type ptr = @import("ptr.spl");
comptime fn RawVec(t: type): type {
ret struct {
data: *t,
length: usize,
cap: usize,
pub fn empty(): @self {
ret .{ .data = null, .length = 0, .cap = 0 };
}
pub fn len(@Self self: *@self): usize {
ret self.length;
}
pub fn capacity(@Self self: *@self): usize {
ret self.cap;
}
pub fn as_raw_ptr(@Self self: *@self): *t {
ret self.data;
}
pub fn as_slice(@Self self: *@self): []t {
ret @Slice(t).from_raw_parts(self.data, self.length);
}
pub fn get(@Self self: *@self, i: usize): @Option(t) {
if i >= self.length { ret .None }
ret .Some(self.data[i]);
}
pub fn at(@Self self: *@self, i: usize): @Option(*t) {
if i >= self.length { ret .None }
ret .Some(self.data + i);
}
pub fn set(@Self self: *@self, i: usize, v: t): bool {
if (i >= self.length) { ret false }
self.data[i] = v;
ret true;
}
pub fn clear(@Self self: *@self): () {
self.length = 0;
}
pub fn truncate(@Self self: *@self, n: usize): () {
if n < self.length {
self.length = n;
}
}
pub fn reset(@Self self: *@self): () {
self.data = null;
self.length = 0;
self.cap = 0;
}
pub fn set_unchecked(@Self self: *@self, i: usize, v: t) {
self.data[i] = v;
}
pub fn push_unchecked(@Self self: *@self, v: t): () {
self.data[self.length] = v;
self.length = self.length + 1;
}
pub fn pop_unchecked(@Self self: *@self): t {
self.length = self.length - 1;
ret self.data[self.length];
}
pub fn insert_unchecked(@Self self: *@self, i: usize, v: t): () {
var j = self.length;
while j > i {
self.data[j] = self.data[j - 1];
j = j - 1;
}
self.data[i] = v;
self.length += 1;
}
pub fn remove_unchecked(@Self self: *@self, i: usize): t {
var v = self.data[i];
var j = i;
while j + 1 < self.length {
self.data[j] = self.data[j + 1];
j = j + 1;
}
self.length -= 1;
ret v;
}
};
}
fn layout_of(size: usize, align: usize, n: usize): Layout {
var limit: usize = ~(0 as usize);
@assert(n == 0 || size <= limit / n, "layout overflow");
ret .{ .size = size * n, .align = align };
}
fn grow_capacity(current: usize, min_cap: usize, need: usize): usize {
var cap = current;
if cap < min_cap {
cap = min_cap;
}
while cap < need {
cap = cap * 2;
}
ret cap;
}
comptime fn Grow(T: type, A: Allocator): type {
ret struct {
fn reserve(base: *@RawVec(T), alloc: A, additional: usize): @Result((), AllocError) {
var need = base.len() + additional;
if need <= base.capacity() {
ret;
}
var new_cap = grow_capacity(base.capacity(), 8, need);
var old_layout = layout_of(@sizeof(T), @alignof(T), base.capacity());
var new_layout = layout_of(@sizeof(T), @alignof(T), new_cap);
var p: *u8 = try alloc.alloc(new_layout) as *u8;
if base.capacity() != 0 {
// TODO : Use copy_nonoverlapping to copy the data from the old allocation to the new one
// This is a placeholder for the actual memory copy operation
ptr.copy(p, base.data as *u8, base.len() * @sizeof(T));
alloc.dealloc(base.data as *any, old_layout);
}
base.data = p as *T;
base.cap = new_cap;
}
};
}
pub comptime fn Vec(T: type, A: Allocator): type {
ret struct {
base: @RawVec(T),
alloc: A,
pub fn empty(alloc: A): @self {
ret .{ .base = @RawVec(T).empty(), .alloc = alloc };
}
pub fn with_capacity(alloc: A, n: usize): @Result(@self, AllocError) {
@assert(@sizeof(T) > 0, "zero-size element unsupported");
var v: @self = .{ .base = @RawVec(T).empty(), .alloc = alloc };
if n == 0 {
ret .Ok(v);
}
try @Grow(T, A).reserve(&v.base, v.alloc, n);
ret .Ok(v);
}
pub fn len(@Self self: *@self): usize {
ret self.base.len();
}
pub fn capacity(@Self self: *@self): usize {
ret self.base.capacity();
}
pub fn as_slice(@Self self: *@self): []T {
ret self.base.as_slice();
}
pub fn get(@Self self: *@self, i: usize): @Option(T) {
ret self.base.get(i);
}
pub fn at(@Self self: *@self, i: usize): @Option(*T) {
ret self.base.at(i);
}
pub fn set(@Self self: *@self, i: usize, v: T): bool {
ret @RawVec(T).set(&self.base, i, v);
}
pub fn reserve(@Self self: *@self, additional: usize): @Result((), AllocError){
try @Grow(T, A).reserve(&self.base, self.alloc, additional);
}
pub fn push(@Self self: *@self, v: T): @Result((), AllocError) {
if self.base.len() + 1 > self.base.cap {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).push_unchecked(&self.base, v);
ret .Ok(());
}
pub fn pop(@Self self: *@self): @Option(T) {
if self.base.len() == 0 {
ret .None;
}
ret .Some(@RawVec(T).pop_unchecked(&self.base));
}
pub fn append(@Self self: *@self, items: []T): @Result((), AllocError) {
var count = items.len();
if count == 0 {
ret .Ok(());
}
var offset: usize = 0;
var inside = false;
if self.base.len() != 0 {
var base_addr = self.base.data as usize;
var src_addr = items.as_ptr() as usize;
if src_addr >= base_addr && src_addr - base_addr < self.base.len() * @sizeof(T) {
offset = src_addr - base_addr;
inside = true;
}
}
if self.base.len() + count > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, count);
}
var src = items.as_ptr();
if inside {
src = ((self.base.data as *u8) + offset) as *T;
}
var i: usize = 0;
while i < count {
@RawVec(T).push_unchecked(&self.base, src[i]);
i = i + 1;
}
ret .Ok(());
}
pub fn insert(@Self self: *@self, i: usize, v: T): @Result((), AllocError) {
@assert(i <= self.base.len(), "insert out of range");
if self.base.len() + 1 > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).insert_unchecked(&self.base, i, v);
ret .Ok(());
}
pub fn remove(@Self self: *@self, i: usize): @Option(T) {
if (i < self.base.len()) {
ret .None;
}
var res = @RawVec(T).remove_unchecked(&self.base, i);
ret .Some(res);
}
pub fn clear(@Self self: *@self): void {
@RawVec(T).clear(&self.base);
}
pub fn truncate(@Self self: *@self, n: usize): bool {
if (n >= self.base.len()) { ret false }
@RawVec(T).truncate(&self.base, n);
ret true;
}
pub fn _set_len(@Self self: *@self, n: usize): bool {
if (n >= self.base.capacity()) { ret false; }
self.base.length = n;
ret true;
}
pub fn drop(@Self self: *@self) {
if self.base.capacity() != 0 {
self.alloc.dealloc(self.base.data as *u8,
layout_of(@sizeof(T), @alignof(T), self.base.capacity()));
}
@RawVec(T).reset(&self.base);
}
pub fn take(@Self self: *@self): @self {
var r = self.*;
@RawVec(T).reset(&self.base);
ret r;
}
};
}
+84
View File
@@ -0,0 +1,84 @@
type .{ .VMWriter, .VMFile, .strlen, .VMAllocator } = @import("compiler/vm.spl");
type .{ .Vec } = @import("core/vec.spl");
type .{ .OptParse } = @import("compiler/optparse.spl");
type .{ .Source, .SourceError } = @import("lexer/source.spl");
fn test() {
var args: []const []const u8 = .["program", "-h"];
var parser = OptParse.with_args(args);
@assert(parser.args.len() == 2, "args len != 2");
@assert(parser.args.as_ptr() == args.as_ptr(), "args not assign");
@assert(parser.current.handle_positional == false, "handle_position");
@assert(parser.current.arg_pos == 1, "args pos need 1");
@assert(parser.current.opt_pos == 0, "opts pos need 0");
@assert(parser.current.opt == null, "current pot need null");
@assert(parser.opts.as_ptr() == null, "opts need null");
}
fn spl_main(args: const[] const[] u8): i32 {
var alloc = VMAllocator{};
var writer = VMFile.with_stdout();
// var writer = VMFile.open("output.txt", .Write) catch .Err(_) {
// @assert(false, "Failed to open output.txt for writing");
// };
for arg in args {
writer.write(arg);
writer.write("\n");
}
var vmfile = VMFile{};
var source = @Source(VMAllocator, VMFile).new(alloc, vmfile);
var ft = source.add_file("./src/test.spl") catch .Err(e) {
match e {
.UnknownError => { @assert(false, "unknow error"); },
.FileOpenError => { @assert(false, "fopen error"); },
.FileAttributeError => { @assert(false, "fattr error"); },
.FileReadError => { @assert(false, "fread error"); },
.OutOfMemory => { @assert(false, "oom error"); } ,
_ => { @assert(false, "error"); },
}
ret 1;
};
test();
}
fn main(argc: i32, _argv: const **u8, envp: const **u8): i32 {
// for i in 0..argc {
// var arg = _argv[i];
// var j: usize = 0;
// while (arg[j] != 0) {
// vm_putchar(arg[j] as i32);
// j = j + 1;
// }
// vm_putchar('\n' as i32);
// }
// var writer = VMWriter.with_stdout();
// // var res = writer.write("Hello, World!\n");
// var argv: []const *u8 = @Slice(const *u8).from_raw_parts(_argv as **u8, argc as usize) as []const *u8;
// for arg in argv {
// // var j: usize = 0;
// // while (arg[j] != 0) {
// // vm_putchar(arg[j] as i32);
// // j = j + 1;
// // }
// // vm_putchar('\n' as i32);
// writer.write(@Slice(const u8).from_raw_parts(arg, strlen(arg)));
// writer.write("\n");
// }
var alloc = VMAllocator{};
var argv: @Vec([]u8, VMAllocator) = @Vec([]u8, VMAllocator)
.with_capacity(alloc, argc as usize)
catch .Err(_) { ret 1; };
for arg in @Slice(*u8).from_raw_parts(_argv as **u8, argc as usize) {
var len = strlen(arg);
var arg_slice = @Slice(u8).from_raw_parts(arg, len);
argv.push(arg_slice) catch .Err(_) { ret 1; };
}
ret spl_main(argv.as_slice());
}
+116 -86
View File
@@ -5,8 +5,12 @@
* -g, --debug-cli interactive debugger (REPL)
* --entry <name> entry function (default: main)
* --trace print every instruction
* --profile native sampling profiler
* --profile-interval <N> profile sampling interval (default: 10000)
* -h, --help show help
*
* 选项可以出现在 <file.sir> 之前或之间;`--` 之后全部作为 spl 程序参数。
*
* spl 程序 argv:argv[0]=file.sir,argv[1..]=args。
* REPL 配合 splc0 -g(.sir 尾部内嵌 debug 段:IR 行 + VAR 行)可显示
* 当前 IR 节点/源行/局部变量。
@@ -21,103 +25,121 @@
#include <stdlib.h>
#include <string.h>
#define SCC_ARGPARSE_IMPLEMENTATION
#define SCC_OPTPARSER_IMPLEMENTATION
#include "../nob/argparse.h"
/* ================================================================
* 命令行解析
* ================================================================ */
typedef struct {
int debug;
int debug_cli;
int trace;
int disasm;
int profile;
cbool debug;
cbool debug_cli;
cbool trace;
cbool disasm;
cbool profile;
int profile_interval;
const char *profile_out;
int stats;
cbool stats;
const char *entry;
const char *path; /* file.sir */
const char **args; /* spl 程序参数(file.sir 之后) */
int nargs;
scc_argparse_list_t args; /* spl 程序参数(file.sir 之后) */
} cli_opts_t;
static void usage(void) {
fprintf(stderr, "Usage: spl_cli [options] <file.sir> [args...]\n"
" -d, --debug stack-canary checks\n"
" -g, --debug-cli interactive debugger (REPL)\n"
" --disasm disasm dump sir\n"
" --entry <name> entry function (default: main)\n"
" --trace print every instruction\n"
" --profile[=N] native sampling profiler (every N insns, default 10000)\n"
" --profile-out <p> profile output prefix (default build/profile)\n"
" --stats print executed instructions / call count at exit\n"
" -h, --help show help\n");
static void add_bool_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
cbool *store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_bool(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
/* options 可穿插;`--` 终止 option 解析(本身不作为 file/args)。
* 第一个非 option 为 file.sir,其后为 spl args。 */
static int parse_args(int argc, const char **argv, cli_opts_t *o) {
static void add_string_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
const char **store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_string(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_int_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
int *store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_int(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_arg_string(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
const char **store, cbool required) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_string(&arg.spec, store);
arg.spec.flag_required = required;
scc_argparse_cmd_add_arg(cmd, &arg);
}
static void add_arg_list(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
scc_argparse_list_t *store) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_list(&arg.spec, store);
scc_argparse_cmd_add_arg(cmd, &arg);
}
/* argparse 的 BOOL 会忽略 `--profile=500` 的尾部值;显式拦掉,避免间隔被悄悄丢掉。 */
static int reject_inline_profile(int argc, const char **argv) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--profile=", 10) == 0) {
fprintf(stderr,
"spl_cli: `%s` is not supported, use `--profile --profile-interval N`\n",
argv[i]);
return -1;
}
}
return 0;
}
/* `--` 之后 optparse 不再识别选项,剩余 token 全部落进 args。 */
static int parse_cli(int argc, const char **argv, cli_opts_t *o) {
memset(o, 0, sizeof *o);
o->entry = "main";
int i = 1;
for (; i < argc; i++) {
const char *a = argv[i];
if (a[0] == '-' && a[1]) {
if (strcmp(a, "--") == 0) {
i++;
break;
}
if (strcmp(a, "-d") == 0 || strcmp(a, "--debug") == 0) {
o->debug = 1;
} else if (strcmp(a, "-g") == 0 || strcmp(a, "--debug-cli") == 0) {
o->debug_cli = 1;
} else if (strcmp(a, "--trace") == 0) {
o->trace = 1;
} else if (strcmp(a, "--disasm") == 0) {
o->disasm = 1;
} else if (strcmp(a, "--stats") == 0) {
o->stats = 1;
} else if (strcmp(a, "--profile") == 0) {
o->profile = 1;
} else if (strncmp(a, "--profile=", 10) == 0) {
o->profile = 1;
o->profile_interval = (int)strtol(a + 10, NULL, 10);
} else if (strcmp(a, "--profile-out") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "spl_cli: --profile-out needs a prefix\n");
if (reject_inline_profile(argc, argv) != 0)
return -1;
scc_argparse_t parser;
scc_argparse_init(&parser, "spl_cli", "SIR VM launcher + gdb-style debugger");
scc_argparse_cmd_t *root = scc_argparse_get_root(&parser);
add_bool_opt(root, 'd', "debug", "stack-canary checks", &o->debug);
add_bool_opt(root, 'g', "debug-cli", "interactive debugger (REPL)", &o->debug_cli);
add_bool_opt(root, 0, "disasm", "disasm dump sir", &o->disasm);
add_string_opt(root, 0, "entry", "entry function (default: main)", &o->entry);
add_bool_opt(root, 0, "trace", "print every instruction", &o->trace);
add_bool_opt(root, 0, "profile", "native sampling profiler", &o->profile);
add_int_opt(root, 0, "profile-interval", "profile sampling interval in insns (default: 10000)",
&o->profile_interval);
add_string_opt(root, 0, "profile-out", "profile output prefix (default: build/profile)",
&o->profile_out);
add_bool_opt(root, 0, "stats", "print executed instructions / call count at exit",
&o->stats);
add_arg_string(root, "file", "SIR bytecode file", &o->path, true);
add_arg_list(root, "args", "arguments passed to the spl program", &o->args);
int rc = scc_argparse_parse(&parser, argc, argv);
if (parser.out.count > 0)
fwrite(parser.out.items, 1, parser.out.count, stdout);
scc_argparse_drop(&parser);
if (rc != SCC_ARGPARSE_ERR_NONE) {
scc_vec_free(o->args);
/* 1 表示 -h/--version 已处理,按成功退出。 */
return rc == SCC_ARGPARSE_ERR_PNT_DEFAULT ? 1 : -1;
}
o->profile_out = argv[++i];
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "spl_cli: --entry needs a name\n");
return -1;
}
o->entry = argv[++i];
} else if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
usage();
return -1;
} else {
fprintf(stderr, "spl_cli: unknown option '%s'\n", a);
usage();
return -1;
}
} else {
break;
}
}
/* 跳过前导 `--`(pipeline 调用会带 `--` 分隔 file 与 args) */
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
if (i >= argc) {
fprintf(stderr, "spl_cli: missing <file.sir>\n");
usage();
return -1;
}
o->path = argv[i++];
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
o->args = argv + i;
o->nargs = argc - i;
return 0;
}
@@ -640,17 +662,20 @@ static void repl_loop(dbg_t *d) {
int main(int argc, const char **argv) {
cli_opts_t o;
if (parse_args(argc, argv, &o) != 0)
return 1;
int cli_rc = parse_cli(argc, argv, &o);
if (cli_rc != 0)
return cli_rc > 0 ? 0 : 1;
spl_prog_t prog;
if (spl_prog_load_from_file(o.path, &prog) != 0) {
fprintf(stderr, "spl_cli: cannot load '%s'\n", o.path);
scc_vec_free(o.args);
return 1;
}
if (o.disasm) {
spl_prog_dump(&prog);
scc_vec_free(o.args);
return 0;
}
spl_syscall_register(&prog);
@@ -671,6 +696,7 @@ int main(int argc, const char **argv) {
fprintf(stderr, "spl_cli: failed to load prog\n");
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
return 1;
}
if (o.profile) {
@@ -680,21 +706,24 @@ int main(int argc, const char **argv) {
}
/* spl 程序 argv:argv[0]=file.sir(程序名),argv[1..]=args */
const char **spl_argv = (const char **)malloc(sizeof(char *) * (size_t)(o.nargs + 1));
int nargs = (int)o.args.count;
const char **spl_argv = (const char **)malloc(sizeof(char *) * (size_t)(nargs + 1));
if (!spl_argv) {
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
return 1;
}
spl_argv[0] = o.path;
for (int i = 0; i < o.nargs; i++)
spl_argv[i + 1] = o.args[i];
for (int i = 0; i < nargs; i++)
spl_argv[i + 1] = o.args.items[i];
if (spl_vm_prepare(&vm, o.entry, o.nargs + 1, spl_argv, NULL) != 0) {
if (spl_vm_prepare(&vm, o.entry, nargs + 1, spl_argv, NULL) != 0) {
fprintf(stderr, "spl_cli: entry point '%s' not found\n", o.entry);
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
return 1;
}
@@ -735,6 +764,7 @@ int main(int argc, const char **argv) {
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
if (ret < 0)
return 1;
+1
View File
@@ -69,6 +69,7 @@ SPL_FN u64 vm_fsize(void *f) {
SPL_FN void *vm_stdin(void) { return (void *)stdin; }
SPL_FN void *vm_stdout(void) { return (void *)stdout; }
SPL_FN void *vm_stderr(void) { return (void *)stderr; }
SPL_FN i32 vm_fflush(void *f) { return f ? fflush((FILE *)f) : 0; }
SPL_FN i32 vm_putchar(i32 c) { return fputc(c, stdout); }
SPL_FN i32 vm_getchar(void) { return fgetc(stdin); }
-581
View File
@@ -100,545 +100,6 @@ SPL_CORE_FN intptr_t vm_memcmp(const void *a, const void *b, uintptr_t n) {
return (intptr_t)memcmp(a, b, (size_t)n);
}
SPL_CORE_FN int spl_bytes_eq_ex(spl_asp_t *asp, const void *a, uintptr_t alen, const void *b,
uintptr_t blen) {
(void)asp;
if (alen != blen)
return 0;
if (alen == 0)
return 1;
if (!a || !b)
return 0;
return memcmp(a, b, (size_t)alen) == 0;
}
/* ---------------- Vec ---------------- */
typedef struct {
uintptr_t raw;
uintptr_t data;
uintptr_t len;
uintptr_t cap;
uintptr_t elem_size;
uintptr_t elem_align;
} spl_vec_t;
SPL_CORE_FN int spl_align_ok(uintptr_t a) { return a != 0 && (a & (a - 1)) == 0; }
SPL_CORE_FN int spl_vec_is_valid(const spl_vec_t *v) {
uintptr_t a;
if (v->elem_size == 0)
return 0;
a = v->elem_align;
if (a == 0 || (a & (a - 1)) != 0)
return 0;
if (v->len > v->cap)
return 0;
if (v->cap == 0)
return v->raw == 0 && v->data == 0 && v->len == 0;
if (v->raw == 0 || v->data == 0)
return 0;
return (v->data & (a - 1)) == 0;
}
SPL_CORE_FN void spl_grow_capacity(uintptr_t current, uintptr_t min_cap, uintptr_t need,
uintptr_t *out) {
uintptr_t cap = current < min_cap ? min_cap : current;
uintptr_t limit = ~(uintptr_t)0;
while (cap < need) {
if (cap > limit / 2) {
cap = need;
break;
}
cap = cap * 2;
}
*out = cap;
}
SPL_CORE_FN int spl_vec_allocate_ex(spl_asp_t *asp, spl_vec_t *out, uintptr_t capacity,
uintptr_t elem_size, uintptr_t elem_align) {
uintptr_t bytes, mask, addr;
uintptr_t raw;
if (elem_size == 0)
return 1;
if (!spl_align_ok(elem_align))
return 4;
out->raw = 0;
out->data = 0;
out->len = 0;
out->cap = 0;
out->elem_size = elem_size;
out->elem_align = elem_align;
if (capacity == 0)
return 0;
if (capacity > ~(uintptr_t)0 / elem_size)
return 3;
bytes = capacity * elem_size;
mask = elem_align - 1;
if (bytes > ~(uintptr_t)0 - mask)
return 3;
raw = asp->alloc(asp->ctx, bytes + mask);
if (!raw)
return 3;
addr = raw;
if (addr > ~(uintptr_t)0 - mask) {
asp->free(asp->ctx, raw);
return 3;
}
out->raw = raw;
out->data = (addr + mask) & ~mask;
out->cap = capacity;
return 0;
}
SPL_CORE_FN int spl_vec_reserve_raw_ex(spl_asp_t *asp, spl_vec_t *v, uintptr_t need) {
uintptr_t new_cap = 0, used = 0, old;
spl_vec_t fresh;
int rc;
if (need <= v->cap)
return 0;
spl_grow_capacity(v->cap, 8, need, &new_cap);
rc = spl_vec_allocate_ex(asp, &fresh, new_cap, v->elem_size, v->elem_align);
if (rc)
return rc;
if (v->len != 0) {
if (v->len > ~(uintptr_t)0 / v->elem_size) {
asp->free(asp->ctx, fresh.raw);
return 3;
}
used = v->len * v->elem_size;
}
if (used)
memcpy(spl_x(asp, fresh.data), spl_x(asp, v->data), used);
fresh.len = v->len;
old = v->raw;
*v = fresh;
if (old)
asp->free(asp->ctx, old);
return 0;
}
SPL_CORE_FN void spl_vec_release_ex(spl_asp_t *asp, spl_vec_t *v) {
uintptr_t es = v->elem_size, ea = v->elem_align;
if (v->raw)
asp->free(asp->ctx, v->raw);
v->raw = 0;
v->data = 0;
v->len = 0;
v->cap = 0;
v->elem_size = es;
v->elem_align = ea;
}
SPL_CORE_FN int spl_vec_valid_ex(const void *vv) {
return vv ? spl_vec_is_valid((const spl_vec_t *)vv) : 0;
}
SPL_CORE_FN int spl_vec_push_raw_ex(spl_asp_t *asp, void *vv, const void *elem) {
spl_vec_t *v = (spl_vec_t *)vv;
if (!v || !elem)
return 0;
if (v->len < v->cap) {
memcpy(spl_x(asp, v->data + v->len * v->elem_size), elem, v->elem_size);
v->len++;
return 1;
}
return 0;
}
SPL_CORE_FN int spl_vec_push_ex(spl_asp_t *asp, void *vv, const void *elem) {
spl_vec_t *v = (spl_vec_t *)vv;
int rc;
if (!v || !elem || !spl_vec_is_valid(v))
return 1;
if (v->len < v->cap) {
memcpy(spl_x(asp, v->data + v->len * v->elem_size), elem, v->elem_size);
v->len++;
return 0;
}
rc = spl_vec_reserve_raw_ex(asp, v, v->len + 1);
if (rc)
return rc;
memmove(spl_x(asp, v->data + v->len * v->elem_size), elem, v->elem_size);
v->len++;
return 0;
}
SPL_CORE_FN int spl_vec_get_ex(spl_asp_t *asp, const void *vv, uintptr_t index, void **out) {
const spl_vec_t *v = (const spl_vec_t *)vv;
unsigned char *p;
if (!v || !out)
return 1;
if (!spl_vec_is_valid(v))
return 1;
if (index >= v->len)
return 2;
p = spl_x(asp, v->data) + index * v->elem_size;
*out = (void *)(uintptr_t)asp->to_off(asp->ctx, p, v->elem_size);
return 0;
}
SPL_CORE_FN int spl_vec_allocate_out_ex(spl_asp_t *asp, void *out, uintptr_t capacity,
uintptr_t elem_size, uintptr_t elem_align) {
if (!out)
return 1;
return spl_vec_allocate_ex(asp, (spl_vec_t *)out, capacity, elem_size, elem_align);
}
SPL_CORE_FN int spl_vec_reserve_raw_void_ex(spl_asp_t *asp, void *vv, uintptr_t need) {
if (!vv)
return 1;
return spl_vec_reserve_raw_ex(asp, (spl_vec_t *)vv, need);
}
SPL_CORE_FN int spl_vec_append_ex(spl_asp_t *asp, void *vv, const void *elems, uintptr_t count) {
spl_vec_t *v = (spl_vec_t *)vv;
uintptr_t copy_bytes, new_len, used, source_offset = 0;
int source_inside = 0, rc;
if (!v || !spl_vec_is_valid(v))
return 1;
if (count == 0)
return 0;
if (!elems)
return 1;
if (count > ~(uintptr_t)0 / v->elem_size)
return 3;
copy_bytes = count * v->elem_size;
if (v->len > ~(uintptr_t)0 - count)
return 3;
new_len = v->len + count;
used = v->len * v->elem_size;
if (used) {
unsigned char *base = spl_x(asp, v->data);
uintptr_t source = (uintptr_t)elems;
if (source >= (uintptr_t)base && source - (uintptr_t)base < used) {
source_offset = source - (uintptr_t)base;
if (copy_bytes > used - source_offset)
return 2;
source_inside = 1;
}
}
rc = spl_vec_reserve_raw_ex(asp, v, new_len);
if (rc)
return rc;
if (source_inside)
elems = (const void *)(spl_x(asp, v->data) + source_offset);
memmove(spl_x(asp, v->data + used), elems, copy_bytes);
v->len = new_len;
return 0;
}
SPL_CORE_FN int spl_vec_set_ex(spl_asp_t *asp, void *vv, uintptr_t index, const void *elem) {
spl_vec_t *v = (spl_vec_t *)vv;
if (!v || !elem || !spl_vec_is_valid(v))
return 1;
if (index >= v->len)
return 2;
memmove(spl_x(asp, v->data + index * v->elem_size), elem, v->elem_size);
return 0;
}
SPL_CORE_FN int spl_vec_pop_ex(spl_asp_t *asp, void *vv, void *out) {
spl_vec_t *v = (spl_vec_t *)vv;
if (!v || !out || !spl_vec_is_valid(v))
return 1;
if (v->len == 0)
return 2;
memmove(out, spl_x(asp, v->data + (v->len - 1) * v->elem_size), v->elem_size);
v->len--;
return 0;
}
SPL_CORE_FN int spl_vec_clone_ex(spl_asp_t *asp, void *outp, const void *srcp) {
spl_vec_t *out = (spl_vec_t *)outp;
const spl_vec_t *src = (const spl_vec_t *)srcp;
spl_vec_t fresh;
uintptr_t bytes;
int rc;
if (!out || !src || !spl_vec_is_valid(out) || !spl_vec_is_valid(src))
return 1;
if (out->elem_size != src->elem_size || out->elem_align != src->elem_align)
return 1;
fresh.raw = 0;
fresh.data = 0;
fresh.len = 0;
fresh.cap = 0;
fresh.elem_size = src->elem_size;
fresh.elem_align = src->elem_align;
rc = spl_vec_reserve_raw_ex(asp, &fresh, src->len);
if (rc)
return rc;
bytes = src->len * src->elem_size;
if (bytes)
memcpy(spl_x(asp, fresh.data), spl_x(asp, src->data), bytes);
fresh.len = src->len;
if (out->raw)
asp->free(asp->ctx, out->raw);
*out = fresh;
return 0;
}
SPL_CORE_FN int spl_vec_drop_ex(spl_asp_t *asp, void *vv) {
if (vv)
spl_vec_release_ex(asp, (spl_vec_t *)vv);
return 0;
}
/* ---------------- Map ---------------- */
typedef struct {
spl_vec_t keys;
spl_vec_t vals;
spl_vec_t states;
uintptr_t size;
uintptr_t key_size;
uintptr_t val_size;
uintptr_t hash_kind;
} spl_map_t;
SPL_CORE_FN uintptr_t spl_hash_usize_value(uintptr_t value) {
uintptr_t prime = 1099511628211ull;
uintptr_t h = value;
h = (h ^ (h >> 30)) * prime;
h = h ^ (h >> 27);
h = h * prime;
h = h ^ (h >> 31);
if (h == 0)
return prime;
return h;
}
SPL_CORE_FN uintptr_t spl_hash_bytes(const void *data, uintptr_t len) {
const unsigned char *p = (const unsigned char *)data;
uintptr_t h = 14695981039346656037ull;
uintptr_t prime = 1099511628211ull;
uintptr_t i;
for (i = 0; i < len; i++)
h = (h ^ (uintptr_t)p[i]) * prime;
return h;
}
SPL_CORE_FN uintptr_t spl_hash_bytes_ex(spl_asp_t *asp, const void *data, uintptr_t len) {
return spl_hash_bytes(spl_x(asp, (uintptr_t)data), len);
}
SPL_CORE_FN uintptr_t spl_map_hash_ex(spl_asp_t *asp, const spl_map_t *m, const void *key) {
const uintptr_t *v;
if (m->hash_kind == 0)
return spl_hash_usize_value(*(const uintptr_t *)key);
if (m->hash_kind == 2)
return 3;
v = (const uintptr_t *)key;
return spl_hash_bytes_ex(asp, (const void *)v[0], v[1]);
}
SPL_CORE_FN int spl_map_eq_ex(spl_asp_t *asp, const spl_map_t *m, const void *a, const void *b) {
const uintptr_t *x;
const uintptr_t *y;
if (m->hash_kind == 0 || m->hash_kind == 2)
return *(const uintptr_t *)a == *(const uintptr_t *)b;
x = (const uintptr_t *)a;
y = (const uintptr_t *)b;
if (x[1] != y[1])
return 0;
if (x[1] == 0)
return 1;
return memcmp(spl_x(asp, x[0]), spl_x(asp, y[0]), (size_t)x[1]) == 0;
}
SPL_CORE_FN int spl_map_valid(const spl_map_t *m) {
if (m->key_size == 0 || m->val_size == 0)
return 0;
if (m->keys.len != m->states.len || m->vals.len != m->states.len)
return 0;
if (m->size > m->states.len)
return 0;
return 1;
}
SPL_CORE_FN uintptr_t spl_map_find_slot_ex(spl_asp_t *asp, const spl_map_t *m, const void *key) {
uintptr_t mask, i, probes;
unsigned char *st;
if (m->states.cap == 0)
return ~(uintptr_t)0;
mask = m->states.cap - 1;
i = spl_map_hash_ex(asp, m, key) & mask;
st = spl_x(asp, m->states.data);
probes = 0;
while (probes < m->states.cap && st[i] != 0) {
if (st[i] == 1 &&
spl_map_eq_ex(asp, m, spl_x(asp, m->keys.data + i * m->key_size), key))
return i;
i = (i + 1) & mask;
probes++;
}
return ~(uintptr_t)0;
}
SPL_CORE_FN void spl_map_place_ex(spl_asp_t *asp, spl_map_t *m, const void *key, const void *val) {
uintptr_t mask = m->states.cap - 1;
uintptr_t i = spl_map_hash_ex(asp, m, key) & mask;
unsigned char *st = spl_x(asp, m->states.data);
uintptr_t first_deleted = ~(uintptr_t)0;
uintptr_t probes = 0;
while (probes < m->states.cap && st[i] != 0) {
if (st[i] == 2 && first_deleted == ~(uintptr_t)0)
first_deleted = i;
i = (i + 1) & mask;
probes++;
}
if (first_deleted != ~(uintptr_t)0)
i = first_deleted;
memcpy(spl_x(asp, m->keys.data + i * m->key_size), key, m->key_size);
memcpy(spl_x(asp, m->vals.data + i * m->val_size), val, m->val_size);
st[i] = 1;
m->size++;
}
SPL_CORE_FN int spl_map_reserve_ex(spl_asp_t *asp, spl_map_t *m, uintptr_t need) {
uintptr_t new_cap = 0, i;
spl_map_t fresh;
int rc;
if (!spl_map_valid(m))
return 1;
if (need <= m->states.cap)
return 0;
spl_grow_capacity(m->states.cap, 8, need, &new_cap);
fresh = *m;
fresh.keys.raw = 0;
fresh.keys.data = 0;
fresh.keys.len = 0;
fresh.keys.cap = 0;
fresh.vals.raw = 0;
fresh.vals.data = 0;
fresh.vals.len = 0;
fresh.vals.cap = 0;
fresh.states.raw = 0;
fresh.states.data = 0;
fresh.states.len = 0;
fresh.states.cap = 0;
fresh.size = 0;
rc = spl_vec_reserve_raw_ex(asp, &fresh.keys, new_cap);
if (rc)
goto fail;
rc = spl_vec_reserve_raw_ex(asp, &fresh.vals, new_cap);
if (rc)
goto fail;
rc = spl_vec_reserve_raw_ex(asp, &fresh.states, new_cap);
if (rc)
goto fail;
fresh.keys.len = new_cap;
fresh.vals.len = new_cap;
fresh.states.len = new_cap;
memset(spl_x(asp, fresh.states.data), 0, new_cap);
for (i = 0; i < m->states.len; i++) {
if (spl_x(asp, m->states.data)[i] == 1)
spl_map_place_ex(asp, &fresh, spl_x(asp, m->keys.data + i * m->key_size),
spl_x(asp, m->vals.data + i * m->val_size));
}
spl_vec_release_ex(asp, &m->keys);
spl_vec_release_ex(asp, &m->vals);
spl_vec_release_ex(asp, &m->states);
*m = fresh;
return 0;
fail:
spl_vec_release_ex(asp, &fresh.keys);
spl_vec_release_ex(asp, &fresh.vals);
spl_vec_release_ex(asp, &fresh.states);
return rc;
}
SPL_CORE_FN int spl_map_valid_ex(const void *mm) {
return mm ? spl_map_valid((const spl_map_t *)mm) : 0;
}
SPL_CORE_FN int spl_map_reserve_void_ex(spl_asp_t *asp, void *mm, uintptr_t need) {
if (!mm)
return 1;
return spl_map_reserve_ex(asp, (spl_map_t *)mm, need);
}
SPL_CORE_FN int spl_map_put_ex(spl_asp_t *asp, void *mm, const void *key, const void *val) {
spl_map_t *m = (spl_map_t *)mm;
uintptr_t existing;
if (!m || !key || !val || !spl_map_valid(m))
return 1;
existing = spl_map_find_slot_ex(asp, m, key);
if (existing != ~(uintptr_t)0) {
memcpy(spl_x(asp, m->vals.data + existing * m->val_size), val, m->val_size);
return 0;
}
if (m->states.cap == 0) {
int rc = spl_map_reserve_ex(asp, m, 8);
if (rc)
return rc;
} else {
uintptr_t next_size, scaled;
if (m->size > ~(uintptr_t)0 - 1)
return 3;
next_size = m->size + 1;
if (next_size > ~(uintptr_t)0 / 128)
return 3;
scaled = next_size * 128;
if (scaled / m->states.cap >= 70) {
int rc;
if (m->states.cap > ~(uintptr_t)0 / 2)
return 3;
rc = spl_map_reserve_ex(asp, m, m->states.cap * 2);
if (rc)
return rc;
}
}
spl_map_place_ex(asp, m, key, val);
return 0;
}
SPL_CORE_FN int spl_map_get_ex(spl_asp_t *asp, void *mm, const void *key, void *out) {
spl_map_t *m = (spl_map_t *)mm;
uintptr_t i;
if (!m || !key || !out || !spl_map_valid(m))
return 1;
i = spl_map_find_slot_ex(asp, m, key);
if (i == ~(uintptr_t)0)
return 1;
memcpy(out, spl_x(asp, m->vals.data + i * m->val_size), m->val_size);
return 0;
}
SPL_CORE_FN int spl_map_del_ex(spl_asp_t *asp, void *mm, const void *key) {
spl_map_t *m = (spl_map_t *)mm;
uintptr_t i;
if (!m || !key || !spl_map_valid(m))
return 1;
i = spl_map_find_slot_ex(asp, m, key);
if (i == ~(uintptr_t)0)
return 1;
spl_x(asp, m->states.data)[i] = 2;
m->size--;
return 0;
}
SPL_CORE_FN int spl_map_clear_ex(spl_asp_t *asp, void *mm) {
spl_map_t *m = (spl_map_t *)mm;
if (!m)
return 0;
if (m->states.data && m->states.len)
memset(spl_x(asp, m->states.data), 0, m->states.len);
m->size = 0;
return 0;
}
SPL_CORE_FN int spl_map_drop_ex(spl_asp_t *asp, void *mm) {
spl_map_t *m = (spl_map_t *)mm;
if (!m)
return 0;
spl_vec_release_ex(asp, &m->keys);
spl_vec_release_ex(asp, &m->vals);
spl_vec_release_ex(asp, &m->states);
m->size = 0;
return 0;
}
/* ================================================================
* 公开 C 符号(identity):供 native 编译器直接调用
* ================================================================ */
@@ -646,46 +107,4 @@ SPL_CORE_FN int spl_map_drop_ex(spl_asp_t *asp, void *mm) {
SPL_CORE_FN void *vm_alloc(uintptr_t sz) { return spl_alloc_ex(SPL_ASP_ID, sz); }
SPL_CORE_FN void vm_free(void *p) { spl_free_ex(SPL_ASP_ID, p); }
SPL_CORE_FN void *vm_realloc(void *p, uintptr_t sz) { return spl_realloc_ex(SPL_ASP_ID, p, sz); }
SPL_CORE_FN int vm_bytes_eq(const void *a, uintptr_t alen, const void *b, uintptr_t blen) {
return spl_bytes_eq_ex(SPL_ASP_ID, a, alen, b, blen);
}
SPL_CORE_FN int vm_vec_valid(const void *v) { return spl_vec_valid_ex(v); }
SPL_CORE_FN int vm_vec_push_raw(void *v, const void *e) {
return spl_vec_push_raw_ex(SPL_ASP_ID, v, e);
}
SPL_CORE_FN int vm_vec_push(void *v, const void *e) { return spl_vec_push_ex(SPL_ASP_ID, v, e); }
SPL_CORE_FN int vm_vec_get(const void *v, uintptr_t i, void **o) {
return spl_vec_get_ex(SPL_ASP_ID, v, i, o);
}
SPL_CORE_FN int vm_vec_allocate(void *o, uintptr_t c, uintptr_t es, uintptr_t ea) {
return spl_vec_allocate_out_ex(SPL_ASP_ID, o, c, es, ea);
}
SPL_CORE_FN int vm_vec_reserve_raw(void *v, uintptr_t n) {
return spl_vec_reserve_raw_void_ex(SPL_ASP_ID, v, n);
}
SPL_CORE_FN int vm_vec_append(void *v, const void *e, uintptr_t n) {
return spl_vec_append_ex(SPL_ASP_ID, v, e, n);
}
SPL_CORE_FN int vm_vec_set(void *v, uintptr_t i, const void *e) {
return spl_vec_set_ex(SPL_ASP_ID, v, i, e);
}
SPL_CORE_FN int vm_vec_pop(void *v, void *o) { return spl_vec_pop_ex(SPL_ASP_ID, v, o); }
SPL_CORE_FN int vm_vec_clone(void *o, const void *s) { return spl_vec_clone_ex(SPL_ASP_ID, o, s); }
SPL_CORE_FN int vm_vec_drop(void *v) { return spl_vec_drop_ex(SPL_ASP_ID, v); }
SPL_CORE_FN int vm_map_valid(const void *m) { return spl_map_valid_ex(m); }
SPL_CORE_FN int vm_map_reserve(void *m, uintptr_t n) {
return spl_map_reserve_void_ex(SPL_ASP_ID, m, n);
}
SPL_CORE_FN int vm_map_put(void *m, const void *k, const void *v) {
return spl_map_put_ex(SPL_ASP_ID, m, k, v);
}
SPL_CORE_FN int vm_map_get(void *m, const void *k, void *o) {
return spl_map_get_ex(SPL_ASP_ID, m, k, o);
}
SPL_CORE_FN int vm_map_del(void *m, const void *k) { return spl_map_del_ex(SPL_ASP_ID, m, k); }
SPL_CORE_FN int vm_map_clear(void *m) { return spl_map_clear_ex(SPL_ASP_ID, m); }
SPL_CORE_FN int vm_map_drop(void *m) { return spl_map_drop_ex(SPL_ASP_ID, m); }
#endif /* __SPL_RT_CORE_H__ */
+40 -148
View File
@@ -182,6 +182,26 @@ static spl_vm_val_t vm_putstr(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
return 0;
}
static spl_vm_val_t spl_sys_panic(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
spl_vm_val_t *slice;
const char *msg;
usize len;
CHECK_NARGS("panic", 1);
slice = (spl_vm_val_t *)VM_X(_vm, args[0]);
if (!slice) {
fputs("panic\n", stderr);
exit(1);
}
msg = (const char *)VM_X(_vm, slice[0]);
len = (usize)slice[1];
fputs("panic: ", stderr);
if (msg && len)
fwrite(msg, 1, len, stderr);
fputc('\n', stderr);
exit(1);
return 0;
}
static spl_vm_val_t vm_fopen(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
const char *path, *mode;
CHECK_NARGS("vm_fopen", 2);
@@ -233,6 +253,15 @@ static spl_vm_val_t vm_fsize(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
return (spl_vm_val_t)(uintptr_t)(sz < 0 ? 0 : sz);
}
static spl_vm_val_t vm_fflush(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
FILE *f;
CHECK_NARGS("vm_fflush", 1);
f = vm_file_get(_vm, args[0]);
if (!f)
return 0;
return (spl_vm_val_t)fflush(f);
}
static spl_vm_val_t vm_std_handle(spl_vm_t *_vm, int which) {
if (_vm->stdio_off[which] == 0) {
FILE *f = which == 0 ? stdin : (which == 1 ? stdout : stderr);
@@ -376,133 +405,6 @@ static spl_vm_val_t spl_sys_vm_memcmp(spl_vm_t *_vm, int nargs, spl_vm_val_t *ar
return (spl_vm_val_t)(uintptr_t)vm_memcmp(a, b, n);
}
/* =================================================================
* Vec syscalls(参数按 VM 偏移解释)
* ================================================================= */
#define VM_VEC_BYTES ((uintptr_t)sizeof(spl_vec_t))
#define VM_MAP_BYTES ((uintptr_t)sizeof(spl_map_t))
static spl_vm_val_t spl_sys_vm_vec_valid(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_valid", 1);
return (spl_vm_val_t)(uintptr_t)spl_vec_valid_ex(VM_XN(_vm, args[0], VM_VEC_BYTES));
}
static spl_vm_val_t spl_sys_vm_vec_push_raw(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_push_raw", 2);
return (spl_vm_val_t)(uintptr_t)spl_vec_push_raw_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), VM_X(_vm, args[1]));
}
static spl_vm_val_t spl_sys_vm_vec_push(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_push", 2);
return (spl_vm_val_t)(uintptr_t)spl_vec_push_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), VM_X(_vm, args[1]));
}
static spl_vm_val_t spl_sys_vm_vec_get(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_get", 3);
return (spl_vm_val_t)(uintptr_t)spl_vec_get_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), (uintptr_t)args[1],
(void **)VM_XN(_vm, args[2], sizeof(void *)));
}
static spl_vm_val_t spl_sys_vm_vec_allocate(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_allocate", 4);
return (spl_vm_val_t)(uintptr_t)spl_vec_allocate_out_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), (uintptr_t)args[1], (uintptr_t)args[2],
(uintptr_t)args[3]);
}
static spl_vm_val_t spl_sys_vm_vec_reserve_raw(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_reserve_raw", 2);
return (spl_vm_val_t)(uintptr_t)spl_vec_reserve_raw_void_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), (uintptr_t)args[1]);
}
static spl_vm_val_t spl_sys_vm_vec_append(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_append", 3);
return (spl_vm_val_t)(uintptr_t)spl_vec_append_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), VM_X(_vm, args[1]), (uintptr_t)args[2]);
}
static spl_vm_val_t spl_sys_vm_vec_set(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_set", 3);
return (spl_vm_val_t)(uintptr_t)spl_vec_set_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), (uintptr_t)args[1], VM_X(_vm, args[2]));
}
static spl_vm_val_t spl_sys_vm_vec_pop(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_pop", 2);
return (spl_vm_val_t)(uintptr_t)spl_vec_pop_ex(VM_ASP(_vm),
VM_XN(_vm, args[0], VM_VEC_BYTES),
VM_X(_vm, args[1]));
}
static spl_vm_val_t spl_sys_vm_vec_clone(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_clone", 2);
return (spl_vm_val_t)(uintptr_t)spl_vec_clone_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_VEC_BYTES), VM_XN(_vm, args[1], VM_VEC_BYTES));
}
static spl_vm_val_t spl_sys_vm_vec_drop(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_vec_drop", 1);
return (spl_vm_val_t)(uintptr_t)spl_vec_drop_ex(VM_ASP(_vm),
VM_XN(_vm, args[0], VM_VEC_BYTES));
}
static spl_vm_val_t spl_sys_vm_bytes_eq(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_bytes_eq", 4);
return (spl_vm_val_t)(uintptr_t)spl_bytes_eq_ex(VM_ASP(_vm), VM_X(_vm, args[0]),
(uintptr_t)args[1], VM_X(_vm, args[2]),
(uintptr_t)args[3]);
}
/* =================================================================
* Map syscalls
* ================================================================= */
static spl_vm_val_t spl_sys_vm_map_valid(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_valid", 1);
return (spl_vm_val_t)(uintptr_t)spl_map_valid_ex(VM_XN(_vm, args[0], VM_MAP_BYTES));
}
static spl_vm_val_t spl_sys_vm_map_reserve(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_reserve", 2);
return (spl_vm_val_t)(uintptr_t)spl_map_reserve_void_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_MAP_BYTES), (uintptr_t)args[1]);
}
static spl_vm_val_t spl_sys_vm_map_put(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_put", 3);
return (spl_vm_val_t)(uintptr_t)spl_map_put_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_MAP_BYTES), VM_X(_vm, args[1]), VM_X(_vm, args[2]));
}
static spl_vm_val_t spl_sys_vm_map_get(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_get", 3);
return (spl_vm_val_t)(uintptr_t)spl_map_get_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_MAP_BYTES), VM_X(_vm, args[1]), VM_X(_vm, args[2]));
}
static spl_vm_val_t spl_sys_vm_map_del(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_del", 2);
return (spl_vm_val_t)(uintptr_t)spl_map_del_ex(
VM_ASP(_vm), VM_XN(_vm, args[0], VM_MAP_BYTES), VM_X(_vm, args[1]));
}
static spl_vm_val_t spl_sys_vm_map_clear(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_clear", 1);
return (spl_vm_val_t)(uintptr_t)spl_map_clear_ex(VM_ASP(_vm),
VM_XN(_vm, args[0], VM_MAP_BYTES));
}
static spl_vm_val_t spl_sys_vm_map_drop(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_map_drop", 1);
return (spl_vm_val_t)(uintptr_t)spl_map_drop_ex(VM_ASP(_vm),
VM_XN(_vm, args[0], VM_MAP_BYTES));
}
/* =================================================================
* printf / timestamp
* ================================================================= */
@@ -662,6 +564,14 @@ static spl_vm_val_t spl_bridge_forward(spl_vm_t *nested, const spl_vm_call_t *ca
return back.ret;
}
/* SIR 后端按名字调用宿主 VM 函数,不需要额外的函数指针登记。 */
static spl_vm_val_t sc_vm_bind_foreign(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
(void)args;
CHECK_NARGS("vm_bind_foreign", 2);
return 0;
}
static spl_vm_val_t vm_new(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_new", 0);
(void)args;
@@ -882,11 +792,13 @@ void spl_syscall_register(spl_prog_t *prog) {
{"vm_getchar", 0, vm_getchar},
{"vm_putint", 0, vm_putint},
{"vm_putstr", 0, vm_putstr},
{"panic", 0, spl_sys_panic},
{"vm_fopen", 0, vm_fopen},
{"vm_fclose", 0, vm_fclose},
{"vm_fread", 0, vm_fread},
{"vm_fwrite", 0, vm_fwrite},
{"vm_fsize", 0, vm_fsize},
{"vm_fflush", 0, vm_fflush},
{"vm_stdin", 0, vm_stdin},
{"vm_stdout", 0, vm_stdout},
{"vm_stderr", 0, vm_stderr},
@@ -900,31 +812,11 @@ void spl_syscall_register(spl_prog_t *prog) {
{"vm_memcmp", 0, spl_sys_vm_memcmp},
{"vm_printf", 0, vm_printf},
{"vm_vec_valid", 0, spl_sys_vm_vec_valid},
{"vm_vec_push_raw", 0, spl_sys_vm_vec_push_raw},
{"vm_vec_push", 0, spl_sys_vm_vec_push},
{"vm_vec_get", 0, spl_sys_vm_vec_get},
{"vm_vec_allocate", 0, spl_sys_vm_vec_allocate},
{"vm_vec_reserve_raw", 0, spl_sys_vm_vec_reserve_raw},
{"vm_vec_append", 0, spl_sys_vm_vec_append},
{"vm_vec_set", 0, spl_sys_vm_vec_set},
{"vm_vec_pop", 0, spl_sys_vm_vec_pop},
{"vm_vec_clone", 0, spl_sys_vm_vec_clone},
{"vm_vec_drop", 0, spl_sys_vm_vec_drop},
{"vm_bytes_eq", 0, spl_sys_vm_bytes_eq},
{"vm_map_valid", 0, spl_sys_vm_map_valid},
{"vm_map_reserve", 0, spl_sys_vm_map_reserve},
{"vm_map_put", 0, spl_sys_vm_map_put},
{"vm_map_get", 0, spl_sys_vm_map_get},
{"vm_map_del", 0, spl_sys_vm_map_del},
{"vm_map_clear", 0, spl_sys_vm_map_clear},
{"vm_map_drop", 0, spl_sys_vm_map_drop},
{"vm_timestamp", 0, vm_timestamp},
{"vm_new", 0, vm_new},
{"vm_set_foreign", 0, sc_vm_set_foreign},
{"vm_bind_foreign", 0, sc_vm_bind_foreign},
{"vm_drop", 0, vm_drop},
{"vm_load", 0, vm_load},
{"vm_load_from_buffer", 0, vm_load_from_buffer},
+89 -1
View File
@@ -11,6 +11,8 @@ void *vm_new(void);
void vm_drop(void *vm);
int vm_load_from_buffer(void *vm, const void *buf, unsigned long long len);
void vm_push(void *vm, unsigned long long val);
void vm_bind_foreign(void *entry, void *handler);
void vm_set_foreign(void *vm, void *entry, void *ctx);
int vm_call(void *vm, const char *name, unsigned long long nargs);
int vm_run(void *vm);
unsigned long long vm_ret_val(void *vm);
@@ -75,6 +77,93 @@ void vm_push(void *p, unsigned long long val) {
vm->stacks.data[vm->sp++] = (spl_vm_val_t)val;
}
/* 原生后端没有“宿主 VM 名字表”,所以 vm_bind_foreign 先把名字和 C 函数指针
* 记到进程内注册表;vm_set_foreign 再按名字安装 trampoline。 */
typedef unsigned long long (*spl_host_bridge_fn)(
void *ctx, const char *name, unsigned long long name_len, void *nested,
unsigned long long arg_base, unsigned long long nargs);
typedef struct {
char name[128];
spl_host_bridge_fn fn;
} spl_host_binding_t;
#define SPL_HOST_BINDING_MAX 8
static spl_host_binding_t spl_host_bindings[SPL_HOST_BINDING_MAX];
static usize spl_host_binding_count = 0;
typedef struct {
spl_host_bridge_fn fn;
void *ctx;
} spl_host_bridge_t;
static spl_vm_val_t spl_host_bridge_tramp(spl_vm_t *nested,
const spl_vm_call_t *call,
void *user) {
spl_host_bridge_t *b = (spl_host_bridge_t *)user;
usize arg_base = spl_vm_call_arg_base(nested, call);
if (!b || !b->fn || arg_base == (usize)-1)
return 0;
return b->fn(b->ctx, call->name ? call->name : "",
call->name ? strlen(call->name) : 0, nested, arg_base,
call->nargs);
}
/* SPL 的 []u8 参数在生成的 C 里是 {ptr,len} 指针。 */
static const char *spl_slice_ptr(void *slice) {
return (const char *)((spl_vm_val_t *)slice)[0];
}
static usize spl_slice_len(void *slice) {
return (usize)((spl_vm_val_t *)slice)[1];
}
static spl_host_bridge_fn spl_host_binding_find(const char *name, usize len) {
usize i = 0;
while (i < spl_host_binding_count) {
usize n = strlen(spl_host_bindings[i].name);
if (n == len && memcmp(spl_host_bindings[i].name, name, len) == 0)
return spl_host_bindings[i].fn;
i += 1;
}
return NULL;
}
void vm_bind_foreign(void *entry, void *handler) {
const char *name = spl_slice_ptr(entry);
usize len = spl_slice_len(entry);
if (!name || len == 0 || len >= sizeof(spl_host_bindings[0].name) || !handler)
return;
usize i = 0;
while (i < spl_host_binding_count) {
if (strlen(spl_host_bindings[i].name) == len &&
memcmp(spl_host_bindings[i].name, name, len) == 0) {
spl_host_bindings[i].fn = (spl_host_bridge_fn)handler;
return;
}
i += 1;
}
if (spl_host_binding_count >= SPL_HOST_BINDING_MAX)
return;
memcpy(spl_host_bindings[spl_host_binding_count].name, name, len);
spl_host_bindings[spl_host_binding_count].name[len] = '\0';
spl_host_bindings[spl_host_binding_count].fn = (spl_host_bridge_fn)handler;
spl_host_binding_count += 1;
}
void vm_set_foreign(void *p, void *entry, void *ctx) {
const char *name = spl_slice_ptr(entry);
usize len = spl_slice_len(entry);
spl_host_bridge_fn fn = spl_host_binding_find(name, len);
if (!fn)
return;
/* 单线程编译器;同一时刻只有一个嵌套 VM 在运行。 */
static spl_host_bridge_t bridge;
bridge.fn = fn;
bridge.ctx = ctx;
spl_vm_set_foreign((spl_vm_t *)p, spl_host_bridge_tramp, &bridge);
}
int vm_call(void *p, const char *name, unsigned long long nargs) {
spl_vm_t *vm = (spl_vm_t *)p;
if (!vm || !name)
@@ -99,7 +188,6 @@ int vm_run(void *p) {
#define vm_mem_read spl_vm_mem_read
#define vm_mem_write spl_vm_mem_write
#define vm_set_foreign spl_vm_set_foreign
#define vm_invoke spl_vm_invoke
#define vm_stack_get spl_vm_stack_get
+22 -12
View File
@@ -105,6 +105,8 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
case SPL_AST_CONTAINER_MEMBERS:
dump_vec(ast, node->container_members.external_tags, stack);
if (node->container_members.module)
dump_node(ast, node->container_members.module, stack, false);
dump_vec(ast, node->container_members.declarations, stack);
break;
@@ -113,8 +115,18 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_vec(ast, node->tag_item.args, stack);
break;
case SPL_AST_MOD_DECL:
dump_vec(ast, node->mod_decl.decorator_list, stack);
dump_vec(ast, node->mod_decl.decls, stack);
break;
case SPL_AST_IMPORT_DECL:
dump_vec(ast, node->import_decl.decorator_list, stack);
break;
case SPL_AST_FN_DECL:
dump_vec(ast, node->fn_decl.tag_list, stack);
dump_vec(ast, node->fn_decl.decorator_list, stack);
dump_vec(ast, node->fn_decl.attr_list, stack);
dump_vec(ast, node->fn_decl.params, stack);
if (node->fn_decl.ret_type)
dump_node(ast, node->fn_decl.ret_type, stack, false);
@@ -124,6 +136,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
case SPL_AST_VAR_DECL:
case SPL_AST_CONST_DECL:
dump_vec(ast, node->var_const_decl.decorator_list, stack);
dump_vec(ast, node->var_const_decl.attr_list, stack);
if (node->var_const_decl.pattern)
dump_node(ast, node->var_const_decl.pattern, stack, false);
@@ -134,6 +147,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
break;
case SPL_AST_TYPE_DECL:
dump_vec(ast, node->type_decl.decorator_list, stack);
dump_vec(ast, node->type_decl.attr_list, stack);
if (node->type_decl.pattern)
dump_node(ast, node->type_decl.pattern, stack, false);
@@ -142,6 +156,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
break;
case SPL_AST_MEMBER_DECL:
dump_vec(ast, node->member_decl.decorator_list, stack);
dump_vec(ast, node->member_decl.attr_list, stack);
if (node->member_decl.type_expr)
dump_node(ast, node->member_decl.type_expr, stack, false);
@@ -155,13 +170,9 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_node(ast, node->param_decl.type_expr, stack, true);
break;
case SPL_AST_COMPTIME_DECL:
if (node->comptime_decl.body)
dump_node(ast, node->comptime_decl.body, stack, true);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
dump_vec(ast, node->top_level_block.tag_list, stack);
dump_vec(ast, node->top_level_block.decorator_list, stack);
dump_vec(ast, node->top_level_block.attr_list, stack);
if (node->top_level_block.block)
dump_node(ast, node->top_level_block.block, stack, true);
break;
@@ -184,7 +195,6 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
break;
case SPL_AST_STATEMENT_DEFER:
case SPL_AST_STATEMENT_COMPTIME:
if (node->statement_defer.body)
dump_node(ast, node->statement_defer.body, stack, true);
break;
@@ -292,8 +302,8 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_vec(ast, node->aggregate_literal.fields, stack);
break;
case SPL_AST_EXPR_COMPTIME_CALL:
dump_vec(ast, node->comptime_call.args, stack);
case SPL_AST_EXPR_COMPILE_CALL:
dump_vec(ast, node->compile_call.args, stack);
break;
case SPL_AST_EXPR_BLOCK:
@@ -394,8 +404,8 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_vec(ast, node->type_aggregate.members, stack);
break;
case SPL_AST_TYPE_COMPTIME_CALL:
dump_vec(ast, node->type_comptime_call.args, stack);
case SPL_AST_TYPE_COMPILE_CALL:
dump_vec(ast, node->type_compile_call.args, stack);
break;
case SPL_AST_PATTERN_IDENT:
File renamed without changes.
+1 -1
View File
@@ -1,5 +1,5 @@
#include "spl_diag.h"
#include "../stage0/include/color.h"
#include "stage0/include/color.h"
#include <stdarg.h>
+309 -253
View File
@@ -8,16 +8,27 @@
聚合值统一表示为「指向存储的指针」:u64 sN[..]; void* vN。
类型/布局全部走 layout,生成期不做运行时分发。非 extern 函数名 f<fid>。 */
typedef struct {
spl_ir_value_kind_t kind;
spl_ir_type_id_t tid;
uint64_t bits;
usize slot;
} cconst_t;
typedef VEC(cconst_t) cconst_vec_t;
typedef struct {
const spl_ir_t *ir;
const spl_type_t *type;
const spl_ir_type_table_t *type;
spl_layout_t *layout;
const spl_attr_t *attr;
spl_ir2c_buf_t *out;
usize gdata_n; /* 每个 mem.global_alloc 生成一块静态数据,从 1 开始编号 */
cconst_vec_t cconsts; /* 当前函数的 CONST 操作数槽 */
bool failed;
} ir2c_t;
/* 常量操作数占用 v 的高位编号,避免与指令结果 v1..vN 冲突。 */
#define SPL_IR2C_CONST_BASE ((usize)1 << 30)
static void buf_append(spl_ir2c_buf_t *b, const char *s, usize n) {
if (n == 0)
return;
@@ -34,12 +45,24 @@ static void buf_append(spl_ir2c_buf_t *b, const char *s, usize n) {
static void put(ir2c_t *c, const char *s) { buf_append(c->out, s, strlen(s)); }
static void put_n(ir2c_t *c, const char *s, usize n) { buf_append(c->out, s, n); }
static void put_byte(ir2c_t *c, char b) { buf_append(c->out, &b, 1); }
static void put_u(ir2c_t *c, usize v) {
static void put_u_raw(ir2c_t *c, usize v) {
char buf[32];
int n = snprintf(buf, sizeof buf, "%llu", (unsigned long long)v);
if (n > 0)
buf_append(c->out, buf, (usize)n);
}
static usize const_slot_lookup(ir2c_t *c, spl_ir_value_t v);
static void put_value_id(ir2c_t *c, spl_ir_value_t v) {
if (v.kind == SPL_IR_VALUE_INST) {
put_u_raw(c, v.inst);
return;
}
put_u_raw(c, SPL_IR2C_CONST_BASE + const_slot_lookup(c, v));
}
/* usize 走原路径;Value 常量走 v<base+slot>。 */
#define put_u(c_, x_) _Generic((x_), spl_ir_value_t: put_value_id, default: put_u_raw)((c_), (x_))
static void put_i(ir2c_t *c, long long v) {
char buf[32];
int n = snprintf(buf, sizeof buf, "%lld", v);
@@ -54,18 +77,18 @@ static void put_unsupported(ir2c_t *c, const char *what) {
put(c, " */\n");
}
static const spl_layout_info_t *info_of(ir2c_t *c, spl_type_id_t tid) {
static const spl_layout_info_t *info_of(ir2c_t *c, spl_ir_type_id_t tid) {
return spl_layout_info_of(c->layout, tid);
}
static usize type_size(ir2c_t *c, spl_type_id_t tid) {
static usize type_size(ir2c_t *c, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = info_of(c, tid);
if (!info)
return 0;
return (info->size_bits + 7) / 8;
}
static usize type_align(ir2c_t *c, spl_type_id_t tid) {
static usize type_align(ir2c_t *c, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = info_of(c, tid);
if (!info)
return 1;
@@ -73,68 +96,64 @@ static usize type_align(ir2c_t *c, spl_type_id_t tid) {
return a ? a : 1;
}
static bool is_aggregate(ir2c_t *c, spl_type_id_t tid) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static bool is_aggregate(ir2c_t *c, spl_ir_type_id_t tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return false;
switch (te->kind) {
case SPL_TYPE_ARRAY:
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_ARRAY:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
return true;
default:
return false;
}
}
static bool tid_is_bool(ir2c_t *c, spl_type_id_t tid) {
spl_type_node_t *te = spl_type_node(c->type, tid);
return te && te->kind == SPL_TYPE_BOOL;
static bool tid_is_bool(ir2c_t *c, spl_ir_type_id_t tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
return te && te->kind == SPL_IR_TYPE_BOOL;
}
static bool tid_is_unit(ir2c_t *c, spl_type_id_t tid) {
static bool tid_is_unit(ir2c_t *c, spl_ir_type_id_t tid) {
if (tid == 0)
return true;
spl_type_node_t *te = spl_type_node(c->type, tid);
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return true;
return te->kind == SPL_TYPE_UNIT;
return te->kind == SPL_IR_TYPE_UNIT;
}
static spl_type_id_t fn_ret_type(ir2c_t *c, spl_type_id_t fn_tid) {
spl_type_node_t *te = spl_type_node(c->type, fn_tid);
if (!te || te->kind != SPL_TYPE_FN)
static spl_ir_type_id_t fn_ret_type(ir2c_t *c, spl_ir_type_id_t fn_tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, fn_tid);
if (!te || te->kind != SPL_IR_TYPE_FN)
return 0;
return te->fn_type.ret;
}
static spl_type_id_t make_ptr(ir2c_t *c, spl_type_id_t pointee) {
return spl_type_builder_ptr((spl_type_t *)c->type, pointee);
static spl_ir_type_id_t make_ptr(ir2c_t *c, spl_ir_type_id_t pointee) {
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)c->type, pointee);
}
static spl_type_id_t make_bool(ir2c_t *c) {
return spl_type_builder_simple((spl_type_t *)c->type, SPL_TYPE_BOOL);
static spl_ir_type_id_t make_bool(ir2c_t *c) {
return spl_ir_type_builder_simple((spl_ir_type_table_t *)c->type, SPL_IR_TYPE_BOOL);
}
static spl_type_id_t make_usize(ir2c_t *c) {
return spl_type_builder_int((spl_type_t *)c->type, 64, 0);
static spl_ir_type_id_t make_usize(ir2c_t *c) {
return spl_ir_type_builder_int((spl_ir_type_table_t *)c->type, 64, 0);
}
static bool put_type(ir2c_t *c, spl_type_id_t tid) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static bool put_type(ir2c_t *c, spl_ir_type_id_t tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return false;
switch (te->kind) {
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_UNIT:
put(c, "void");
return true;
case SPL_TYPE_NEVER:
put(c, "void");
return true;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
put(c, "u8");
return true;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (te->int_type.bits == 8)
put(c, te->int_type.is_signed ? "i8" : "u8");
else if (te->int_type.bits == 16)
@@ -144,21 +163,20 @@ static bool put_type(ir2c_t *c, spl_type_id_t tid) {
else
put(c, te->int_type.is_signed ? "i64" : "u64");
return true;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
put(c, te->float_type.bits == 32 ? "float" : "double");
return true;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
put(c, "void*");
return true;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
put(c, "void*");
return true;
/* 聚合值统一以「指向存储的指针」表示 */
case SPL_TYPE_ARRAY:
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_ARRAY:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
put(c, "void*");
return true;
default:
@@ -167,7 +185,7 @@ static bool put_type(ir2c_t *c, spl_type_id_t tid) {
}
static bool fn_is_extern(ir2c_t *c, const spl_ir_func_t *f) {
return spl_ir_fn_extern_attr(c->attr, f) != NULL;
return f->extern_fn || spl_ir_fn_extern_attr(c->attr, f) != NULL;
}
static void c_fn_name(ir2c_t *c, spl_ir_func_ref_t fid) {
@@ -181,71 +199,60 @@ static void c_fn_name(ir2c_t *c, spl_ir_func_ref_t fid) {
put_u(c, fid);
}
/* 读取 type.const 的整数值;按 tid 决定落在哪个 union 成员(同 ir2vm 约定)。 */
static usize const_node(ir2c_t *c, const spl_ir_func_t *f, spl_ir_node_ref_t ref) {
if (ref == 0 || ref >= vec_size(f->nodes))
return 0;
const spl_ir_node_t *n = &vec_at(f->nodes, ref);
if (n->kind != SPL_IR_TYPE_CONST)
return 0;
spl_type_node_t *te = spl_type_node(c->type, n->type_const.tid);
if (!te)
return 0;
switch (te->kind) {
case SPL_TYPE_BOOL:
return n->type_const.bool_lit ? 1 : 0;
case SPL_TYPE_INT:
if (te->int_type.bits == 8)
return (usize)(unsigned char)n->type_const.ch_lit;
return n->type_const.int_lit;
case SPL_TYPE_PTR:
return (usize)n->type_const.ptr_lit;
default:
return 0;
/* 常量操作数按 (tid, 位模式) 共享一个 v<slot> 变量。 */
static uint64_t value_bits(spl_ir_value_t v) {
uint64_t bits = 0;
memcpy(&bits, &v.int_bits, sizeof bits);
return bits;
}
static usize const_slot_lookup(ir2c_t *c, spl_ir_value_t v) {
uint64_t bits = value_bits(v);
for (usize i = 0; i < vec_size(c->cconsts); ++i) {
cconst_t *e = &vec_at(c->cconsts, i);
if (e->kind == v.kind && e->tid == v.tid && e->bits == bits)
return e->slot;
}
cconst_t e = {.kind = v.kind, .tid = v.tid, .bits = bits, .slot = vec_size(c->cconsts)};
vec_push(c->cconsts, e);
return e.slot;
}
/* 函数常量节点(Fn lit)持有的函数 ref;非函数常量返回 0。 */
static spl_ir_func_ref_t const_fn_ref(ir2c_t *c, const spl_ir_func_t *f, spl_ir_node_ref_t ref) {
if (ref == 0 || ref >= vec_size(f->nodes))
return 0;
const spl_ir_node_t *n = &vec_at(f->nodes, ref);
if (n->kind != SPL_IR_TYPE_CONST)
return 0;
spl_type_node_t *te = spl_type_node(c->type, n->type_const.tid);
if (!te || te->kind != SPL_TYPE_FN)
return 0;
return n->type_const.fn;
static usize value_int(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? (usize)v.int_bits : 0;
}
static spl_type_id_t field_tid(ir2c_t *c, spl_type_id_t tid, usize idx) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static spl_ir_func_ref_t value_fn(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? v.fn : 0;
}
static spl_ir_type_id_t field_tid(ir2c_t *c, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return 0;
switch (te->kind) {
case SPL_TYPE_ENUM:
case SPL_IR_TYPE_ENUM:
if (idx == SPL_ENUM_TAG_FIELD_IDX)
return te->agg_type.tag_type;
idx -= 1;
/* fallthrough */
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
if (idx < vec_size(te->agg_type.variants))
return vec_at(te->agg_type.variants, idx).type_id;
return 0;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
return te->array_type.element;
default:
return 0;
}
}
static usize field_off(ir2c_t *c, spl_type_id_t tid, usize idx) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static usize field_off(ir2c_t *c, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return 0;
if (te->kind == SPL_TYPE_ARRAY)
if (te->kind == SPL_IR_TYPE_ARRAY)
return idx * type_size(c, te->array_type.element);
const spl_layout_info_t *info = info_of(c, tid);
if (!info || idx >= vec_size(info->field_bit_offsets))
@@ -254,7 +261,7 @@ static usize field_off(ir2c_t *c, spl_type_id_t tid, usize idx) {
}
/* 节点的「值类型」;0 表示无结果。 */
static spl_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
static spl_ir_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
@@ -291,16 +298,12 @@ static spl_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
return n->cast.to_tid;
case SPL_IR_MEM_ALLOCA:
return make_ptr(c, n->mem_alloc.tid);
case SPL_IR_MEM_GLOBAL_ALLOC:
return n->mem_global_alloc.tid; /* 已是 *u8 */
case SPL_IR_MEM_LOAD:
return n->mem_load.tid;
case SPL_IR_MEM_OFFSET:
return make_ptr(c, n->mem_offset.tid);
case SPL_IR_MEM_FIELD_PTR:
return make_ptr(c, field_tid(c, n->mem_field_ptr.tid, n->mem_field_ptr.field_idx));
case SPL_IR_TYPE_CONST:
return n->type_const.tid;
case SPL_IR_TYPE_BITSIZEOF:
case SPL_IR_TYPE_SIZEOF:
case SPL_IR_TYPE_ALIGNOF:
@@ -324,6 +327,14 @@ static spl_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
}
}
static spl_ir_type_id_t value_type(ir2c_t *c, const spl_ir_func_t *f, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST)
return v.tid;
if (v.inst == 0 || v.inst >= vec_size(f->nodes))
return 0;
return result_tid(c, &vec_at(f->nodes, v.inst));
}
static void bind_agg(ir2c_t *c, usize ref) {
put(c, "v");
put_u(c, ref);
@@ -332,7 +343,7 @@ static void bind_agg(ir2c_t *c, usize ref) {
put(c, ";\n");
}
static void declare_ref(ir2c_t *c, usize ref, spl_type_id_t tid) {
static void declare_ref(ir2c_t *c, usize ref, spl_ir_type_id_t tid) {
if (is_aggregate(c, tid)) {
usize size = type_size(c, tid);
usize words = (size + 7) / 8;
@@ -360,10 +371,12 @@ static void emit_agg_construct(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
return;
}
bind_agg(c, ref);
spl_type_id_t agg_t = n->agg_construct.tid;
spl_ir_type_id_t agg_t = n->agg_construct.tid;
for (usize i = 0; i < vec_size(n->agg_construct.fields); ++i) {
spl_ir_node_ref_t fref = vec_at(n->agg_construct.fields, i);
spl_type_id_t ftid = field_tid(c, agg_t, i);
spl_ir_value_t fref = vec_at(n->agg_construct.fields, i);
if (spl_ir_value_is_none(fref))
continue;
spl_ir_type_id_t ftid = field_tid(c, agg_t, i);
if (!ftid)
continue;
usize foff = field_off(c, agg_t, i);
@@ -421,7 +434,7 @@ static void emit_agg_extract(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
static void emit_agg_insert(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
bind_agg(c, ref);
spl_type_id_t agg_t = n->agg_insert.tid;
spl_ir_type_id_t agg_t = n->agg_insert.tid;
usize sz = type_size(c, agg_t);
put(c, "memcpy(v");
put_u(c, ref);
@@ -430,7 +443,7 @@ static void emit_agg_insert(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
put(c, ", ");
put_u(c, sz);
put(c, ");\n");
spl_type_id_t ftid = field_tid(c, agg_t, n->agg_insert.field_idx);
spl_ir_type_id_t ftid = field_tid(c, agg_t, n->agg_insert.field_idx);
usize foff = field_off(c, agg_t, n->agg_insert.field_idx);
if (!ftid)
return;
@@ -598,14 +611,14 @@ static void emit_cast(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
bool from_is_ptr = false;
bool from_is_bool = false;
bool to_is_ptr = false;
spl_type_node_t *te = spl_type_node(c->type, n->cast.from_tid);
spl_ir_type_node_t *te = spl_ir_type_node(c->type, n->cast.from_tid);
if (te) {
from_is_ptr = te->kind == SPL_TYPE_PTR;
from_is_bool = te->kind == SPL_TYPE_BOOL;
from_is_ptr = te->kind == SPL_IR_TYPE_PTR;
from_is_bool = te->kind == SPL_IR_TYPE_BOOL;
}
spl_type_node_t *tte = spl_type_node(c->type, n->cast.to_tid);
spl_ir_type_node_t *tte = spl_ir_type_node(c->type, n->cast.to_tid);
if (tte)
to_is_ptr = tte->kind == SPL_TYPE_PTR;
to_is_ptr = tte->kind == SPL_IR_TYPE_PTR;
if (to_is_ptr) {
put(c, "(void*)(usize)v");
put_u(c, n->cast.val);
@@ -623,68 +636,8 @@ static void emit_cast(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
put(c, ";\n");
}
static void emit_const(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
spl_type_id_t tid = n->type_const.tid;
spl_type_node_t *te = spl_type_node(c->type, tid);
if (!te)
return;
if (te->kind == SPL_TYPE_UNIT)
return;
put(c, "v");
put_u(c, ref);
put(c, " = ");
switch (te->kind) {
case SPL_TYPE_BOOL:
put(c, n->type_const.bool_lit ? "1" : "0");
break;
case SPL_TYPE_INT: {
usize raw = (te->int_type.bits == 8) ? (usize)(unsigned char)n->type_const.ch_lit
: n->type_const.int_lit;
if (te->int_type.is_signed) {
long long sv = (long long)raw;
if (sv == (-9223372036854775807LL - 1))
put(c, "(-9223372036854775807 - 1)");
else
put_i(c, sv);
} else {
put_u(c, raw);
if (te->int_type.bits >= 64)
put(c, "ull");
}
break;
}
case SPL_TYPE_PTR:
put(c, "(void*)");
put_u(c, (usize)n->type_const.ptr_lit);
break;
/* 字节常量(字符串/文件名):只被 mem.global_alloc 通过字段引用,vN 是死值。
若输出宿主指针会导致生成物随编译进程地址而变,这里固定为 0。 */
case SPL_TYPE_ARRAY:
put(c, "(void*)0");
break;
case SPL_TYPE_FN:
put(c, "(void*)&");
c_fn_name(c, n->type_const.fn);
break;
case SPL_TYPE_FLOAT: {
double d = n->type_const.float_lit;
if (isfinite(d)) {
char buf[64];
snprintf(buf, sizeof buf, "%.17g", d);
put(c, buf);
} else {
put(c, "0.0");
}
break;
}
default:
put(c, "0");
break;
}
put(c, ";\n");
}
static void emit_mem(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n) {
(void)f;
switch (n->kind) {
case SPL_IR_MEM_ALLOCA:
@@ -766,62 +719,13 @@ static void emit_mem(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_
break;
}
case SPL_IR_MEM_GLOBAL_ALLOC: {
spl_type_id_t ctid = 0;
const void *pv = NULL;
if (n->mem_global_alloc.const_node > 0 &&
n->mem_global_alloc.const_node < vec_size(f->nodes)) {
const spl_ir_node_t *cn = &vec_at(f->nodes, n->mem_global_alloc.const_node);
if (cn->kind == SPL_IR_TYPE_CONST) {
ctid = cn->type_const.tid;
pv = cn->type_const.ptr_lit;
}
}
if (!pv) {
put(c, "v");
put_u(c, ref);
put(c, " = (void*)0;\n");
break;
}
/* size 为 0(空数组)时只生成一个零词,避免越界读取宿主内存导致生成物不确定。 */
usize size = type_size(c, ctid);
usize gid = c->gdata_n++;
usize words = (size + 7) / 8;
if (words == 0)
words = 1;
put(c, "static const u64 g");
put_u(c, gid);
put(c, "[");
put_u(c, words);
put(c, "] = {");
for (usize j = 0; j < words; ++j) {
if (j > 0)
put(c, ", ");
uint64_t w = 0;
for (usize k = 0; k < 8; ++k) {
usize idx = j * 8 + k;
uint64_t b = 0;
if (idx < size)
b = (uint64_t)((const unsigned char *)pv)[idx];
w |= b << (k * 8);
}
put_u(c, (usize)w);
put(c, "ull");
}
put(c, "};\nv");
put_u(c, ref);
put(c, " = (void*)g");
put_u(c, gid);
put(c, ";\n");
break;
}
default:
break;
}
}
static void emit_typeop(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n) {
(void)f;
usize v = 0;
switch (n->kind) {
case SPL_IR_TYPE_SIZEOF:
@@ -838,21 +742,20 @@ static void emit_typeop(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_
break;
case SPL_IR_TYPE_OFFSETOF: {
/* field_idx 是一个常量节点 ref */
usize idx = const_node(c, f, n->ir_offsetof.field_idx);
usize idx = value_int(n->ir_offsetof.field_idx);
v = field_off(c, n->ir_offsetof.tid, idx);
break;
}
case SPL_IR_TYPE_FIELD_COUNT: {
spl_type_node_t *te = spl_type_node(c->type, n->field_count.tid);
spl_ir_type_node_t *te = spl_ir_type_node(c->type, n->field_count.tid);
if (te) {
switch (te->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
v = vec_size(te->agg_type.variants);
break;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
v = te->array_type.len;
break;
default:
@@ -872,7 +775,7 @@ static void emit_typeop(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_
}
static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n) {
spl_ir_func_ref_t callee = const_fn_ref(c, f, n->control_call.func);
spl_ir_func_ref_t callee = value_fn(n->control_call.func);
bool ret_agg = is_aggregate(c, n->control_call.tid);
if (callee != 0) {
if (ret_agg) {
@@ -899,11 +802,9 @@ static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
}
/* 间接调用:从 func 值的类型构造函数指针类型 */
spl_type_id_t func_tid = 0;
if (n->control_call.func < vec_size(f->nodes))
func_tid = result_tid(c, &vec_at(f->nodes, n->control_call.func));
spl_type_node_t *ftnode = spl_type_node(c->type, func_tid);
if (!ftnode || ftnode->kind != SPL_TYPE_FN) {
spl_ir_type_id_t func_tid = value_type(c, f, n->control_call.func);
spl_ir_type_node_t *ftnode = spl_ir_type_node(c->type, func_tid);
if (!ftnode || ftnode->kind != SPL_IR_TYPE_FN) {
put_unsupported(c, "indirect call type");
return;
}
@@ -930,7 +831,7 @@ static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
for (usize kp = 0; kp < np; ++kp) {
if (need_comma)
put(c, ", ");
spl_type_id_t pt = vec_at(ftnode->fn_type.params, kp);
spl_ir_type_id_t pt = vec_at(ftnode->fn_type.params, kp);
if (is_aggregate(c, pt))
put(c, "void*");
else if (!put_type(c, pt))
@@ -956,10 +857,10 @@ static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
}
static void emit_control(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n,
spl_type_id_t ret_tid) {
spl_ir_type_id_t ret_tid) {
switch (n->kind) {
case SPL_IR_CONTROL_PARAM: {
usize idx = const_node(c, f, n->control_param.idx);
usize idx = value_int(n->control_param.idx);
if (is_aggregate(c, n->control_param.tid)) {
put(c, "v");
put_u(c, ref);
@@ -980,7 +881,7 @@ static void emit_control(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl
case SPL_IR_CONTROL_RET:
if (is_aggregate(c, ret_tid)) {
if (n->control_ret.val) {
if (!spl_ir_value_is_none(n->control_ret.val)) {
usize sz = type_size(c, ret_tid);
put(c, "memcpy(ret__, v");
put_u(c, n->control_ret.val);
@@ -1024,12 +925,8 @@ static void emit_control(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl
}
static void emit_node(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n,
spl_type_id_t ret_tid) {
spl_ir_type_id_t ret_tid) {
switch (n->kind) {
case SPL_IR_TYPE_CONST:
emit_const(c, ref, n);
break;
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
@@ -1074,7 +971,6 @@ static void emit_node(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
case SPL_IR_MEM_STORE:
case SPL_IR_MEM_OFFSET:
case SPL_IR_MEM_FIELD_PTR:
case SPL_IR_MEM_GLOBAL_ALLOC:
emit_mem(c, f, ref, n);
break;
@@ -1160,14 +1056,109 @@ static void emit_node(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
}
}
static void emit_const_literal(ir2c_t *c, spl_ir_value_t v) {
if (v.kind == SPL_IR_VALUE_GLOBAL) {
put(c, "(void*)gg");
put_u_raw(c, v.global_id);
return;
}
spl_ir_type_node_t *te = spl_ir_type_node(c->type, v.tid);
if (!te) {
put(c, "0");
return;
}
switch (te->kind) {
case SPL_IR_TYPE_BOOL:
put(c, v.int_bits ? "1" : "0");
break;
case SPL_IR_TYPE_INT: {
uint64_t raw = v.int_bits;
if (te->int_type.bits == 8)
raw = (unsigned char)raw;
if (te->int_type.is_signed) {
long long sv = (long long)raw;
if (sv == (-9223372036854775807LL - 1))
put(c, "(-9223372036854775807LL - 1)");
else {
put(c, "(");
put_i(c, sv);
put(c, ")");
}
} else {
put(c, "(");
put_u_raw(c, (usize)raw);
if (te->int_type.bits >= 64)
put(c, "ull");
put(c, ")");
}
break;
}
case SPL_IR_TYPE_PTR:
if (v.global_id) {
put(c, "(void*)gg");
put_u_raw(c, v.global_id);
} else {
put(c, "(void*)0");
}
break;
case SPL_IR_TYPE_FN:
if (v.fn == 0) {
put(c, "(void*)0");
} else {
put(c, "(void*)&");
c_fn_name(c, v.fn);
}
break;
case SPL_IR_TYPE_FLOAT: {
char buf[64];
if (isfinite(v.float_bits))
snprintf(buf, sizeof buf, "%.17g", v.float_bits);
else
snprintf(buf, sizeof buf, "0.0");
put(c, buf);
break;
}
default:
put(c, "0");
break;
}
}
static void collect_const_cb(void *ud, spl_ir_value_t v) {
ir2c_t *c = ud;
if (v.kind != SPL_IR_VALUE_INST)
(void)const_slot_lookup(c, v);
}
static void declare_consts(ir2c_t *c) {
for (usize i = 0; i < vec_size(c->cconsts); ++i) {
cconst_t *e = &vec_at(c->cconsts, i);
if (!put_type(c, e->tid))
put(c, "void*");
put(c, " v");
put_u_raw(c, SPL_IR2C_CONST_BASE + e->slot);
put(c, " = ");
spl_ir_value_t v = {0};
v.kind = e->kind;
v.tid = e->tid;
memcpy(&v.int_bits, &e->bits, sizeof e->bits);
emit_const_literal(c, v);
put(c, ";\n");
}
}
static void declare_all(ir2c_t *c, const spl_ir_func_t *f) {
c->cconsts.size = 0;
for (usize i = 1; i < vec_size(f->nodes); ++i)
spl_ir_node_visit_values(&vec_at(f->nodes, i), collect_const_cb, c);
for (usize i = 1; i < vec_size(f->nodes); ++i) {
const spl_ir_node_t *n = &vec_at(f->nodes, i);
if (n->kind == SPL_IR_MEM_ALLOCA) {
usize count = const_node(c, f, n->mem_alloc.count);
usize count = value_int(n->mem_alloc.count);
if (count == 0)
count = 1;
spl_type_id_t pointee = n->mem_alloc.tid;
spl_ir_type_id_t pointee = n->mem_alloc.tid;
if (is_aggregate(c, pointee)) {
usize esz = type_size(c, pointee);
usize words = (esz * count + 7) / 8;
@@ -1193,15 +1184,16 @@ static void declare_all(ir2c_t *c, const spl_ir_func_t *f) {
}
continue;
}
spl_type_id_t tid = result_tid(c, n);
spl_ir_type_id_t tid = result_tid(c, n);
if (tid != 0 && !tid_is_unit(c, tid))
declare_ref(c, i, tid);
}
declare_consts(c);
}
static void emit_fn_sig(ir2c_t *c, spl_ir_func_ref_t fid, bool with_names) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, fid);
spl_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
spl_ir_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
bool ret_agg = is_aggregate(c, ret_tid);
if (ret_agg)
put(c, "void");
@@ -1215,13 +1207,20 @@ static void emit_fn_sig(ir2c_t *c, spl_ir_func_ref_t fid, bool with_names) {
put(c, "void* ret__");
need = true;
}
spl_type_node_t *te = spl_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_TYPE_FN) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_IR_TYPE_FN) {
usize nargs = vec_size(te->fn_type.params);
for (usize k = 0; k < nargs; ++k) {
if (need)
put(c, ", ");
spl_type_id_t pt = vec_at(te->fn_type.params, k);
spl_ir_type_id_t pt = vec_at(te->fn_type.params, k);
spl_ir_type_node_t *ptn = spl_ir_type_node(c->type, pt);
if (ptn && ptn->kind == SPL_IR_TYPE_UNIT) {
/* varargs 标记在 IR 里落成 unit 类型。 */
put(c, "...");
need = true;
continue;
}
if (is_aggregate(c, pt))
put(c, "void*");
else if (!put_type(c, pt))
@@ -1245,7 +1244,7 @@ static void emit_proto(ir2c_t *c, spl_ir_func_ref_t fid) {
static void emit_def(ir2c_t *c, spl_ir_func_ref_t fid) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, fid);
spl_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
spl_ir_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
emit_fn_sig(c, fid, true);
put(c, " {\n");
declare_all(c, f);
@@ -1267,14 +1266,63 @@ static spl_ir_func_ref_t find_main(ir2c_t *c) {
return 0;
}
static void emit_globals(ir2c_t *c) {
for (usize i = 1; i < vec_size(c->ir->globals); ++i) {
const spl_ir_global_t *g = &vec_at(c->ir->globals, i);
usize size = type_size(c, g->tid);
usize words = (size + 7) / 8;
if (words == 0)
words = 1;
put(c, "static ");
if (g->readonly)
put(c, "const ");
put(c, "u64 gg");
put_u_raw(c, i);
put(c, "[");
put_u_raw(c, words);
put(c, "] = {");
for (usize w = 0; w < words; ++w) {
if (w > 0)
put(c, ", ");
uint64_t word = 0;
if (g->init.kind == SPL_IR_VALUE_CONST) {
spl_ir_type_node_t *it = spl_ir_type_node(c->type, g->init.tid);
if (it && it->kind == SPL_IR_TYPE_ARRAY) {
spl_ir_const_t *k =
spl_ir_const((spl_ir_t *)c->ir, g->init.const_id);
if (k) {
for (usize b = 0; b < 8; ++b) {
usize idx = w * 8 + b;
if (idx < k->bytes.len)
word |= (uint64_t)k->bytes.data[idx] << (b * 8);
}
}
} else if (w == 0) {
memcpy(&word, &g->init.int_bits, sizeof word);
}
}
put_u_raw(c, (usize)word);
put(c, "ull");
}
put(c, "};");
if (g->name) {
put(c, " /* ");
put(c, g->name);
put(c, " */");
}
put(c, "\n");
}
}
static void run(ir2c_t *c) {
put(c, "// AUTO-GENERATED\n");
put(c, "#include \"spl_rt.h\"\n");
emit_globals(c);
usize nf = vec_size(c->ir->funcs);
for (spl_ir_func_ref_t i = 1; i < nf; ++i) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, i);
if (f && !fn_is_extern(c, f))
if (f)
emit_proto(c, i);
}
for (spl_ir_func_ref_t i = 1; i < nf; ++i) {
@@ -1287,13 +1335,20 @@ static void run(ir2c_t *c) {
if (m != 0) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, m);
usize nargs = 0;
spl_type_node_t *te = spl_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_TYPE_FN)
spl_ir_type_node_t *te = spl_ir_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_IR_TYPE_FN)
nargs = vec_size(te->fn_type.params);
if (nargs == 0) {
put(c, "int main(void) { f");
put(c, "int main(void) { ");
if (!tid_is_unit(c, fn_ret_type(c, f->fn_tid))) {
put(c, "return (int)f");
put_u(c, m);
put(c, "(); }\n");
} else {
put(c, "f");
put_u(c, m);
put(c, "(); return 0; }\n");
}
} else {
put(c, "int main(int argc, char** argv) { ");
if (!tid_is_unit(c, fn_ret_type(c, f->fn_tid))) {
@@ -1309,17 +1364,18 @@ static void run(ir2c_t *c) {
}
}
bool spl_ir2c_run(const spl_ir_t *ir, const spl_type_t *type, spl_layout_t *layout,
const spl_attr_t *attr, spl_ir2c_buf_t *out) {
bool spl_ir2c_run(const spl_ir_t *ir, spl_layout_t *layout, const spl_attr_t *attr,
spl_ir2c_buf_t *out) {
ir2c_t c = {
.ir = ir,
.type = type,
.type = ir->types,
.layout = layout,
.attr = attr,
.out = out,
.gdata_n = 1,
.failed = false,
};
vec_init(c.cconsts);
run(&c);
vec_free(c.cconsts);
return !c.failed;
}
@@ -4,18 +4,18 @@
static usize align_up(usize x, usize a);
/* size/align/offset 统一取自 layout(spl_layout 是唯一准确来源)。 */
static const spl_layout_info_t *ir_layout(spl_ir2vm_t *ctx, spl_type_id_t tid) {
static const spl_layout_info_t *ir_layout(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
return spl_layout_info_of(ctx->layout, tid);
}
static usize ir_type_size(spl_ir2vm_t *ctx, spl_type_id_t tid) {
static usize ir_type_size(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = ir_layout(ctx, tid);
if (!info)
return 0;
return (info->size_bits + 7) / 8;
}
static usize ir_type_align(spl_ir2vm_t *ctx, spl_type_id_t tid) {
static usize ir_type_align(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = ir_layout(ctx, tid);
if (!info)
return 1;
@@ -23,34 +23,34 @@ static usize ir_type_align(spl_ir2vm_t *ctx, spl_type_id_t tid) {
return a ? a : 1;
}
static bool ir_is_aggregate(spl_ir2vm_t *ctx, spl_type_id_t tid) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static bool ir_is_aggregate(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return false;
return tn->kind == SPL_TYPE_ARRAY || tn->kind == SPL_TYPE_STRUCT ||
tn->kind == SPL_TYPE_UNION || tn->kind == SPL_TYPE_ENUM || tn->kind == SPL_TYPE_SHAPE;
return tn->kind == SPL_IR_TYPE_ARRAY || tn->kind == SPL_IR_TYPE_STRUCT ||
tn->kind == SPL_IR_TYPE_UNION || tn->kind == SPL_IR_TYPE_ENUM;
}
/* 从 fn_tid 取返回类型;非 fn 类型返回 0。 */
static spl_type_id_t fn_ret_type(spl_ir2vm_t *ctx, spl_type_id_t fn_tid) {
spl_type_node_t *ftn = spl_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_TYPE_FN)
static spl_ir_type_id_t fn_ret_type(spl_ir2vm_t *ctx, spl_ir_type_id_t fn_tid) {
spl_ir_type_node_t *ftn = spl_ir_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_IR_TYPE_FN)
return 0;
return ftn->fn_type.ret;
}
static usize fn_nargs(spl_ir2vm_t *ctx, spl_type_id_t fn_tid) {
spl_type_node_t *ftn = spl_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_TYPE_FN)
static usize fn_nargs(spl_ir2vm_t *ctx, spl_ir_type_id_t fn_tid) {
spl_ir_type_node_t *ftn = spl_ir_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_IR_TYPE_FN)
return 0;
return vec_size(ftn->fn_type.params);
}
static spl_type_id_t ir_agg_field_tid(spl_ir2vm_t *ctx, spl_type_id_t tid, usize idx) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static spl_ir_type_id_t ir_agg_field_tid(spl_ir2vm_t *ctx, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return 0;
if (tn->kind == SPL_TYPE_ENUM) {
if (tn->kind == SPL_IR_TYPE_ENUM) {
if (idx == SPL_ENUM_TAG_FIELD_IDX)
return tn->agg_type.tag_type;
usize vidx = idx - 1;
@@ -58,20 +58,20 @@ static spl_type_id_t ir_agg_field_tid(spl_ir2vm_t *ctx, spl_type_id_t tid, usize
return vec_at(tn->agg_type.variants, vidx).type_id;
return 0;
}
if (tn->kind == SPL_TYPE_STRUCT || tn->kind == SPL_TYPE_UNION) {
if (tn->kind == SPL_IR_TYPE_STRUCT || tn->kind == SPL_IR_TYPE_UNION) {
if (idx < vec_size(tn->agg_type.variants))
return vec_at(tn->agg_type.variants, idx).type_id;
} else if (tn->kind == SPL_TYPE_ARRAY) {
} else if (tn->kind == SPL_IR_TYPE_ARRAY) {
return tn->array_type.element;
}
return 0;
}
static usize ir_agg_field_off(spl_ir2vm_t *ctx, spl_type_id_t tid, usize idx) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static usize ir_agg_field_off(spl_ir2vm_t *ctx, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return 0;
if (tn->kind == SPL_TYPE_ARRAY)
if (tn->kind == SPL_IR_TYPE_ARRAY)
return idx * ir_type_size(ctx, tn->array_type.element);
const spl_layout_info_t *info = ir_layout(ctx, tid);
@@ -96,16 +96,16 @@ static int get_or_add_native(spl_ir2vm_t *ctx, const char *name) {
return (int)(vec_size(ctx->prog.natives) - 1);
}
static uint8_t vm_kind_of(spl_ir2vm_t *ctx, spl_type_id_t tid) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static uint8_t vm_kind_of(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return SPL_VOID;
switch (tn->kind) {
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_UNIT:
return SPL_VOID;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
return SPL_BOOL;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (tn->int_type.bits == 0)
return SPL_I32;
switch (tn->int_type.bits) {
@@ -118,20 +118,20 @@ static uint8_t vm_kind_of(spl_ir2vm_t *ctx, spl_type_id_t tid) {
default:
return tn->int_type.is_signed ? SPL_I64 : SPL_U64;
}
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
return tn->float_type.bits == 32 ? SPL_F32 : SPL_F64;
default:
return SPL_PTR;
}
}
/* 计算 IR 节点的"值类型",两处用途:
/* 计算 IR 节点的值类型,两处用途:
* 1) frame_build 判断该节点是否占用结果槽(只看是否非 0);
* 2) CALL 推导实参的 LOAD/STORE kind。
* mem.offset/mem.field 的 .tid 存的是 pointee/aggregate,须转成指针类型。
* cmp/type.* 这里刻意返回操作数/被测量类型的 tid 而非 bool/usize:
* cmp/type.* 这里刻意返回操作数被测量类型的 tid 而非 bool/usize;
* CALL 实参 kind 依赖此点,改动会改变生成字节码,diff 测试据此守门。 */
static spl_type_id_t ir_result_tid(spl_ir2vm_t *ctx, const spl_ir_node_t *n) {
static spl_ir_type_id_t ir_result_tid(spl_ir2vm_t *ctx, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
@@ -167,20 +167,16 @@ static spl_type_id_t ir_result_tid(spl_ir2vm_t *ctx, const spl_ir_node_t *n) {
case SPL_IR_CASE_FLOAT2INT:
return n->cast.to_tid;
case SPL_IR_MEM_ALLOCA:
return spl_type_builder_ptr((spl_type_t *)ctx->type, n->mem_alloc.tid);
case SPL_IR_MEM_GLOBAL_ALLOC:
return n->mem_global_alloc.tid;
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)ctx->type, n->mem_alloc.tid);
case SPL_IR_MEM_LOAD:
return n->mem_load.tid;
case SPL_IR_MEM_OFFSET:
return spl_type_builder_ptr((spl_type_t *)ctx->type, n->mem_offset.tid);
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)ctx->type, n->mem_offset.tid);
case SPL_IR_MEM_FIELD_PTR: {
spl_type_id_t field =
spl_ir_type_id_t field =
ir_agg_field_tid(ctx, n->mem_field_ptr.tid, n->mem_field_ptr.field_idx);
return spl_type_builder_ptr((spl_type_t *)ctx->type, field);
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)ctx->type, field);
}
case SPL_IR_TYPE_CONST:
return n->type_const.tid;
case SPL_IR_TYPE_BITSIZEOF:
return n->bitsizeof.tid;
case SPL_IR_TYPE_SIZEOF:
@@ -226,16 +222,28 @@ typedef struct {
/* panic 数据区:fmt slice + msg slice,各 2 words(ptr + len)。 */
enum { IR2VM_PANIC_WORDS = 4 };
static spl_ir_type_id_t value_tid(spl_ir2vm_t *ctx, const spl_ir_func_t *f, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST)
return v.tid;
if (v.inst == 0 || v.inst >= vec_size(f->nodes))
return 0;
return ir_result_tid(ctx, &vec_at(f->nodes, v.inst));
}
static usize value_int(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? (usize)v.int_bits : 0;
}
static spl_ir_func_ref_t value_fn(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? v.fn : 0;
}
/* 结果槽存标量;聚合/大对象额外分配一块数据区(data_off)。 */
static usize node_data_size(spl_ir2vm_t *ctx, const spl_ir_func_t *f, const spl_ir_node_t *node) {
(void)f;
switch (node->kind) {
case SPL_IR_MEM_ALLOCA: {
usize count = 1;
if (node->mem_alloc.count < vec_size(f->nodes)) {
const spl_ir_node_t *cn = &vec_at(f->nodes, node->mem_alloc.count);
if (cn->kind == SPL_IR_TYPE_CONST)
count = (usize)cn->type_const.int_lit;
}
usize count = value_int(node->mem_alloc.count);
if (count == 0)
count = 1;
usize sz = ir_type_size(ctx, node->mem_alloc.tid);
@@ -280,7 +288,7 @@ static void frame_build(frame_layout_t *fl, spl_ir2vm_t *ctx, spl_ir_func_ref_t
for (usize i = 0; i < n; ++i)
vec_push(fl->slots, (slot_t){0});
/* 聚合返回时 fp+0 是 caller 传入的 sret 指针,占用一个隐藏参数槽 */
/* 聚合返回时 fp+0 是 caller 传入的 sret 指针,占用一个隐藏参数槽。 */
usize nargs = fn_nargs(ctx, f->fn_tid);
usize hidden_sret = ir_is_aggregate(ctx, fn_ret_type(ctx, f->fn_tid)) ? 1 : 0;
fl->args_bytes = (nargs + hidden_sret) * sizeof(spl_vm_val_t);
@@ -343,8 +351,14 @@ static void CG_OP(cgen_t *cg, uint8_t op, uint8_t k) { emit(cg, op, k, 0); }
static void CG_SWAP(cgen_t *cg) { emit(cg, SPL_SWAP, SPL_VOID, 0); }
static void CG_GADDR(cgen_t *cg, spl_vm_val_t idx) { emit(cg, SPL_GADDR, SPL_VOID, idx); }
static void cg_load_slot(cgen_t *cg, usize ref, uint8_t k) {
CG_LADDR(cg, vec_at(cg->frame.slots, ref).result_off);
static void cg_push_const(cgen_t *cg, spl_ir_value_t v, uint8_t k);
static void cg_load_slot(cgen_t *cg, spl_ir_value_t v, uint8_t k) {
if (v.kind != SPL_IR_VALUE_INST) {
cg_push_const(cg, v, k);
return;
}
CG_LADDR(cg, vec_at(cg->frame.slots, v.inst).result_off);
CG_LOAD(cg, k);
}
@@ -364,6 +378,7 @@ typedef struct {
bool indirect;
usize off;
usize base;
int gdata; /* >0:全局数据区索引,直接 GADDR */
} data_loc_t;
static data_loc_t direct_data(usize off) {
@@ -372,16 +387,19 @@ static data_loc_t direct_data(usize off) {
static data_loc_t direct_data_base(usize off, usize base) {
return (data_loc_t){.indirect = false, .off = off, .base = base};
}
static data_loc_t ptr_slot(usize slot_off) {
return (data_loc_t){.indirect = true, .off = slot_off, .base = 0};
}
static data_loc_t ptr_slot_base(usize slot_off, usize base) {
return (data_loc_t){.indirect = true, .off = slot_off, .base = base};
}
static void cg_push_addr(cgen_t *cg, data_loc_t loc, usize extra) {
usize delta = loc.base + extra;
if (loc.indirect) {
if (loc.gdata > 0) {
emit(cg, SPL_GADDR, SPL_VOID, (spl_vm_val_t)loc.gdata);
if (delta) {
CG_PUSH(cg, SPL_U64, delta);
CG_OP(cg, SPL_ADD, SPL_PTR);
}
} else if (loc.indirect) {
CG_LADDR(cg, loc.off);
CG_LOAD(cg, SPL_PTR);
if (delta) {
@@ -393,7 +411,19 @@ static void cg_push_addr(cgen_t *cg, data_loc_t loc, usize extra) {
}
}
static void cg_copy_agg(cgen_t *cg, data_loc_t src, data_loc_t dst, spl_type_id_t tid) {
/* 聚合值的存储位置:指令槽指针,或全局数据区地址。 */
static data_loc_t value_ptr_loc(cgen_t *cg, spl_ir_value_t v, usize base) {
if (v.kind == SPL_IR_VALUE_GLOBAL) {
usize gid = v.global_id;
int idx = 0;
if (gid > 0 && gid < vec_size(cg->ctx->global_data_idx))
idx = (int)vec_at(cg->ctx->global_data_idx, gid);
return (data_loc_t){.gdata = idx, .base = base};
}
return ptr_slot_base(vec_at(cg->frame.slots, v.inst).result_off, base);
}
static void cg_copy_agg(cgen_t *cg, data_loc_t src, data_loc_t dst, spl_ir_type_id_t tid) {
usize sz = ir_type_size(cg->ctx, tid);
usize done = 0;
while (sz - done >= 8) {
@@ -442,60 +472,63 @@ static void cg_cmp(cgen_t *cg, usize ref, const spl_ir_node_t *n, uint8_t op) {
cg_store_slot(cg, ref, SPL_BOOL);
}
static void cg_const(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
static void cg_push_const(cgen_t *cg, spl_ir_value_t v, uint8_t k) {
spl_ir2vm_t *ctx = cg->ctx;
spl_type_id_t tid = n->type_const.tid;
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
if (v.kind == SPL_IR_VALUE_GLOBAL) {
int gi = (v.global_id > 0 && v.global_id < vec_size(ctx->global_data_idx))
? (int)vec_at(ctx->global_data_idx, v.global_id)
: 0;
if (gi > 0)
emit(cg, SPL_GADDR, SPL_VOID, (spl_vm_val_t)gi);
else
CG_PUSH(cg, SPL_PTR, 0);
return;
}
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, v.tid);
if (!tn)
return;
if (tn->kind == SPL_TYPE_FN) {
if (tn->kind == SPL_IR_TYPE_FN) {
isize nat_idx = -1;
if (n->type_const.fn > 0)
map_get(ctx->extern_native, n->type_const.fn, &nat_idx);
if (v.fn > 0)
map_get(ctx->extern_native, v.fn, &nat_idx);
if (nat_idx >= 0) {
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)nat_idx);
} else {
usize idx = ip_of(cg);
CG_PUSH(cg, SPL_PTR, 0);
cg_add_fix(cg, idx, FIX_FNADDR, 0, n->type_const.fn);
cg_add_fix(cg, idx, FIX_FNADDR, 0, v.fn);
}
cg_store_slot(cg, ref, SPL_PTR);
return;
}
uint8_t k = vm_kind_of(ctx, tid);
spl_vm_val_t imm = 0;
switch (tn->kind) {
case SPL_TYPE_BOOL:
imm = n->type_const.bool_lit ? 1 : 0;
case SPL_IR_TYPE_BOOL:
imm = v.int_bits ? 1 : 0;
break;
case SPL_TYPE_INT:
if (tn->int_type.bits == 8)
imm = (spl_vm_val_t)(unsigned char)n->type_const.ch_lit;
else
imm = (spl_vm_val_t)n->type_const.int_lit;
case SPL_IR_TYPE_INT:
imm = (spl_vm_val_t)v.int_bits;
break;
case SPL_TYPE_FLOAT:
memcpy(&imm, &n->type_const.float_lit, sizeof(double));
case SPL_IR_TYPE_FLOAT:
memcpy(&imm, &v.float_bits, sizeof(double));
break;
case SPL_TYPE_PTR:
imm = (spl_vm_val_t)(usize)n->type_const.ptr_lit;
case SPL_IR_TYPE_PTR:
imm = 0;
break;
case SPL_TYPE_UNIT:
return;
default:
break;
}
CG_PUSH(cg, k, imm);
cg_store_slot(cg, ref, k);
}
static void cg_cast(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
spl_ir2vm_t *ctx = cg->ctx;
spl_type_node_t *ft = spl_type_node(ctx->type, n->cast.from_tid);
spl_type_node_t *tt = spl_type_node(ctx->type, n->cast.to_tid);
spl_ir_type_node_t *ft = spl_ir_type_node(ctx->type, n->cast.from_tid);
spl_ir_type_node_t *tt = spl_ir_type_node(ctx->type, n->cast.to_tid);
if (!ft || !tt)
return;
@@ -504,14 +537,14 @@ static void cg_cast(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_load_slot(cg, n->cast.val, fk);
if (ft->kind == SPL_TYPE_INT && tt->kind == SPL_TYPE_INT) {
if (ft->kind == SPL_IR_TYPE_INT && tt->kind == SPL_IR_TYPE_INT) {
usize fb = ft->int_type.bits;
usize tb = tt->int_type.bits;
if (fb > tb)
emit(cg, SPL_TRUNC, SPL_VOID, tb);
else if (fb < tb)
emit(cg, ft->int_type.is_signed ? SPL_SEXT : SPL_ZEXT, SPL_VOID, fb);
} else if (ft->kind == SPL_TYPE_BOOL && tt->kind == SPL_TYPE_INT) {
} else if (ft->kind == SPL_IR_TYPE_BOOL && tt->kind == SPL_IR_TYPE_INT) {
emit(cg, SPL_ZEXT, SPL_VOID, 1);
}
@@ -528,26 +561,11 @@ static void cg_mem(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
}
case SPL_IR_MEM_GLOBAL_ALLOC: {
const spl_ir_node_t *cn = &vec_at(cg->irf->nodes, n->mem_global_alloc.const_node);
int idx = 0;
if (cn->kind == SPL_IR_TYPE_CONST && cn->type_const.ptr_lit) {
usize size = ir_type_size(ctx, cn->type_const.tid);
idx = spl_prog_add_data(&ctx->prog, cn->type_const.ptr_lit, size);
}
if (idx > 0)
emit(cg, SPL_GADDR, SPL_VOID, (spl_vm_val_t)idx);
else
CG_PUSH(cg, SPL_PTR, 0);
cg_store_slot(cg, ref, SPL_PTR);
break;
}
case SPL_IR_MEM_LOAD: {
spl_type_id_t tid = n->mem_load.tid;
spl_ir_type_id_t tid = n->mem_load.tid;
if (ir_is_aggregate(ctx, tid)) {
usize data = vec_at(cg->frame.slots, ref).data_off;
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->mem_load.ptr).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, n->mem_load.ptr, 0),
direct_data(data), tid);
CG_LADDR(cg, data);
cg_store_slot(cg, ref, SPL_PTR);
@@ -561,10 +579,10 @@ static void cg_mem(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_MEM_STORE: {
spl_type_id_t tid = n->mem_store.tid;
spl_ir_type_id_t tid = n->mem_store.tid;
if (ir_is_aggregate(ctx, tid)) {
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->mem_store.val).result_off),
ptr_slot(vec_at(cg->frame.slots, n->mem_store.ptr).result_off), tid);
cg_copy_agg(cg, value_ptr_loc(cg, n->mem_store.val, 0),
value_ptr_loc(cg, n->mem_store.ptr, 0), tid);
} else {
uint8_t k = vm_kind_of(ctx, tid);
cg_load_slot(cg, n->mem_store.ptr, SPL_PTR);
@@ -588,7 +606,7 @@ static void cg_mem(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_MEM_FIELD_PTR: {
spl_type_id_t agg_tid = n->mem_field_ptr.tid;
spl_ir_type_id_t agg_tid = n->mem_field_ptr.tid;
usize off = ir_agg_field_off(ctx, agg_tid, n->mem_field_ptr.field_idx);
cg_load_slot(cg, n->mem_field_ptr.agg, SPL_PTR);
if (off) {
@@ -610,17 +628,19 @@ static void cg_agg(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
case SPL_IR_AGG_CONSTRUCT: {
usize base = vec_at(cg->frame.slots, ref).data_off;
spl_type_id_t agg_t = n->agg_construct.tid;
spl_ir_type_id_t agg_t = n->agg_construct.tid;
for (usize i = 0; i < vec_size(n->agg_construct.fields); ++i) {
spl_ir_node_ref_t fref = vec_at(n->agg_construct.fields, i);
spl_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, i);
spl_ir_value_t fref = vec_at(n->agg_construct.fields, i);
if (spl_ir_value_is_none(fref))
continue;
spl_ir_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, i);
if (!ftid)
continue;
usize foff = ir_agg_field_off(ctx, agg_t, i);
if (ir_is_aggregate(ctx, ftid)) {
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, fref).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, fref, 0),
direct_data_base(base, foff), ftid);
} else {
uint8_t fk = vm_kind_of(ctx, ftid);
@@ -634,14 +654,14 @@ static void cg_agg(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_AGG_EXTRACT: {
spl_type_id_t agg_t = n->agg_extract.tid;
spl_type_id_t ftid = n->agg_extract.field_tid;
spl_ir_type_id_t agg_t = n->agg_extract.tid;
spl_ir_type_id_t ftid = n->agg_extract.field_tid;
usize foff = ir_agg_field_off(ctx, agg_t, n->agg_extract.field_idx);
if (ir_is_aggregate(ctx, ftid)) {
usize data = vec_at(cg->frame.slots, ref).data_off;
cg_copy_agg(cg,
ptr_slot_base(vec_at(cg->frame.slots, n->agg_extract.val).result_off, foff),
value_ptr_loc(cg, n->agg_extract.val, foff),
direct_data(data), ftid);
CG_LADDR(cg, data);
cg_store_slot(cg, ref, SPL_PTR);
@@ -660,16 +680,16 @@ static void cg_agg(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
case SPL_IR_AGG_INSERT: {
usize base = vec_at(cg->frame.slots, ref).data_off;
spl_type_id_t agg_t = n->agg_insert.tid;
spl_ir_type_id_t agg_t = n->agg_insert.tid;
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->agg_insert.agg).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, n->agg_insert.agg, 0),
direct_data(base), agg_t);
usize foff = ir_agg_field_off(ctx, agg_t, n->agg_insert.field_idx);
spl_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, n->agg_insert.field_idx);
spl_ir_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, n->agg_insert.field_idx);
if (ftid) {
if (ir_is_aggregate(ctx, ftid)) {
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->agg_insert.field).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, n->agg_insert.field, 0),
direct_data_base(base, foff), ftid);
} else {
uint8_t fk = vm_kind_of(ctx, ftid);
@@ -704,19 +724,14 @@ static void cg_typeop(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
v = ir_type_align(ctx, n->ir_alignof.tid);
break;
case SPL_IR_TYPE_OFFSETOF: {
usize idx = 0;
if (n->ir_offsetof.field_idx < vec_size(cg->irf->nodes)) {
const spl_ir_node_t *idx_node = &vec_at(cg->irf->nodes, n->ir_offsetof.field_idx);
if (idx_node->kind == SPL_IR_TYPE_CONST)
idx = (usize)idx_node->type_const.int_lit;
}
usize idx = value_int(n->ir_offsetof.field_idx);
v = ir_agg_field_off(ctx, n->ir_offsetof.tid, idx);
break;
}
case SPL_IR_TYPE_FIELD_COUNT: {
spl_type_node_t *tn = spl_type_node(ctx->type, n->field_count.tid);
if (tn && (tn->kind == SPL_TYPE_STRUCT || tn->kind == SPL_TYPE_UNION ||
tn->kind == SPL_TYPE_ENUM || tn->kind == SPL_TYPE_SHAPE))
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, n->field_count.tid);
if (tn && (tn->kind == SPL_IR_TYPE_STRUCT || tn->kind == SPL_IR_TYPE_UNION ||
tn->kind == SPL_IR_TYPE_ENUM))
v = vec_size(tn->agg_type.variants);
break;
}
@@ -733,13 +748,8 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
case SPL_IR_CONTROL_PARAM: {
uint8_t k = vm_kind_of(ctx, n->control_param.tid);
usize idx = 0;
if (n->control_param.idx < vec_size(cg->irf->nodes)) {
const spl_ir_node_t *idx_node = &vec_at(cg->irf->nodes, n->control_param.idx);
if (idx_node->kind == SPL_IR_TYPE_CONST)
idx = (usize)idx_node->type_const.int_lit;
}
/* 聚合返回时 fp+0 是 sret 指针,实参从 fp+8 起 */
usize idx = value_int(n->control_param.idx);
/* 聚合返回时 fp+0 是 sret 指针,实参从 fp+8 起。 */
usize shift = ir_is_aggregate(ctx, fn_ret_type(ctx, cg->irf->fn_tid)) ? 1 : 0;
CG_LADDR(cg, (idx + shift) * sizeof(spl_vm_val_t));
CG_LOAD(cg, k);
@@ -748,10 +758,10 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_CONTROL_RET: {
spl_type_id_t ret_tid = n->control_ret.tid;
spl_ir_type_id_t ret_tid = n->control_ret.tid;
if (ir_is_aggregate(ctx, ret_tid)) {
/* sret:把返回值写入 *(fp+0),然后以 void 返回 */
if (n->control_ret.val) {
/* sret:把返回值写入 *(fp+0),然后以 void 返回。 */
if (!spl_ir_value_is_none(n->control_ret.val)) {
usize sz = ir_type_size(ctx, ret_tid);
CG_LADDR(cg, 0);
CG_LOAD(cg, SPL_PTR);
@@ -763,7 +773,7 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
}
uint8_t k = vm_kind_of(ctx, ret_tid);
if (k != SPL_VOID && n->control_ret.val)
if (k != SPL_VOID && !spl_ir_value_is_none(n->control_ret.val))
cg_load_slot(cg, n->control_ret.val, k);
emit(cg, SPL_RET, k, 0);
break;
@@ -788,13 +798,7 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_CONTROL_CALL: {
spl_ir_func_ref_t callee_ref = 0;
spl_ir_node_ref_t fref = n->control_call.func;
if (fref < vec_size(cg->irf->nodes)) {
const spl_ir_node_t *fn_node = &vec_at(cg->irf->nodes, fref);
if (fn_node->kind == SPL_IR_TYPE_CONST)
callee_ref = fn_node->type_const.fn;
}
spl_ir_func_ref_t callee_ref = value_fn(n->control_call.func);
isize nat_idx = -1;
if (callee_ref > 0)
@@ -804,21 +808,34 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
if (nat_idx >= 0) {
for (usize i = 0; i < nargs; ++i) {
spl_ir_node_ref_t pref = vec_at(n->control_call.params, i);
const spl_ir_node_t *pn = &vec_at(cg->irf->nodes, pref);
uint8_t pk = vm_kind_of(ctx, ir_result_tid(ctx, pn));
spl_ir_value_t pref = vec_at(n->control_call.params, i);
uint8_t pk = vm_kind_of(ctx, value_tid(ctx, cg->irf, pref));
cg_load_slot(cg, pref, pk);
}
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)nat_idx);
emit(cg, SPL_NCALL, SPL_VOID, (spl_vm_val_t)nargs);
if (ir_is_aggregate(ctx, n->control_call.tid)) {
usize sz = ir_type_size(ctx, n->control_call.tid);
usize result_off = vec_at(cg->frame.slots, ref).result_off;
usize data_off = vec_at(cg->frame.slots, ref).data_off;
cg_store_slot(cg, ref, SPL_PTR);
CG_LADDR(cg, data_off);
CG_LADDR(cg, result_off);
CG_LOAD(cg, SPL_PTR);
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)sz);
emit(cg, SPL_MEMCPY, SPL_VOID, 0);
CG_LADDR(cg, data_off);
cg_store_slot(cg, ref, SPL_PTR);
} else {
uint8_t rk = vm_kind_of(ctx, n->control_call.tid);
if (rk == SPL_VOID)
emit(cg, SPL_DROP, SPL_VOID, 0); /* NCALL always push result */
else
cg_store_slot(cg, ref, rk);
}
} else {
spl_type_id_t ret_t = n->control_call.tid;
spl_ir_type_id_t ret_t = n->control_call.tid;
bool ret_is_sret = ir_is_aggregate(ctx, ret_t);
usize sret_off = 0;
@@ -831,17 +848,16 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
CG_LADDR(cg, sret_off);
}
for (usize i = 0; i < nargs; ++i) {
spl_ir_node_ref_t pref = vec_at(n->control_call.params, i);
const spl_ir_node_t *pn = &vec_at(cg->irf->nodes, pref);
uint8_t pk = vm_kind_of(ctx, ir_result_tid(ctx, pn));
spl_ir_value_t pref = vec_at(n->control_call.params, i);
uint8_t pk = vm_kind_of(ctx, value_tid(ctx, cg->irf, pref));
cg_load_slot(cg, pref, pk);
}
cg_load_slot(cg, fref, SPL_PTR);
cg_load_slot(cg, n->control_call.func, SPL_PTR);
spl_vm_val_t actual_nargs = nargs + (ret_is_sret ? 1 : 0);
emit(cg, SPL_CALL, SPL_VOID, actual_nargs);
if (ret_is_sret) {
/* result slot 保存 sret 指针 */
/* result slot 保存 sret 指针。 */
CG_LADDR(cg, sret_off);
cg_store_slot(cg, ref, SPL_PTR);
} else {
@@ -865,10 +881,6 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_TYPE_CONST:
cg_const(cg, ref, n);
break;
case SPL_IR_ARITH_ADD:
cg_binop(cg, ref, n, SPL_ADD);
break;
@@ -879,14 +891,14 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_binop(cg, ref, n, SPL_MUL);
break;
case SPL_IR_ARITH_DIV: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_binop(cg, ref, n, sgn ? SPL_DIV_S : SPL_DIV_U);
break;
}
case SPL_IR_ARITH_REM: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_binop(cg, ref, n, sgn ? SPL_REM_S : SPL_REM_U);
break;
}
@@ -903,8 +915,8 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_binop(cg, ref, n, SPL_SHL);
break;
case SPL_IR_ARITH_SHR: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_binop(cg, ref, n, sgn ? SPL_SHR_S : SPL_SHR_U);
break;
}
@@ -912,8 +924,8 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_unop(cg, ref, n, SPL_NEG);
break;
case SPL_IR_ARITH_NOT: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
if (tn && tn->kind == SPL_TYPE_BOOL) {
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
if (tn && tn->kind == SPL_IR_TYPE_BOOL) {
cg_load_slot(cg, n->arith.left, SPL_BOOL);
CG_PUSH(cg, SPL_BOOL, 0);
CG_OP(cg, SPL_EQ, SPL_BOOL);
@@ -931,26 +943,26 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_cmp(cg, ref, n, SPL_NE);
break;
case SPL_IR_CMP_LT: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SLT : SPL_ULT);
break;
}
case SPL_IR_CMP_LE: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SLE : SPL_ULE);
break;
}
case SPL_IR_CMP_GT: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SGT : SPL_UGT);
break;
}
case SPL_IR_CMP_GE: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SGE : SPL_UGE);
break;
}
@@ -970,7 +982,6 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
case SPL_IR_MEM_ALLOCA:
case SPL_IR_MEM_GLOBAL_ALLOC:
case SPL_IR_MEM_LOAD:
case SPL_IR_MEM_STORE:
case SPL_IR_MEM_OFFSET:
@@ -1011,19 +1022,19 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
if (msg_idx <= 0 || fmt_idx <= 0)
break;
/* fmt slice = {ptr, len=2} 写到 data+0 */
/* fmt slice = {ptr, len=2} 写到 data+0。 */
CG_GADDR(cg, (spl_vm_val_t)fmt_idx);
cg_store_at(cg, data + 0, SPL_PTR);
CG_PUSH(cg, SPL_U64, 2);
cg_store_at(cg, data + 8, SPL_U64);
/* msg slice = {ptr, len} 写到 data+16 */
/* msg slice = {ptr, len} 写到 data+16。 */
CG_GADDR(cg, (spl_vm_val_t)msg_idx);
cg_store_at(cg, data + 16, SPL_PTR);
CG_PUSH(cg, SPL_U64, n->dbg_panic.len);
cg_store_at(cg, data + 24, SPL_U64);
/* push fmt slice 指针,push msg slice 指针 */
/* push fmt slice 指针,push msg slice 指针。 */
CG_LADDR(cg, data + 0);
CG_LADDR(cg, data + 16);
@@ -1040,7 +1051,7 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
default:
/* 前端不发射 select/mem.copy/mem.set/abs;出现即后端缺口,直接报错。 */
/* 前端不发射 select/mem.copy/mem.set/abs;出现即后端缺口,直接报错。 */
Panic("ir2vm: unsupported IR node kind %d", (int)n->kind);
break;
}
@@ -1110,7 +1121,8 @@ static void register_externs(spl_ir2vm_t *ctx) {
if (!irf)
continue;
spl_attr_node_t *ext = spl_ir_fn_extern_attr(ctx->attr, irf);
if (ext) {
if (ext || irf->extern_fn) {
if (ext)
ext->consumed_mask |= (1u << SPL_ATTR_STAGE_IR);
int nat_idx = get_or_add_native(ctx, irf->name);
map_put(ctx->extern_native, i, (isize)nat_idx);
@@ -1121,14 +1133,49 @@ static void register_externs(spl_ir2vm_t *ctx) {
static usize spl_map_hash(usize k) { return MAP_HASH_INT(k); }
static int spl_map_cmp(usize a, usize b) { return MAP_CMP_INT(a, b); }
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type,
spl_layout_t *layout, const spl_attr_t *attr) {
Assert(ir != NULL && type != NULL && attr != NULL);
static void prepare_globals(spl_ir2vm_t *ctx) {
vec_push(ctx->global_data_idx, 0);
for (usize i = 1; i < vec_size(ctx->ir->globals); ++i) {
const spl_ir_global_t *g = &vec_at(ctx->ir->globals, i);
usize size = ir_type_size(ctx, g->tid);
if (size == 0)
size = 1;
unsigned char *buf = calloc(1, size);
if (!buf) {
vec_push(ctx->global_data_idx, 0);
continue;
}
if (g->init.kind == SPL_IR_VALUE_CONST) {
spl_ir_type_node_t *it = spl_ir_type_node(ctx->type, g->init.tid);
if (it && it->kind == SPL_IR_TYPE_ARRAY) {
spl_ir_const_t *k = spl_ir_const((spl_ir_t *)ctx->ir, g->init.const_id);
if (k) {
usize n = size < k->bytes.len ? size : k->bytes.len;
memcpy(buf, k->bytes.data, n);
}
} else {
uint64_t bits = 0;
memcpy(&bits, &g->init.int_bits, sizeof bits);
usize n = size < sizeof(bits) ? size : sizeof(bits);
for (usize j = 0; j < n; ++j)
buf[j] = (unsigned char)(bits >> (j * 8));
}
}
int idx = spl_prog_add_data(&ctx->prog, buf, size);
vec_push(ctx->global_data_idx, idx);
free(buf);
}
}
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr) {
Assert(ir != NULL && attr != NULL);
ctx->ir = ir;
ctx->type = type;
ctx->type = ir->types;
ctx->attr = attr;
ctx->layout = layout;
map_init(ctx->extern_native, spl_map_hash, spl_map_cmp);
vec_init(ctx->global_data_idx);
spl_prog_init(&ctx->prog);
ctx->diag = NULL;
@@ -1136,6 +1183,7 @@ void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type
void spl_ir2vm_drop(spl_ir2vm_t *ctx) {
spl_prog_drop(&ctx->prog);
vec_free(ctx->global_data_idx);
map_free(ctx->extern_native);
}
@@ -1145,12 +1193,13 @@ int spl_ir2vm_run(spl_ir2vm_t *ctx) {
return 0;
register_externs(ctx);
prepare_globals(ctx);
/* 保留 insn 0 作为哨兵:确保真实函数入口地址非零,
从而 0 可唯一表示 null 函数指针(函数指针与 null 比较)。 */
/* 保留 insn 0 作为哨兵:确认真实函数入口地址非零,
从而使 0 唯一表示 null 函数指针(函数指针与 null 比较)。 */
spl_prog_add_instr(&ctx->prog, SPL_HALT, SPL_VOID, 0);
/* Pass 2:翻译非 extern 的函数 */
/* Pass 2:翻译非 extern 的函数。 */
/* Pass 2锛氱炕璇戦潪 extern 鐨勫嚱鏁?*/
usize *fid_ip = calloc(n, sizeof(usize));
fix_vec_t all_fixups;
vec_init(all_fixups);
@@ -1161,8 +1210,8 @@ int spl_ir2vm_run(spl_ir2vm_t *ctx) {
continue;
fid_ip[i] = translate_function(ctx, i, &all_fixups);
}
/* FNADDR 回填 */
/* FNADDR 回填。 */
/* FNADDR 鍥炲~ */
for (usize i = 0; i < vec_size(all_fixups); ++i) {
fix_t *fx = &vec_at(all_fixups, i);
if (fx->kind != FIX_FNADDR)
@@ -2,7 +2,7 @@
#include "vm_opt.h"
#include "../stage0/include/core_map.h"
#include "stage0/include/core_map.h"
#include <stdlib.h>
+422
View File
@@ -0,0 +1,422 @@
#include "spl_cfg_ast.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
spl_ast_t *ast;
spl_ast_node_ref_t ref;
spl_cfg_node_t node;
} ast_fn_ref_t;
typedef VEC(ast_fn_ref_t) ast_fn_ref_vec_t;
typedef struct {
spl_cfg_t *cfg;
spl_sema_t *sema;
spl_ast_t *ast;
spl_cfg_node_t fn_node;
spl_cfg_node_t *def_node;
usize def_count;
MAP(const char *, spl_cfg_node_t) hosts;
} ast_ctx_t;
static void walk_node(ast_ctx_t *c, spl_ast_node_ref_t ref);
static void walk_vec(ast_ctx_t *c, spl_ast_node_ref_vec_t vec);
static void collect_decls(ast_ctx_t *c, spl_ast_node_ref_t ref, ast_fn_ref_vec_t *out);
static void walk_opt(ast_ctx_t *c, spl_ast_node_ref_t ref) {
if (ref)
walk_node(c, ref);
}
static void walk_vec(ast_ctx_t *c, spl_ast_node_ref_vec_t vec) {
for (usize i = 0; i < vec_size(vec); ++i)
walk_opt(c, vec_at(vec, i));
}
static spl_def_node_t *ctx_def(ast_ctx_t *c, usize def_id) {
if (!def_id || def_id >= c->def_count)
return NULL;
return spl_def_node(c->sema->type, def_id);
}
static void add_fn_edge(ast_ctx_t *c, usize def_id, spl_cfg_edge_kind_t kind) {
spl_def_node_t *def = ctx_def(c, def_id);
if (!def || def->kind != SPL_DEF_FN || def_id >= c->def_count)
return;
spl_cfg_node_t target = c->def_node[def_id];
if (!target || (target == c->fn_node && kind == SPL_CFG_EDGE_FUNC_REF))
return;
spl_cfg_add_edge(c->cfg, c->fn_node, target, kind);
}
static spl_cfg_node_t add_host(ast_ctx_t *c, const char *name) {
if (!name)
return 0;
spl_cfg_node_t node = 0;
if (map_get(c->hosts, name, &node))
return node;
spl_cfg_node_info_t info = {0};
info.kind = SPL_CFG_NODE_HOST;
info.name = name;
node = spl_cfg_add_node(c->cfg, info);
map_put(c->hosts, name, node);
return node;
}
static void add_host_edge(ast_ctx_t *c, const char *name) {
spl_cfg_node_t host = add_host(c, name);
if (host)
spl_cfg_add_edge(c->cfg, c->fn_node, host, SPL_CFG_EDGE_HOST);
}
static void walk_compile_call(ast_ctx_t *c, const char *name, spl_ast_node_ref_vec_t args) {
if (name && strncmp(name, "sap.", 4) == 0) {
add_host_edge(c, name);
} else if (name) {
spl_symbol_t sym;
if (c->sema->ns && spl_ns_lookup(c->sema->ns, name, &sym) &&
sym.kind == SPL_SYMBOL_KIND_FN)
add_fn_edge(c, sym.node, SPL_CFG_EDGE_CALL);
}
walk_vec(c, args);
}
static void walk_call(ast_ctx_t *c, spl_ast_node_t *n) {
spl_ast_node_t *callee = spl_ast_node(c->ast, n->call.callee);
if (callee && callee->kind == SPL_AST_EXPR_IDENT) {
add_fn_edge(c, callee->resolved_def_id, SPL_CFG_EDGE_CALL);
} else if (callee && callee->kind == SPL_AST_EXPR_FIELD) {
add_fn_edge(c, callee->resolved_def_id, SPL_CFG_EDGE_CALL);
walk_opt(c, callee->field.obj);
} else {
walk_opt(c, n->call.callee);
}
walk_vec(c, n->call.args);
}
static void walk_node(ast_ctx_t *c, spl_ast_node_ref_t ref) {
spl_ast_node_t *n = spl_ast_node(c->ast, ref);
if (!n)
return;
switch (n->kind) {
case SPL_AST_ROOT:
walk_opt(c, n->root.members);
break;
case SPL_AST_CONTAINER_MEMBERS:
walk_vec(c, n->container_members.external_tags);
walk_opt(c, n->container_members.module);
walk_vec(c, n->container_members.declarations);
break;
case SPL_AST_EXTERNAL_TAG_ITEM:
case SPL_AST_TAG_ITEM:
walk_vec(c, n->tag_item.args);
break;
case SPL_AST_MOD_DECL:
walk_vec(c, n->mod_decl.decorator_list);
walk_vec(c, n->mod_decl.decls);
break;
case SPL_AST_IMPORT_DECL:
walk_vec(c, n->import_decl.decorator_list);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
walk_vec(c, n->top_level_block.decorator_list);
walk_vec(c, n->top_level_block.attr_list);
walk_opt(c, n->top_level_block.block);
break;
case SPL_AST_FN_DECL:
/* 嵌套函数由 collect_decls 单独处理,避免把它的引用算到外层。 */
break;
case SPL_AST_VAR_DECL:
case SPL_AST_CONST_DECL:
walk_vec(c, n->var_const_decl.decorator_list);
walk_vec(c, n->var_const_decl.attr_list);
walk_opt(c, n->var_const_decl.pattern);
walk_opt(c, n->var_const_decl.type);
walk_opt(c, n->var_const_decl.init_expr);
break;
case SPL_AST_TYPE_DECL:
walk_vec(c, n->type_decl.decorator_list);
walk_vec(c, n->type_decl.attr_list);
walk_opt(c, n->type_decl.pattern);
walk_opt(c, n->type_decl.type_expr);
break;
case SPL_AST_MEMBER_DECL:
walk_vec(c, n->member_decl.decorator_list);
walk_vec(c, n->member_decl.attr_list);
walk_opt(c, n->member_decl.type_expr);
walk_opt(c, n->member_decl.init_expr);
break;
case SPL_AST_PARAM_DECL:
walk_vec(c, n->param_decl.attr_list);
walk_opt(c, n->param_decl.type_expr);
break;
case SPL_AST_AGGREGATE_MEMBER:
walk_vec(c, n->aggregate_member.attr_list);
walk_opt(c, n->aggregate_member.type_expr);
walk_opt(c, n->aggregate_member.init_expr);
break;
case SPL_AST_STRUCT_INIT_ITEM:
walk_opt(c, n->struct_init_item.expr);
break;
case SPL_AST_MATCH_ARM:
walk_opt(c, n->match_arm.pattern);
walk_opt(c, n->match_arm.body);
break;
case SPL_AST_STATEMENT_RET:
walk_opt(c, n->statement_ret.expr);
break;
case SPL_AST_STATEMENT_BREAK:
walk_opt(c, n->statement_break.label);
walk_opt(c, n->statement_break.expr);
break;
case SPL_AST_STATEMENT_CONTINUE:
walk_opt(c, n->statement_continue.label);
break;
case SPL_AST_STATEMENT_DEFER:
walk_opt(c, n->statement_defer.body);
break;
case SPL_AST_STATEMENT_DECL:
walk_opt(c, n->statement_decl.decl);
break;
case SPL_AST_STATEMENT_EXPR:
walk_opt(c, n->statement_expr.expr);
break;
case SPL_AST_EXPR_IDENT:
add_fn_edge(c, n->resolved_def_id, SPL_CFG_EDGE_FUNC_REF);
break;
case SPL_AST_EXPR_UNARY:
walk_opt(c, n->unary.operand);
break;
case SPL_AST_EXPR_BINARY:
walk_opt(c, n->binary.left);
walk_opt(c, n->binary.right);
break;
case SPL_AST_EXPR_CALL:
walk_call(c, n);
break;
case SPL_AST_EXPR_FIELD:
add_fn_edge(c, n->resolved_def_id, SPL_CFG_EDGE_FUNC_REF);
walk_opt(c, n->field.obj);
break;
case SPL_AST_EXPR_INDEX:
walk_opt(c, n->index.obj);
walk_opt(c, n->index.index);
break;
case SPL_AST_EXPR_SLICE:
walk_opt(c, n->slice.obj);
walk_opt(c, n->slice.begin);
walk_opt(c, n->slice.end);
break;
case SPL_AST_EXPR_CAST:
walk_opt(c, n->cast.expr);
walk_opt(c, n->cast.type);
break;
case SPL_AST_EXPR_TUPLE:
walk_vec(c, n->tuple.elems);
break;
case SPL_AST_EXPR_ARRAY_LIT:
walk_opt(c, n->array_literal.elem_type);
walk_vec(c, n->array_literal.elems);
break;
case SPL_AST_EXPR_AGGREGATE_LIT:
walk_vec(c, n->aggregate_literal.fields);
break;
case SPL_AST_EXPR_COMPILE_CALL:
walk_compile_call(c, n->compile_call.name, n->compile_call.args);
break;
case SPL_AST_EXPR_BLOCK:
walk_vec(c, n->block.stmts);
walk_opt(c, n->block.tail_expr);
break;
case SPL_AST_EXPR_IF:
walk_opt(c, n->if_expr.cond);
walk_opt(c, n->if_expr.then_block);
walk_opt(c, n->if_expr.else_branch);
break;
case SPL_AST_EXPR_IFVAR:
walk_opt(c, n->ifvar_expr.var_decl);
walk_opt(c, n->ifvar_expr.then_block);
walk_opt(c, n->ifvar_expr.else_branch);
break;
case SPL_AST_EXPR_WHILE:
walk_opt(c, n->while_expr.label);
walk_opt(c, n->while_expr.cond);
walk_opt(c, n->while_expr.body);
walk_opt(c, n->while_expr.else_branch);
break;
case SPL_AST_EXPR_LOOP:
walk_opt(c, n->loop_expr.label);
walk_opt(c, n->loop_expr.body);
break;
case SPL_AST_EXPR_FOR:
walk_opt(c, n->for_expr.label);
walk_vec(c, n->for_expr.iter_exprs);
walk_opt(c, n->for_expr.pattern);
walk_opt(c, n->for_expr.body);
walk_opt(c, n->for_expr.else_branch);
break;
case SPL_AST_EXPR_MATCH:
walk_opt(c, n->match_expr.matched_expr);
walk_vec(c, n->match_expr.arms);
break;
case SPL_AST_EXPR_FN_TYPE:
walk_vec(c, n->fn_type.params);
walk_opt(c, n->fn_type.ret_type);
break;
case SPL_AST_TYPE_PATH:
walk_vec(c, n->type_path.generic_args);
break;
case SPL_AST_TYPE_POINTER:
walk_opt(c, n->type_pointer.pointee);
break;
case SPL_AST_TYPE_ARRAY:
walk_opt(c, n->type_array.elem_type);
break;
case SPL_AST_TYPE_SLICE:
walk_opt(c, n->type_slice.elem_type);
break;
case SPL_AST_TYPE_FN:
walk_vec(c, n->type_fn.params);
walk_opt(c, n->type_fn.ret_type);
break;
case SPL_AST_TYPE_PAREN:
walk_vec(c, n->type_paren.types);
break;
case SPL_AST_TYPE_AGGREGATE:
walk_vec(c, n->type_aggregate.members);
break;
case SPL_AST_TYPE_COMPILE_CALL:
walk_compile_call(c, n->type_compile_call.name, n->type_compile_call.args);
break;
case SPL_AST_PATTERN_DOT:
walk_opt(c, n->pattern_dot.sub_pattern);
break;
case SPL_AST_PATTERN_TUPLE:
walk_vec(c, n->pattern_tuple.patterns);
break;
case SPL_AST_PATTERN_LIST:
walk_vec(c, n->pattern_list.patterns);
break;
case SPL_AST_PATTERN_AGGREGATE:
walk_vec(c, n->pattern_aggregate.fields);
break;
case SPL_AST_PATTERN_FIELD:
walk_opt(c, n->pattern_field.pattern);
break;
case SPL_AST_PATTERN_REF:
walk_opt(c, n->pattern_ref.pat);
break;
default:
break;
}
}
static void collect_decls(ast_ctx_t *c, spl_ast_node_ref_t ref, ast_fn_ref_vec_t *out) {
spl_ast_node_t *n = spl_ast_node(c->ast, ref);
if (!n)
return;
switch (n->kind) {
case SPL_AST_ROOT:
collect_decls(c, n->root.members, out);
break;
case SPL_AST_CONTAINER_MEMBERS:
for (usize i = 0; i < vec_size(n->container_members.declarations); ++i)
collect_decls(c, vec_at(n->container_members.declarations, i), out);
break;
case SPL_AST_MOD_DECL:
for (usize i = 0; i < vec_size(n->mod_decl.decls); ++i)
collect_decls(c, vec_at(n->mod_decl.decls, i), out);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
collect_decls(c, n->top_level_block.block, out);
break;
case SPL_AST_EXPR_BLOCK:
for (usize i = 0; i < vec_size(n->block.stmts); ++i)
collect_decls(c, vec_at(n->block.stmts, i), out);
break;
case SPL_AST_STATEMENT_DECL:
collect_decls(c, n->statement_decl.decl, out);
break;
case SPL_AST_TYPE_DECL: {
spl_ast_node_t *te = spl_ast_node(c->ast, n->type_decl.type_expr);
if (te && te->kind == SPL_AST_TYPE_AGGREGATE)
collect_decls(c, n->type_decl.type_expr, out);
break;
}
case SPL_AST_TYPE_AGGREGATE:
for (usize i = 0; i < vec_size(n->type_aggregate.members); ++i)
collect_decls(c, vec_at(n->type_aggregate.members, i), out);
break;
case SPL_AST_FN_DECL: {
usize def_id = n->resolved_def_id;
if (!def_id || def_id >= c->def_count || c->def_node[def_id])
break;
spl_cfg_node_info_t info = {0};
info.kind = SPL_CFG_NODE_FN;
info.name = n->fn_decl.name;
info.user = def_id;
spl_cfg_node_t node = spl_cfg_add_node(c->cfg, info);
c->def_node[def_id] = node;
ast_fn_ref_t entry = {.ast = c->ast, .ref = ref, .node = node};
vec_push(*out, entry);
break;
}
default:
break;
}
}
bool spl_cfg_ast_build(spl_cfg_t *cfg, spl_sema_t *sema, const spl_ast_ptr_vec_t *asts) {
if (!cfg || !sema || !asts)
return false;
usize def_count = vec_size(sema->type->def_table);
spl_cfg_node_t *def_node = calloc(def_count ? def_count : 1, sizeof(*def_node));
if (!def_node)
return false;
ast_ctx_t c = {0};
c.cfg = cfg;
c.sema = sema;
c.def_node = def_node;
c.def_count = def_count;
map_init(c.hosts, MAP_HASH_STR, MAP_CMP_STR);
ast_fn_ref_vec_t fns;
vec_init(fns);
for (usize i = 0; i < vec_size(*asts); ++i) {
spl_ast_t *ast = vec_at(*asts, i);
if (!ast || !ast->root)
continue;
c.ast = ast;
collect_decls(&c, ast->root, &fns);
}
for (usize i = 0; i < vec_size(fns); ++i) {
ast_fn_ref_t *fn = &vec_at(fns, i);
spl_ast_node_t *n = spl_ast_node(fn->ast, fn->ref);
if (!n || n->kind != SPL_AST_FN_DECL)
continue;
c.ast = fn->ast;
c.fn_node = fn->node;
spl_ns_id_t saved_scope = sema->ns ? sema->ns->current : 0;
if (n->resolved_ns_id && sema->ns)
sema->ns->current = n->resolved_ns_id;
walk_vec(&c, n->fn_decl.decorator_list);
walk_vec(&c, n->fn_decl.attr_list);
walk_vec(&c, n->fn_decl.params);
walk_opt(&c, n->fn_decl.ret_type);
walk_opt(&c, n->fn_decl.body);
if (sema->ns)
sema->ns->current = saved_scope;
}
vec_free(fns);
map_free(c.hosts);
free(def_node);
return spl_cfg_finalize(cfg);
}
+432
View File
@@ -0,0 +1,432 @@
#include "spl_cfg.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *spl_cfg_node_kind_name(spl_cfg_node_kind_t kind) {
switch (kind) {
case SPL_CFG_NODE_FN:
return "fn";
case SPL_CFG_NODE_BLOCK:
return "block";
case SPL_CFG_NODE_HOST:
return "host";
case SPL_CFG_NODE_EXIT:
return "exit";
default:
return "?";
}
}
const char *spl_cfg_edge_kind_name(spl_cfg_edge_kind_t kind) {
switch (kind) {
case SPL_CFG_EDGE_CALL:
return "call";
case SPL_CFG_EDGE_FUNC_REF:
return "func_ref";
case SPL_CFG_EDGE_BR_TRUE:
return "br_true";
case SPL_CFG_EDGE_BR_FALSE:
return "br_false";
case SPL_CFG_EDGE_JMP:
return "jmp";
case SPL_CFG_EDGE_HOST:
return "host";
default:
return "?";
}
}
void spl_cfg_init(spl_cfg_t *cfg) {
memset(cfg, 0, sizeof(*cfg));
vec_init(cfg->nodes);
vec_init(cfg->edges);
vec_init(cfg->out_start);
vec_init(cfg->out_edges);
vec_init(cfg->in_start);
vec_init(cfg->in_edges);
vec_init(cfg->scc);
vec_init(cfg->topo);
/* 哨兵节点。 */
spl_cfg_node_info_t none = {0};
vec_push(cfg->nodes, none);
}
void spl_cfg_drop(spl_cfg_t *cfg) {
if (!cfg)
return;
vec_free(cfg->nodes);
vec_free(cfg->edges);
vec_free(cfg->out_start);
vec_free(cfg->out_edges);
vec_free(cfg->in_start);
vec_free(cfg->in_edges);
vec_free(cfg->scc);
vec_free(cfg->topo);
memset(cfg, 0, sizeof(*cfg));
}
static void cfg_invalidate(spl_cfg_t *cfg) {
cfg->finalized = false;
cfg->scc_done = false;
cfg->topo_done = false;
}
spl_cfg_node_t spl_cfg_add_node(spl_cfg_t *cfg, spl_cfg_node_info_t info) {
vec_push(cfg->nodes, info);
cfg_invalidate(cfg);
return vec_size(cfg->nodes) - 1;
}
void spl_cfg_add_edge(spl_cfg_t *cfg, spl_cfg_node_t from, spl_cfg_node_t to,
spl_cfg_edge_kind_t kind) {
if (!from || !to || from >= vec_size(cfg->nodes) || to >= vec_size(cfg->nodes))
return;
spl_cfg_edge_t edge = {.from = from, .to = to, .kind = kind};
vec_push(cfg->edges, edge);
cfg_invalidate(cfg);
}
const spl_cfg_node_info_t *spl_cfg_node_info(const spl_cfg_t *cfg, spl_cfg_node_t node) {
if (!cfg || !node || node >= vec_size(cfg->nodes))
return NULL;
return &vec_at(cfg->nodes, node);
}
usize spl_cfg_node_count(const spl_cfg_t *cfg) { return cfg ? vec_size(cfg->nodes) : 0; }
bool spl_cfg_finalize(spl_cfg_t *cfg) {
if (!cfg)
return false;
if (cfg->finalized)
return true;
usize n = vec_size(cfg->nodes);
usize ne = vec_size(cfg->edges);
cfg->out_start.size = 0;
cfg->out_edges.size = 0;
cfg->in_start.size = 0;
cfg->in_edges.size = 0;
for (usize i = 0; i <= n; ++i)
vec_push(cfg->out_start, 0);
for (usize i = 0; i <= n; ++i)
vec_push(cfg->in_start, 0);
for (usize i = 0; i < ne; ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
vec_at(cfg->out_start, e->from + 1) += 1;
vec_at(cfg->in_start, e->to + 1) += 1;
}
for (usize i = 1; i <= n; ++i) {
vec_at(cfg->out_start, i) += vec_at(cfg->out_start, i - 1);
vec_at(cfg->in_start, i) += vec_at(cfg->in_start, i - 1);
}
for (usize i = 0; i < ne; ++i)
vec_push(cfg->out_edges, 0);
for (usize i = 0; i < ne; ++i)
vec_push(cfg->in_edges, 0);
spl_cfg_index_vec_t out_cursor;
spl_cfg_index_vec_t in_cursor;
vec_init(out_cursor);
vec_init(in_cursor);
for (usize i = 0; i < n; ++i) {
vec_push(out_cursor, vec_at(cfg->out_start, i));
vec_push(in_cursor, vec_at(cfg->in_start, i));
}
for (usize i = 0; i < ne; ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
vec_at(cfg->out_edges, vec_at(out_cursor, e->from)++) = i;
vec_at(cfg->in_edges, vec_at(in_cursor, e->to)++) = i;
}
vec_free(out_cursor);
vec_free(in_cursor);
cfg->finalized = true;
return true;
}
static bool cfg_scc_impl(spl_cfg_t *cfg) {
if (!spl_cfg_finalize(cfg))
return false;
if (cfg->scc_done)
return true;
usize n = vec_size(cfg->nodes);
spl_cfg_index_vec_t visited;
spl_cfg_index_vec_t cursor;
spl_cfg_index_vec_t stack;
spl_cfg_index_vec_t post;
vec_init(visited);
vec_init(cursor);
vec_init(stack);
vec_init(post);
for (usize i = 0; i < n; ++i) {
vec_push(visited, 0);
vec_push(cursor, 0);
}
for (usize start = 1; start < n; ++start) {
if (vec_at(visited, start))
continue;
vec_at(visited, start) = 1;
vec_at(cursor, start) = vec_at(cfg->out_start, start);
vec_push(stack, start);
while (vec_size(stack) > 0) {
usize u = vec_at(stack, vec_size(stack) - 1);
usize cur = vec_at(cursor, u);
usize end = vec_at(cfg->out_start, u + 1);
if (cur < end) {
usize ei = vec_at(cfg->out_edges, cur);
vec_at(cursor, u) = cur + 1;
usize w = vec_at(cfg->edges, ei).to;
if (!vec_at(visited, w)) {
vec_at(visited, w) = 1;
vec_at(cursor, w) = vec_at(cfg->out_start, w);
vec_push(stack, w);
}
} else {
(void)vec_pop(stack);
vec_push(post, u);
}
}
}
cfg->scc.size = 0;
for (usize i = 0; i < n; ++i)
vec_push(cfg->scc, 0);
usize nscc = 0;
for (usize i = vec_size(post); i > 0; --i) {
usize start = vec_at(post, i - 1);
if (vec_at(cfg->scc, start))
continue;
nscc += 1;
vec_at(cfg->scc, start) = nscc;
vec_push(stack, start);
while (vec_size(stack) > 0) {
usize u = vec_pop(stack);
usize begin = vec_at(cfg->in_start, u);
usize end = vec_at(cfg->in_start, u + 1);
for (usize k = begin; k < end; ++k) {
usize ei = vec_at(cfg->in_edges, k);
usize w = vec_at(cfg->edges, ei).from;
if (!vec_at(cfg->scc, w)) {
vec_at(cfg->scc, w) = nscc;
vec_push(stack, w);
}
}
}
}
vec_free(visited);
vec_free(cursor);
vec_free(stack);
vec_free(post);
cfg->scc_done = true;
return true;
}
bool spl_cfg_scc(spl_cfg_t *cfg) { return cfg_scc_impl(cfg); }
static bool cfg_topo_impl(spl_cfg_t *cfg) {
if (!cfg_scc_impl(cfg))
return false;
if (cfg->topo_done)
return true;
usize n = vec_size(cfg->nodes);
usize nscc = 0;
for (usize i = 1; i < n; ++i) {
if (vec_at(cfg->scc, i) > nscc)
nscc = vec_at(cfg->scc, i);
}
spl_cfg_index_vec_t cond_start;
spl_cfg_index_vec_t cond_edges;
spl_cfg_index_vec_t indeg;
vec_init(cond_start);
vec_init(cond_edges);
vec_init(indeg);
for (usize i = 0; i < nscc + 2; ++i)
vec_push(cond_start, 0);
for (usize i = 0; i < nscc + 1; ++i)
vec_push(indeg, 0);
for (usize i = 0; i < vec_size(cfg->edges); ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
usize su = vec_at(cfg->scc, e->from);
usize sv = vec_at(cfg->scc, e->to);
if (su == sv)
continue;
vec_at(cond_start, su + 1) += 1;
}
for (usize i = 1; i <= nscc + 1; ++i)
vec_at(cond_start, i) += vec_at(cond_start, i - 1);
for (usize i = 0; i < vec_at(cond_start, nscc + 1); ++i)
vec_push(cond_edges, 0);
spl_cfg_index_vec_t cursor;
vec_init(cursor);
for (usize i = 0; i < nscc + 1; ++i)
vec_push(cursor, vec_at(cond_start, i));
for (usize i = 0; i < vec_size(cfg->edges); ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
usize su = vec_at(cfg->scc, e->from);
usize sv = vec_at(cfg->scc, e->to);
if (su == sv)
continue;
vec_at(cond_edges, vec_at(cursor, su)++) = sv;
vec_at(indeg, sv) += 1;
}
vec_free(cursor);
spl_cfg_index_vec_t queue;
spl_cfg_index_vec_t order;
vec_init(queue);
vec_init(order);
for (usize s = 1; s <= nscc; ++s) {
if (vec_at(indeg, s) == 0)
vec_push(queue, s);
}
usize head = 0;
while (head < vec_size(queue)) {
usize s = vec_at(queue, head++);
vec_push(order, s);
usize begin = vec_at(cond_start, s);
usize end = vec_at(cond_start, s + 1);
for (usize i = begin; i < end; ++i) {
usize t = vec_at(cond_edges, i);
if (vec_at(indeg, t) == 0)
continue;
vec_at(indeg, t) -= 1;
if (vec_at(indeg, t) == 0)
vec_push(queue, t);
}
}
if (vec_size(order) != nscc) {
vec_free(cond_start);
vec_free(cond_edges);
vec_free(indeg);
vec_free(queue);
vec_free(order);
return false;
}
/* 按 SCC 顺序展开节点;SCC 内按节点 id 升序。 */
spl_cfg_index_vec_t scc_start;
spl_cfg_index_vec_t scc_nodes;
vec_init(scc_start);
vec_init(scc_nodes);
for (usize i = 0; i < nscc + 2; ++i)
vec_push(scc_start, 0);
for (usize v = 1; v < n; ++v)
vec_at(scc_start, vec_at(cfg->scc, v) + 1) += 1;
for (usize i = 1; i <= nscc + 1; ++i)
vec_at(scc_start, i) += vec_at(scc_start, i - 1);
for (usize i = 0; i < n; ++i)
vec_push(scc_nodes, 0);
spl_cfg_index_vec_t fill;
vec_init(fill);
for (usize i = 0; i < nscc + 1; ++i)
vec_push(fill, vec_at(scc_start, i));
for (usize v = 1; v < n; ++v) {
usize s = vec_at(cfg->scc, v);
vec_at(scc_nodes, vec_at(fill, s)++) = v;
}
vec_free(fill);
cfg->topo.size = 0;
for (usize i = 0; i < vec_size(order); ++i) {
usize s = vec_at(order, i);
usize begin = vec_at(scc_start, s);
usize end = vec_at(scc_start, s + 1);
for (usize k = begin; k < end; ++k)
vec_push(cfg->topo, vec_at(scc_nodes, k));
}
vec_free(scc_start);
vec_free(scc_nodes);
vec_free(cond_start);
vec_free(cond_edges);
vec_free(indeg);
vec_free(queue);
vec_free(order);
cfg->topo_done = true;
return true;
}
bool spl_cfg_topo(spl_cfg_t *cfg) { return cfg_topo_impl(cfg); }
bool spl_cfg_closure(spl_cfg_t *cfg, spl_cfg_node_t root, spl_cfg_node_vec_t *out) {
if (!cfg || !out || !spl_cfg_finalize(cfg))
return false;
usize n = vec_size(cfg->nodes);
if (!root || root >= n)
return false;
spl_cfg_index_vec_t visited;
spl_cfg_index_vec_t stack;
vec_init(visited);
vec_init(stack);
for (usize i = 0; i < n; ++i)
vec_push(visited, 0);
vec_at(visited, root) = 1;
vec_push(stack, root);
while (vec_size(stack) > 0) {
usize u = vec_pop(stack);
vec_push(*out, u);
usize begin = vec_at(cfg->out_start, u);
usize end = vec_at(cfg->out_start, u + 1);
for (usize i = begin; i < end; ++i) {
usize ei = vec_at(cfg->out_edges, i);
usize w = vec_at(cfg->edges, ei).to;
if (!vec_at(visited, w)) {
vec_at(visited, w) = 1;
vec_push(stack, w);
}
}
}
vec_free(visited);
vec_free(stack);
return true;
}
void spl_cfg_dump(const spl_cfg_t *cfg, FILE *out) {
if (!cfg || !out)
return;
fprintf(out, "cfg nodes=%zu edges=%zu\n", vec_size(cfg->nodes) - 1, vec_size(cfg->edges));
for (usize i = 1; i < vec_size(cfg->nodes); ++i) {
const spl_cfg_node_info_t *info = &vec_at(cfg->nodes, i);
fprintf(out, " node %zu %s", i, spl_cfg_node_kind_name(info->kind));
if (info->name)
fprintf(out, " %s", info->name);
if (info->user)
fprintf(out, " user=%zu", info->user);
if (vec_size(cfg->scc) > i)
fprintf(out, " scc=%zu", vec_at(cfg->scc, i));
fprintf(out, "\n");
}
for (usize i = 0; i < vec_size(cfg->edges); ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
fprintf(out, " edge %zu -> %zu %s\n", e->from, e->to, spl_cfg_edge_kind_name(e->kind));
}
if (vec_size(cfg->topo) > 0) {
fprintf(out, " topo:");
for (usize i = 0; i < vec_size(cfg->topo); ++i)
fprintf(out, " %zu", vec_at(cfg->topo, i));
fprintf(out, "\n");
}
}
+104
View File
@@ -0,0 +1,104 @@
#include "spl_cfg_ir.h"
#include <stdlib.h>
#include <string.h>
bool spl_cfg_ir_build(spl_cfg_t *cfg, const spl_ir_t *ir, spl_ir_func_ref_t fid,
spl_cfg_node_t *entry) {
if (!cfg || !ir || !fid || !entry)
return false;
spl_ir_func_t *f = spl_ir_func((spl_ir_t *)ir, fid);
if (!f)
return false;
usize n = vec_size(f->nodes);
if (n <= 1)
return false;
unsigned char *starts = calloc(n, 1);
spl_cfg_node_t *block_of = calloc(n, sizeof(*block_of));
spl_cfg_node_t *block_nodes = calloc(n, sizeof(*block_nodes));
if (!starts || !block_of || !block_nodes) {
free(starts);
free(block_of);
free(block_nodes);
return false;
}
starts[1] = 1;
for (usize i = 1; i < n; ++i) {
spl_ir_node_t *node = &vec_at(f->nodes, i);
if (node->kind == SPL_IR_CONTROL_BR) {
if (node->control_br.true_label > 0 && node->control_br.true_label < n)
starts[node->control_br.true_label] = 1;
if (node->control_br.false_label > 0 && node->control_br.false_label < n)
starts[node->control_br.false_label] = 1;
} else if (node->kind == SPL_IR_CONTROL_JMP) {
if (node->control_jmp.label > 0 && node->control_jmp.label < n)
starts[node->control_jmp.label] = 1;
}
}
usize nblocks = 0;
for (usize i = 1; i < n; ++i) {
if (!starts[i])
continue;
spl_cfg_node_info_t info = {0};
info.kind = SPL_CFG_NODE_BLOCK;
info.name = f->name;
info.user = i;
spl_cfg_node_t b = spl_cfg_add_node(cfg, info);
block_of[i] = b;
block_nodes[nblocks++] = b;
if (nblocks == 1)
*entry = b;
}
/* 每个节点归属到最近的、以某个 start 开始的 block。 */
usize bi = 0;
for (usize i = 1; i < n; ++i) {
if (i != 1 && starts[i])
bi += 1;
block_of[i] = block_nodes[bi];
}
spl_cfg_node_info_t exit_info = {0};
exit_info.kind = SPL_CFG_NODE_EXIT;
exit_info.name = f->name;
spl_cfg_node_t exit_node = spl_cfg_add_node(cfg, exit_info);
for (usize k = 0; k < nblocks; ++k) {
usize end = (k + 1 < nblocks)
? (usize)spl_cfg_node_info(cfg, block_nodes[k + 1])->user
: n;
usize last = end - 1;
spl_ir_node_t *term = &vec_at(f->nodes, last);
if (term->kind == SPL_IR_CONTROL_BR) {
usize tl = term->control_br.true_label;
usize fl = term->control_br.false_label;
if (tl > 0 && tl < n && block_of[tl])
spl_cfg_add_edge(cfg, block_nodes[k], block_of[tl], SPL_CFG_EDGE_BR_TRUE);
if (fl > 0 && fl < n && block_of[fl])
spl_cfg_add_edge(cfg, block_nodes[k], block_of[fl], SPL_CFG_EDGE_BR_FALSE);
} else if (term->kind == SPL_IR_CONTROL_JMP) {
usize tl = term->control_jmp.label;
if (tl > 0 && tl < n && block_of[tl])
spl_cfg_add_edge(cfg, block_nodes[k], block_of[tl], SPL_CFG_EDGE_JMP);
} else if (term->kind == SPL_IR_CONTROL_RET || term->kind == SPL_IR_CONTROL_TRAP ||
term->kind == SPL_IR_CONTROL_UNREACHABLE) {
spl_cfg_add_edge(cfg, block_nodes[k], exit_node, SPL_CFG_EDGE_JMP);
} else {
if (k + 1 < nblocks)
spl_cfg_add_edge(cfg, block_nodes[k], block_nodes[k + 1], SPL_CFG_EDGE_JMP);
else
spl_cfg_add_edge(cfg, block_nodes[k], exit_node, SPL_CFG_EDGE_JMP);
}
}
free(starts);
free(block_of);
free(block_nodes);
return spl_cfg_finalize(cfg);
}
+110 -88
View File
@@ -1,13 +1,15 @@
/* splc0.c - SPL compiler CLI (stage 1, 引导用)
/* splc1.c - SPL compiler CLI (stage 1, 引导用)
*
* splc0 --dump tokens|ast|sema|ir|vm <file> dump 前端产物
* splc0 <in> <out> 编译
* splc1 [--dump <none|lex|ast|sema|ir|vm|c>] [-g] [--opt] <in> <out>
*/
#define __SCC_LOG_IMPL_IMPORT_SRC__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#define SCC_ARGPARSE_IMPLEMENTATION
#define SCC_OPTPARSER_IMPLEMENTATION
#include "nob/argparse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ir_opt.h"
@@ -18,7 +20,10 @@
#include "spl_diag.h"
#include "spl_ir2c.h"
#include "spl_ir2vm.h"
#include "spl_ir_link.h"
#include "spl_lexer.h"
#include "spl_meta.h"
#include "spl_module.h"
#include "spl_parser.h"
#include "spl_sema.h"
#include "spl_tok.h"
@@ -47,10 +52,17 @@ typedef struct {
spl_driver_module_vec_t modules;
MAP(const char *, usize) path_to_idx;
spl_module_registry_t module_registry;
spl_diag_t *diag;
} spl_driver_t;
static spl_module_id_t driver_register_module(spl_driver_t *d, spl_ast_t *ast, const char *path,
spl_diag_t *diag) {
return spl_module_register(&d->module_registry, ast, path, spl_module_declared_name(ast),
diag);
}
static char *read_file(const char *path, long *out_len) {
FILE *f = fopen(path, "rb");
if (!f) {
@@ -217,6 +229,8 @@ static spl_ast_t *driver_load(void *user, const char *from_fname, const char *pa
vec_at(d->modules, idx).ast = ast;
vec_at(d->modules, idx).src = src;
if (!driver_register_module(d, ast, key, diag))
return NULL;
return ast;
}
@@ -234,6 +248,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_ast_init(&drv.main_ast, &drv.main_toks);
map_init(drv.path_to_idx, MAP_HASH_STR, MAP_CMP_STR);
vec_init(drv.modules);
spl_module_registry_init(&drv.module_registry);
int rc = 0;
@@ -243,6 +258,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
dump_tokens(drv.main_toks);
free(drv.main_path);
map_free(drv.path_to_idx);
spl_module_registry_drop(&drv.module_registry);
spl_diag_drop(&diag);
return 0;
}
@@ -251,8 +267,10 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_lang_type_t lang_type;
spl_layout_target_t layout_target;
spl_layout_t layout;
spl_scope_t scope;
spl_namespace_t ns;
spl_sema_t sema;
spl_meta_t *meta = NULL;
spl_ir_link_t *ir_link = NULL;
spl_ast2ir_t a2ir;
spl_ir_builder_t ir_builder;
spl_ir2vm_t ir2vm;
@@ -277,9 +295,17 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
goto cleanup;
}
if (!driver_register_module(&drv, &drv.main_ast, drv.main_path, &diag)) {
spl_diag_summary(&diag);
rc = 1;
goto cleanup;
}
spl_attr_init(&attr);
attr_ok = 1;
spl_lang_type_init(&lang_type);
spl_ir_builder_init(&ir_builder);
irb_ok = 1;
spl_lang_type_init(&lang_type, ir_builder.ir.types);
lang_type_ok = 1;
/* 目标描述符:剥离目标机器细节,layout 是 size/align/offset 的唯一来源。 */
@@ -290,10 +316,16 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_layout_init(&layout, &layout_target);
layout_ok = 1;
spl_scope_init(&scope);
spl_ns_init(&ns);
scope_ok = 1;
spl_sema_init(&sema, &drv.main_ast, &lang_type, &layout, &scope, &attr);
spl_sema_init(&sema, &drv.main_ast, &lang_type, &layout, &ns, &attr);
sema.modules = &drv.module_registry;
sema.ir = &ir_builder.ir;
ir_link = spl_ir_link_create(&ir_builder.ir, &sema);
sema.ir_link = ir_link;
meta = spl_meta_create(&sema);
sema.meta = meta;
sema_ok = 1;
spl_module_loader_t loader = {.load = driver_load, .user = &drv};
sema.loader = &loader;
@@ -318,8 +350,6 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
for (usize i = 0; i < vec_size(drv.modules); ++i)
vec_push(all_asts, vec_at(drv.modules, i).ast);
spl_ir_builder_init(&ir_builder);
irb_ok = 1;
spl_ast2ir_init(&a2ir, &ir_builder, &layout, &sema);
a2ir_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_AST2IR);
@@ -335,18 +365,18 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_ir_opt(&ir_builder.ir, &attr);
if (dump == DUMP_IR) {
spl_ir_dump(&ir_builder.ir, &lang_type.ir, &attr);
spl_ir_dump(&ir_builder.ir, &attr);
goto cleanup;
}
/* 类型已全部就绪:解析 layout,供 ir2vm/ir2c 的 size/align/offset 使用。 */
spl_layout_resolve(&layout, &lang_type.ir);
spl_layout_resolve(&layout, ir_builder.ir.types);
/* 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);
bool cok = spl_ir2c_run(&a2ir.ir->ir, &layout, &attr, &cbuf);
FILE *cf = fopen(outpath, "wb");
if (!cf) {
LOG_FATAL("cannot open C output file `%s`", outpath);
@@ -363,7 +393,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
goto cleanup;
}
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &lang_type.ir, &layout, &attr);
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &layout, &attr);
ir2vm_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_IR2VM);
ir2vm.diag = &diag;
@@ -390,16 +420,18 @@ cleanup:
spl_ir2vm_drop(&ir2vm);
if (a2ir_ok)
spl_ast2ir_drop(&a2ir);
if (irb_ok)
spl_ir_builder_drop(&ir_builder);
spl_meta_destroy(meta);
if (sema_ok)
spl_sema_drop(&sema);
if (scope_ok)
spl_scope_drop(&scope);
if (layout_ok)
spl_layout_drop(&layout);
spl_ir_link_destroy(ir_link);
if (lang_type_ok)
spl_lang_type_drop(&lang_type);
if (layout_ok)
spl_layout_drop(&layout);
if (irb_ok)
spl_ir_builder_drop(&ir_builder);
if (scope_ok)
spl_ns_drop(&ns);
if (attr_ok)
spl_attr_drop(&attr);
@@ -416,86 +448,76 @@ cleanup:
vec_free(drv.modules);
/* map 的 key 是 module 里 strdup 出的 abs_path,已随 module 释放 */
map_free(drv.path_to_idx);
spl_module_registry_drop(&drv.module_registry);
free(drv.main_path);
spl_diag_drop(&diag);
return rc;
}
typedef struct {
const char *in;
const char *out;
int dump_choice;
cbool gen_debug;
cbool opt;
} splc1_cli_t;
/* 顺序必须与 dump_t 一致:choices 存的是下标,这里直接当下标用。 */
static const char *DUMP_MODE_NAMES[] = {"none", "lex", "ast", "sema", "ir", "vm", "c"};
static void add_bool_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
cbool *store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_bool(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_arg_string(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
const char **store, cbool required) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_string(&arg.spec, store);
arg.spec.flag_required = required;
scc_argparse_cmd_add_arg(cmd, &arg);
}
int main(int argc, char **argv) {
if (argc < 2) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
LOG_INFO("splc0 <in> <out> compile (.spl -> .sir, stage B)");
LOG_INFO("splc0 --dump <flags> <file> dump: lex,ast,sema,ir,vm,none");
return 0;
}
int opt = 0;
for (int ai = 1; ai < argc; ai++)
if (strcmp(argv[ai], "--opt") == 0)
opt = 1;
splc1_cli_t cli = {0};
cli.dump_choice = DUMP_NONE;
int argi = 1;
if (argi >= argc) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
scc_argparse_t parser;
scc_argparse_init(&parser, "splc1", "The first spl compiler.");
scc_argparse_cmd_t *root = scc_argparse_get_root(&parser);
dump_t dump = DUMP_NONE;
if (strcmp(argv[argi], "--dump") == 0) {
if (argc < argi + 3) {
LOG_INFO("splc0: --dump need <flags> <file>");
return 1;
}
scc_argparse_opt_t dump_opt;
scc_argparse_opt_init(&dump_opt, 0, "dump", "dump a front-end product");
scc_argparse_spec_setup_choices(&dump_opt.spec, DUMP_MODE_NAMES,
(int)(sizeof DUMP_MODE_NAMES / sizeof DUMP_MODE_NAMES[0]),
&cli.dump_choice);
scc_argparse_opt_set_group(&dump_opt, "Dump");
scc_argparse_cmd_add_opt(root, &dump_opt);
const char *flags = argv[argi + 1];
if (strcmp(flags, "lex") == 0) {
dump = DUMP_TOKEN;
} else if (strcmp(flags, "ast") == 0) {
dump = DUMP_AST;
} else if (strcmp(flags, "sema") == 0) {
dump = DUMP_SEMA;
} else if (strcmp(flags, "ir") == 0) {
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|c|none, got `%s`", flags);
return 1;
}
argi += 2;
}
/* splc0 [-g] <in> <out> */
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] or splc0 --dump <flags> <file>\n");
return 1;
}
int gen_debug = 0;
while (argi < argc - 1) {
if (strcmp(argv[argi], "-g") == 0) {
gen_debug = 1;
argi++;
} else if (strcmp(argv[argi], "--opt") == 0) {
opt = 1;
argi++;
} else {
break;
}
}
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] [--opt] or splc0 --dump <flags> <file>\n");
return 1;
add_bool_opt(root, 'g', NULL, "emit debug info", &cli.gen_debug);
add_bool_opt(root, 0, "opt", "enable IR/bytecode optimizations", &cli.opt);
add_arg_string(root, "in", "source file", &cli.in, true);
add_arg_string(root, "out", "output file", &cli.out, true);
int rc = scc_argparse_parse(&parser, argc, (const char **)argv);
if (parser.out.count > 0)
fwrite(parser.out.items, 1, parser.out.count, stdout);
if (rc != SCC_ARGPARSE_ERR_NONE) {
scc_argparse_drop(&parser);
return rc == SCC_ARGPARSE_ERR_PNT_DEFAULT ? 0 : 1;
}
scc_argparse_drop(&parser);
long len;
char *src = read_file(argv[argi], &len);
char *src = read_file(cli.in, &len);
if (!src)
return 1;
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug, dump, opt);
rc = compile_spl(src, cli.in, cli.out, cli.gen_debug, (dump_t)cli.dump_choice, cli.opt);
free(src);
return rc;
}
+407
View File
@@ -0,0 +1,407 @@
#include "spl_exec.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
spl_exec_unit_key_t key;
spl_exec_unit_t *unit;
bool loaded;
} spl_exec_unit_entry_t;
typedef VEC(spl_exec_unit_entry_t) spl_exec_unit_entry_vec_t;
typedef struct {
spl_ir_func_ref_t root;
spl_exec_phase_t phase;
usize viewpoint;
usize generation;
spl_exec_plan_t plan;
} spl_exec_plan_entry_t;
typedef VEC(spl_exec_plan_entry_t) spl_exec_plan_entry_vec_t;
typedef struct {
spl_exec_unit_key_t key;
usize generation;
usize nargs;
usize *args;
usize result;
} spl_exec_result_entry_t;
typedef VEC(spl_exec_result_entry_t) spl_exec_result_entry_vec_t;
struct spl_exec {
spl_ir_t *ir;
spl_layout_t *layout;
const spl_exec_frontend_t *frontend;
const spl_exec_backend_t *backend;
spl_exec_phase_t phase;
usize viewpoint;
usize generation;
spl_exec_unit_entry_vec_t units;
spl_exec_plan_entry_vec_t plans;
spl_exec_result_entry_vec_t results;
VEC(spl_exec_host_t) hosts;
spl_exec_stats_t stats;
};
static bool unit_key_eq(const spl_exec_unit_key_t *a, const spl_exec_unit_key_t *b) {
return a->callee == b->callee && a->phase == b->phase && a->viewpoint == b->viewpoint &&
a->specialization == b->specialization;
}
static bool plan_key_eq(const spl_exec_plan_entry_t *e, spl_ir_func_ref_t root,
spl_exec_phase_t phase, usize viewpoint, usize generation) {
return e->root == root && e->phase == phase && e->viewpoint == viewpoint &&
e->generation == generation;
}
static void plan_clone(spl_exec_plan_t *dst, const spl_exec_plan_t *src) {
dst->root = src->root;
vec_init(dst->order);
for (usize i = 0; i < vec_size(src->order); ++i)
vec_push(dst->order, vec_at(src->order, i));
}
void spl_exec_plan_drop(spl_exec_plan_t *plan) {
if (!plan)
return;
vec_free(plan->order);
memset(plan, 0, sizeof(*plan));
}
static void exec_unload_unit(spl_exec_t *exec, spl_exec_unit_entry_t *entry) {
if (!entry->unit)
return;
if (exec->backend && exec->backend->unload)
exec->backend->unload(exec, entry->unit);
free(entry->unit);
entry->unit = NULL;
entry->loaded = false;
}
spl_exec_t *spl_exec_create(spl_ir_t *ir, spl_layout_t *layout,
const spl_exec_frontend_t *frontend,
const spl_exec_backend_t *backend) {
spl_exec_t *exec = calloc(1, sizeof(*exec));
if (!exec)
return NULL;
exec->ir = ir;
exec->layout = layout;
exec->frontend = frontend;
exec->backend = backend;
exec->phase = SPL_EXEC_PHASE_META;
exec->viewpoint = 0;
exec->generation = 1;
vec_init(exec->units);
vec_init(exec->plans);
vec_init(exec->results);
vec_init(exec->hosts);
return exec;
}
void spl_exec_destroy(spl_exec_t *exec) {
if (!exec)
return;
for (usize i = 0; i < vec_size(exec->units); ++i)
exec_unload_unit(exec, &vec_at(exec->units, i));
vec_free(exec->units);
for (usize i = 0; i < vec_size(exec->plans); ++i)
spl_exec_plan_drop(&vec_at(exec->plans, i).plan);
vec_free(exec->plans);
for (usize i = 0; i < vec_size(exec->results); ++i)
free(vec_at(exec->results, i).args);
vec_free(exec->results);
vec_free(exec->hosts);
free(exec);
}
void spl_exec_set_phase(spl_exec_t *exec, spl_exec_phase_t phase, usize viewpoint) {
if (!exec)
return;
exec->phase = phase;
exec->viewpoint = viewpoint;
}
static void exec_flush(spl_exec_t *exec) {
for (usize i = 0; i < vec_size(exec->units); ++i)
exec_unload_unit(exec, &vec_at(exec->units, i));
exec->units.size = 0;
for (usize i = 0; i < vec_size(exec->plans); ++i)
spl_exec_plan_drop(&vec_at(exec->plans, i).plan);
exec->plans.size = 0;
for (usize i = 0; i < vec_size(exec->results); ++i)
free(vec_at(exec->results, i).args);
exec->results.size = 0;
}
void spl_exec_bump_generation(spl_exec_t *exec) {
if (!exec)
return;
exec_flush(exec);
exec->generation += 1;
}
usize spl_exec_generation(const spl_exec_t *exec) { return exec ? exec->generation : 0; }
const spl_exec_stats_t *spl_exec_stats_view(const spl_exec_t *exec) {
return exec ? &exec->stats : NULL;
}
const spl_exec_frontend_t *spl_exec_frontend_of(const spl_exec_t *exec) {
return exec ? exec->frontend : NULL;
}
const spl_exec_backend_t *spl_exec_backend_of(const spl_exec_t *exec) {
return exec ? exec->backend : NULL;
}
const spl_ir_t *spl_exec_ir(const spl_exec_t *exec) {
return exec ? exec->ir : NULL;
}
spl_layout_t *spl_exec_layout(const spl_exec_t *exec) {
return exec ? exec->layout : NULL;
}
const spl_exec_host_t *spl_exec_find_host(spl_exec_t *exec, const char *name) {
if (!exec || !name)
return NULL;
for (usize i = 0; i < vec_size(exec->hosts); ++i) {
spl_exec_host_t *host = &vec_at(exec->hosts, i);
if (host->name && strcmp(host->name, name) == 0)
return host;
}
return NULL;
}
bool spl_exec_register_host(spl_exec_t *exec, const spl_exec_host_t *host) {
if (!exec || !host || !host->name || !host->fn)
return false;
if (spl_exec_find_host(exec, host->name))
return false;
vec_push(exec->hosts, *host);
return true;
}
static spl_exec_unit_entry_t *exec_find_unit(spl_exec_t *exec,
const spl_exec_unit_key_t *key) {
for (usize i = 0; i < vec_size(exec->units); ++i) {
spl_exec_unit_entry_t *entry = &vec_at(exec->units, i);
if (unit_key_eq(&entry->key, key))
return entry;
}
return NULL;
}
static spl_exec_unit_entry_t *exec_compile_unit(spl_exec_t *exec,
const spl_exec_unit_key_t *key) {
spl_exec_unit_entry_t *existing = exec_find_unit(exec, key);
if (existing) {
exec->stats.unit_cache_hits += 1;
return existing;
}
if (!exec->frontend || !exec->frontend->compile)
return NULL;
if (exec->frontend->ready && !exec->frontend->ready(exec, key))
return NULL;
spl_exec_unit_t *unit = calloc(1, sizeof(*unit));
if (!unit)
return NULL;
unit->key = *key;
if (!exec->frontend->compile(exec, key, unit)) {
free(unit);
return NULL;
}
spl_exec_unit_entry_t entry = {.key = *key, .unit = unit, .loaded = false};
vec_push(exec->units, entry);
exec->stats.unit_compiles += 1;
return &vec_at(exec->units, vec_size(exec->units) - 1);
}
static bool fn_vec_contains(const spl_ir_func_ref_vec_t *v, spl_ir_func_ref_t fn) {
for (usize i = 0; i < vec_size(*v); ++i) {
if (vec_at(*v, i) == fn)
return true;
}
return false;
}
static bool plan_visit(spl_exec_t *exec, spl_ir_func_ref_t fn, spl_ir_func_ref_vec_t *visited,
spl_ir_func_ref_vec_t *order) {
if (fn_vec_contains(visited, fn))
return true;
if (!spl_ir_func(exec->ir, fn))
return false;
vec_push(*visited, fn);
spl_exec_unit_key_t key = {
.callee = fn,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.specialization = 0,
};
if (!exec_compile_unit(exec, &key))
return false;
spl_ir_func_ref_vec_t callees;
vec_init(callees);
spl_ir_func_callees(exec->ir, fn, &callees);
for (usize i = 0; i < vec_size(callees); ++i) {
if (!plan_visit(exec, vec_at(callees, i), visited, order)) {
vec_free(callees);
return false;
}
}
vec_free(callees);
vec_push(*order, fn);
return true;
}
bool spl_exec_plan_build(spl_exec_t *exec, spl_ir_func_ref_t root, spl_exec_plan_t *out) {
if (!exec || !exec->ir || !out || !spl_ir_func(exec->ir, root))
return false;
memset(out, 0, sizeof(*out));
for (usize i = 0; i < vec_size(exec->plans); ++i) {
spl_exec_plan_entry_t *entry = &vec_at(exec->plans, i);
if (plan_key_eq(entry, root, exec->phase, exec->viewpoint, exec->generation)) {
plan_clone(out, &entry->plan);
exec->stats.plan_cache_hits += 1;
return true;
}
}
spl_exec_plan_t plan = {.root = root};
vec_init(plan.order);
spl_ir_func_ref_vec_t visited;
vec_init(visited);
if (!plan_visit(exec, root, &visited, &plan.order)) {
vec_free(visited);
spl_exec_plan_drop(&plan);
return false;
}
vec_free(visited);
spl_exec_plan_entry_t entry = {
.root = root,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.generation = exec->generation,
.plan = plan,
};
vec_push(exec->plans, entry);
exec->stats.plan_builds += 1;
plan_clone(out, &plan);
return true;
}
bool spl_exec_compile_plan(spl_exec_t *exec, spl_exec_plan_t *plan) {
if (!exec || !plan)
return false;
for (usize i = 0; i < vec_size(plan->order); ++i) {
spl_ir_func_ref_t fn = vec_at(plan->order, i);
spl_exec_unit_key_t key = {
.callee = fn,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.specialization = 0,
};
if (!exec_compile_unit(exec, &key))
return false;
spl_exec_unit_entry_t *entry = exec_find_unit(exec, &key);
if (!entry || !entry->unit || !exec->backend || !exec->backend->load)
return false;
if (!entry->loaded) {
if (!exec->backend->load(exec, entry->unit))
return false;
entry->loaded = true;
}
}
return true;
}
static bool exec_unit_is_pure(spl_exec_t *exec, const spl_exec_unit_key_t *key) {
return exec->frontend && exec->frontend->is_pure && exec->frontend->is_pure(exec, key);
}
static bool args_equal(const usize *a, usize nargs, const usize *b) {
if (nargs == 0)
return true;
return a && b && memcmp(a, b, nargs * sizeof(*a)) == 0;
}
static usize *args_clone(const usize *args, usize nargs) {
if (nargs == 0)
return NULL;
usize *copy = malloc(nargs * sizeof(*copy));
if (!copy)
return NULL;
memcpy(copy, args, nargs * sizeof(*copy));
return copy;
}
bool spl_exec_execute_plan(spl_exec_t *exec, const spl_exec_plan_t *plan, const usize *args,
usize nargs, usize *out) {
if (!exec || !plan || !out)
return false;
spl_exec_unit_key_t key = {
.callee = plan->root,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.specialization = 0,
};
spl_exec_unit_entry_t *entry = exec_find_unit(exec, &key);
if (!entry || !entry->unit)
return false;
if (exec_unit_is_pure(exec, &key)) {
for (usize i = 0; i < vec_size(exec->results); ++i) {
spl_exec_result_entry_t *cached = &vec_at(exec->results, i);
if (cached->generation != exec->generation)
continue;
if (!unit_key_eq(&cached->key, &key))
continue;
if (cached->nargs != nargs || !args_equal(cached->args, nargs, args))
continue;
*out = cached->result;
exec->stats.result_cache_hits += 1;
return true;
}
}
usize result = 0;
if (!exec->backend->invoke(exec, entry->unit, args, nargs, &result))
return false;
exec->stats.invokes += 1;
*out = result;
if (exec_unit_is_pure(exec, &key)) {
spl_exec_result_entry_t cached = {
.key = key,
.generation = exec->generation,
.nargs = nargs,
.args = args_clone(args, nargs),
.result = result,
};
vec_push(exec->results, cached);
}
return true;
}
bool spl_exec_run(spl_exec_t *exec, spl_ir_func_ref_t root, const usize *args, usize nargs,
usize *out) {
spl_exec_plan_t plan;
if (!spl_exec_plan_build(exec, root, &plan))
return false;
bool ok = spl_exec_compile_plan(exec, &plan) && spl_exec_execute_plan(exec, &plan, args, nargs, out);
spl_exec_plan_drop(&plan);
return ok;
}
+109
View File
@@ -0,0 +1,109 @@
#include "spl_exec_frontend.h"
#include "spl_ast2ir.h"
#include "spl_ir.h"
#include <stdlib.h>
struct spl_exec_frontend_ctx {
spl_sema_t *sema;
spl_ir_link_t *link;
spl_ir_builder_t ir;
spl_ast2ir_t a2ir;
bool ir_ok;
bool a2ir_ok;
spl_exec_frontend_t vtable;
};
spl_exec_frontend_ctx_t *spl_exec_frontend_create(spl_sema_t *sema) {
if (!sema)
return NULL;
spl_exec_frontend_ctx_t *ctx = calloc(1, sizeof(*ctx));
if (!ctx)
return NULL;
ctx->sema = sema;
spl_ir_builder_init_shared(&ctx->ir, sema->type->ir_types);
ctx->ir_ok = true;
ctx->link = spl_ir_link_create(&ctx->ir.ir, sema);
if (!ctx->link) {
spl_ir_builder_drop(&ctx->ir);
free(ctx);
return NULL;
}
spl_ast2ir_init(&ctx->a2ir, &ctx->ir, sema->layout, sema);
ctx->a2ir.link = ctx->link;
ctx->a2ir_ok = true;
ctx->a2ir.mode = SPL_AST2IR_EXEC;
ctx->a2ir.diag = sema->diag;
ctx->vtable.ready = NULL;
ctx->vtable.compile = NULL;
ctx->vtable.is_pure = NULL;
ctx->vtable.user = ctx;
return ctx;
}
void spl_exec_frontend_destroy(spl_exec_frontend_ctx_t *ctx) {
if (!ctx)
return;
if (ctx->a2ir_ok)
spl_ast2ir_drop(&ctx->a2ir);
spl_ir_link_destroy(ctx->link);
if (ctx->ir_ok)
spl_ir_builder_drop(&ctx->ir);
free(ctx);
}
const spl_ir_t *spl_exec_frontend_ir(spl_exec_frontend_ctx_t *ctx) {
return ctx ? &ctx->ir.ir : NULL;
}
spl_ir_link_t *spl_exec_frontend_link(spl_exec_frontend_ctx_t *ctx) {
return ctx ? ctx->link : NULL;
}
static bool frontend_ready(spl_exec_t *exec, const spl_exec_unit_key_t *key) {
spl_exec_frontend_ctx_t *ctx = (spl_exec_frontend_ctx_t *)spl_exec_frontend_of(exec)->user;
usize def_id = 0;
if (!spl_ir_link_def_of_fn(ctx->link, key->callee, &def_id))
return false;
spl_def_node_t *def = spl_def_node(ctx->sema->type, def_id);
if (!def || def->kind != SPL_DEF_FN || !def->owner_ast)
return false;
spl_ast_node_t *fn = spl_ast_node(def->owner_ast, def->ast_node_ref);
return fn && fn->kind == SPL_AST_FN_DECL;
}
static bool frontend_compile(spl_exec_t *exec, const spl_exec_unit_key_t *key,
spl_exec_unit_t *out) {
spl_exec_frontend_ctx_t *ctx = (spl_exec_frontend_ctx_t *)spl_exec_frontend_of(exec)->user;
usize def_id = 0;
if (!spl_ir_link_def_of_fn(ctx->link, key->callee, &def_id))
return false;
spl_def_node_t *def = spl_def_node(ctx->sema->type, def_id);
if (!def || !def->owner_ast)
return false;
if (!spl_ast2ir_lower_fn(&ctx->a2ir, def->owner_ast, def->ast_node_ref))
return false;
if (spl_ir_link_reserve_fn(ctx->link, def_id) != key->callee)
return false;
out->state = (void *)(uintptr_t)key->callee;
return true;
}
static bool frontend_is_pure(spl_exec_t *exec, const spl_exec_unit_key_t *key) {
(void)exec;
(void)key;
return false;
}
const spl_exec_frontend_t *spl_exec_frontend_vtable(spl_exec_frontend_ctx_t *ctx) {
if (!ctx)
return NULL;
ctx->vtable.ready = frontend_ready;
ctx->vtable.compile = frontend_compile;
ctx->vtable.is_pure = frontend_is_pure;
ctx->vtable.user = ctx;
return &ctx->vtable;
}
+217
View File
@@ -0,0 +1,217 @@
#include "spl_exec_vm.h"
#include "spl_ir2vm.h"
#include "stage0/spl_vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct spl_exec_vm_ctx {
const spl_ir_t *ir;
spl_layout_t *layout;
const spl_attr_t *attr;
spl_ir2vm_t gen;
spl_vm_t vm;
bool gen_ok;
bool vm_ok;
bool ready;
spl_exec_backend_t vtable;
};
spl_exec_vm_ctx_t *spl_exec_vm_create(const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr) {
if (!ir || !layout || !attr)
return NULL;
spl_exec_vm_ctx_t *ctx = calloc(1, sizeof(*ctx));
if (!ctx)
return NULL;
ctx->ir = ir;
ctx->layout = layout;
ctx->attr = attr;
return ctx;
}
void spl_exec_vm_destroy(spl_exec_vm_ctx_t *ctx) {
if (!ctx)
return;
if (ctx->vm_ok)
spl_vm_drop(&ctx->vm);
if (ctx->gen_ok)
spl_ir2vm_drop(&ctx->gen);
free(ctx);
}
static bool vm_load(spl_exec_t *exec, spl_exec_unit_t *unit) {
(void)exec;
(void)unit;
spl_exec_vm_ctx_t *ctx = (spl_exec_vm_ctx_t *)spl_exec_backend_of(exec)->user;
ctx->ready = false;
return true;
}
static bool vm_is_aggregate(spl_exec_vm_ctx_t *ctx, spl_ir_type_id_t tid) {
const spl_ir_type_node_t *tn = spl_ir_type_node(ctx->ir->types, tid);
if (!tn)
return false;
return tn->kind == SPL_IR_TYPE_ARRAY || tn->kind == SPL_IR_TYPE_STRUCT ||
tn->kind == SPL_IR_TYPE_UNION || tn->kind == SPL_IR_TYPE_ENUM;
}
static usize vm_type_size(spl_exec_vm_ctx_t *ctx, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = spl_layout_info_of(ctx->layout, tid);
return info ? (info->size_bits + 7) / 8 : 0;
}
static spl_ir_func_t *vm_find_fn(spl_exec_vm_ctx_t *ctx, const char *name) {
if (!name)
return NULL;
for (usize i = 1; i < vec_size(ctx->ir->funcs); ++i) {
spl_ir_func_t *f = &vec_at(ctx->ir->funcs, i);
if (f->name && strcmp(f->name, name) == 0)
return f;
}
return NULL;
}
static spl_vm_val_t vm_foreign(spl_vm_t *vm, const spl_vm_call_t *call, void *user) {
spl_exec_t *exec = (spl_exec_t *)user;
spl_exec_vm_ctx_t *ctx = (spl_exec_vm_ctx_t *)spl_exec_backend_of(exec)->user;
const spl_exec_host_t *host = spl_exec_find_host(exec, call->name);
if (!host) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "compile-time host `%s` is not registered",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
spl_ir_func_t *fn = vm_find_fn(ctx, call->name);
if (!fn) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host signature for `%s` not found",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
const spl_ir_type_node_t *ftn = spl_ir_type_node(ctx->ir->types, fn->fn_tid);
if (!ftn || ftn->kind != SPL_IR_TYPE_FN || vec_size(ftn->fn_type.params) != call->nargs) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host signature mismatch for `%s`",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
spl_exec_value_t args[16];
if (call->nargs > 16) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host argument count too large");
vm->exit_code = 1;
return 0;
}
for (usize i = 0; i < call->nargs; ++i) {
spl_ir_type_id_t pt = vec_at(ftn->fn_type.params, i);
memset(&args[i], 0, sizeof(args[i]));
args[i].type = pt;
if (vm_is_aggregate(ctx, pt)) {
usize size = vm_type_size(ctx, pt);
args[i].size = size;
args[i].mem.off = (usize)call->args[i];
args[i].mem.ptr = spl_vm_xlate(vm, call->args[i], size);
if (!args[i].mem.ptr) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host aggregate argument is invalid");
vm->exit_code = 1;
return 0;
}
} else {
args[i].bits = (uint64_t)call->args[i];
}
}
spl_exec_value_t ret = {0};
spl_ir_type_id_t ret_tid = ftn->fn_type.ret;
ret.type = ret_tid;
if (vm_is_aggregate(ctx, ret_tid)) {
usize size = vm_type_size(ctx, ret_tid);
ret.size = size;
ret.mem.off = (usize)spl_vm_mem_alloc(vm, size);
ret.mem.ptr = spl_vm_xlate(vm, (spl_vm_val_t)ret.mem.off, size);
if (!ret.mem.off || !ret.mem.ptr) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host aggregate return is unavailable");
vm->exit_code = 1;
return 0;
}
}
if (!host->fn(exec, host->user, args, call->nargs, &ret)) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "compile-time host `%s` failed",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
return vm_is_aggregate(ctx, ret_tid) ? (spl_vm_val_t)ret.mem.off : (spl_vm_val_t)ret.bits;
}
static bool vm_rebuild(spl_exec_t *exec, spl_exec_vm_ctx_t *ctx) {
if (ctx->vm_ok) {
spl_vm_drop(&ctx->vm);
ctx->vm_ok = false;
}
if (ctx->gen_ok) {
spl_ir2vm_drop(&ctx->gen);
ctx->gen_ok = false;
}
spl_ir2vm_init(&ctx->gen, ctx->ir, ctx->layout, ctx->attr);
ctx->gen_ok = true;
spl_layout_resolve(ctx->layout, ctx->ir->types);
if (spl_ir2vm_run(&ctx->gen) != 0)
return false;
spl_vm_init(&ctx->vm);
ctx->vm_ok = true;
if (spl_vm_load_prog(&ctx->vm, &ctx->gen.prog) != 0)
return false;
spl_vm_set_foreign(&ctx->vm, vm_foreign, exec);
ctx->ready = true;
return true;
}
static bool vm_invoke(spl_exec_t *exec, spl_exec_unit_t *unit, const usize *args, usize nargs,
usize *out) {
spl_exec_vm_ctx_t *ctx = (spl_exec_vm_ctx_t *)spl_exec_backend_of(exec)->user;
if (!ctx->ready && !vm_rebuild(exec, ctx))
return false;
spl_ir_func_ref_t fn_ref = (spl_ir_func_ref_t)(uintptr_t)unit->state;
const spl_ir_func_t *fn = spl_ir_func((spl_ir_t *)ctx->ir, fn_ref);
if (!fn || !fn->name)
return false;
spl_vm_call_t call = {
.name = fn->name,
.args = (const spl_vm_val_t *)args,
.nargs = nargs,
.ret = 0,
};
if (spl_vm_invoke(&ctx->vm, &call) != 0)
return false;
if (ctx->vm.exit_code)
return false;
*out = (usize)call.ret;
return true;
}
static void vm_unload(spl_exec_t *exec, spl_exec_unit_t *unit) {
(void)exec;
(void)unit;
}
const spl_exec_backend_t *spl_exec_vm_vtable(spl_exec_vm_ctx_t *ctx) {
if (!ctx)
return NULL;
ctx->vtable.load = vm_load;
ctx->vtable.invoke = vm_invoke;
ctx->vtable.unload = vm_unload;
ctx->vtable.user = ctx;
return &ctx->vtable;
}
File renamed without changes.
+38 -17
View File
@@ -1,7 +1,7 @@
#ifndef __SPL_AST_H__
#define __SPL_AST_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_attr.h"
#include "spl_dbg.h"
#include "spl_tok.h"
@@ -13,7 +13,8 @@
X(SPL_AST_CONTAINER_MEMBERS, V0, container_members) \
X(SPL_AST_EXTERNAL_TAG_ITEM, V0, external_tag_item) \
X(SPL_AST_TAG_ITEM, V0, tag_item) \
X(SPL_AST_COMPTIME_DECL, V0, comptime_decl) \
X(SPL_AST_MOD_DECL, V0, mod_decl) \
X(SPL_AST_IMPORT_DECL, V0, import_decl) \
X(SPL_AST_TOP_LEVEL_BLOCK, V0, top_level_block) \
X(SPL_AST_FN_DECL, V0, fn_decl) \
X(SPL_AST_VAR_DECL, V0, var_decl) \
@@ -25,7 +26,6 @@
X(SPL_AST_STATEMENT_BREAK, V0, statement_break) \
X(SPL_AST_STATEMENT_CONTINUE, V0, statement_continue) \
X(SPL_AST_STATEMENT_DEFER, V0, statement_defer) \
X(SPL_AST_STATEMENT_COMPTIME, V0, statement_comptime) \
X(SPL_AST_STATEMENT_DECL, V0, statement_decl) \
X(SPL_AST_STATEMENT_EXPR, V0, statement_expr) \
X(SPL_AST_AGGREGATE_MEMBER, V0, aggregate_member) \
@@ -50,7 +50,7 @@
X(SPL_AST_EXPR_TUPLE, V0, tuple) \
X(SPL_AST_EXPR_ARRAY_LIT, V0, array_literal) \
X(SPL_AST_EXPR_AGGREGATE_LIT, V0, aggregate_literal) \
X(SPL_AST_EXPR_COMPTIME_CALL, V0, comptime_call) \
X(SPL_AST_EXPR_COMPILE_CALL, V0, compile_call) \
X(SPL_AST_EXPR_BLOCK, V0, block) \
X(SPL_AST_EXPR_IF, V0, if_expr) \
X(SPL_AST_EXPR_IFVAR, V0, ifvar_expr) \
@@ -66,7 +66,7 @@
X(SPL_AST_TYPE_FN, V0, type_fn) \
X(SPL_AST_TYPE_PAREN, V0, type_paren) \
X(SPL_AST_TYPE_AGGREGATE, V0, type_aggregate) \
X(SPL_AST_TYPE_COMPTIME_CALL, V0, type_comptime_call) \
X(SPL_AST_TYPE_COMPILE_CALL, V0, type_compile_call) \
X(SPL_AST_PATTERN_IDENT, V0, pattern_ident) \
X(SPL_AST_PATTERN_UNDERSCORE, V0, pattern_underscore) \
X(SPL_AST_PATTERN_DOT, V0, pattern_dot) \
@@ -143,6 +143,12 @@ typedef enum {
SPL_UNARY_OP_DEREF,
} spl_unary_op_t;
typedef enum {
SPL_FN_KIND_NORMAL,
SPL_FN_KIND_META,
SPL_FN_KIND_MACRO,
} spl_fn_kind_t;
struct spl_ast_node;
typedef struct spl_ast_node spl_ast_node_t;
typedef usize spl_ast_node_ref_t;
@@ -153,7 +159,9 @@ struct spl_ast_node {
spl_dbg_node_t dbg;
usize resolved_def_id;
usize resolved_outer_def_id;
usize resolved_lang_tid;
usize resolved_ns_id;
usize expected_lang_tid;
spl_attr_id_vec_t attrs;
@@ -164,12 +172,14 @@ struct spl_ast_node {
struct {
spl_ast_node_ref_vec_t external_tags;
spl_ast_node_ref_t module;
spl_ast_node_ref_vec_t declarations;
} container_members;
struct {
spl_ast_node_ref_vec_t tag_list;
bool is_comptime;
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_fn_kind_t fn_kind;
const char *name;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
@@ -177,6 +187,7 @@ struct spl_ast_node {
} fn_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t type;
@@ -184,12 +195,14 @@ struct spl_ast_node {
} var_const_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t type_expr;
} type_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
@@ -210,11 +223,22 @@ struct spl_ast_node {
} tag_item;
struct {
spl_ast_node_ref_t body;
} comptime_decl;
spl_ast_node_ref_vec_t decorator_list;
const char *path;
bool has_body;
spl_ast_node_ref_vec_t decls;
} mod_decl;
struct {
spl_ast_node_ref_vec_t tag_list;
spl_ast_node_ref_vec_t decorator_list;
bool is_path;
const char *path;
const char *alias;
} import_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t block;
} top_level_block;
@@ -234,9 +258,6 @@ struct spl_ast_node {
struct {
spl_ast_node_ref_t body;
} statement_defer;
struct {
spl_ast_node_ref_t body;
} statement_comptime;
struct {
spl_ast_node_ref_t decl;
} statement_decl;
@@ -339,7 +360,9 @@ struct spl_ast_node {
struct {
const char *name;
spl_ast_node_ref_vec_t args;
} comptime_call;
} compile_call;
struct {
spl_ast_node_ref_vec_t stmts;
@@ -384,7 +407,6 @@ struct spl_ast_node {
} match_expr;
struct {
bool is_comptime;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
} fn_type;
@@ -410,7 +432,6 @@ struct spl_ast_node {
} type_slice;
struct {
bool is_comptime;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
} type_fn;
@@ -427,7 +448,7 @@ struct spl_ast_node {
struct {
const char *name;
spl_ast_node_ref_vec_t args;
} type_comptime_call;
} type_compile_call;
struct {
const char *name;
@@ -5,26 +5,44 @@
#include "spl_ir.h"
#include "spl_sema.h"
typedef MAP(spl_def_id_t, spl_ir_node_ref_t) spl_def2ir_map_t;
typedef MAP(spl_def_id_t, spl_ir_value_t) spl_def2ir_map_t;
typedef struct {
usize cont_blk;
usize defer_base;
const char *label;
spl_ir_node_ref_vec_t breaks;
spl_ir_node_ref_t result_slot;
spl_type_id_t result_tid;
spl_ir_value_t result_slot;
spl_ir_type_id_t result_tid;
} spl_loop_ctx_t;
typedef VEC(spl_loop_ctx_t) spl_loop_ctx_vec_t;
typedef VEC(spl_ast_node_ref_t) spl_defer_stack_t;
typedef struct {
spl_ast_t *ast;
spl_ast_node_ref_t decl;
} spl_module_init_t;
typedef VEC(spl_module_init_t) spl_module_init_vec_t;
typedef enum {
SPL_AST2IR_RUNTIME,
SPL_AST2IR_META,
SPL_AST2IR_EXEC,
} spl_ast2ir_mode_t;
struct spl_ir_link;
typedef struct {
const spl_sema_t *sema;
struct spl_ir_link *link;
spl_ir_builder_t *ir;
spl_ast_t *ast;
spl_layout_t *layout; /* 借用 splc0 的 layout */
spl_ast2ir_mode_t mode;
spl_def2ir_map_t def2ir_map;
MAP(spl_def_id_t, usize) global_map;
spl_module_init_vec_t module_inits;
spl_loop_ctx_vec_t loop_stack;
spl_defer_stack_t defer_stack;
spl_lang_type_id_t cur_ret_lang;
@@ -37,6 +55,13 @@ void spl_ast2ir_init(spl_ast2ir_t *ast2ir, spl_ir_builder_t *ir, spl_layout_t *l
const spl_sema_t *sema);
void spl_ast2ir_drop(spl_ast2ir_t *ast2ir);
/* 生成函数在 IR 中的符号名;meta 与运行期共用同一规则。 */
bool spl_ast2ir_fn_name(const spl_sema_t *sema, const spl_attr_t *attr, const spl_ast_t *ast,
const spl_ast_node_t *fn, char *out, usize cap);
/* 只 lowering 一个函数;exec 的按函数编译入口。 */
bool spl_ast2ir_lower_fn(spl_ast2ir_t *ast2ir, spl_ast_t *ast, spl_ast_node_ref_t fn_ref);
void spl_ast2ir_run(spl_ast2ir_t *ast2ir, spl_ast_ptr_vec_t ast_vec);
#endif /* __SPL_AST2IR_H__ */
@@ -1,7 +1,7 @@
#ifndef __SPL_ATTR_H__
#define __SPL_ATTR_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_mpa.h"
typedef enum {
+85
View File
@@ -0,0 +1,85 @@
#ifndef __SPL_CFG_H__
#define __SPL_CFG_H__
#include "stage0/include/utils.h"
/* 通用有向图:调用图(函数)和过程内控制流图(基本块)共用同一套算法。
node 0 是哨兵,真实节点从 1 开始。 */
typedef usize spl_cfg_node_t;
typedef usize spl_cfg_edge_ref_t;
typedef VEC(spl_cfg_node_t) spl_cfg_node_vec_t;
typedef VEC(usize) spl_cfg_index_vec_t;
typedef enum {
SPL_CFG_NODE_FN,
SPL_CFG_NODE_BLOCK,
SPL_CFG_NODE_HOST,
SPL_CFG_NODE_EXIT,
} spl_cfg_node_kind_t;
typedef enum {
SPL_CFG_EDGE_CALL,
SPL_CFG_EDGE_FUNC_REF,
SPL_CFG_EDGE_BR_TRUE,
SPL_CFG_EDGE_BR_FALSE,
SPL_CFG_EDGE_JMP,
SPL_CFG_EDGE_HOST,
} spl_cfg_edge_kind_t;
typedef struct {
spl_cfg_node_kind_t kind;
const char *name;
/* 通用 payload:调用图里是 def_id,控制流图里是 IR 节点引用。 */
usize user;
} spl_cfg_node_info_t;
typedef struct {
spl_cfg_node_t from;
spl_cfg_node_t to;
spl_cfg_edge_kind_t kind;
} spl_cfg_edge_t;
typedef struct {
VEC(spl_cfg_node_info_t) nodes;
VEC(spl_cfg_edge_t) edges;
/* CSR 邻接:out_edges[out_start[n] .. out_start[n+1]) 是边的下标。 */
spl_cfg_index_vec_t out_start;
spl_cfg_index_vec_t out_edges;
spl_cfg_index_vec_t in_start;
spl_cfg_index_vec_t in_edges;
/* 1-based SCC id;0 表示未计算。 */
spl_cfg_index_vec_t scc;
/* 拓扑序:topo[i] 是节点;边 from -> to 保证 from 在 to 之前。 */
spl_cfg_index_vec_t topo;
bool finalized;
bool scc_done;
bool topo_done;
} spl_cfg_t;
void spl_cfg_init(spl_cfg_t *cfg);
void spl_cfg_drop(spl_cfg_t *cfg);
spl_cfg_node_t spl_cfg_add_node(spl_cfg_t *cfg, spl_cfg_node_info_t info);
void spl_cfg_add_edge(spl_cfg_t *cfg, spl_cfg_node_t from, spl_cfg_node_t to,
spl_cfg_edge_kind_t kind);
const spl_cfg_node_info_t *spl_cfg_node_info(const spl_cfg_t *cfg, spl_cfg_node_t node);
usize spl_cfg_node_count(const spl_cfg_t *cfg);
/* 构建 CSR;add_node/add_edge 后内部算法会自动重建。 */
bool spl_cfg_finalize(spl_cfg_t *cfg);
/* 强连通分量;同一 SCC 内节点 scc[..] 相同。 */
bool spl_cfg_scc(spl_cfg_t *cfg);
/* 拓扑序;要求图已 finalize。 */
bool spl_cfg_topo(spl_cfg_t *cfg);
/* 从 root 出发沿所有边可达的节点(包含 root)。 */
bool spl_cfg_closure(spl_cfg_t *cfg, spl_cfg_node_t root, spl_cfg_node_vec_t *out);
const char *spl_cfg_node_kind_name(spl_cfg_node_kind_t kind);
const char *spl_cfg_edge_kind_name(spl_cfg_edge_kind_t kind);
void spl_cfg_dump(const spl_cfg_t *cfg, FILE *out);
#endif /* __SPL_CFG_H__ */
+14
View File
@@ -0,0 +1,14 @@
#ifndef __SPL_CFG_AST_H__
#define __SPL_CFG_AST_H__
#include "spl_cfg.h"
#include "spl_sema.h"
/* 从 AST/符号构建函数级调用图:
- FN 节点 user = def_id;
- CALL = 直接调用;
- FUNC_REF = 函数符号被当作值使用;
- HOST = @sap.* 等编译期 host 调用。 */
bool spl_cfg_ast_build(spl_cfg_t *cfg, spl_sema_t *sema, const spl_ast_ptr_vec_t *asts);
#endif /* __SPL_CFG_AST_H__ */
+11
View File
@@ -0,0 +1,11 @@
#ifndef __SPL_CFG_IR_H__
#define __SPL_CFG_IR_H__
#include "spl_cfg.h"
#include "spl_ir.h"
/* 从单个 IR 函数构建基本块控制流图;entry 返回入口 block 节点。 */
bool spl_cfg_ir_build(spl_cfg_t *cfg, const spl_ir_t *ir, spl_ir_func_ref_t fid,
spl_cfg_node_t *entry);
#endif /* __SPL_CFG_IR_H__ */
File renamed without changes.
@@ -1,7 +1,7 @@
#ifndef __SPL_DIAG_H__
#define __SPL_DIAG_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_dbg.h"
typedef enum {
+114
View File
@@ -0,0 +1,114 @@
#ifndef __SPL_EXEC_H__
#define __SPL_EXEC_H__
#include "spl_ir.h"
#include "spl_layout.h"
/* 编译期执行底座:unit/plan/cache/backend。
不依赖 SPL 语义;meta/macro/普通函数都只是可编译函数。 */
typedef enum {
SPL_EXEC_PHASE_MACRO,
SPL_EXEC_PHASE_SEMA,
SPL_EXEC_PHASE_META,
} spl_exec_phase_t;
typedef struct {
spl_ir_func_ref_t callee;
spl_exec_phase_t phase;
usize viewpoint;
usize specialization;
} spl_exec_unit_key_t;
typedef struct {
spl_ir_func_ref_t root;
spl_ir_func_ref_vec_t order; /* 只含 FN,callee 在前 */
} spl_exec_plan_t;
typedef struct {
spl_exec_unit_key_t key;
void *state; /* backend 私有 */
} spl_exec_unit_t;
typedef struct spl_exec spl_exec_t;
typedef struct {
bool (*ready)(spl_exec_t *exec, const spl_exec_unit_key_t *key);
bool (*compile)(spl_exec_t *exec, const spl_exec_unit_key_t *key, spl_exec_unit_t *out);
bool (*is_pure)(spl_exec_t *exec, const spl_exec_unit_key_t *key);
void *user;
} spl_exec_frontend_t;
typedef struct {
bool (*load)(spl_exec_t *exec, spl_exec_unit_t *unit);
bool (*invoke)(spl_exec_t *exec, spl_exec_unit_t *unit, const usize *args, usize nargs,
usize *out);
void (*unload)(spl_exec_t *exec, spl_exec_unit_t *unit);
void *user;
} spl_exec_backend_t;
typedef struct {
usize plan_builds;
usize plan_cache_hits;
usize unit_compiles;
usize unit_cache_hits;
usize invokes;
usize result_cache_hits;
} spl_exec_stats_t;
typedef enum {
SPL_EXEC_CAP_READ = 1u << 0,
SPL_EXEC_CAP_WRITE = 1u << 1,
SPL_EXEC_CAP_DIAG = 1u << 2,
SPL_EXEC_CAP_IO = 1u << 3,
} spl_exec_capability_t;
typedef struct {
spl_ir_type_id_t type;
usize size;
union {
uint64_t bits; /* 标量 */
struct {
usize off; /* VM 地址空间偏移;用于返回值回拷 */
void *ptr; /* 对应的宿主可写指针 */
} mem; /* 聚合 */
};
} spl_exec_value_t;
typedef bool (*spl_exec_host_fn)(spl_exec_t *exec, void *user, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret);
typedef struct {
const char *name;
usize capabilities;
spl_exec_host_fn fn;
void *user;
} spl_exec_host_t;
bool spl_exec_register_host(spl_exec_t *exec, const spl_exec_host_t *host);
const spl_exec_host_t *spl_exec_find_host(spl_exec_t *exec, const char *name);
spl_exec_t *spl_exec_create(spl_ir_t *ir, spl_layout_t *layout,
const spl_exec_frontend_t *frontend,
const spl_exec_backend_t *backend);
void spl_exec_destroy(spl_exec_t *exec);
void spl_exec_set_phase(spl_exec_t *exec, spl_exec_phase_t phase, usize viewpoint);
void spl_exec_bump_generation(spl_exec_t *exec);
usize spl_exec_generation(const spl_exec_t *exec);
const spl_exec_stats_t *spl_exec_stats_view(const spl_exec_t *exec);
const spl_exec_frontend_t *spl_exec_frontend_of(const spl_exec_t *exec);
const spl_exec_backend_t *spl_exec_backend_of(const spl_exec_t *exec);
const spl_ir_t *spl_exec_ir(const spl_exec_t *exec);
spl_layout_t *spl_exec_layout(const spl_exec_t *exec);
bool spl_exec_plan_build(spl_exec_t *exec, spl_ir_func_ref_t root, spl_exec_plan_t *out);
bool spl_exec_compile_plan(spl_exec_t *exec, spl_exec_plan_t *plan);
bool spl_exec_execute_plan(spl_exec_t *exec, const spl_exec_plan_t *plan, const usize *args,
usize nargs, usize *out);
void spl_exec_plan_drop(spl_exec_plan_t *plan);
/* 便捷入口:plan -> compile -> execute。 */
bool spl_exec_run(spl_exec_t *exec, spl_ir_func_ref_t root, const usize *args, usize nargs,
usize *out);
#endif /* __SPL_EXEC_H__ */
+17
View File
@@ -0,0 +1,17 @@
#ifndef __SPL_EXEC_FRONTEND_H__
#define __SPL_EXEC_FRONTEND_H__
#include "spl_exec.h"
#include "spl_ir.h"
#include "spl_ir_link.h"
#include "spl_sema.h"
typedef struct spl_exec_frontend_ctx spl_exec_frontend_ctx_t;
spl_exec_frontend_ctx_t *spl_exec_frontend_create(spl_sema_t *sema);
void spl_exec_frontend_destroy(spl_exec_frontend_ctx_t *ctx);
const spl_exec_frontend_t *spl_exec_frontend_vtable(spl_exec_frontend_ctx_t *ctx);
const spl_ir_t *spl_exec_frontend_ir(spl_exec_frontend_ctx_t *ctx);
spl_ir_link_t *spl_exec_frontend_link(spl_exec_frontend_ctx_t *ctx);
#endif /* __SPL_EXEC_FRONTEND_H__ */
+15
View File
@@ -0,0 +1,15 @@
#ifndef __SPL_EXEC_VM_H__
#define __SPL_EXEC_VM_H__
#include "spl_exec.h"
#include "spl_ir.h"
#include "spl_layout.h"
typedef struct spl_exec_vm_ctx spl_exec_vm_ctx_t;
spl_exec_vm_ctx_t *spl_exec_vm_create(const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr);
void spl_exec_vm_destroy(spl_exec_vm_ctx_t *ctx);
const spl_exec_backend_t *spl_exec_vm_vtable(spl_exec_vm_ctx_t *ctx);
#endif /* __SPL_EXEC_VM_H__ */
@@ -1,7 +1,7 @@
#ifndef __SPL_FOLD_H__
#define __SPL_FOLD_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
/* 通用 intrusive 哈希集合,对应 LLVM FoldingSet 的桶链部分。
- 节点表由调用方持有,节点自带 next 字段;
@@ -1,7 +1,7 @@
#ifndef __SPL_INTRIN_H__
#define __SPL_INTRIN_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_lang_type.h"
typedef enum {
@@ -54,7 +54,7 @@ typedef struct {
spl_intrin_t spl_intrin_lookup_call(const char *name);
spl_intrin_t spl_intrin_lookup_field(spl_lang_type_kind_t recv_kind, const char *field);
spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type_id_t tt);
spl_intrin_t spl_intrin_lookup_cast(spl_ir_type_table_t *type, spl_ir_type_id_t ft, spl_ir_type_id_t tt);
const spl_intrin_info_t *spl_intrin_info(spl_intrin_t kind);
+263 -142
View File
@@ -1,10 +1,10 @@
#ifndef __SPL_IR_H__
#define __SPL_IR_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_attr.h"
#include "spl_dbg.h"
#include "spl_type.h"
#include "spl_ir_type.h"
/* clang-format off */
#define SPL_IR_FN_TABLE \
@@ -39,14 +39,12 @@
X(case.int2float, V0, SPL_IR_CASE_INT2FLOAT) \
X(case.float2int, V0, SPL_IR_CASE_FLOAT2INT) \
X(mem.alloca, V0, SPL_IR_MEM_ALLOCA) \
X(mem.global_alloc, V0, SPL_IR_MEM_GLOBAL_ALLOC) \
X(mem.load, V0, SPL_IR_MEM_LOAD) \
X(mem.store, V0, SPL_IR_MEM_STORE) \
X(mem.offset, V0, SPL_IR_MEM_OFFSET) \
X(mem.field, V0, SPL_IR_MEM_FIELD_PTR) \
X(mem.copy, V0, SPL_IR_MEM_COPY) \
X(mem.set, V0, SPL_IR_MEM_SET) \
X(type.const, V0, SPL_IR_TYPE_CONST) \
X(type.bitsizeof, V0, SPL_IR_TYPE_BITSIZEOF) \
X(type.sizeof, V0, SPL_IR_TYPE_SIZEOF) \
X(type.alignof, V0, SPL_IR_TYPE_ALIGNOF) \
@@ -65,6 +63,7 @@
X(control.trap, V0, SPL_IR_CONTROL_TRAP) \
X(dbg.breakpoint, V0, SPL_IR_DBG_BREAKPOINT) \
X(dbg.panic, V0, SPL_IR_DBG_PANIC) \
/* clang-format on */
typedef enum {
#ifdef X
@@ -74,12 +73,129 @@ typedef enum {
SPL_IR_FN_TABLE
#undef X
} spl_ir_kind_t;
/* clang-format on */
typedef usize spl_ir_node_ref_t; /* 0 is error */
typedef VEC(spl_ir_node_ref_t) spl_ir_node_ref_vec_t;
typedef usize spl_ir_func_ref_t; /* 0 is error */
typedef VEC(spl_ir_func_ref_t) spl_ir_func_ref_vec_t;
/* 抽象机器的值:指令结果、常量或全局实体句柄。常量按 tid 的 SPL_IR_TYPE_* 解释:
* BOOL/INT(<=64) -> int_bits,FLOAT -> float_bits,FN -> fn,
* PTR -> 仅表示 null,其余需要去重的量 -> const_id。
* GLOBAL 表示模块级全局实体的地址,载荷是 global_id。 */
typedef enum {
SPL_IR_VALUE_INST,
SPL_IR_VALUE_CONST,
SPL_IR_VALUE_GLOBAL,
} spl_ir_value_kind_t;
typedef struct {
spl_ir_value_kind_t kind;
spl_ir_type_id_t tid; /* CONST 时有效;INST 必须为 0 */
union {
spl_ir_node_ref_t inst;
uint64_t int_bits;
double float_bits;
spl_ir_func_ref_t fn;
usize global_id;
usize const_id;
};
} spl_ir_value_t;
typedef VEC(spl_ir_value_t) spl_ir_value_vec_t;
static inline spl_ir_value_t spl_ir_value_none(void) {
spl_ir_value_t v = {0};
return v;
}
static inline bool spl_ir_value_is_none(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_INST && v.inst == 0;
}
static inline spl_ir_value_t spl_ir_value_inst(spl_ir_node_ref_t ref) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_INST;
v.inst = ref;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_int(spl_ir_type_id_t tid, uint64_t bits) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.int_bits = bits;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_float(spl_ir_type_id_t tid, double bits) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.float_bits = bits;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_fn(spl_ir_type_id_t tid, spl_ir_func_ref_t fn) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.fn = fn;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_null(spl_ir_type_id_t tid) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.global_id = 0;
return v;
}
static inline spl_ir_value_t spl_ir_value_global(spl_ir_type_id_t ptr_tid, usize gid) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_GLOBAL;
v.tid = ptr_tid;
v.global_id = gid;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_pool(spl_ir_type_id_t tid, usize const_id) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.const_id = const_id;
return v;
}
static inline spl_ir_node_ref_t spl_ir_value_inst_ref(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_INST ? v.inst : 0;
}
/* 常量池项:只放需要去重的量,标量直接内联在 Value 里。 */
typedef struct {
spl_ir_type_id_t tid;
union {
struct {
unsigned char *data;
usize len;
} bytes;
struct {
uint64_t *limbs;
usize count;
} big_int;
};
} spl_ir_const_t;
typedef VEC(spl_ir_const_t) spl_ir_const_vec_t;
/* 全局存储声明。引用是 PTR 常量(global_id),不是指令。 */
typedef struct {
const char *name;
spl_ir_type_id_t tid; /* 对象类型 */
spl_ir_value_t init;
bool readonly;
} spl_ir_global_t;
typedef VEC(spl_ir_global_t) spl_ir_global_vec_t;
#define SPL_ENUM_TAG_FIELD_IDX 0
@@ -88,115 +204,99 @@ typedef struct {
spl_dbg_node_t dbg;
spl_attr_id_vec_t attrs;
union {
spl_type_id_t tid;
spl_ir_type_id_t tid;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t left;
spl_ir_node_ref_t right;
spl_ir_type_id_t tid;
spl_ir_value_t left;
spl_ir_value_t right;
} arith;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t a;
spl_ir_node_ref_t b;
spl_ir_type_id_t tid;
spl_ir_value_t a;
spl_ir_value_t b;
} cmp;
struct {
spl_type_id_t from_tid;
spl_type_id_t to_tid;
spl_ir_node_ref_t val;
spl_ir_type_id_t from_tid;
spl_ir_type_id_t to_tid;
spl_ir_value_t val;
} cast;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t count;
spl_ir_type_id_t tid;
spl_ir_value_t count;
} mem_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t const_node;
} mem_global_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_type_id_t tid;
spl_ir_value_t ptr;
} mem_load;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t val;
spl_ir_type_id_t tid;
spl_ir_value_t ptr;
spl_ir_value_t val;
} mem_store;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t offset;
spl_ir_type_id_t tid;
spl_ir_value_t ptr;
spl_ir_value_t offset;
} mem_offset;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t agg;
spl_ir_type_id_t tid;
spl_ir_value_t agg;
usize field_idx;
} mem_field_ptr;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t src;
spl_ir_node_ref_t size;
spl_ir_type_id_t tid;
spl_ir_value_t dst;
spl_ir_value_t src;
spl_ir_value_t size;
} mem_copy;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t val;
spl_ir_node_ref_t size;
spl_ir_type_id_t tid;
spl_ir_value_t dst;
spl_ir_value_t val;
spl_ir_value_t size;
} mem_set;
struct {
spl_type_id_t tid;
union {
bool bool_lit;
void *ptr_lit;
usize int_lit;
double float_lit;
// const char *cstr_lit;
char ch_lit;
spl_ir_func_ref_t fn;
};
} type_const;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} bitsizeof;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} ir_sizeof;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} ir_alignof;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t field_idx;
spl_ir_type_id_t tid;
spl_ir_value_t field_idx;
} ir_offsetof;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} field_count;
struct {
spl_type_id_t tid;
spl_ir_node_ref_vec_t fields;
spl_ir_type_id_t tid;
spl_ir_value_vec_t fields;
} agg_construct;
struct {
spl_type_id_t tid;
spl_type_id_t field_tid;
spl_ir_type_id_t tid;
spl_ir_type_id_t field_tid;
usize field_idx;
spl_ir_node_ref_t val;
spl_ir_value_t val;
} agg_extract;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
usize field_idx;
spl_ir_node_ref_t agg;
spl_ir_node_ref_t field;
spl_ir_value_t agg;
spl_ir_value_t field;
} agg_insert;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t cond;
spl_ir_node_ref_t true_val;
spl_ir_node_ref_t false_val;
spl_ir_type_id_t tid;
spl_ir_value_t cond;
spl_ir_value_t true_val;
spl_ir_value_t false_val;
} control_select;
struct {
spl_ir_node_ref_t cond;
spl_ir_value_t cond;
spl_ir_node_ref_t true_label;
spl_ir_node_ref_t false_label;
} control_br;
@@ -204,17 +304,17 @@ typedef struct {
spl_ir_node_ref_t label;
} control_jmp;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t func;
spl_ir_node_ref_vec_t params;
spl_ir_type_id_t tid;
spl_ir_value_t func;
spl_ir_value_vec_t params;
} control_call;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t idx;
spl_ir_type_id_t tid;
spl_ir_value_t idx;
} control_param;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t val;
spl_ir_type_id_t tid;
spl_ir_value_t val;
} control_ret;
struct {
@@ -228,7 +328,8 @@ typedef VEC(spl_ir_node_t) spl_ir_node_vec_t;
typedef struct {
const char *name;
spl_attr_id_vec_t attrs;
spl_type_id_t fn_tid;
spl_ir_type_id_t fn_tid;
bool extern_fn;
spl_ir_node_vec_t nodes;
} spl_ir_func_t;
typedef VEC(spl_ir_func_t) spl_ir_func_vec_t;
@@ -244,10 +345,22 @@ typedef struct {
typedef VEC(spl_ir_fix_t) spl_ir_fix_vec_t;
typedef struct {
spl_ir_type_id_t tid;
const unsigned char *data;
usize len;
} spl_ir_const_key_t;
typedef struct {
spl_ir_type_table_t *types; /* 主 IR 拥有;meta IR 与主 IR 共享。 */
bool owns_types;
spl_ir_func_vec_t funcs;
spl_ir_const_vec_t consts;
spl_ir_global_vec_t globals;
MAP(spl_ir_const_key_t, usize) const_index;
} spl_ir_t;
void spl_ir_init(spl_ir_t *ir);
void spl_ir_init_shared(spl_ir_t *ir, spl_ir_type_table_t *types);
void spl_ir_drop(spl_ir_t *ir);
spl_ir_node_ref_t spl_ir_alloc_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
@@ -255,12 +368,23 @@ spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir);
spl_ir_node_t *spl_ir_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_node_ref_t node_id);
spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
spl_ir_const_t *spl_ir_const(spl_ir_t *ir, usize const_id);
/* INST 返回对应节点;CONST 返回 NULL。 */
spl_ir_node_t *spl_ir_value_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_value_t v);
/* 遍历节点里所有值型操作数(块标签除外)。 */
typedef void (*spl_ir_value_cb_t)(void *ud, spl_ir_value_t v);
void spl_ir_node_visit_values(spl_ir_node_t *n, spl_ir_value_cb_t cb, void *ud);
/* 一个函数体里出现的可静态发现的函数引用(直接调用与函数值常量)。
extern 函数不进入结果;结果按出现顺序去重。 */
void spl_ir_func_callees(spl_ir_t *ir, spl_ir_func_ref_t fn, spl_ir_func_ref_vec_t *out);
bool spl_ir_func_is_extern(spl_ir_t *ir, spl_ir_func_ref_t fn);
/* f 是否声明为 extern(属性表内名为 "extern" 的属性);命中返回该属性节点,否则 NULL。
供各后端复用,避免 "extern" 字符串判断散落多处。 */
spl_attr_node_t *spl_ir_fn_extern_attr(const spl_attr_t *attr, const spl_ir_func_t *f);
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty, const spl_attr_t *attr);
void spl_ir_dump(spl_ir_t *ir, const spl_attr_t *attr);
const char *spl_ir_kind_name(spl_ir_kind_t kind);
typedef struct {
@@ -310,12 +434,13 @@ typedef struct {
X(case_float2int, SPL_IR_CASE_FLOAT2INT)
/* clang-format on */
void spl_ir_builder_init(spl_ir_builder_t *b);
void spl_ir_builder_init_shared(spl_ir_builder_t *b, spl_ir_type_table_t *types);
void spl_ir_builder_drop(spl_ir_builder_t *b);
spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
spl_ir_type_id_t fn_tid);
spl_ir_func_ref_t spl_ir_builder_fn_reserve(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
spl_ir_type_id_t fn_tid);
void spl_ir_builder_fn_begin_at(spl_ir_builder_t *b, spl_ir_func_ref_t fid);
void spl_ir_builder_fn_end(spl_ir_builder_t *b);
@@ -323,102 +448,98 @@ usize spl_ir_builder_block_begin(spl_ir_builder_t *b);
void spl_ir_builder_block_end(spl_ir_builder_t *b);
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
spl_ir_node_ref_t left, spl_ir_node_ref_t right);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_ir_type_id_t tid, \
spl_ir_value_t left, spl_ir_value_t right);
SPL_IR_BIN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
spl_ir_node_ref_t val);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_ir_type_id_t tid, \
spl_ir_value_t val);
SPL_IR_UN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t tid, \
spl_ir_node_ref_t a, spl_ir_node_ref_t b);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t tid, \
spl_ir_value_t a, spl_ir_value_t b);
SPL_IR_CMP_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t from_tid, \
spl_type_id_t to_tid, spl_ir_node_ref_t val);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_ir_type_id_t from_tid, \
spl_ir_type_id_t to_tid, spl_ir_value_t val);
SPL_IR_CAST_TABLE
#undef X
/* memory */
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t count);
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t const_node);
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr);
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset);
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t agg, usize field_idx);
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
spl_ir_node_ref_t size);
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
spl_ir_node_ref_t size);
spl_ir_value_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t count);
spl_ir_value_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t ptr);
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t ptr, spl_ir_value_t val);
spl_ir_value_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t ptr, spl_ir_value_t offset);
spl_ir_value_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t agg,
usize field_idx);
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t src, spl_ir_value_t size);
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t val, spl_ir_value_t size);
/* type const */
/* 常量:标量内联;需要去重的量进常量池并返回 const_id。 */
spl_ir_node_ref_t spl_ir_builder_type_const_ptr(spl_ir_builder_t *b, spl_type_id_t tid, void *val);
spl_ir_node_ref_t spl_ir_builder_type_const_bool(spl_ir_builder_t *b, spl_type_id_t tid, bool val);
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val);
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
double val);
spl_ir_node_ref_t spl_ir_builder_type_const_bytes(spl_ir_builder_t *b, spl_type_id_t tid,
const void *data, usize len);
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val);
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_func_ref_t val);
spl_ir_value_t spl_ir_builder_const_int(spl_ir_type_id_t tid, uint64_t bits);
spl_ir_value_t spl_ir_builder_const_bool(spl_ir_type_id_t tid, bool val);
spl_ir_value_t spl_ir_builder_const_float(spl_ir_type_id_t tid, double val);
spl_ir_value_t spl_ir_builder_const_null(spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_const_fn(spl_ir_type_id_t tid, spl_ir_func_ref_t fn);
spl_ir_value_t spl_ir_builder_global_addr(spl_ir_type_id_t ptr_tid, usize global_id);
spl_ir_value_t spl_ir_builder_const_bytes(spl_ir_builder_t *b, spl_ir_type_id_t tid, const void *data,
usize len);
usize spl_ir_builder_global_declare(spl_ir_builder_t *b, const char *name, spl_ir_type_id_t tid,
spl_ir_value_t init, bool readonly);
/* type */
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t field_idx);
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t field_idx);
spl_ir_value_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_ir_type_id_t tid);
/* agg */
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_ir_type_id_t tid);
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
spl_ir_node_ref_t field);
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
spl_type_id_t field_tid, usize field_idx,
spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
spl_ir_node_ref_t agg, spl_ir_node_ref_t field);
spl_ir_value_t field);
spl_ir_value_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_type_id_t field_tid, usize field_idx,
spl_ir_value_t val);
spl_ir_value_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_ir_type_id_t tid, usize field_idx,
spl_ir_value_t agg, spl_ir_value_t field);
/* control */
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
spl_ir_node_ref_t false_val);
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond);
spl_ir_value_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t cond, spl_ir_value_t true_val,
spl_ir_value_t false_val);
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_value_t cond);
void spl_ir_builder_control_br_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref, usize true_block,
usize false_block);
spl_ir_node_ref_t spl_ir_builder_control_jmp(spl_ir_builder_t *b);
void spl_ir_builder_control_jmp_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref,
usize target_block);
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t func);
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t func);
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t call_node,
spl_ir_node_ref_t arg);
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t idx);
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t val);
spl_ir_value_t arg);
spl_ir_value_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t idx);
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t val);
spl_ir_node_ref_t spl_ir_builder_control_unreachable(spl_ir_builder_t *b);
spl_ir_node_ref_t spl_ir_builder_control_trap(spl_ir_builder_t *b);
@@ -4,13 +4,12 @@
#include "spl_attr.h"
#include "spl_ir.h"
#include "spl_layout.h"
#include "spl_type.h"
/* 生成结果的字节缓冲(C 源码文本);调用方负责初始化与释放。 */
typedef VEC(char) spl_ir2c_buf_t;
/* 生成 C99 源码追加到 out;返回 false 表示遇到不支持的结构(已在输出中就地标注)。 */
bool spl_ir2c_run(const spl_ir_t *ir, const spl_type_t *type, spl_layout_t *layout,
const spl_attr_t *attr, spl_ir2c_buf_t *out);
bool spl_ir2c_run(const spl_ir_t *ir, spl_layout_t *layout, const spl_attr_t *attr,
spl_ir2c_buf_t *out);
#endif /* __SPL_IR2C_H__ */
@@ -4,25 +4,25 @@
#include "spl_diag.h"
#include "spl_ir.h"
#include "spl_layout.h"
#include "spl_type.h"
#include "../stage0/spl_mcode.h"
#include "stage0/spl_mcode.h"
typedef MAP(spl_ir_func_ref_t, isize) spl_extern_idx_map_t;
typedef struct {
const spl_ir_t *ir;
const spl_type_t *type;
const spl_ir_type_table_t *type;
const spl_attr_t *attr;
spl_extern_idx_map_t extern_native;
VEC(isize) global_data_idx;
spl_prog_t prog;
spl_layout_t *layout; /* 借用 splc0 的 layout(size/align/offset 唯一来源) */
spl_diag_t *diag;
} spl_ir2vm_t;
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type,
spl_layout_t *layout, const spl_attr_t *attr);
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr);
void spl_ir2vm_drop(spl_ir2vm_t *ctx);
int spl_ir2vm_run(spl_ir2vm_t *ctx);
+18
View File
@@ -0,0 +1,18 @@
#ifndef __SPL_IR_LINK_H__
#define __SPL_IR_LINK_H__
#include "spl_ir.h"
#include "spl_sema.h"
/* 前端与 IR 的双向绑定:def/lang_type <-> ir_func/ir_type。
公开接口只暴露 IR 身份;前端结构体在实现文件里使用。 */
typedef struct spl_ir_link spl_ir_link_t;
spl_ir_link_t *spl_ir_link_create(spl_ir_t *ir, spl_sema_t *sema);
void spl_ir_link_destroy(spl_ir_link_t *link);
spl_ir_func_ref_t spl_ir_link_reserve_fn(spl_ir_link_t *link, usize def_id);
spl_ir_value_t spl_ir_link_fn_value(spl_ir_link_t *link, usize def_id);
bool spl_ir_link_def_of_fn(const spl_ir_link_t *link, spl_ir_func_ref_t fn, usize *out_def);
#endif /* __SPL_IR_LINK_H__ */
+121
View File
@@ -0,0 +1,121 @@
#ifndef __SPL_IR_TYPE_H__
#define __SPL_IR_TYPE_H__
#include "stage0/include/utils.h"
#include "spl_fold.h"
/* 类型 intern 用的哈希混合(FNV-1a 风格,顺序敏感)。
hash 只用于选择桶;相等判定始终由结构比较完成。 */
static inline usize spl_hash_mix(usize h, usize x) {
h ^= x;
h *= (usize)1099511628211ULL;
return h;
}
static inline usize spl_hash_mix_str(usize h, const char *s) {
if (!s) {
return spl_hash_mix(h, 0);
}
while (*s) {
h = spl_hash_mix(h, (usize)(unsigned char)*s);
s++;
}
return spl_hash_mix(h, 0); /* 终止符参与混合,避免名称拼接歧义 */
}
static inline usize spl_hash_seed(void) { return (usize)14695981039346656037ULL; }
typedef usize spl_ir_type_id_t;
typedef VEC(spl_ir_type_id_t) spl_ir_type_id_vec_t;
typedef enum {
SPL_IR_TYPE_ERROR,
SPL_IR_TYPE_UNIT,
SPL_IR_TYPE_BOOL,
SPL_IR_TYPE_INT,
SPL_IR_TYPE_FLOAT,
SPL_IR_TYPE_PTR,
SPL_IR_TYPE_ARRAY,
SPL_IR_TYPE_STRUCT,
SPL_IR_TYPE_UNION,
SPL_IR_TYPE_ENUM,
SPL_IR_TYPE_FN,
} spl_ir_type_kind_t;
typedef enum {
SPL_IR_TYPE_LAYOUT_AUTO,
SPL_IR_TYPE_LAYOUT_EXTERN_C,
SPL_IR_TYPE_LAYOUT_PACKED,
} spl_ir_type_layout_mode_t;
typedef struct {
spl_ir_type_layout_mode_t mode;
usize fixed_align_bits;
} spl_ir_type_layout_t;
typedef struct {
const char *name;
spl_ir_type_id_t type_id;
usize ast_node_ref;
} spl_ir_type_member_t;
typedef VEC(spl_ir_type_member_t) spl_ir_type_member_vec_t;
typedef struct {
spl_ir_type_kind_t kind;
spl_ir_type_layout_t layout;
union {
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
struct {
spl_ir_type_id_t pointee;
} ptr_type;
struct {
spl_ir_type_id_t element;
usize len;
} array_type;
struct {
spl_ir_type_member_vec_t variants;
spl_ir_type_id_t tag_type;
} agg_type;
struct {
spl_ir_type_id_vec_t params;
spl_ir_type_id_t ret;
} fn_type;
};
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_ir_type_node_t;
typedef VEC(spl_ir_type_node_t) spl_ir_type_node_vec_t;
typedef struct {
spl_ir_type_node_vec_t type_table;
spl_fold_t type_fold;
} spl_ir_type_table_t;
void spl_ir_type_table_init(spl_ir_type_table_t *type);
void spl_ir_type_table_drop(spl_ir_type_table_t *type);
spl_ir_type_node_t *spl_ir_type_node(const spl_ir_type_table_t *type, spl_ir_type_id_t id);
spl_ir_type_id_t spl_ir_type_push(spl_ir_type_table_t *type, spl_ir_type_node_t *type_node);
spl_ir_type_id_t spl_ir_type_builder_simple(spl_ir_type_table_t *type, spl_ir_type_kind_t kind);
spl_ir_type_id_t spl_ir_type_builder_int(spl_ir_type_table_t *type, usize bits, int is_signed);
spl_ir_type_id_t spl_ir_type_builder_float(spl_ir_type_table_t *type, usize bits);
spl_ir_type_id_t spl_ir_type_builder_ptr(spl_ir_type_table_t *type, spl_ir_type_id_t pointee);
spl_ir_type_id_t spl_ir_type_builder_array(spl_ir_type_table_t *type, spl_ir_type_id_t element, usize len);
spl_ir_type_id_t spl_ir_type_builder_fn(spl_ir_type_table_t *type, spl_ir_type_id_t ret, const spl_ir_type_id_t *params,
usize nparams);
spl_ir_type_id_t spl_ir_type_builder_agg(spl_ir_type_table_t *type, spl_ir_type_kind_t tk,
spl_ir_type_member_vec_t *variants, spl_ir_type_id_t tag_type,
spl_ir_type_layout_t layout);
void spl_ir_type_dump(spl_ir_type_table_t *type, spl_ir_type_id_t id);
const spl_ir_type_member_t *spl_ir_type_member(spl_ir_type_table_t *type, spl_ir_type_id_t tid, const char *name);
bool spl_ir_type_member_idx(spl_ir_type_table_t *type, spl_ir_type_id_t tid, const char *name, usize *out_idx);
#endif /* __SPL_IR_TYPE_H__ */
@@ -1,10 +1,10 @@
#ifndef __SPL_LANG_TYPE_H__
#define __SPL_LANG_TYPE_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_mpa.h"
#include "spl_type.h"
#include "spl_ir_type.h"
typedef usize spl_lang_type_id_t;
typedef VEC(spl_lang_type_id_t) spl_lang_type_id_vec_t;
@@ -39,9 +39,19 @@ typedef struct {
} spl_lang_method_t;
typedef VEC(spl_lang_method_t) spl_lang_method_vec_t;
typedef struct {
const char *name;
spl_lang_type_id_t type;
spl_def_id_t def_id;
usize ast_node_ref;
} spl_lang_member_t;
typedef VEC(spl_lang_member_t) spl_lang_member_vec_t;
typedef struct {
spl_lang_type_kind_t kind;
spl_type_id_t ir_type_id;
spl_ir_type_id_t ir_type_id;
spl_def_id_t def_id; /* 非 0 表示声明身份;合成类型为 0。 */
spl_lang_member_vec_t members;
spl_lang_method_vec_t methods;
union {
spl_lang_type_id_t elem;
@@ -50,6 +60,13 @@ typedef struct {
spl_lang_type_id_vec_t params;
spl_lang_type_id_t ret;
} fn;
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
} extra;
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_lang_type_node_t;
@@ -74,10 +91,18 @@ typedef enum {
SPL_DECL_ERROR,
} spl_decl_state_t;
/* 函数 def 的执行阶段;NORMAL 才进入运行期 IR。 */
typedef enum {
SPL_DEF_FN_NORMAL,
SPL_DEF_FN_META,
SPL_DEF_FN_MACRO,
} spl_def_fn_kind_t;
struct spl_ast;
typedef struct {
spl_def_node_kind_t kind;
spl_def_fn_kind_t fn_kind;
const char *name;
spl_dbg_node_t dbg_node;
spl_lang_type_id_t lang_id;
@@ -89,26 +114,31 @@ typedef struct {
typedef VEC(spl_def_node_t) spl_def_node_vec_t;
typedef struct {
spl_type_t ir;
spl_ir_type_table_t *ir_types; /* 借用 IR 模块的类型表,不拥有 */
spl_lang_type_vec_t lang_table;
spl_fold_t lang_fold;
spl_def_node_vec_t def_table;
} spl_lang_type_t;
void spl_lang_type_init(spl_lang_type_t *type);
void spl_lang_type_init(spl_lang_type_t *type, spl_ir_type_table_t *ir_types);
void spl_lang_type_drop(spl_lang_type_t *type);
spl_lang_type_node_t *spl_lang_type_node(const spl_lang_type_t *type, spl_lang_type_id_t id);
spl_lang_type_id_t spl_lang_node_push(spl_lang_type_t *type, spl_lang_type_node_t *node);
spl_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id);
spl_ir_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id);
const spl_lang_member_t *spl_lang_member_at(spl_lang_type_t *type, spl_lang_type_id_t agg,
usize idx);
bool spl_lang_member_idx(spl_lang_type_t *type, spl_lang_type_id_t agg, const char *name,
usize *out_idx);
/* 前向引用支持:reserve 一个 type_table 空槽位(kind=ERROR)作为身份锚点,
让 *Node / []Node 这类成员能拿到稳定 pointee;成员解析完后再调 define
把真实内容填进去。占位槽位**不写 type_fold**,不参与 hash-consing——
后续相同形状的类型走 spl_type_node_push 会生成独立 id,语义等价。 */
spl_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type);
void spl_lang_define_ir(spl_lang_type_t *type, spl_type_id_t id, spl_type_node_t *node);
后续相同形状的类型走 spl_ir_type_push 会生成独立 id,语义等价。 */
spl_ir_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type);
void spl_lang_define_ir(spl_lang_type_t *type, spl_ir_type_id_t id, spl_ir_type_node_t *node);
spl_lang_type_id_t spl_lang_make_error(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_infer(spl_lang_type_t *type);
@@ -129,6 +159,10 @@ spl_lang_type_id_t spl_lang_make_fn(spl_lang_type_t *type, spl_lang_type_id_t re
spl_lang_type_id_t spl_lang_make_aggregate(spl_lang_type_t *type, spl_lang_type_kind_t kind,
const char *name, const spl_lang_type_id_t *members,
usize nmembers);
spl_lang_type_id_t spl_lang_make_struct_named(spl_lang_type_t *type, const char *name,
const char *const *field_names,
const spl_lang_type_id_t *field_types,
usize nfields);
spl_lang_type_id_t spl_lang_make_varargs(spl_lang_type_t *type);
spl_lang_type_id_t spl_type_lookup_builtin(spl_lang_type_t *type, const char *name);
@@ -144,8 +178,10 @@ spl_def_id_t spl_def_alloc(spl_lang_type_t *type, spl_def_node_kind_t kind, cons
spl_dbg_node_t dbg, struct spl_ast *owner_ast, usize ast_node_ref);
void spl_def_resolve(spl_lang_type_t *type, spl_def_id_t id, spl_lang_type_id_t lang_id);
spl_def_node_t *spl_def_node(const spl_lang_type_t *type, spl_def_id_t id);
bool spl_def_is_compile_time(const spl_def_node_t *def);
bool spl_def_is_macro_fn(const spl_def_node_t *def);
spl_lang_type_id_t spl_def_get_lang_id(spl_lang_type_t *type, spl_def_id_t def_id);
spl_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id);
spl_ir_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id);
void spl_lang_type_dump(spl_lang_type_t *type, spl_lang_type_id_t id);
void spl_type_def_dump(spl_lang_type_t *type, spl_def_id_t id);
@@ -1,7 +1,7 @@
#ifndef __SPL_LAYOUT_H__
#define __SPL_LAYOUT_H__
#include "spl_type.h"
#include "spl_ir_type.h"
typedef struct {
usize size;
@@ -47,11 +47,11 @@ typedef struct {
void spl_layout_init(spl_layout_t *layout, spl_layout_target_t *target);
void spl_layout_drop(spl_layout_t *layout);
void spl_layout_resolve(spl_layout_t *layout, spl_type_t *type);
void spl_layout_resolve(spl_layout_t *layout, const spl_ir_type_table_t *type);
void spl_layout_add_scalar(spl_layout_t *layout, usize size, usize abi_align);
void spl_layout_add_ptr(spl_layout_t *layout, usize addr_space, usize size, usize align);
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_type_id_t id);
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_ir_type_id_t id);
#endif /* __SPL_LAYOUT_H__ */
File renamed without changes.
+29
View File
@@ -0,0 +1,29 @@
#ifndef __SPL_META_H__
#define __SPL_META_H__
#include "spl_sema.h"
#include "spl_sap.h"
typedef struct spl_meta spl_meta_t;
/* 编译期执行环境:把 meta/macro 函数编译到独立 IR,并默认用 VM 执行。
生命周期由调用方持有;内部只借用 sema 的 type/layout/attr/ns。 */
spl_meta_t *spl_meta_create(spl_sema_t *sema);
void spl_meta_destroy(spl_meta_t *meta);
/* 惰性编译所有编译期函数。失败返回 false,诊断已写入 sema->diag。 */
bool spl_meta_prepare(spl_meta_t *meta);
/* 按 def_id 调用编译期函数;args/out 是标量位模式。 */
bool spl_meta_invoke(spl_meta_t *meta, spl_def_id_t def_id, const usize *args, usize nargs,
usize *out);
/* sema 在 @ 调用点执行 meta fn,并把结果落回 n。 */
spl_lang_type_id_t spl_meta_eval_call(spl_sema_t *sema, spl_ast_node_t *n, spl_def_id_t def_id);
/* 语言绑定层暴露给 sema 的 SAP 能力。 */
spl_sap_t *spl_meta_sap(spl_meta_t *meta);
spl_sap_handle_t spl_meta_register_handle(spl_meta_t *meta, spl_ast_t *ast,
spl_ast_node_ref_t ref);
#endif /* __SPL_META_H__ */
+63
View File
@@ -0,0 +1,63 @@
#ifndef __SPL_MODULE_H__
#define __SPL_MODULE_H__
#include "spl_ast.h"
#include "spl_diag.h"
#include "spl_lang_type.h"
#include "spl_namespace.h"
typedef usize spl_module_id_t;
typedef enum {
SPL_MODULE_LOADING,
SPL_MODULE_LOADED,
SPL_MODULE_ERROR,
} spl_module_state_t;
typedef struct {
spl_module_id_t id;
char *name;
char *file_path;
spl_ast_t *ast;
spl_ast_node_ref_t container;
spl_module_id_t parent;
spl_def_id_t def_id;
spl_lang_type_id_t lang_id;
spl_ns_id_t ns;
spl_module_state_t state;
int sema_state;
} spl_module_t;
typedef struct {
VEC(spl_module_t) modules;
MAP(const char *, spl_module_id_t) by_name;
MAP(const char *, spl_module_id_t) by_path;
} spl_module_registry_t;
void spl_module_registry_init(spl_module_registry_t *reg);
void spl_module_registry_drop(spl_module_registry_t *reg);
/* 由文件路径推导默认模块名:去扩展名,非法标识符字符映射为 '_'。
结果写入 out,成功返回 true。 */
bool spl_module_name_from_path(const char *path, char *out, usize cap);
/* 读取文件头 mod 声明的点分路径;没有声明返回 NULL。 */
const char *spl_module_declared_name(spl_ast_t *ast);
/* 登记一个已解析的文件模块。declared_name 为空时使用文件名推导。
重名或重路径冲突返回 0 并写诊断。 */
spl_module_id_t spl_module_register(spl_module_registry_t *reg, spl_ast_t *ast,
const char *file_path, const char *declared_name,
spl_diag_t *diag);
spl_module_t *spl_module_get(spl_module_registry_t *reg, spl_module_id_t id);
spl_module_id_t spl_module_find_name(spl_module_registry_t *reg, const char *name);
spl_module_id_t spl_module_find_ast(spl_module_registry_t *reg, spl_ast_t *ast);
/* 返回模块名最后一个点分段的起点;名字中必须含该段。 */
const char *spl_module_last_segment(const char *name);
/* 返回模块 container_members 节点引用;无 AST 返回 0。 */
spl_ast_node_ref_t spl_module_container(spl_module_t *mod);
#endif /* __SPL_MODULE_H__ */
File renamed without changes.
+71
View File
@@ -0,0 +1,71 @@
#ifndef __SPL_NAMESPACE_H__
#define __SPL_NAMESPACE_H__
#include "spl_lang_type.h"
typedef usize spl_ns_id_t;
typedef enum {
SPL_SYMBOL_KIND_ERROR,
SPL_SYMBOL_KIND_VAR,
SPL_SYMBOL_KIND_MEMBER,
SPL_SYMBOL_KIND_FN,
SPL_SYMBOL_KIND_TYPE,
} spl_symbol_kind_t;
typedef struct {
const char *name;
spl_symbol_kind_t kind;
spl_def_id_t node;
} spl_symbol_t;
typedef VEC(const char *) spl_symbol_path_t;
typedef enum {
SPL_NS_ROOT,
SPL_NS_MODULE,
SPL_NS_AGGREGATE,
SPL_NS_FUNCTION,
SPL_NS_BLOCK,
} spl_ns_kind_t;
typedef struct {
spl_ns_id_t id;
spl_ns_id_t parent;
spl_ns_kind_t kind;
const char *name;
const char *qualified;
MAP(const char *, spl_symbol_t) symbols;
usize owner_kind;
usize owner_id;
} spl_ns_node_t;
typedef VEC(spl_ns_node_t) spl_ns_node_vec_t;
typedef struct {
spl_ns_node_vec_t nodes;
spl_ns_id_t root;
spl_ns_id_t current;
} spl_namespace_t;
void spl_ns_init(spl_namespace_t *ns);
void spl_ns_drop(spl_namespace_t *ns);
spl_ns_id_t spl_ns_root(spl_namespace_t *ns);
spl_ns_id_t spl_ns_create(spl_namespace_t *ns, spl_ns_id_t parent, spl_ns_kind_t kind,
const char *name, usize owner_kind, usize owner_id);
spl_ns_id_t spl_ns_alloc(spl_namespace_t *ns, spl_ns_kind_t kind, const char *name);
bool spl_ns_enter(spl_namespace_t *ns, spl_ns_id_t id);
bool spl_ns_leave(spl_namespace_t *ns);
bool spl_ns_insert(spl_namespace_t *ns, spl_ns_id_t id, spl_symbol_t symbol);
bool spl_ns_lookup(spl_namespace_t *ns, const char *name, spl_symbol_t *out);
bool spl_ns_lookup_local(spl_namespace_t *ns, spl_ns_id_t id, const char *name,
spl_symbol_t *out);
const char *spl_ns_qualified(spl_namespace_t *ns, spl_ns_id_t id);
bool spl_ns_symbol_qualified(spl_namespace_t *ns, spl_ns_id_t id, const char *local_name,
char *out, usize cap);
spl_ns_id_t spl_ns_child(spl_namespace_t *ns, spl_ns_id_t parent, const char *name);
#endif /* __SPL_NAMESPACE_H__ */
@@ -8,6 +8,7 @@ typedef struct spl_parser {
spl_ast_t *ast;
spl_diag_t *diag;
usize pos;
usize last_tok_line;
int failed;
int stop_agg;
usize error_count;
+53
View File
@@ -0,0 +1,53 @@
#ifndef __SPL_SAP_H__
#define __SPL_SAP_H__
#include "spl_ast.h"
#include "spl_exec.h"
#include "spl_lang_type.h"
/* SAP 句柄:0 = 空;其余是 spl_sap_t 句柄表下标。 */
typedef usize spl_sap_handle_t;
typedef struct spl_sap spl_sap_t;
typedef enum {
SPL_SAP_ARG_HANDLE,
SPL_SAP_ARG_USIZE,
SPL_SAP_ARG_VIEW,
} spl_sap_arg_kind_t;
typedef bool (*spl_sap_host_fn)(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret);
typedef struct {
const char *name;
usize nparams;
spl_sap_arg_kind_t params[4];
spl_sap_arg_kind_t ret;
spl_sap_host_fn host;
} spl_sap_op_t;
spl_sap_t *spl_sap_create(spl_lang_type_t *type);
void spl_sap_destroy(spl_sap_t *sap);
const spl_sap_op_t *spl_sap_lookup(const char *name);
const spl_sap_op_t *spl_sap_ops(usize *count);
spl_lang_type_id_t spl_sap_arg_type(spl_sap_t *sap, spl_sap_arg_kind_t kind);
spl_lang_type_id_t spl_sap_op_fn_type(spl_sap_t *sap, const spl_sap_op_t *op);
spl_lang_type_id_t spl_sap_meta_view_type(spl_sap_t *sap);
const char *const *spl_sap_meta_view_fields(usize *count);
/* AST kind 域由 SPL_AST_KIND_TABLE 自动生成。 */
usize spl_sap_kind_count(void);
const char *spl_sap_kind_name(usize kind);
spl_sap_handle_t spl_sap_handle_register(spl_sap_t *sap, spl_ast_t *ast,
spl_ast_node_ref_t ref);
bool spl_sap_handle_node(spl_sap_t *sap, spl_sap_handle_t handle, spl_ast_t **ast,
spl_ast_node_ref_t *ref);
bool spl_sap_bind(spl_exec_t *exec, spl_sap_t *sap);
bool spl_sap_type_lookup(spl_sap_t *sap, const char *name, spl_lang_type_id_t *out);
#endif /* __SPL_SAP_H__ */
@@ -4,11 +4,13 @@
#include "spl_ast.h"
#include "spl_attr.h"
#include "spl_diag.h"
#include "spl_ir.h"
#include "spl_lang_type.h"
#include "spl_layout.h"
#include "spl_mpa.h"
#include "spl_scope.h"
#include "spl_type.h"
#include "spl_module.h"
#include "spl_namespace.h"
#include "spl_ir_type.h"
typedef struct spl_module_loader spl_module_loader_t;
struct spl_module_loader {
@@ -19,27 +21,41 @@ struct spl_module_loader {
void *user;
};
struct spl_meta;
struct spl_ir_link;
typedef struct {
spl_ast_t *ast;
spl_lang_type_t *type;
spl_ir_t *ir; /* 当前 IR 程序;由 driver/meta 借用 */
struct spl_ir_link *ir_link; /* 前端 <-> IR 绑定;由 driver 借用 */
spl_layout_t *layout; /* 由 splc0 拥有并解析;sema 仅借用 */
spl_scope_t *scope;
spl_namespace_t *ns;
spl_symbol_t root;
spl_attr_t *attr;
struct spl_meta *meta; /* 编译期执行环境;可为 NULL(只做 sema 时) */
spl_lang_type_id_t current_aggregate_lang;
spl_lang_type_id_t current_fn_ret_tid;
spl_lang_type_id_t current_loop_break_tid;
spl_def_fn_kind_t current_fn_kind;
spl_symbol_path_t label_stack;
const spl_module_loader_t *loader;
spl_module_registry_t *modules;
spl_diag_t *diag;
} spl_sema_t;
void spl_sema_init(spl_sema_t *sema, spl_ast_t *ast, spl_lang_type_t *type,
spl_layout_t *layout, spl_scope_t *scope, spl_attr_t *attr);
spl_layout_t *layout, spl_namespace_t *ns, spl_attr_t *attr);
void spl_sema_drop(spl_sema_t *sema);
void spl_sema_run_module(spl_sema_t *sema, spl_ast_node_ref_t module_ref);
void spl_sema_run(spl_sema_t *sema);
void spl_sema_dump(spl_sema_t *sema);
/* 编译期执行器复用 sema 的表达式推断/转换;供 meta 模块调用。 */
spl_lang_type_id_t spl_sema_infer_expr(spl_sema_t *sema, spl_ast_node_ref_t ref);
spl_lang_type_id_t spl_sema_coerce_expr(spl_sema_t *sema, spl_ast_node_ref_t ref,
spl_lang_type_id_t expected);
spl_lang_type_id_t spl_sema_eval_decl(spl_sema_t *sema, spl_def_id_t def_id);
#endif /* __SPL_SEMA_H__ */
@@ -2,7 +2,7 @@
#ifndef __SPL_TOK_H__
#define __SPL_TOK_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
/* clang-format off */
#define KEYWORD_TABLE \
@@ -10,26 +10,26 @@
X(as , KW_AS , SPL_V0) \
X(bool , KW_BOOL , SPL_V0) \
X(break , KW_BREAK , SPL_V0) \
X(catch , KW_CATCH , SPL_V0) \
X(comptime , KW_COMPTIME , SPL_V0) \
X(const , KW_CONST , SPL_V0) \
X(continue , KW_CONTINUE , SPL_V0) \
X(defer , KW_DEFER , SPL_V0) \
X(else , KW_ELSE , SPL_V0) \
X(enum , KW_ENUM , SPL_V0) \
X(errdefer , KW_ERRDEFER , SPL_V0) \
X(false , KW_FALSE , SPL_V0) \
X(fn , KW_FN , SPL_V0) \
X(for , KW_FOR , SPL_V0) \
X(if , KW_IF , SPL_V0) \
X(import , KW_IMPORT , SPL_V0) \
X(loop , KW_LOOP , SPL_V0) \
X(macro , KW_MACRO , SPL_V0) \
X(match , KW_MATCH , SPL_V0) \
X(meta , KW_META , SPL_V0) \
X(mod , KW_MOD , SPL_V0) \
X(null , KW_NULL , SPL_V0) \
X(ret , KW_RET , SPL_V0) \
X(shape , KW_SHAPE , SPL_V0) \
X(struct , KW_STRUCT , SPL_V0) \
X(true , KW_TRUE , SPL_V0) \
X(try , KW_TRY , SPL_V0) \
X(type , KW_TYPE , SPL_V0) \
X(undefined , KW_UNDEFINED , SPL_V0) \
X(union , KW_UNION , SPL_V0) \
@@ -93,11 +93,9 @@
X(";" , TOK_SEMICOLON , SPL_V0 ) \
X("," , TOK_COMMA , SPL_V0 ) \
X(":" , TOK_COLON , SPL_V0 ) \
X(":=" , TOK_COLON_ASSIGN , SPL_V0 ) \
X("." , TOK_DOT , SPL_V0 ) \
X(".." , TOK_RANGE , SPL_V0 ) \
X("..." , TOK_ELLIPSIS , SPL_V0 ) \
X("?" , TOK_COND , SPL_V0 ) \
X(ident , TOK_IDENT , SPL_V0 ) \
X(int , TOK_INT_LITERAL , SPL_V0 ) \
X(float , TOK_FLOAT_LITERAL , SPL_V0 ) \
+1 -1
View File
@@ -3,7 +3,7 @@
/* 字节码(VM 层)优化 pass:输入输出都是 spl_prog_t,纯函数式、可开关。 */
#include "../stage0/spl_mcode.h"
#include "stage0/spl_mcode.h"
void spl_prog_peephole(spl_prog_t *prog);
void spl_prog_opt(spl_prog_t *prog);
+138 -128
View File
@@ -12,62 +12,86 @@ typedef struct {
spl_ir_t *ir;
spl_ir_func_ref_t caller;
spl_ir_func_ref_t callee;
spl_ir_node_ref_t shift; /* new = old + shift */
usize nparams;
spl_ir_node_ref_t *param_ref;
spl_ir_node_ref_t *param_arg;
/* callee Ref -> caller Value;Param 直接映射到实参,其余映射到克隆节点。 */
spl_ir_value_t *val_map;
usize val_map_size;
} inline_ctx_t;
static spl_ir_node_t *nd(spl_ir_t *ir, spl_ir_func_ref_t fid, spl_ir_node_ref_t ref) {
return spl_ir_node(ir, fid, ref);
}
/* ---- 引用重写(克隆体旧 ref -> 新 ref) ---- */
/* ---- 引用重写(克隆体旧 ref -> 新 value) ---- */
static spl_ir_node_ref_t rw(inline_ctx_t *c, spl_ir_node_ref_t r) {
if (r == 0)
return 0;
for (usize i = 0; i < c->nparams; i++)
if (c->param_ref[i] == r)
return c->param_arg[i];
return r + c->shift;
static spl_ir_value_t rw_value(inline_ctx_t *c, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST || v.inst == 0)
return v;
if (v.inst < c->val_map_size) {
spl_ir_value_t mapped = c->val_map[v.inst];
if (mapped.kind != SPL_IR_VALUE_INST || mapped.inst != 0)
return mapped;
}
Assert(false && "unmapped callee value ref");
return v;
}
typedef spl_ir_node_ref_t (*ref_xform_t)(void *ud, spl_ir_node_ref_t ref);
static spl_ir_node_ref_t rw_label(inline_ctx_t *c, spl_ir_node_ref_t ref) {
if (ref == 0)
return 0;
return spl_ir_value_inst_ref(rw_value(c, spl_ir_value_inst(ref)));
}
static void xform_vec(spl_ir_node_ref_vec_t *v, ref_xform_t fx, void *ud) {
typedef spl_ir_value_t (*value_xform_t)(void *ud, spl_ir_value_t v);
static void xform_value_vec(spl_ir_value_vec_t *v, value_xform_t fx, void *ud) {
for (usize i = 0; i < vec_size(*v); i++)
vec_at(*v, i) = fx(ud, vec_at(*v, i));
}
/* 对节点的所有「值引用」字段应用 fx;块标签字段不在此列(由调用方单独处理)。 */
static void xform_node_value_refs(spl_ir_node_t *n, ref_xform_t fx, void *ud) {
/* 对节点的所有「值」字段应用 fx;块标签字段由 rw_node 单独处理。 */
static void xform_node_values(spl_ir_node_t *n, value_xform_t fx, void *ud) {
switch (n->kind) {
case SPL_IR_ARITH_ADD: case SPL_IR_ARITH_SUB: case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV: case SPL_IR_ARITH_REM: case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS: case SPL_IR_ARITH_AND: case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR: case SPL_IR_ARITH_SHL: case SPL_IR_ARITH_SHR:
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV:
case SPL_IR_ARITH_REM:
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_AND:
case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR:
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
case SPL_IR_ARITH_NOT:
n->arith.left = fx(ud, n->arith.left);
n->arith.right = fx(ud, n->arith.right);
break;
case SPL_IR_CMP_EQ: case SPL_IR_CMP_NE: case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE: case SPL_IR_CMP_GT: case SPL_IR_CMP_GE:
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE:
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
n->cmp.a = fx(ud, n->cmp.a);
n->cmp.b = fx(ud, n->cmp.b);
break;
case SPL_IR_CAST_TRUNC: case SPL_IR_CAST_ZEXT: case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT: case SPL_IR_CAST_FTRUNC: case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT: case SPL_IR_CAST_INT2PTR: case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT: case SPL_IR_CASE_FLOAT2INT:
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT:
case SPL_IR_CAST_FTRUNC:
case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT:
case SPL_IR_CAST_INT2PTR:
case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
n->cast.val = fx(ud, n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
n->mem_alloc.count = fx(ud, n->mem_alloc.count);
break;
case SPL_IR_MEM_GLOBAL_ALLOC:
n->mem_global_alloc.const_node = fx(ud, n->mem_global_alloc.const_node);
break;
case SPL_IR_MEM_LOAD:
n->mem_load.ptr = fx(ud, n->mem_load.ptr);
break;
@@ -96,7 +120,7 @@ static void xform_node_value_refs(spl_ir_node_t *n, ref_xform_t fx, void *ud) {
n->ir_offsetof.field_idx = fx(ud, n->ir_offsetof.field_idx);
break;
case SPL_IR_AGG_CONSTRUCT:
xform_vec(&n->agg_construct.fields, fx, ud);
xform_value_vec(&n->agg_construct.fields, fx, ud);
break;
case SPL_IR_AGG_EXTRACT:
n->agg_extract.val = fx(ud, n->agg_extract.val);
@@ -121,27 +145,24 @@ static void xform_node_value_refs(spl_ir_node_t *n, ref_xform_t fx, void *ud) {
break;
case SPL_IR_CONTROL_CALL:
n->control_call.func = fx(ud, n->control_call.func);
xform_vec(&n->control_call.params, fx, ud);
xform_value_vec(&n->control_call.params, fx, ud);
break;
default:
break;
}
}
static spl_ir_node_ref_t rw_thunk(void *ud, spl_ir_node_ref_t r) {
return rw((inline_ctx_t *)ud, r);
}
static spl_ir_value_t rw_thunk(void *ud, spl_ir_value_t v) { return rw_value((inline_ctx_t *)ud, v); }
/* 克隆体旧 ref -> 新 ref;块标签也参与平移。 */
static void rw_node(inline_ctx_t *c, spl_ir_node_t *n) {
xform_node_value_refs(n, rw_thunk, c);
xform_node_values(n, rw_thunk, c);
switch (n->kind) {
case SPL_IR_CONTROL_BR:
n->control_br.true_label = rw(c, n->control_br.true_label);
n->control_br.false_label = rw(c, n->control_br.false_label);
n->control_br.true_label = rw_label(c, n->control_br.true_label);
n->control_br.false_label = rw_label(c, n->control_br.false_label);
break;
case SPL_IR_CONTROL_JMP:
n->control_jmp.label = rw(c, n->control_jmp.label);
n->control_jmp.label = rw_label(c, n->control_jmp.label);
break;
default:
break;
@@ -166,6 +187,22 @@ static void clone_ref_vec(spl_ir_node_ref_vec_t *dst, const spl_ir_node_ref_vec_
dst->cap = n;
}
static void clone_value_vec(spl_ir_value_vec_t *dst, const spl_ir_value_vec_t *src) {
dst->size = 0;
dst->cap = 0;
dst->data = NULL;
usize n = vec_size(*src);
if (n == 0)
return;
spl_ir_value_t *p = (spl_ir_value_t *)malloc(sizeof(spl_ir_value_t) * n);
if (!p)
return;
memcpy(p, src->data, sizeof(spl_ir_value_t) * n);
dst->data = p;
dst->size = n;
dst->cap = n;
}
static void clone_node(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t dst_ref,
const spl_ir_node_t *src) {
spl_ir_node_t *dst = nd(ir, caller, dst_ref);
@@ -177,18 +214,20 @@ static void clone_node(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
clone_ref_vec((spl_ir_node_ref_vec_t *)&dst->attrs,
(const spl_ir_node_ref_vec_t *)&src->attrs);
if (src->kind == SPL_IR_AGG_CONSTRUCT)
clone_ref_vec(&dst->agg_construct.fields, &src->agg_construct.fields);
clone_value_vec(&dst->agg_construct.fields, &src->agg_construct.fields);
else if (src->kind == SPL_IR_CONTROL_CALL)
clone_ref_vec(&dst->control_call.params, &src->control_call.params);
clone_value_vec(&dst->control_call.params, &src->control_call.params);
}
/* ---- 调用图可达性(防环) ---- */
static spl_ir_func_ref_t call_callee(spl_ir_t *ir, spl_ir_func_ref_t fid, spl_ir_node_t *call) {
spl_ir_node_t *fn = nd(ir, fid, call->control_call.func);
if (!fn || fn->kind != SPL_IR_TYPE_CONST)
(void)ir;
(void)fid;
spl_ir_value_t fn = call->control_call.func;
if (fn.kind != SPL_IR_VALUE_CONST)
return 0;
return fn->type_const.fn;
return fn.fn;
}
static bool reaches(spl_ir_t *ir, spl_ir_func_ref_t from, spl_ir_func_ref_t target,
@@ -234,38 +273,27 @@ static bool reaches_succ(spl_ir_t *ir, spl_ir_func_ref_t from, spl_ir_func_ref_t
typedef struct {
spl_ir_node_ref_t clone_ref;
spl_ir_node_ref_t val;
spl_ir_value_t val;
} ret_rec_t;
static bool param_index(spl_ir_t *ir, spl_ir_func_ref_t fid, spl_ir_node_t *p, usize *out) {
spl_ir_node_t *idx = nd(ir, fid, p->control_param.idx);
if (!idx || idx->kind != SPL_IR_TYPE_CONST)
static bool param_index(spl_ir_node_t *p, usize *out) {
spl_ir_value_t idx = p->control_param.idx;
if (idx.kind != SPL_IR_VALUE_CONST)
return false;
*out = idx->type_const.int_lit;
*out = (usize)idx.int_bits;
return true;
}
static spl_ir_node_ref_t find_const_src(spl_ir_t *ir, spl_ir_func_ref_t fid) {
spl_ir_func_t *f = spl_ir_func(ir, fid);
if (!f)
return 0;
for (usize i = 1; i < vec_size(f->nodes); i++) {
spl_ir_node_t *x = nd(ir, fid, i);
if (x && x->kind == SPL_IR_TYPE_CONST)
return i;
}
return 0;
}
/* 值引用定点替换:等于 ci 的改为 ret_new。 */
typedef struct {
spl_ir_node_ref_t ci;
spl_ir_node_ref_t ret_new;
spl_ir_value_t ret_new;
} replace_one_t;
static spl_ir_node_ref_t replace_one(void *ud, spl_ir_node_ref_t r) {
static spl_ir_value_t replace_one(void *ud, spl_ir_value_t v) {
replace_one_t *p = ud;
return r == p->ci ? p->ret_new : r;
if (v.kind == SPL_IR_VALUE_INST && v.inst == p->ci)
return p->ret_new;
return v;
}
static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t ci,
@@ -285,7 +313,6 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
usize nargs = vec_size(call->control_call.params);
/* 统计参数与返回,分配动态映射。 */
usize cnodes = vec_size(calf->nodes);
usize in_params = 0;
usize in_rets = 0;
@@ -306,100 +333,85 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
c.ir = ir;
c.caller = caller;
c.callee = callee;
c.nparams = in_params;
c.param_ref = (spl_ir_node_ref_t *)malloc(sizeof(spl_ir_node_ref_t) * (in_params ? in_params : 1));
c.param_arg = (spl_ir_node_ref_t *)malloc(sizeof(spl_ir_node_ref_t) * (in_params ? in_params : 1));
c.val_map_size = cnodes;
c.val_map = (spl_ir_value_t *)calloc(cnodes ? cnodes : 1, sizeof(spl_ir_value_t));
ret_rec_t *recs = (ret_rec_t *)malloc(sizeof(ret_rec_t) * (in_rets ? in_rets : 1));
if (!c.param_ref || !c.param_arg || !recs) {
free(c.param_ref);
free(c.param_arg);
if (!c.val_map || !recs) {
free(c.val_map);
free(recs);
return false;
}
spl_type_id_t ret_tid = call->control_call.tid;
bool ok = true;
/* 参数映射(旧 ref -> 实参 ref)。 */
usize pi = 0;
for (usize i = 1; i < cnodes; i++) {
/* 参数:直接映射到实参 Value。 */
for (usize i = 1; i < cnodes && ok; i++) {
spl_ir_node_t *x = nd(ir, callee, i);
if (x && x->kind == SPL_IR_CONTROL_PARAM) {
usize idx = 0;
if (!param_index(ir, callee, x, &idx) || idx >= nargs) {
free(c.param_ref);
free(c.param_arg);
if (!param_index(x, &idx) || idx >= nargs) {
ok = false;
break;
}
c.val_map[i] = vec_at(call->control_call.params, idx);
}
}
if (!ok) {
free(c.val_map);
free(recs);
return false;
}
c.param_ref[pi] = i;
c.param_arg[pi] = vec_at(call->control_call.params, idx);
pi++;
}
}
bool has_val = false;
for (usize i = 1; i < cnodes; i++) {
spl_ir_node_t *x = nd(ir, callee, i);
if (x && x->kind == SPL_IR_CONTROL_RET && x->control_ret.val != 0)
if (x && x->kind == SPL_IR_CONTROL_RET && !spl_ir_value_is_none(x->control_ret.val))
has_val = true;
}
spl_ir_node_ref_t const_src = find_const_src(ir, callee);
if (has_val && const_src == 0) {
free(c.param_ref);
free(c.param_arg);
free(recs);
return false;
}
/* 释放调用点原 params(随后 ci 改为 jmp) */
spl_ir_type_id_t ret_tid = call->control_call.tid;
/* 释放调用点原 params(实参已映射进 val_map)。 */
vec_free(call->control_call.params);
/* 克隆体入口前置:常量 1 + ret 槽 */
spl_ir_node_ref_t body_entry = 0;
spl_ir_node_ref_t slot_ref = 0;
if (has_val) {
spl_ir_node_ref_t c_ref = spl_ir_alloc_node(ir, caller);
clone_node(ir, caller, c_ref, nd(ir, callee, const_src));
spl_ir_node_t *cn = nd(ir, caller, c_ref);
cn->kind = SPL_IR_TYPE_CONST;
cn->type_const.int_lit = 1;
slot_ref = spl_ir_alloc_node(ir, caller);
spl_ir_node_t *sn = nd(ir, caller, slot_ref);
memset(sn, 0, sizeof(*sn));
sn->kind = SPL_IR_MEM_ALLOCA;
sn->mem_alloc.tid = ret_tid;
sn->mem_alloc.count = c_ref;
body_entry = c_ref;
sn->mem_alloc.count = spl_ir_value_const_int(0, 1);
body_entry = slot_ref;
}
c.shift = vec_size(cf->nodes) - 1;
if (!has_val)
body_entry = vec_size(cf->nodes);
/* 克隆体 */
usize nrec = 0;
/* 第一遍:为非 Param 节点分配目标下标,保证前向块标签可解析。 */
for (usize i = 1; i < cnodes; i++) {
spl_ir_node_t *src = nd(ir, callee, i);
if (!src || src->kind == SPL_IR_CONTROL_PARAM)
continue;
spl_ir_node_ref_t dst_ref = spl_ir_alloc_node(ir, caller);
if (dst_ref == 0) {
free(c.param_ref);
free(c.param_arg);
free(c.val_map);
free(recs);
return false;
}
c.val_map[i] = spl_ir_value_inst(dst_ref);
if (body_entry == 0)
body_entry = dst_ref;
}
/* 第二遍:复制内容、重写引用,并把 ret 改成 jmp 占位。 */
usize nrec = 0;
for (usize i = 1; i < cnodes; i++) {
spl_ir_node_t *src = nd(ir, callee, i);
if (!src || src->kind == SPL_IR_CONTROL_PARAM)
continue;
spl_ir_node_ref_t dst_ref = spl_ir_value_inst_ref(c.val_map[i]);
clone_node(ir, caller, dst_ref, src);
rw_node(&c, nd(ir, caller, dst_ref));
spl_ir_node_t *x = nd(ir, caller, dst_ref);
/* 克隆进来的 Param 使用处已替换为实参,节点本身不能留在调用者里
* 改变其参数个数;退化为无害常量。 */
if (src->kind == SPL_IR_CONTROL_PARAM) {
x->kind = SPL_IR_TYPE_CONST;
x->type_const.tid = 0;
x->type_const.int_lit = 0;
continue;
}
if (x->kind == SPL_IR_CONTROL_RET) {
recs[nrec].clone_ref = dst_ref;
recs[nrec].val = x->control_ret.val;
@@ -409,16 +421,15 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
}
}
spl_ir_node_ref_t ret_new = 0;
spl_ir_value_t ret_new = spl_ir_value_none();
if (has_val) {
spl_ir_node_ref_t join = spl_ir_alloc_node(ir, caller);
spl_ir_node_t *jn = nd(ir, caller, join);
memset(jn, 0, sizeof(*jn));
jn->kind = SPL_IR_MEM_LOAD;
jn->mem_load.tid = ret_tid;
jn->mem_load.ptr = slot_ref;
jn->mem_load.ptr = spl_ir_value_inst(slot_ref);
/* join 之后跳回调用点的后继(原代码此处靠 fallthrough)。 */
spl_ir_node_ref_t jc = spl_ir_alloc_node(ir, caller);
spl_ir_node_t *jcn = nd(ir, caller, jc);
memset(jcn, 0, sizeof(*jcn));
@@ -431,7 +442,7 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
memset(stn, 0, sizeof(*stn));
stn->kind = SPL_IR_MEM_STORE;
stn->mem_store.tid = ret_tid;
stn->mem_store.ptr = slot_ref;
stn->mem_store.ptr = spl_ir_value_inst(slot_ref);
stn->mem_store.val = recs[k].val;
spl_ir_node_ref_t jr = spl_ir_alloc_node(ir, caller);
@@ -443,7 +454,7 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
spl_ir_node_t *rn = nd(ir, caller, recs[k].clone_ref);
rn->control_jmp.label = st;
}
ret_new = join;
ret_new = spl_ir_value_inst(join);
} else {
for (usize k = 0; k < nrec; k++) {
spl_ir_node_t *rn = nd(ir, caller, recs[k].clone_ref);
@@ -461,11 +472,10 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
for (usize j = 1; j < orig_len; j++) {
spl_ir_node_t *x = nd(ir, caller, j);
if (x)
xform_node_value_refs(x, replace_one, &rep);
xform_node_values(x, replace_one, &rep);
}
free(c.param_ref);
free(c.param_arg);
free(c.val_map);
free(recs);
return true;
}
@@ -490,7 +500,7 @@ static int opt_function(spl_ir_t *ir, spl_ir_func_ref_t fid, const spl_attr_t *a
if (!func_has_attr(attr, calf, "inline") || func_has_attr(attr, calf, "noinline"))
continue;
/* extern 是占位体,绝不能内联。 */
if (func_has_attr(attr, calf, "extern"))
if (calf->extern_fn || func_has_attr(attr, calf, "extern"))
continue;
/* 防环:callee 传递可达 caller 时拒绝(覆盖直接/间接互递归)。 */
memset(mark, 0, nfuncs);
+441 -197
View File
@@ -1,4 +1,6 @@
#include "spl_ir.h"
#include <stdlib.h>
#include <string.h>
const char *spl_ir_kind_name(spl_ir_kind_t kind) {
static const char *const names[] = {
@@ -11,9 +13,44 @@ const char *spl_ir_kind_name(spl_ir_kind_t kind) {
return "?";
}
static usize const_key_hash(spl_ir_const_key_t k) {
usize h = MAP_HASH_INT((usize)k.tid);
for (usize i = 0; i < k.len; ++i)
h = ((h << 5) + h) ^ (usize)k.data[i];
return h;
}
static int const_key_cmp(spl_ir_const_key_t a, spl_ir_const_key_t b) {
if (a.tid != b.tid || a.len != b.len)
return 1;
if (a.len == 0)
return 0;
return memcmp(a.data, b.data, a.len);
}
void spl_ir_init(spl_ir_t *ir) {
ir->types = calloc(1, sizeof(*ir->types));
spl_ir_type_table_init(ir->types);
ir->owns_types = true;
vec_init(ir->funcs);
vec_push(ir->funcs, (spl_ir_func_t){0});
vec_init(ir->consts);
vec_push(ir->consts, (spl_ir_const_t){0});
vec_init(ir->globals);
vec_push(ir->globals, (spl_ir_global_t){0});
map_init(ir->const_index, const_key_hash, const_key_cmp);
}
void spl_ir_init_shared(spl_ir_t *ir, spl_ir_type_table_t *types) {
ir->types = types;
ir->owns_types = false;
vec_init(ir->funcs);
vec_push(ir->funcs, (spl_ir_func_t){0});
vec_init(ir->consts);
vec_push(ir->consts, (spl_ir_const_t){0});
vec_init(ir->globals);
vec_push(ir->globals, (spl_ir_global_t){0});
map_init(ir->const_index, const_key_hash, const_key_cmp);
}
static void node_drop_vecs(spl_ir_node_t *n) {
@@ -43,8 +80,24 @@ void spl_ir_drop(spl_ir_t *ir) {
}
vec_free(f->attrs);
vec_free(f->nodes);
free((char *)f->name);
}
vec_free(ir->funcs);
for (usize i = 1; i < vec_size(ir->consts); ++i) {
spl_ir_const_t *c = &vec_at(ir->consts, i);
/* 当前池里只有字节块;大整数分支尚未产生,避免 union 双重释放。 */
free(c->bytes.data);
}
vec_free(ir->consts);
for (usize i = 1; i < vec_size(ir->globals); ++i)
free((char *)vec_at(ir->globals, i).name);
vec_free(ir->globals);
map_free(ir->const_index);
if (ir->owns_types && ir->types) {
spl_ir_type_table_drop(ir->types);
free(ir->types);
}
ir->types = NULL;
}
spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir) {
@@ -86,6 +139,168 @@ spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id) {
return &vec_at(ir->funcs, fn_id);
}
spl_ir_const_t *spl_ir_const(spl_ir_t *ir, usize const_id) {
if (!ir || const_id == 0 || const_id >= vec_size(ir->consts))
return NULL;
return &vec_at(ir->consts, const_id);
}
spl_ir_node_t *spl_ir_value_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST || v.inst == 0)
return NULL;
return spl_ir_node(ir, fn_id, v.inst);
}
void spl_ir_node_visit_values(spl_ir_node_t *n, spl_ir_value_cb_t cb, void *ud) {
if (!n || !cb)
return;
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV:
case SPL_IR_ARITH_REM:
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_AND:
case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR:
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
case SPL_IR_ARITH_NOT:
cb(ud, n->arith.left);
cb(ud, n->arith.right);
break;
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE:
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
cb(ud, n->cmp.a);
cb(ud, n->cmp.b);
break;
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT:
case SPL_IR_CAST_FTRUNC:
case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT:
case SPL_IR_CAST_INT2PTR:
case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
cb(ud, n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
cb(ud, n->mem_alloc.count);
break;
case SPL_IR_MEM_LOAD:
cb(ud, n->mem_load.ptr);
break;
case SPL_IR_MEM_STORE:
cb(ud, n->mem_store.ptr);
cb(ud, n->mem_store.val);
break;
case SPL_IR_MEM_OFFSET:
cb(ud, n->mem_offset.ptr);
cb(ud, n->mem_offset.offset);
break;
case SPL_IR_MEM_FIELD_PTR:
cb(ud, n->mem_field_ptr.agg);
break;
case SPL_IR_MEM_COPY:
cb(ud, n->mem_copy.dst);
cb(ud, n->mem_copy.src);
cb(ud, n->mem_copy.size);
break;
case SPL_IR_MEM_SET:
cb(ud, n->mem_set.dst);
cb(ud, n->mem_set.val);
cb(ud, n->mem_set.size);
break;
case SPL_IR_TYPE_OFFSETOF:
cb(ud, n->ir_offsetof.field_idx);
break;
case SPL_IR_AGG_CONSTRUCT:
for (usize i = 0; i < vec_size(n->agg_construct.fields); ++i)
cb(ud, vec_at(n->agg_construct.fields, i));
break;
case SPL_IR_AGG_EXTRACT:
cb(ud, n->agg_extract.val);
break;
case SPL_IR_AGG_INSERT:
cb(ud, n->agg_insert.agg);
cb(ud, n->agg_insert.field);
break;
case SPL_IR_CONTROL_SELECT:
cb(ud, n->control_select.cond);
cb(ud, n->control_select.true_val);
cb(ud, n->control_select.false_val);
break;
case SPL_IR_CONTROL_BR:
cb(ud, n->control_br.cond);
break;
case SPL_IR_CONTROL_PARAM:
cb(ud, n->control_param.idx);
break;
case SPL_IR_CONTROL_RET:
cb(ud, n->control_ret.val);
break;
case SPL_IR_CONTROL_CALL:
cb(ud, n->control_call.func);
for (usize i = 0; i < vec_size(n->control_call.params); ++i)
cb(ud, vec_at(n->control_call.params, i));
break;
default:
break;
}
}
typedef struct {
spl_ir_t *ir;
spl_ir_func_ref_vec_t *out;
} spl_ir_callee_scan_t;
static bool callee_contains(const spl_ir_func_ref_vec_t *out, spl_ir_func_ref_t fn) {
for (usize i = 0; i < vec_size(*out); ++i) {
if (vec_at(*out, i) == fn)
return true;
}
return false;
}
static void callee_scan_value(void *ud, spl_ir_value_t v) {
spl_ir_callee_scan_t *scan = (spl_ir_callee_scan_t *)ud;
if (v.kind != SPL_IR_VALUE_CONST || !v.tid || !v.fn)
return;
spl_ir_type_node_t *tn = spl_ir_type_node(scan->ir->types, v.tid);
if (!tn || tn->kind != SPL_IR_TYPE_FN)
return;
spl_ir_func_t *callee = spl_ir_func(scan->ir, v.fn);
if (!callee || callee->extern_fn)
return;
if (!callee_contains(scan->out, v.fn))
vec_push(*scan->out, v.fn);
}
bool spl_ir_func_is_extern(spl_ir_t *ir, spl_ir_func_ref_t fn) {
spl_ir_func_t *f = spl_ir_func(ir, fn);
return f && f->extern_fn;
}
void spl_ir_func_callees(spl_ir_t *ir, spl_ir_func_ref_t fn, spl_ir_func_ref_vec_t *out) {
if (!ir || !out)
return;
spl_ir_func_t *f = spl_ir_func(ir, fn);
if (!f)
return;
spl_ir_callee_scan_t scan = {.ir = ir, .out = out};
for (usize i = 1; i < vec_size(f->nodes); ++i)
spl_ir_node_visit_values(&vec_at(f->nodes, i), callee_scan_value, &scan);
}
spl_attr_node_t *spl_ir_fn_extern_attr(const spl_attr_t *attr, const spl_ir_func_t *f) {
if (!attr || !f)
return NULL;
@@ -97,9 +312,9 @@ spl_attr_node_t *spl_ir_fn_extern_attr(const spl_attr_t *attr, const spl_ir_func
return NULL;
}
static inline void ir_dump_type(const spl_type_t *ty, spl_type_id_t tid) {
static inline void ir_dump_type(const spl_ir_type_table_t *ty, spl_ir_type_id_t tid) {
printf("(");
spl_type_pure_dump((spl_type_t *)ty, tid);
spl_ir_type_dump((spl_ir_type_table_t *)ty, tid);
printf(")");
}
@@ -111,7 +326,31 @@ static inline void ir_dump_ref(spl_ir_node_ref_t ref) {
}
}
static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
static inline void ir_dump_value(const spl_ir_type_table_t *ty, spl_ir_value_t v) {
if (v.kind == SPL_IR_VALUE_INST) {
ir_dump_ref(v.inst);
return;
}
if (v.kind == SPL_IR_VALUE_GLOBAL) {
printf(" g#%zu", v.global_id);
return;
}
spl_ir_type_node_t *t = spl_ir_type_node((spl_ir_type_table_t *)ty, v.tid);
if (t && t->kind == SPL_IR_TYPE_FLOAT)
printf(" float=%f", v.float_bits);
else if (t && t->kind == SPL_IR_TYPE_FN)
printf(" fn#%zu", v.fn);
else if (t && t->kind == SPL_IR_TYPE_PTR)
printf(" null");
else if (t && t->kind == SPL_IR_TYPE_INT && t->int_type.bits == 8)
printf(" char='%c'", (char)v.int_bits);
else if (t && (t->kind == SPL_IR_TYPE_ARRAY))
printf(" c#%zu", v.const_id);
else
printf(" int=%llu", (unsigned long long)v.int_bits);
}
static void ir_dump_node(const spl_ir_type_table_t *ty, spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
@@ -124,14 +363,14 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
ir_dump_type(ty, n->arith.tid);
ir_dump_ref(n->arith.left);
ir_dump_ref(n->arith.right);
ir_dump_value(ty, n->arith.left);
ir_dump_value(ty, n->arith.right);
break;
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_NOT:
ir_dump_type(ty, n->arith.tid);
ir_dump_ref(n->arith.left);
ir_dump_value(ty, n->arith.left);
break;
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
@@ -140,8 +379,8 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
ir_dump_type(ty, n->cmp.tid);
ir_dump_ref(n->cmp.a);
ir_dump_ref(n->cmp.b);
ir_dump_value(ty, n->cmp.a);
ir_dump_value(ty, n->cmp.b);
break;
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
@@ -155,67 +394,46 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
printf(" ");
spl_type_pure_dump((spl_type_t *)ty, n->cast.from_tid);
spl_ir_type_dump((spl_ir_type_table_t *)ty, n->cast.from_tid);
printf(" -> ");
spl_type_pure_dump((spl_type_t *)ty, n->cast.to_tid);
ir_dump_ref(n->cast.val);
spl_ir_type_dump((spl_ir_type_table_t *)ty, n->cast.to_tid);
ir_dump_value(ty, n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
ir_dump_type(ty, n->mem_alloc.tid);
ir_dump_ref(n->mem_alloc.count);
break;
case SPL_IR_MEM_GLOBAL_ALLOC:
ir_dump_type(ty, n->mem_global_alloc.tid);
printf(" g#%zu", n->mem_global_alloc.const_node);
ir_dump_value(ty, n->mem_alloc.count);
break;
case SPL_IR_MEM_LOAD:
ir_dump_type(ty, n->mem_load.tid);
ir_dump_ref(n->mem_load.ptr);
ir_dump_value(ty, n->mem_load.ptr);
break;
case SPL_IR_MEM_STORE:
ir_dump_type(ty, n->mem_store.tid);
ir_dump_ref(n->mem_store.ptr);
ir_dump_ref(n->mem_store.val);
ir_dump_value(ty, n->mem_store.ptr);
ir_dump_value(ty, n->mem_store.val);
break;
case SPL_IR_MEM_OFFSET:
ir_dump_type(ty, n->mem_offset.tid);
ir_dump_ref(n->mem_offset.ptr);
ir_dump_ref(n->mem_offset.offset);
ir_dump_value(ty, n->mem_offset.ptr);
ir_dump_value(ty, n->mem_offset.offset);
break;
case SPL_IR_MEM_FIELD_PTR:
ir_dump_type(ty, n->mem_field_ptr.tid);
ir_dump_ref(n->mem_field_ptr.agg);
ir_dump_value(ty, n->mem_field_ptr.agg);
printf(" #%zu", n->mem_field_ptr.field_idx);
break;
case SPL_IR_MEM_COPY:
ir_dump_type(ty, n->mem_copy.tid);
ir_dump_ref(n->mem_copy.dst);
ir_dump_ref(n->mem_copy.src);
ir_dump_ref(n->mem_copy.size);
ir_dump_value(ty, n->mem_copy.dst);
ir_dump_value(ty, n->mem_copy.src);
ir_dump_value(ty, n->mem_copy.size);
break;
case SPL_IR_MEM_SET:
ir_dump_type(ty, n->mem_set.tid);
ir_dump_ref(n->mem_set.dst);
ir_dump_ref(n->mem_set.val);
ir_dump_ref(n->mem_set.size);
ir_dump_value(ty, n->mem_set.dst);
ir_dump_value(ty, n->mem_set.val);
ir_dump_value(ty, n->mem_set.size);
break;
case SPL_IR_TYPE_CONST: {
ir_dump_type(ty, n->type_const.tid);
spl_type_node_t *t = spl_type_node((spl_type_t *)ty, n->type_const.tid);
if (t && t->kind == SPL_TYPE_FLOAT) {
printf(" float=%f", n->type_const.float_lit);
} else if (t && t->kind == SPL_TYPE_FN) {
printf(" fn#%zu", n->type_const.fn);
} else if (t && t->kind == SPL_TYPE_ARRAY) {
/* 字节常量:不打印宿主指针(不确定),只标记 bytes。 */
printf(" bytes");
} else if (t && t->kind == SPL_TYPE_INT && t->int_type.bits == 8) {
printf(" char='%c'", n->type_const.ch_lit);
} else {
printf(" int=%zu", n->type_const.int_lit);
}
break;
}
case SPL_IR_TYPE_BITSIZEOF:
ir_dump_type(ty, n->bitsizeof.tid);
break;
@@ -227,34 +445,34 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
break;
case SPL_IR_TYPE_OFFSETOF:
ir_dump_type(ty, n->ir_offsetof.tid);
ir_dump_ref(n->ir_offsetof.field_idx);
ir_dump_value(ty, n->ir_offsetof.field_idx);
break;
case SPL_IR_TYPE_FIELD_COUNT:
ir_dump_type(ty, n->field_count.tid);
break;
case SPL_IR_AGG_CONSTRUCT:
ir_dump_type(ty, n->agg_construct.tid);
vec_for(n->agg_construct.fields, i) ir_dump_ref(vec_at(n->agg_construct.fields, i));
vec_for(n->agg_construct.fields, i) ir_dump_value(ty, vec_at(n->agg_construct.fields, i));
break;
case SPL_IR_AGG_EXTRACT:
ir_dump_type(ty, n->agg_extract.tid);
printf(" #%zu", n->agg_extract.field_idx);
ir_dump_ref(n->agg_extract.val);
ir_dump_value(ty, n->agg_extract.val);
break;
case SPL_IR_AGG_INSERT:
ir_dump_type(ty, n->agg_insert.tid);
printf(" #%zu", n->agg_insert.field_idx);
ir_dump_ref(n->agg_insert.agg);
ir_dump_ref(n->agg_insert.field);
ir_dump_value(ty, n->agg_insert.agg);
ir_dump_value(ty, n->agg_insert.field);
break;
case SPL_IR_CONTROL_SELECT:
ir_dump_type(ty, n->control_select.tid);
ir_dump_ref(n->control_select.cond);
ir_dump_ref(n->control_select.true_val);
ir_dump_ref(n->control_select.false_val);
ir_dump_value(ty, n->control_select.cond);
ir_dump_value(ty, n->control_select.true_val);
ir_dump_value(ty, n->control_select.false_val);
break;
case SPL_IR_CONTROL_BR:
ir_dump_ref(n->control_br.cond);
ir_dump_value(ty, n->control_br.cond);
ir_dump_ref(n->control_br.true_label);
ir_dump_ref(n->control_br.false_label);
break;
@@ -263,16 +481,16 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
break;
case SPL_IR_CONTROL_CALL:
ir_dump_type(ty, n->control_call.tid);
ir_dump_ref(n->control_call.func);
vec_for(n->control_call.params, i) ir_dump_ref(vec_at(n->control_call.params, i));
ir_dump_value(ty, n->control_call.func);
vec_for(n->control_call.params, i) ir_dump_value(ty, vec_at(n->control_call.params, i));
break;
case SPL_IR_CONTROL_PARAM:
ir_dump_type(ty, n->control_param.tid);
ir_dump_ref(n->control_param.idx);
ir_dump_value(ty, n->control_param.idx);
break;
case SPL_IR_CONTROL_RET:
ir_dump_type(ty, n->control_ret.tid);
ir_dump_ref(n->control_ret.val);
ir_dump_value(ty, n->control_ret.val);
break;
case SPL_IR_CONTROL_UNREACHABLE:
case SPL_IR_CONTROL_TRAP:
@@ -296,14 +514,36 @@ static void ir_dump_attr_list(const spl_attr_t *attr, spl_attr_id_vec_t *ids) {
printf("]");
}
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty, const spl_attr_t *attr) {
void spl_ir_dump(spl_ir_t *ir, const spl_attr_t *attr) {
const spl_ir_type_table_t *ty = ir->types;
for (usize i = 1; i < vec_size(ir->consts); ++i) {
spl_ir_const_t *c = &vec_at(ir->consts, i);
printf("const c#%zu ", i);
spl_ir_type_dump((spl_ir_type_table_t *)ty, c->tid);
spl_ir_type_node_t *tn = spl_ir_type_node((spl_ir_type_table_t *)ty, c->tid);
if (tn && tn->kind == SPL_IR_TYPE_ARRAY)
printf(" bytes=%zu", c->bytes.len);
printf("\n");
}
for (usize i = 1; i < vec_size(ir->globals); ++i) {
spl_ir_global_t *g = &vec_at(ir->globals, i);
printf("global g#%zu %s ", i, g->readonly ? "const" : "var");
spl_ir_type_dump((spl_ir_type_table_t *)ty, g->tid);
if (g->name)
printf(" %s", g->name);
if (!spl_ir_value_is_none(g->init)) {
printf(" =");
ir_dump_value(ty, g->init);
}
printf("\n");
}
vec_for(ir->funcs, i) {
if (i == 0)
continue;
spl_ir_func_t *func = &vec_at(ir->funcs, i);
printf("func %s %%%zu", func->name ? func->name : "?", i);
printf(" tid = ");
spl_type_pure_dump((spl_type_t *)ty, func->fn_tid);
spl_ir_type_dump((spl_ir_type_table_t *)ty, func->fn_tid);
ir_dump_attr_list(attr, &func->attrs);
printf("\n");
@@ -344,8 +584,19 @@ static spl_ir_node_ref_t builder_alloc_node(spl_ir_builder_t *b, spl_ir_kind_t k
return ref;
}
static void spl_ir_builder_reset(spl_ir_builder_t *b);
void spl_ir_builder_init(spl_ir_builder_t *b) {
spl_ir_init(&b->ir);
spl_ir_builder_reset(b);
}
void spl_ir_builder_init_shared(spl_ir_builder_t *b, spl_ir_type_table_t *types) {
spl_ir_init_shared(&b->ir, types);
spl_ir_builder_reset(b);
}
static void spl_ir_builder_reset(spl_ir_builder_t *b) {
b->current_fn = 0;
b->dbg = (spl_dbg_node_t){0};
vec_init(b->blocks);
@@ -361,13 +612,13 @@ void spl_ir_builder_drop(spl_ir_builder_t *b) {
}
spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid) {
spl_ir_type_id_t fn_tid) {
if (b->current_fn) {
spl_ir_builder_fn_end(b);
}
spl_ir_func_ref_t fid = spl_ir_alloc_fn(&b->ir);
spl_ir_func_t *f = spl_ir_func(&b->ir, fid);
f->name = name;
f->name = name ? strdup(name) : NULL;
vec_init(f->attrs);
f->fn_tid = fn_tid;
@@ -380,10 +631,10 @@ spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
}
spl_ir_func_ref_t spl_ir_builder_fn_reserve(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid) {
spl_ir_type_id_t fn_tid) {
spl_ir_func_ref_t fid = spl_ir_alloc_fn(&b->ir);
spl_ir_func_t *f = spl_ir_func(&b->ir, fid);
f->name = name;
f->name = name ? strdup(name) : NULL;
vec_init(f->attrs);
f->fn_tid = fn_tid;
return fid;
@@ -458,86 +709,141 @@ void spl_ir_builder_block_end(spl_ir_builder_t *b) {
}
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_left, spl_ir_node_ref_t x_right) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_tid, \
spl_ir_value_t x_left, spl_ir_value_t x_right) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->arith.tid = x_tid; \
n->arith.left = x_left; \
n->arith.right = x_right; \
return ref; \
return spl_ir_value_inst(ref); \
}
SPL_IR_BIN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_val) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_tid, \
spl_ir_value_t x_val) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->arith.tid = x_tid; \
n->arith.left = x_val; \
n->arith.right = 0; \
return ref; \
n->arith.right = spl_ir_value_none(); \
return spl_ir_value_inst(ref); \
}
SPL_IR_UN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_a, spl_ir_node_ref_t x_b) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_tid, \
spl_ir_value_t x_a, spl_ir_value_t x_b) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->cmp.tid = x_tid; \
n->cmp.a = x_a; \
n->cmp.b = x_b; \
return ref; \
return spl_ir_value_inst(ref); \
}
SPL_IR_CMP_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_from, \
spl_type_id_t x_to, spl_ir_node_ref_t x_val) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_from, \
spl_ir_type_id_t x_to, spl_ir_value_t x_val) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->cast.from_tid = x_from; \
n->cast.to_tid = x_to; \
n->cast.val = x_val; \
return ref; \
return spl_ir_value_inst(ref); \
}
SPL_IR_CAST_TABLE
#undef X
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t count) {
spl_ir_value_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t count) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_ALLOCA);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_alloc.tid = tid;
n->mem_alloc.count = count;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t const_node) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_GLOBAL_ALLOC);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_global_alloc.tid = tid;
n->mem_global_alloc.const_node = const_node;
return ref;
static usize const_pool_add(spl_ir_t *ir, spl_ir_type_id_t tid, const void *data, usize len) {
spl_ir_const_key_t key = {.tid = tid, .data = data, .len = len};
usize id = 0;
if (map_get(ir->const_index, key, &id))
return id;
spl_ir_const_t entry = {0};
entry.tid = tid;
entry.bytes.len = len;
entry.bytes.data = malloc(len ? len : 1);
if (!entry.bytes.data)
return 0;
if (len)
memcpy(entry.bytes.data, data, len);
vec_push(ir->consts, entry);
id = vec_size(ir->consts) - 1;
/* 去重键必须指向池内稳定副本,调用方的指针可能马上失效。 */
key.data = entry.bytes.data;
map_put(ir->const_index, key, id);
return id;
}
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr) {
spl_ir_value_t spl_ir_builder_const_bytes(spl_ir_builder_t *b, spl_ir_type_id_t tid, const void *data,
usize len) {
usize id = const_pool_add(&b->ir, tid, data, len);
return spl_ir_value_const_pool(tid, id);
}
spl_ir_value_t spl_ir_builder_const_int(spl_ir_type_id_t tid, uint64_t bits) {
return spl_ir_value_const_int(tid, bits);
}
spl_ir_value_t spl_ir_builder_const_bool(spl_ir_type_id_t tid, bool val) {
return spl_ir_value_const_int(tid, val ? 1 : 0);
}
spl_ir_value_t spl_ir_builder_const_float(spl_ir_type_id_t tid, double val) {
return spl_ir_value_const_float(tid, val);
}
spl_ir_value_t spl_ir_builder_const_null(spl_ir_type_id_t tid) {
return spl_ir_value_const_null(tid);
}
spl_ir_value_t spl_ir_builder_const_fn(spl_ir_type_id_t tid, spl_ir_func_ref_t fn) {
return spl_ir_value_const_fn(tid, fn);
}
spl_ir_value_t spl_ir_builder_global_addr(spl_ir_type_id_t ptr_tid, usize global_id) {
return spl_ir_value_global(ptr_tid, global_id);
}
usize spl_ir_builder_global_declare(spl_ir_builder_t *b, const char *name, spl_ir_type_id_t tid,
spl_ir_value_t init, bool readonly) {
spl_ir_global_t g = {
.name = name ? strdup(name) : NULL,
.tid = tid,
.init = init,
.readonly = readonly,
};
vec_push(b->ir.globals, g);
return vec_size(b->ir.globals) - 1;
}
spl_ir_value_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t ptr) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_LOAD);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_load.tid = tid;
n->mem_load.ptr = ptr;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val) {
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t ptr, spl_ir_value_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_STORE);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_store.tid = tid;
@@ -546,29 +852,28 @@ spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t ti
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset) {
spl_ir_value_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t ptr,
spl_ir_value_t offset) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_OFFSET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_offset.tid = tid;
n->mem_offset.ptr = ptr;
n->mem_offset.offset = offset;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t agg, usize field_idx) {
spl_ir_value_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t agg,
usize field_idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_FIELD_PTR);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_field_ptr.tid = tid;
n->mem_field_ptr.agg = agg;
n->mem_field_ptr.field_idx = field_idx;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
spl_ir_node_ref_t size) {
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t src, spl_ir_value_t size) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_COPY);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_copy.tid = tid;
@@ -578,9 +883,8 @@ spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
spl_ir_node_ref_t size) {
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t val, spl_ir_value_t size) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_SET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_set.tid = tid;
@@ -590,104 +894,44 @@ spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_bool(spl_ir_builder_t *b, spl_type_id_t tid, bool val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.bool_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_ptr(spl_ir_builder_t *b, spl_type_id_t tid, void *val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ptr_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.int_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
double val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.float_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_bytes(spl_ir_builder_t *b, spl_type_id_t tid,
const void *data, usize len) {
(void)len;
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ptr_lit = (void *)data;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ch_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_func_ref_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.fn = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_BITSIZEOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->bitsizeof.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_SIZEOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_sizeof.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_ALIGNOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_alignof.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t field_idx) {
spl_ir_value_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t field_idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_OFFSETOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_offsetof.tid = tid;
n->ir_offsetof.field_idx = field_idx;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_FIELD_COUNT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->field_count.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_CONSTRUCT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_construct.tid = tid;
@@ -696,48 +940,48 @@ spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_
}
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
spl_ir_node_ref_t field) {
spl_ir_value_t field) {
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, node);
Assert(n != NULL);
vec_push(n->agg_construct.fields, field);
}
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
spl_type_id_t field_tid, usize field_idx,
spl_ir_node_ref_t val) {
spl_ir_value_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_type_id_t field_tid, usize field_idx,
spl_ir_value_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_EXTRACT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_extract.tid = tid;
n->agg_extract.field_tid = field_tid;
n->agg_extract.field_idx = field_idx;
n->agg_extract.val = val;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
spl_ir_node_ref_t agg, spl_ir_node_ref_t field) {
spl_ir_value_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_ir_type_id_t tid, usize field_idx,
spl_ir_value_t agg, spl_ir_value_t field) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_INSERT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_insert.tid = tid;
n->agg_insert.field_idx = field_idx;
n->agg_insert.agg = agg;
n->agg_insert.field = field;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
spl_ir_node_ref_t false_val) {
spl_ir_value_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t cond, spl_ir_value_t true_val,
spl_ir_value_t false_val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_SELECT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_select.tid = tid;
n->control_select.cond = cond;
n->control_select.true_val = true_val;
n->control_select.false_val = false_val;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond) {
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_value_t cond) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_BR);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_br.cond = cond;
@@ -777,8 +1021,8 @@ void spl_ir_builder_control_jmp_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref
vec_push(b->fixups, fx);
}
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t func) {
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t func) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_CALL);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_call.tid = tid;
@@ -788,23 +1032,23 @@ spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t
}
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t call_node,
spl_ir_node_ref_t arg) {
spl_ir_value_t arg) {
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, call_node);
Assert(n != NULL);
vec_push(n->control_call.params, arg);
}
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t idx) {
spl_ir_value_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_PARAM);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_param.tid = tid;
n->control_param.idx = idx;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t val) {
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_RET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_ret.tid = tid;
+116 -173
View File
@@ -1,45 +1,41 @@
#include "spl_type.h"
#include "spl_ir_type.h"
static usize spl_type_hash(spl_type_node_t n) {
static usize spl_type_hash(spl_ir_type_node_t n) {
usize hash = spl_hash_seed();
hash = spl_hash_mix(hash, (usize)n.kind);
switch (n.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_UNIT:
case SPL_TYPE_ANY:
case SPL_TYPE_NEVER:
case SPL_TYPE_INFER:
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_ERROR:
case SPL_IR_TYPE_UNIT:
case SPL_IR_TYPE_BOOL:
break;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
hash = spl_hash_mix(hash, n.int_type.bits);
hash = spl_hash_mix(hash, (usize)n.int_type.is_signed);
break;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
hash = spl_hash_mix(hash, n.float_type.bits);
break;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
hash = spl_hash_mix(hash, n.ptr_type.pointee);
break;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
hash = spl_hash_mix(hash, n.array_type.element);
hash = spl_hash_mix(hash, n.array_type.len);
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
hash = spl_hash_mix(hash, (usize)n.layout.mode);
hash = spl_hash_mix(hash, n.layout.fixed_align_bits);
hash = spl_hash_mix(hash, n.agg_type.tag_type);
hash = spl_hash_mix(hash, vec_size(n.agg_type.variants));
for (usize i = 0; i < vec_size(n.agg_type.variants); i++) {
spl_type_member_t *m = &vec_at(n.agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(n.agg_type.variants, i);
hash = spl_hash_mix(hash, m->type_id);
hash = spl_hash_mix_str(hash, m->name);
}
break;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
hash = spl_hash_mix(hash, n.fn_type.ret);
hash = spl_hash_mix(hash, vec_size(n.fn_type.params));
for (usize i = 0; i < vec_size(n.fn_type.params); i++) {
@@ -50,31 +46,27 @@ static usize spl_type_hash(spl_type_node_t n) {
return hash;
}
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
static int spl_type_eq(spl_ir_type_node_t n1, spl_ir_type_node_t n2) {
if (n1.kind != n2.kind)
return 1;
switch (n1.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_UNIT:
case SPL_TYPE_ANY:
case SPL_TYPE_NEVER:
case SPL_TYPE_INFER:
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_ERROR:
case SPL_IR_TYPE_UNIT:
case SPL_IR_TYPE_BOOL:
return 0;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
return (n1.int_type.bits != n2.int_type.bits) ||
(n1.int_type.is_signed != n2.int_type.is_signed);
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
return n1.float_type.bits != n2.float_type.bits;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
return n1.ptr_type.pointee != n2.ptr_type.pointee;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
return (n1.array_type.element != n2.array_type.element) ||
(n1.array_type.len != n2.array_type.len);
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
@@ -83,8 +75,8 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
if (vec_size(n1.agg_type.variants) != vec_size(n2.agg_type.variants))
return 1;
for (usize i = 0; i < vec_size(n1.agg_type.variants); i++) {
spl_type_member_t *a = &n1.agg_type.variants.data[i];
spl_type_member_t *b = &n2.agg_type.variants.data[i];
spl_ir_type_member_t *a = &n1.agg_type.variants.data[i];
spl_ir_type_member_t *b = &n2.agg_type.variants.data[i];
if (a->type_id != b->type_id)
return 1;
if ((a->name == NULL) != (b->name == NULL))
@@ -93,7 +85,7 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
return 1;
}
return 0;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
if (n1.fn_type.ret != n2.fn_type.ret)
return 1;
if (vec_size(n1.fn_type.params) != vec_size(n2.fn_type.params))
@@ -107,15 +99,14 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
return 1;
}
static void spl_type_node_free_vecs(spl_type_node_t *tn) {
static void spl_ir_type_node_free_vecs(spl_ir_type_node_t *tn) {
switch (tn->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
vec_free(tn->agg_type.variants);
break;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
vec_free(tn->fn_type.params);
break;
default:
@@ -125,96 +116,60 @@ static void spl_type_node_free_vecs(spl_type_node_t *tn) {
/* spl_fold 回调:只在链内做结构比较(同桶已保证 hash 相同)。 */
static int spl_type_fold_eq(void *ctx, spl_fold_id_t node, const void *probe) {
spl_type_t *type = (spl_type_t *)ctx;
return spl_type_eq(vec_at(type->type_table, node), *(const spl_type_node_t *)probe) == 0;
spl_ir_type_table_t *type = (spl_ir_type_table_t *)ctx;
return spl_type_eq(vec_at(type->type_table, node), *(const spl_ir_type_node_t *)probe) == 0;
}
static spl_fold_id_t spl_type_fold_next(void *ctx, spl_fold_id_t node) {
spl_type_t *type = (spl_type_t *)ctx;
spl_ir_type_table_t *type = (spl_ir_type_table_t *)ctx;
return vec_at(type->type_table, node).hash_next;
}
static void spl_type_fold_set_next(void *ctx, spl_fold_id_t node, spl_fold_id_t next) {
spl_type_t *type = (spl_type_t *)ctx;
spl_ir_type_table_t *type = (spl_ir_type_table_t *)ctx;
vec_at(type->type_table, node).hash_next = next;
}
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *tn) {
spl_ir_type_id_t spl_ir_type_push(spl_ir_type_table_t *type, spl_ir_type_node_t *tn) {
usize hash = spl_type_hash(*tn);
spl_type_id_t existing = spl_fold_find(&type->type_fold, hash, tn);
spl_ir_type_id_t existing = spl_fold_find(&type->type_fold, hash, tn);
if (existing) {
spl_type_node_free_vecs(tn);
spl_ir_type_node_free_vecs(tn);
return existing;
}
spl_type_id_t id = vec_size(type->type_table);
spl_ir_type_id_t id = vec_size(type->type_table);
vec_push(type->type_table, *tn);
spl_fold_insert(&type->type_fold, hash, id);
tn->kind = SPL_TYPE_ERROR;
tn->kind = SPL_IR_TYPE_ERROR;
return id;
}
void spl_type_init(spl_type_t *type) {
void spl_ir_type_table_init(spl_ir_type_table_t *type) {
vec_init(type->type_table);
spl_type_node_t type_node = {0};
spl_ir_type_node_t type_node = {0};
vec_push(type->type_table, type_node);
spl_fold_init(&type->type_fold, type, spl_type_fold_eq, spl_type_fold_next,
spl_type_fold_set_next);
}
void spl_type_drop(spl_type_t *type) {
void spl_ir_type_table_drop(spl_ir_type_table_t *type) {
for (usize i = 0; i < vec_size(type->type_table); i++) {
spl_type_node_t *n = &vec_at(type->type_table, i);
spl_type_node_free_vecs(n);
spl_ir_type_node_t *n = &vec_at(type->type_table, i);
spl_ir_type_node_free_vecs(n);
}
spl_fold_drop(&type->type_fold);
vec_free(type->type_table);
}
spl_type_node_t *spl_type_node(const spl_type_t *type, spl_type_id_t id) {
spl_ir_type_node_t *spl_ir_type_node(const spl_ir_type_table_t *type, spl_ir_type_id_t id) {
if (!id || id >= vec_size(type->type_table))
return NULL;
return &vec_at(type->type_table, id);
}
bool spl_type_is_subtype(const spl_type_t *type, spl_type_id_t sub, spl_type_id_t super) {
if (sub == 0 || super == 0)
return false;
if (sub == super)
return true;
spl_type_node_t *nsub = spl_type_node(type, sub);
spl_type_node_t *nsuper = spl_type_node(type, super);
if (!nsub || !nsuper)
return false;
if (nsub->kind == SPL_TYPE_NEVER)
return true;
if (nsuper->kind == SPL_TYPE_ANY)
return true;
if (nsub->kind == SPL_TYPE_INT && nsuper->kind == SPL_TYPE_INT) {
if (nsub->int_type.bits == 0)
return true;
if (nsub->int_type.is_signed == nsuper->int_type.is_signed) {
return nsub->int_type.bits <= nsuper->int_type.bits;
}
if (!nsub->int_type.is_signed && nsuper->int_type.is_signed) {
return nsuper->int_type.bits > nsub->int_type.bits;
}
return false;
}
if (nsub->kind == SPL_TYPE_FLOAT && nsuper->kind == SPL_TYPE_FLOAT) {
if (nsub->float_type.bits == 0)
return true;
return nsub->float_type.bits <= nsuper->float_type.bits;
}
return false;
}
static void spl_type_pure_dump_rec(spl_type_t *type, spl_type_id_t id, spl_type_id_vec_t *stack) {
static void spl_ir_type_dump_rec(spl_ir_type_table_t *type, spl_ir_type_id_t id, spl_ir_type_id_vec_t *stack) {
for (usize i = 0; i < vec_size(*stack); i++) {
if (vec_at(*stack, i) == id) {
printf("<rec#%zu>", id);
@@ -227,104 +182,92 @@ static void spl_type_pure_dump_rec(spl_type_t *type, spl_type_id_t id, spl_type_
}
vec_push(*stack, id);
spl_type_node_t *n = spl_type_node(type, id);
spl_ir_type_node_t *n = spl_ir_type_node(type, id);
if (!n) {
printf("none");
(void)vec_pop(*stack);
return;
}
switch (n->kind) {
case SPL_TYPE_ERROR:
case SPL_IR_TYPE_ERROR:
printf("error");
break;
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_UNIT:
printf("unit");
break;
case SPL_TYPE_ANY:
printf("any");
break;
case SPL_TYPE_NEVER:
printf("never");
break;
case SPL_TYPE_INFER:
printf("infer");
break;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
printf("bool");
break;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (n->int_type.bits == 0)
printf("comptime_int");
else
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
break;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
if (n->float_type.bits == 0)
printf("comptime_float");
else
printf("f%zu", n->float_type.bits);
break;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
printf("*");
spl_type_pure_dump_rec(type, n->ptr_type.pointee, stack);
spl_ir_type_dump_rec(type, n->ptr_type.pointee, stack);
break;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
printf("[%zu]", n->array_type.len);
spl_type_pure_dump_rec(type, n->array_type.element, stack);
spl_ir_type_dump_rec(type, n->array_type.element, stack);
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE: {
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM: {
const char *kw = "struct";
if (n->kind == SPL_TYPE_UNION)
if (n->kind == SPL_IR_TYPE_UNION)
kw = "union";
else if (n->kind == SPL_TYPE_ENUM)
else if (n->kind == SPL_IR_TYPE_ENUM)
kw = "enum";
else if (n->kind == SPL_TYPE_SHAPE)
kw = "shape";
printf("%s{", kw);
for (usize i = 0; i < vec_size(n->agg_type.variants); i++) {
if (i)
printf(", ");
spl_type_member_t *m = &n->agg_type.variants.data[i];
spl_ir_type_member_t *m = &n->agg_type.variants.data[i];
printf("%s:", m->name ? m->name : "?");
spl_type_pure_dump_rec(type, m->type_id, stack);
spl_ir_type_dump_rec(type, m->type_id, stack);
}
printf("}");
break;
}
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
printf("fn(");
for (usize i = 0; i < vec_size(n->fn_type.params); i++) {
if (i)
printf(",");
spl_type_pure_dump_rec(type, vec_at(n->fn_type.params, i), stack);
spl_ir_type_dump_rec(type, vec_at(n->fn_type.params, i), stack);
}
printf(")");
spl_type_pure_dump_rec(type, n->fn_type.ret, stack);
spl_ir_type_dump_rec(type, n->fn_type.ret, stack);
break;
}
(void)vec_pop(*stack);
}
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
spl_type_id_vec_t stack;
void spl_ir_type_dump(spl_ir_type_table_t *type, spl_ir_type_id_t id) {
spl_ir_type_id_vec_t stack;
vec_init(stack);
spl_type_pure_dump_rec(type, id, &stack);
spl_ir_type_dump_rec(type, id, &stack);
vec_free(stack);
}
static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_type_id_t tid,
static const spl_ir_type_member_t *spl_ir_type_member_find(spl_ir_type_table_t *type, spl_ir_type_id_t tid,
const char *name, usize *out_idx) {
spl_type_node_t *n = spl_type_node(type, tid);
spl_ir_type_node_t *n = spl_ir_type_node(type, tid);
if (!n || !name)
return NULL;
if (n->kind == SPL_TYPE_STRUCT || n->kind == SPL_TYPE_UNION || n->kind == SPL_TYPE_ENUM ||
n->kind == SPL_TYPE_SHAPE) {
if (n->kind == SPL_IR_TYPE_STRUCT || n->kind == SPL_IR_TYPE_UNION ||
n->kind == SPL_IR_TYPE_ENUM) {
for (usize i = 0; i < vec_size(n->agg_type.variants); i++) {
spl_type_member_t *m = &n->agg_type.variants.data[i];
spl_ir_type_member_t *m = &n->agg_type.variants.data[i];
if (m->name && strcmp(m->name, name) == 0) {
if (out_idx)
*out_idx = i;
@@ -335,82 +278,82 @@ static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_t
return NULL;
}
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid,
const spl_ir_type_member_t *spl_ir_type_member(spl_ir_type_table_t *type, spl_ir_type_id_t tid,
const char *name) {
return spl_type_agg_member_find(type, tid, name, NULL);
return spl_ir_type_member_find(type, tid, name, NULL);
}
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name,
bool spl_ir_type_member_idx(spl_ir_type_table_t *type, spl_ir_type_id_t tid, const char *name,
usize *out_idx) {
return spl_type_agg_member_find(type, tid, name, out_idx) != NULL;
return spl_ir_type_member_find(type, tid, name, out_idx) != NULL;
}
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind) {
spl_type_node_t tn = {0};
spl_ir_type_id_t spl_ir_type_builder_simple(spl_ir_type_table_t *type, spl_ir_type_kind_t kind) {
spl_ir_type_node_t tn = {0};
tn.kind = kind;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
return spl_type_node_push(type, &tn);
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_INT;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_int(spl_ir_type_table_t *type, usize bits, int is_signed) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_INT;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.int_type.bits = bits;
tn.int_type.is_signed = is_signed;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FLOAT;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_float(spl_ir_type_table_t *type, usize bits) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_FLOAT;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.float_type.bits = bits;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_PTR;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_ptr(spl_ir_type_table_t *type, spl_ir_type_id_t pointee) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_PTR;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.ptr_type.pointee = pointee;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_ARRAY;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_array(spl_ir_type_table_t *type, spl_ir_type_id_t element, usize len) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_ARRAY;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.array_type.element = element;
tn.array_type.len = len;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
spl_ir_type_id_t spl_ir_type_builder_fn(spl_ir_type_table_t *type, spl_ir_type_id_t ret, const spl_ir_type_id_t *params,
usize nparams) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FN;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_FN;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
vec_init(tn.fn_type.params);
for (usize i = 0; i < nparams; i++) {
vec_push(tn.fn_type.params, params[i]);
}
tn.fn_type.ret = ret;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
spl_type_member_vec_t *variants, spl_type_id_t tag_type,
spl_type_layout_t layout) {
spl_type_node_t tn = {0};
spl_ir_type_id_t spl_ir_type_builder_agg(spl_ir_type_table_t *type, spl_ir_type_kind_t tk,
spl_ir_type_member_vec_t *variants, spl_ir_type_id_t tag_type,
spl_ir_type_layout_t layout) {
spl_ir_type_node_t tn = {0};
tn.kind = tk;
tn.layout = layout;
tn.agg_type.variants = *variants;
vec_init(*variants);
if (tk == SPL_TYPE_ENUM) {
if (tk == SPL_IR_TYPE_ENUM) {
tn.agg_type.tag_type = tag_type;
} else {
tn.agg_type.tag_type = 0;
}
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
+39 -37
View File
@@ -9,7 +9,7 @@ static void infos_grow(spl_layout_t *layout, usize n) {
}
}
static spl_layout_info_t *infos_at(spl_layout_t *layout, spl_type_id_t id) {
static spl_layout_info_t *infos_at(spl_layout_t *layout, spl_ir_type_id_t id) {
if (id == 0 || id >= vec_size(layout->infos))
return NULL;
return &vec_at(layout->infos, id);
@@ -84,20 +84,20 @@ static const spl_layout_ptr_t *default_ptr(spl_layout_t *layout) {
return &vec_at(layout->pointers, 0);
}
static bool layout_scalar(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_info_t *out) {
static bool layout_scalar(spl_layout_t *layout, spl_ir_type_node_t *tn, spl_layout_info_t *out) {
usize size_bits = 0;
switch (tn->kind) {
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (tn->int_type.bits == 0)
return false; /* comptime_int 未落地 */
size_bits = tn->int_type.bits;
break;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
if (tn->float_type.bits == 0)
return false; /* comptime_float 未落地 */
size_bits = tn->float_type.bits;
break;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
size_bits = 8;
break;
default:
@@ -129,11 +129,11 @@ static usize round_up_bits(usize x, usize align_bits) {
return (x + a - 1) / a * a;
}
static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_info_t *out) {
static bool layout_agg(spl_layout_t *layout, spl_ir_type_node_t *tn, spl_layout_info_t *out) {
usize n = vec_size(tn->agg_type.variants);
if (tn->kind == SPL_TYPE_ENUM) {
spl_type_id_t tag_tid = tn->agg_type.tag_type;
if (tn->kind == SPL_IR_TYPE_ENUM) {
spl_ir_type_id_t tag_tid = tn->agg_type.tag_type;
if (!tag_tid)
return false;
spl_layout_info_t *tag_info = infos_at(layout, tag_tid);
@@ -145,7 +145,7 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
usize payload_size_bits = 0;
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
if (m->type_id == 0) /* 无载荷变体 */
continue;
spl_layout_info_t *fi = infos_at(layout, m->type_id);
@@ -168,7 +168,7 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
vec_push(out->field_bit_offsets, 0);
vec_push(out->field_bit_sizes, tag_info->size_bits);
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
usize fsize = 0;
if (m->type_id) {
spl_layout_info_t *fi = infos_at(layout, m->type_id);
@@ -189,10 +189,10 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
usize max_align_bits = 8;
usize offset_bits = 0;
bool is_union = (tn->kind == SPL_TYPE_UNION);
bool is_union = (tn->kind == SPL_IR_TYPE_UNION);
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
usize fsize_bits = 0;
usize fsize_align = 8;
if (m->type_id) {
@@ -236,12 +236,12 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
return true;
}
static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t id) {
static void resolve_type(spl_layout_t *layout, const spl_ir_type_table_t *type, spl_ir_type_id_t id) {
spl_layout_info_t *info = infos_at(layout, id);
if (!info || info->resolved)
return;
spl_type_node_t *tn = spl_type_node(type, id);
spl_ir_type_node_t *tn = spl_ir_type_node(type, id);
if (!tn)
return;
@@ -250,30 +250,23 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
info->resolved = true;
switch (tn->kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_INFER:
case SPL_TYPE_NEVER:
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_ERROR:
case SPL_IR_TYPE_UNIT:
info->size_bits = 0;
info->align_bits = 8;
return;
case SPL_TYPE_ANY:
/* 顶层类型按不透明指针处理 */
layout_ptr(layout, info);
return;
case SPL_TYPE_BOOL:
case SPL_TYPE_INT:
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_BOOL:
case SPL_IR_TYPE_INT:
case SPL_IR_TYPE_FLOAT:
layout_scalar(layout, tn, info);
return;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
layout_ptr(layout, info);
return;
case SPL_TYPE_ARRAY: {
case SPL_IR_TYPE_ARRAY: {
resolve_type(layout, type, tn->array_type.element);
spl_layout_info_t *elem = infos_at(layout, tn->array_type.element);
if (!elem || !elem->resolved)
@@ -283,14 +276,13 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
return;
}
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE: {
if (tn->kind == SPL_TYPE_ENUM && tn->agg_type.tag_type)
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM: {
if (tn->kind == SPL_IR_TYPE_ENUM && tn->agg_type.tag_type)
resolve_type(layout, type, tn->agg_type.tag_type);
for (usize i = 0; i < vec_size(tn->agg_type.variants); ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
if (m->type_id)
resolve_type(layout, type, m->type_id);
}
@@ -298,7 +290,7 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
return;
}
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
/* 函数类型按函数指针布局 */
for (usize i = 0; i < vec_size(tn->fn_type.params); ++i)
resolve_type(layout, type, vec_at(tn->fn_type.params, i));
@@ -308,13 +300,23 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
}
}
void spl_layout_resolve(spl_layout_t *layout, spl_type_t *type) {
void spl_layout_resolve(spl_layout_t *layout, const spl_ir_type_table_t *type) {
infos_grow(layout, vec_size(type->type_table));
for (usize i = 0; i < vec_size(layout->infos); ++i) {
spl_layout_info_t *info = &vec_at(layout->infos, i);
vec_free(info->field_bit_offsets);
vec_free(info->field_bit_sizes);
vec_init(info->field_bit_offsets);
vec_init(info->field_bit_sizes);
info->size_bits = 0;
info->align_bits = 0;
info->resolved = false;
}
for (usize i = 1; i < vec_size(type->type_table); ++i)
resolve_type(layout, type, i);
}
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_type_id_t id) {
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_ir_type_id_t id) {
spl_layout_info_t *info = infos_at(layout, id);
if (!info || !info->resolved)
return NULL;
@@ -434,7 +434,6 @@ spl_tok_vec_t spl_lex(const char *source, const char *fname) {
TRY_OP2('|', '=', TOK_ASSIGN_OR, TOK_OR)
TRY_OP2('^', '=', TOK_ASSIGN_XOR, TOK_XOR)
TRY_OP2('-', '>', TOK_RIGHT_ARROW, TOK_SUB)
TRY_OP2(':', '=', TOK_COLON_ASSIGN, TOK_COLON)
/* Single-character operators */
TRY_OP1('+', TOK_ADD);
@@ -463,7 +462,6 @@ spl_tok_vec_t spl_lex(const char *source, const char *fname) {
TRY_OP1('#', TOK_SHARP);
TRY_OP1('@', TOK_AT);
TRY_OP1('$', TOK_DOLLAR);
TRY_OP1('?', TOK_COND);
LOG_ERROR("%s:%zu:%zu: unknown character '%c' (0x%02x)", fname ? fname : "<null>", line, col,
(c >= 32 && c < 127) ? c : '?', (unsigned char)c);
File renamed without changes.
File diff suppressed because it is too large. Load diff
File renamed without changes.
@@ -83,14 +83,14 @@ spl_intrin_t spl_intrin_lookup_field(spl_lang_type_kind_t recv_kind, const char
return SPL_INTRIN_NONE;
}
spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type_id_t tt) {
spl_intrin_t spl_intrin_lookup_cast(spl_ir_type_table_t *type, spl_ir_type_id_t ft, spl_ir_type_id_t tt) {
/* 这是 `as` 的展开规则表。要调整 as 的语义,改这里。 */
spl_type_node_t *f = spl_type_node(type, ft);
spl_type_node_t *t = spl_type_node(type, tt);
spl_ir_type_node_t *f = spl_ir_type_node(type, ft);
spl_ir_type_node_t *t = spl_ir_type_node(type, tt);
if (!f || !t)
return SPL_INTRIN_NONE;
if (f->kind == SPL_TYPE_INT && t->kind == SPL_TYPE_INT) {
if (f->kind == SPL_IR_TYPE_INT && t->kind == SPL_IR_TYPE_INT) {
usize fb = f->int_type.bits;
usize tb = t->int_type.bits;
if (fb == tb)
@@ -99,15 +99,15 @@ spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type
return SPL_INTRIN_TRUNCATE;
return SPL_INTRIN_INT_CAST;
}
if (f->kind == SPL_TYPE_FLOAT && t->kind == SPL_TYPE_FLOAT)
if (f->kind == SPL_IR_TYPE_FLOAT && t->kind == SPL_IR_TYPE_FLOAT)
return SPL_INTRIN_FLOAT_CAST;
if (f->kind == SPL_TYPE_BOOL && t->kind == SPL_TYPE_INT)
if (f->kind == SPL_IR_TYPE_BOOL && t->kind == SPL_IR_TYPE_INT)
return SPL_INTRIN_BOOL2INT;
if (f->kind == SPL_TYPE_PTR && t->kind == SPL_TYPE_INT)
if (f->kind == SPL_IR_TYPE_PTR && t->kind == SPL_IR_TYPE_INT)
return SPL_INTRIN_PTR2INT;
if (f->kind == SPL_TYPE_INT && t->kind == SPL_TYPE_PTR)
if (f->kind == SPL_IR_TYPE_INT && t->kind == SPL_IR_TYPE_PTR)
return SPL_INTRIN_INT2PTR;
if (f->kind == SPL_TYPE_PTR && t->kind == SPL_TYPE_PTR)
if (f->kind == SPL_IR_TYPE_PTR && t->kind == SPL_IR_TYPE_PTR)
return SPL_INTRIN_PTR_CAST;
/* int float 刻意不在这里:只能通过显式 builtin 调用。
+135
View File
@@ -0,0 +1,135 @@
#include "spl_ir_link.h"
#include "spl_ast2ir.h"
#include "spl_lang_type.h"
#include "spl_sema.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
usize def_id;
spl_ir_func_ref_t fn;
} spl_ir_link_fn_entry_t;
typedef VEC(spl_ir_link_fn_entry_t) spl_ir_link_fn_vec_t;
struct spl_ir_link {
spl_ir_t *ir;
spl_sema_t *sema;
spl_ir_link_fn_vec_t fns;
};
spl_ir_link_t *spl_ir_link_create(spl_ir_t *ir, spl_sema_t *sema) {
if (!ir || !sema)
return NULL;
spl_ir_link_t *link = calloc(1, sizeof(*link));
if (!link)
return NULL;
link->ir = ir;
link->sema = sema;
vec_init(link->fns);
return link;
}
void spl_ir_link_destroy(spl_ir_link_t *link) {
if (!link)
return;
vec_free(link->fns);
free(link);
}
static spl_ir_link_fn_entry_t *link_find_def(spl_ir_link_t *link, usize def_id) {
for (usize i = 0; i < vec_size(link->fns); ++i) {
spl_ir_link_fn_entry_t *entry = &vec_at(link->fns, i);
if (entry->def_id == def_id)
return entry;
}
return NULL;
}
static spl_ir_link_fn_entry_t *link_find_fn(spl_ir_link_t *link, spl_ir_func_ref_t fn) {
for (usize i = 0; i < vec_size(link->fns); ++i) {
spl_ir_link_fn_entry_t *entry = &vec_at(link->fns, i);
if (entry->fn == fn)
return entry;
}
return NULL;
}
spl_ir_func_ref_t spl_ir_link_reserve_fn(spl_ir_link_t *link, usize def_id) {
if (!link || !def_id)
return 0;
spl_ir_link_fn_entry_t *existing = link_find_def(link, def_id);
if (existing)
return existing->fn;
spl_def_node_t *def = spl_def_node(link->sema->type, def_id);
if (!def || def->kind != SPL_DEF_FN || !def->owner_ast)
return 0;
spl_lang_type_id_t fn_lang = def->lang_id;
if (!fn_lang)
return 0;
spl_lang_type_node_t *fn_ln = spl_lang_type_node(link->sema->type, fn_lang);
if (!fn_ln || fn_ln->kind != SPL_LANG_TYPE_FN || !fn_ln->ir_type_id)
return 0;
char name_buf[1024];
const char *name = def->name;
spl_ast_node_t *fn_node = spl_ast_node(def->owner_ast, def->ast_node_ref);
if (fn_node && fn_node->kind == SPL_AST_FN_DECL &&
spl_ast2ir_fn_name(link->sema, link->sema->attr, def->owner_ast, fn_node, name_buf,
sizeof(name_buf)))
name = name_buf;
spl_ir_func_ref_t fn = spl_ir_alloc_fn(link->ir);
spl_ir_func_t *irf = spl_ir_func(link->ir, fn);
if (!irf)
return 0;
irf->name = name ? strdup(name) : NULL;
vec_init(irf->attrs);
irf->fn_tid = fn_ln->ir_type_id;
if (fn_node && fn_node->kind == SPL_AST_FN_DECL && link->sema->attr) {
for (usize i = 0; i < vec_size(fn_node->attrs); ++i) {
spl_attr_node_t *an = spl_attr_node(link->sema->attr, vec_at(fn_node->attrs, i));
if (an && an->info && an->info->name && strcmp(an->info->name, "extern") == 0) {
irf->extern_fn = true;
break;
}
}
}
spl_ir_link_fn_entry_t entry = {.def_id = def_id, .fn = fn};
vec_push(link->fns, entry);
return fn;
}
spl_ir_value_t spl_ir_link_fn_value(spl_ir_link_t *link, usize def_id) {
spl_ir_func_ref_t fn = spl_ir_link_reserve_fn(link, def_id);
if (!fn)
return spl_ir_value_none();
spl_ir_link_fn_entry_t *entry = link_find_fn(link, fn);
if (!entry)
return spl_ir_value_none();
spl_def_node_t *def = spl_def_node(link->sema->type, entry->def_id);
if (!def || !def->lang_id)
return spl_ir_value_none();
spl_lang_type_node_t *fn_ln = spl_lang_type_node(link->sema->type, def->lang_id);
if (!fn_ln || !fn_ln->ir_type_id)
return spl_ir_value_none();
return spl_ir_value_const_fn(fn_ln->ir_type_id, fn);
}
bool spl_ir_link_def_of_fn(const spl_ir_link_t *link, spl_ir_func_ref_t fn, usize *out_def) {
if (!link || !fn)
return false;
for (usize i = 0; i < vec_size(link->fns); ++i) {
const spl_ir_link_fn_entry_t *entry = &vec_at(link->fns, i);
if (entry->fn == fn) {
if (out_def)
*out_def = entry->def_id;
return true;
}
}
return false;
}
+96
View File
@@ -0,0 +1,96 @@
#include "spl_meta.h"
#include "spl_exec.h"
#include "spl_exec_frontend.h"
#include "spl_exec_vm.h"
#include "spl_sap.h"
#include <stdlib.h>
struct spl_meta {
spl_sema_t *sema;
spl_exec_frontend_ctx_t *frontend;
spl_exec_vm_ctx_t *backend;
spl_exec_t *exec;
spl_sap_t *sap;
bool prepared;
bool failed;
};
spl_meta_t *spl_meta_create(spl_sema_t *sema) {
if (!sema)
return NULL;
spl_meta_t *m = calloc(1, sizeof(*m));
if (!m)
return NULL;
m->sema = sema;
m->sap = spl_sap_create(sema->type);
if (!m->sap) {
free(m);
return NULL;
}
return m;
}
void spl_meta_destroy(spl_meta_t *m) {
if (!m)
return;
if (m->exec)
spl_exec_destroy(m->exec);
spl_sap_destroy(m->sap);
spl_exec_vm_destroy(m->backend);
spl_exec_frontend_destroy(m->frontend);
free(m);
}
bool spl_meta_prepare(spl_meta_t *m) {
if (!m)
return false;
if (m->prepared)
return !m->failed;
m->prepared = true;
m->frontend = spl_exec_frontend_create(m->sema);
if (!m->frontend) {
m->failed = true;
return false;
}
m->backend = spl_exec_vm_create(spl_exec_frontend_ir(m->frontend), m->sema->layout,
m->sema->attr);
if (!m->backend) {
m->failed = true;
return false;
}
m->exec = spl_exec_create((spl_ir_t *)spl_exec_frontend_ir(m->frontend), m->sema->layout,
spl_exec_frontend_vtable(m->frontend),
spl_exec_vm_vtable(m->backend));
if (!m->exec) {
m->failed = true;
return false;
}
spl_exec_set_phase(m->exec, SPL_EXEC_PHASE_META, 0);
if (!spl_sap_bind(m->exec, m->sap)) {
m->failed = true;
return false;
}
return true;
}
spl_sap_t *spl_meta_sap(spl_meta_t *m) { return m ? m->sap : NULL; }
spl_sap_handle_t spl_meta_register_handle(spl_meta_t *m, spl_ast_t *ast,
spl_ast_node_ref_t ref) {
if (!m || !m->sap)
return 0;
return spl_sap_handle_register(m->sap, ast, ref);
}
bool spl_meta_invoke(spl_meta_t *m, spl_def_id_t def_id, const usize *args, usize nargs,
usize *out) {
if (!m || !out || !spl_meta_prepare(m))
return false;
spl_ir_func_ref_t fn = spl_ir_link_reserve_fn(spl_exec_frontend_link(m->frontend), def_id);
if (!fn)
return false;
return spl_exec_run(m->exec, fn, args, nargs, out);
}
+134
View File
@@ -0,0 +1,134 @@
#include "spl_meta.h"
static bool meta_const_bits(spl_ast_node_t *n, usize *out) {
if (!n)
return false;
switch (n->kind) {
case SPL_AST_EXPR_INT_LIT:
*out = (usize)n->int_lit.bits;
return true;
case SPL_AST_EXPR_BOOL_LIT:
*out = n->bool_lit.val ? 1 : 0;
return true;
case SPL_AST_EXPR_CHAR_LIT:
*out = (usize)(unsigned char)n->char_lit.val;
return true;
case SPL_AST_EXPR_NULL_LIT:
*out = 0;
return true;
default:
return false;
}
}
spl_lang_type_id_t spl_meta_eval_call(spl_sema_t *sema, spl_ast_node_t *n, spl_def_id_t def_id) {
if (!sema->meta) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_UNHANDLED_NODE, &n->dbg,
"compile-time execution is not available");
return 0;
}
spl_def_node_t *def = spl_def_node(sema->type, def_id);
if (!def) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_UNDEFINED_SYMBOL, &n->dbg,
"meta function definition not found");
return 0;
}
spl_lang_type_id_t fn_tid = def->lang_id;
if (fn_tid == 0)
fn_tid = spl_sema_eval_decl(sema, def_id);
spl_lang_type_node_t *fn = spl_lang_type_node(sema->type, fn_tid);
if (!fn || fn->kind != SPL_LANG_TYPE_FN) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_NOT_A_FUNCTION, &n->dbg,
"`@%s` is not a meta function", n->compile_call.name);
return 0;
}
usize nargs = vec_size(n->compile_call.args);
usize nparams = vec_size(fn->extra.fn.params);
if (nargs != nparams) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_ARG_COUNT_MISMATCH, &n->dbg,
"meta call argument count mismatch (expected %zu, got %zu)", nparams, nargs);
return 0;
}
/* 后续求值会继续 push lang_table,先把签名拷出来。 */
spl_lang_type_id_t ret_tid = fn->extra.fn.ret;
spl_lang_type_id_t *params = nparams ? malloc(nparams * sizeof(*params)) : NULL;
if (nparams && !params) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_INTERNAL, &n->dbg, "out of memory");
return 0;
}
for (usize i = 0; i < nparams; ++i)
params[i] = vec_at(fn->extra.fn.params, i);
if (sema->current_fn_kind != SPL_DEF_FN_NORMAL) {
/* 编译期函数体内部:这里只做类型检查,调用留到 meta IR 执行。 */
for (usize i = 0; i < nparams; ++i) {
spl_ast_node_ref_t aref = vec_at(n->compile_call.args, i);
if (!spl_sema_coerce_expr(sema, aref, params[i])) {
free(params);
return 0;
}
}
free(params);
n->resolved_def_id = def_id;
n->resolved_lang_tid = ret_tid;
return ret_tid;
}
usize *bits = nparams ? calloc(nparams, sizeof(*bits)) : NULL;
if (nparams && !bits) {
free(params);
spl_diag_error(sema->diag, SPL_DIAG_KIND_INTERNAL, &n->dbg, "out of memory");
return 0;
}
for (usize i = 0; i < nparams; ++i) {
spl_ast_node_ref_t aref = vec_at(n->compile_call.args, i);
if (!spl_sema_coerce_expr(sema, aref, params[i])) {
free(params);
free(bits);
return 0;
}
spl_ast_node_t *arg = spl_ast_node(sema->ast, aref);
if (!meta_const_bits(arg, &bits[i])) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_TYPE_MISMATCH, arg ? &arg->dbg : &n->dbg,
"meta call argument must be a compile-time constant");
free(params);
free(bits);
return 0;
}
}
free(params);
usize result = 0;
bool ok = spl_meta_invoke(sema->meta, def_id, bits, nparams, &result);
free(bits);
if (!ok) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_INTERNAL, &n->dbg,
"compile-time call `@%s` failed", n->compile_call.name);
return 0;
}
spl_lang_type_node_t *ret = spl_lang_type_node(sema->type, ret_tid);
if (ret && ret->kind == SPL_LANG_TYPE_INT) {
vec_free(n->compile_call.args);
n->kind = SPL_AST_EXPR_INT_LIT;
n->int_lit.bits = (uint64_t)result;
} else if (ret && ret->kind == SPL_LANG_TYPE_BOOL) {
vec_free(n->compile_call.args);
n->kind = SPL_AST_EXPR_BOOL_LIT;
n->bool_lit.val = result != 0;
} else if (ret && ret->kind == SPL_LANG_TYPE_UNIT) {
return ret_tid;
} else {
spl_diag_error(sema->diag, SPL_DIAG_KIND_TYPE_MISMATCH, &n->dbg,
"meta call result type cannot land as a constant yet");
return 0;
}
n->resolved_lang_tid = ret_tid;
return ret_tid;
}
+166
View File
@@ -0,0 +1,166 @@
#include "spl_module.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
static const char *path_basename(const char *path) {
const char *base = path;
for (const char *p = path; *p; ++p)
if (*p == '/' || *p == '\\')
base = p + 1;
return base;
}
bool spl_module_name_from_path(const char *path, char *out, usize cap) {
if (!path || !out || cap == 0)
return false;
const char *base = path_basename(path);
const char *dot = strrchr(base, '.');
usize len = dot && dot != base ? (usize)(dot - base) : strlen(base);
if (len == 0)
return false;
usize w = 0;
if (isdigit((unsigned char)base[0])) {
if (w + 1 >= cap)
return false;
out[w++] = '_';
}
for (usize i = 0; i < len && w + 1 < cap; ++i) {
unsigned char c = (unsigned char)base[i];
out[w++] = (isalnum(c) || c == '_') ? (char)c : '_';
}
out[w] = '\0';
return w > 0;
}
const char *spl_module_declared_name(spl_ast_t *ast) {
if (!ast || !ast->root)
return NULL;
spl_ast_node_t *root = spl_ast_node(ast, ast->root);
if (!root || root->kind != SPL_AST_ROOT || !root->root.members)
return NULL;
spl_ast_node_t *cm = spl_ast_node(ast, root->root.members);
if (!cm || cm->kind != SPL_AST_CONTAINER_MEMBERS || !cm->container_members.module)
return NULL;
spl_ast_node_t *mod = spl_ast_node(ast, cm->container_members.module);
if (!mod || mod->kind != SPL_AST_MOD_DECL)
return NULL;
return mod->mod_decl.path;
}
spl_ast_node_ref_t spl_module_container(spl_module_t *mod) {
if (!mod || !mod->ast || !mod->ast->root)
return 0;
spl_ast_node_t *root = spl_ast_node(mod->ast, mod->ast->root);
if (!root || root->kind != SPL_AST_ROOT)
return 0;
return root->root.members;
}
const char *spl_module_last_segment(const char *name) {
if (!name)
return NULL;
const char *last = name;
for (const char *p = name; *p; ++p)
if (*p == '.')
last = p + 1;
return last;
}
void spl_module_registry_init(spl_module_registry_t *reg) {
vec_init(reg->modules);
map_init(reg->by_name, MAP_HASH_STR, MAP_CMP_STR);
map_init(reg->by_path, MAP_HASH_STR, MAP_CMP_STR);
}
void spl_module_registry_drop(spl_module_registry_t *reg) {
for (usize i = 0; i < vec_size(reg->modules); ++i) {
free(vec_at(reg->modules, i).name);
free(vec_at(reg->modules, i).file_path);
}
vec_free(reg->modules);
map_free(reg->by_name);
map_free(reg->by_path);
}
spl_module_t *spl_module_get(spl_module_registry_t *reg, spl_module_id_t id) {
if (!reg || id == 0 || id > vec_size(reg->modules))
return NULL;
return &vec_at(reg->modules, id - 1);
}
spl_module_id_t spl_module_find_name(spl_module_registry_t *reg, const char *name) {
spl_module_id_t id = 0;
if (!reg || !name)
return 0;
if (map_get(reg->by_name, name, &id))
return id;
return 0;
}
spl_module_id_t spl_module_find_ast(spl_module_registry_t *reg, spl_ast_t *ast) {
if (!reg || !ast)
return 0;
for (usize i = 0; i < vec_size(reg->modules); ++i)
if (vec_at(reg->modules, i).ast == ast)
return vec_at(reg->modules, i).id;
return 0;
}
spl_module_id_t spl_module_register(spl_module_registry_t *reg, spl_ast_t *ast,
const char *file_path, const char *declared_name,
spl_diag_t *diag) {
if (!reg || !ast)
return 0;
char derived[256];
const char *name = declared_name;
if (!name || !*name) {
if (!file_path || !spl_module_name_from_path(file_path, derived, sizeof derived)) {
spl_diag_error(diag, SPL_DIAG_KIND_INTERNAL, NULL, "cannot derive module name");
return 0;
}
name = derived;
}
spl_module_id_t existing_path = 0;
if (file_path && map_get(reg->by_path, file_path, &existing_path))
return existing_path;
spl_module_id_t existing_name = 0;
if (map_get(reg->by_name, name, &existing_name)) {
spl_module_t *old = spl_module_get(reg, existing_name);
spl_diag_error(diag, SPL_DIAG_KIND_DUPLICATE_SYMBOL, NULL,
"duplicate module `%s` (already loaded from `%s`)", name,
old && old->file_path ? old->file_path : "?");
return 0;
}
spl_module_t mod = {0};
mod.id = vec_size(reg->modules) + 1;
mod.name = strdup(name);
mod.file_path = file_path ? strdup(file_path) : NULL;
mod.ast = ast;
mod.state = SPL_MODULE_LOADED;
mod.sema_state = 0;
spl_ast_node_t *root = spl_ast_node(ast, ast->root);
if (root && root->kind == SPL_AST_ROOT && root->root.members) {
mod.container = root->root.members;
spl_ast_node_t *cm = spl_ast_node(ast, mod.container);
if (cm && cm->kind == SPL_AST_CONTAINER_MEMBERS && cm->container_members.module) {
spl_ast_node_t *header = spl_ast_node(ast, cm->container_members.module);
if (header && header->kind == SPL_AST_MOD_DECL)
mod.state = SPL_MODULE_LOADED;
}
}
vec_push(reg->modules, mod);
spl_module_t *stored = &vec_at(reg->modules, vec_size(reg->modules) - 1);
map_put(reg->by_name, stored->name, stored->id);
if (stored->file_path)
map_put(reg->by_path, stored->file_path, stored->id);
return stored->id;
}
+167
View File
@@ -0,0 +1,167 @@
#include "spl_namespace.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *ns_strdup(const char *s) {
if (!s)
return NULL;
usize n = strlen(s);
char *r = malloc(n + 1);
if (!r)
return NULL;
memcpy(r, s, n + 1);
return r;
}
static const char *ns_name_or_default(const char *name, spl_ns_id_t id, char *buf, usize cap) {
if (name && *name)
return name;
snprintf(buf, cap, "$ns%zu", id);
return buf;
}
void spl_ns_init(spl_namespace_t *ns) {
vec_init(ns->nodes);
spl_ns_node_t dummy = {0};
vec_push(ns->nodes, dummy);
ns->root = 0;
ns->current = 0;
ns->root = spl_ns_create(ns, 0, SPL_NS_ROOT, "pkg", 0, 0);
ns->current = ns->root;
}
void spl_ns_drop(spl_namespace_t *ns) {
for (usize i = 0; i < vec_size(ns->nodes); ++i) {
free((char *)vec_at(ns->nodes, i).name);
free((char *)vec_at(ns->nodes, i).qualified);
map_free(vec_at(ns->nodes, i).symbols);
}
vec_free(ns->nodes);
ns->root = 0;
ns->current = 0;
}
spl_ns_id_t spl_ns_root(spl_namespace_t *ns) {
if (!ns)
return 0;
if (ns->root == 0)
ns->root = spl_ns_create(ns, 0, SPL_NS_ROOT, "pkg", 0, 0);
return ns->root;
}
spl_ns_id_t spl_ns_create(spl_namespace_t *ns, spl_ns_id_t parent, spl_ns_kind_t kind,
const char *name, usize owner_kind, usize owner_id) {
if (!ns)
return 0;
spl_ns_id_t id = vec_size(ns->nodes);
char name_buf[32];
const char *resolved_name = ns_name_or_default(name, id, name_buf, sizeof name_buf);
const char *parent_qualified = NULL;
if (parent && parent < vec_size(ns->nodes))
parent_qualified = vec_at(ns->nodes, parent).qualified;
usize cap = strlen(resolved_name) + (parent_qualified ? strlen(parent_qualified) + 2 : 1);
char *qualified = malloc(cap);
if (!qualified)
return 0;
if (parent_qualified && *parent_qualified)
snprintf(qualified, cap, "%s.%s", parent_qualified, resolved_name);
else
snprintf(qualified, cap, "%s", resolved_name);
spl_ns_node_t node = {0};
node.id = id;
node.parent = parent;
node.kind = kind;
node.name = ns_strdup(resolved_name);
node.qualified = qualified;
node.owner_kind = owner_kind;
node.owner_id = owner_id;
map_init(node.symbols, MAP_HASH_STR, MAP_CMP_STR);
vec_push(ns->nodes, node);
if (!ns->root)
ns->root = id;
return id;
}
spl_ns_id_t spl_ns_alloc(spl_namespace_t *ns, spl_ns_kind_t kind, const char *name) {
if (!ns)
return 0;
spl_ns_id_t parent = ns->current ? ns->current : spl_ns_root(ns);
return spl_ns_create(ns, parent, kind, name, 0, 0);
}
bool spl_ns_enter(spl_namespace_t *ns, spl_ns_id_t id) {
if (!ns || id == 0 || id >= vec_size(ns->nodes))
return false;
ns->current = id;
return true;
}
bool spl_ns_leave(spl_namespace_t *ns) {
if (!ns || ns->current == 0)
return false;
ns->current = vec_at(ns->nodes, ns->current).parent;
return true;
}
bool spl_ns_insert(spl_namespace_t *ns, spl_ns_id_t id, spl_symbol_t symbol) {
if (!ns || id == 0 || id >= vec_size(ns->nodes) || !symbol.name)
return false;
spl_ns_node_t *node = &vec_at(ns->nodes, id);
spl_symbol_t old = {0};
if (map_get(node->symbols, symbol.name, &old))
return false;
map_put(node->symbols, symbol.name, symbol);
return true;
}
bool spl_ns_lookup(spl_namespace_t *ns, const char *name, spl_symbol_t *out) {
if (!ns || !name || !out)
return false;
spl_ns_id_t id = ns->current ? ns->current : ns->root;
for (; id != 0 && id < vec_size(ns->nodes); id = vec_at(ns->nodes, id).parent) {
if (map_get(vec_at(ns->nodes, id).symbols, name, out))
return true;
}
return false;
}
bool spl_ns_lookup_local(spl_namespace_t *ns, spl_ns_id_t id, const char *name,
spl_symbol_t *out) {
if (!ns || id == 0 || id >= vec_size(ns->nodes) || !name || !out)
return false;
return map_get(vec_at(ns->nodes, id).symbols, name, out);
}
const char *spl_ns_qualified(spl_namespace_t *ns, spl_ns_id_t id) {
if (!ns || id == 0 || id >= vec_size(ns->nodes))
return NULL;
return vec_at(ns->nodes, id).qualified;
}
bool spl_ns_symbol_qualified(spl_namespace_t *ns, spl_ns_id_t id, const char *local_name,
char *out, usize cap) {
if (!out || cap == 0)
return false;
const char *prefix = spl_ns_qualified(ns, id);
if (!prefix || !local_name)
return false;
int n = snprintf(out, cap, "%s.%s", prefix, local_name);
return n >= 0 && (usize)n < cap;
}
spl_ns_id_t spl_ns_child(spl_namespace_t *ns, spl_ns_id_t parent, const char *name) {
if (!ns || !name)
return 0;
for (usize i = 1; i < vec_size(ns->nodes); ++i) {
spl_ns_node_t *n = &vec_at(ns->nodes, i);
if (n->parent == parent && n->name && strcmp(n->name, name) == 0)
return n->id;
}
return 0;
}
+381 -170
View File
@@ -87,11 +87,18 @@ static inline const spl_tok_t *peek(spl_parser_t *p) {
static inline const spl_tok_t *advance(spl_parser_t *p) {
const spl_tok_t *t = peek(p);
if (t && t->type != TOK_EOF)
if (t && t->type != TOK_EOF) {
p->last_tok_line = t->line;
p->pos++;
}
return t;
}
static inline int line_changed(const spl_parser_t *p) {
const spl_tok_t *t = &vec_at(p->ast->input, p->pos);
return t->line > p->last_tok_line;
}
static inline spl_ast_node_t *node_at(spl_ast_t *ast, spl_ast_node_ref_t ref) {
return &ast->node_buckets.data[ref];
}
@@ -209,7 +216,6 @@ static int can_start_expr(spl_tok_type_t t) {
case KW_UNDEFINED:
case TOK_IDENT:
case TOK_AT:
case TOK_SHARP:
case TOK_DOLLAR:
case TOK_L_PAREN:
case TOK_L_BRACKET:
@@ -220,6 +226,10 @@ static int can_start_expr(spl_tok_type_t t) {
case TOK_BIT_NOT:
case TOK_AND:
case TOK_MUL:
case KW_RET:
case KW_BREAK:
case KW_CONTINUE:
case KW_DEFER:
case KW_IF:
case KW_WHILE:
case KW_LOOP:
@@ -245,7 +255,10 @@ static int can_start_statement(spl_tok_type_t t) {
case KW_VAR:
case KW_CONST:
case KW_TYPE:
case KW_COMPTIME:
case KW_FN:
case KW_META:
case KW_MACRO:
case TOK_SHARP:
return 1;
default:
return 0;
@@ -266,13 +279,17 @@ static spl_ast_node_ref_t parse_expr(spl_parser_t *p);
static spl_ast_node_ref_vec_t parse_expr_list(spl_parser_t *p);
static spl_ast_node_ref_t parse_block(spl_parser_t *p);
static spl_ast_node_ref_t parse_type_expr(spl_parser_t *p);
static spl_ast_node_ref_t parse_type_comptime_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_type_compile_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_statement(spl_parser_t *p);
static spl_ast_node_ref_t parse_container_declaration(spl_parser_t *p);
static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p);
static spl_ast_node_ref_t parse_pattern(spl_parser_t *p);
static spl_ast_node_ref_t parse_pattern_atom(spl_parser_t *p);
static spl_ast_node_ref_t parse_pattern_aggregate(spl_parser_t *p, const spl_tok_t *start);
static void parse_decorators(spl_parser_t *p, spl_ast_node_ref_vec_t *out);
static void parse_attributes(spl_parser_t *p, spl_ast_node_ref_vec_t *out);
static void parse_external_tags(spl_parser_t *p, spl_ast_node_ref_vec_t *out);
static const char *parse_dotted_path(spl_parser_t *p, const char *what);
static spl_ast_node_ref_t parse_cast(spl_parser_t *p);
static spl_ast_node_ref_t parse_prefix(spl_parser_t *p);
@@ -280,7 +297,7 @@ static spl_ast_node_ref_t parse_postfix(spl_parser_t *p);
static spl_ast_node_ref_t parse_primary(spl_parser_t *p);
static spl_ast_node_ref_vec_t parse_aggregate_fields(spl_parser_t *p);
static spl_ast_node_ref_t parse_array_literal(spl_parser_t *p);
static spl_ast_node_ref_t parse_comptime_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_compile_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_if_expr(spl_parser_t *p);
static spl_ast_node_ref_t parse_while_expr(spl_parser_t *p);
static spl_ast_node_ref_t parse_loop_expr(spl_parser_t *p);
@@ -290,7 +307,6 @@ static spl_ast_node_ref_t parse_ret_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_break_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_continue_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_defer_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_comptime_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_label(spl_parser_t *p);
/* ---------- Pattern ---------- */
@@ -395,6 +411,9 @@ static spl_ast_node_ref_t parse_pattern_atom(spl_parser_t *p) {
case KW_NULL:
advance(p);
return new_node(p, SPL_AST_EXPR_NULL_LIT, t);
case KW_UNDEFINED:
advance(p);
return new_node(p, SPL_AST_EXPR_UNDEFINED_LIT, t);
case TOK_IDENT: {
advance(p);
@@ -510,49 +529,129 @@ static spl_ast_node_ref_t parse_pattern(spl_parser_t *p) {
/* ---------- 声明 ---------- */
static void parse_tag_list(spl_parser_t *p, spl_ast_node_ref_vec_t *out, int is_external,
int allow_at) {
while (!p->failed) {
static const char *parse_dotted_path(spl_parser_t *p, const char *what) {
const spl_tok_t *t = peek(p);
if (!t || (t->type != TOK_AT && t->type != TOK_SHARP))
return;
if (!allow_at && t->type == TOK_AT)
return;
int is_at = (t->type == TOK_AT);
advance(p);
if (is_external) {
t = peek(p);
if (!t || t->type != TOK_NOT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected '!' in external tag");
return;
}
advance(p);
if (!t || t->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected %s", what);
return NULL;
}
usize cap = 64;
usize len = 0;
char *buf = malloc(cap);
if (!buf)
return NULL;
while (1) {
if (len + t->len + 2 > cap) {
cap = (len + t->len + 2) * 2;
char *grown = realloc(buf, cap);
if (!grown) {
free(buf);
return NULL;
}
buf = grown;
}
memcpy(buf + len, t->lexeme, t->len);
len += t->len;
advance(p);
if (!peek(p) || peek(p)->type != TOK_DOT)
break;
advance(p);
t = peek(p);
if (!t || t->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected tag name");
return;
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected identifier after '.'");
break;
}
buf[len++] = '.';
}
advance(p);
const char *name = intern_string(p->ast, buf, len);
free(buf);
return name;
}
static spl_ast_node_ref_t parse_tag_item(spl_parser_t *p, const spl_tok_t *start, int is_external,
int is_at) {
spl_ast_node_ref_t ref =
new_node(p, is_external ? SPL_AST_EXTERNAL_TAG_ITEM : SPL_AST_TAG_ITEM, t);
new_node(p, is_external ? SPL_AST_EXTERNAL_TAG_ITEM : SPL_AST_TAG_ITEM, start);
spl_ast_node_t *tag = node_at(p->ast, ref);
tag->tag_item.is_at = is_at;
tag->tag_item.is_external = is_external;
SET_STR_FIELD(p->ast, tag->tag_item.name, t);
vec_init(tag->tag_item.args);
t = peek(p);
if (is_at) {
const char *name = parse_dotted_path(p, "decorator name");
if (!name)
return ref;
node_at(p->ast, ref)->tag_item.name = name;
} else {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected tag name");
return ref;
}
advance(p);
SET_STR_FIELD(p->ast, tag->tag_item.name, t);
}
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_L_PAREN) {
advance(p);
spl_ast_node_ref_vec_t args = parse_expr_list(p);
node_at(p->ast, ref)->tag_item.args = args;
if (!expect(p, TOK_R_PAREN, "')' in tag args"))
expect(p, TOK_R_PAREN, "')' in tag args");
}
return ref;
}
static void parse_attributes(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_SHARP)
return;
advance(p);
spl_ast_node_ref_t ref = parse_tag_item(p, t, 0, 0);
vec_push(*out, ref);
}
}
static void parse_decorators(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_AT)
return;
advance(p);
spl_ast_node_ref_t ref = parse_tag_item(p, t, 0, 1);
vec_push(*out, ref);
}
}
static void parse_external_tags(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_SHARP)
return;
usize save = p->pos;
usize save_line = p->last_tok_line;
advance(p);
const spl_tok_t *bang = peek(p);
if (!bang || bang->type != TOK_NOT) {
p->pos = save;
p->last_tok_line = save_line;
return;
}
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected external tag name");
return;
}
spl_ast_node_ref_t ref = parse_tag_item(p, t, 1, 0);
node_at(p->ast, ref)->tag_item.name =
intern_string(p->ast, name->lexeme, name->len);
vec_push(*out, ref);
}
}
@@ -565,7 +664,7 @@ static void parse_param_list(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
if (t->type == TOK_R_PAREN) {
break;
} else if (t->type == TOK_AT || t->type == TOK_SHARP || t->type == TOK_IDENT) {
} else if (t->type == TOK_SHARP || t->type == TOK_IDENT) {
spl_ast_node_ref_t pd = parse_param_decl_impl(p);
if (pd)
vec_push(*out, pd);
@@ -594,7 +693,7 @@ static void parse_param_list(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p) {
spl_ast_node_ref_vec_t attr_list;
vec_init(attr_list);
parse_tag_list(p, &attr_list, 0, 1);
parse_attributes(p, &attr_list);
const spl_tok_t *name = peek(p);
if (!name || (name->type != TOK_IDENT && name->type != KW_UNDERSCORE)) {
@@ -609,7 +708,7 @@ static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p) {
return 0;
}
parse_tag_list(p, &attr_list, 0, 0);
parse_attributes(p, &attr_list);
spl_ast_node_ref_t type_expr = parse_type_expr(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_PARAM_DECL, name);
@@ -620,8 +719,9 @@ static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p) {
return ref;
}
static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list) {
const spl_tok_t *kw = peek(p);
static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list, spl_fn_kind_t fn_kind,
const spl_tok_t *kw) {
if (!kw || kw->type != KW_FN)
return 0;
advance(p);
@@ -629,13 +729,15 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name ? name : kw, "expected function name");
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
if (!expect(p, TOK_L_PAREN, "'(' in function declaration")) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
@@ -643,7 +745,8 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
vec_init(params);
parse_param_list(p, &params);
if (!expect(p, TOK_R_PAREN, "')' in function declaration")) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
vec_free(params);
return 0;
}
@@ -664,15 +767,17 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
} else {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, t,
"function declaration must end with ';' or block");
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
vec_free(params);
return 0;
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_FN_DECL, kw);
spl_ast_node_t *fn = node_at(p->ast, ref);
MOVE_VEC(fn->fn_decl.tag_list, tag_list);
fn->fn_decl.is_comptime = 0;
MOVE_VEC(fn->fn_decl.decorator_list, decorator_list);
MOVE_VEC(fn->fn_decl.attr_list, attr_list);
fn->fn_decl.fn_kind = fn_kind;
SET_STR_FIELD(p->ast, fn->fn_decl.name, name);
fn->fn_decl.params = params;
fn->fn_decl.ret_type = ret_type;
@@ -680,27 +785,34 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
return ref;
}
static spl_ast_node_ref_t parse_type_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list) {
static spl_ast_node_ref_t parse_type_decl(spl_parser_t *p, spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_TYPE)
if (!kw || kw->type != KW_TYPE) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
spl_ast_node_ref_t pattern = parse_pattern(p);
if (!pattern) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, peek(p), "expected pattern after 'type'");
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
if (!expect(p, TOK_ASSIGN, "'=' in type declaration")) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_DECL, kw);
spl_ast_node_t *td = node_at(p->ast, ref);
MOVE_VEC(td->type_decl.attr_list, tag_list);
MOVE_VEC(td->type_decl.decorator_list, decorator_list);
MOVE_VEC(td->type_decl.attr_list, attr_list);
td->type_decl.pattern = pattern;
spl_ast_node_ref_t type_expr = parse_type_expr(p);
@@ -713,20 +825,31 @@ static spl_ast_node_ref_t parse_type_decl(spl_parser_t *p, spl_ast_node_ref_vec_
return ref;
}
static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list,
int is_const) {
static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p,
spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list, int is_const) {
const spl_tok_t *kw = peek(p);
if (!kw)
if (!kw) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
if (is_const && kw->type != KW_CONST)
}
if (is_const && kw->type != KW_CONST) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
if (!is_const && kw->type != KW_VAR)
}
if (!is_const && kw->type != KW_VAR) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
spl_ast_node_ref_t pattern = parse_pattern(p);
if (!pattern) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
@@ -749,7 +872,8 @@ static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p, spl_ast_node_ref
spl_ast_node_ref_t ref = new_node(p, is_const ? SPL_AST_CONST_DECL : SPL_AST_VAR_DECL, kw);
spl_ast_node_t *vc = node_at(p->ast, ref);
MOVE_VEC(vc->var_const_decl.attr_list, tag_list);
MOVE_VEC(vc->var_const_decl.decorator_list, decorator_list);
MOVE_VEC(vc->var_const_decl.attr_list, attr_list);
vc->var_const_decl.pattern = pattern;
vc->var_const_decl.type = type_expr;
vc->var_const_decl.init_expr = init_expr;
@@ -760,10 +884,15 @@ static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p, spl_ast_node_ref
return ref;
}
static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list) {
static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p,
spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list) {
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT)
if (!name || name->type != TOK_IDENT) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
spl_ast_node_ref_t type_expr = 0;
@@ -771,7 +900,7 @@ static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_ve
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_COLON) {
advance(p);
parse_tag_list(p, &tag_list, 0, 0);
parse_attributes(p, &attr_list);
type_expr = parse_type_expr(p);
t = peek(p);
if (t && t->type == TOK_ASSIGN) {
@@ -785,7 +914,8 @@ static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_ve
spl_ast_node_ref_t ref = new_node(p, SPL_AST_MEMBER_DECL, name);
spl_ast_node_t *md = node_at(p->ast, ref);
MOVE_VEC(md->member_decl.attr_list, tag_list);
MOVE_VEC(md->member_decl.decorator_list, decorator_list);
MOVE_VEC(md->member_decl.attr_list, attr_list);
SET_STR_FIELD(p->ast, md->member_decl.name, name);
md->member_decl.type_expr = type_expr;
md->member_decl.init_expr = init_expr;
@@ -796,61 +926,178 @@ static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_ve
return ref;
}
static spl_ast_node_ref_t parse_comptime_decl(spl_parser_t *p) {
static spl_ast_node_ref_t parse_mod_decl(spl_parser_t *p, spl_ast_node_ref_vec_t decorator_list) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_COMPTIME)
if (!kw || kw->type != KW_MOD) {
vec_free(decorator_list);
return 0;
}
advance(p);
spl_ast_node_ref_t body = 0;
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_L_BRACE)
body = parse_block(p);
else
body = parse_expr(p);
const char *path = parse_dotted_path(p, "module path");
if (!path) {
vec_free(decorator_list);
return 0;
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_COMPTIME_DECL, kw);
node_at(p->ast, ref)->comptime_decl.body = body;
spl_ast_node_ref_t ref = new_node(p, SPL_AST_MOD_DECL, kw);
spl_ast_node_t *mod = node_at(p->ast, ref);
MOVE_VEC(mod->mod_decl.decorator_list, decorator_list);
mod->mod_decl.path = path;
mod->mod_decl.has_body = false;
vec_init(mod->mod_decl.decls);
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_SEMICOLON) {
advance(p);
return ref;
}
if (!t || t->type != TOK_L_BRACE) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected ';' or '{' after module path");
return ref;
}
advance(p);
mod = node_at(p->ast, ref);
mod->mod_decl.has_body = true;
while (!p->failed) {
t = peek(p);
if (!t || t->type == TOK_EOF) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "module missing '}'");
break;
}
if (t->type == TOK_R_BRACE) {
advance(p);
break;
}
spl_ast_node_ref_t decl = parse_container_declaration(p);
mod = node_at(p->ast, ref);
if (decl)
vec_push(mod->mod_decl.decls, decl);
else
break;
t = peek(p);
if (t && (t->type == TOK_COMMA || t->type == TOK_SEMICOLON))
advance(p);
}
return ref;
}
static spl_ast_node_ref_t parse_import_decl(spl_parser_t *p,
spl_ast_node_ref_vec_t decorator_list) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_IMPORT) {
vec_free(decorator_list);
return 0;
}
advance(p);
bool is_path = true;
const char *path = NULL;
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_STRING_LITERAL) {
advance(p);
usize len = 0;
path = parse_string_literal(p, t, &len);
is_path = false;
} else {
path = parse_dotted_path(p, "import path");
if (!path) {
vec_free(decorator_list);
return 0;
}
}
const char *alias = NULL;
t = peek(p);
if (t && t->type == KW_AS) {
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected alias after 'as'");
vec_free(decorator_list);
return 0;
}
advance(p);
alias = intern_string(p->ast, name->lexeme, name->len);
t = peek(p);
}
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_IMPORT_DECL, kw);
spl_ast_node_t *imp = node_at(p->ast, ref);
MOVE_VEC(imp->import_decl.decorator_list, decorator_list);
imp->import_decl.is_path = is_path;
imp->import_decl.path = path;
imp->import_decl.alias = alias;
return ref;
}
static spl_ast_node_ref_t parse_container_declaration(spl_parser_t *p) {
spl_ast_node_ref_vec_t tag_list;
vec_init(tag_list);
parse_tag_list(p, &tag_list, 0, 0);
spl_ast_node_ref_vec_t decorator_list;
vec_init(decorator_list);
parse_decorators(p, &decorator_list);
spl_ast_node_ref_vec_t attr_list;
vec_init(attr_list);
parse_attributes(p, &attr_list);
const spl_tok_t *t = peek(p);
if (!t || t->type == TOK_EOF) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
switch (t->type) {
case KW_FN:
return parse_fn_decl(p, tag_list);
return parse_fn_decl(p, decorator_list, attr_list, SPL_FN_KIND_NORMAL, t);
case KW_META:
case KW_MACRO: {
spl_fn_kind_t fn_kind = (t->type == KW_META) ? SPL_FN_KIND_META : SPL_FN_KIND_MACRO;
advance(p);
const spl_tok_t *fn_kw = peek(p);
if (!fn_kw || fn_kw->type != KW_FN) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, fn_kw, "expected 'fn' after '%s'",
fn_kind == SPL_FN_KIND_META ? "meta" : "macro");
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
return parse_fn_decl(p, decorator_list, attr_list, fn_kind, fn_kw);
}
case KW_TYPE:
return parse_type_decl(p, tag_list);
return parse_type_decl(p, decorator_list, attr_list);
case KW_VAR:
return parse_var_const_decl(p, tag_list, 0);
return parse_var_const_decl(p, decorator_list, attr_list, 0);
case KW_CONST:
return parse_var_const_decl(p, tag_list, 1);
return parse_var_const_decl(p, decorator_list, attr_list, 1);
case TOK_IDENT:
return parse_member_decl(p, tag_list);
case KW_COMPTIME:
vec_free(tag_list);
return parse_comptime_decl(p);
return parse_member_decl(p, decorator_list, attr_list);
case KW_MOD:
vec_free(attr_list);
return parse_mod_decl(p, decorator_list);
case KW_IMPORT:
vec_free(attr_list);
return parse_import_decl(p, decorator_list);
case TOK_L_BRACE: {
spl_ast_node_ref_t block = parse_block(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TOP_LEVEL_BLOCK, t);
spl_ast_node_t *tb = node_at(p->ast, ref);
MOVE_VEC(tb->top_level_block.tag_list, tag_list);
MOVE_VEC(tb->top_level_block.decorator_list, decorator_list);
MOVE_VEC(tb->top_level_block.attr_list, attr_list);
tb->top_level_block.block = block;
return ref;
}
default:
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, t, "unrecognized declaration");
advance(p); /* 消费该 token,避免调用方在错误恢复时原地死循环 */
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
}
@@ -871,7 +1118,6 @@ static spl_ast_node_ref_t parse_type_base(spl_parser_t *p) {
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_FN, bt);
spl_ast_node_t *fn_type = node_at(p->ast, ref);
fn_type->type_fn.is_comptime = 0;
vec_init(fn_type->type_fn.params);
while (!p->failed && peek(p) && peek(p)->type != TOK_R_PAREN) {
@@ -945,25 +1191,22 @@ static spl_ast_node_ref_t parse_type_base(spl_parser_t *p) {
return ref;
}
if (bt->type == TOK_AT || bt->type == TOK_SHARP)
return parse_type_comptime_call(p);
if (bt->type == TOK_AT)
return parse_type_compile_call(p);
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, bt, "unrecognized type");
return 0;
}
static spl_ast_node_ref_t parse_type_comptime_call(spl_parser_t *p) {
static spl_ast_node_ref_t parse_type_compile_call(spl_parser_t *p) {
const spl_tok_t *start = peek(p);
if (!start || (start->type != TOK_AT && start->type != TOK_SHARP))
if (!start || start->type != TOK_AT)
return 0;
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected comptime name");
const char *name = parse_dotted_path(p, "compile-time call name");
if (!name)
return 0;
}
advance(p);
spl_ast_node_ref_vec_t args;
vec_init(args);
@@ -972,16 +1215,16 @@ static spl_ast_node_ref_t parse_type_comptime_call(spl_parser_t *p) {
if (t && t->type == TOK_L_PAREN) {
advance(p);
args = parse_expr_list(p);
if (!expect(p, TOK_R_PAREN, "')' in comptime type")) {
if (!expect(p, TOK_R_PAREN, "')' in compile-time type")) {
vec_free(args);
return 0;
}
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_COMPTIME_CALL, start);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_COMPILE_CALL, start);
spl_ast_node_t *cc = node_at(p->ast, ref);
SET_STR_FIELD(p->ast, cc->type_comptime_call.name, name);
cc->type_comptime_call.args = args;
cc->type_compile_call.name = name;
cc->type_compile_call.args = args;
return ref;
}
@@ -1369,6 +1612,14 @@ static spl_ast_node_ref_t parse_prefix(spl_parser_t *p) {
spl_unary_op_t uop;
switch (t->type) {
case KW_RET:
return parse_ret_stmt(p);
case KW_BREAK:
return parse_break_stmt(p);
case KW_CONTINUE:
return parse_continue_stmt(p);
case KW_DEFER:
return parse_defer_stmt(p);
case TOK_SUB:
uop = SPL_UNARY_OP_MINUS;
break;
@@ -1599,8 +1850,7 @@ static spl_ast_node_ref_t parse_primary(spl_parser_t *p) {
case TOK_L_BRACE:
return parse_block(p);
case TOK_AT:
case TOK_SHARP:
return parse_comptime_call(p);
return parse_compile_call(p);
case TOK_L_PAREN: {
advance(p);
@@ -1693,18 +1943,15 @@ static spl_ast_node_ref_t parse_array_literal(spl_parser_t *p) {
return ref;
}
static spl_ast_node_ref_t parse_comptime_call(spl_parser_t *p) {
static spl_ast_node_ref_t parse_compile_call(spl_parser_t *p) {
const spl_tok_t *start = peek(p);
if (!start || (start->type != TOK_AT && start->type != TOK_SHARP))
if (!start || start->type != TOK_AT)
return 0;
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected comptime name");
const char *name = parse_dotted_path(p, "compile-time call name");
if (!name)
return 0;
}
advance(p);
spl_ast_node_ref_vec_t args;
vec_init(args);
@@ -1713,16 +1960,16 @@ static spl_ast_node_ref_t parse_comptime_call(spl_parser_t *p) {
if (t && t->type == TOK_L_PAREN) {
advance(p);
args = parse_expr_list(p);
if (!expect(p, TOK_R_PAREN, "')' in comptime call")) {
if (!expect(p, TOK_R_PAREN, "')' in compile-time call")) {
vec_free(args);
return 0;
}
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_EXPR_COMPTIME_CALL, start);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_EXPR_COMPILE_CALL, start);
spl_ast_node_t *cc = node_at(p->ast, ref);
SET_STR_FIELD(p->ast, cc->comptime_call.name, name);
cc->comptime_call.args = args;
cc->compile_call.name = name;
cc->compile_call.args = args;
return ref;
}
@@ -1998,10 +2245,6 @@ static spl_ast_node_ref_t parse_ret_stmt(spl_parser_t *p) {
if (t && can_start_expr(t->type))
expr = parse_expr(p);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_RET, kw);
node_at(p->ast, ref)->statement_ret.expr = expr;
return ref;
@@ -2019,10 +2262,6 @@ static spl_ast_node_ref_t parse_break_stmt(spl_parser_t *p) {
if (t && can_start_expr(t->type))
expr = parse_expr(p);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_BREAK, kw);
node_at(p->ast, ref)->statement_break.label = label;
node_at(p->ast, ref)->statement_break.expr = expr;
@@ -2037,10 +2276,6 @@ static spl_ast_node_ref_t parse_continue_stmt(spl_parser_t *p) {
spl_ast_node_ref_t label = parse_label(p);
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_CONTINUE, kw);
node_at(p->ast, ref)->statement_continue.label = label;
return ref;
@@ -2060,9 +2295,6 @@ static spl_ast_node_ref_t parse_defer_stmt(spl_parser_t *p) {
body = parse_statement(p);
} else {
body = parse_expr(p);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_DEFER, kw);
@@ -2070,24 +2302,6 @@ static spl_ast_node_ref_t parse_defer_stmt(spl_parser_t *p) {
return ref;
}
static spl_ast_node_ref_t parse_comptime_stmt(spl_parser_t *p) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_COMPTIME)
return 0;
advance(p);
spl_ast_node_ref_t body = 0;
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_L_BRACE)
body = parse_block(p);
else
body = parse_expr(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_COMPTIME, kw);
node_at(p->ast, ref)->statement_comptime.body = body;
return ref;
}
static spl_ast_node_ref_t parse_statement(spl_parser_t *p) {
const spl_tok_t *t = peek(p);
if (!t)
@@ -2102,25 +2316,16 @@ static spl_ast_node_ref_t parse_statement(spl_parser_t *p) {
return parse_continue_stmt(p);
case KW_DEFER:
return parse_defer_stmt(p);
case KW_COMPTIME:
return parse_comptime_stmt(p);
case KW_FN:
case KW_META:
case KW_MACRO:
case KW_VAR:
case KW_CONST:
case KW_TYPE: {
spl_ast_node_ref_vec_t tag_list;
vec_init(tag_list);
parse_tag_list(p, &tag_list, 0, 0);
spl_ast_node_ref_t decl;
if (t->type == KW_VAR)
decl = parse_var_const_decl(p, tag_list, 0);
else if (t->type == KW_CONST)
decl = parse_var_const_decl(p, tag_list, 1);
else
decl = parse_type_decl(p, tag_list);
case KW_TYPE:
case TOK_SHARP: {
spl_ast_node_ref_t decl = parse_container_declaration(p);
if (!decl)
return 0;
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_DECL, t);
node_at(p->ast, ref)->statement_decl.decl = decl;
return ref;
@@ -2167,10 +2372,12 @@ static spl_ast_node_ref_t parse_block(spl_parser_t *p) {
if (can_start_statement(t->type)) {
spl_ast_node_ref_t stmt = parse_statement(p);
block = node_at(p->ast, ref);
if (stmt)
vec_push(block->block.stmts, stmt);
else
if (!stmt)
break;
vec_push(block->block.stmts, stmt);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
} else if (can_start_expr(t->type)) {
spl_ast_node_ref_t expr = parse_expr(p);
if (!expr)
@@ -2192,7 +2399,7 @@ static spl_ast_node_ref_t parse_block(spl_parser_t *p) {
(k == SPL_AST_EXPR_BLOCK || k == SPL_AST_EXPR_IF || k == SPL_AST_EXPR_IFVAR ||
k == SPL_AST_EXPR_WHILE || k == SPL_AST_EXPR_LOOP || k == SPL_AST_EXPR_FOR ||
k == SPL_AST_EXPR_MATCH);
if (block_like)
if (block_like || line_changed(p))
vec_push(block->block.stmts, expr);
else {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t,
@@ -2215,6 +2422,7 @@ void spl_parser_init(spl_parser_t *parser) {
parser->ast = NULL;
parser->diag = NULL;
parser->pos = 0;
parser->last_tok_line = 0;
parser->failed = 0;
parser->stop_agg = 0;
parser->error_count = 0;
@@ -2241,6 +2449,7 @@ void spl_ast_parse(spl_parser_t *parser, spl_ast_t *ast) {
parser->ast = ast;
parser->pos = 0;
parser->last_tok_line = 0;
parser->failed = 0;
parser->stop_agg = 0;
@@ -2248,26 +2457,27 @@ void spl_ast_parse(spl_parser_t *parser, spl_ast_t *ast) {
vec_init(external_tags);
spl_ast_node_ref_vec_t declarations;
vec_init(declarations);
spl_ast_node_ref_t module_ref = 0;
while (!parser->failed) {
const spl_tok_t *t = peek(parser);
if (!t || t->type == TOK_EOF)
break;
if (t->type == TOK_AT || t->type == TOK_SHARP) {
usize save_pos = parser->pos;
const spl_tok_t *t2 = NULL;
parser->pos++;
t2 = peek(parser);
parser->pos = save_pos;
if (t2 && t2->type == TOK_NOT) {
parse_tag_list(parser, &external_tags, 1, 1);
if (t->type == TOK_SHARP) {
usize before = vec_size(external_tags);
parse_external_tags(parser, &external_tags);
if (vec_size(external_tags) > before)
continue;
}
}
spl_ast_node_ref_t decl = parse_container_declaration(parser);
if (decl) {
spl_ast_node_t *dn = node_at(ast, decl);
if (dn->kind == SPL_AST_MOD_DECL && !dn->mod_decl.has_body && module_ref == 0 &&
vec_size(declarations) == 0)
module_ref = decl;
else
vec_push(declarations, decl);
} else if (!parser->failed) {
const spl_tok_t *at = peek(parser);
@@ -2282,6 +2492,7 @@ void spl_ast_parse(spl_parser_t *parser, spl_ast_t *ast) {
spl_ast_node_ref_t container_members = new_node(parser, SPL_AST_CONTAINER_MEMBERS, NULL);
spl_ast_node_t *cm = node_at(ast, container_members);
cm->container_members.external_tags = external_tags;
cm->container_members.module = module_ref;
cm->container_members.declarations = declarations;
spl_ast_node_ref_t root = new_node(parser, SPL_AST_ROOT, NULL);
+260
View File
@@ -0,0 +1,260 @@
#include "spl_sap.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
spl_ast_t *ast;
spl_ast_node_ref_t ref;
} sap_handle_entry_t;
typedef VEC(sap_handle_entry_t) sap_handle_vec_t;
typedef struct {
spl_sap_t *sap;
const spl_sap_op_t *op;
} sap_binding_t;
typedef VEC(sap_binding_t) sap_binding_vec_t;
struct spl_sap {
spl_lang_type_t *type;
spl_lang_type_id_t meta_view_tid;
sap_handle_vec_t handles;
sap_binding_vec_t bindings;
};
static bool sap_host_kind_count(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
(void)sap;
(void)exec;
(void)args;
if (nargs != 0)
return false;
ret->bits = spl_sap_kind_count();
return true;
}
static bool sap_host_kind(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
(void)exec;
if (nargs != 1)
return false;
ret->bits = 0;
spl_sap_handle_t handle = (spl_sap_handle_t)args[0].bits;
if (!handle)
return true;
spl_ast_t *ast = NULL;
spl_ast_node_ref_t ref = 0;
if (!spl_sap_handle_node(sap, handle, &ast, &ref))
return false;
spl_ast_node_t *node = spl_ast_node(ast, ref);
if (!node)
return false;
ret->bits = (usize)node->kind;
return true;
}
static bool sap_write_usize(spl_exec_value_t *ret, usize bit_offset, usize value) {
usize off = bit_offset / 8;
if (!ret || !ret->mem.ptr || off + sizeof(value) > ret->size)
return false;
memcpy((unsigned char *)ret->mem.ptr + off, &value, sizeof(value));
return true;
}
static bool sap_host_view(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
if (nargs != 1 || !ret || !ret->mem.ptr || !ret->size)
return false;
spl_layout_t *layout = spl_exec_layout(exec);
const spl_layout_info_t *info = layout ? spl_layout_info_of(layout, ret->type) : NULL;
if (!info || vec_size(info->field_bit_offsets) < 3)
return false;
memset(ret->mem.ptr, 0, ret->size);
spl_sap_handle_t handle = (spl_sap_handle_t)args[0].bits;
if (!handle)
return true;
spl_ast_t *ast = NULL;
spl_ast_node_ref_t ref = 0;
if (!spl_sap_handle_node(sap, handle, &ast, &ref))
return false;
spl_ast_node_t *node = spl_ast_node(ast, ref);
if (!node)
return false;
usize values[3] = {(usize)node->kind, (usize)node->dbg.line, (usize)node->dbg.col};
for (usize i = 0; i < 3; ++i) {
if (!sap_write_usize(ret, vec_at(info->field_bit_offsets, i), values[i]))
return false;
}
return true;
}
static const spl_sap_op_t g_sap_ops[] = {
{"sap.kind_count", 0, {0}, SPL_SAP_ARG_USIZE, sap_host_kind_count},
{"sap.kind", 1, {SPL_SAP_ARG_HANDLE}, SPL_SAP_ARG_USIZE, sap_host_kind},
{"sap.view", 1, {SPL_SAP_ARG_HANDLE}, SPL_SAP_ARG_VIEW, sap_host_view},
};
static const usize g_sap_op_count = sizeof(g_sap_ops) / sizeof(g_sap_ops[0]);
const spl_sap_op_t *spl_sap_lookup(const char *name) {
if (!name)
return NULL;
for (usize i = 0; i < g_sap_op_count; ++i) {
if (strcmp(g_sap_ops[i].name, name) == 0)
return &g_sap_ops[i];
}
return NULL;
}
const spl_sap_op_t *spl_sap_ops(usize *count) {
if (count)
*count = g_sap_op_count;
return g_sap_ops;
}
spl_lang_type_id_t spl_sap_meta_view_type(spl_sap_t *sap) {
if (!sap || !sap->type)
return 0;
if (sap->meta_view_tid)
return sap->meta_view_tid;
static const char *const names[] = {"kind", "line", "col"};
spl_lang_type_id_t usize_tid = spl_lang_make_int(sap->type, sizeof(void *) * 8, 0);
spl_lang_type_id_t types[3] = {usize_tid, usize_tid, usize_tid};
sap->meta_view_tid = spl_lang_make_struct_named(sap->type, "sap.MetaView", names, types, 3);
return sap->meta_view_tid;
}
const char *const *spl_sap_meta_view_fields(usize *count) {
static const char *const fields[] = {"kind", "line", "col"};
if (count)
*count = 3;
return fields;
}
spl_lang_type_id_t spl_sap_arg_type(spl_sap_t *sap, spl_sap_arg_kind_t kind) {
if (!sap || !sap->type)
return 0;
if (kind == SPL_SAP_ARG_VIEW)
return spl_sap_meta_view_type(sap);
/* Handle 与 usize 在编译期值表示上相同;ViewPoint 再区分。 */
return spl_lang_make_int(sap->type, sizeof(void *) * 8, 0);
}
spl_lang_type_id_t spl_sap_op_fn_type(spl_sap_t *sap, const spl_sap_op_t *op) {
if (!sap || !sap->type || !op || op->nparams > 4)
return 0;
spl_lang_type_id_t params[4];
for (usize i = 0; i < op->nparams; ++i)
params[i] = spl_sap_arg_type(sap, op->params[i]);
spl_lang_type_id_t ret = spl_sap_arg_type(sap, op->ret);
return spl_lang_make_fn(sap->type, ret, params, op->nparams);
}
usize spl_sap_kind_count(void) { return (usize)SPL_AST_COUNT; }
const char *spl_sap_kind_name(usize kind) {
if (kind >= spl_sap_kind_count())
return "?";
return spl_ast_kind_name((spl_ast_node_kind_t)kind);
}
spl_sap_t *spl_sap_create(spl_lang_type_t *type) {
if (!type)
return NULL;
spl_sap_t *sap = calloc(1, sizeof(*sap));
if (!sap)
return NULL;
sap->type = type;
vec_init(sap->handles);
vec_init(sap->bindings);
/* 0 号句柄保留为空。 */
sap_handle_entry_t none = {0};
vec_push(sap->handles, none);
return sap;
}
void spl_sap_destroy(spl_sap_t *sap) {
if (!sap)
return;
vec_free(sap->handles);
vec_free(sap->bindings);
free(sap);
}
spl_sap_handle_t spl_sap_handle_register(spl_sap_t *sap, spl_ast_t *ast,
spl_ast_node_ref_t ref) {
if (!sap || !ast || !ref)
return 0;
for (usize i = 1; i < vec_size(sap->handles); ++i) {
sap_handle_entry_t *entry = &vec_at(sap->handles, i);
if (entry->ast == ast && entry->ref == ref)
return i;
}
sap_handle_entry_t entry = {.ast = ast, .ref = ref};
vec_push(sap->handles, entry);
return vec_size(sap->handles) - 1;
}
bool spl_sap_handle_node(spl_sap_t *sap, spl_sap_handle_t handle, spl_ast_t **ast,
spl_ast_node_ref_t *ref) {
if (!sap || !handle || handle >= vec_size(sap->handles))
return false;
sap_handle_entry_t *entry = &vec_at(sap->handles, handle);
if (ast)
*ast = entry->ast;
if (ref)
*ref = entry->ref;
return true;
}
bool spl_sap_type_lookup(spl_sap_t *sap, const char *name, spl_lang_type_id_t *out) {
if (!sap || !name || !out)
return false;
if (strcmp(name, "Handle") == 0) {
*out = spl_sap_arg_type(sap, SPL_SAP_ARG_HANDLE);
return *out != 0;
}
if (strcmp(name, "MetaView") == 0) {
*out = spl_sap_meta_view_type(sap);
return *out != 0;
}
return false;
}
static bool sap_host_adapter(spl_exec_t *exec, void *user, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
sap_binding_t *binding = (sap_binding_t *)user;
if (!binding || !binding->op || !binding->op->host)
return false;
return binding->op->host(binding->sap, exec, args, nargs, ret);
}
bool spl_sap_bind(spl_exec_t *exec, spl_sap_t *sap) {
if (!exec || !sap)
return false;
sap->bindings.size = 0;
for (usize i = 0; i < g_sap_op_count; ++i) {
sap_binding_t binding = {.sap = sap, .op = &g_sap_ops[i]};
vec_push(sap->bindings, binding);
}
for (usize i = 0; i < vec_size(sap->bindings); ++i) {
sap_binding_t *binding = &vec_at(sap->bindings, i);
spl_exec_host_t host = {
.name = binding->op->name,
.capabilities = SPL_EXEC_CAP_READ,
.fn = sap_host_adapter,
.user = binding,
};
if (!spl_exec_register_host(exec, &host))
return false;
}
return true;
}
@@ -1,8 +1,19 @@
#include "spl_lang_type.h"
static bool spl_lang_is_aggregate_kind(spl_lang_type_kind_t kind) {
return kind == SPL_LANG_TYPE_STRUCT || kind == SPL_LANG_TYPE_UNION ||
kind == SPL_LANG_TYPE_ENUM || kind == SPL_LANG_TYPE_SHAPE;
}
static usize spl_lang_type_hash(spl_lang_type_node_t n) {
usize hash = spl_hash_seed();
hash = spl_hash_mix(hash, (usize)n.kind);
if (spl_lang_is_aggregate_kind(n.kind)) {
/* 声明聚合按 def 唯一;合成聚合按已 intern 的 IR 形状唯一。
members/methods 可能在 reserve 之后才填,不能参与 hash。 */
hash = spl_hash_mix(hash, n.def_id ? n.def_id : n.ir_type_id);
return hash;
}
hash = spl_hash_mix(hash, n.ir_type_id);
switch (n.kind) {
case SPL_LANG_TYPE_PTR:
@@ -23,16 +34,12 @@ static usize spl_lang_type_hash(spl_lang_type_node_t n) {
hash = spl_hash_mix(hash, vec_at(n.extra.fn.params, i));
}
break;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
hash = spl_hash_mix(hash, vec_size(n.methods));
for (usize i = 0; i < vec_size(n.methods); i++) {
spl_lang_method_t *m = &vec_at(n.methods, i);
hash = spl_hash_mix(hash, m->def_id);
hash = spl_hash_mix_str(hash, m->name);
}
case SPL_LANG_TYPE_INT:
hash = spl_hash_mix(hash, n.extra.int_type.bits);
hash = spl_hash_mix(hash, (usize)n.extra.int_type.is_signed);
break;
case SPL_LANG_TYPE_FLOAT:
hash = spl_hash_mix(hash, n.extra.float_type.bits);
break;
default:
break;
@@ -41,7 +48,14 @@ static usize spl_lang_type_hash(spl_lang_type_node_t n) {
}
static int spl_lang_type_eq(spl_lang_type_node_t n1, spl_lang_type_node_t n2) {
if (n1.kind != n2.kind || n1.ir_type_id != n2.ir_type_id)
if (n1.kind != n2.kind)
return 1;
if (spl_lang_is_aggregate_kind(n1.kind)) {
if (n1.def_id || n2.def_id)
return n1.def_id != n2.def_id;
return n1.ir_type_id != n2.ir_type_id;
}
if (n1.ir_type_id != n2.ir_type_id)
return 1;
switch (n1.kind) {
case SPL_LANG_TYPE_PTR:
@@ -66,29 +80,18 @@ static int spl_lang_type_eq(spl_lang_type_node_t n1, spl_lang_type_node_t n2) {
return 1;
}
return 0;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
if (vec_size(n1.methods) != vec_size(n2.methods))
return 1;
for (usize i = 0; i < vec_size(n1.methods); i++) {
spl_lang_method_t *a = &vec_at(n1.methods, i);
spl_lang_method_t *b = &vec_at(n2.methods, i);
if (a->def_id != b->def_id)
return 1;
if ((a->name == NULL) != (b->name == NULL))
return 1;
if (a->name && strcmp(a->name, b->name) != 0)
return 1;
}
return 0;
case SPL_LANG_TYPE_INT:
return (n1.extra.int_type.bits != n2.extra.int_type.bits) ||
(n1.extra.int_type.is_signed != n2.extra.int_type.is_signed);
case SPL_LANG_TYPE_FLOAT:
return n1.extra.float_type.bits != n2.extra.float_type.bits;
default:
return 0;
}
}
static void spl_lang_node_free_extra(spl_lang_type_node_t *n) {
vec_free(n->members);
switch (n->kind) {
case SPL_LANG_TYPE_TUPLE:
vec_free(n->extra.elems);
@@ -140,8 +143,8 @@ spl_lang_type_id_t spl_lang_node_push(spl_lang_type_t *type, spl_lang_type_node_
return id;
}
void spl_lang_type_init(spl_lang_type_t *type) {
spl_type_init(&type->ir);
void spl_lang_type_init(spl_lang_type_t *type, spl_ir_type_table_t *ir_types) {
type->ir_types = ir_types;
vec_init(type->lang_table);
spl_lang_type_node_t lang_node = {0};
@@ -162,8 +165,7 @@ void spl_lang_type_drop(spl_lang_type_t *type) {
vec_free(type->lang_table);
vec_free(type->def_table);
spl_type_drop(&type->ir);
type->ir_types = NULL;
}
spl_lang_type_node_t *spl_lang_type_node(const spl_lang_type_t *type, spl_lang_type_id_t id) {
@@ -178,32 +180,64 @@ spl_def_node_t *spl_def_node(const spl_lang_type_t *type, spl_def_id_t id) {
return &vec_at(type->def_table, id);
}
spl_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id) {
bool spl_def_is_compile_time(const spl_def_node_t *def) {
return def && def->fn_kind != SPL_DEF_FN_NORMAL;
}
bool spl_def_is_macro_fn(const spl_def_node_t *def) {
return def && def->fn_kind == SPL_DEF_FN_MACRO;
}
spl_ir_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id) {
spl_lang_type_node_t *n = spl_lang_type_node(type, lang_id);
return n ? n->ir_type_id : 0;
}
spl_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type) {
spl_type_node_t empty = {0};
empty.kind = SPL_TYPE_ERROR;
empty.layout.mode = SPL_TYPE_LAYOUT_AUTO;
vec_push(type->ir.type_table, empty);
return vec_size(type->ir.type_table) - 1;
const spl_lang_member_t *spl_lang_member_at(spl_lang_type_t *type, spl_lang_type_id_t agg,
usize idx) {
spl_lang_type_node_t *n = spl_lang_type_node(type, agg);
if (!n || idx >= vec_size(n->members))
return NULL;
return &vec_at(n->members, idx);
}
void spl_lang_define_ir(spl_lang_type_t *type, spl_type_id_t id, spl_type_node_t *node) {
if (!id || id >= vec_size(type->ir.type_table))
bool spl_lang_member_idx(spl_lang_type_t *type, spl_lang_type_id_t agg, const char *name,
usize *out_idx) {
spl_lang_type_node_t *n = spl_lang_type_node(type, agg);
if (!n || !name)
return false;
for (usize i = 0; i < vec_size(n->members); ++i) {
spl_lang_member_t *m = &vec_at(n->members, i);
if (m->name && strcmp(m->name, name) == 0) {
if (out_idx)
*out_idx = i;
return true;
}
}
return false;
}
spl_ir_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type) {
spl_ir_type_node_t empty = {0};
empty.kind = SPL_IR_TYPE_ERROR;
empty.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
vec_push(type->ir_types->type_table, empty);
return vec_size(type->ir_types->type_table) - 1;
}
void spl_lang_define_ir(spl_lang_type_t *type, spl_ir_type_id_t id, spl_ir_type_node_t *node) {
if (!id || id >= vec_size(type->ir_types->type_table))
return;
spl_type_node_t *slot = &vec_at(type->ir.type_table, id);
spl_ir_type_node_t *slot = &vec_at(type->ir_types->type_table, id);
/* slot 原是空 ERROR 节点,无 vec 字段可释放。node 的 vec 字段 move 进 slot。
占位 id 不写 type_fold,不参与 hash-consing。 */
*slot = *node;
node->kind = SPL_TYPE_ERROR;
node->kind = SPL_IR_TYPE_ERROR;
}
static spl_lang_type_id_t spl_lang_node_simple(spl_lang_type_t *type,
spl_lang_type_kind_t lang_kind,
spl_type_id_t ir_type_id) {
spl_ir_type_id_t ir_type_id) {
spl_lang_type_node_t node = {0};
node.kind = lang_kind;
node.ir_type_id = ir_type_id;
@@ -211,51 +245,60 @@ static spl_lang_type_id_t spl_lang_node_simple(spl_lang_type_t *type,
}
spl_lang_type_id_t spl_lang_make_error(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_ERROR);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_ERROR);
return spl_lang_node_simple(type, SPL_LANG_TYPE_ERROR, ir);
}
spl_lang_type_id_t spl_lang_make_infer(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_INFER);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INFER, ir);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INFER, 0);
}
spl_lang_type_id_t spl_lang_make_never(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_NEVER);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
return spl_lang_node_simple(type, SPL_LANG_TYPE_NEVER, ir);
}
spl_lang_type_id_t spl_lang_make_any(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_ANY);
spl_ir_type_id_t unit = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
spl_ir_type_id_t ir = spl_ir_type_builder_ptr(type->ir_types, unit);
return spl_lang_node_simple(type, SPL_LANG_TYPE_ANY, ir);
}
spl_lang_type_id_t spl_lang_make_unit(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_UNIT);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
return spl_lang_node_simple(type, SPL_LANG_TYPE_UNIT, ir);
}
spl_lang_type_id_t spl_lang_make_bool(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_BOOL);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_BOOL);
return spl_lang_node_simple(type, SPL_LANG_TYPE_BOOL, ir);
}
spl_lang_type_id_t spl_lang_make_int(spl_lang_type_t *type, usize bits, int is_signed) {
spl_type_id_t ir = spl_type_builder_int(&type->ir, bits, is_signed);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INT, ir);
spl_ir_type_id_t ir = spl_ir_type_builder_int(type->ir_types, bits, is_signed);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_INT;
node.ir_type_id = ir;
node.extra.int_type.bits = bits;
node.extra.int_type.is_signed = is_signed;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_float(spl_lang_type_t *type, usize bits) {
spl_type_id_t ir = spl_type_builder_float(&type->ir, bits);
return spl_lang_node_simple(type, SPL_LANG_TYPE_FLOAT, ir);
spl_ir_type_id_t ir = spl_ir_type_builder_float(type->ir_types, bits);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_FLOAT;
node.ir_type_id = ir;
node.extra.float_type.bits = bits;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_array(spl_lang_type_t *type, spl_lang_type_id_t elem_lang,
usize len) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_type_id_t ir = spl_type_builder_array(&type->ir, elem_ir, len);
spl_ir_type_id_t ir = spl_ir_type_builder_array(type->ir_types, elem_ir, len);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_ARRAY;
node.ir_type_id = ir;
@@ -264,10 +307,10 @@ spl_lang_type_id_t spl_lang_make_array(spl_lang_type_t *type, spl_lang_type_id_t
}
spl_lang_type_id_t spl_lang_make_ptr(spl_lang_type_t *type, spl_lang_type_id_t pointee_lang) {
spl_type_id_t pointee_ir = spl_lang_type_get_ir_type(type, pointee_lang);
spl_ir_type_id_t pointee_ir = spl_lang_type_get_ir_type(type, pointee_lang);
if (!pointee_ir)
return 0;
spl_type_id_t ir = spl_type_builder_ptr(&type->ir, pointee_ir);
spl_ir_type_id_t ir = spl_ir_type_builder_ptr(type->ir_types, pointee_ir);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_PTR;
node.ir_type_id = ir;
@@ -276,99 +319,109 @@ spl_lang_type_id_t spl_lang_make_ptr(spl_lang_type_t *type, spl_lang_type_id_t p
}
spl_lang_type_id_t spl_lang_make_slice(spl_lang_type_t *type, spl_lang_type_id_t elem_lang) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_lang_type_id_t ptr_lang = spl_lang_make_ptr(type, elem_lang);
spl_lang_type_id_t usize_lang = spl_lang_make_int(type, sizeof(void *) * 8, 0);
spl_type_id_t ptr_ir = spl_lang_type_get_ir_type(type, ptr_lang);
spl_type_id_t usize_ir = spl_lang_type_get_ir_type(type, usize_lang);
spl_ir_type_id_t ptr_ir = spl_lang_type_get_ir_type(type, ptr_lang);
spl_ir_type_id_t usize_ir = spl_lang_type_get_ir_type(type, usize_lang);
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_type_member_t m1 = {.name = "ptr", .type_id = ptr_ir};
spl_type_member_t m2 = {.name = "len", .type_id = usize_ir};
spl_ir_type_member_t m1 = {.name = "ptr", .type_id = ptr_ir};
spl_ir_type_member_t m2 = {.name = "len", .type_id = usize_ir};
vec_push(members, m1);
vec_push(members, m2);
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t struct_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_SLICE;
node.ir_type_id = struct_ir;
node.extra.elem = elem_lang;
vec_init(node.members);
vec_push(node.members, ((spl_lang_member_t){.name = "ptr", .type = ptr_lang}));
vec_push(node.members, ((spl_lang_member_t){.name = "len", .type = usize_lang}));
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_tuple(spl_lang_type_t *type, const spl_lang_type_id_t *elems,
usize count) {
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
for (usize i = 0; i < count; i++) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elems[i]);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elems[i]);
if (!elem_ir) {
vec_free(members);
return 0;
}
char name[32];
snprintf(name, sizeof(name), "%zu", i);
spl_type_member_t m = {.name = strdup(name), .type_id = elem_ir};
spl_ir_type_member_t m = {.name = strdup(name), .type_id = elem_ir};
vec_push(members, m);
}
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t struct_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_TUPLE;
node.ir_type_id = struct_ir;
vec_init(node.extra.elems);
vec_init(node.members);
for (usize i = 0; i < count; i++) {
vec_push(node.extra.elems, elems[i]);
char name[32];
snprintf(name, sizeof(name), "%zu", i);
vec_push(node.members, ((spl_lang_member_t){.name = strdup(name), .type = elems[i]}));
}
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_range(spl_lang_type_t *type, spl_lang_type_id_t elem_lang) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_type_member_t m1 = {.name = "start", .type_id = elem_ir};
spl_type_member_t m2 = {.name = "end", .type_id = elem_ir};
spl_ir_type_member_t m1 = {.name = "start", .type_id = elem_ir};
spl_ir_type_member_t m2 = {.name = "end", .type_id = elem_ir};
vec_push(members, m1);
vec_push(members, m2);
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t struct_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_RANGE;
node.ir_type_id = struct_ir;
node.extra.elem = elem_lang;
vec_init(node.members);
vec_push(node.members, ((spl_lang_member_t){.name = "start", .type = elem_lang}));
vec_push(node.members, ((spl_lang_member_t){.name = "end", .type = elem_lang}));
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_fn(spl_lang_type_t *type, spl_lang_type_id_t ret_lang,
const spl_lang_type_id_t *params_lang, usize nparams) {
spl_type_id_t ret_ir = spl_lang_type_get_ir_type(type, ret_lang);
spl_ir_type_id_t ret_ir = spl_lang_type_get_ir_type(type, ret_lang);
if (!ret_ir)
return 0;
spl_type_id_vec_t param_irs;
spl_ir_type_id_vec_t param_irs;
vec_init(param_irs);
for (usize i = 0; i < nparams; i++) {
spl_type_id_t pir = spl_lang_type_get_ir_type(type, params_lang[i]);
spl_ir_type_id_t pir = spl_lang_type_get_ir_type(type, params_lang[i]);
if (!pir) {
vec_free(param_irs);
return 0;
}
vec_push(param_irs, pir);
}
spl_type_id_t fn_ir =
spl_type_builder_fn(&type->ir, ret_ir, param_irs.data, vec_size(param_irs));
spl_ir_type_id_t fn_ir =
spl_ir_type_builder_fn(type->ir_types, ret_ir, param_irs.data, vec_size(param_irs));
vec_free(param_irs);
spl_lang_type_node_t node = {0};
@@ -387,48 +440,85 @@ spl_lang_type_id_t spl_lang_make_aggregate(spl_lang_type_t *type, spl_lang_type_
usize nmembers) {
(void)name; // TODO
spl_type_node_kind_t tk;
spl_ir_type_kind_t tk;
switch (kind) {
case SPL_LANG_TYPE_STRUCT:
tk = SPL_TYPE_STRUCT;
tk = SPL_IR_TYPE_STRUCT;
break;
case SPL_LANG_TYPE_UNION:
tk = SPL_TYPE_UNION;
tk = SPL_IR_TYPE_UNION;
break;
case SPL_LANG_TYPE_ENUM:
tk = SPL_TYPE_ENUM;
tk = SPL_IR_TYPE_ENUM;
break;
case SPL_LANG_TYPE_SHAPE:
tk = SPL_TYPE_SHAPE;
tk = SPL_IR_TYPE_STRUCT;
break;
default:
return 0;
}
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_lang_type_node_t node = {0};
node.kind = kind;
vec_init(node.members);
for (usize i = 0; i < nmembers; i++) {
spl_type_id_t member_ir = spl_lang_type_get_ir_type(type, members_lang[i]);
spl_ir_type_id_t member_ir = spl_lang_type_get_ir_type(type, members_lang[i]);
if (!member_ir) {
vec_free(members);
vec_free(node.members);
return 0;
}
char field_name[32];
snprintf(field_name, sizeof(field_name), "%zu", i);
spl_type_member_t m = {.name = strdup(field_name), .type_id = member_ir};
const char *stored_name = strdup(field_name);
spl_ir_type_member_t m = {.name = stored_name, .type_id = member_ir};
vec_push(members, m);
vec_push(node.members, ((spl_lang_member_t){.name = stored_name, .type = members_lang[i]}));
}
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t agg_ir = spl_type_builder_agg(&type->ir, tk, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t agg_ir = spl_ir_type_builder_agg(type->ir_types, tk, &members, 0, layout);
node.ir_type_id = agg_ir;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_struct_named(spl_lang_type_t *type, const char *name,
const char *const *field_names,
const spl_lang_type_id_t *field_types,
usize nfields) {
(void)name;
if (!type || (nfields > 0 && (!field_names || !field_types)))
return 0;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_lang_type_node_t node = {0};
node.kind = kind;
node.kind = SPL_LANG_TYPE_STRUCT;
vec_init(node.members);
for (usize i = 0; i < nfields; ++i) {
spl_ir_type_id_t member_ir = spl_lang_type_get_ir_type(type, field_types[i]);
if (!member_ir) {
vec_free(members);
vec_free(node.members);
return 0;
}
const char *stored_name = strdup(field_names[i]);
spl_ir_type_member_t m = {.name = stored_name, .type_id = member_ir};
vec_push(members, m);
vec_push(node.members, ((spl_lang_member_t){.name = stored_name, .type = field_types[i]}));
}
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t agg_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
node.ir_type_id = agg_ir;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_varargs(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_UNIT);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_VARARGS;
node.ir_type_id = ir;
@@ -482,19 +572,11 @@ bool spl_lang_type_is_subtype(const spl_lang_type_t *type, spl_lang_type_id_t su
if (nsuper->kind == SPL_LANG_TYPE_ANY)
return true;
if (nsub->kind == SPL_LANG_TYPE_INT && nsuper->kind == SPL_LANG_TYPE_INT) {
spl_type_node_t *ir_sub = spl_type_node(&type->ir, nsub->ir_type_id);
if (!ir_sub)
return false;
return ir_sub->int_type.bits == 0;
}
if (nsub->kind == SPL_LANG_TYPE_INT && nsuper->kind == SPL_LANG_TYPE_INT)
return nsub->extra.int_type.bits == 0;
if (nsub->kind == SPL_LANG_TYPE_FLOAT && nsuper->kind == SPL_LANG_TYPE_FLOAT) {
spl_type_node_t *ir_sub = spl_type_node(&type->ir, nsub->ir_type_id);
if (!ir_sub)
return false;
return ir_sub->float_type.bits == 0;
}
if (nsub->kind == SPL_LANG_TYPE_FLOAT && nsuper->kind == SPL_LANG_TYPE_FLOAT)
return nsub->extra.float_type.bits == 0;
/* null(*never)可隐式转换为函数指针:函数值按指针布局,可空。 */
if (nsuper->kind == SPL_LANG_TYPE_FN && nsub->kind == SPL_LANG_TYPE_PTR) {
@@ -543,12 +625,8 @@ spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type
bool b_flt = nb->kind == SPL_LANG_TYPE_FLOAT;
if (a_int && b_int) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (!ira || !irb)
return 0;
bool a_ct = ira->int_type.bits == 0;
bool b_ct = irb->int_type.bits == 0;
bool a_ct = na->extra.int_type.bits == 0;
bool b_ct = nb->extra.int_type.bits == 0;
if (a_ct && b_ct)
return a;
if (a_ct)
@@ -559,12 +637,8 @@ spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type
}
if (a_flt && b_flt) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (!ira || !irb)
return 0;
bool a_ct = ira->float_type.bits == 0;
bool b_ct = irb->float_type.bits == 0;
bool a_ct = na->extra.float_type.bits == 0;
bool b_ct = nb->extra.float_type.bits == 0;
if (a_ct && b_ct)
return a;
if (a_ct)
@@ -575,16 +649,12 @@ spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type
}
if (a_int && b_flt) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (ira && irb && ira->int_type.bits == 0 && irb->float_type.bits == 0)
if (na->extra.int_type.bits == 0 && nb->extra.float_type.bits == 0)
return spl_lang_make_float((spl_lang_type_t *)type, 0);
return 0;
}
if (a_flt && b_int) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (ira && irb && ira->float_type.bits == 0 && irb->int_type.bits == 0)
if (na->extra.float_type.bits == 0 && nb->extra.int_type.bits == 0)
return spl_lang_make_float((spl_lang_type_t *)type, 0);
return 0;
}
@@ -628,13 +698,10 @@ bool spl_lang_mpa_int_fits(const spl_lang_type_t *type, spl_lang_type_id_t targe
spl_lang_type_node_t *nt = spl_lang_type_node(type, target);
if (!nt || nt->kind != SPL_LANG_TYPE_INT)
return false;
spl_type_node_t *ir = spl_type_node(&type->ir, nt->ir_type_id);
if (!ir)
return false;
uint32_t bits = (uint32_t)ir->int_type.bits;
uint32_t bits = (uint32_t)nt->extra.int_type.bits;
if (bits == 0)
return true;
bool target_signed = ir->int_type.is_signed != 0;
bool target_signed = nt->extra.int_type.is_signed != 0;
uint64_t uval = v.bits;
if (target_signed) {
@@ -677,7 +744,7 @@ spl_lang_type_id_t spl_def_get_lang_id(spl_lang_type_t *type, spl_def_id_t def_i
return d ? d->lang_id : 0;
}
spl_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id) {
spl_ir_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id) {
spl_lang_type_id_t lang = spl_def_get_lang_id(type, def_id);
return lang ? spl_lang_type_get_ir_type(type, lang) : 0;
}
@@ -724,30 +791,26 @@ static void spl_lang_type_dump_rec(spl_lang_type_t *type, spl_lang_type_id_t id,
case SPL_LANG_TYPE_VARARGS:
printf("...");
break;
case SPL_LANG_TYPE_INT: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
if (tn && tn->int_type.bits == 0)
case SPL_LANG_TYPE_INT:
if (n->extra.int_type.bits == 0)
printf("comptime_int");
else
spl_type_pure_dump(&type->ir, n->ir_type_id);
printf("%s%zu", n->extra.int_type.is_signed ? "i" : "u", n->extra.int_type.bits);
break;
}
case SPL_LANG_TYPE_FLOAT: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
if (tn && tn->float_type.bits == 0)
case SPL_LANG_TYPE_FLOAT:
if (n->extra.float_type.bits == 0)
printf("comptime_float");
else
spl_type_pure_dump(&type->ir, n->ir_type_id);
printf("f%zu", n->extra.float_type.bits);
break;
}
case SPL_LANG_TYPE_PTR:
printf("*");
spl_lang_type_dump_rec(type, n->extra.elem, stack);
break;
case SPL_LANG_TYPE_ARRAY: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
spl_ir_type_node_t *tn = spl_ir_type_node(type->ir_types, n->ir_type_id);
printf("[%zu]", tn->array_type.len);
spl_type_pure_dump(&type->ir, n->ir_type_id);
spl_ir_type_dump(type->ir_types, n->ir_type_id);
} break;
case SPL_LANG_TYPE_SLICE:
printf("[]");
@@ -781,7 +844,7 @@ static void spl_lang_type_dump_rec(spl_lang_type_t *type, spl_lang_type_id_t id,
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
spl_type_pure_dump(&type->ir, n->ir_type_id);
spl_ir_type_dump(type->ir_types, n->ir_type_id);
break;
}
File diff suppressed because it is too large. Load diff
-46
View File
@@ -1,46 +0,0 @@
#include "spl_scope.h"
void spl_scope_init(spl_scope_t *scope) {
vec_init(scope->scopes);
vec_push(scope->scopes, (spl_scope_node_t){0});
scope->current_scope = 0;
scope->root_scope = 0;
}
void spl_scope_drop(spl_scope_t *scope) {
for (usize i = 0; i < vec_size(scope->scopes); ++i) {
map_free(vec_at(scope->scopes, i).symbols);
}
vec_free(scope->scopes);
scope->current_scope = 0;
scope->root_scope = 0;
}
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope) {
spl_scope_node_t n = {0};
n.parent = scope->current_scope;
map_init(n.symbols, MAP_HASH_STR, MAP_CMP_STR);
vec_push(scope->scopes, n);
return vec_size(scope->scopes) - 1;
}
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol) {
Assert(id != 0 && id < vec_size(scope->scopes));
spl_scope_node_t *node = &vec_at(scope->scopes, id);
spl_symbol_t old = {0};
if (map_get(node->symbols, symbol.name, &old))
return false;
map_put(node->symbols, symbol.name, symbol);
return true;
}
bool spl_scope_find(spl_scope_t *scope, const char *name, spl_symbol_t *out) {
if (!scope || !name || !out)
return false;
for (spl_scope_id_t id = scope->current_scope; id != 0; id = vec_at(scope->scopes, id).parent) {
spl_scope_node_t *s = &vec_at(scope->scopes, id);
if (map_get(s->symbols, name, out))
return true;
}
return false;
}
-42
View File
@@ -1,42 +0,0 @@
#ifndef __SPL_SCOPE_H__
#define __SPL_SCOPE_H__
#include "spl_lang_type.h"
typedef usize spl_scope_id_t;
typedef enum {
SPL_SYMBOL_KIND_ERROR,
SPL_SYMBOL_KIND_VAR,
SPL_SYMBOL_KIND_MEMBER,
SPL_SYMBOL_KIND_FN,
SPL_SYMBOL_KIND_TYPE,
} spl_symbol_kind_t;
typedef struct {
const char *name;
spl_symbol_kind_t kind;
spl_def_id_t node;
} spl_symbol_t;
typedef VEC(const char *) spl_symbol_path_t;
typedef struct {
spl_scope_id_t parent;
MAP(const char *, spl_symbol_t) symbols;
} spl_scope_node_t;
typedef VEC(spl_scope_node_t) spl_scope_node_vec_t;
typedef struct {
spl_scope_node_vec_t scopes;
spl_scope_id_t root_scope;
spl_scope_id_t current_scope;
} spl_scope_t;
void spl_scope_init(spl_scope_t *scope);
void spl_scope_drop(spl_scope_t *scope);
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope);
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol);
bool spl_scope_find(spl_scope_t *scop, const char *symbol_name, spl_symbol_t *out);
#endif /* __SPL_SCOPE_H__ */
-128
View File
@@ -1,128 +0,0 @@
#ifndef __SPL_TYPE_H__
#define __SPL_TYPE_H__
#include "../stage0/include/utils.h"
#include "spl_fold.h"
/* 类型 intern 用的哈希混合(FNV-1a 风格,顺序敏感)。
hash 只用于选择桶;相等判定始终由结构比较完成。 */
static inline usize spl_hash_mix(usize h, usize x) {
h ^= x;
h *= (usize)1099511628211ULL;
return h;
}
static inline usize spl_hash_mix_str(usize h, const char *s) {
if (!s)
return spl_hash_mix(h, 0);
while (*s) {
h = spl_hash_mix(h, (usize)(unsigned char)*s);
s++;
}
return spl_hash_mix(h, 0); /* 终止符参与混合,避免名称拼接歧义 */
}
static inline usize spl_hash_seed(void) { return (usize)14695981039346656037ULL; }
typedef usize spl_type_id_t;
typedef VEC(spl_type_id_t) spl_type_id_vec_t;
typedef enum {
SPL_TYPE_ERROR,
SPL_TYPE_NEVER, // bottom type
SPL_TYPE_ANY, // top type
SPL_TYPE_UNIT,
SPL_TYPE_INFER,
SPL_TYPE_BOOL,
SPL_TYPE_INT,
SPL_TYPE_FLOAT,
SPL_TYPE_PTR,
SPL_TYPE_ARRAY,
SPL_TYPE_STRUCT,
SPL_TYPE_UNION,
SPL_TYPE_ENUM,
SPL_TYPE_FN,
SPL_TYPE_SHAPE,
} spl_type_node_kind_t;
typedef enum {
SPL_TYPE_LAYOUT_AUTO,
SPL_TYPE_LAYOUT_EXTERN_C,
SPL_TYPE_LAYOUT_PACKED,
} spl_type_layout_mode_t;
typedef struct {
spl_type_layout_mode_t mode;
usize fixed_align_bits;
} spl_type_layout_t;
typedef struct {
const char *name;
spl_type_id_t type_id;
usize ast_node_ref;
} spl_type_member_t;
typedef VEC(spl_type_member_t) spl_type_member_vec_t;
typedef struct {
spl_type_node_kind_t kind;
spl_type_layout_t layout;
union {
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
struct {
spl_type_id_t pointee;
} ptr_type;
struct {
spl_type_id_t element;
usize len;
} array_type;
struct {
spl_type_member_vec_t variants;
spl_type_id_t tag_type;
} agg_type;
struct {
spl_type_id_vec_t params;
spl_type_id_t ret;
} fn_type;
struct {
} shape_type;
};
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_type_node_t;
typedef VEC(spl_type_node_t) spl_type_node_vec_t;
typedef struct {
spl_type_node_vec_t type_table;
spl_fold_t type_fold;
} spl_type_t;
void spl_type_init(spl_type_t *type);
void spl_type_drop(spl_type_t *type);
spl_type_node_t *spl_type_node(const spl_type_t *type, spl_type_id_t id);
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *type_node);
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind);
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed);
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits);
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee);
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len);
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
usize nparams);
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
spl_type_member_vec_t *variants, spl_type_id_t tag_type,
spl_type_layout_t layout);
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id);
bool spl_type_is_subtype(const spl_type_t *type, spl_type_id_t sub, spl_type_id_t super);
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid, const char *name);
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name, usize *out_idx);
#endif /* __SPL_TYPE_H__ */
+43 -21
View File
@@ -7,7 +7,7 @@ type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .append_usize } = @import("utils/fmt.spl");
type .{ .append_bytes_ok, .append_byte_ok, .append_usize_ok } = @import("utils/fmt.spl");
type .{ .Punct } = @import("token.spl");
type BigInt = @import("utils/mp.spl");
type .{ .Span, .span_none, .span_make, .span_is_none } = @import("./diag.spl");
@@ -68,6 +68,7 @@ type Body = enum {
ExprNullLit,
ExprUndefinedLit,
ExprIdent: struct { name: ByteView },
ExprLambda: struct { params: Vec, ret_type: usize, body: usize },
ExprUnary: struct { op: Punct, operand: usize },
ExprBinary: struct { op: Punct, left: usize, right: usize },
ExprCall: struct { callee: usize, args: Vec },
@@ -85,6 +86,7 @@ type Body = enum {
},
ExprAggregateLit: struct { name: ByteView, fields: Vec },
ExprComptimeCall: struct { name: ByteView, args: Vec },
ExprShapeApply: struct { adapter: ByteView, shapes: Vec, args: Vec },
ExprTry: struct { value: usize }, // `try expr`
ExprCatch: struct { value: usize, pattern: usize, handler: usize }, // `expr catch <pat> { }`
ExprBlock: struct { stmts: Vec, tail_expr: usize },
@@ -96,23 +98,23 @@ type Body = enum {
label: usize,
iter_exprs: Vec,
pattern: usize,
pattern_type: usize,
body: usize,
else_branch: usize,
},
ExprMatch: struct { matched_expr: usize, arms: Vec },
ExprFnType: struct { is_comptime: bool, params: Vec, ret_type: usize },
TypePath: struct { name: ByteView, generic_args: Vec },
TypePath: struct { name: ByteView, generic_args: Vec, is_call: bool },
TypePointer: struct { pointee: usize },
TypeArray: struct {
has_len: bool,
len: isize,
len_expr: usize, // 长度表达式 AST(0 = `[_]T`)
is_underscore_len: bool,
elem_type: usize,
},
TypeSlice: struct { elem_type: usize },
TypeFn: struct { is_comptime: bool, params: Vec, ret_type: usize },
TypeParen: struct { types: Vec },
TypeAggregate: struct { kind_name: ByteView, members: Vec },
TypeAggregate: struct { kind_name: ByteView, conforms: Vec, members: Vec },
TypeComptimeCall: struct { name: ByteView, args: Vec },
PatternIdent: struct { name: ByteView },
PatternUnderscore,
@@ -124,6 +126,11 @@ type Body = enum {
PatternRef: struct { pat: usize },
ExprComptime: struct { body: usize },
ExprComptimeInit: struct { name: ByteView, args: Vec, fields: Vec },
AssocDecl: struct { attr_list: Vec, name: ByteView },
TypeShapeApply: struct { base: ByteView, binds: Vec },
TypeAssocBind: struct { name: ByteView, ty: usize },
TypeShapeUse: struct { adapter: ByteView, shapes: Vec },
TypeShapeNoDefault: struct { shapes: Vec },
}
fn kind_name(body: Body): []u8 {
@@ -139,6 +146,7 @@ fn kind_name(body: Body): []u8 {
.VarDecl(_) => { ret "var_decl"; },
.ConstDecl(_) => { ret "const_decl"; },
.TypeDecl(_) => { ret "type_decl"; },
.AssocDecl(_) => { ret "assoc_decl"; },
.MemberDecl(_) => { ret "member_decl"; },
.ParamDecl(_) => { ret "param_decl"; },
.StatementRet(_) => { ret "statement_ret"; },
@@ -162,6 +170,7 @@ fn kind_name(body: Body): []u8 {
.ExprNullLit => { ret "null_lit"; },
.ExprUndefinedLit => { ret "undefined_lit"; },
.ExprIdent(_) => { ret "ident"; },
.ExprLambda(_) => { ret "lambda"; },
.ExprUnary(_) => { ret "unary"; },
.ExprBinary(_) => { ret "binary"; },
.ExprCall(_) => { ret "call"; },
@@ -173,6 +182,7 @@ fn kind_name(body: Body): []u8 {
.ExprArrayLit(_) => { ret "array_literal"; },
.ExprAggregateLit(_) => { ret "aggregate_literal"; },
.ExprComptimeCall(_) => { ret "comptime_call"; },
.ExprShapeApply(_) => { ret "shape_apply"; },
.ExprTry(_) => { ret "try_expr"; },
.ExprCatch(_) => { ret "catch_expr"; },
.ExprComptimeInit(_) => { ret "comptime_init"; },
@@ -191,6 +201,10 @@ fn kind_name(body: Body): []u8 {
.TypeFn(_) => { ret "type_fn"; },
.TypeParen(_) => { ret "type_paren"; },
.TypeAggregate(_) => { ret "type_aggregate"; },
.TypeShapeApply(_) => { ret "type_shape_apply"; },
.TypeAssocBind(_) => { ret "type_assoc_bind"; },
.TypeShapeUse(_) => { ret "type_shape_use"; },
.TypeShapeNoDefault(_) => { ret "type_shape_no_default"; },
.TypeComptimeCall(_) => { ret "type_comptime_call"; },
.PatternIdent(_) => { ret "pattern_ident"; },
.PatternUnderscore => { ret "pattern_underscore"; },
@@ -332,27 +346,15 @@ fn ref_vec(): Vec {
// indent:栈上每层 last 为真输出 " ",否则 "| "。
fn push(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_bytes_ok(buf, bytes);
}
fn push_byte(buf: *ByteBuffer, byte: u8): bool {
match ByteBuffer.append_byte(buf, byte) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_byte_ok(buf, byte);
}
fn push_usize(buf: *ByteBuffer, value: usize): bool {
match append_usize(buf, value, 10, false) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_usize_ok(buf, value);
}
fn ref_at(list: Vec, index: usize): usize {
@@ -454,6 +456,9 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
dump_opt(ast, buf, stack, d.pattern, false) &&
dump_opt(ast, buf, stack, d.type_expr, true);
},
.AssocDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list);
},
.MemberDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.type_expr, false) &&
@@ -494,6 +499,11 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
.ExprNullLit => {},
.ExprUndefinedLit => {},
.ExprIdent(x) => {},
.ExprLambda(x) => {
ok = dump_list(ast, buf, stack, x.params) &&
dump_opt(ast, buf, stack, x.ret_type, false) &&
dump_opt(ast, buf, stack, x.body, true);
},
.ExprUnary(u) => { ok = dump_opt(ast, buf, stack, u.operand, true); },
.ExprBinary(b) => {
ok = dump_opt(ast, buf, stack, b.left, false) &&
@@ -524,6 +534,10 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
},
.ExprAggregateLit(a) => { ok = dump_list(ast, buf, stack, a.fields); },
.ExprComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); },
.ExprShapeApply(x) => {
ok = dump_list(ast, buf, stack, x.shapes) &&
dump_list(ast, buf, stack, x.args);
},
.ExprTry(t2) => { ok = dump_opt(ast, buf, stack, t2.value, true); },
.ExprCatch(c2) => {
ok = dump_opt(ast, buf, stack, c2.value, false) &&
@@ -559,6 +573,7 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
ok = dump_opt(ast, buf, stack, f.label, false) &&
dump_list(ast, buf, stack, f.iter_exprs) &&
dump_opt(ast, buf, stack, f.pattern, false) &&
dump_opt(ast, buf, stack, f.pattern_type, true) &&
dump_opt(ast, buf, stack, f.body, false) &&
dump_opt(ast, buf, stack, f.else_branch, true);
},
@@ -579,7 +594,14 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
dump_opt(ast, buf, stack, f.ret_type, true);
},
.TypeParen(p) => { ok = dump_list(ast, buf, stack, p.types); },
.TypeAggregate(a) => { ok = dump_list(ast, buf, stack, a.members); },
.TypeAggregate(a) => {
ok = dump_list(ast, buf, stack, a.conforms) &&
dump_list(ast, buf, stack, a.members);
},
.TypeShapeApply(a) => { ok = dump_list(ast, buf, stack, a.binds); },
.TypeAssocBind(a) => { ok = dump_opt(ast, buf, stack, a.ty, true); },
.TypeShapeUse(a) => { ok = dump_list(ast, buf, stack, a.shapes); },
.TypeShapeNoDefault(a) => { ok = dump_list(ast, buf, stack, a.shapes); },
.TypeComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); },
.PatternIdent(x) => {},
.PatternUnderscore => {},
+9 -28
View File
@@ -10,7 +10,7 @@ type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .hash_usize, .eq_usize } = @import("utils/hash.spl");
type BigInt = @import("utils/mp.spl");
type .{ .append_usize } = @import("utils/fmt.spl");
type .{ .append_bytes_ok, .append_usize_ok } = @import("utils/fmt.spl");
type .{ .Sources, .Source, .set_at } = @import("utils/source.spl");
type .{ .Span, .span_none, .Code, .no_file } = @import("./diag.spl");
type Diag = @import("./diag.spl");
@@ -681,13 +681,11 @@ fn ast2ir_intrin_assert(self: *Ast2Ir, n: *Node, args: Vec): usize {
}
fn append_bytes(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) { .Ok => { ret true; }, .Err(e) => { ret false; } }
ret false;
ret append_bytes_ok(buf, bytes);
}
fn append_num(buf: *ByteBuffer, v: usize): bool {
match append_usize(buf, v, 10, false) { .Ok => { ret true; }, .Err(e) => { ret false; } }
ret false;
ret append_usize_ok(buf, v);
}
@@ -765,7 +763,7 @@ fn lvalue_field(self: *Ast2Ir, n: *Node, obj_ref: usize, field_name: ByteView):
var agg_lang: usize = 0;
if kind_is(self, obj_lang, .Ptr) {
base = emit_expr(self, obj_ref);
agg_lang = extra_elem(obj_ln.*);
agg_lang = LangType.elem_of(obj_ln.*);
} else {
base = emit_lvalue(self, obj_ref);
agg_lang = obj_lang;
@@ -789,7 +787,7 @@ fn lvalue_index(self: *Ast2Ir, n: *Node, obj_ref: usize, index_ref: usize): usiz
var elem_lang: usize = 0;
if kind_is(self, obj_lang, .Ptr) || kind_is(self, obj_lang, .Array) ||
kind_is(self, obj_lang, .Slice) {
elem_lang = extra_elem(obj_ln.*);
elem_lang = LangType.elem_of(obj_ln.*);
}
if kind_is(self, obj_lang, .Tuple) {
@@ -829,15 +827,6 @@ fn is_int_lit(n: *Node): bool {
ret false;
}
fn extra_elem(e: LangEntry): usize {
match e.extra {
.Elem(x) => { ret x; },
.Array(a) => { ret a.elem; },
_ => { ret 0; },
}
ret 0;
}
fn ast2ir_emit_cast_builtin(self: *Ast2Ir, n: *Node, in: Intrin, ft: usize, tt: usize,
@@ -1113,7 +1102,7 @@ fn emit_binary(self: *Ast2Ir, n: *Node, op: Punct, left: usize, right: usize): u
var lt = node_lang(ln);
var lln = ltn(self, lt);
if lln != null && punct_is_op_ptr_addsub(op) && kind_is(self, lt, .Ptr) {
var elem_lang = extra_elem(lln.*);
var elem_lang = LangType.elem_of(lln.*);
var elem_ir = to_ir_type(self, elem_lang);
var rn = Ast.node(self.ast, right);
var rt_ir = node_ir(self, rn);
@@ -1310,7 +1299,7 @@ fn emit_array_lit(self: *Ast2Ir, n: *Node, elems: Vec): usize {
var sln = ltn(self, node_lang(n));
if sln != null && kind_is(self, node_lang(n), .Slice) {
ret emit_array_to_slice(self, n, t, elems, extra_elem(sln.*), nelems);
ret emit_array_to_slice(self, n, t, elems, LangType.elem_of(sln.*), nelems);
}
var field_refs = Vec.blank(@sizeof(usize), @alignof(usize));
var i: usize = 0;
@@ -1610,7 +1599,7 @@ fn emit_slice(self: *Ast2Ir, n: *Node, obj_ref: usize, begin_ref: usize, end_ref
var obj_lang = node_lang(obj);
var obj_ln = ltn(self, obj_lang);
if obj_ln == null { ret 0; }
var obj_elem = extra_elem(obj_ln.*);
var obj_elem = LangType.elem_of(obj_ln.*);
var obj_ir = obj_ln.ir_type_id;
var slice_ir = node_ir(self, n);
if slice_ir == 0 { ret 0; }
@@ -1946,7 +1935,7 @@ fn emit_fn_reserve(self: *Ast2Ir, n: *Node): usize {
if n == null || n.resolved_def_id == 0 { ret 0; }
var existing: usize = 0;
if ir_map_get(self, n.resolved_def_id, &existing) {
diag_name(self, n.span, .Internal, "fn reserved twice `", fn_name_of(n));
Diag.err_name(self.diag, n.span, .Internal, "fn reserved twice `", fn_name_of(n));
ret 0;
}
var fn_lang = LangType.def_lang_id(&self.sema.types, n.resolved_def_id);
@@ -1965,14 +1954,6 @@ fn fn_name_of(n: *Node): ByteView {
ret ByteView.empty();
}
fn diag_name(self: *Ast2Ir, span: Span, code: Code, prefix: []u8, name: ByteView) {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
ByteBuffer.append(&b, prefix);
ByteBuffer.append(&b, ByteView.as_slice(name));
Diag.err(self.diag, span, code, ByteBuffer.as_slice(b));
}
fn emit_fn_body(self: *Ast2Ir, n: *Node) {
if n == null || n.resolved_def_id == 0 { ret; }
var fn_ref: usize = 0;
+3 -11
View File
@@ -7,7 +7,7 @@ type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .append_usize, .append_i64 } = @import("utils/fmt.spl");
type .{ .append_usize, .append_i64, .append_bytes_ok, .append_usize_ok } = @import("utils/fmt.spl");
type AttrStage = enum {
Sema,
@@ -203,19 +203,11 @@ fn register_builtins(self: *Attr) {
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_bytes_ok(buf, bytes);
}
fn push_usize(buf: *ByteBuffer, value: usize): bool {
match append_usize(buf, value, 10, false) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_usize_ok(buf, value);
}
fn push_hex(buf: *ByteBuffer, value: u32): bool {
+3 -11
View File
@@ -7,7 +7,7 @@ type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .append_usize } = @import("utils/fmt.spl");
type .{ .append_bytes_ok, .append_usize_ok } = @import("utils/fmt.spl");
type .{ .Span, .span_none } = @import("./diag.spl");
type DefKind = enum {
@@ -165,19 +165,11 @@ fn is_type_kind(kind: DefKind): bool {
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_bytes_ok(buf, bytes);
}
fn push_usize(buf: *ByteBuffer, value: usize): bool {
match append_usize(buf, value, 10, false) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_usize_ok(buf, value);
}
fn dump(self: *DefTable, id: usize, out: *ByteBuffer): bool {
+9
View File
@@ -209,6 +209,15 @@ fn err(self: *Diag, span: Span, code: Code, msg: []u8): usize {
ret emit(self, .Error, .None, code, span, msg);
}
// 常见诊断载荷:前缀 + 一个标识/名称;避免各阶段各写一份拼接。
fn err_name(self: *Diag, span: Span, code: Code, prefix: []u8, name: ByteView) {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
ByteBuffer.append(&b, prefix);
ByteBuffer.append(&b, ByteView.as_slice(name));
Diag.err(self, span, code, ByteBuffer.as_slice(b));
}
fn warn(self: *Diag, span: Span, code: Code, msg: []u8): usize {
ret emit(self, .Warning, .None, code, span, msg);
}
+1
View File
@@ -1228,6 +1228,7 @@ fn find_main(self: *Ir2C): usize {
}
fn run(self: *Ir2C) {
put(self, "// AUTO-GENERATED \n");
put(self, "#include \"spl_rt.h\"\n");
// 模块级全局变量(Zero → BSS:无初始化式)。
+28 -5
View File
@@ -561,6 +561,16 @@ fn cg_unop(cg: *Cgen, ref: usize, n: *IrEntry, op: Op) {
}
}
fn tid_is_float(ctx: *Ir2Vm, tid: usize): bool {
var te = TypeTable.node(ctx.ty, tid);
if te == null { ret false; }
match te.node {
.Float(_) => { ret true; },
_ => {},
}
ret false;
}
fn cg_cmp(cg: *Cgen, ref: usize, n: *IrEntry, op: Op) {
match n.body {
.Cmp(c) => {
@@ -942,6 +952,12 @@ fn cg_control(cg: *Cgen, ref: usize, n: *IrEntry) {
var nargs = cl.params.len;
if nat_idx >= 0 {
var ret_is_sret = ir_is_aggregate(ctx, cl.tid);
var sret_off: usize = 0;
if ret_is_sret {
sret_off = slot_data(&cg.frame, ref);
cg_laddr(cg, sret_off);
}
var i: usize = 0;
while i < nargs {
var pref = usize_at(&cl.params, i);
@@ -951,13 +967,20 @@ fn cg_control(cg: *Cgen, ref: usize, n: *IrEntry) {
i = i + 1;
}
cg_push(cg, .U64, nat_idx as usize);
emit(cg, .Ncall, .Void, nargs);
var actual = nargs;
if ret_is_sret { actual = actual + 1; }
emit(cg, .Ncall, .Void, actual);
if ret_is_sret {
cg_laddr(cg, sret_off);
cg_store_slot(cg, ref, .Ptr);
} else {
var rk = vm_kind_of(ctx, cl.tid);
if @enum2int(rk) == @enum2int(VmKind.Void) {
emit(cg, .Drop, .Void, 0);
} else {
cg_store_slot(cg, ref, rk);
}
}
} else {
/* ABI:实参下方预留 2 个空闲 slot(PAD0/PAD1)。 */
cg_push(cg, .U64, 0);
@@ -1046,19 +1069,19 @@ fn cg_node(cg: *Cgen, ref: usize, n: *IrEntry) {
.CmpNe => { cg_cmp(cg, ref, n, .Ne); },
.CmpLt => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Slt); } else { cg_cmp(cg, ref, n, .Ult); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Slt); } else { cg_cmp(cg, ref, n, .Ult); }
},
.CmpLe => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Sle); } else { cg_cmp(cg, ref, n, .Ule); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Sle); } else { cg_cmp(cg, ref, n, .Ule); }
},
.CmpGt => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Sgt); } else { cg_cmp(cg, ref, n, .Ugt); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Sgt); } else { cg_cmp(cg, ref, n, .Ugt); }
},
.CmpGe => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Sge); } else { cg_cmp(cg, ref, n, .Uge); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Sge); } else { cg_cmp(cg, ref, n, .Uge); }
},
.CastTrunc => { cg_cast(cg, ref, n); },
+13 -20
View File
@@ -8,7 +8,7 @@ type .{ .Vec } = @import("utils/vec.spl");
type .{ .Map, .hash_kind_usize } = @import("utils/map.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .append_usize } = @import("utils/fmt.spl");
type .{ .append_usize, .append_bytes_ok, .append_usize_ok } = @import("utils/fmt.spl");
type .{ .hash_usize, .eq_usize } = @import("utils/hash.spl");
type BigInt = @import("utils/mp.spl");
type .{ .Span, .span_none } = @import("./diag.spl");
@@ -132,6 +132,7 @@ fn is_agg_kind(kind: LangKind): bool {
fn elem_of(entry: LangEntry): usize {
match entry.extra {
.Elem(x) => { ret x; },
.Array(a) => { ret a.elem; },
_ => { ret 0; },
}
ret 0;
@@ -283,7 +284,7 @@ fn hash_entry(e: *LangEntry): usize {
h = mix(h, v.len);
var i: usize = 0;
while i < v.len {
h = mix(h, TypeTable.usize_at(v, i));
h = mix(h, Vec.usize_at_value(v, i));
i = i + 1;
}
},
@@ -292,7 +293,7 @@ fn hash_entry(e: *LangEntry): usize {
h = mix(h, f.params.len);
var i: usize = 0;
while i < f.params.len {
h = mix(h, TypeTable.usize_at(f.params, i));
h = mix(h, Vec.usize_at_value(f.params, i));
i = i + 1;
}
},
@@ -332,7 +333,7 @@ fn eq_elem(a: LangExtra, b: LangExtra): bool {
if v.len != w.len { ret false; }
var i: usize = 0;
while i < v.len {
if TypeTable.usize_at(v, i) != TypeTable.usize_at(w, i) { ret false; }
if Vec.usize_at_value(v, i) != Vec.usize_at_value(w, i) { ret false; }
i = i + 1;
}
ret true;
@@ -347,7 +348,7 @@ fn eq_elem(a: LangExtra, b: LangExtra): bool {
if f.params.len != g.params.len { ret false; }
var i: usize = 0;
while i < f.params.len {
if TypeTable.usize_at(f.params, i) != TypeTable.usize_at(g.params, i) {
if Vec.usize_at_value(f.params, i) != Vec.usize_at_value(g.params, i) {
ret false;
}
i = i + 1;
@@ -564,7 +565,7 @@ fn make_tuple(self: *LangType, elems: Vec): usize {
var members = Vec.blank(@sizeof(Member), @alignof(Member));
var i: usize = 0;
while i < elems.len {
var elem_ir = ir_type(self, TypeTable.usize_at(elems, i));
var elem_ir = ir_type(self, Vec.usize_at_value(elems, i));
if elem_ir == 0 {
Vec.drop(&members);
Vec.drop(&elems);
@@ -595,7 +596,7 @@ fn make_fn(self: *LangType, ret_lang: usize, params: Vec): usize {
var param_irs = Vec.blank(@sizeof(usize), @alignof(usize));
var i: usize = 0;
while i < params.len {
var pir = ir_type(self, TypeTable.usize_at(params, i));
var pir = ir_type(self, Vec.usize_at_value(params, i));
if pir == 0 {
Vec.drop(&param_irs);
Vec.drop(&params);
@@ -844,25 +845,17 @@ fn int_fits(self: *LangType, target: usize, value: BigInt): bool {
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_bytes_ok(buf, bytes);
}
fn push_usize(buf: *ByteBuffer, value: usize): bool {
match append_usize(buf, value, 10, false) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
ret append_usize_ok(buf, value);
}
fn dump_rec(self: *LangType, id: usize, out: *ByteBuffer, stack: *Vec): bool {
var i: usize = 0;
while i < stack.len {
if TypeTable.usize_at(stack.*, i) == id {
if Vec.usize_at_value(stack.*, i) == id {
if !push_out(out, "<rec#") { ret false; }
if !push_usize(out, id) { ret false; }
ret push_out(out, ">");
@@ -936,7 +929,7 @@ fn dump_rec(self: *LangType, id: usize, out: *ByteBuffer, stack: *Vec): bool {
var j: usize = 0;
while ok && j < elems.len {
if j != 0 && !push_out(out, ",") { ok = false; }
if ok { ok = dump_rec(self, TypeTable.usize_at(elems, j), out, stack); }
if ok { ok = dump_rec(self, Vec.usize_at_value(elems, j), out, stack); }
j = j + 1;
}
if ok && !push_out(out, ")") { ok = false; }
@@ -960,7 +953,7 @@ fn dump_rec(self: *LangType, id: usize, out: *ByteBuffer, stack: *Vec): bool {
var j: usize = 0;
while ok && j < params.len {
if j != 0 && !push_out(out, ",") { ok = false; }
if ok { ok = dump_rec(self, TypeTable.usize_at(params, j), out, stack); }
if ok { ok = dump_rec(self, Vec.usize_at_value(params, j), out, stack); }
j = j + 1;
}
if ok && !push_out(out, ")") { ok = false; }
+3 -11
View File
@@ -85,14 +85,6 @@ fn push_usize(v: *Vec, x: usize) {
Vec.push(v, &x as *u8);
}
fn usize_at(v: *Vec, i: usize): usize {
match Vec.get(v, i) {
.Ok(ptr) => { ret (ptr as *usize).*; },
.Err(error) => { ret 0; },
}
ret 0;
}
// 标量对齐(字节);0 表示没有匹配的标量(即未落地)。
fn scalar_align(size_bytes: usize): usize {
if size_bytes == 1 { ret 1; }
@@ -273,7 +265,7 @@ fn resolve_one(self: *Layout, tt: *TypeTable, id: usize) {
.Fn(f) => {
var i: usize = 0;
while i < f.params.len {
resolve_one(self, tt, usize_at(&f.params, i));
resolve_one(self, tt, Vec.usize_at(&f.params, i));
i = i + 1;
}
resolve_one(self, tt, f.ret_type);
@@ -323,8 +315,8 @@ fn main() {
}
@assert(info.size_bits == 64, "struct size_bits");
@assert(info.align_bits == 32, "struct align_bits");
@assert(usize_at(&info.field_bit_offsets, 0) == 0, "field0 off");
@assert(usize_at(&info.field_bit_offsets, 1) == 32, "field1 off");
@assert(Vec.usize_at(&info.field_bit_offsets, 0) == 0, "field0 off");
@assert(Vec.usize_at(&info.field_bit_offsets, 1) == 32, "field1 off");
var arr = make_array(&tt, i32t, 3);
resolve(&layout, &tt);
+1 -1
View File
@@ -1,6 +1,6 @@
// Expect retcode = 0
// 字节流 -> Vec<Token>。行为镜像 splc0(保证 diff):行注释作为 token 产出,块注释
// 字节流 -> Vec[Token]。行为镜像 splc0(保证 diff):行注释作为 token 产出,块注释
//(可嵌套)跳过,换行产 Endline,EOF 产 Eof。Token.text 借用输入,不复制。
type .{ .Vec, .VecResult } = @import("utils/vec.spl");
Loaded 100 of 314 files, more files were not shown because too many files have changed in this diff. Show more