Compare commits

...

12 Commits

36 changed files with 8144 additions and 9663 deletions

1
.gitignore vendored
View File

@@ -8,5 +8,6 @@ build/
*.o
*.obj
*.old
*.exe
*.out

75
SPL.md
View File

@@ -1,13 +1,13 @@
# SPL Self-bootstrapping/System Programming Language
# SPL - Self-bootstrapping/System Programming Language
## 项目概述
SPL是一个从零构建的自举编译器项目。引导链:
```
stage0/spl_vm.c SIR 虚拟机 (C 语言实现)
stage1/splc0.c SPL->SIR 编译器 (C 语言实现,引导用)
stage1/splc1.spl SPL->SIR 编译器 (SPL 语言实现,自举第一版)
stage0/spl_vm.c - SIR 虚拟机 (C 语言实现)
stage1/splc0.c - SPL->SIR 编译器 (C 语言实现,引导用)
stage1/splc1.spl - SPL->SIR 编译器 (SPL 语言实现,自举第一版)
...将来...
```
@@ -56,7 +56,7 @@ DirectiveBlock
<- DirectiveHead Block (* @init { } / #test { } *)
# ================================================================
# comptime 编译期执行 / 断言 (仅容器层)
# comptime - 编译期执行 / 断言 (仅容器层)
# ================================================================
ComptimeStmt
@@ -88,6 +88,7 @@ TypeDecl
MemberDecl
<- IDENTIFIER (COLON TypeExpr)? (COMMA / SEMICOLON)?
(* 聚合成员分隔: `,` 与 `;` 均可。当前 `;` 路径不稳定,测试以 `,` 为准,`;` 仅作兼容验证。 *)
# ================================================================
# 类型表达式 (Type Expression, LL(1), 无左递归)
@@ -98,6 +99,7 @@ TypeExpr <- PrefixTypeOp* AttrList? TypeBase
TypeBase
<- FnTypeExpr
/ TypePath
/ KEYWORD_shape LBRACE ContainerDeclaration* RBRACE (* TODO *)
/ KEYWORD_struct LBRACE ContainerDeclaration* RBRACE
/ KEYWORD_union LBRACE ContainerDeclaration* RBRACE
/ KEYWORD_enum LBRACE ContainerDeclaration* RBRACE
@@ -141,7 +143,7 @@ ConstDecl
# ================================================================
# 块 / 语句层 (Block & Statement 仅函数体内)
# 块 / 语句层 (Block & Statement - 仅函数体内)
# ================================================================
Block <- LBRACE BlockItem* Expr? RBRACE
@@ -159,6 +161,9 @@ Statement (* LL(1): 14 分支互
/ BreakStatement
/ ContinueStatement
/ DeferStatement
/ TryStatement (* TODO *)
/ CatchStatement (* TODO *)
/ ErrDeferStatement (* TODO *)
/ VarDecl
/ ConstDecl
/ TypeDecl
@@ -234,8 +239,7 @@ ShiftExpr <- AddExpr ((L_ARROW2 / R_ARROW2) AddExpr)*
AddExpr <- MulExpr ((PLUS / MINUS) MulExpr)*
MulExpr <- PrefixExpr ((ASTERISK / SLASH / PERCENT) PrefixExpr)*
PrefixExpr <- PrefixOp* PostfixExpr
PrefixOp <- MINUS / BANG / TILDE / AMPERSAND / ASTERISK
PrefixOp <- MINUS / BANG / TILDE / AMPERSAND
# ---- 后缀 ----
@@ -389,19 +393,29 @@ FLOAT <- [0-9]+ '.' [0-9]+
CHAR_LITERAL <- "'" (CHAR_PLAIN / CHAR_ESCAPE) "'"
CHAR_PLAIN <- [^\\'\n]
CHAR_ESCAPE <- '\\' [ntr\\'"0]
/ '\\x' [0-9a-fA-F] [0-9a-fA-F]
STRING_LITERAL <- '"' (STRING_CHUNK)* '"'
STRING_CHUNK <- [^\\"\n]+ / '\\' [ntr\\'"0]
/ '\\x' [0-9a-fA-F] [0-9a-fA-F]
LINE_COMMENT <- '//' [^\n]*
BLOCK_COMMENT <- '/*' (!'*/' .)* '*/'
BLOCK_COMMENT <- '/*' (BLOCK_COMMENT / !'*/' .)* '*/' (* 支持嵌套 *)
eof <- !.
```
## 当前阶段暂不支持stage1 引导实现限制)
以下语法/特性在当前引导阶段**暂不实现**,使用时报编译错误("not implemented")。
实现推进时按序补齐,并同步更新本清单与测试。
- **comptime 语句**: `comptime { }` / `comptime expr;`spl_ast.c 报 "not implemented: comptime statement"
- **f32 类型**: `var x: f32` 变量声明暂不可用(缺 float 转换指令f64 字面量->f32 需截断),见 BUGS.md #1f64 类型已完整支持
- **@ / # 指令块**: `@init { }` / `#test { }`spl_ast.c 报 "not implemented: @/# directive block"
- **嵌套类型路径构造**: 类型体内嵌套类型可定义,但 `Shape.Inner { ... }` 的路径构造未实现
## TODO
```spl
// 约束关键字,语义是`类型子集形状`
type name = shape { ... }
// 默认字段
@@ -443,7 +457,20 @@ DirectiveBlock @id { } / #id { } 为扩展占位,无预定义行为。未识
@name(args) / #name(args): 内置调用,出现在表达式位置。
语义: 完全由语言版本或库注册决定。当前所有均视为未识别,产生警告 (宽松) 或错误 (严格)
语义: 由编译器的内置函数注册决定stage1/spl_builtin.h/c。未注册名称在宽松模式下警告、严格模式下错误
### 内置函数注册表
| 内置 | 参数 | 返回 | 状态 |
|---|---|---|---|
| @sizeof(T) | 类型表达式 | usize | 已实现 |
| @bitsizeof(T) | 类型表达式 | usize | 已实现 |
| @alignof(T) | 类型表达式 | usize | 已实现 |
| @offsetof(T, field) | 类型表达式 + 字段标识符 | usize | 已实现 |
| @field_count(T) | 类型表达式 | usize | 已实现 |
| @dbg(args...) | 表达式列表 | void | 已实现(发射断点) |
| @assert(cond) | bool 表达式 | void | 已实现(失败 trap |
| @import(path) | 字符串字面量 | 模块 | 预留,未实现 |
## 函数
@@ -459,7 +486,7 @@ AttrList? fn IDENTIFIER ( ParamDeclList ) TypeExpr? ( ; | Block )
## 类型声明与聚合体
### 别名
type T = TypeExpr 完全同义。
type T = TypeExpr - 完全同义。
### struct
字段必须 name: Type不可省略。名称唯一。
@@ -798,13 +825,13 @@ T (任意) T 是 无 相同类型
*_ *T 是 警告: “不安全的指针重解释”
[N]T []T 是 无 数组到切片强制转换
整数字面量 整数类型 U 是 (若值在 U 范围内) 无 字面量自动拓宽 (含字符 'c' 视为 u8)
i32 i64 否 需显式 as i64防止意外
i64 i32 否 窄化必须显式
i32 i64 否 - 需显式 as i64防止意外
i64 i32 否 - 窄化必须显式
null *T / []T 是 无 空指针/空切片初始化、比较、赋值、聚合字段
浮点字面量 f32 是 (值可表示则) 无
f64 f32 否 窄化需显式
bool 整数 否
整数 bool 否
f64 f32 否 - 窄化需显式
bool 整数 否 -
整数 bool 否 -
注:
@@ -1179,11 +1206,11 @@ CONSTANT ← INTEGER | FLOAT | STRING | 'true' | 'false' | 'null' | 'undefine
标记附加在函数定义前,用逗号分隔。所有标记均不影响 IR 控制流语义,仅向后端传递元数据。
标记 参数 含义 使用场景
!link("export") 符号对外可见 库的公开 API
!link("import") 符号来自外部模块 调用外部库
!link("weak") 弱符号 可被覆盖的默认实现
!link("export") - 符号对外可见 库的公开 API
!link("import") - 符号来自外部模块 调用外部库
!link("weak") - 弱符号 可被覆盖的默认实现
!abi("C") 调用约定名称 指定跨函数调用的 ABI 与 C 代码交互
!symbol("name") 字符串 自定义导出符号名 避免名称混淆
!naked 无函数序言/尾声 中断向量、系统调用包装
!noinline 禁止内联 调试或特殊性能需求
!alwaysinline 总是内联 简单的包装函数
!naked - 无函数序言/尾声 中断向量、系统调用包装
!noinline - 禁止内联 调试或特殊性能需求
!alwaysinline - 总是内联 简单的包装函数

417
build.py
View File

@@ -1,417 +0,0 @@
#!/usr/bin/env python3
"""SPL build system — .c → .o → exe, .spl → .sir, deps auto-resolved."""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
BUILD_DIR = ROOT / "build"
CACHE_FILE = BUILD_DIR / ".build_cache.json"
DESC_FILE = ROOT / "project_desc.py"
EXE_EXT = ".exe" if os.name == "nt" else ""
CC = os.environ.get("CC", "gcc")
CFLAGS = os.environ.get("CFLAGS", "-Wall -Wextra -O0 -g").split()
def load_desc():
ns = {"__builtins__": __builtins__}
exec(DESC_FILE.read_text(), ns)
return {
"exe": ns.get("exe", {}),
"spl": ns.get("spl", {}),
"pipeline": ns.get("pipeline", {}),
}
# ── Helpers ─────────────────────────────────────────────────────────────
def obj_key(src):
return src.rsplit(".", 1)[0].replace("/", "_").replace("\\", "_")
def obj_path(src):
return BUILD_DIR / (obj_key(src) + ".o")
def exe_path(name):
return BUILD_DIR / (name + EXE_EXT)
def sir_path(name):
return BUILD_DIR / (name + ".sir")
# ── Cache ───────────────────────────────────────────────────────────────
def load_cache():
if CACHE_FILE.is_file():
try:
return json.loads(CACHE_FILE.read_text())
except (json.JSONDecodeError, OSError):
pass
return {}
def save_cache(cache):
BUILD_DIR.mkdir(parents=True, exist_ok=True)
CACHE_FILE.write_text(json.dumps(cache, indent=2))
def hash_file(p):
h = hashlib.sha256()
with p.open("rb") as f:
while chunk := f.read(65536):
h.update(chunk)
return h.hexdigest()
# ── C compilation ───────────────────────────────────────────────────────
_built_objs = set()
def compile_c(src, cache, force):
key = f"obj:{src}"
dst = obj_path(src)
src_path = ROOT / src
if not src_path.is_file():
print(f" ERR {src} not found"); return False
h = hashlib.sha256()
h.update(hash_file(src_path).encode())
h.update(" ".join(CFLAGS).encode())
ch = h.hexdigest()
cached = cache.get(key)
if not force and cached and cached["h"] == ch and dst.is_file():
_built_objs.add(src); return True
BUILD_DIR.mkdir(parents=True, exist_ok=True)
cmd = [CC] + CFLAGS + ["-c", str(src_path), "-o", str(dst)]
print(f" CC {src}")
if subprocess.run(cmd).returncode: return False
cache[key] = {"h": ch}
_built_objs.add(src)
return True
def link_exe(name, sources, cache, force):
key = f"exe:{name}"
dst = exe_path(name)
# hash = concat of all input obj hashes + name
h = hashlib.sha256(name.encode())
for src in sources:
cached = cache.get(f"obj:{src}", {})
h.update(cached.get("h", "?").encode())
ch = h.hexdigest()
cached = cache.get(key)
if not force and cached and cached["h"] == ch and dst.is_file():
return True
cmd = [CC] + CFLAGS + [str(obj_path(s)) for s in sources] + ["-o", str(dst)]
print(f" LINK {name}")
if subprocess.run(cmd).returncode: return False
cache[key] = {"h": ch}
return True
# ── SPL compilation ─────────────────────────────────────────────────────
def find_imports(src_path):
"""Scan source for @import("path") directives, return resolved paths."""
deps = []
try:
text = src_path.read_text(errors="replace")
except OSError:
return deps
idx = 0
while True:
idx = text.find('@import("', idx)
if idx < 0:
break
start = idx + 9
end = text.find('")', start)
if end < 0:
break
imp_path = text[start:end]
imp_file = (src_path.parent / imp_path).resolve()
if imp_file.is_file():
deps.append(imp_file)
idx = end + 2
return deps
def collect_deps(src_path):
"""Collect all transitive @import dependencies."""
seen = set()
result = []
def walk(p):
p = p.resolve()
if p in seen:
return
seen.add(p)
for dep in find_imports(p):
walk(dep)
result.append(dep)
walk(src_path)
return result
def compile_spl(name, src, compiler, desc, cache, force):
key = f"spl:{name}"
dst = sir_path(name)
src_path = ROOT / src
if not src_path.is_file():
print(f" ERR {src} not found"); return False
h = hashlib.sha256()
h.update(hash_file(src_path).encode())
# Hash @import dependencies (transitive)
for dep in collect_deps(src_path):
h.update(hash_file(dep).encode())
# Determine how to run the compiler
if compiler in desc.get("spl", {}):
# SPL-based compiler: run via VM runner
cinfo = desc["spl"][compiler]
pl = desc.get("pipeline", {}).get(cinfo.get("pipeline", ""), {})
runner = pl.get("runner") or cinfo.get("runner", "spl_cli")
runner_exe = exe_path(runner)
sir = sir_path(compiler)
if runner_exe.is_file():
h.update(hash_file(runner_exe).encode())
if os.path.isfile(sir):
h.update(hash_file(Path(sir)).encode())
ch = h.hexdigest()
cached = cache.get(key)
if not force and cached and cached["h"] == ch and dst.is_file():
return True
BUILD_DIR.mkdir(parents=True, exist_ok=True)
cmd = [str(runner_exe), str(sir), str(src_path), str(dst)]
print(f" SPL {name} ({compiler} via {runner})")
else:
# Native exe compiler
ce = exe_path(compiler)
if ce.is_file():
h.update(hash_file(ce).encode())
ch = h.hexdigest()
cached = cache.get(key)
if not force and cached and cached["h"] == ch and dst.is_file():
return True
BUILD_DIR.mkdir(parents=True, exist_ok=True)
cmd = [str(ce), str(src_path), str(dst)]
print(f" SPL {name} ({compiler})")
if subprocess.run(cmd).returncode: return False
cache[key] = {"h": ch}
return True
# ── Dependency-aware build ──────────────────────────────────────────────
_built = set()
def build(name, desc, cache, force):
"""Build target + all deps (auto-resolved DAG traversal)."""
if name in _built:
return True
if name in desc.get("exe", {}):
sources = desc["exe"][name]
for src in sources:
if not compile_c(src, cache, force):
return False
if not link_exe(name, sources, cache, force):
return False
elif name in desc.get("spl", {}):
info = desc["spl"][name]
pl = desc.get("pipeline", {}).get(info.get("pipeline", ""), {})
compiler = pl.get("compiler") or info.get("compiler")
if not compiler:
print(f" ERR '{name}': no compiler in pipeline '{info.get('pipeline')}'")
return False
if not build(compiler, desc, cache, force):
return False
if not compile_spl(name, info["src"], compiler, desc, cache, force):
return False
else:
print(f" ERR unknown target '{name}'")
return False
_built.add(name)
return True
def build_all(desc, cache, force):
targets = list(desc.get("exe", {})) + list(desc.get("spl", {}))
for t in targets:
if not build(t, desc, cache, force):
return False
return True
# ── Run ─────────────────────────────────────────────────────────────────
def run_target(name, desc, cache, force, extra_args):
if name in desc.get("exe", {}):
if not build(name, desc, cache, force):
return 1
exe = exe_path(name)
print(f" RUN {name}")
return subprocess.run([str(exe)] + extra_args).returncode
if name in desc.get("spl", {}):
info = desc["spl"][name]
pl = desc.get("pipeline", {}).get(info.get("pipeline", ""), {})
runner = pl.get("runner") or info.get("runner", "spl_cli")
if not runner:
print(f" ERR '{name}': no runner"); return 1
if not build(name, desc, cache, force):
return 1
if not build(runner, desc, cache, force):
return 1
print(f" RUN {name} (via {runner})")
return subprocess.run(
[str(exe_path(runner)), str(sir_path(name))] + extra_args
).returncode
if name in desc.get("pipeline", {}):
pl = desc["pipeline"][name]
compiler = pl.get("compiler")
runner = pl.get("runner")
if not compiler or not runner:
print(f" ERR pipeline '{name}' missing compiler or runner"); return 1
if not extra_args:
print(" ERR usage: run <pipeline> <src> [args]"); return 1
src = extra_args[0]
if not build(compiler, desc, cache, force): return 1
if not build(runner, desc, cache, force): return 1
sir_name = "pipeline_" + hashlib.sha256(str(ROOT / src).encode()).hexdigest()[:8]
if not compile_spl(sir_name, src, compiler, desc, cache, force):
return 1
print(f" RUN pipeline {name} ({src})")
return subprocess.run(
[str(exe_path(runner)), str(sir_path(sir_name))] + extra_args[1:]
).returncode
print(f" ERR unknown target '{name}'"); return 1
# ── Clean / List ────────────────────────────────────────────────────────
def clean():
if BUILD_DIR.is_dir():
shutil.rmtree(BUILD_DIR)
print(f" CLEAN {BUILD_DIR}")
def list_targets(desc):
print("Executables (.c → .o → exe):")
for name, sources in desc.get("exe", {}).items():
print(f" {name}")
for s in sources:
print(f" {s}")
if desc.get("spl"):
print("\nSPL programs (.spl → .sir via pipeline):")
for name, info in desc["spl"].items():
pl_name = info.get("pipeline", "-")
print(f" {name} pipeline={pl_name} src={info['src']}")
if desc.get("pipeline"):
print("\nPipelines:")
for name, pl in desc["pipeline"].items():
print(f" {name} compiler={pl['compiler']} runner={pl.get('runner', '-')}")
# ── CLI ─────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="SPL build system")
sub = parser.add_subparsers(dest="command")
bp = sub.add_parser("build", help="build targets (default: all)")
bp.add_argument("targets", nargs="*")
bp.add_argument("-f", "--force", action="store_true")
rp = sub.add_parser("run", help="build and run a target, or run pipeline <name> <src> [args]")
rp.add_argument("target")
rp.add_argument("extra", nargs="*")
sub.add_parser("test", help="build and run VM unit tests")
sub.add_parser("clean", help="remove build artifacts")
sub.add_parser("list", help="list all targets")
args = parser.parse_args()
if not DESC_FILE.is_file():
print(f"ERR {DESC_FILE} not found"); return 1
# Default: build all
if args.command is None:
desc = load_desc(); cache = load_cache()
ok = build_all(desc, cache, False)
save_cache(cache)
return 0 if ok else 1
# Build
if args.command == "build":
desc = load_desc(); cache = load_cache()
if args.targets:
ok = all(build(t, desc, cache, args.force) for t in args.targets)
else:
ok = build_all(desc, cache, args.force)
save_cache(cache)
return 0 if ok else 1
# Run
if args.command == "run":
desc = load_desc(); cache = load_cache()
rc = run_target(args.target, desc, cache, False, args.extra)
save_cache(cache)
return rc
# Pipeline: build compiler → compile .spl → run via runner
if args.command == "pipeline":
desc = load_desc(); cache = load_cache()
pl = desc.get("pipeline", {}).get(args.name)
if not pl:
print(f" ERR unknown pipeline '{args.name}'"); return 1
compiler = pl.get("compiler")
runner = pl.get("runner")
if not compiler or not runner:
print(f" ERR pipeline '{args.name}' missing compiler or runner"); return 1
src_path = ROOT / args.src
if not src_path.is_file():
print(f" ERR source not found: {args.src}"); return 1
# Build compiler + runner
if not build(compiler, desc, cache, False): return 1
if not build(runner, desc, cache, False): return 1
# Compile .spl → .sir (temp name = src path hash)
sir_name = "pipeline_" + hashlib.sha256(str(src_path).encode()).hexdigest()[:8]
if not compile_spl(sir_name, args.src, compiler, desc, cache, False):
return 1
# Run .sir via runner
print(f" PIPELINE {args.name} ({args.src})")
rc = subprocess.run(
[str(exe_path(runner)), str(sir_path(sir_name))] + args.extra
).returncode
save_cache(cache)
return rc
# Test
if args.command == "test":
desc = load_desc(); cache = load_cache()
ok = build("test", desc, cache, False)
save_cache(cache)
if not ok: return 1
return subprocess.run([str(exe_path("test"))]).returncode
# Clean / List
if args.command == "clean":
clean(); return 0
if args.command == "list":
list_targets(load_desc()); return 0
return 0
if __name__ == "__main__":
sys.exit(main())

294
nob.c Normal file
View File

@@ -0,0 +1,294 @@
#undef UNICODE
#define NOB_IMPLEMENTATION
// Redefine nob_cc_flags() to carry the project's debug flags. Keep in sync
// with CFLAGS_STR below.
#define SPL_CFLAGS "-Wall", "-Wextra", "-O0", "-g", "-D_CRT_SECURE_NO_WARNINGS"
#define nob_cc_flags(cmd) nob_cmd_append(cmd, SPL_CFLAGS)
#include "nob.h"
#ifdef _WIN32
#include <consoleapi2.h>
#endif
// C-side bootstrap build script. Builds the stage0 VM tools and the splc0
// compiler from their C sources. The SPL self-hosting chain (splc1, ...) is
// out of scope and is driven by a different mechanism.
//
// Usage:
// cc -o nob nob.c # bootstrap once
// ./nob # build all targets
// ./nob build <targets...> # build specific targets
// ./nob run <target> [..] # build and run
// ./nob test # build and run VM unit tests
// ./nob clean # remove build artifacts
// ./nob list # list all targets
// ./nob help # print this help
#define BUILD_FOLDER "build/"
#ifdef _WIN32
#define EXE_SUFFIX ".exe"
#else
#define EXE_SUFFIX ""
#endif
// Content of the .cflags stamp file; must match SPL_CFLAGS above.
#define CFLAGS_STR "-Wall -Wextra -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";
// Target descriptions
#define VM_SRCS "stage0/spl_mcode.c", "stage0/spl_syscall.c", "stage0/spl_vm.c"
#define SPLC0_PART_SRCS \
"stage1/spl_ast.c", "stage1/spl_lexer.c", "stage1/spl_dumptree.c", "stage1/spl_type.c", \
"stage1/spl_sema.c", "stage1/spl_ir.c", "stage1/spl_ast2ir.c"
static const char *spl_cli_srcs[] = {"stage0/spl_cli.c", VM_SRCS};
static const char *splc0_srcs[] = {"stage1/splc0.c", VM_SRCS, SPLC0_PART_SRCS};
static const char *test_srcs[] = {"stage0/test_spl_vm.c", VM_SRCS};
static const char *spl_disasm_srcs[] = {"stage0/spl_disasm.c", VM_SRCS};
typedef struct {
const char *name;
const char **srcs;
size_t srcs_count;
} Exe_Target;
static Exe_Target exe_targets[] = {
{"spl_cli", spl_cli_srcs, NOB_ARRAY_LEN(spl_cli_srcs)},
{"splc0", splc0_srcs, NOB_ARRAY_LEN(splc0_srcs)},
{"test", test_srcs, NOB_ARRAY_LEN(test_srcs)},
{"spl_disasm", spl_disasm_srcs, NOB_ARRAY_LEN(spl_disasm_srcs)},
};
static const Exe_Target *find_exe_target(const char *name) {
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
if (strcmp(exe_targets[i].name, name) == 0) {
return &exe_targets[i];
}
}
return NULL;
}
static const char *obj_path(const char *src) {
// "stage0/spl_vm.c" -> "build/stage0_spl_vm.o"
size_t prefix_len = strlen(BUILD_FOLDER);
char *out = (char *)nob_temp_alloc(prefix_len + strlen(src) + 2 + 1);
char *w = out;
memcpy(w, BUILD_FOLDER, prefix_len);
w += prefix_len;
for (const char *p = src; *p && *p != '.'; ++p) {
*w++ = (*p == '/' || *p == '\\') ? '_' : *p;
}
memcpy(w, ".o", 3);
return out;
}
static const char *exe_path(const char *name) {
return nob_temp_sprintf(BUILD_FOLDER "%s" EXE_SUFFIX, name);
}
static bool sync_cflags_stamp(void) {
Nob_String_View cflags = nob_sv_from_cstr(CFLAGS_STR);
Nob_String_Builder old = {0};
bool changed = true;
if (nob_file_exists(CFLAGS_STAMP) && nob_read_entire_file(CFLAGS_STAMP, &old)) {
changed = !nob_sv_eq(nob_sb_to_sv(old), cflags);
}
nob_sb_free(old);
if (changed) {
if (!nob_write_entire_file(CFLAGS_STAMP, cflags.data, cflags.count)) {
return false;
}
}
return true;
}
static bool prepare_build(void) {
if (!nob_mkdir_if_not_exists(BUILD_FOLDER))
return false;
return sync_cflags_stamp();
}
static bool build_object(const char *src) {
const char *obj = obj_path(src);
if (!nob_file_exists(src)) {
nob_log(NOB_ERROR, "source file `%s` does not exist", src);
return false;
}
const char *inputs[] = {src, CFLAGS_STAMP};
int needs = nob_needs_rebuild(obj, inputs, NOB_ARRAY_LEN(inputs));
if (needs < 0)
return false;
if (needs == 0)
return true;
Nob_Cmd cmd = {0};
nob_cc(&cmd);
nob_cc_flags(&cmd);
nob_cmd_append(&cmd, "-c");
nob_cc_inputs(&cmd, src);
nob_cc_output(&cmd, obj);
return nob_cmd_run(&cmd);
}
static bool link_exe(const Exe_Target *target) {
const char *exe = exe_path(target->name);
const char **objs = (const char **)nob_temp_alloc(sizeof(const char *) * target->srcs_count);
for (size_t i = 0; i < target->srcs_count; ++i) {
objs[i] = obj_path(target->srcs[i]);
}
int needs = nob_needs_rebuild(exe, objs, target->srcs_count);
if (needs < 0)
return false;
if (needs == 0)
return true;
Nob_Cmd cmd = {0};
nob_cc(&cmd);
nob_cc_flags(&cmd);
for (size_t i = 0; i < target->srcs_count; ++i) {
nob_cc_inputs(&cmd, objs[i]);
}
nob_cc_output(&cmd, exe);
return nob_cmd_run(&cmd);
}
static bool build_target(const char *name) {
const Exe_Target *target = find_exe_target(name);
if (target == NULL) {
nob_log(NOB_ERROR, "unknown target `%s`", name);
return false;
}
for (size_t i = 0; i < target->srcs_count; ++i) {
if (!build_object(target->srcs[i])) {
return false;
}
}
return link_exe(target);
}
static bool build_all(void) {
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
if (!build_target(exe_targets[i].name)) {
return false;
}
}
return true;
}
static bool delete_walk_entry(Nob_Walk_Entry entry) { return nob_delete_file(entry.path); }
static bool delete_directory_recursively(const char *dir_path) {
return nob_walk_dir(dir_path, delete_walk_entry, .post_order = true);
}
static void print_help(const char *program_name) {
nob_log(NOB_INFO, "SPL C-side bootstrap build system (nob)");
nob_log(NOB_INFO, "%s", " ");
nob_log(NOB_INFO, "Usage: %s <command> [args...]", program_name);
nob_log(NOB_INFO, "%s", " ");
nob_log(NOB_INFO, "Commands:");
nob_log(NOB_INFO, " build [targets...] build all targets or the given ones");
nob_log(NOB_INFO, " run <target> [args] build and run a target");
nob_log(NOB_INFO, " test build and run VM unit tests");
nob_log(NOB_INFO, " clean remove build artifacts");
nob_log(NOB_INFO, " list list all targets");
nob_log(NOB_INFO, " help/-h/--help print this help message");
nob_log(NOB_INFO, "%s", " ");
nob_log(NOB_INFO, "Targets:");
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
nob_log(NOB_INFO, " %s", exe_targets[i].name);
}
}
int main(int argc, char **argv) {
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
NOB_GO_REBUILD_URSELF_PLUS(argc, argv, "nob.h");
set_log_handler(nob_cancer_log_handler);
const char *program_name = nob_shift(argv, argc);
const char *command_name = "build";
if (argc > 0) {
command_name = nob_shift(argv, argc);
}
if (strcmp(command_name, "build") == 0) {
if (!prepare_build())
return 1;
if (argc > 0) {
while (argc > 0) {
const char *target_name = nob_shift(argv, argc);
if (!build_target(target_name))
return 1;
}
} else {
if (!build_all())
return 1;
}
return 0;
}
if (strcmp(command_name, "run") == 0) {
if (argc <= 0) {
nob_log(NOB_ERROR, "usage: %s run <target> [args...]", program_name);
return 1;
}
const char *target_name = nob_shift(argv, argc);
if (!prepare_build())
return 1;
if (!build_target(target_name))
return 1;
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, exe_path(target_name));
while (argc > 0) {
nob_cmd_append(&cmd, nob_shift(argv, argc));
}
return nob_cmd_run(&cmd) ? 0 : 1;
}
if (strcmp(command_name, "test") == 0) {
if (!prepare_build())
return 1;
if (!build_target("test"))
return 1;
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, exe_path("test"));
return nob_cmd_run(&cmd) ? 0 : 1;
}
if (strcmp(command_name, "clean") == 0) {
if (nob_file_exists(BUILD_FOLDER)) {
if (!delete_directory_recursively(BUILD_FOLDER))
return 1;
}
nob_log(NOB_INFO, "cleaned %s", BUILD_FOLDER);
return 0;
}
if (strcmp(command_name, "list") == 0) {
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
nob_log(NOB_INFO, "%s:", exe_targets[i].name);
for (size_t j = 0; j < exe_targets[i].srcs_count; ++j) {
nob_log(NOB_INFO, " %s", exe_targets[i].srcs[j]);
}
}
return 0;
}
if (strcmp(command_name, "help") == 0 || strcmp(command_name, "-h") == 0 ||
strcmp(command_name, "--help") == 0) {
print_help(program_name);
return 0;
}
nob_log(NOB_ERROR, "unknown command `%s`", command_name);
print_help(program_name);
return 1;
}

3390
nob.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,53 +0,0 @@
vm = [
"stage0/spl_mcode.c",
"stage0/spl_syscall.c",
"stage0/spl_vm.c",
]
splc0_part = [
"stage1/spl_ir.c",
"stage1/spl_ast.c",
"stage1/spl_lexer.c",
"stage1/spl_dumptree.c",
"stage1/spl_type.c",
"stage1/spl_sema.c",
"stage1/spl_ast2ir.c",
"stage1/spl_ir2vm.c",
]
exe = {
"spl_cli": ["stage0/spl_cli.c"] + vm,
"splc_cli": ["stage1/splc_cli.c"] + vm,
"splc0": ["stage1/splc0.c"] + vm + splc0_part,
"test": ["stage0/test_spl_vm.c"] + vm,
"spl_disasm": ["stage0/spl_disasm.c"] + vm,
}
pipeline = {
"splc0b": {"compiler": "splc0", "runner": "spl_cli"},
"splc0r": {"compiler": "splc0", "runner": "splc_cli"},
"splc0d": {"compiler": "splc0", "runner": "spl_disasm"},
"splc1b": {"compiler": "splc0", "runner": "splc_cli"},
"splc1r": {"compiler": "splc1", "runner": "splc_cli"},
"splc1d": {"compiler": "splc1", "runner": "spl_disasm"},
"splc2b": {"compiler": "splc1", "runner": "splc_cli"},
"splc2r": {"compiler": "splc2", "runner": "splc_cli"},
"splc2d": {"compiler": "splc2", "runner": "spl_disasm"},
"splc3b": {"compiler": "splc2", "runner": "splc_cli"},
"splc3r": {"compiler": "splc3", "runner": "splc_cli"},
"splc3d": {"compiler": "splc3", "runner": "spl_disasm"},
"splc4b": {"compiler": "splc3", "runner": "splc_cli"},
"splc4r": {"compiler": "splc4", "runner": "splc_cli"},
"splc4d": {"compiler": "splc4", "runner": "spl_disasm"},
}
spl = {
"splc1": {"src": "stage2/splc1.spl", "pipeline": "splc0r"},
"splc2": {"src": "stage2/splc2.spl", "pipeline": "splc1r"},
"splc3": {"src": "stage3/splc3.spl", "pipeline": "splc2r"},
"splc4": {"src": "stage4/splc4.spl", "pipeline": "splc3r"},
}

View File

@@ -77,6 +77,8 @@ static inline usize map_hash_str(const char *s) {
for (usize(idx) = 0; (idx) < (map).cap; ++(idx)) \
if ((map).data[(idx)].state == __MAP_SLOT_OCCUPIED)
#define unsafe_map_at(map, idx) ((map).data[(idx)])
/**
* 插入(若键已存在则更新值)
* 注意:扩容使用 realloc失败会 abort可自行修改错误处理
@@ -128,6 +130,56 @@ static inline usize map_hash_str(const char *s) {
} \
} while (0)
/**
* 插入(仅当键不存在时),若键已存在则静默跳过,不更新值
* 与 map_put 的差异仅在"键已存在时"map_put 更新值map_put_new 放弃
*/
#define map_put_new(map, _key, _val) \
do { \
/* 扩容 */ \
if ((map).cap == 0 || (map).size * 128 / (map).cap >= MAP_DEFAULT_LOAD_FACTOR) { \
usize new_cap = (map).cap == 0 ? 8 : (map).cap * 2; \
MAP_SLOT(MAP_TYPEOF((map).data->key), MAP_TYPEOF((map).data->val)) *new_data = \
calloc(new_cap, sizeof(*new_data)); \
if (!new_data) \
abort(); \
/* 重新插入旧元素 */ \
for (usize _i = 0; _i < (map).cap; ++_i) { \
if ((map).data[_i].state == __MAP_SLOT_OCCUPIED) { \
usize _h = (map).hash((map).data[_i].key) & (new_cap - 1); \
while (new_data[_h].state == __MAP_SLOT_OCCUPIED) \
_h = (_h + 1) & (new_cap - 1); \
new_data[_h].key = (map).data[_i].key; \
new_data[_h].val = (map).data[_i].val; \
new_data[_h].state = __MAP_SLOT_OCCUPIED; \
} \
} \
free((map).data); \
(map).data = (void *)new_data; \
(map).cap = new_cap; \
} \
/* 查找 */ \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _mask; \
usize _first_del = (usize) - 1; \
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
(map).cmp((map).data[_idx].key, _key) == 0) { \
break; /* 已存在,不更新 */ \
} \
if ((map).data[_idx].state == __MAP_SLOT_DELETED && _first_del == (usize) - 1) \
_first_del = _idx; \
_idx = (_idx + 1) & _mask; \
} \
if ((map).data[_idx].state == __MAP_SLOT_EMPTY) { \
usize _target = (_first_del != (usize) - 1) ? _first_del : _idx; \
(map).data[_target].key = _key; \
(map).data[_target].val = _val; \
(map).data[_target].state = __MAP_SLOT_OCCUPIED; \
++(map).size; \
} \
} while (0)
/**
* 查询:若找到,*out_val 被赋值为对应值并返回 1否则返回 0
*/
@@ -150,6 +202,33 @@ static inline usize map_hash_str(const char *s) {
_found; \
}))
/**
* 查询(续探):首次调用前将 *in_out_idx 置为 (usize)-1
* 则从键自身的 hash 桶开始查找;命中后 *out_val 被赋值、返回 1
* 且 *in_out_idx 更新为命中槽位,下次调用从该槽的下一个继续探测(碰撞续探)。
* 扫描到空槽返回 0。用于 key 碰撞后需要回表二次比较的场景。
*/
#define map_get_continue(map, _key, out_val, in_out_idx) \
(({ \
int _found = 0; \
if ((map).cap > 0) { \
usize _mask = (map).cap - 1; \
usize _idx = (*(in_out_idx) == (usize) - 1) ? (map).hash(_key) & _mask \
: (*(in_out_idx) + 1) & _mask; \
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
(map).cmp((map).data[_idx].key, _key) == 0) { \
*out_val = (map).data[_idx].val; \
*(in_out_idx) = _idx; \
_found = 1; \
break; \
} \
_idx = (_idx + 1) & _mask; \
} \
} \
_found; \
}))
/**
* 删除指定键
*/

View File

@@ -14,7 +14,7 @@
#include <stdlib.h>
#define log_vsnprintf vsnprintf
#define log_puts puts
#define log_abort abort
#define log_abort() exit(1)
#endif
#ifdef __GNUC__ // GCC, Clang

View File

@@ -1,4 +1,4 @@
/* spl_cli.c SIR VM launcher + gdb-style interactive debugger
/* spl_cli.c SIR VM launcher + gdb-style interactive debugger
*
* Usage: spl_cli [options] <file.sir> [args...]
* -d, --debug stack-canary checks
@@ -189,7 +189,7 @@ typedef struct {
static const char *fn_name_at(spl_prog_t *prog, usize ip) {
for (usize i = 0; i < vec_size(prog->funcs); i++) {
spl_func_t *f = &vec_at(prog->funcs, i);
spl_vm_func_t *f = &vec_at(prog->funcs, i);
if (ip >= f->address && ip < f->address + f->ninsns)
return f->name ? f->name : "?";
}
@@ -201,7 +201,7 @@ static void cur_func_bounds(spl_prog_t *prog, usize ip, usize *start, usize *end
*start = 0;
*end = vec_size(prog->insns);
for (usize i = 0; i < vec_size(prog->funcs); i++) {
spl_func_t *f = &vec_at(prog->funcs, i);
spl_vm_func_t *f = &vec_at(prog->funcs, i);
if (ip >= f->address && ip < f->address + f->ninsns) {
*start = f->address;
*end = f->address + f->ninsns;
@@ -211,9 +211,9 @@ static void cur_func_bounds(spl_prog_t *prog, usize ip, usize *start, usize *end
}
/* 格式化一条指令(不含行号前缀) */
static void fmt_insn(const spl_ins_t *ins, char *buf, size_t n) {
snprintf(buf, n, "%-11s %-5s %zu", spl_opcode_name(ins->opcode), spl_type_tag_name(ins->type),
ins->imm);
static void fmt_insn(const spl_vm_ins_t *ins, char *buf, size_t n) {
snprintf(buf, n, "%-11s %-5s %zu", spl_vm_opcode_name(ins->opcode),
spl_vm_type_kind_name(ins->type), ins->imm);
}
static void dbg_show_location(dbg_t *d) {
@@ -539,7 +539,7 @@ static int cmd_x(dbg_t *d, const char *args) {
return 0;
}
unsigned char *sbase = (unsigned char *)d->vm->stacks.data;
usize slen = d->vm->config.max_stack_depth * sizeof(spl_val_t);
usize slen = d->vm->config.max_stack_depth * sizeof(spl_vm_val_t);
printf(" addr=%#llx stack=[%p,+%zu) in=%d\n", addr, sbase, slen,
addr >= (uintptr_t)sbase && addr < (uintptr_t)(sbase + slen));
unsigned char *p = (unsigned char *)(uintptr_t)addr;
@@ -567,7 +567,7 @@ static int cmd_p(dbg_t *d, const char *args) {
printf(" no variable '%s' in %s\n", args, fn);
return 0;
}
spl_val_t *addr = (spl_val_t *)((char *)&d->vm->stacks.data[d->vm->fp] + v->offset);
spl_vm_val_t *addr = (spl_vm_val_t *)((char *)&d->vm->stacks.data[d->vm->fp] + v->offset);
printf(" %s = %zu (0x%zx) @ fp+%zu\n", v->name, *addr, *addr, v->offset);
d->last_ptr = (usize)*addr; /* 供 x 无参重读 */
return 0;

View File

@@ -1,4 +1,4 @@
/* spl_disasm.c SIR bytecode disassembler
/* spl_disasm.c - SIR bytecode disassembler
*
* Usage: spl_disasm <file.sir>
*/
@@ -25,7 +25,7 @@ int main(int argc, const char **argv) {
if (vec_size(prog.funcs) > 0) {
printf(";; --- functions ---\n");
for (usize i = 0; i < vec_size(prog.funcs); i++) {
spl_func_t *f = &vec_at(prog.funcs, i);
spl_vm_func_t *f = &vec_at(prog.funcs, i);
printf(" %s nargs=%zu ninsns=%zu addr=%zu\n", f->name ? f->name : "(anon)", f->nargs,
f->ninsns, f->address);
}
@@ -35,7 +35,7 @@ int main(int argc, const char **argv) {
if (vec_size(prog.natives) > 0) {
printf(";; --- natives ---\n");
for (int i = 0; i < (int)vec_size(prog.natives); i++) {
spl_native_t *n = &vec_at(prog.natives, i);
spl_vm_native_t *n = &vec_at(prog.natives, i);
printf(" %s\n", n->name ? n->name : "(anon)");
}
printf("\n");
@@ -51,22 +51,22 @@ int main(int argc, const char **argv) {
printf(";; --- instructions ---\n");
for (usize i = 0; i < vec_size(prog.insns); i++) {
spl_ins_t *ins = &vec_at(prog.insns, i);
printf("%4zd: %s", i, spl_opcode_name((spl_opcode_t)ins->opcode));
spl_vm_ins_t *ins = &vec_at(prog.insns, i);
printf("%4zd: %s", i, spl_vm_opcode_name((spl_vm_opcode_t)ins->opcode));
if (ins->type != SPL_VOID)
printf(" %s", spl_type_tag_name((spl_type_t)ins->type));
printf(" %s", spl_vm_type_kind_name((spl_vm_kind_t)ins->type));
printf(" %zd", ins->imm);
/* annotate jumps / calls */
if (ins->opcode == SPL_JMP || ins->opcode == SPL_BZ || ins->opcode == SPL_BNZ) {
long long target = (long long)i + 1 + (long long)ins->imm;
printf(" ; -> %zd", target);
spl_vm_val_t target = i + 1 + ins->imm;
printf(" ; -> %zu", target);
} else if (ins->opcode == SPL_CALL) {
printf(" ; nargs=%zd, from stack", (long long)ins->imm);
printf(" ; nargs=%zu, from stack", ins->imm);
} else if (ins->opcode == SPL_CALLI) {
printf(" ; indirect call");
} else if (ins->opcode == SPL_GADDR) {
printf(" ; gdata[%zd]", (long long)ins->imm);
printf(" ; gdata[%zu]", ins->imm);
}
printf("\n");
}

View File

@@ -1,4 +1,4 @@
/* spl_mcode.c SPL VM machine code binary serialization, deserialization, and utilities
/* spl_mcode.c - SPL VM machine code binary serialization, deserialization, and utilities
*
* Binary format (all metadata fields are spl_val_t = uint64_t LE):
* [HEADER] magic(8) nfuncs(8) ninsns(8) nnatives(8) nstrs(8) ndata(8)
@@ -45,16 +45,16 @@ void spl_prog_drop(spl_prog_t *prog) {
/* ---- LE read/write helpers ---- */
static inline spl_val_t rd64(const unsigned char **p) {
spl_val_t v = (spl_val_t)(*p)[0] | ((spl_val_t)(*p)[1] << 8) | ((spl_val_t)(*p)[2] << 16) |
((spl_val_t)(*p)[3] << 24) | ((spl_val_t)(*p)[4] << 32) |
((spl_val_t)(*p)[5] << 40) | ((spl_val_t)(*p)[6] << 48) |
((spl_val_t)(*p)[7] << 56);
static inline spl_vm_val_t rd64(const unsigned char **p) {
spl_vm_val_t v = (spl_vm_val_t)(*p)[0] | ((spl_vm_val_t)(*p)[1] << 8) |
((spl_vm_val_t)(*p)[2] << 16) | ((spl_vm_val_t)(*p)[3] << 24) |
((spl_vm_val_t)(*p)[4] << 32) | ((spl_vm_val_t)(*p)[5] << 40) |
((spl_vm_val_t)(*p)[6] << 48) | ((spl_vm_val_t)(*p)[7] << 56);
*p += 8;
return v;
}
static inline void wr64(unsigned char **p, spl_val_t v) {
static inline void wr64(unsigned char **p, spl_vm_val_t v) {
*(*p)++ = (unsigned char)(v);
*(*p)++ = (unsigned char)(v >> 8);
*(*p)++ = (unsigned char)(v >> 16);
@@ -73,7 +73,7 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
unsigned char *data;
long len;
const unsigned char *p;
spl_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
spl_vm_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
if (!fname || !prog)
return -1;
@@ -120,9 +120,9 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
ndata = rd64(&p);
/* ---- function table ---- */
for (spl_val_t i = 0; i < nfuncs; i++) {
spl_func_t func = {0};
spl_val_t nlen = rd64(&p);
for (spl_vm_val_t i = 0; i < nfuncs; i++) {
spl_vm_func_t func = {0};
spl_vm_val_t nlen = rd64(&p);
usize pad = ALIGN8((usize)nlen) - (usize)nlen;
func.name = (char *)malloc((usize)nlen);
@@ -141,12 +141,12 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
}
/* ---- instructions ---- */
for (spl_val_t i = 0; i < ninsns; i++) {
for (spl_vm_val_t i = 0; i < ninsns; i++) {
if ((size_t)(p - data) + 12 > (size_t)len) {
free(data);
return -1;
}
spl_ins_t ins;
spl_vm_ins_t ins;
ins.opcode = (uint16_t)p[0] | ((uint16_t)p[1] << 8);
ins.type = (uint16_t)p[2] | ((uint16_t)p[3] << 8);
p += 4;
@@ -155,9 +155,9 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
}
/* ---- native table ---- */
for (spl_val_t i = 0; i < nnatives; i++) {
spl_native_t nat = {0};
spl_val_t nlen = rd64(&p);
for (spl_vm_val_t i = 0; i < nnatives; i++) {
spl_vm_native_t nat = {0};
spl_vm_val_t nlen = rd64(&p);
usize pad = ALIGN8((usize)nlen) - (usize)nlen;
nat.name = (char *)malloc((usize)nlen);
@@ -174,8 +174,8 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
}
/* ---- string table ---- */
for (spl_val_t i = 0; i < nstrs; i++) {
spl_val_t slen = rd64(&p);
for (spl_vm_val_t i = 0; i < nstrs; i++) {
spl_vm_val_t slen = rd64(&p);
usize pad = ALIGN8((usize)slen) - (usize)slen;
char *s = (char *)malloc((usize)slen + 1);
if (!s) {
@@ -189,8 +189,8 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
}
/* ---- global data ---- */
for (spl_val_t i = 0; i < ndata; i++) {
spl_gdata_t entry;
for (spl_vm_val_t i = 0; i < ndata; i++) {
spl_vm_gdata_t entry;
entry.size = rd64(&p);
usize pad = ALIGN8(entry.size) - entry.size;
entry.data = (unsigned char *)malloc(entry.size);
@@ -226,9 +226,9 @@ int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
int spl_prog_store_to_file(const char *fname, spl_prog_t *prog) {
unsigned char *buf, *p;
spl_val_t i;
spl_vm_val_t i;
size_t total;
spl_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
spl_vm_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
usize nlen, pad;
if (!fname || !prog)
@@ -306,7 +306,7 @@ int spl_prog_store_to_file(const char *fname, spl_prog_t *prog) {
/* ---- instructions ---- */
for (i = 0; i < ninsns; i++) {
spl_ins_t *ins = &vec_at(prog->insns, i);
spl_vm_ins_t *ins = &vec_at(prog->insns, i);
*p++ = (unsigned char)(ins->opcode);
*p++ = (unsigned char)(ins->opcode >> 8);
*p++ = (unsigned char)(ins->type);
@@ -341,7 +341,7 @@ int spl_prog_store_to_file(const char *fname, spl_prog_t *prog) {
/* ---- global data ---- */
for (i = 0; i < ndata; i++) {
spl_gdata_t *entry = &vec_at(prog->gdata, i);
spl_vm_gdata_t *entry = &vec_at(prog->gdata, i);
pad = ALIGN8(entry->size) - entry->size;
wr64(&p, entry->size);
memcpy(p, entry->data, entry->size);
@@ -362,22 +362,22 @@ int spl_prog_store_to_file(const char *fname, spl_prog_t *prog) {
return 0;
}
int spl_prog_add_instr(spl_prog_t *prog, uint8_t opcode, uint8_t type, spl_val_t imm) {
int spl_prog_add_instr(spl_prog_t *prog, uint8_t opcode, uint8_t type, spl_vm_val_t imm) {
if (!prog)
return 0;
spl_ins_t ins = (spl_ins_t){.opcode = opcode, .type = type, .imm = imm};
spl_vm_ins_t ins = (spl_vm_ins_t){.opcode = opcode, .type = type, .imm = imm};
vec_push(prog->insns, ins);
return vec_size(prog->insns);
}
int spl_prog_add_func(spl_prog_t *prog, spl_func_t *func) {
int spl_prog_add_func(spl_prog_t *prog, spl_vm_func_t *func) {
if (!prog || !func)
return 0;
vec_push(prog->funcs, *func);
return vec_size(prog->funcs);
}
int spl_prog_add_native(spl_prog_t *prog, spl_native_t *native) {
int spl_prog_add_native(spl_prog_t *prog, spl_vm_native_t *native) {
if (!prog || !native)
return 0;
vec_push(prog->natives, *native);
@@ -385,7 +385,7 @@ int spl_prog_add_native(spl_prog_t *prog, spl_native_t *native) {
}
int spl_prog_add_data(spl_prog_t *prog, void *ptr, usize size) {
spl_gdata_t entry;
spl_vm_gdata_t entry;
if (!prog)
return 0;
entry.data = (unsigned char *)malloc(size);
@@ -397,7 +397,7 @@ int spl_prog_add_data(spl_prog_t *prog, void *ptr, usize size) {
return vec_size(prog->gdata);
}
spl_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name) {
spl_vm_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name) {
if (!prog || !name)
return NULL;
vec_for(prog->funcs, i) {
@@ -409,7 +409,7 @@ spl_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name) {
return NULL;
}
spl_native_t *spl_prog_get_native(spl_prog_t *prog, const char *name) {
spl_vm_native_t *spl_prog_get_native(spl_prog_t *prog, const char *name) {
if (!prog || !name)
return NULL;
vec_for(prog->natives, i) {
@@ -426,8 +426,8 @@ const char *opcode_name[] = {
SPL_OPCODES(X)
#undef X
};
const char *spl_opcode_name(spl_opcode_t opcode) { return opcode_name[opcode]; }
const char *spl_type_tag_name(spl_type_t type) {
const char *spl_vm_opcode_name(spl_vm_opcode_t opcode) { return opcode_name[opcode]; }
const char *spl_vm_type_kind_name(spl_vm_kind_t type) {
switch (type) {
case SPL_VOID:
return "void";
@@ -464,10 +464,10 @@ const char *spl_type_tag_name(spl_type_t type) {
}
}
void spl_ins_dump(spl_ins_t *ins, spl_val_t addr) {
printf("%4zu: %s", addr, spl_opcode_name((spl_opcode_t)ins->opcode));
void spl_vm_ins_dump(spl_vm_ins_t *ins, spl_vm_val_t addr) {
printf("%4zu: %s", addr, spl_vm_opcode_name((spl_vm_opcode_t)ins->opcode));
if (ins->type != SPL_VOID)
printf(" %s", spl_type_tag_name((spl_type_t)ins->type));
printf(" %s", spl_vm_type_kind_name((spl_vm_kind_t)ins->type));
printf(" %zd:%zx", ins->imm, ins->imm);
printf("\n");
}

View File

@@ -29,7 +29,7 @@ typedef enum {
SPL_F64,
SPL_PTR,
SPL_TYPE_COUNT,
} spl_type_t;
} spl_vm_kind_t;
/* clang-format off */
#define SPL_OPCODES(X) \
@@ -103,7 +103,7 @@ typedef enum {
#define X(opcode, name, argc, pop, push, desc) opcode,
SPL_OPCODES(X)
#undef X
} spl_opcode_t;
} spl_vm_opcode_t;
/*
* Binary format (all metadata fields spl_val_t LE):
@@ -151,48 +151,48 @@ typedef enum {
#define SPL_BINFMT_MAGIC "SPLBIN\0\0"
// All SIR stack values are ptr-bit unsigned integers
typedef usize spl_val_t;
typedef usize spl_vm_val_t;
typedef struct spl_ins {
typedef struct spl_vm_ins {
uint8_t opcode;
uint8_t type;
spl_val_t imm;
} spl_ins_t;
typedef VEC(spl_ins_t) spl_ins_vec_t;
spl_vm_val_t imm;
} spl_vm_ins_t;
typedef VEC(spl_vm_ins_t) spl_vm_ins_vec_t;
typedef struct spl_func {
typedef struct spl_vm_func {
char *name;
spl_val_t idx_of_strtab;
spl_val_t nargs;
spl_val_t ninsns;
spl_val_t address;
} spl_func_t;
typedef VEC(spl_func_t) spl_func_vec_t;
spl_vm_val_t idx_of_strtab;
spl_vm_val_t nargs;
spl_vm_val_t ninsns;
spl_vm_val_t address;
} spl_vm_func_t;
typedef VEC(spl_vm_func_t) spl_vm_func_vec_t;
/* Native function pointer type */
typedef spl_val_t (*spl_fn_t)(int nargs, spl_val_t *args);
typedef struct spl_native {
typedef spl_vm_val_t (*spl_vm_fn_t)(int nargs, spl_vm_val_t *args);
typedef struct spl_vm_native {
char *name;
spl_val_t idx_of_strtab;
spl_fn_t impl_fn;
} spl_native_t;
typedef VEC(spl_native_t) spl_native_vec_t;
spl_vm_val_t idx_of_strtab;
spl_vm_fn_t impl_fn;
} spl_vm_native_t;
typedef VEC(spl_vm_native_t) spl_vm_native_vec_t;
typedef struct {
unsigned char *data;
usize size;
} spl_gdata_t;
typedef VEC(spl_gdata_t) spl_data_t;
typedef VEC(const char *) spl_strtab_t;
typedef MAP(const char *, const char *) spl_symtab_t;
} spl_vm_gdata_t;
typedef VEC(spl_vm_gdata_t) spl_vm_data_t;
typedef VEC(const char *) spl_vm_strtab_t;
typedef MAP(const char *, const char *) spl_vm_symtab_t;
/* Opaque handle for loaded program */
typedef struct spl_prog {
spl_ins_vec_t insns;
spl_func_vec_t funcs;
spl_native_vec_t natives;
spl_data_t gdata;
spl_strtab_t strtab;
spl_symtab_t symtab;
spl_vm_ins_vec_t insns;
spl_vm_func_vec_t funcs;
spl_vm_native_vec_t natives;
spl_vm_data_t gdata;
spl_vm_strtab_t strtab;
spl_vm_symtab_t symtab;
char *debug; /* 文件尾部 debug 段splc0 -g 追加的文本),无则 NULL */
usize debug_size;
} spl_prog_t;
@@ -203,18 +203,18 @@ void spl_prog_drop(spl_prog_t *prog);
int spl_prog_load_from_file(const char *fname, spl_prog_t *prog);
int spl_prog_store_to_file(const char *fname, spl_prog_t *prog);
int spl_prog_add_instr(spl_prog_t *prog, uint8_t opcode, uint8_t type, spl_val_t imm);
int spl_prog_add_instr(spl_prog_t *prog, uint8_t opcode, uint8_t type, spl_vm_val_t imm);
int spl_prog_add_data(spl_prog_t *prog, void *ptr, usize size);
int spl_prog_add_func(spl_prog_t *prog, spl_func_t *func);
int spl_prog_add_native(spl_prog_t *prog, spl_native_t *native);
int spl_prog_add_func(spl_prog_t *prog, spl_vm_func_t *func);
int spl_prog_add_native(spl_prog_t *prog, spl_vm_native_t *native);
spl_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name);
spl_native_t *spl_prog_get_native(spl_prog_t *prog, const char *name);
spl_vm_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name);
spl_vm_native_t *spl_prog_get_native(spl_prog_t *prog, const char *name);
/* Opcode name lookup for debugging/dumping */
const char *spl_opcode_name(spl_opcode_t opcode);
const char *spl_type_tag_name(spl_type_t type);
const char *spl_vm_opcode_name(spl_vm_opcode_t opcode);
const char *spl_vm_type_kind_name(spl_vm_kind_t type);
void spl_ins_dump(spl_ins_t *ins, spl_val_t addr);
void spl_vm_ins_dump(spl_vm_ins_t *ins, spl_vm_val_t addr);
#endif /* __SPL_MCODE_H__ */

View File

@@ -1,4 +1,4 @@
/* spl_syscall.c built-in syscall implementations + registration
/* spl_syscall.c - built-in syscall implementations + registration
*
* All syscalls validate nargs, cast spl_val_t args to the expected C types,
* execute, and return the result as spl_val_t.
@@ -23,7 +23,7 @@
* Each SYSCALL_N macro:
* 1. Validates nargs (prints error and returns -1 on mismatch)
* 2. Casts args[n] from spl_val_t to the specified C type via
* (type)(uintptr_t) this handles both integer and pointer types
* (type)(uintptr_t) - this handles both integer and pointer types
* 3. Evaluates the expression and returns the result as spl_val_t
* ================================================================= */
@@ -36,94 +36,94 @@
} while (0)
#define SYSCALL_0(name, ret_expr) \
static spl_val_t name(int nargs, spl_val_t *args) { \
static spl_vm_val_t name(int nargs, spl_vm_val_t *args) { \
CHECK_NARGS(#name, 0); \
(void)args; \
return (spl_val_t)(uintptr_t)(ret_expr); \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_1(name, t1, ret_expr) \
static spl_val_t name(int nargs, spl_val_t *args) { \
static spl_vm_val_t name(int nargs, spl_vm_val_t *args) { \
CHECK_NARGS(#name, 1); \
t1 a1 = (t1)(uintptr_t)args[0]; \
return (spl_val_t)(uintptr_t)(ret_expr); \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_2(name, t1, t2, ret_expr) \
static spl_val_t name(int nargs, spl_val_t *args) { \
static spl_vm_val_t name(int nargs, spl_vm_val_t *args) { \
CHECK_NARGS(#name, 2); \
t1 a1 = (t1)(uintptr_t)args[0]; \
t2 a2 = (t2)(uintptr_t)args[1]; \
return (spl_val_t)(uintptr_t)(ret_expr); \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_3(name, t1, t2, t3, ret_expr) \
static spl_val_t name(int nargs, spl_val_t *args) { \
static spl_vm_val_t name(int nargs, spl_vm_val_t *args) { \
CHECK_NARGS(#name, 3); \
t1 a1 = (t1)(uintptr_t)args[0]; \
t2 a2 = (t2)(uintptr_t)args[1]; \
t3 a3 = (t3)(uintptr_t)args[2]; \
return (spl_val_t)(uintptr_t)(ret_expr); \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_4(name, t1, t2, t3, t4, ret_expr) \
static spl_val_t name(int nargs, spl_val_t *args) { \
static spl_vm_val_t name(int nargs, spl_vm_val_t *args) { \
CHECK_NARGS(#name, 4); \
t1 a1 = (t1)(uintptr_t)args[0]; \
t2 a2 = (t2)(uintptr_t)args[1]; \
t3 a3 = (t3)(uintptr_t)args[2]; \
t4 a4 = (t4)(uintptr_t)args[3]; \
return (spl_val_t)(uintptr_t)(ret_expr); \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
/* =================================================================
* OS syscalls
* ================================================================= */
/* vm_exit terminate process with the given exit code */
SYSCALL_1(vm_exit, int, (exit(a1), (spl_val_t)0))
/* vm_exit - terminate process with the given exit code */
SYSCALL_1(vm_exit, int, (exit(a1), (spl_vm_val_t)0))
/* vm_putchar write a single character to stdout */
/* vm_putchar - write a single character to stdout */
SYSCALL_1(vm_putchar, int, putchar(a1))
/* vm_getchar read a single character from stdin */
/* vm_getchar - read a single character from stdin */
SYSCALL_0(vm_getchar, getchar())
/* vm_putint print an integer to stdout */
SYSCALL_1(vm_putint, int, (fprintf(stdout, "%d", a1), (spl_val_t)0))
/* vm_putint - print an integer to stdout */
SYSCALL_1(vm_putint, int, (fprintf(stdout, "%d", a1), (spl_vm_val_t)0))
/* vm_putstr print a string to stdout (no trailing newline) */
SYSCALL_1(vm_putstr, const char *, (fputs(a1, stdout), (spl_val_t)0))
/* vm_putstr - print a string to stdout (no trailing newline) */
SYSCALL_1(vm_putstr, const char *, (fputs(a1, stdout), (spl_vm_val_t)0))
/* vm_fopen open a file, returns FILE* as spl_val_t */
/* vm_fopen - open a file, returns FILE* as spl_val_t */
SYSCALL_2(vm_fopen, const char *, const char *, (uintptr_t)fopen(a1, a2))
/* vm_fclose close a file, returns 0 on success */
/* vm_fclose - close a file, returns 0 on success */
SYSCALL_1(vm_fclose, FILE *, fclose(a1))
/* vm_fread read from file, returns number of items read */
/* vm_fread - read from file, returns number of items read */
SYSCALL_4(vm_fread, void *, size_t, size_t, FILE *, fread(a1, a2, a3, a4))
/* vm_fwrite write to file, returns number of items written */
/* vm_fwrite - write to file, returns number of items written */
SYSCALL_4(vm_fwrite, const void *, size_t, size_t, FILE *, fwrite(a1, a2, a3, a4))
/* vm_fsize get file size in bytes */
static spl_val_t vm_fsize(int nargs, spl_val_t *args) {
/* vm_fsize - get file size in bytes */
static spl_vm_val_t vm_fsize(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_fsize", 1);
FILE *f = (FILE *)(uintptr_t)args[0];
long cur = ftell(f);
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, cur, SEEK_SET);
return (spl_val_t)(uintptr_t)sz;
return (spl_vm_val_t)(uintptr_t)sz;
}
SYSCALL_0(vm_stdin, stdin)
SYSCALL_0(vm_stdout, stdout)
SYSCALL_0(vm_stderr, stderr)
/* vm_read_file read entire file into a malloc'd, null-terminated buffer */
static spl_val_t vm_read_file(int nargs, spl_val_t *args) {
/* vm_read_file - read entire file into a malloc'd, null-terminated buffer */
static spl_vm_val_t vm_read_file(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_read_file", 1);
const char *path = (const char *)(uintptr_t)args[0];
if (path == nullptr) {
@@ -146,28 +146,28 @@ static spl_val_t vm_read_file(int nargs, spl_val_t *args) {
size_t nread = fread(buf, 1, (size_t)sz, f);
fclose(f);
buf[nread] = '\0';
return (spl_val_t)(uintptr_t)buf;
return (spl_vm_val_t)(uintptr_t)buf;
}
/* vm_alloc allocate memory (malloc) */
/* vm_alloc - allocate memory (malloc) */
SYSCALL_1(vm_alloc, size_t, (uintptr_t)malloc(a1))
/* vm_free free memory */
SYSCALL_1(vm_free, void *, (free(a1), (spl_val_t)0))
/* vm_free - free memory */
SYSCALL_1(vm_free, void *, (free(a1), (spl_vm_val_t)0))
/* vm_realloc reallocate memory (realloc) */
/* vm_realloc - reallocate memory (realloc) */
SYSCALL_2(vm_realloc, void *, size_t, (uintptr_t)realloc(a1, a2))
/* vm_strlen get string length */
/* vm_strlen - get string length */
SYSCALL_1(vm_strlen, const char *, strlen(a1))
/* vm_strcmp compare two strings */
/* vm_strcmp - compare two strings */
SYSCALL_2(vm_strcmp, const char *, const char *, strcmp(a1, a2))
/* vm_memcpy copy memory, returns dst */
/* vm_memcpy - copy memory, returns dst */
SYSCALL_3(vm_memcpy, void *, const void *, size_t, (memcpy(a1, a2, a3), (uintptr_t)a1))
static spl_val_t vm_printf(int nargs, spl_val_t *args) {
static spl_vm_val_t vm_printf(int nargs, spl_vm_val_t *args) {
(void)args;
if (nargs <= 0) {
return 0;
@@ -228,25 +228,25 @@ static spl_val_t vm_printf(int nargs, spl_val_t *args) {
}
/* =================================================================
* VM syscalls (for comptime compile-time code execution)
* VM syscalls (for comptime - compile-time code execution)
*
* These let SPL code create isolated sub-VMs, load compiled .sir
* programs into them, push arguments, call functions, and run.
* ================================================================= */
/* vm_new create a new sub-VM instance, returns spl_vm_t* */
static spl_val_t vm_new(int nargs, spl_val_t *args) {
/* vm_new - create a new sub-VM instance, returns spl_vm_t* */
static spl_vm_val_t vm_new(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_new", 0);
(void)args;
spl_vm_t *vm = (spl_vm_t *)malloc(sizeof(spl_vm_t));
if (!vm)
return 0;
spl_vm_init(vm);
return (spl_val_t)(uintptr_t)vm;
return (spl_vm_val_t)(uintptr_t)vm;
}
/* vm_drop destroy a sub-VM and its loaded program */
static spl_val_t vm_drop(int nargs, spl_val_t *args) {
/* vm_drop - destroy a sub-VM and its loaded program */
static spl_vm_val_t vm_drop(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_drop", 1);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
if (!vm)
@@ -261,8 +261,8 @@ static spl_val_t vm_drop(int nargs, spl_val_t *args) {
return 0;
}
/* vm_load load a .sir file, register syscalls, return spl_prog_t* */
static spl_val_t vm_load(int nargs, spl_val_t *args) {
/* vm_load - load a .sir file, register syscalls, return spl_prog_t* */
static spl_vm_val_t vm_load(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_load", 2);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
const char *path = (const char *)(uintptr_t)args[1];
@@ -282,14 +282,14 @@ static spl_val_t vm_load(int nargs, spl_val_t *args) {
free(prog);
return -1;
}
return (spl_val_t)(uintptr_t)prog;
return (spl_vm_val_t)(uintptr_t)prog;
}
/* vm_push push a value onto the sub-VM's stack (for passing arguments) */
static spl_val_t vm_push(int nargs, spl_val_t *args) {
/* vm_push - push a value onto the sub-VM's stack (for passing arguments) */
static spl_vm_val_t vm_push(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_push", 2);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
spl_val_t val = args[1];
spl_vm_val_t val = args[1];
if (!vm)
return -1;
if (vm->sp >= vm->config.max_stack_depth) {
@@ -300,7 +300,7 @@ static spl_val_t vm_push(int nargs, spl_val_t *args) {
return 0;
}
/* vm_call call a function by name with pre-pushed arguments
/* vm_call - call a function by name with pre-pushed arguments
*
* Args (3): vm, function_name, nargs
* The arguments should already be on the sub-VM's stack via vm_push.
@@ -311,15 +311,15 @@ static spl_val_t vm_push(int nargs, spl_val_t *args) {
* - Sets fp = sp - nargs (so arg0 = data[fp], arg1 = data[fp+1], ...)
* - Sets ip to the function address
*/
static spl_val_t vm_call(int nargs, spl_val_t *args) {
static spl_vm_val_t vm_call(int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_call", 3);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
const char *name = (const char *)(uintptr_t)args[1];
spl_val_t call_nargs = args[2];
spl_vm_val_t call_nargs = args[2];
if (!vm || !name)
return -1;
spl_func_t *func = spl_prog_get_func(vm->prog, name);
spl_vm_func_t *func = spl_prog_get_func(vm->prog, name);
if (!func) {
fprintf(stderr, "vm_call: function '%s' not found\n", name);
return -1;
@@ -347,7 +347,7 @@ static spl_val_t vm_call(int nargs, spl_val_t *args) {
return 0;
}
/* vm_run run a sub-VM to completion, returns exit_code */
/* vm_run - run a sub-VM to completion, returns exit_code */
SYSCALL_1(vm_run, spl_vm_t *, spl_vm_run_until(a1, 0))
/* =================================================================
@@ -358,7 +358,7 @@ SYSCALL_1(vm_run, spl_vm_t *, spl_vm_run_until(a1, 0))
* ================================================================= */
void spl_syscall_register(spl_prog_t *prog) {
static spl_native_t table[] = {
static spl_vm_native_t table[] = {
/* OS operations */
{"vm_exit", 0, vm_exit},
{"vm_putchar", 0, vm_putchar},
@@ -393,7 +393,7 @@ void spl_syscall_register(spl_prog_t *prog) {
if (!prog)
return;
vec_for(prog->natives, i) {
spl_native_t *nat = &vec_at(prog->natives, i);
spl_vm_native_t *nat = &vec_at(prog->natives, i);
if (!nat->name || nat->impl_fn)
continue;
for (int j = 0; j < n; j++) {

View File

@@ -1,4 +1,4 @@
/* spl_syscall.h built-in syscall layer for SIR VM
/* spl_syscall.h - built-in syscall layer for SIR VM
*
* Provides I/O native functions (putchar, getchar, file ops, etc.)
* that compiled SPL programs can call via NCALL.

View File

@@ -1,4 +1,4 @@
/* spl_vm.c SIR step-by-step interpreter
/* spl_vm.c - SIR step-by-step interpreter
*
* Implements the spl_vm.h API with macro-based type dispatch to
* eliminate repetitive per-type switch cases.
@@ -28,8 +28,8 @@
* Type helpers
* ================================================================ */
static int spl_is_float(spl_type_t t) { return t == SPL_F32 || t == SPL_F64; }
static int spl_is_signed(spl_type_t t) {
static int spl_is_float(spl_vm_kind_t t) { return t == SPL_F32 || t == SPL_F64; }
static int spl_is_signed(spl_vm_kind_t t) {
switch (t) {
case SPL_I8:
case SPL_I16:
@@ -41,7 +41,7 @@ static int spl_is_signed(spl_type_t t) {
return 0;
}
}
static int spl_type_size(spl_type_t t) {
static int spl_type_size(spl_vm_kind_t t) {
switch (t) {
case SPL_VOID:
return 0;
@@ -99,9 +99,10 @@ static int spl_type_size(spl_type_t t) {
#define PUSH(v) \
do { \
spl_vm_val_t _pv = (spl_vm_val_t)(v); \
if (vm->sp >= vm->config.max_stack_depth) \
VM_ERROR("stack overflow"); \
vm->stacks.data[(vm->sp)++] = (spl_val_t)(v); \
vm->stacks.data[(vm->sp)++] = _pv; \
} while (0)
#define POP() vm->stacks.data[--(vm->sp)]
@@ -109,20 +110,20 @@ static int spl_type_size(spl_type_t t) {
/* ================================================================
* Type-dispatch macros for arithmetic / comparison
*
* ARITH_BINOP ADD / SUB / MUL (two's complement: op same for
* ARITH_BINOP - ADD / SUB / MUL (two's complement: op same for
* signed and unsigned at the same bit-width)
* DIV_REM_S signed division / remainder
* DIV_REM_U unsigned division / remainder
* CMP_ALL EQ / NE (bitwise compare, also handles floats)
* CMP_S signed ordering (<, <=, >, >=)
* CMP_U unsigned ordering
* DIV_REM_S - signed division / remainder
* DIV_REM_U - unsigned division / remainder
* CMP_ALL - EQ / NE (bitwise compare, also handles floats)
* CMP_S - signed ordering (<, <=, >, >=)
* CMP_U - unsigned ordering
* ================================================================ */
#define ARITH_BINOP(OP) \
do { \
spl_val_t _b = POP(), _a = POP(); \
spl_val_t _r = 0; \
if (spl_is_float((spl_type_t)ins->type)) { \
spl_vm_val_t _b = POP(), _a = POP(); \
spl_vm_val_t _r = 0; \
if (spl_is_float((spl_vm_kind_t)ins->type)) { \
double _da, _db, _dr; \
if (ins->type == SPL_F32) { \
float _fa, _fb; \
@@ -144,25 +145,25 @@ static int spl_type_size(spl_type_t t) {
} else { \
switch (ins->type) { \
case SPL_I8: \
_r = (spl_val_t)((int8_t)_a OP(int8_t) _b); \
_r = (spl_vm_val_t)((int8_t)_a OP(int8_t) _b); \
break; \
case SPL_U8: \
_r = (spl_val_t)((uint8_t)_a OP(uint8_t) _b); \
_r = (spl_vm_val_t)((uint8_t)_a OP(uint8_t) _b); \
break; \
case SPL_I16: \
_r = (spl_val_t)((int16_t)_a OP(int16_t) _b); \
_r = (spl_vm_val_t)((int16_t)_a OP(int16_t) _b); \
break; \
case SPL_U16: \
_r = (spl_val_t)((uint16_t)_a OP(uint16_t) _b); \
_r = (spl_vm_val_t)((uint16_t)_a OP(uint16_t) _b); \
break; \
case SPL_I32: \
_r = (spl_val_t)((int32_t)_a OP(int32_t) _b); \
_r = (spl_vm_val_t)((int32_t)_a OP(int32_t) _b); \
break; \
case SPL_U32: \
_r = (spl_val_t)((uint32_t)_a OP(uint32_t) _b); \
_r = (spl_vm_val_t)((uint32_t)_a OP(uint32_t) _b); \
break; \
case SPL_I64: \
_r = (spl_val_t)((int64_t)_a OP(int64_t) _b); \
_r = (spl_vm_val_t)((int64_t)_a OP(int64_t) _b); \
break; \
case SPL_U64: \
case SPL_PTR: \
@@ -177,14 +178,14 @@ static int spl_type_size(spl_type_t t) {
PUSH(_r); \
} while (0)
/* signed division / remainder all types cast to signed */
/* signed division / remainder - all types cast to signed */
#define DIV_REM_S(OP) \
do { \
spl_val_t _b = POP(), _a = POP(); \
spl_vm_val_t _b = POP(), _a = POP(); \
if (_b == 0) \
VM_ERROR("division by zero"); \
spl_val_t _r = 0; \
if (spl_is_float((spl_type_t)ins->type)) { \
spl_vm_val_t _r = 0; \
if (spl_is_float((spl_vm_kind_t)ins->type)) { \
double _da, _db, _dr; \
if (ins->type == SPL_F32) { \
float _fa, _fb; \
@@ -206,31 +207,31 @@ static int spl_type_size(spl_type_t t) {
} else { \
switch (ins->type) { \
case SPL_I8: \
_r = (spl_val_t)((int8_t)_a OP(int8_t) _b); \
_r = (spl_vm_val_t)((int8_t)_a OP(int8_t) _b); \
break; \
case SPL_U8: \
_r = (spl_val_t)((int8_t)_a OP(int8_t) _b); \
_r = (spl_vm_val_t)((int8_t)_a OP(int8_t) _b); \
break; \
case SPL_I16: \
_r = (spl_val_t)((int16_t)_a OP(int16_t) _b); \
_r = (spl_vm_val_t)((int16_t)_a OP(int16_t) _b); \
break; \
case SPL_U16: \
_r = (spl_val_t)((int16_t)_a OP(int16_t) _b); \
_r = (spl_vm_val_t)((int16_t)_a OP(int16_t) _b); \
break; \
case SPL_I32: \
_r = (spl_val_t)((int32_t)_a OP(int32_t) _b); \
_r = (spl_vm_val_t)((int32_t)_a OP(int32_t) _b); \
break; \
case SPL_U32: \
_r = (spl_val_t)((int32_t)_a OP(int32_t) _b); \
_r = (spl_vm_val_t)((int32_t)_a OP(int32_t) _b); \
break; \
case SPL_I64: \
_r = (spl_val_t)((int64_t)_a OP(int64_t) _b); \
_r = (spl_vm_val_t)((int64_t)_a OP(int64_t) _b); \
break; \
case SPL_U64: \
case SPL_PTR: \
case SPL_USIZE: \
case SPL_ISIZE: \
_r = (spl_val_t)((int64_t)_a OP(int64_t) _b); \
_r = (spl_vm_val_t)((int64_t)_a OP(int64_t) _b); \
break; \
default: \
VM_ERROR("bad type for signed division"); \
@@ -242,31 +243,31 @@ static int spl_type_size(spl_type_t t) {
/* unsigned division / remainder */
#define DIV_REM_U(OP) \
do { \
spl_val_t _b = POP(), _a = POP(); \
spl_vm_val_t _b = POP(), _a = POP(); \
if (_b == 0) \
VM_ERROR("division by zero"); \
spl_val_t _r = 0; \
spl_vm_val_t _r = 0; \
switch (ins->type) { \
case SPL_I8: \
_r = (spl_val_t)((uint8_t)_a OP(uint8_t) _b); \
_r = (spl_vm_val_t)((uint8_t)_a OP(uint8_t) _b); \
break; \
case SPL_U8: \
_r = (spl_val_t)((uint8_t)_a OP(uint8_t) _b); \
_r = (spl_vm_val_t)((uint8_t)_a OP(uint8_t) _b); \
break; \
case SPL_I16: \
_r = (spl_val_t)((uint16_t)_a OP(uint16_t) _b); \
_r = (spl_vm_val_t)((uint16_t)_a OP(uint16_t) _b); \
break; \
case SPL_U16: \
_r = (spl_val_t)((uint16_t)_a OP(uint16_t) _b); \
_r = (spl_vm_val_t)((uint16_t)_a OP(uint16_t) _b); \
break; \
case SPL_I32: \
_r = (spl_val_t)((uint32_t)_a OP(uint32_t) _b); \
_r = (spl_vm_val_t)((uint32_t)_a OP(uint32_t) _b); \
break; \
case SPL_U32: \
_r = (spl_val_t)((uint32_t)_a OP(uint32_t) _b); \
_r = (spl_vm_val_t)((uint32_t)_a OP(uint32_t) _b); \
break; \
case SPL_I64: \
_r = (spl_val_t)((uint64_t)_a OP(uint64_t) _b); \
_r = (spl_vm_val_t)((uint64_t)_a OP(uint64_t) _b); \
break; \
case SPL_U64: \
case SPL_PTR: \
@@ -280,10 +281,10 @@ static int spl_type_size(spl_type_t t) {
PUSH(_r); \
} while (0)
/* CMP_ALL equality comparisons (all types, floats via memcpy) */
/* CMP_ALL - equality comparisons (all types, floats via memcpy) */
#define CMP_ALL(OP) \
do { \
spl_val_t _b = POP(), _a = POP(); \
spl_vm_val_t _b = POP(), _a = POP(); \
intptr_t _r = 0; \
switch (ins->type) { \
case SPL_I8: \
@@ -334,10 +335,10 @@ static int spl_type_size(spl_type_t t) {
PUSH(_r); \
} while (0)
/* CMP_S signed ordering (all ints cast to signed, floats OK) */
/* CMP_S - signed ordering (all ints cast to signed, floats OK) */
#define CMP_S(OP) \
do { \
spl_val_t _b = POP(), _a = POP(); \
spl_vm_val_t _b = POP(), _a = POP(); \
intptr_t _r = 0; \
switch (ins->type) { \
case SPL_I8: \
@@ -388,10 +389,10 @@ static int spl_type_size(spl_type_t t) {
PUSH(_r); \
} while (0)
/* CMP_U unsigned ordering (all ints cast to unsigned, no float) */
/* CMP_U - unsigned ordering (all ints cast to unsigned, no float) */
#define CMP_U(OP) \
do { \
spl_val_t _b = POP(), _a = POP(); \
spl_vm_val_t _b = POP(), _a = POP(); \
intptr_t _r = 0; \
switch (ins->type) { \
case SPL_I8: \
@@ -428,6 +429,7 @@ static int spl_type_size(spl_type_t t) {
PUSH(_r); \
} while (0)
#ifdef _WIN32
// 辅助函数:将异常代码转为可读字符串
const char *ExceptionCodeToString(DWORD code) {
switch (code) {
@@ -536,12 +538,14 @@ LONG WINAPI UnhandledExceptionFilterImpl(EXCEPTION_POINTERS *pExceptionInfo) {
// 你可以在这里调用 exit(1) 或直接返回,进程会被终止
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
/* ================================================================
* spl_vm_init / spl_vm_drop
* ================================================================ */
void spl_vm_init_ex(spl_vm_t *vm, int stack_size, int call_depth) {
#ifdef _WIN32
SetErrorMode(SEM_FAILCRITICALERRORS);
SetUnhandledExceptionFilter(UnhandledExceptionFilterImpl);
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
@@ -595,7 +599,10 @@ void spl_vm_add_breakpoint_fn(spl_vm_t *vm, const char *name) {
for (usize i = 0; i < vec_size(vm->fn_breakpoints); i++)
if (strcmp(vm->fn_breakpoints.data[i], name) == 0)
return;
vec_push(vm->fn_breakpoints, strdup(name));
char *cpname = malloc(strlen(name) + 1);
Assert(cpname != NULL);
strcpy(cpname, name);
vec_push(vm->fn_breakpoints, cpname);
}
void spl_vm_clear_breakpoints(spl_vm_t *vm) {
@@ -613,10 +620,10 @@ void spl_vm_skip_breakpoint(spl_vm_t *vm) {
}
/* 前向声明(定义在文件尾部 dump 区域) */
static const char *func_name_by_ip(spl_prog_t *prog, spl_val_t ip);
static const char *func_name_by_ip(spl_prog_t *prog, spl_vm_val_t ip);
/* 函数名断点命中addr 所在函数名是否在断点表 */
static int fn_breakpoint_hit(spl_vm_t *vm, spl_val_t addr) {
static int fn_breakpoint_hit(spl_vm_t *vm, spl_vm_val_t addr) {
if (!vm || !vm->prog || !vec_size(vm->fn_breakpoints))
return 0;
const char *fn = func_name_by_ip(vm->prog, addr);
@@ -668,7 +675,7 @@ void spl_vm_set_debug(spl_vm_t *vm, int enabled) {
#define STACK_CANARY(vm) (vm)->stacks.data[(vm)->fp - 1]
static inline int spl_vm_call(spl_vm_t *vm, spl_val_t addr, spl_val_t nargs) {
static inline int spl_vm_call(spl_vm_t *vm, spl_vm_val_t addr, spl_vm_val_t nargs) {
if (vm->cp >= vm->config.max_call_depth)
VM_ERROR("CALLI: call stack overflow");
// spl_vm_stackdump(vm, vm->sp);
@@ -695,7 +702,7 @@ int spl_vm_prepare(spl_vm_t *vm, const char *entry, int argc, const char **argv,
if (!vm || !vm->prog) {
return -1;
}
spl_func_t *fn = spl_prog_get_func(vm->prog, entry ? entry : "main");
spl_vm_func_t *fn = spl_prog_get_func(vm->prog, entry ? entry : "main");
if (!fn) {
fprintf(stderr, "vm: entry point '%s' not found\n", entry ? entry : "main");
return -1;
@@ -726,13 +733,13 @@ int spl_vm_prepare(spl_vm_t *vm, const char *entry, int argc, const char **argv,
}
/* ================================================================
* spl_vm_run_once execute one instruction
* spl_vm_run_once - execute one instruction
*
* Returns: 0 = still running, 1 = halted, 2 = breakpoint (SPL_DBG), -1 = error
* ================================================================ */
int spl_vm_run_once(spl_vm_t *vm) {
const spl_ins_t *ins;
const spl_vm_ins_t *ins;
spl_prog_t *prog;
if (!vm || !vm->prog)
@@ -745,7 +752,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
return -1;
}
/* 断点:即将执行的指令命中 ip 断点 暂停(返回 2
/* 断点:即将执行的指令命中 ip 断点 -> 暂停(返回 2
* skip_bp 置位时执行当前指令continue 越过当前断点)。 */
if (ip_breakpoint_hit(vm)) {
if (vm->skip_bp) {
@@ -760,7 +767,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
if (vm->trace) {
fprintf(stderr, "vm: ip=%zd op=%s type=%s imm=%zu sp=%zd fp=%zd\n", vm->ip - 1,
spl_opcode_name(ins->opcode), spl_type_tag_name(ins->type), ins->imm, vm->sp,
spl_vm_opcode_name(ins->opcode), spl_vm_type_kind_name(ins->type), ins->imm, vm->sp,
vm->fp);
}
@@ -774,7 +781,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
case SPL_DUP: {
if (vm->sp < 1)
VM_ERROR("DUP: stack underflow");
spl_val_t _v = vm->stacks.data[vm->sp - 1];
spl_vm_val_t _v = vm->stacks.data[vm->sp - 1];
PUSH(_v);
break;
}
@@ -788,7 +795,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
case SPL_SWAP: {
if (vm->sp < 2)
VM_ERROR("SWAP: stack underflow");
spl_val_t _t = vm->stacks.data[vm->sp - 1];
spl_vm_val_t _t = vm->stacks.data[vm->sp - 1];
vm->stacks.data[vm->sp - 1] = vm->stacks.data[vm->sp - 2];
vm->stacks.data[vm->sp - 2] = _t;
break;
@@ -805,9 +812,9 @@ int spl_vm_run_once(spl_vm_t *vm) {
case SPL_ROT: {
if (vm->sp < 3)
VM_ERROR("ROT: stack underflow");
spl_val_t _a = vm->stacks.data[vm->sp - 3];
spl_val_t _b = vm->stacks.data[vm->sp - 2];
spl_val_t _c = vm->stacks.data[vm->sp - 1];
spl_vm_val_t _a = vm->stacks.data[vm->sp - 3];
spl_vm_val_t _b = vm->stacks.data[vm->sp - 2];
spl_vm_val_t _c = vm->stacks.data[vm->sp - 1];
vm->stacks.data[vm->sp - 3] = _b;
vm->stacks.data[vm->sp - 2] = _c;
vm->stacks.data[vm->sp - 1] = _a;
@@ -839,8 +846,8 @@ int spl_vm_run_once(spl_vm_t *vm) {
break;
case SPL_NEG: {
spl_val_t _a = POP();
if (spl_is_float((spl_type_t)ins->type)) {
spl_vm_val_t _a = POP();
if (spl_is_float((spl_vm_kind_t)ins->type)) {
double _d;
if (ins->type == SPL_F32) {
float _f;
@@ -861,17 +868,17 @@ int spl_vm_run_once(spl_vm_t *vm) {
/* ========== Bitwise ========== */
case SPL_AND: {
spl_val_t _b = POP(), _a = POP();
spl_vm_val_t _b = POP(), _a = POP();
PUSH(_a & _b);
break;
}
case SPL_OR: {
spl_val_t _b = POP(), _a = POP();
spl_vm_val_t _b = POP(), _a = POP();
PUSH(_a | _b);
break;
}
case SPL_XOR: {
spl_val_t _b = POP(), _a = POP();
spl_vm_val_t _b = POP(), _a = POP();
PUSH(_a ^ _b);
break;
}
@@ -945,8 +952,8 @@ int spl_vm_run_once(spl_vm_t *vm) {
}
case SPL_CALL: {
spl_val_t _nargs = ins->imm;
spl_val_t _addr = POP();
spl_vm_val_t _nargs = ins->imm;
spl_vm_val_t _addr = POP();
int _hit = fn_breakpoint_hit(vm, _addr);
spl_vm_call(vm, _addr, _nargs);
if (_hit)
@@ -955,8 +962,8 @@ int spl_vm_run_once(spl_vm_t *vm) {
}
case SPL_CALLI: {
spl_val_t _addr = POP();
spl_val_t _nargs = POP();
spl_vm_val_t _addr = POP();
spl_vm_val_t _nargs = POP();
int _hit = fn_breakpoint_hit(vm, _addr);
spl_vm_call(vm, _addr, _nargs);
if (_hit)
@@ -965,7 +972,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
}
case SPL_RET: {
spl_val_t _retval = 0;
spl_vm_val_t _retval = 0;
if (ins->type != SPL_VOID)
_retval = POP();
if (vm->cp <= 0)
@@ -995,7 +1002,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
/* ========== Stack / Frame Local Memory ========== */
case SPL_ALLOC: {
spl_val_t _k = ins->imm;
spl_vm_val_t _k = ins->imm;
uintptr_t _new_sp = vm->sp + _k;
if (_new_sp > vm->config.max_stack_depth)
VM_ERROR("ALLOC: stack overflow");
@@ -1006,14 +1013,14 @@ int spl_vm_run_once(spl_vm_t *vm) {
}
case SPL_LADDR:
PUSH((spl_val_t)((char *)(vm->stacks.data + vm->fp) + ins->imm));
PUSH((spl_vm_val_t)((char *)(vm->stacks.data + vm->fp) + ins->imm));
break;
case SPL_GADDR: {
spl_val_t _idx = ins->imm;
spl_vm_val_t _idx = ins->imm;
if (_idx >= vec_size(prog->gdata))
VM_ERROR("GADDR: global data index out of range");
PUSH((spl_val_t)(uintptr_t)vec_at(prog->gdata, _idx).data);
PUSH((spl_vm_val_t)(uintptr_t)vec_at(prog->gdata, _idx).data);
break;
}
@@ -1021,19 +1028,19 @@ int spl_vm_run_once(spl_vm_t *vm) {
case SPL_LOAD: {
void *_addr = (void *)POP();
CHECK_ADDR(_addr, "LOAD");
spl_val_t _v = 0;
spl_vm_val_t _v = 0;
usize _sz = spl_type_size(ins->type);
memcpy(&_v, _addr, _sz);
/* Sign-extend signed integer types smaller than 64 bits */
if (_sz > 0 && _sz < sizeof(spl_val_t) && spl_is_signed(ins->type)) {
usize _shift = (sizeof(spl_val_t) - _sz) * 8;
_v = (spl_val_t)(((isize)(_v << _shift)) >> _shift);
if (_sz > 0 && _sz < sizeof(spl_vm_val_t) && spl_is_signed(ins->type)) {
usize _shift = (sizeof(spl_vm_val_t) - _sz) * 8;
_v = (spl_vm_val_t)(((isize)(_v << _shift)) >> _shift);
}
PUSH(_v);
break;
}
case SPL_STORE: {
spl_val_t _v = POP();
spl_vm_val_t _v = POP();
void *_addr = (void *)POP();
CHECK_ADDR(_addr, "STORE");
memcpy(_addr, &_v, spl_type_size(ins->type));
@@ -1042,12 +1049,12 @@ int spl_vm_run_once(spl_vm_t *vm) {
/* ========== Type Conversion ========== */
case SPL_TRUNC: {
spl_val_t _v = POP();
spl_vm_val_t _v = POP();
intptr_t _bits = ins->imm;
if (_bits < 1 || _bits > 64)
VM_ERROR("TRUNC: bad bit-width");
if (_bits < 64) {
spl_val_t _mask = ((spl_val_t)1 << _bits) - 1;
spl_vm_val_t _mask = ((spl_vm_val_t)1 << _bits) - 1;
_v &= _mask;
}
PUSH(_v);
@@ -1055,13 +1062,13 @@ int spl_vm_run_once(spl_vm_t *vm) {
}
case SPL_SEXT: {
spl_val_t _v = POP();
spl_vm_val_t _v = POP();
intptr_t _bits = ins->imm;
if (_bits < 1 || _bits > 64)
VM_ERROR("SEXT: bad bit-width");
if (_bits < 64) {
spl_val_t _sign = (spl_val_t)1 << (_bits - 1);
spl_val_t _mask = ((spl_val_t)1 << _bits) - 1;
spl_vm_val_t _sign = (spl_vm_val_t)1 << (_bits - 1);
spl_vm_val_t _mask = ((spl_vm_val_t)1 << _bits) - 1;
_v &= _mask;
if (_v & _sign)
_v |= ~_mask;
@@ -1071,12 +1078,12 @@ int spl_vm_run_once(spl_vm_t *vm) {
}
case SPL_ZEXT: {
spl_val_t _v = POP();
spl_vm_val_t _v = POP();
intptr_t _bits = ins->imm;
if (_bits < 1 || _bits > 64)
VM_ERROR("ZEXT: bad bit-width");
if (_bits < 64)
_v &= ((spl_val_t)1 << _bits) - 1;
_v &= ((spl_vm_val_t)1 << _bits) - 1;
PUSH(_v);
break;
}
@@ -1084,8 +1091,8 @@ int spl_vm_run_once(spl_vm_t *vm) {
/* ========== Native Interface ========== */
case SPL_NCALL: {
intptr_t _nargs = ins->imm;
spl_val_t _nat_idx = POP();
spl_native_t *_nat;
spl_vm_val_t _nat_idx = POP();
spl_vm_native_t *_nat;
if (_nat_idx >= vec_size(prog->natives))
VM_ERROR("NCALL: native index out of range");
_nat = &vec_at(prog->natives, _nat_idx);
@@ -1094,18 +1101,18 @@ int spl_vm_run_once(spl_vm_t *vm) {
"NCALL: NULL native function pointer expect %s", _nat->name);
VM_ERROR(vm->error_msg);
}
spl_val_t *_arg_base = vm->stacks.data + vm->sp - _nargs;
spl_vm_val_t *_arg_base = vm->stacks.data + vm->sp - _nargs;
// spl_vm_stackdump(vm, vm->sp);
// printf("addr %p nargs %zd sp %zd stack %p arg_base %p\n", _nat->impl_fn, _nargs, vm->sp,
// vm->stacks.data, _arg_base);
spl_val_t _result = _nat->impl_fn(_nargs, _arg_base);
spl_vm_val_t _result = _nat->impl_fn(_nargs, _arg_base);
vm->sp -= _nargs;
PUSH(_result);
break;
}
case SPL_NLIB: {
spl_val_t _si = ins->imm;
spl_vm_val_t _si = ins->imm;
const char *_lib;
if (_si >= vec_size(prog->strtab) || !vec_at(prog->strtab, _si))
VM_ERROR("NLIB: invalid string index");
@@ -1174,44 +1181,44 @@ int spl_vm_run_until(spl_vm_t *vm, size_t step) {
}
}
static const char *func_name_by_ip(spl_prog_t *prog, spl_val_t ip) {
static const char *func_name_by_ip(spl_prog_t *prog, spl_vm_val_t ip) {
vec_for(prog->funcs, i) {
spl_func_t *f = &vec_at(prog->funcs, i);
spl_vm_func_t *f = &vec_at(prog->funcs, i);
if (ip >= f->address && ip < (f->address + f->ninsns))
return f->name;
}
return "?";
}
void spl_vm_dump_instr(spl_vm_t *vm, spl_val_t ip) {
void spl_vm_dump_instr(spl_vm_t *vm, spl_vm_val_t ip) {
if (!vm || !vm->prog)
return;
if (ip >= vec_size(vm->prog->insns))
return;
spl_ins_t *ins = &vec_at(vm->prog->insns, ip);
fprintf(stderr, " instr at ip=%zd: op=%s type=%s imm=%zu\n", ip, spl_opcode_name(ins->opcode),
spl_type_tag_name(ins->type), ins->imm);
spl_vm_ins_t *ins = &vec_at(vm->prog->insns, ip);
fprintf(stderr, " instr at ip=%zd: op=%s type=%s imm=%zu\n", ip,
spl_vm_opcode_name(ins->opcode), spl_vm_type_kind_name(ins->type), ins->imm);
}
void spl_vm_stackdump(spl_vm_t *vm, spl_val_t sp) {
void spl_vm_stackdump(spl_vm_t *vm, spl_vm_val_t sp) {
if (!vm)
return;
fprintf(stderr, "stack dump (sp=%zd, fp=%zd):\n", sp, vm->fp);
spl_val_t start = sp > 32 ? sp - 32 : 0;
for (spl_val_t i = start; i <= sp; i++) {
spl_vm_val_t start = sp > 32 ? sp - 32 : 0;
for (spl_vm_val_t i = start; i <= sp; i++) {
fprintf(stderr, " [%3zd] = [addr 0x%p] 0x%016zx (%zd)\n", i, &vm->stacks.data[i],
vm->stacks.data[i], vm->stacks.data[i]);
}
}
int spl_vm_backtrace(spl_vm_t *vm, spl_val_t fp) {
int spl_vm_backtrace(spl_vm_t *vm, spl_vm_val_t fp) {
if (!vm || !vm->prog)
return -1;
(void)fp;
fprintf(stderr, "backtrace: \n");
for (isize i = vm->cp - 1; i >= 0; i--) {
spl_val_t _saved_ip = vm->frames.data[i].saved_ip;
spl_val_t _saved_fp = vm->frames.data[i].saved_fp;
spl_vm_val_t _saved_ip = vm->frames.data[i].saved_ip;
spl_vm_val_t _saved_fp = vm->frames.data[i].saved_fp;
const char *_fn = func_name_by_ip(vm->prog, _saved_ip - 1);
fprintf(stderr, " [%3zd] %s (fp=%zd, ip=%zd, args=%zd)\n", i, _fn, _saved_fp, _saved_ip,
vm->frames.data[i].nargs);

View File

@@ -1,4 +1,4 @@
/* spl_vm.h SIR interpreter */
/* spl_vm.h - SIR interpreter */
#ifndef __SPL_VM_H__
#define __SPL_VM_H__
@@ -7,16 +7,16 @@
#include "spl_mcode.h"
#include <stdint.h>
#define SPL_STACK_CANARY ((spl_val_t)0xDEADBEEFCAFEBABEull)
#define SPL_STACK_CANARY ((spl_vm_val_t)0xDEADBEEFCAFEBABEull)
typedef struct {
uintptr_t saved_sp;
uintptr_t saved_fp;
uintptr_t saved_ip;
spl_val_t nargs;
spl_vm_val_t nargs;
} spl_callframe_t;
typedef VEC(spl_val_t) spl_stack_vec_t;
typedef VEC(spl_vm_val_t) spl_stack_vec_t;
typedef VEC(spl_callframe_t) spl_frame_vec_t;
typedef struct {
@@ -71,8 +71,8 @@ void spl_vm_clear_breakpoints(spl_vm_t *vm);
/* 让 run_once 执行当前指令忽略一次断点命中continue 越过当前断点用 */
void spl_vm_skip_breakpoint(spl_vm_t *vm);
void spl_vm_dump_instr(spl_vm_t *vm, spl_val_t ip);
void spl_vm_stackdump(spl_vm_t *vm, spl_val_t sp);
int spl_vm_backtrace(spl_vm_t *vm, spl_val_t fp);
void spl_vm_dump_instr(spl_vm_t *vm, spl_vm_val_t ip);
void spl_vm_stackdump(spl_vm_t *vm, spl_vm_val_t sp);
int spl_vm_backtrace(spl_vm_t *vm, spl_vm_val_t fp);
#endif /* __SPL_VM_H__ */

View File

@@ -20,7 +20,7 @@
#define LE64(p, v) \
do { \
unsigned char *_p = (p); \
spl_val_t _v = (spl_val_t)(v); \
spl_vm_val_t _v = (spl_vm_val_t)(v); \
*_p++ = (unsigned char)(_v); \
*_p++ = (unsigned char)(_v >> 8); \
*_p++ = (unsigned char)(_v >> 16); \
@@ -33,8 +33,8 @@
} while (0)
/* Convenience: build spl_ins_t from raw fields */
static spl_ins_t ins(uint16_t op, uint16_t type, spl_val_t imm) {
spl_ins_t x;
static spl_vm_ins_t ins(uint16_t op, uint16_t type, spl_vm_val_t imm) {
spl_vm_ins_t x;
x.opcode = op;
x.type = type;
x.imm = imm;
@@ -43,8 +43,8 @@ static spl_ins_t ins(uint16_t op, uint16_t type, spl_val_t imm) {
/* Build a single-function SIR binary in malloc'd memory.
* Returns buffer that must be freed by caller. */
static unsigned char *build_binary(const char *fname, spl_val_t nargs, const spl_ins_t *instns,
int ninsns, size_t *out_len) {
static unsigned char *build_binary(const char *fname, spl_vm_val_t nargs,
const spl_vm_ins_t *instns, int ninsns, size_t *out_len) {
size_t nlen = strlen(fname) + 1;
size_t npad = ((nlen + 7) / 8) * 8 - nlen;
size_t sz = 8 + 8 + 8 + 8 + 8 + 8 /* magic + 5 counts */
@@ -56,20 +56,20 @@ static unsigned char *build_binary(const char *fname, spl_val_t nargs, const spl
memcpy(p, "SPLBIN\0\0", 8);
p += 8; /* magic */
LE64(p, 1); /* nfuncs */
LE64(p, (spl_val_t)ninsns); /* ninsns */
LE64(p, (spl_vm_val_t)ninsns); /* ninsns */
LE64(p, 0); /* nnatives */
LE64(p, 0); /* nstrs */
LE64(p, 0); /* ndata */
/* func entry */
LE64(p, (spl_val_t)nlen); /* name_len */
LE64(p, (spl_vm_val_t)nlen); /* name_len */
memcpy(p, fname, nlen);
p += nlen;
memset(p, 0, npad);
p += npad;
LE64(p, 0); /* idx_of_strtab */
LE64(p, nargs);
LE64(p, (spl_val_t)ninsns);
LE64(p, (spl_vm_val_t)ninsns);
LE64(p, 0); /* address = 0 */
for (int i = 0; i < ninsns; i++) {
@@ -101,7 +101,7 @@ static int write_temp(const unsigned char *bin, size_t len) {
}
/* Run a single-function program, return exit code (or -1 on failure). */
static int run(const spl_ins_t *instns, int ninsns) {
static int run(const spl_vm_ins_t *instns, int ninsns) {
size_t len;
unsigned char *bin = build_binary("main", 0, instns, ninsns, &len);
spl_prog_t prog;
@@ -127,7 +127,7 @@ static int run(const spl_ins_t *instns, int ninsns) {
}
/* Run with native functions registered. */
static int run_with_natives(const spl_ins_t *instns, int ninsns, spl_native_t *natives,
static int run_with_natives(const spl_vm_ins_t *instns, int ninsns, spl_vm_native_t *natives,
int nnatives) {
size_t len;
unsigned char *bin = build_binary("main", 0, instns, ninsns, &len);
@@ -159,7 +159,7 @@ static int run_with_natives(const spl_ins_t *instns, int ninsns, spl_native_t *n
* Native function for NCALL tests
* ================================================================ */
static spl_val_t native_add_impl(int nargs, spl_val_t *args) {
static spl_vm_val_t native_add_impl(int nargs, spl_vm_val_t *args) {
return (nargs >= 2) ? args[0] + args[1] : 0;
}
@@ -168,24 +168,24 @@ static spl_val_t native_add_impl(int nargs, spl_val_t *args) {
* ================================================================ */
void test_push_imm(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_RET, SPL_I32, 0)};
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 2) == 42);
}
void test_dup(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 99), ins(SPL_DUP, SPL_VOID, 0),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 99), ins(SPL_DUP, SPL_VOID, 0),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 198);
}
void test_drop(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
ins(SPL_DROP, SPL_VOID, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_swap(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
ins(SPL_SWAP, SPL_VOID, 0), ins(SPL_DROP, SPL_VOID, 0),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 5) == 2);
@@ -193,7 +193,7 @@ void test_swap(void) {
void test_pick(void) {
/* push 10, 20, 30, pick 1 -> copy 20, add -> 50 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_PUSH, SPL_I32, 30), ins(SPL_PICK, SPL_VOID, 1),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 6) == 50);
@@ -204,43 +204,43 @@ void test_pick(void) {
* ================================================================ */
void test_add(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 2), ins(SPL_PUSH, SPL_I32, 3), ins(SPL_ADD, SPL_I32, 0),
ins(SPL_RET, SPL_I32, 0)};
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 2), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 5);
}
void test_sub(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 3),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_SUB, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 7);
}
void test_mul(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 6), ins(SPL_PUSH, SPL_I32, 7), ins(SPL_MUL, SPL_I32, 0),
ins(SPL_RET, SPL_I32, 0)};
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 6), ins(SPL_PUSH, SPL_I32, 7),
ins(SPL_MUL, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 42);
}
void test_div(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 100), ins(SPL_PUSH, SPL_I32, 3),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 100), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_DIV_S, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 33);
}
void test_rem(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 100), ins(SPL_PUSH, SPL_I32, 3),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 100), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_REM_S, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_neg(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_NEG, SPL_I32, 0),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_NEG, SPL_I32, 0),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 3) == -42);
}
void test_i64_arith(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I64, 42), ins(SPL_RET, SPL_I64, 0)};
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I64, 42), ins(SPL_RET, SPL_I64, 0)};
TEST_CHECK(run(p, 2) == 42);
}
@@ -249,45 +249,46 @@ void test_i64_arith(void) {
* ================================================================ */
void test_and(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFF00), ins(SPL_PUSH, SPL_U32, 0x0FF0),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFF00), ins(SPL_PUSH, SPL_U32, 0x0FF0),
ins(SPL_AND, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0x0F00);
}
void test_or(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFF00), ins(SPL_PUSH, SPL_U32, 0x00FF),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFF00), ins(SPL_PUSH, SPL_U32, 0x00FF),
ins(SPL_OR, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0xFFFF);
}
void test_xor(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF), ins(SPL_PUSH, SPL_U32, 0x0FF0),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF), ins(SPL_PUSH, SPL_U32, 0x0FF0),
ins(SPL_XOR, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0xF00F);
}
void test_not(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF0000), ins(SPL_NOT, SPL_U32, 0),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF0000), ins(SPL_NOT, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 3) == (unsigned int)0x0000FFFF);
}
void test_shl(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 1), ins(SPL_PUSH, SPL_U32, 10),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 1), ins(SPL_PUSH, SPL_U32, 10),
ins(SPL_SHL, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1024);
}
void test_shr(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 1024), ins(SPL_PUSH, SPL_U32, 10),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 1024), ins(SPL_PUSH, SPL_U32, 10),
ins(SPL_SHR_U, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_shr_s(void) {
/* arithmetic right shift: -1024 >> 5 sign-extends */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, (spl_val_t)(int32_t)-1024), ins(SPL_PUSH, SPL_U32, 5),
ins(SPL_SHR_S, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, (spl_vm_val_t)(int32_t)-1024),
ins(SPL_PUSH, SPL_U32, 5), ins(SPL_SHR_S, SPL_I32, 0),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == -32);
}
@@ -296,68 +297,68 @@ void test_shr_s(void) {
* ================================================================ */
void test_eq(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_PUSH, SPL_I32, 42),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_PUSH, SPL_I32, 42),
ins(SPL_EQ, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_neq(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_PUSH, SPL_I32, 99),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_PUSH, SPL_I32, 99),
ins(SPL_NE, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_lt(void) {
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_SLT, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_gt_signed(void) {
/* -1 > 1 should be 0 (false) for signed compare */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
ins(SPL_SGT, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 0);
}
void test_sle(void) {
/* -1 <= 1 -> true (1) for signed */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
ins(SPL_SLE, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_sge(void) {
/* -1 >= 1 -> false (0) for signed */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
ins(SPL_SGE, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 0);
}
void test_ult(void) {
/* 0xFFFFFFFF < 1 -> false (0) for unsigned */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
ins(SPL_ULT, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0);
}
void test_ule(void) {
/* 0xFFFFFFFF <= 0xFFFFFFFF -> true (1) */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF),
ins(SPL_ULE, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_ugt(void) {
/* 0xFFFFFFFF > 1 -> true (1) for unsigned */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
ins(SPL_UGT, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_uge(void) {
/* 0xFFFFFFFF >= 1 -> true (1) */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
ins(SPL_UGE, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
@@ -369,7 +370,7 @@ void test_uge(void) {
void test_jmp(void) {
/* push 1, jmp +3 (skip next 2 insns), push 2 (skipped), push 3, add, ret -> 4 */
/* jmp at ip=1, after fetch ip=2, target ip=3 (push 3) => offset = 1 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_JMP, SPL_VOID, 1),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_JMP, SPL_VOID, 1),
ins(SPL_PUSH, SPL_I32, 2), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 6) == 4);
@@ -377,13 +378,13 @@ void test_jmp(void) {
void test_bz_bnz(void) {
/* push 0, bz +2 (skip to ret with 1) -> return 1 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0), ins(SPL_BZ, SPL_VOID, 2),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0), ins(SPL_BZ, SPL_VOID, 2),
ins(SPL_PUSH, SPL_I32, 99), ins(SPL_RET, SPL_I32, 0),
ins(SPL_PUSH, SPL_I32, 1), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 6) == 1);
/* push 1, bnz +2 (skip to ret with 42) -> return 42 */
spl_ins_t q[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_BNZ, SPL_VOID, 2),
spl_vm_ins_t q[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_BNZ, SPL_VOID, 2),
ins(SPL_PUSH, SPL_I32, 99), ins(SPL_RET, SPL_I32, 0),
ins(SPL_PUSH, SPL_I32, 42), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(q, 6) == 42);
@@ -395,7 +396,7 @@ void test_bz_bnz(void) {
void test_alloc_laddr_st64_ld64(void) {
/* alloc 1 local, laddr + st64 42, laddr + ld64 back -> 42 */
spl_ins_t p[] = {
spl_vm_ins_t p[] = {
ins(SPL_ALLOC, SPL_VOID, 1), /* 0: alloc 1 local */
ins(SPL_LADDR, SPL_VOID, 0), /* 1: addr of local[0] */
ins(SPL_PUSH, SPL_I64, 42), /* 2: value */
@@ -409,7 +410,7 @@ void test_alloc_laddr_st64_ld64(void) {
void test_alloc_zeroed(void) {
/* alloc 1 local, laddr + ld64 -> should be 0 (zero-initialized) */
spl_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 1), ins(SPL_LADDR, SPL_VOID, 0),
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 1), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_LOAD, SPL_I64, 0), ins(SPL_RET, SPL_I64, 0)};
TEST_CHECK(run(p, 4) == 0);
}
@@ -420,7 +421,7 @@ void test_alloc_zeroed(void) {
void test_ld_st64(void) {
/* alloc 8 slots, st64 42, ld64 back -> 42 */
spl_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 42),
ins(SPL_STORE, SPL_I64, 0), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_RET, SPL_I64, 0)};
@@ -428,7 +429,7 @@ void test_ld_st64(void) {
}
void test_ld_st32(void) {
spl_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 0xAABBCCDD),
ins(SPL_STORE, SPL_U32, 0), ins(SPL_LOAD, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
@@ -436,7 +437,7 @@ void test_ld_st32(void) {
}
void test_ld_st16(void) {
spl_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 0xBEEF),
ins(SPL_STORE, SPL_U16, 0), ins(SPL_LOAD, SPL_U16, 0),
ins(SPL_RET, SPL_U16, 0)};
@@ -444,7 +445,7 @@ void test_ld_st16(void) {
}
void test_ld_st8(void) {
spl_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 0xAB),
ins(SPL_STORE, SPL_U8, 0), ins(SPL_LOAD, SPL_U8, 0),
ins(SPL_RET, SPL_U8, 0)};
@@ -475,10 +476,10 @@ void test_call_add(void) {
* call 2 ip=9 nargs=2
* ret i64 ip=10
*/
spl_ins_t add_insns[] = {ins(SPL_LADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_I64, 0),
spl_vm_ins_t add_insns[] = {ins(SPL_LADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_LADDR, SPL_VOID, 8), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_ADD, SPL_I64, 0), ins(SPL_RET, SPL_I64, 0)};
spl_ins_t main_insns[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
spl_vm_ins_t main_insns[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_PUSH, SPL_VOID, 0), ins(SPL_CALL, SPL_VOID, 2),
ins(SPL_RET, SPL_I64, 0)};
@@ -499,32 +500,32 @@ void test_call_add(void) {
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
LE64(p, 2);
LE64(p, (spl_val_t)ninsns_t);
LE64(p, (spl_vm_val_t)ninsns_t);
LE64(p, 0);
LE64(p, 0);
LE64(p, 0);
/* func[0]: "add" */
LE64(p, (spl_val_t)nlen0);
LE64(p, (spl_vm_val_t)nlen0);
memcpy(p, "add", nlen0);
p += nlen0;
memset(p, 0, npad0);
p += npad0;
LE64(p, 0);
LE64(p, 2);
LE64(p, (spl_val_t)nadd);
LE64(p, (spl_vm_val_t)nadd);
LE64(p, 0);
/* func[1]: "main" */
LE64(p, (spl_val_t)nlen1);
LE64(p, (spl_vm_val_t)nlen1);
memcpy(p, "main", nlen1);
p += nlen1;
memset(p, 0, npad1);
p += npad1;
LE64(p, 0);
LE64(p, 0);
LE64(p, (spl_val_t)nmain);
LE64(p, (spl_val_t)nadd); /* address */
LE64(p, (spl_vm_val_t)nmain);
LE64(p, (spl_vm_val_t)nadd); /* address */
for (int i = 0; i < nadd; i++) {
*p++ = (unsigned char)(add_insns[i].opcode);
@@ -582,10 +583,10 @@ void test_calli(void) {
* calli ip=10
* ret i64 ip=11
*/
spl_ins_t add_insns[] = {ins(SPL_LADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_I64, 0),
spl_vm_ins_t add_insns[] = {ins(SPL_LADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_LADDR, SPL_VOID, 8), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_ADD, SPL_I64, 0), ins(SPL_RET, SPL_I64, 0)};
spl_ins_t main_insns[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
spl_vm_ins_t main_insns[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_PUSH, SPL_VOID, 2), ins(SPL_PUSH, SPL_VOID, 0),
ins(SPL_CALLI, SPL_VOID, 0), ins(SPL_RET, SPL_I64, 0)};
@@ -602,13 +603,13 @@ void test_calli(void) {
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
LE64(p, 2);
LE64(p, (spl_val_t)ninsns_t);
LE64(p, (spl_vm_val_t)ninsns_t);
LE64(p, 0);
LE64(p, 0);
LE64(p, 0);
/* func[0]: add */
LE64(p, (spl_val_t)nlen0);
LE64(p, (spl_vm_val_t)nlen0);
memcpy(p, "add", nlen0);
p += nlen0;
memset(p, 0, npad0);
@@ -619,7 +620,7 @@ void test_calli(void) {
LE64(p, 0);
/* func[1]: main */
LE64(p, (spl_val_t)nlen1);
LE64(p, (spl_vm_val_t)nlen1);
memcpy(p, "main", nlen1);
p += nlen1;
memset(p, 0, npad1);
@@ -669,7 +670,7 @@ void test_calli(void) {
void test_gaddr_ld32(void) {
/* Load program, add global data, GADDR + LD32 to read it back */
spl_ins_t p[] = {ins(SPL_GADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_U32, 0),
spl_vm_ins_t p[] = {ins(SPL_GADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
size_t len;
unsigned char *bin = build_binary("main", 0, p, 3, &len);
@@ -697,7 +698,7 @@ void test_gaddr_ld32(void) {
void test_gaddr_multi(void) {
/* Two global data entries: read second one via GADDR 1 */
spl_ins_t p[] = {ins(SPL_GADDR, SPL_VOID, 1), ins(SPL_LOAD, SPL_U32, 0),
spl_vm_ins_t p[] = {ins(SPL_GADDR, SPL_VOID, 1), ins(SPL_LOAD, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
size_t len;
unsigned char *bin = build_binary("main", 0, p, 3, &len);
@@ -731,10 +732,10 @@ void test_gaddr_multi(void) {
void test_ncall(void) {
/* main() -> i32 { return native_add(30, 12); } */
/* NCALL imm = nargs, native index is pushed separately */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 30), ins(SPL_PUSH, SPL_I32, 12),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 30), ins(SPL_PUSH, SPL_I32, 12),
ins(SPL_PUSH, SPL_VOID, 0), ins(SPL_NCALL, SPL_I32, 2),
ins(SPL_RET, SPL_I32, 0)};
spl_native_t nat[] = {{"native_add", 0, native_add_impl}};
spl_vm_native_t nat[] = {{"native_add", 0, native_add_impl}};
TEST_CHECK(run_with_natives(p, 5, nat, 1) == 42);
}
@@ -744,21 +745,21 @@ void test_ncall(void) {
void test_trunc(void) {
/* push 0xABCD, trunc to 8 bits -> 0xCD */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xABCD), ins(SPL_TRUNC, SPL_U8, 8),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xABCD), ins(SPL_TRUNC, SPL_U8, 8),
ins(SPL_RET, SPL_U8, 0)};
TEST_CHECK(run(p, 3) == 0xCD);
}
void test_sext(void) {
/* push 0x80, sext from 8 bits -> 0xFFFFFF80 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0x80), ins(SPL_SEXT, SPL_I32, 8),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0x80), ins(SPL_SEXT, SPL_I32, 8),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 3) == (int)(int8_t)(0x80));
}
void test_zext(void) {
/* push 0xFFFF, zext from 8 bits -> 0xFF */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF), ins(SPL_ZEXT, SPL_U32, 8),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF), ins(SPL_ZEXT, SPL_U32, 8),
ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 3) == 0xFF);
}
@@ -769,14 +770,14 @@ void test_zext(void) {
void test_div_u(void) {
/* unsigned: 100 / 3 = 33 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 100), ins(SPL_PUSH, SPL_U32, 3),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 100), ins(SPL_PUSH, SPL_U32, 3),
ins(SPL_DIV_U, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 33);
}
void test_rem_u(void) {
/* unsigned: 100 % 3 = 1 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 100), ins(SPL_PUSH, SPL_U32, 3),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 100), ins(SPL_PUSH, SPL_U32, 3),
ins(SPL_REM_U, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
@@ -787,15 +788,16 @@ void test_rem_u(void) {
void test_many_ops(void) {
/* (1+2) * (3+4) = 21 */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2), ins(SPL_ADD, SPL_I32, 0),
ins(SPL_PUSH, SPL_I32, 3), ins(SPL_PUSH, SPL_I32, 4), ins(SPL_ADD, SPL_I32, 0),
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_PUSH, SPL_I32, 4), ins(SPL_ADD, SPL_I32, 0),
ins(SPL_MUL, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 8) == 21);
}
void test_halt(void) {
/* push 77, halt -> exit code 0 (HALT doesn't pop) */
spl_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 77), ins(SPL_HALT, SPL_VOID, 0)};
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 77), ins(SPL_HALT, SPL_VOID, 0)};
TEST_CHECK(run(p, 2) == 0);
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,31 +2,134 @@
#define __SPL_AST_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_lexer.h"
#include "spl_tok.h"
typedef enum {
SPL_AST_CONTAINER_ITEM,
SPL_AST_FN_DECL,
SPL_AST_FN_DEFINE,
SPL_AST_TYPE_DECL,
SPL_AST_VAR_DECL,
SPL_AST_CONST_DECL,
SPL_AST_MEMBER_DECL,
SPL_AST__COMPTIME_STMT, /*不实现*/
SPL_AST__DIRECTIVE_BLOCK, /*不实现*/
/* clang-format off */
#define SPL_AST_KIND_TABLE \
X(SPL_AST_NONE, V0, none) \
X(SPL_AST_CONTAINER_MEMBERS, V0, container_members) \
X(SPL_AST_FN_DECL, V0, fn_decl) \
X(SPL_AST_FN_DEFINE, V0, fn_define) \
X(SPL_AST_TYPE_DECL, V0, type_decl) \
X(SPL_AST_VAR_DECL, V0, var_decl) \
X(SPL_AST_CONST_DECL, V0, const_decl) \
X(SPL_AST_MEMBER_DECL, V0, member_decl) \
X(SPL_AST__COMPTIME_STMT, V0, comptime_stmt) \
X(SPL_AST__DIRECTIVE_BLOCK, V0, directive_block) \
X(SPL_AST_PARAM_DECL, V0, param_decl) \
X(SPL_AST_ATTR_ITEM, V0, attr_item) \
X(SPL_AST_ARGG_INIT_ITEM, V0, argg_init_item) \
X(SPL_AST_IF_STATEMENT, V0, if_statement) \
X(SPL_AST_IFVAR_STATEMENT, V0, ifvar_statement) \
X(SPL_AST_WHILE_STATEMENT, V0, while_statement) \
X(SPL_AST_LOOP_STATEMENT, V0, loop_statement) \
X(SPL_AST_FOR_STATEMENT, V0, for_statement) \
X(SPL_AST_MATCH_STATEMENT, V0, match_statement) \
X(SPL_AST_RET_STATEMENT, V0, ret_statement) \
X(SPL_AST_BREAK_STATEMENT, V0, break_statement) \
X(SPL_AST_CONTINUE_STATEMENT, V0, continue_statement) \
X(SPL_AST_DEFER_STATEMENT, V0, defer_statement) \
X(SPL_AST_TRY_STATEMENT, V0, try_statement) \
X(SPL_AST_CATCH_STATEMENT, V0, catch_statement) \
X(SPL_AST_ERRDEFER_STATEMEMT, V0, errdefer_statement) \
X(SPL_AST_EXPR_STATEMENT, V0, expr_statement) \
X(SPL_AST_PACKED_EXPR, V0, packed_expr) \
X(SPL_AST_ASSIGN_EXPR, V0, assign_expr) \
X(SPL_AST_ASSIGN_ADD_EXPR, V0, assign_add_expr) \
X(SPL_AST_ASSIGN_SUB_EXPR, V0, assign_sub_expr) \
X(SPL_AST_ASSIGN_MUL_EXPR, V0, assign_mul_expr) \
X(SPL_AST_ASSIGN_DIV_EXPR, V0, assign_div_expr) \
X(SPL_AST_ASSIGN_MOD_EXPR, V0, assign_mod_expr) \
X(SPL_AST_ASSIGN_AND_EXPR, V0, assign_and_expr) \
X(SPL_AST_ASSIGN_OR_EXPR, V0, assign_or_expr) \
X(SPL_AST_ASSIGN_XOR_EXPR, V0, assign_xor_expr) \
X(SPL_AST_ASSIGN_LSHIFT_EXPR, V0, assign_lshift_expr) \
X(SPL_AST_ASSIGN_USHIFT_EXPR, V0, assign_ushift_expr) \
X(SPL_AST_BOOL_OR_EXPR, V0, bool_or_expr) \
X(SPL_AST_BOOL_AND_EXPR, V0, bool_and_expr) \
X(SPL_AST_BIT_OR_EXPR, V0, bit_or_expr) \
X(SPL_AST_BIT_XOR_EXPR, V0, bit_xor_expr) \
X(SPL_AST_BIT_AND_EXPR, V0, bit_and_expr) \
X(SPL_AST_CMP_EQ_EXPR, V0, cmp_eq_expr) \
X(SPL_AST_CMP_NE_EXPR, V0, cmp_ne_expr) \
X(SPL_AST_CMP_LE_EXPR, V0, cmp_le_expr) \
X(SPL_AST_CMP_GE_EXPR, V0, cmp_ge_expr) \
X(SPL_AST_CMP_LT_EXPR, V0, cmp_lt_expr) \
X(SPL_AST_CMP_GT_EXPR, V0, cmp_gt_expr) \
X(SPL_AST_RANGE_EXPR, V0, range_expr) \
X(SPL_AST_LSHIFT_EXPR, V0, lshift_expr) \
X(SPL_AST_RSHIFT_EXPR, V0, rshift_expr) \
X(SPL_AST_ADD_EXPR, V0, add_expr) \
X(SPL_AST_SUB_EXPR, V0, sub_expr) \
X(SPL_AST_MUL_EXPR, V0, mul_expr) \
X(SPL_AST_DIV_EXPR, V0, div_expr) \
X(SPL_AST_MOD_EXPR, V0, mod_expr) \
X(SPL_AST_MINUS_EXPR, V0, minus_expr) \
X(SPL_AST_NOT_EXPR, V0, not_expr) \
X(SPL_AST_BIT_NOT_EXPR, V0, bit_not_expr) \
X(SPL_AST_ADDRESS_EXPR, V0, address_expr) \
X(SPL_AST_CALL_EXPR, V0, call_expr) \
X(SPL_AST_FIELD_EXPR, V0, field_expr) \
X(SPL_AST_DEREF_EXPR, V0, deref_expr) \
X(SPL_AST_INDEX_EXPR, V0, index_expr) \
X(SPL_AST_SLICE_EXPR, V0, slice_expr) \
X(SPL_AST_AS_EXPR, V0, as_expr) \
X(SPL_AST_EXPR_INTEGER_LIT, V0, integer_lit) \
X(SPL_AST_EXPR_FLOAT_LIT, V0, float_lit) \
X(SPL_AST_EXPR_CHAR_LIT, V0, char_lit) \
X(SPL_AST_EXPR_STRING_LIT, V0, string_lit) \
X(SPL_AST_EXPR_TRUE, V0, true_lit) \
X(SPL_AST_EXPR_FALSE, V0, false_lit) \
X(SPL_AST_EXPR_NULL, V0, null_lit) \
X(SPL_AST_EXPR_UNDEFINED, V0, undefined_lit) \
X(SPL_AST_EXPR_IDENT, V0, ident_expr) \
X(SPL_AST_ARGGREGATE_INIT, V0, aggregate_init) \
X(SPL_AST_EXPR_EXPR, V0, expr_expr) \
X(SPL_AST_ARRAY_LIT, V0, array_lit) \
X(SPL_AST_BUILTIN_EXPR, V0, builtin_expr) \
X(SPL_AST_BLOCK_EXPR, V0, block_expr) \
X(SPL_AST_BASE_TYPE_FN, V0, base_type_fn) \
X(SPL_AST_BASE_TYPE_PATH, V0, base_type_path) \
X(SPL_AST_TYPE_POINTER, V0, type_pointer) \
X(SPL_AST_TYPE_ARRAY, V0, type_array) \
X(SPL_AST_TYPE_SLICE, V0, type_slice) \
X(SPL_AST_TYPE_STRUCT, V0, type_struct) \
X(SPL_AST_TYPE_UNION, V0, type_union) \
X(SPL_AST_TYPE_SHAPE, V0, type_shape) \
X(SPL_AST_TYPE_ENUM, V0, type_enum) \
X(SPL_AST_TYPE_VOID, V0, type_void) \
X(SPL_AST_TYPE_BOOL, V0, type_bool) \
X(SPL_AST_TYPE_OPAQUE, V0, type_opaque) \
X(SPL_AST_TYPE_I8, V0, type_i8) \
X(SPL_AST_TYPE_U8, V0, type_u8) \
X(SPL_AST_TYPE_I16, V0, type_i16) \
X(SPL_AST_TYPE_U16, V0, type_u16) \
X(SPL_AST_TYPE_I32, V0, type_i32) \
X(SPL_AST_TYPE_U32, V0, type_u32) \
X(SPL_AST_TYPE_I64, V0, type_i64) \
X(SPL_AST_TYPE_U64, V0, type_u64) \
X(SPL_AST_TYPE_ISIZE, V0, type_isize) \
X(SPL_AST_TYPE_USIZE, V0, type_usize) \
X(SPL_AST_TYPE__F32, V0, type_f32) \
X(SPL_AST_TYPE__F64, V0, type_f64) \
X(SPL_AST_TYPE_ANY, V0, type_any) \
X(SPL_AST_TYPE_IDENT, V0, type_ident) \
SPL_AST_BLOCK_ITEM,
SPL_AST_EXPR,
SPL_AST_TYPE_EXPR,
SPL_AST_ATTR_LIST,
/* clang-format on*/
typedef enum {
#ifdef X
#undef X
#endif
#define X(name, ...) name,
SPL_AST_KIND_TABLE
#undef X
SPL_AST_COUNT,
} spl_ast_node_kind_t;
typedef struct {
const char *fname;
int line;
int col;
} spl_ast_loc_t;
const char *spl_ast_kind_name(spl_ast_node_kind_t kind);
struct spl_ast_node;
typedef struct spl_ast_node spl_ast_node_t;
@@ -34,15 +137,14 @@ typedef usize spl_ast_node_ref_t;
typedef VEC(spl_ast_node_ref_t) spl_ast_node_ref_vec_t;
struct spl_ast_node {
spl_ast_node_kind_t kind;
spl_ast_loc_t loc;
spl_dbg_node_t dbg;
usize resolved_def_id;
union {
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
spl_ast_node_ref_t self; /* self */
spl_ast_node_ref_vec_t members; /* container_decl 列表 */
} container_item;
usize resolved_def_id;
usize resolved_type_id;
};
union {
spl_ast_node_ref_vec_t container_members; /* container_decl */
struct {
const char *ident;
@@ -53,8 +155,8 @@ struct spl_ast_node {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
const char *name;
spl_ast_node_ref_vec_t param_list; /* param_decl */
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_vec_t block; /* block_item */
spl_ast_node_ref_t type_expr; /* ret type expr */
spl_ast_node_ref_vec_t block; /* 语句/尾表达式 */
} fn_decl;
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
@@ -77,58 +179,35 @@ struct spl_ast_node {
const char *name;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t expr;
} var_decl;
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
spl_ast_node_ref_t type_expr;
const char *name;
spl_ast_node_ref_t expr;
} const_decl;
} var_const_decl;
struct {
enum {
SPL_AST_IF_STATEMENT,
SPL_AST_IFVAR_STATEMENT,
SPL_AST_WHILE_STATEMENT,
SPL_AST_LOOP_STATEMENT,
SPL_AST_FOR_STATEMENT,
SPL_AST_MATCH_STATEMENT,
SPL_AST_RET_STATEMENT,
SPL_AST_BREAK_STATEMENT,
SPL_AST_CONTINUE_STATEMENT,
SPL_AST_DEFER_STATEMENT,
SPL_AST_VARDECL,
SPL_AST_CONSTDECL,
SPL_AST_TYPEDECL,
SPL_AST_EXPR_STATEMENT,
} kind;
union {
/* 语句数据kind 决定解释哪个成员 */
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_vec_t if_block; /* block_item */
spl_ast_node_ref_vec_t else_block; /* block_item */
spl_ast_node_ref_vec_t if_block; /* 语句 */
spl_ast_node_ref_vec_t else_block; /* 语句 */
} if_statement;
struct {
spl_ast_node_ref_t packed_expr;
spl_ast_node_ref_vec_t if_block; /* block_item */
spl_ast_node_ref_vec_t else_block; /* block_item */
spl_ast_node_ref_vec_t if_block; /* 语句 */
spl_ast_node_ref_vec_t else_block; /* 语句 */
} ifvar_statement;
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_vec_t while_block; /* block_item */
spl_ast_node_ref_vec_t while_block; /* 语句 */
} while_statement;
struct {
spl_ast_node_ref_vec_t loop_block; /* block_item */
spl_ast_node_ref_vec_t loop_block; /* 语句 */
} loop_statement;
struct {
spl_ast_node_ref_vec_t expr_vec;
VEC(char *) ident_vec;
spl_ast_node_ref_vec_t block; /* block_item */
spl_ast_node_ref_vec_t block; /* 语句 */
} for_statement;
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_vec_t paced_exprs; /* packed_expr */
spl_ast_node_ref_vec_t match_block; /* block_item */
spl_ast_node_ref_vec_t match_block; /* 语句 */
} match_statement;
struct {
spl_ast_node_ref_t expr;
@@ -138,88 +217,22 @@ struct spl_ast_node {
struct {
} continue_statement;
struct {
spl_ast_node_ref_vec_t block_or_statement; /* block_item/statement */
spl_ast_node_ref_vec_t block_or_statement; /* 语句 */
} defer_statement;
spl_ast_node_ref_t var_decl;
spl_ast_node_ref_t const_decl;
spl_ast_node_ref_t type_decl;
spl_ast_node_ref_t expr_statement;
};
} block_item;
struct {
const char *ident;
const char *bind_ident;
spl_ast_node_ref_t expr;
} packed_expr;
struct {
enum {
SPL_AST_ASSIGN_EXPR,
SPL_AST_ASSIGN_ADD_EXPR,
SPL_AST_ASSIGN_sUB_EXPR,
SPL_AST_ASSIGN_MUL_EXPR,
SPL_AST_ASSIGN_DIV_EXPR,
SPL_AST_ASSIGN_MOD_EXPR,
SPL_AST_ASSIGN_AND_EXPR,
SPL_AST_ASSIGN_OR_EXPR,
SPL_AST_ASSIGN_XOR_EXPR,
SPL_AST_ASSIGN_LSHIFT_EXPR,
SPL_AST_ASSIGN_USHIFT_EXPR,
SPL_AST_BOOLOR_EXPR,
SPL_AST_BOOLAND_EXPR,
SPL_AST_BITOR_EXPR,
SPL_AST_BITXOR_EXPR,
SPL_AST_BITAND_EXPR,
SPL_AST_CMPEQ_EXPR,
SPL_AST_CMPNE_EXPR,
SPL_AST_CMP_LE_EXPR,
SPL_AST_CMP_GE_EXPR,
SPL_AST_CMP_LT_EXPR,
SPL_AST_CMP_GT_EXPR,
SPL_AST_RANGE_EXPR,
SPL_AST_LSHIFT_EXPR,
SPL_AST_RSHIFT_EXPR,
SPL_AST_ADD_EXPR,
SPL_AST_SUB_EXPR,
SPL_AST_MUL_EXPR,
SPL_AST_DIV_EXPR,
SPL_AST_MOD_EXPR,
SPL_AST_PREFIX_EXPR, /* left ref node */
SPL_AST_POSTFIX_EXPR, /* left ref node */
SPL_AST_PRIMARY_EXPR, /* left ref node */
} op;
struct {
spl_ast_node_ref_t left;
spl_ast_node_ref_t right;
} op_expr;
} expr;
struct {
enum {
SPL_AST_MINUS_EXPR,
SPL_AST_BANG_EXPR,
SPL_AST_TILDE_EXPR,
SPL_AST_AMPERSAND_EXPR,
SPL_AST_ASTERISK_EXPR,
} kind;
spl_ast_node_ref_t postfix_expr;
} prefix_expr;
struct {
enum {
SPL_AST_CALL_EXPR,
SPL_AST_FIELD_EXPR,
SPL_AST_DEREF_EXPR,
SPL_AST_INDEX_EXPR,
SPL_AST_SLICE_EXPR,
SPL_AST_AS_EXPR,
} kind;
spl_ast_node_ref_t primary_expr;
union {
spl_ast_node_ref_vec_t call_expr;
@@ -232,23 +245,8 @@ struct spl_ast_node {
spl_ast_node_ref_t type_expr;
};
} postfix_expr;
struct {
enum {
SPL_AST_INTEGER,
SPL_AST_FLOAT,
SPL_AST_CHAR_LIT,
SPL_AST_STRING_LIT,
SPL_AST_TRUE,
SPL_AST_FALSE,
SPL_AST_NULL,
SPL_AST_IDENT,
SPL_AST_ARGGREGATE_INIT,
SPL_AST_EXPR_EXPR,
SPL_AST_ARRAY_LIT,
SPL_AST_BUILTIN_EXPR,
SPL_AST_BLOCK_EXPR,
} kind;
union {
isize integer_expr;
double float_expr;
char char_lit_expr;
@@ -270,28 +268,30 @@ struct spl_ast_node {
const char *ident;
spl_ast_node_ref_vec_t expr_list;
} builtin_expr;
spl_ast_node_ref_vec_t block_expr; /* block_item */
};
spl_ast_node_ref_vec_t block_expr; /* 语句 */
} primary_expr;
struct {
const char *ident;
spl_ast_node_ref_t expr;
} aggregate_init_item;
struct {
spl_ast_node_ref_vec_t type_prefixs; /* prefix_type */
spl_ast_node_ref_vec_t attr_list; /* attr_item */
enum {
SPL_AST_BASE_TYPE_FN,
SPL_AST_BASE_TYPE_PATH,
SPL_AST_TYPE_STRUCT,
SPL_AST_TYPE_UNION,
SPL_AST_TYPE_ENUM,
} kind;
const char *spl_base_type;
union {
spl_ast_node_ref_vec_t type_path; /* type_atom */
struct {
VEC(const char *) ident_vec;
} type_path;
struct {
spl_ast_node_ref_t element;
spl_ast_node_ref_t size;
} array_type;
struct {
spl_ast_node_ref_t element;
} slice_type;
struct {
spl_ast_node_ref_t pointee;
} pointer_type;
struct {
spl_ast_node_ref_vec_t param_list; /* param_decl */
spl_ast_node_ref_t type_expr;
@@ -299,48 +299,24 @@ struct spl_ast_node {
spl_ast_node_ref_vec_t aggregate_list; /* container_decl */
};
} type_expr;
struct {
/* ASTERISK = 1, [] = 2, else = 0*/
int pointer;
/* if array_size != 0 then pointer == 2 */
int array_size;
} prefix_type;
struct {
enum {
SPL_AST_TYPE_VOID,
SPL_AST_TYPE_BOOL,
SPL_AST_TYPE_I8,
SPL_AST_TYPE_U8,
SPL_AST_TYPE_I16,
SPL_AST_TYPE_U16,
SPL_AST_TYPE_I32,
SPL_AST_TYPE_U32,
SPL_AST_TYPE_I64,
SPL_AST_TYPE_U64,
SPL_AST_TYPE_ISIZE,
SPL_AST_TYPE_USIZE,
SPL_AST_TYPE__F32, /*不实现*/
SPL_AST_TYPE__F64, /*不实现*/
SPL_AST_TYPE_PTR,
SPL_AST_TYPE_ANY,
SPL_AST_TYPE_IDENT,
} kind;
const char *ident;
} type_atom;
};
};
typedef VEC(spl_ast_node_t) spl_ast_node_vec_t;
typedef VEC(char*)spl_ast_cstr_ref_vec_t;
typedef struct {
int parsed;
spl_tok_vec_t input;
spl_ast_node_vec_t buckets;
spl_ast_node_vec_t node_buckets;
spl_ast_cstr_ref_vec_t str_buckets;
spl_ast_node_ref_t root;
} spl_ast_t;
void spl_ast_init(spl_ast_t *ast, const spl_tok_vec_t *tok_vec /*move*/);
void spl_ast_drop(spl_ast_t *ast);
spl_ast_node_t* spl_ast_node(spl_ast_t *ast, spl_ast_node_ref_t node);
void spl_ast_prase(spl_ast_t *ast);
void spl_ast_valid(spl_ast_t *ast);
void spl_ast_dump(spl_ast_t *ast, spl_ast_node_ref_t node);

File diff suppressed because it is too large Load Diff

View File

@@ -4,21 +4,13 @@
#include "spl_ir.h"
#include "spl_sema.h"
/* 全局 var/const 的 def → gdata 向量中的 value 节点索引 */
typedef struct {
spl_def_id_t def_id;
usize gdata_idx;
} spl_ast2ir_gref_t;
typedef struct {
const spl_sema_t *sema;
spl_ir_t ir;
VEC(char *) owned_names; /* 本模块 malloc 的函数名drop 时释放 */
VEC(spl_ast2ir_gref_t) gdata_ref; /* def_id → gdata value 节点索引 */
spl_ir_builder_t *ir;
int err_count;
} spl_ast2ir_t;
void spl_ast2ir_init(spl_ast2ir_t *ast2ir, const spl_sema_t *sema);
void spl_ast2ir_init(spl_ast2ir_t *ast2ir, spl_ir_builder_t *ir, const spl_sema_t *sema);
void spl_ast2ir_drop(spl_ast2ir_t *ast2ir);
void spl_ast2ir_run(spl_ast2ir_t *ast2ir);

View File

@@ -1,28 +0,0 @@
/* spl_builtin.c — 内置函数集中注册表实现 */
#include "spl_builtin.h"
#include "../stage0/include/utils.h"
#include <string.h>
static const spl_builtin_t k_builtins[] = {
{"sizeof", SPL_BUILTIN_SIZE_OF, 1, 1, 0},
{"bitsizeof", SPL_BUILTIN_BITSIZE_OF, 1, 1, 0},
{"alignof", SPL_BUILTIN_ALIGN_OF, 1, 1, 0},
{"offsetof", SPL_BUILTIN_OFFSET_OF, 2, 2, 0},
{"field_count", SPL_BUILTIN_FIELD_COUNT, 1, 1, 0},
{"dbg", SPL_BUILTIN_DBG, 0, -1, 1},
{"assert", SPL_BUILTIN_ASSERT, 1, 1, 1},
{"import", SPL_BUILTIN_IMPORT, 1, 1, 1},
};
const spl_builtin_t *spl_builtin_lookup(const char *name) {
if (!name)
return NULL;
for (usize i = 0; i < sizeof(k_builtins) / sizeof(k_builtins[0]); i++) {
if (strcmp(k_builtins[i].name, name) == 0)
return &k_builtins[i];
}
return NULL;
}
int spl_builtin_count(void) { return (int)(sizeof(k_builtins) / sizeof(k_builtins[0])); }

View File

@@ -1,43 +0,0 @@
/* spl_builtin.h — 内置函数集中注册表
*
* @builtin 名称/类别/参数/返回类型的单一事实来源。
* sema类型推导与 ast2irIR 发射)各自按 kind 分发实现。
*/
#ifndef __SPL_BUILTIN_H__
#define __SPL_BUILTIN_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
SPL_BUILTIN_SIZE_OF, /* @sizeof(T) -> usize */
SPL_BUILTIN_BITSIZE_OF, /* @bitsizeof(T) -> usize */
SPL_BUILTIN_ALIGN_OF, /* @alignof(T) -> usize */
SPL_BUILTIN_OFFSET_OF, /* @offsetof(T, field) -> usize */
SPL_BUILTIN_FIELD_COUNT, /* @field_count(T) -> usize */
SPL_BUILTIN_DBG, /* @dbg(args...) -> void */
SPL_BUILTIN_ASSERT, /* @assert(cond) -> void */
SPL_BUILTIN_IMPORT, /* @import(path) -> 模块 (预留) */
SPL_BUILTIN_COUNT
} spl_builtin_kind_t;
typedef struct {
const char *name;
spl_builtin_kind_t kind;
int min_args; /* 参数个数下限 */
int max_args; /* 参数个数上限,-1 = 不限 */
int ret_is_void; /* 1 = void 返回 */
} spl_builtin_t;
/* 按名称查找内置;未注册返回 NULL */
const spl_builtin_t *spl_builtin_lookup(const char *name);
/* 内置总数 */
int spl_builtin_count(void);
#ifdef __cplusplus
}
#endif
#endif /* __SPL_BUILTIN_H__ */

25
stage1/spl_dbg.h Normal file
View File

@@ -0,0 +1,25 @@
#ifndef __SPL_DBG_H__
#define __SPL_DBG_H__
typedef struct {
const char *fname;
int line;
int col;
const char *dbg_name;
// TODO
} spl_dbg_node_t;
#define SPL_FATAL(dbg, fmt, ...) \
LOG_FATAL("fatal at %s:%zd:%zd " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#define SPL_ERROR(dbg, fmt, ...) \
LOG_ERROR("error at %s:%zd:%zd " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#define SPL_WARN(dbg, fmt, ...) \
LOG_ERROR("warn at %s:%zd:%zd " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#endif /* __SPL_DBG_H__ */

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,7 @@
#define __SPL_IR_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_type.h"
/* clang-format off */
@@ -44,7 +45,6 @@
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(mem.fence, V0, SPL_IR_MEM_FENCE) \
X(type.const, V0, SPL_IR_TYPE_CONST) \
X(type.bitsizeof, V0, SPL_IR_TYPE_BITSIZEOF) \
X(type.sizeof, V0, SPL_IR_TYPE_SIZEOF) \
@@ -54,15 +54,6 @@
X(agg.construct, V0, SPL_IR_AGG_CONSTRUCT) \
X(agg.extract, V0, SPL_IR_AGG_EXTRACT) \
X(agg.insert, V0, SPL_IR_AGG_INSERT) \
X(atomic.load, V0, SPL_IR_ATOMIC_LOAD) \
X(atomic.store, V0, SPL_IR_ATOMIC_STORE) \
X(atomic.rmw_add, V0, SPL_IR_ATOMIC_RMW_ADD) \
X(atomic.rmw_sub, V0, SPL_IR_ATOMIC_RMW_SUB) \
X(atomic.rmw_and, V0, SPL_IR_ATOMIC_RMW_AND) \
X(atomic.rmw_or, V0, SPL_IR_ATOMIC_RMW_OR) \
X(atomic.rmw_xor, V0, SPL_IR_ATOMIC_RMW_XOR) \
X(atomic.rmw_xchg, V0, SPL_IR_ATOMIC_RMW_XCHG) \
X(atomic.cmpxchg, V0, SPL_IR_ATOMIC_CMPXCHG) \
X(control.select, V0, SPL_IR_CONTROL_SELECT) \
X(control.br, V0, SPL_IR_CONTROL_BR) \
X(control.jmp, V0, SPL_IR_CONTROL_JMP) \
@@ -72,7 +63,6 @@
X(control.unreachable, V0, SPL_IR_CONTROL_UNREACHABLE) \
X(control.trap, V0, SPL_IR_CONTROL_TRAP) \
X(dbg.breakpoint, V0, SPL_IR_DBG_BREAKPOINT) \
X(dbg.declare, V0, SPL_IR_DBG_DECLARE)
typedef enum {
#ifdef X
@@ -91,8 +81,9 @@ typedef usize spl_ir_func_ref_t; /* 0 is error */
typedef struct {
spl_ir_kind_t kind;
usize src_ref; /* AST 节点 ref调试行号用ast2ir 注解) */
spl_dbg_node_t dbg;
union {
spl_type_id_t tid;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t left;
@@ -147,9 +138,6 @@ typedef struct {
spl_ir_node_ref_t val;
spl_ir_node_ref_t size;
} mem_set;
struct {
spl_ir_node_ref_t ordering;
} mem_fence;
struct {
spl_type_id_t tid;
union {
@@ -234,28 +222,16 @@ typedef struct {
SPL_IR_ATTR_NAKED, /* 不实现 */
SPL_IR_ATTR_NOINLINE, /* 不实现 */
SPL_IR_ATTR_ALWAYSINLINE, /* 不实现 */
};
} kind;
} spl_ir_attr_t;
typedef VEC(spl_ir_attr_t) spl_ir_attr_vec_t;
/* 调试:函数内变量(名 → 内存位置。alloca 节点或参数槽。 */
typedef struct {
const char *name; /* 指向 AST 字符串,不拥有 */
spl_ir_node_ref_t alloca; /* 非参数alloca 节点 ref */
spl_type_id_t tid;
int is_param; /* 参数则用 param_idx */
usize param_idx;
usize offset; /* fp 字节偏移LADDR imm 语义ir2vm 填) */
} spl_ir_dbg_var_t;
typedef VEC(spl_ir_dbg_var_t) spl_ir_dbg_var_vec_t;
typedef struct {
const char *name;
spl_ir_attr_t attr;
spl_type_id_t fn_tid;
spl_ir_node_vec_t nodes;
spl_ir_node_ref_vec_t labels;
spl_ir_dbg_var_vec_t dbg_vars; /* 调试变量表fp 偏移在 ir2vm 填) */
} spl_ir_func_t;
typedef VEC(spl_ir_func_t) spl_ir_func_vec_t;
@@ -277,4 +253,145 @@ spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty);
const char *spl_ir_kind_name(spl_ir_kind_t kind);
typedef struct {
spl_ir_t ir;
spl_ir_func_ref_t current_fn;
spl_ir_node_ref_t current_node;
spl_ir_node_ref_vec_t reloc_label;
spl_dbg_node_t dbg;
} spl_ir_builder_t;
/* clang-format off */
#define SPL_IR_BIN_ARITH_TABLE \
X(arith_add, SPL_IR_ARITH_ADD) \
X(arith_sub, SPL_IR_ARITH_SUB) \
X(arith_mul, SPL_IR_ARITH_MUL) \
X(arith_div, SPL_IR_ARITH_DIV) \
X(arith_rem, SPL_IR_ARITH_REM) \
X(arith_and, SPL_IR_ARITH_AND) \
X(arith_or, SPL_IR_ARITH_OR) \
X(arith_xor, SPL_IR_ARITH_XOR) \
X(arith_shl, SPL_IR_ARITH_SHL) \
X(arith_shr, SPL_IR_ARITH_SHR)
#define SPL_IR_UN_ARITH_TABLE \
X(arith_neg, SPL_IR_ARITH_NEG) \
X(arith_abs, SPL_IR_ARITH_ABS) \
X(arith_not, SPL_IR_ARITH_NOT)
#define SPL_IR_CMP_TABLE \
X(cmp_eq, SPL_IR_CMP_EQ) \
X(cmp_ne, SPL_IR_CMP_NE) \
X(cmp_lt, SPL_IR_CMP_LT) \
X(cmp_le, SPL_IR_CMP_LE) \
X(cmp_gt, SPL_IR_CMP_GT) \
X(cmp_ge, SPL_IR_CMP_GE)
#define SPL_IR_CAST_TABLE \
X(cast_trunc, SPL_IR_CAST_TRUNC) \
X(cast_zext, SPL_IR_CAST_ZEXT) \
X(cast_sext, SPL_IR_CAST_SEXT) \
X(cast_fext, SPL_IR_CAST_FEXT) \
X(cast_ftrunc, SPL_IR_CAST_FTRUNC) \
X(cast_bitcast, SPL_IR_CAST_BITCAST) \
X(cast_ptr2int, SPL_IR_CAST_PTR2INT) \
X(cast_int2ptr, SPL_IR_CAST_INT2PTR) \
X(cast_bool2int, SPL_IR_CAST_BOOL2INT) \
X(case_int2float, SPL_IR_CASE_INT2FLOAT) \
X(case_float2int, SPL_IR_CASE_FLOAT2INT)
/* clang-format on */
void spl_ir_builder_init(spl_ir_builder_t *b);
void spl_ir_builder_drop(spl_ir_builder_t *b);
spl_ir_func_ref_t spl_ir_builder_fn_new(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
spl_ir_func_ref_t spl_ir_builder_cur_fn(const spl_ir_builder_t *b);
void spl_ir_builder_set_dbg(spl_ir_builder_t *b, spl_dbg_node_t dbg);
spl_ir_node_ref_t spl_ir_builder_block_new(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_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_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_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_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_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_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_cstr(spl_ir_builder_t *b, spl_type_id_t tid,
const char *val);
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_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_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_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_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_node_ref_t true_label,
spl_ir_node_ref_t false_label);
spl_ir_node_ref_t spl_ir_builder_control_jmp(spl_ir_builder_t *b, spl_ir_node_ref_t label);
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);
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t 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_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);
spl_ir_node_ref_t spl_ir_builder_dbg_breakpoint(spl_ir_builder_t *b);
#endif /* __SPL_IR_H__ */

0
stage1/spl_layout.c Normal file
View File

0
stage1/spl_layout.h Normal file
View File

View File

@@ -1,4 +1,4 @@
/* spl_lexer.c SPL lexical analyzer */
/* spl_lexer.c - SPL lexical analyzer */
#include "spl_lexer.h"
#include "spl_tok.h"
@@ -21,7 +21,7 @@ static spl_tok_type_t keyword_type(const char *ident, usize len) {
return TOK_IDENT;
}
/* Escape sequence decoder returns the decoded character,
/* Escape sequence decoder - returns the decoded character,
* advances *s past the escape sequence, returns 0 on success,
* non-zero on error. */
int spl_decode_escape(const char **s, char *out) {
@@ -85,7 +85,7 @@ spl_tok_vec_t spl_lex(const char *source, const char *fname) {
const char *start = source + offset;
char c = *start;
/* Skip whitespace (but not newlines emit TOK_ENDLINE) */
/* Skip whitespace (but not newlines - emit TOK_ENDLINE) */
if (c == ' ' || c == '\t' || c == '\r') {
offset++;
col++;

View File

@@ -1,4 +1,4 @@
/* spl_lexer.h 独立词法分析器 */
/* spl_lexer.h - 独立词法分析器 */
#ifndef __SPL_LEXER_H__
#define __SPL_LEXER_H__

File diff suppressed because it is too large Load Diff

View File

@@ -4,32 +4,53 @@
#include "spl_ast.h"
#include "spl_type.h"
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 usize spl_scope_id_t; /* 0 is error */
typedef struct {
spl_scope_id_t parent;
MAP(const char *, spl_def_id_t) symbols;
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_ast_t *ast;
spl_type_t type;
spl_scope_node_vec_t scopes;
spl_scope_id_t root_scope;
spl_scope_id_t current_scope;
spl_def_id_t root_def;
} 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);
typedef VEC(const char *) spl_symbol_path_t;
bool spl_scope_find(spl_scope_t *scop, const char *symbol_name, spl_symbol_t *out);
typedef struct {
spl_ast_t *ast;
spl_type_t *type;
spl_scope_t *scope;
spl_symbol_t root;
int error_count;
spl_scope_id_t store_scope;
spl_type_id_t current_fn_ret_tid; // TODO
} spl_sema_t;
void spl_sema_init(spl_sema_t *sema);
void spl_sema_init(spl_sema_t *sema, spl_ast_t *ast, spl_type_t *type, spl_scope_t *scope);
void spl_sema_drop(spl_sema_t *sema);
void spl_sema_run(spl_sema_t *sema);
void spl_sema_check(spl_sema_t *sema);
spl_scope_id_t spl_sema_scope_alloc(spl_sema_t *sema);
bool spl_sema_scope_insert(spl_sema_t *sema, spl_scope_id_t id, const char *symbol_name,
spl_def_id_t symbol_val);
typedef VEC(const char *) spl_symbol_path_t;
spl_def_id_t spl_sema_scope_find(spl_sema_t *sema, spl_symbol_path_t path);
void spl_sema_run(spl_sema_t *sema);
void spl_sema_dump(spl_sema_t *sema);
#endif /* __SPL_SEMA_H__ */

View File

@@ -1,4 +1,4 @@
/* spl_tok.h Token type definitions (extracted from spl_lexer.h) */
/* spl_tok.h - Token type definitions (extracted from spl_lexer.h) */
#ifndef __SPL_TOK_H__
#define __SPL_TOK_H__
@@ -9,12 +9,14 @@
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) \
@@ -23,9 +25,12 @@
X(match , KW_MATCH , SPL_V0) \
X(null , KW_NULL , SPL_V0) \
X(ret , KW_RET , SPL_V0) \
X(shape , WK_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_UNDEFINDED , SPL_V0) \
X(union , KW_UNION , SPL_V0) \
X(var , KW_VAR , SPL_V0) \
X(void , KW_VOID , SPL_V0) \

View File

@@ -1,160 +1,368 @@
// WRITE BY AI
/* spl_type.c SPL 类型系统type/def 两张完全独立的 arena 表 + 构造器 + dump
* type_table 按 spl_type_id_t 存匿名类型def_table 按 spl_def_id_t 存命名实体。
* 两表 id 空间互不相干0 均保留为 error。 */
#include "spl_type.h"
#include <stdio.h>
#include <string.h>
static spl_type_id_t type_push(spl_type_t *type) {
spl_type_node_t n;
memset(&n, 0, sizeof n);
n.kind = SPL_TYPE_VOID;
vec_push(type->type_table, n);
return type->type_table.size - 1;
static usize spl_type_hash(spl_type_node_t n) {
usize hash = n.kind << 20;
switch (n.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_VOID:
case SPL_TYPE_BOOL:
case SPL_TYPE_UNDEFINED:
case SPL_TYPE_NULL:
break;
case SPL_TYPE_INT:
hash += n.int_type.bits + n.int_type.is_signed;
break;
case SPL_TYPE_FLOAT:
hash += n.float_type.bits;
break;
case SPL_TYPE_PTR:
hash += n.ptr_pointee;
break;
case SPL_TYPE_SLICE:
hash += n.slice_element;
break;
case SPL_TYPE_RANGE:
hash += n.range_element;
break;
case SPL_TYPE_ARRAY:
hash += n.array_type.element + n.array_type.len;
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
hash += n.layout.mode * 31 + n.layout.fixed_align_bits;
vec_for(n.agg_members, i) {
hash += (n.agg_members.data[i].name ? map_hash_str(n.agg_members.data[i].name) : 0) +
n.agg_members.data[i].type_id;
}
break;
case SPL_TYPE_ENUM:
hash += n.layout.mode * 31 + n.layout.fixed_align_bits;
hash += n.adt_type.tag_type;
vec_for(n.adt_type.variants, i) {
hash +=
(n.adt_type.variants.data[i].name ? map_hash_str(n.adt_type.variants.data[i].name)
: 0) +
n.adt_type.variants.data[i].type_id;
}
break;
case SPL_TYPE_FN:
hash += n.fn_type.ret;
vec_for(n.fn_type.params, i) { hash += vec_at(n.fn_type.params, i); }
break;
default: // TODO
break;
}
return hash;
}
/* 内置整型去重:同 bits/signed 复用同一 id类型唯一化 */
spl_type_id_t spl_type_int(spl_type_t *type, usize bits, int is_signed) {
for (usize i = 1; i < type->type_table.size; i++) {
spl_type_node_t *n = &type->type_table.data[i];
if (n->kind == SPL_TYPE_INT && n->int_type.bits == bits &&
n->int_type.is_signed == is_signed)
return i;
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
if (n1.kind != n2.kind)
return 1;
switch (n1.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_VOID:
case SPL_TYPE_BOOL:
case SPL_TYPE_UNDEFINED:
case SPL_TYPE_NULL:
break;
case SPL_TYPE_INT:
if (n1.int_type.bits != n2.int_type.bits)
return 1;
if (n1.int_type.is_signed != n2.int_type.is_signed)
return 1;
break;
case SPL_TYPE_FLOAT:
if (n1.float_type.bits != n2.float_type.bits)
return 1;
break;
case SPL_TYPE_PTR:
if (n1.ptr_pointee != n2.ptr_pointee)
return 1;
break;
case SPL_TYPE_SLICE:
if (n1.slice_element != n2.slice_element)
return 1;
break;
case SPL_TYPE_RANGE:
if (n1.range_element != n2.range_element)
return 1;
break;
case SPL_TYPE_ARRAY:
if (n1.array_type.element != n2.array_type.element)
return 1;
if (n1.array_type.len != n2.array_type.len)
return 1;
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
if (vec_size(n1.agg_members) != vec_size(n2.agg_members))
return 1;
vec_for(n1.agg_members, i) {
const char *na = n1.agg_members.data[i].name;
const char *nb = n2.agg_members.data[i].name;
if (strcmp(na ? na : "", nb ? nb : "") != 0)
return 1;
if (n1.agg_members.data[i].type_id != n2.agg_members.data[i].type_id)
return 1;
}
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_INT;
type->type_table.data[id].int_type.bits = bits;
type->type_table.data[id].int_type.is_signed = is_signed;
break;
case SPL_TYPE_ENUM:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
if (n1.adt_type.tag_type != n2.adt_type.tag_type)
return 1;
if (vec_size(n1.adt_type.variants) != vec_size(n2.adt_type.variants))
return 1;
vec_for(n1.adt_type.variants, i) {
const char *na = n1.adt_type.variants.data[i].name;
const char *nb = n2.adt_type.variants.data[i].name;
if (strcmp(na ? na : "", nb ? nb : "") != 0)
return 1;
if (n1.adt_type.variants.data[i].type_id != n2.adt_type.variants.data[i].type_id)
return 1;
}
break;
case SPL_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))
return 1;
vec_for(n1.fn_type.params, i) {
if (vec_at(n1.fn_type.params, i) != vec_at(n2.fn_type.params, i))
return 1;
}
break;
default: // TODO
return 1;
}
return 0;
}
static usize spl_type_map_hash(usize k) { return MAP_HASH_INT(k); }
static int spl_type_map_cmp(usize a, usize b) { return MAP_CMP_INT(a, b); }
static void spl_type_node_free_vecs(spl_type_node_t *tn) {
switch (tn->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
vec_free(tn->agg_members);
break;
case SPL_TYPE_ENUM:
vec_free(tn->adt_type.variants);
break;
case SPL_TYPE_FN:
vec_free(tn->fn_type.params);
break;
default:
break;
}
}
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *tn) {
usize hash = spl_type_hash(*tn);
usize idx = (usize)-1;
spl_type_id_t cand = 0;
while (map_get_continue(type->type_map, hash, &cand, &idx)) {
spl_type_node_t *existing = &vec_at(type->type_table, cand);
if (spl_type_eq(*existing, *tn) == 0) {
spl_type_node_free_vecs(tn);
return cand;
}
}
spl_type_id_t id = vec_size(type->type_table);
vec_push(type->type_table, *tn);
map_put_new(type->type_map, hash, id);
tn->kind = SPL_TYPE_ERROR;
return id;
}
/* 内置浮点去重 */
spl_type_id_t spl_type_float(spl_type_t *type, usize bits) {
for (usize i = 1; i < type->type_table.size; i++) {
spl_type_node_t *n = &type->type_table.data[i];
if (n->kind == SPL_TYPE_FLOAT && n->float_type.bits == bits)
return i;
static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_type_id_t tid,
const char *name, usize *out_idx) {
spl_type_node_t *n = spl_type_node(type, tid);
if (!n || !name) {
return NULL;
}
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_FLOAT;
type->type_table.data[id].float_type.bits = bits;
return id;
if (n->kind == SPL_TYPE_STRUCT || n->kind == SPL_TYPE_UNION) {
vec_for(n->agg_members, i) {
const char *mn = n->agg_members.data[i].name;
if (strcmp(mn ? mn : "", name) == 0) {
if (out_idx) {
*out_idx = i;
}
return &n->agg_members.data[i];
}
}
} else if (n->kind == SPL_TYPE_ENUM) {
vec_for(n->adt_type.variants, i) {
const char *mn = n->adt_type.variants.data[i].name;
if (strcmp(mn ? mn : "", name) == 0) {
if (out_idx) {
*out_idx = i;
}
return &n->adt_type.variants.data[i];
}
}
}
return NULL;
}
spl_type_id_t spl_type_void(spl_type_t *type) {
for (usize i = 1; i < type->type_table.size; i++)
if (type->type_table.data[i].kind == SPL_TYPE_VOID)
return i;
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_VOID;
return id;
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid,
const char *name) {
return spl_type_agg_member_find(type, tid, name, NULL);
}
spl_type_id_t spl_type_bool(spl_type_t *type) {
for (usize i = 1; i < type->type_table.size; i++)
if (type->type_table.data[i].kind == SPL_TYPE_BOOL)
return i;
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_BOOL;
return id;
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name,
usize *out_idx) {
return spl_type_agg_member_find(type, tid, name, out_idx) != NULL;
}
spl_type_id_t spl_type_ptr(spl_type_t *type, spl_type_id_t val) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_PTR;
type->type_table.data[id].ptr_pointee = val;
return id;
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind) {
spl_type_node_t tn = {0};
tn.kind = kind;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_slice(spl_type_t *type, spl_type_id_t val) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_SLICE;
type->type_table.data[id].slice_element = val;
return id;
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.int_type.bits = bits;
tn.int_type.is_signed = is_signed;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_range(spl_type_t *type, spl_type_id_t val) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_RANGE;
type->type_table.data[id].range_element = val;
return id;
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.float_type.bits = bits;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_array(spl_type_t *type, spl_type_id_t val, usize len) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_ARRAY;
type->type_table.data[id].array_type.element = val;
type->type_table.data[id].array_type.len = len;
return id;
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.ptr_pointee = pointee;
return spl_type_node_push(type, &tn);
}
/* 绑定节点/别名引用type 节点指向被引用的类型 id
* (供未来"底层同型但类型系统不认"的 newtype 使用,暂不参与注册) */
spl_type_id_t spl_type_tid(spl_type_t *type, spl_type_id_t val) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_ID;
type->type_table.data[id].type_id = val;
return id;
spl_type_id_t spl_type_builder_slice(spl_type_t *type, spl_type_id_t element) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_SLICE;
tn.slice_element = element;
return spl_type_node_push(type, &tn);
}
/* 聚合类型:默认 STRUCT字段类型列表 */
spl_type_id_t spl_type_agg(spl_type_t *type, spl_type_id_vec_t fields) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_STRUCT;
type->type_table.data[id].agg_field_types = fields;
return id;
spl_type_id_t spl_type_builder_range(spl_type_t *type, spl_type_id_t element) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_RANGE;
tn.range_element = element;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_enum(spl_type_t *type, spl_type_id_vec_t variants, spl_type_id_t tag) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_ENUM;
type->type_table.data[id].enum_type.variants = variants;
type->type_table.data[id].enum_type.tag_type = tag;
return id;
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.array_type.element = element;
tn.array_type.len = len;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_fn(spl_type_t *type, spl_type_id_vec_t params, spl_type_id_t ret) {
spl_type_id_t id = type_push(type);
type->type_table.data[id].kind = SPL_TYPE_FN;
type->type_table.data[id].fn_type.params = params;
type->type_table.data[id].fn_type.ret = ret;
return id;
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_node_t tn = {0};
tn.kind = SPL_TYPE_FN;
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);
}
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
const spl_type_member_t *members, usize nmembers,
spl_type_id_t tag_type, spl_type_layout_t layout) {
spl_type_node_t tn = {0};
tn.kind = tk;
tn.layout = layout;
if (tk == SPL_TYPE_ENUM) {
vec_init(tn.adt_type.variants);
for (usize i = 0; i < nmembers; i++) {
vec_push(tn.adt_type.variants, members[i]);
}
tn.adt_type.tag_type = tag_type;
} else {
vec_init(tn.agg_members);
for (usize i = 0; i < nmembers; i++) {
vec_push(tn.agg_members, members[i]);
}
}
return spl_type_node_push(type, &tn);
}
spl_def_id_t spl_type_def_alloc(spl_type_t *type, spl_def_node_kind_t kind, const char *name,
spl_dbg_node_t dbg, usize ast_node_ref) {
spl_def_node_t n = {0};
n.kind = kind;
n.name = name;
n.dbg_node = dbg;
n.ast_node_ref = ast_node_ref;
vec_push(type->def_table, n);
return vec_size(type->def_table) - 1;
}
void spl_type_def_resolve(spl_type_t *type, spl_def_id_t id, spl_type_id_t tid) {
spl_def_node_t *d = spl_type_def(type, id);
if (!d) {
return;
}
d->type_id = tid;
}
spl_type_id_t spl_type_fn_param_tid(spl_type_t *type, spl_type_id_t fn_tid, usize idx) {
spl_type_node_t *n = spl_type_node(type, fn_tid);
if (!n || n->kind != SPL_TYPE_FN || idx >= vec_size(n->fn_type.params))
return 0;
return vec_at(n->fn_type.params, idx);
}
void spl_type_init(spl_type_t *type) {
vec_init(type->type_table);
vec_push(type->type_table, (spl_type_node_t){0});
map_init(type->type_map, spl_type_map_hash, spl_type_map_cmp);
vec_init(type->def_table);
/* 两表 id 0 均保留为 error */
type_push(type);
spl_type_def_alloc(type);
/* 关键字/内置类型(去重后 i8..u64 等各占一个 iddef 由 sema 登记) */
spl_type_void(type);
spl_type_bool(type);
spl_type_int(type, 8, 1);
spl_type_int(type, 8, 0);
spl_type_int(type, 16, 1);
spl_type_int(type, 16, 0);
spl_type_int(type, 32, 1);
spl_type_int(type, 32, 0);
spl_type_int(type, 64, 1);
spl_type_int(type, 64, 0);
spl_type_float(type, 32);
spl_type_float(type, 64);
vec_push(type->def_table, (spl_def_node_t){0});
spl_type_builder_simple(type, SPL_TYPE_VOID);
spl_type_builder_simple(type, SPL_TYPE_BOOL);
spl_type_builder_simple(type, SPL_TYPE_UNDEFINED);
spl_type_builder_simple(type, SPL_TYPE_NULL);
spl_type_builder_int(type, 8, false);
spl_type_builder_int(type, 16, false);
spl_type_builder_int(type, 32, false);
spl_type_builder_int(type, 64, false);
spl_type_builder_int(type, 8, true);
spl_type_builder_int(type, 16, true);
spl_type_builder_int(type, 32, true);
spl_type_builder_int(type, 64, true);
spl_type_builder_float(type, 32);
spl_type_builder_float(type, 64);
}
void spl_type_drop(spl_type_t *type) {
/* type 节点持有的内嵌 vec */
for (usize i = 0; i < type->type_table.size; i++) {
spl_type_node_t *n = &type->type_table.data[i];
vec_for(type->type_table, i) {
spl_type_node_t *n = &vec_at(type->type_table, i);
switch (n->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
vec_free(n->agg_field_types);
vec_free(n->agg_members);
break;
case SPL_TYPE_ENUM:
vec_free(n->enum_type.variants);
vec_free(n->adt_type.variants);
break;
case SPL_TYPE_FN:
vec_free(n->fn_type.params);
@@ -163,86 +371,59 @@ void spl_type_drop(spl_type_t *type) {
break;
}
}
/* def 节点持有的内嵌 vec */
for (usize i = 0; i < type->def_table.size; i++) {
spl_def_node_t *d = &type->def_table.data[i];
switch (d->kind) {
case SPL_DEF_AGG:
vec_free(d->agg_def);
break;
case SPL_DEF_FN_PARAMS:
vec_free(d->fn_params_def);
break;
default:
break;
}
}
map_free(type->type_map);
vec_free(type->type_table);
vec_free(type->def_table);
}
spl_type_id_t spl_type_alloc(spl_type_t *type) { return type_push(type); }
spl_type_node_t *spl_type_node(spl_type_t *type, spl_type_id_t id) {
if (!id || id >= type->type_table.size)
if (!id || id >= vec_size(type->type_table))
return NULL;
return &type->type_table.data[id];
}
spl_def_id_t spl_type_def_alloc(spl_type_t *type) {
spl_def_node_t d;
memset(&d, 0, sizeof d);
d.kind = SPL_DEF_NONE;
vec_push(type->def_table, d);
return type->def_table.size - 1;
return &vec_at(type->type_table, id);
}
spl_def_node_t *spl_type_def(spl_type_t *type, spl_def_id_t id) {
if (!id || id >= type->def_table.size)
if (!id || id >= vec_size(type->def_table))
return NULL;
return &type->def_table.data[id];
}
static const char *def_kind_name(spl_def_node_t *d) {
switch (d->kind) {
case SPL_DEF_NONE:
return "none";
case SPL_DEF_BUILTIN:
return "builtin";
case SPL_DEF_VAR:
return "var";
case SPL_DEF_MEMBER:
return "member";
case SPL_DEF_FN_PARAMS:
return "fn_params";
case SPL_DEF_AGG:
return "agg";
case SPL_DEF_DISTINCT:
return "distinct";
case SPL_DEF_ALIAS:
return "alias";
}
return "?";
return &vec_at(type->def_table, id);
}
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
spl_type_node_t *n = spl_type_node(type, id);
if (!n) {
printf("(err)");
printf("none");
return;
}
switch (n->kind) {
case SPL_TYPE_ERROR:
printf("error");
break;
case SPL_TYPE_VOID:
printf("void");
break;
case SPL_TYPE_BOOL:
printf("bool");
break;
case SPL_TYPE_UNDEFINED:
printf("undefined");
break;
case SPL_TYPE_NULL:
printf("null");
break;
case SPL_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:
if (n->float_type.bits == 0) {
printf("comptime_float");
} else {
printf("f%zu", n->float_type.bits);
}
break;
case SPL_TYPE_PTR:
printf("*");
@@ -262,20 +443,48 @@ void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
spl_type_pure_dump(type, n->array_type.element);
break;
case SPL_TYPE_STRUCT:
printf("struct{%zu fields}", n->agg_field_types.size);
printf("struct{");
vec_for(n->agg_members, i) {
if (i) {
printf(", ");
}
spl_type_member_t *member = &vec_at(n->agg_members, i);
printf("%s:", member->name ? member->name : "?");
spl_type_pure_dump(type, member->type_id);
}
printf("}");
break;
case SPL_TYPE_UNION:
printf("union{%zu fields}", n->agg_field_types.size);
printf("union{");
vec_for(n->agg_members, i) {
if (i) {
printf(", ");
}
spl_type_member_t *member = &vec_at(n->agg_members, i);
printf("%s:", member->name ? member->name : "?");
spl_type_pure_dump(type, member->type_id);
}
printf("}");
break;
case SPL_TYPE_ENUM:
printf("enum{%zu variants}", n->enum_type.variants.size);
printf("enum{"); // TODO tag_type
vec_for(n->adt_type.variants, i) {
if (i) {
printf(", ");
}
spl_type_member_t *member = &vec_at(n->adt_type.variants, i);
printf("%s:", member->name ? member->name : "?");
spl_type_pure_dump(type, member->type_id);
}
printf("}");
break;
case SPL_TYPE_FN: {
printf("fn(");
for (usize i = 0; i < n->fn_type.params.size; i++) {
if (i)
vec_for(n->fn_type.params, i) {
if (i) {
printf(",");
spl_type_pure_dump(type, n->fn_type.params.data[i]);
}
spl_type_pure_dump(type, vec_at(n->fn_type.params, i));
}
printf(") -> ");
spl_type_pure_dump(type, n->fn_type.ret);
@@ -288,42 +497,39 @@ void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
}
void spl_type_def_dump(spl_type_t *type, spl_def_id_t id) {
spl_def_node_t *d = spl_type_def(type, id);
if (!d) {
printf("(err)");
spl_def_node_t *node = spl_type_def(type, id);
if (!node) {
printf("none");
return;
}
printf("kind=%s type_id=%zu", def_kind_name(d), d->type_id);
switch (d->kind) {
case SPL_DEF_VAR:
printf(" var=%s", d->var_def.name ? d->var_def.name : "?");
const char *def_kind_name = "null";
switch (node->kind) {
case SPL_DEF_ERROR:
def_kind_name = "error";
break;
case SPL_DEF_SCALAR:
def_kind_name = "scalar";
break;
case SPL_DEF_MEMBER:
printf(" member=%s", d->var_def.name ? d->var_def.name : "?");
def_kind_name = "member";
break;
case SPL_DEF_ALIAS:
case SPL_DEF_DISTINCT:
printf(" type=%s", d->type_def.name ? d->type_def.name : "?");
break;
case SPL_DEF_AGG:
printf(" agg{");
for (usize i = 0; i < d->agg_def.size; i++) {
if (i)
printf(",");
printf("%s", d->agg_def.data[i].name ? d->agg_def.data[i].name : "?");
}
printf("}");
case SPL_DEF_VAR:
def_kind_name = "var";
break;
case SPL_DEF_FN_PARAMS:
printf(" fn(");
for (usize i = 0; i < d->fn_params_def.size; i++) {
if (i)
printf(",");
printf("%s", d->fn_params_def.data[i].name ? d->fn_params_def.data[i].name : "?");
}
printf(")");
def_kind_name = "fn_params";
break;
default:
case SPL_DEF_AGG:
def_kind_name = "agg";
break;
case SPL_DEF_DISTINCT:
def_kind_name = "newtype";
break;
case SPL_DEF_ALIAS:
def_kind_name = "sametypes";
break;
}
printf("kind=%s type_id=%zu name=%s", def_kind_name, node->type_id,
node->name ? node->name : "?");
}

View File

@@ -2,28 +2,53 @@
#define __SPL_TYPE_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
typedef usize spl_type_id_t; /* 0 is error */
typedef VEC(spl_type_id_t) spl_type_id_vec_t;
typedef usize spl_def_id_t; /* 0 is error */
typedef VEC(spl_def_id_t) spl_def_id_vec_t;
typedef struct {
enum {
typedef enum {
SPL_TYPE_ERROR,
SPL_TYPE_VOID,
SPL_TYPE_BOOL,
SPL_TYPE_INT,
SPL_TYPE_FLOAT,
SPL_TYPE_UNDEFINED, // 自动配对任意类型的字面量,值为 undefined
SPL_TYPE_NULL, // 自动配对指针/切片的字面量,值为 0
SPL_TYPE_PTR,
SPL_TYPE_SLICE,
SPL_TYPE_RANGE,
SPL_TYPE_SLICE, // 未来拥有泛型后删除
SPL_TYPE_RANGE, // 未来拥有泛型后删除
SPL_TYPE_ARRAY,
SPL_TYPE_STRUCT,
SPL_TYPE_UNION,
SPL_TYPE_ENUM,
SPL_TYPE_FN,
SPL_TYPE_ID,
} kind;
} 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; // 回 AST member_decl 节点引用 dbg/IDE 定位用 不参与 hash
} 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;
@@ -39,11 +64,11 @@ typedef struct {
spl_type_id_t element;
usize len;
} array_type;
spl_type_id_vec_t agg_field_types;
spl_type_member_vec_t agg_members;
struct {
spl_type_id_vec_t variants;
spl_type_member_vec_t variants;
spl_type_id_t tag_type;
} enum_type; // ADT
} adt_type; // ADT
struct {
spl_type_id_vec_t params;
spl_type_id_t ret;
@@ -53,47 +78,30 @@ typedef struct {
} spl_type_node_t;
typedef VEC(spl_type_node_t) spl_type_node_vec_t;
typedef struct {
const char *name;
spl_def_id_t def_id;
spl_type_id_t type_id;
usize scope_id;
int is_const; /* var_def 是否为 const 声明(只读) */
} spl_var_def_t;
typedef VEC(spl_var_def_t) spl_var_def_vec_t;
typedef struct {
enum {
SPL_DEF_NONE,
SPL_DEF_BUILTIN,
typedef enum {
SPL_DEF_ERROR,
SPL_DEF_SCALAR,
SPL_DEF_MEMBER,
SPL_DEF_VAR,
SPL_DEF_FN_PARAMS,
SPL_DEF_AGG, // include enum variants
SPL_DEF_DISTINCT, // newtype
SPL_DEF_ALIAS, // sametypes
} kind;
} spl_def_node_kind_t;
typedef struct {
spl_def_node_kind_t kind;
const char *name;
spl_dbg_node_t dbg_node;
spl_type_id_t type_id;
union {
spl_var_def_t var_def;
spl_var_def_vec_t agg_def; // include enum variants
spl_var_def_vec_t fn_params_def;
spl_var_def_t type_def;
};
int source_loc;
enum {
SPL_FLAG_NONE,
} flag;
usize ast_node_ref;
} spl_def_node_t;
typedef VEC(spl_def_node_t) spl_def_node_vec_t;
/*
SPL 设计是严格区分类型做到类型和名称无关即
type (类型名) = (匿名类型)
好处是递归使用可以直接操作类型名的映射的提前分配的匿名类型的id
*/
typedef MAP(usize, spl_type_id_t) spl_type_node_map_t;
typedef struct {
spl_type_node_vec_t type_table;
spl_type_node_map_t type_map;
spl_def_node_vec_t def_table;
} spl_type_t;
@@ -103,22 +111,28 @@ void spl_type_drop(spl_type_t *type);
void spl_type_def_dump(spl_type_t *type, spl_def_id_t id);
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id);
spl_type_id_t spl_type_alloc(spl_type_t *type);
spl_type_node_t *spl_type_node(spl_type_t *type, spl_type_id_t id);
spl_def_id_t spl_type_def_alloc(spl_type_t *type);
spl_def_node_t *spl_type_def(spl_type_t *type, spl_def_id_t id);
spl_type_id_t spl_type_void(spl_type_t *type);
spl_type_id_t spl_type_bool(spl_type_t *type);
spl_type_id_t spl_type_int(spl_type_t *type, usize bits, int is_signed);
spl_type_id_t spl_type_float(spl_type_t *type, usize bits);
spl_type_id_t spl_type_ptr(spl_type_t *type, spl_type_id_t val);
spl_type_id_t spl_type_slice(spl_type_t *type, spl_type_id_t val);
spl_type_id_t spl_type_range(spl_type_t *type, spl_type_id_t val);
spl_type_id_t spl_type_array(spl_type_t *type, spl_type_id_t val, usize len);
spl_type_id_t spl_type_tid(spl_type_t *type, spl_type_id_t val);
spl_type_id_t spl_type_agg(spl_type_t *type, spl_type_id_vec_t fields);
spl_type_id_t spl_type_enum(spl_type_t *type, spl_type_id_vec_t variants, spl_type_id_t tag);
spl_type_id_t spl_type_fn(spl_type_t *type, spl_type_id_vec_t params, spl_type_id_t ret);
spl_type_id_t spl_type_def_alloc(spl_type_t *type, spl_def_node_kind_t kind, const char *name,
spl_dbg_node_t dbg, usize ast_node_ref);
void spl_type_def_resolve(spl_type_t *type, spl_def_id_t id, spl_type_id_t tid);
spl_type_id_t spl_type_fn_param_tid(spl_type_t *type, spl_type_id_t fn_tid, usize idx);
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);
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_slice(spl_type_t *type, spl_type_id_t element);
spl_type_id_t spl_type_builder_range(spl_type_t *type, spl_type_id_t element);
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,
const spl_type_member_t *members, usize nmembers,
spl_type_id_t tag_type, spl_type_layout_t layout);
#endif /* __SPL_TYPE_H__ */

View File

@@ -1,4 +1,4 @@
/* splc0.c SPL compiler CLI (stage 1, 引导用)
/* splc0.c - SPL compiler CLI (stage 1, 引导用)
*
* splc0 --dump tokens|ast|all <file> dump 前端产物
* splc0 <in> <out> 编译 (阶段 B 实现)
@@ -12,14 +12,23 @@
#include "spl_ast.h"
#include "spl_ast2ir.h"
#include "spl_ir2vm.h"
// #include "spl_ir2vm.h"
#include "spl_lexer.h"
#include "spl_sema.h"
#include "spl_tok.h"
typedef enum {
DUMP_NONE,
DUMP_TOKEN,
DUMP_AST,
DUMP_SEMA,
DUMP_IR,
} dump_t;
static char *read_file(const char *path, long *out_len) {
FILE *f = fopen(path, "rb");
if (!f) {
fprintf(stderr, "path `%s` ", path);
perror("fopen");
return NULL;
}
@@ -47,8 +56,7 @@ static const char *const tok_type_names[] = {
#undef X
};
static void dump_tokens(const char *src, const char *fname) {
spl_tok_vec_t toks = spl_lex(src, fname);
static void dump_tokens(spl_tok_vec_t toks) {
printf("tokens got (%zu)\n", toks.size);
for (usize i = 0; i < toks.size; i++) {
const spl_tok_t *t = &toks.data[i];
@@ -58,183 +66,52 @@ static void dump_tokens(const char *src, const char *fname) {
vec_free(toks);
}
static void dump_ast(const char *src, const char *fname) {
static int compile_spl(const char *src, const char *fname, const char *outpath, int gen_debug,
dump_t dump) {
spl_tok_vec_t toks = spl_lex(src, fname);
spl_ast_t ast;
spl_ast_init(&ast, &toks);
spl_ast_prase(&ast);
if (ast.parsed < 0) {
printf("parse failed, skip AST dump\n");
spl_ast_drop(&ast);
return;
}
spl_ast_valid(&ast);
spl_ast_dump(&ast, ast.root);
spl_ast_drop(&ast);
}
static void dump_sema(const char *src, const char *fname) {
spl_tok_vec_t toks = spl_lex(src, fname);
spl_ast_t ast;
spl_ast_init(&ast, &toks);
spl_ast_prase(&ast);
if (ast.parsed < 0) {
printf("parse failed, skip sema dump\n");
spl_ast_drop(&ast);
return;
}
spl_ast_valid(&ast);
spl_sema_t sema;
spl_sema_init(&sema);
sema.ast = &ast;
spl_sema_run(&sema);
spl_sema_check(&sema);
printf("Sema root_scope=%zu scopes=%zu errors=%d\n", sema.root_scope, sema.scopes.size,
sema.error_count);
for (usize i = 0; i < sema.scopes.size; i++) {
printf("scope[%zu] parent=%zu\n", i, sema.scopes.data[i].parent);
map_for(sema.scopes.data[i].symbols, mi) {
printf(" %s -> def#%zu\n", sema.scopes.data[i].symbols.data[mi].key,
sema.scopes.data[i].symbols.data[mi].val);
}
}
printf("TypeTable:\n");
for (usize i = 0; i < sema.type.type_table.size; i++) {
printf(" id#%zu type=", i);
spl_type_pure_dump(&sema.type, i);
printf("\n");
}
printf("DefTable:\n");
for (usize i = 0; i < sema.type.def_table.size; i++) {
printf(" def#%zu ", i);
spl_type_def_dump(&sema.type, i);
printf("\n");
}
spl_sema_drop(&sema);
spl_ast_drop(&ast);
}
static void dump_ir(const char *src, const char *fname) {
spl_tok_vec_t toks = spl_lex(src, fname);
spl_ast_t ast;
spl_ast_init(&ast, &toks);
spl_ast_prase(&ast);
if (ast.parsed < 0) {
printf("parse failed, skip IR\n");
spl_ast_drop(&ast);
return;
}
spl_ast_valid(&ast);
spl_sema_t sema;
spl_sema_init(&sema);
sema.ast = &ast;
spl_sema_run(&sema);
spl_sema_check(&sema);
if (sema.error_count) {
printf("sema errors=%d, skip IR\n", sema.error_count);
spl_sema_drop(&sema);
spl_ast_drop(&ast);
return;
}
spl_ast2ir_t a2ir;
spl_ast2ir_init(&a2ir, &sema);
spl_ast2ir_run(&a2ir);
if (a2ir.err_count)
printf("ast2ir errors=%d\n", a2ir.err_count);
spl_ir_dump(&a2ir.ir, &sema.type);
spl_ast2ir_drop(&a2ir);
spl_sema_drop(&sema);
spl_ast_drop(&ast);
}
static int cmd_dump(const char *flags, const char *path) {
long len;
char *src = read_file(path, &len);
if (!src)
return 1;
int do_tokens = strstr(flags, "tokens") != NULL || strcmp(flags, "all") == 0;
int do_ast = strstr(flags, "ast") != NULL || strcmp(flags, "all") == 0;
int do_sema = strstr(flags, "sema") != NULL || strcmp(flags, "all") == 0;
int do_ir = strstr(flags, "ir") != NULL || strcmp(flags, "all") == 0;
if (do_tokens)
dump_tokens(src, path);
if (do_ast)
dump_ast(src, path);
if (do_sema)
dump_sema(src, path);
if (do_ir)
dump_ir(src, path);
free(src);
if (dump == DUMP_TOKEN) {
dump_tokens(toks);
// memory leak
return 0;
}
static spl_ast_node_t *ast_node_at(spl_ast_t *ast, spl_ast_node_ref_t ref) {
if (ref == 0 || ref >= ast->buckets.size)
return NULL;
return &ast->buckets.data[ref];
}
static int ast_line(spl_ast_t *ast, spl_ast_node_ref_t ref) {
spl_ast_node_t *n = ast_node_at(ast, ref);
return n ? n->loc.line : 0;
}
/* -g在 .sir 尾部追加 debug 段文本IR 行 + VAR 行spl_cli -g 读取 */
static void gen_debug_map(const char *outpath, spl_ast_t *ast, const spl_ir_t *ir,
const spl_ir2vm_t *ir2vm) {
FILE *f = fopen(outpath, "ab");
if (!f)
return;
fprintf(f, "SPLDBG\n");
for (usize i = 0; i < ir2vm->fdbg.size; i++) {
const spl_ir2vm_fdbg_t *fd = &ir2vm->fdbg.data[i];
if (fd->fid >= ir->funcs.size)
continue;
const spl_ir_func_t *fn = &ir->funcs.data[fd->fid];
const char *fname = fn->name ? fn->name : "?";
for (usize ref = 1; ref < fd->node_first_ip.size; ref++) {
usize ip = fd->node_first_ip.data[ref];
if (ip == (usize)-1)
continue;
const spl_ir_node_t *n = &fn->nodes.data[ref];
fprintf(f, "IR %zu %zu %d %s\n", ip, ref, ast_line(ast, n->src_ref),
spl_ir_kind_name(n->kind));
}
for (usize j = 0; j < fn->dbg_vars.size; j++) {
const spl_ir_dbg_var_t *dv = &fn->dbg_vars.data[j];
if (!dv->name)
continue;
fprintf(f, "VAR %s %s %zu %zu %d\n", fname, dv->name, dv->offset, dv->tid,
dv->is_param);
}
}
fclose(f);
}
static int compile_spl(const char *src, const char *fname, const char *outpath, int gen_debug) {
spl_tok_vec_t toks = spl_lex(src, fname);
spl_ast_t ast;
spl_ast_init(&ast, &toks);
spl_ast_prase(&ast);
if (ast.parsed < 0) {
printf("parse failed, no output\n");
spl_ast_drop(&ast);
// memory leak
return 1;
}
spl_ast_valid(&ast);
// spl_ast_valid(&ast); TODO
if (dump == DUMP_AST) {
spl_ast_dump(&ast, ast.root);
// memory leak
return 0;
}
spl_sema_t sema;
spl_sema_init(&sema);
spl_type_t type;
spl_scope_t scope;
spl_type_init(&type);
spl_scope_init(&scope);
spl_sema_init(&sema, &ast, &type, &scope);
sema.ast = &ast;
spl_sema_run(&sema);
spl_sema_check(&sema);
if (sema.error_count) {
printf("sema errors=%d, no output\n", sema.error_count);
spl_sema_drop(&sema);
spl_ast_drop(&ast);
// memory leak
return 1;
}
if (dump == DUMP_SEMA) {
spl_sema_dump(&sema);
spl_ast_dump(&ast, ast.root);
// memory leak
return 0;
}
spl_ast2ir_t a2ir;
spl_ast2ir_init(&a2ir, &sema);
spl_ir_builder_t ir_builder;
spl_ir_builder_init(&ir_builder);
spl_ast2ir_init(&a2ir, &ir_builder, &sema);
spl_ast2ir_run(&a2ir);
if (a2ir.err_count) {
printf("ast2ir errors=%d, no output\n", a2ir.err_count);
@@ -243,16 +120,23 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_ast_drop(&ast);
return 1;
}
spl_ir2vm_t ir2vm;
spl_ir2vm_init(&ir2vm, &a2ir.ir, &sema.type);
int rc = spl_ir2vm_run(&ir2vm, outpath);
if (gen_debug && rc == 0)
gen_debug_map(outpath, &ast, &a2ir.ir, &ir2vm);
spl_ir2vm_drop(&ir2vm);
spl_ast2ir_drop(&a2ir);
spl_sema_drop(&sema);
spl_ast_drop(&ast);
return rc ? 1 : 0;
if (dump == DUMP_IR) {
spl_ir_dump(&ir_builder.ir, &type);
// memory leak
return 0;
}
// spl_ir2vm_t ir2vm;
// spl_ir2vm_init(&ir2vm, &a2ir.ir, &sema.type);
// int rc = spl_ir2vm_run(&ir2vm, outpath);
// if (gen_debug && rc == 0)
// gen_debug_map(outpath, &ast, &a2ir.ir, &ir2vm);
// spl_ir2vm_drop(&ir2vm);
// spl_ast2ir_drop(&a2ir);
// spl_sema_drop(&sema);
// spl_ast_drop(&ast);
// return rc ? 1 : 0;
return 0;
}
int main(int argc, char **argv) {
@@ -262,7 +146,7 @@ int main(int argc, char **argv) {
}
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: tokens,ast,sema,ir,all");
LOG_INFO("splc0 --dump <flags> <file> dump: lex,ast,sema,ir");
return 0;
}
int argi = 1;
@@ -270,12 +154,28 @@ int main(int argc, char **argv) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
dump_t dump = DUMP_NONE;
if (strcmp(argv[argi], "--dump") == 0) {
if (argc < argi + 3) {
LOG_INFO("splc0: --dump need <flags> <file>");
return 1;
}
return cmd_dump(argv[argi + 1], argv[argi + 2]);
const char *flags = argv[argi + 1];
if (strstr(flags, "lex") != NULL) {
dump = DUMP_TOKEN;
}
if (strstr(flags, "ast") != NULL) {
dump = DUMP_AST;
}
if (strstr(flags, "sema") != NULL) {
dump = DUMP_SEMA;
}
if (strstr(flags, "ir") != NULL) {
dump = DUMP_IR;
}
argi += 2;
}
/* splc0 [-g] <in> <out> */
if (argc < argi + 2) {
@@ -295,7 +195,7 @@ int main(int argc, char **argv) {
char *src = read_file(argv[argi], &len);
if (!src)
return 1;
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug);
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug, dump);
free(src);
return rc;
}