Compare commits

..

42 Commits

Author SHA1 Message Date
zzy
78d767bf21 stage0 修复windows函数没有进入宏包装 2026-08-14 20:42:11 +08:00
zzy
2a7db9e48c stage0 重命名字段 修复windows函数没有进入宏包装 2026-08-14 20:41:09 +08:00
zzy
c06d7247bb stage1 人工重构ast以及type部分 修复vm的UB行为 2026-08-14 18:10:58 +08:00
zzy
b0e6b406ac stage1 人工重构ast.c 2026-08-12 10:29:38 +08:00
zzy
314100afbc stage1 初步实现 2026-08-06 19:26:30 +08:00
zzy
a56b4cbb70 stage0 支持类gdb的调试vm手段 2026-08-06 09:11:15 +08:00
zzy
ca7cf221c8 stage1 修复设计问题 实现ir2vm 2026-08-05 19:13:48 +08:00
zzy
2ccee5f1cf stage1 修复设计问题 实现ast2ir 2026-08-05 08:14:23 +08:00
zzy
8ac59dfaa1 stage1 完成sema词法 2026-08-04 10:20:57 +08:00
zzy
74d7376039 stage1 完成ast 定义sema 2026-08-03 12:39:28 +08:00
zzy
a4ec5656d2 stage1 完整ast 部分ir 定义 2026-08-01 22:48:42 +08:00
zzy
b43042c88d stage1 重构代码 2026-08-01 21:15:47 +08:00
zzy
a77eade06f stage0 更改名称spl_ir -> spl_mcode spl_cli提供debug模式 提供临时语言规范 2026-07-29 12:05:18 +08:00
zzy
89d4bae8db stage1 修复错误 提供类型检查 2026-07-25 22:48:35 +08:00
zzy
02095524b1 stage1 修复错误 提供类型检查 2026-07-25 10:28:24 +08:00
zzy
da9dae734c stage1 修复错误 提供类型检查 2026-07-22 18:04:35 +08:00
zzy
a2d5dd9ce8 stage1 整理代码 修复错误 2026-07-21 20:00:19 +08:00
zzy
7c5bb41e09 stage1 整理代码 提供更多错误信息 2026-07-21 09:56:19 +08:00
zzy
459b6188a9 stage1 - 全面重构 stage1 编译器架构:类型系统(arena + items)、IR 发射层(spl_emit.h/c)、统一所有 emit 调用点。
- 实现 as 类型转换运算符、修复 &&/|| 短路求值 bug。
- 在 splc1.spl 中实现 Vec/Map/Emit 基础库(~50 个方法)。
- 修复实例方法调用中 self 参数被错误丢弃的 bug。
2026-07-20 20:53:41 +08:00
zzy
21f35b30fa stage1 重构代码 2026-07-20 12:10:55 +08:00
zzy
ab63c8ed90 stage1 修复vm 提供简单参数检查 修复聚合类型bug 2026-07-14 22:30:19 +08:00
zzy
f7f71c5f52 stage1 修复bug 2026-07-13 21:50:28 +08:00
zzy
b67edc5cee stage1 修复类型体内部函数前向引用时 CALL 地址错误 2026-07-12 22:16:17 +08:00
zzy
1ceda90207 stage1 修复类型重复解析 修复嵌套结构体字面量无限循环 2026-07-12 14:20:41 +08:00
zzy
9b9b25ce0f stage1 禁止隐式调用 修复bug 2026-07-12 11:43:27 +08:00
zzy
118c153280 stage1 优化重构代码 2026-07-12 10:01:57 +08:00
zzy
f1b4225c92 stage1 优化重构代码 2026-07-11 23:18:06 +08:00
zzy
53ae30f1ca stage1 重制18测试用例替换成match 完成现有全部测试 2026-07-11 21:24:52 +08:00
zzy
147f26e063 stage1 修复bug 删除递归测试 2026-07-08 11:45:45 +08:00
zzy
463177d3be stage1 修改部分测试 完成17-19测试 2026-07-07 12:11:49 +08:00
zzy
1df3e3bcb4 stage1 将数组和聚合类型使用byte offset而不是slot idx 2026-07-07 11:38:31 +08:00
zzy
3cf11f922e stage1 优化代码 完成16测试 2026-07-07 10:40:30 +08:00
zzy
69cea030dc stage1 完成15测试 2026-07-06 21:26:27 +08:00
zzy
0892c084ee stage1 完成14测试 2026-07-06 15:18:17 +08:00
zzy
ad473f245c stage1 完成11-13测试 2026-07-06 13:00:55 +08:00
zzy
0182b8ed5c stage1 完成09,10测试 2026-07-06 10:52:31 +08:00
zzy
777b6b42d1 stage1 完成07,08测试 2026-07-06 10:44:01 +08:00
zzy
5dadf6d6ee stage1 重构到 USIZE, 使得 vm 支持 usize, isize 2026-07-06 00:07:39 +08:00
zzy
67c8a137dd stage1 实现06测试 2026-07-05 22:47:00 +08:00
zzy
e2e0ebc21f stage1 重构测试且成功00-05 2026-07-05 21:45:43 +08:00
zzy
51d8510b79 stage1 部分功能测试00,01,02,06成功 2026-07-05 18:23:33 +08:00
zzy
50b07074fb stage0 2026-07-03 22:27:50 +08:00
42 changed files with 20060 additions and 0 deletions

8
.gitignore vendored
View File

@@ -2,3 +2,11 @@
!.gitignore
build/
*.sir
*.o
*.obj
*.exe
*.out

1216
SPL.md Normal file

File diff suppressed because it is too large Load Diff

417
build.py Normal file
View File

@@ -0,0 +1,417 @@
#!/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())

53
project_desc.py Normal file
View File

@@ -0,0 +1,53 @@
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_builtin.c",
# "stage1/spl_ast2ir.c",
# "stage1/spl_ir2vm.c",
]
exe = {
"spl_cli": ["stage0/spl_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": "spl_cli"},
"splc0d": {"compiler": "splc0", "runner": "spl_disasm"},
"splc1b": {"compiler": "splc0", "runner": "spl_cli"},
"splc1r": {"compiler": "splc1", "runner": "spl_cli"},
"splc1d": {"compiler": "splc1", "runner": "spl_disasm"},
"splc2b": {"compiler": "splc1", "runner": "spl_cli"},
"splc2r": {"compiler": "splc2", "runner": "spl_cli"},
"splc2d": {"compiler": "splc2", "runner": "spl_disasm"},
"splc3b": {"compiler": "splc2", "runner": "spl_cli"},
"splc3r": {"compiler": "splc3", "runner": "spl_cli"},
"splc3d": {"compiler": "splc3", "runner": "spl_disasm"},
"splc4b": {"compiler": "splc3", "runner": "spl_cli"},
"splc4r": {"compiler": "splc4", "runner": "spl_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"},
}

1994
stage0/include/acutest.h Normal file

File diff suppressed because it is too large Load Diff

61
stage0/include/color.h Normal file
View File

@@ -0,0 +1,61 @@
/**
* @file color.h
* @brief ANSI终端颜色控制码定义
*
* 提供跨平台的终端文本颜色和样式控制支持
*/
#ifndef __SCC_TERMINAL_COLOR_H__
#define __SCC_TERMINAL_COLOR_H__
/* clang-format off */
/// @name 前景色控制码
/// @{
#define ANSI_FG_BLACK "\33[30m" ///< 黑色前景
#define ANSI_FG_RED "\33[31m" ///< 红色前景
#define ANSI_FG_GREEN "\33[32m" ///< 绿色前景
#define ANSI_FG_YELLOW "\33[33m" ///< 黄色前景
#define ANSI_FG_BLUE "\33[34m" ///< 蓝色前景
#define ANSI_FG_MAGENTA "\33[35m" ///< 品红色前景
#define ANSI_FG_CYAN "\33[36m" ///< 青色前景
#define ANSI_FG_WHITE "\33[37m" ///< 白色前景
/// @}
/// @name 背景色控制码
/// @{
#define ANSI_BG_BLACK "\33[40m" ///< 黑色背景
#define ANSI_BG_RED "\33[41m" ///< 红色背景
#define ANSI_BG_GREEN "\33[42m" ///< 绿色背景
#define ANSI_BG_YELLOW "\33[43m" ///< 黄色背景
#define ANSI_BG_BLUE "\33[44m" ///< 蓝色背景
#define ANSI_BG_MAGENTA "\33[45m" ///< 品红色背景原始代码此处应为45m
#define ANSI_BG_CYAN "\33[46m" ///< 青色背景
#define ANSI_BG_WHITE "\33[47m" ///< 白色背景
/// @}
/// @name 文字样式控制码
/// @{
#define ANSI_UNDERLINED "\33[4m" ///< 下划线样式
#define ANSI_BOLD "\33[1m" ///< 粗体样式
#define ANSI_NONE "\33[0m" ///< 重置所有样式
/// @}
/* clang-format on */
/**
* @def ANSI_FMT
* @brief 安全文本格式化宏
* @param str 目标字符串
* @param fmt ANSI格式序列可组合多个样式
*
* @note 当定义ANSI_FMT_DISABLE时自动禁用颜色输出
* @code
* printf(ANSI_FMT("Warning!", ANSI_FG_YELLOW ANSI_BOLD));
* @endcode
*/
#ifndef ANSI_FMT_DISABLE
#define ANSI_FMT(str, fmt) fmt str ANSI_NONE ///< 启用样式包裹
#else
#define ANSI_FMT(str, fmt) str ///< 禁用样式输出
#endif
#endif /* __SCC_TERMINAL_COLOR_H__ */

173
stage0/include/core_map.h Normal file
View File

@@ -0,0 +1,173 @@
#ifndef __CORE_MAP_H__
#define __CORE_MAP_H__
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef nullptr
#define nullptr NULL
#endif
typedef uintptr_t usize;
typedef intptr_t isize;
#define MAP_TYPEOF __typeof__
/* 状态常量 */
#define __MAP_SLOT_EMPTY 0
#define __MAP_SLOT_OCCUPIED 1
#define __MAP_SLOT_DELETED 2
/* 默认负载因子 factor/128 */
#define MAP_DEFAULT_LOAD_FACTOR 70
/* ---------- 默认哈希/比较函数 ---------- */
#define MAP_HASH_INT(k) ((usize)((k) * 2654435761U))
#define MAP_CMP_INT(a, b) ((a) != (b))
static inline usize map_hash_str(const char *s) {
usize h = 5381;
while (*s)
h = ((h << 5) + h) + (unsigned char)*s++;
return h;
}
#define MAP_HASH_STR map_hash_str
#define MAP_CMP_STR strcmp
/* ---------- 数据结构宏 ---------- */
#define MAP_SLOT(key_t, val_t) \
struct { \
key_t key; \
val_t val; \
char state; \
}
#define MAP(key_t, val_t) \
struct { \
usize size; \
usize cap; \
MAP_SLOT(key_t, val_t) * data; \
usize (*hash)(key_t); \
int (*cmp)(key_t, key_t); \
}
/* ---------- 操作宏 ---------- */
/** 初始化,必须提供哈希和比较函数 */
#define map_init(map, hash_fn, cmp_fn) \
do { \
(map).size = 0; \
(map).cap = 0; \
(map).data = nullptr; \
(map).hash = (hash_fn); \
(map).cmp = (cmp_fn); \
} while (0)
/** 释放内部数组 */
#define map_free(map) \
do { \
free((map).data); \
(map).data = nullptr; \
(map).size = (map).cap = 0; \
} while (0)
/** 遍历所有有效元素 */
#define map_for(map, idx) \
for (usize(idx) = 0; (idx) < (map).cap; ++(idx)) \
if ((map).data[(idx)].state == __MAP_SLOT_OCCUPIED)
/**
* 插入(若键已存在则更新值)
* 注意:扩容使用 realloc失败会 abort可自行修改错误处理
*/
#define map_put(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) { \
(map).data[_idx].val = _val; \
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
*/
#define map_get(map, _key, out_val) \
(({ \
int _found = 0; \
if ((map).cap > 0) { \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _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; \
_found = 1; \
break; \
} \
_idx = (_idx + 1) & _mask; \
} \
} \
_found; \
}))
/**
* 删除指定键
*/
#define map_del(map, _key) \
do { \
if ((map).cap == 0) \
break; \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _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) { \
(map).data[_idx].state = __MAP_SLOT_DELETED; \
--(map).size; \
break; \
} \
_idx = (_idx + 1) & _mask; \
} \
} while (0)
#endif /* __CORE_MAP_H__ */

258
stage0/include/core_vec.h Normal file
View File

@@ -0,0 +1,258 @@
/**
* @file vec.h
* @brief 动态数组Dynamic Array实现
*
* 提供类型安全的动态数组容器实现,支持自动扩容和基本操作
*/
#ifndef __CORE_VEC_H__
#define __CORE_VEC_H__
#define __CORE_VEC_USE_STD__
#ifndef __CORE_VEC_USE_STD__
#include "core_log.h"
#include "core_impl.h"
#include "core_type.h"
#define __vec_realloc realloc
#define __vec_free free
#define __vec_memcpy memcpy
#else
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#ifndef nullptr
#define nullptr NULL
#endif
typedef size_t usize;
#define __vec_realloc realloc
#define __vec_free free
#define __vec_memcpy memcpy
#ifndef LOG_FATAL
#include <stdio.h>
#define LOG_FATAL(...) \
do { \
printf(__VA_ARGS__); \
abort(); \
} while (0)
#endif
#ifndef Assert
#include <assert.h>
#define Assert(cond) assert(cond)
#endif
#endif
/** @defgroup vec_struct 数据结构定义 */
/**
* @def VEC(type)
* @brief 声明向量结构体
* @param type 存储的数据类型
*
* 生成包含size/cap/data三个字段的结构体定义
* - size: 当前元素数量
* - cap: 数组容量
* - data: 存储数组指针
* @example
* VEC(char) string; <=> char[dynamic_array] string;
* struct people { VEC(char) name; int age; VEC(struct people) children;
* };
*/
#define VEC(type) \
struct { \
usize size; \
usize cap; \
type *data; \
}
/** @defgroup vec_operations 动态数组操作宏 */
/**
* @def vec_init(vec)
* @brief 初始化向量结构体
* @param vec 要初始化的向量结构体变量
*
* @note 此宏不会分配内存,仅做零初始化
*/
#define vec_init(vec) \
do { \
(vec).size = 0, (vec).cap = 0, (vec).data = 0; \
} while (0)
#define vec_realloc(vec, new_cap) \
do { \
void *data = __vec_realloc((vec).data, new_cap * sizeof(*(vec).data)); \
if (!data) { \
LOG_FATAL("vector_push: realloc failed\n"); \
} \
(vec).cap = new_cap; \
(vec).data = data; \
} while (0)
#define vec_size(vec) ((vec).size)
#define vec_cap(vec) ((vec).cap)
#define vec_for(vec, idx) for (usize idx = 0; idx < vec_size(vec); idx += 1)
/**
* @def vec_push(vec, value)
* @brief 添加元素到向量末尾
* @param vec 目标向量结构体
* @param value 要添加的值(需匹配存储类型)
*
* @note 当容量不足时自动扩容为2倍初始容量为4
* @warning 内存分配失败时会触发LOG_FATAL
*/
#define vec_push(vec, value) \
do { \
if ((vec).size >= (vec).cap) { \
usize cap = (vec).cap ? (vec).cap * 2 : 4; \
vec_realloc(vec, cap); \
} \
Assert((vec).data != nullptr); \
(vec).data[(vec).size++] = value; \
} while (0)
/**
* @def vec_pop(vec)
* @brief 弹出最后一个元素
* @param vec 目标向量结构体
* @return 最后元素的引用
* @warning 需确保size > 0时使用
*/
#define vec_pop(vec) ((vec).data[--(vec).size])
/**
* @def vec_at(vec, idx)
* @brief 获取指定索引元素
* @param vec 目标向量结构体
* @param idx 元素索引0 <= idx < size
* @return 对应元素的引用
*/
#define vec_at(vec, idx) (((vec).data)[idx])
/**
* @def vec_idx(vec, ptr)
* @brief 获取元素指针对应的索引
* @param vec 目标向量结构体
* @param ptr 元素指针需在data数组范围内
* @return 元素索引值
*/
#define vec_idx(vec, ptr) ((ptr) - (vec).data)
/**
* @def vec_free(vec)
* @brief 释放向量内存
* @param vec 目标向量结构体
*
* @note 释放后需重新初始化才能再次使用
*/
#define vec_free(vec) \
do { \
if ((vec).data == nullptr) \
break; \
__vec_free((vec).data); \
(vec).data = nullptr; \
(vec).size = (vec).cap = 0; \
} while (0)
#define vec_unsafe_get_data(vec) ((vec).data)
#define vec_unsafe_from_buffer(vec, buffer, buffer_size) \
do { \
(vec).size = buffer_size; \
(vec).cap = (vec).size; \
(vec).data = buffer; \
} while (0)
#define vec_unsafe_from_static_array(vec, array) \
do { \
(vec).size = sizeof(array) / sizeof((array)[0]); \
(vec).cap = (vec).size; \
(vec).data = array; \
} while (0)
/**
* @def vec_sized_realloc(vec, elem_size, new_cap)
* @brief 内部宏:按 elem_size 重新分配内存
*/
#define vec_sized_realloc(vec, elem_size, new_cap) \
do { \
void *new_data = __vec_realloc((vec).data, (new_cap) * (elem_size)); \
if (!new_data) \
LOG_FATAL("vec_sized_realloc: failed\n"); \
(vec).data = new_data; \
(vec).cap = new_cap; \
} while (0)
/**
* @def vec_sized_push(vec, elem_size, src_ptr)
* @brief 添加一个元素(从 src_ptr 拷贝 elem_size 字节)
* @param vec VEC(type) 定义的向量变量type 可为 char 或 void
* @param elem_size 每个元素占用的字节数
* @param src_ptr 源数据的指针
* @param copy_size 要拷贝的字节数
*
* @note 使用前需确保 vec.data 类型与 src_ptr 无关,内部会按字节拷贝。
* 推荐声明时为 `VEC(char)` 或 `VEC(unsigned char)`。
*/
#define vec_sized_push(vec, elem_size, src_ptr, copy_size) \
do { \
if ((vec).size >= (vec).cap) { \
usize new_cap = (vec).cap ? (vec).cap * 2 : 4; \
vec_sized_realloc(vec, elem_size, new_cap); \
} \
char *slot = (char *)(vec).data + (vec).size * (elem_size); \
__vec_memcpy(slot, (src_ptr), (copy_size)); \
(vec).size++; \
} while (0)
/**
* @def vec_sized_at_ptr(vec, elem_size, idx)
* @brief 获取第 idx 个元素的指针void*
* @return 指向元素的指针,需转换为具体类型使用
*/
#define vec_sized_at_ptr(vec, elem_size, idx) ((void *)((char *)(vec).data + (idx) * (elem_size)))
/**
* @def vec_sized_foreach(vec, elem_size, elem_ptr_var, block)
* @brief 遍历所有元素
* @param elem_ptr_var 循环内的变量名void* 类型)
* @param block 循环体语句块
*/
#define vec_sized_foreach(vec, elem_size, elem_ptr_var, block) \
do { \
for (usize __i = 0; __i < (vec).size; ++__i) { \
void *elem_ptr_var = vec_sized_at_ptr(vec, elem_size, __i); \
block; \
} \
} while (0)
/**
* @def vec_sized_pop(vec, elem_size)
* @brief 弹出最后一个元素(仅减小 size不返回数据
*/
#define vec_sized_pop(vec, elem_size) \
do { \
if ((vec).size == 0) \
LOG_FATAL("vec_sized_pop: empty\n"); \
(vec).size--; \
} while (0)
/**
* @def vec_sized_clear(vec)
* @brief 清空向量(重置 size = 0不释放内存
*/
#define vec_sized_clear(vec) ((vec).size = 0)
/**
* @def vec_sized_free(vec)
* @brief 释放向量内存(与原始 vec_free 相同,可复用)
* @note 注意:如果元素内部有堆资源,需在释放前自行遍历调用析构函数。
*/
#define vec_sized_free(vec) vec_free(vec)
#endif /* __CORE_VEC_H__ */

88
stage0/include/log.c Normal file
View File

@@ -0,0 +1,88 @@
#include "log.h"
static inline int log_snprintf(char *s, size_t n, const char *format, ...) {
int ret;
va_list args;
va_start(args, format);
ret = log_vsnprintf(s, n, format, args);
va_end(args);
return ret;
}
int log_default_handler(logger_t *module, log_level_t level, const char *file, int line,
const char *func, const char *fmt, ...) {
const char *level_str;
int offset = 0;
va_list args;
va_start(args, fmt);
/* clang-format off */
switch (level) {
case LOG_LEVEL_DEBUG: level_str = "DEBUG"; break;
case LOG_LEVEL_INFO: level_str = "INFO "; break;
case LOG_LEVEL_WARN: level_str = "WARN "; break;
case LOG_LEVEL_ERROR: level_str = "ERROR"; break;
case LOG_LEVEL_FATAL: level_str = "FATAL"; break;
case LOG_LEVEL_TRACE: level_str = "TRACE"; break;
default: level_str = "NOTSET"; break;
}
/// @note: 定义 __LOG_NO_COLOR__ 会取消颜色输出
#ifndef __LOG_NO_COLOR__
const char *color_code;
switch (level) {
case LOG_LEVEL_DEBUG: color_code = ANSI_FG_CYAN; break;
case LOG_LEVEL_INFO: color_code = ANSI_FG_GREEN; break;
case LOG_LEVEL_TRACE: color_code = ANSI_FG_BLUE; break;
case LOG_LEVEL_WARN: color_code = ANSI_FG_YELLOW; break;
case LOG_LEVEL_ERROR: color_code = ANSI_FG_RED; break;
case LOG_LEVEL_FATAL: color_code = ANSI_FG_RED ANSI_UNDERLINED; break;
default: color_code = ANSI_NONE;
}
/* clang-format on */
offset = log_snprintf(module->buf, sizeof(module->buf),
ANSI_BOLD "%s[%s] %s - %s:%d in %s()" ANSI_NONE " ", color_code,
level_str, module->name, file, line, func);
#else
offset = log_snprintf(module->buf, sizeof(module->buf), "[%s] %s - %s:%d in %s() ", level_str,
module->name, file, line, func);
#endif
/* 然后写入用户消息(如果有) */
if (fmt && fmt[0]) {
log_vsnprintf(module->buf + offset, sizeof(module->buf) - offset, fmt, args);
}
va_end(args);
log_puts(module->buf);
// for clangd warning
// clang-analyzer-deadcode.DeadStores
(void)color_code;
(void)level_str;
if (level & LOG_LEVEL_FATAL) {
log_abort();
}
return 0;
}
logger_t __default_logger_root = {
.name = "root",
.level = LOG_LEVEL_ALL,
.handler = log_default_handler,
};
void init_logger(logger_t *logger, const char *name) {
logger->name = name;
logger->handler = log_default_handler;
log_set_level(logger, LOG_LEVEL_ALL);
}
void log_set_level(logger_t *logger, int level) {
if (logger)
logger->level = level;
else
__default_logger_root.level = level;
}
void log_set_handler(logger_t *logger, log_handler handler) {
if (logger)
logger->handler = handler;
else
__default_logger_root.handler = handler;
}

193
stage0/include/log.h Normal file
View File

@@ -0,0 +1,193 @@
/**
* @file log.h
* @brief 日志系统核心模块(支持多级日志、断言和异常处理)
*/
#ifndef __SCC_LOG_IMPL_H__
#define __SCC_LOG_IMPL_H__
#include "color.h"
#include <stdarg.h>
#ifdef __SCC_LOG_IMPL_USE_STD_IMPL__
#include <stdio.h>
#include <stdlib.h>
#define log_vsnprintf vsnprintf
#define log_puts puts
#define log_abort() exit(1)
#endif
#ifdef __GNUC__ // GCC, Clang
#define __scc_log_unreachable() (__builtin_unreachable())
#elif defined _MSC_VER // MSVC
#define __scc_log_unreachable() (__assume(false))
#elif defined __SCC_BUILTIN_UNREACHEABLE__ // The SCC Compiler (my compiler)
#define __scc_log_unreachable() (__scc_builtin_unreachable())
#else
#define __scc_log_unreachable() ((void)0)
#endif
#ifndef log_vsnprintf
#define log_vsnprintf(...)
#warning "log_vsnprintf not defined"
#endif
#ifndef log_puts
#define log_puts(...)
#warning "log_puts not defined"
#endif
#ifndef log_abort
#define log_abort(...)
#warning "log_abort not defined"
#endif
/**
* @brief 日志级别枚举
*
* 定义日志系统的输出级别和组合标志位
*/
typedef enum log_level {
LOG_LEVEL_NOTSET = 0, ///< 未设置级别(继承默认配置)
LOG_LEVEL_DEBUG = 1 << 0, ///< 调试信息(开发阶段详细信息)
LOG_LEVEL_INFO = 1 << 1, ///< 常规信息(系统运行状态)
LOG_LEVEL_WARN = 1 << 2, ///< 警告信息(潜在问题提示)
LOG_LEVEL_ERROR = 1 << 3, ///< 错误信息(可恢复的错误)
LOG_LEVEL_FATAL = 1 << 4, ///< 致命错误(导致程序终止的严重错误)
LOG_LEVEL_TRACE = 1 << 5, ///< 追踪(性能追踪或者栈帧追踪)
LOG_LEVEL_ALL = 0xFF, ///< 全级别标志(组合所有日志级别)
} log_level_t;
#ifndef LOGGER_MAX_BUF_SIZE
#define LOGGER_MAX_BUF_SIZE 512 ///< 单条日志最大缓冲区尺寸
#endif
typedef struct logger logger_t;
typedef int (*log_handler)(logger_t *module, log_level_t level, const char *file, int line,
const char *func, const char *fmt, ...);
/**
* @brief 日志器实例结构体
*
* 每个日志器实例维护独立的配置和缓冲区
*/
struct logger {
const char *name; ///< 日志器名称(用于模块区分)
log_level_t level; ///< 当前设置的日志级别
union {
log_handler handler;
void *user_handler;
}; ///< 日志处理回调函数
void *user_data; ///< 用户自定义数据
char buf[LOGGER_MAX_BUF_SIZE]; ///< 格式化缓冲区
};
int log_default_handler(logger_t *module, log_level_t level, const char *file, int line,
const char *func, const char *fmt, ...);
extern logger_t __default_logger_root;
#ifndef LOG_DEFAULT_HANDLER
#define LOG_DEFAULT_HANDLER &__default_logger_root
#endif
/**
* @brief 初始化日志实例 其余参数设置为默认值
* @param[in] logger 日志器实例指针
* @param[in] name 日志器名称nullptr表示获取默认日志器名称
*/
void init_logger(logger_t *logger, const char *name);
/**
* @brief 设置日志级别
* @param[in] logger 目标日志器实例
* @param[in] level 要设置的日志级别(可组合多个级别)
*/
void log_set_level(logger_t *logger, int level);
/**
* @brief 设置自定义日志处理器
* @param[in] logger 目标日志器实例
* @param[in] handler 自定义处理函数nullptr恢复默认处理
*/
void log_set_handler(logger_t *logger, log_handler handler);
#ifndef LOG_MAX_MAROC_BUF_SIZE
#define LOG_MAX_MAROC_BUF_SIZE LOGGER_MAX_BUF_SIZE ///< 宏展开缓冲区尺寸
#endif
#define SCC_LOG_HANDLE_ARGS(_module_, _level_, ...) \
(_module_), (_level_), __FILE__, __LINE__, __func__, ##__VA_ARGS__
#define SCC_LOG_IMPL(_module_, _level_, _fmt_, ...) \
do { \
/* TODO check _module_ is nullptr */ \
if ((_module_)->handler && ((_module_)->level & (_level_))) \
(_module_)->handler(SCC_LOG_HANDLE_ARGS(_module_, _level_, _fmt_, ##__VA_ARGS__)); \
} while (0)
/* clang-format off */
/// @name 模块日志宏
/// @{
#define MLOG_NOTSET(module, ...)SCC_LOG_IMPL(module, LOG_LEVEL_NOTSET, __VA_ARGS__) ///< 未分类日志
#define MLOG_DEBUG(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_DEBUG, __VA_ARGS__) ///< 调试日志需启用DEBUG级别
#define MLOG_INFO(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_INFO, __VA_ARGS__) ///< 信息日志(常规运行日志)
#define MLOG_WARN(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_WARN, __VA_ARGS__) ///< 警告日志(潜在问题)
#define MLOG_ERROR(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_ERROR, __VA_ARGS__) ///< 错误日志(可恢复错误)
#define MLOG_FATAL(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_FATAL, __VA_ARGS__) ///< 致命错误日志(程序终止前)
#define MLOG_TRACE(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_TRACE, __VA_ARGS__) ///< 追踪日志(调用栈跟踪)
/// @}
/// @name 快捷日志宏
/// @{
#define LOG_NOTSET(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_NOTSET, __VA_ARGS__) ///< 未分类日志
#define LOG_DEBUG(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_DEBUG, __VA_ARGS__) ///< 调试日志需启用DEBUG级别
#define LOG_INFO(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_INFO, __VA_ARGS__) ///< 信息日志(常规运行日志)
#define LOG_WARN(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_WARN, __VA_ARGS__) ///< 警告日志(潜在问题)
#define LOG_ERROR(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_ERROR, __VA_ARGS__) ///< 错误日志(可恢复错误)
#define LOG_FATAL(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_FATAL, __VA_ARGS__) ///< 致命错误日志(程序终止前)
#define LOG_TRACE(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_TRACE, __VA_ARGS__) ///< 追踪日志(调用栈跟踪)
/// @}
/* clang-format on */
/**
* @def _Assert
* @brief 断言检查内部宏
* @param cond 检查条件表达式
* @param ... 错误信息参数(格式字符串+参数)
*/
#define _Assert(cond, ...) \
((void)((cond) || (__default_logger_root.handler(SCC_LOG_HANDLE_ARGS( \
&__default_logger_root, LOG_LEVEL_FATAL, __VA_ARGS__)), \
log_abort(), __scc_log_unreachable(), 0)))
/// @name 断言工具宏
/// @{
#define __INNERSCC_LOG_IMPL_STR(str) #str
#define _SCC_LOG_IMPL_STR(str) __INNERSCC_LOG_IMPL_STR(str)
#define AssertFmt(cond, format, ...) \
_Assert(cond, "Assertion Failure: " format, ##__VA_ARGS__) ///< 带格式的断言检查
#define PanicFmt(format, ...) _Assert(0, "Panic: " format, ##__VA_ARGS__) ///< 立即触发致命错误
#define Assert(cond) AssertFmt(cond, "cond is `" _SCC_LOG_IMPL_STR(cond) "`") ///< 基础断言检查
#define Panic(...) PanicFmt(__VA_ARGS__) ///< 触发致命错误(带自定义消息)
#define TODO() PanicFmt("TODO please implement me") ///< 标记未实现代码(触发致命错误)
#define UNREACHABLE() PanicFmt("UNREACHABLE") ///< 触发致命错误(代码不可达)
#define FIXME(str) PanicFmt("FIXME " _SCC_LOG_IMPL_STR(str)) ///< 提醒开发者修改代码(触发致命错误)
/// @}
/**
* @brief 静态断言(编译时)
*
* 利用数组大小不能为负的特性
* 或使用 _Static_assert (C11)
*/
#if __STDC_VERSION__ >= 201112L
#define StaticAssert _Static_assert
#else
#define StaticAssert(cond, msg) extern char __static_assertion[(cond) ? 1 : -1]
#endif
#ifdef __SCC_LOG_IMPL_IMPORT_SRC__
#include "log.c"
#endif
#endif /* __SCC_LOG_IMPL_H__ */

10
stage0/include/utils.h Normal file
View File

@@ -0,0 +1,10 @@
#ifndef __UTILS_H__
#define __UTILS_H__
#define __SCC_LOG_IMPL_USE_STD_IMPL__
#include "log.h"
#include "core_map.h"
#include "core_vec.h"
#endif /* __UTILS_H__ */

686
stage0/spl_cli.c Normal file
View File

@@ -0,0 +1,686 @@
/* spl_cli.c SIR VM launcher + gdb-style interactive debugger
*
* Usage: spl_cli [options] <file.sir> [args...]
* -d, --debug stack-canary checks
* -g, --debug-cli interactive debugger (REPL)
* --entry <name> entry function (default: main)
* --trace print every instruction
* -h, --help show help
*
* spl 程序 argvargv[0]=file.sirargv[1..]=args。
* REPL 配合 splc0 -g.sir 尾部内嵌 debug 段IR 行 + VAR 行)可显示
* 当前 IR 节点/源行/局部变量。
*/
#include "spl_mcode.h"
#include "spl_syscall.h"
#include "spl_vm.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ================================================================
* 命令行解析
* ================================================================ */
typedef struct {
int debug;
int debug_cli;
int trace;
const char *entry;
const char *path; /* file.sir */
const char **args; /* spl 程序参数file.sir 之后) */
int nargs;
} cli_opts_t;
static void usage(void) {
fprintf(stderr, "Usage: spl_cli [options] <file.sir> [args...]\n"
" -d, --debug stack-canary checks\n"
" -g, --debug-cli interactive debugger (REPL)\n"
" --entry <name> entry function (default: main)\n"
" --trace print every instruction\n"
" -h, --help show help\n");
}
/* options 可穿插;`--` 终止 option 解析(本身不作为 file/args
* 第一个非 option 为 file.sir其后为 spl args。 */
static int parse_args(int argc, const char **argv, cli_opts_t *o) {
memset(o, 0, sizeof *o);
o->entry = "main";
int i = 1;
for (; i < argc; i++) {
const char *a = argv[i];
if (a[0] == '-' && a[1]) {
if (strcmp(a, "--") == 0) {
i++;
break;
}
if (strcmp(a, "-d") == 0 || strcmp(a, "--debug") == 0) {
o->debug = 1;
} else if (strcmp(a, "-g") == 0 || strcmp(a, "--debug-cli") == 0) {
o->debug_cli = 1;
} else if (strcmp(a, "--trace") == 0) {
o->trace = 1;
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "spl_cli: --entry needs a name\n");
return -1;
}
o->entry = argv[++i];
} else if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
usage();
return -1;
} else {
fprintf(stderr, "spl_cli: unknown option '%s'\n", a);
usage();
return -1;
}
} else {
break;
}
}
/* 跳过前导 `--`pipeline 调用会带 `--` 分隔 file 与 args */
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
if (i >= argc) {
fprintf(stderr, "spl_cli: missing <file.sir>\n");
usage();
return -1;
}
o->path = argv[i++];
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
o->args = argv + i;
o->nargs = argc - i;
return 0;
}
/* ================================================================
* Debug mapsplc0 -g 追加在 .sir 尾部的文本段)
* IR <ip> <node_ref> <line> <kind>
* VAR <func> <name> <fp_offset> <tid> <is_param>
* ================================================================ */
typedef struct {
usize ip;
usize ref;
int line;
char kind[64];
} dbg_irline_t;
typedef VEC(dbg_irline_t) dbg_irline_vec_t;
typedef struct {
char func[128];
char name[128];
usize offset;
usize tid;
int is_param;
} dbg_var_t;
typedef VEC(dbg_var_t) dbg_var_vec_t;
typedef struct {
dbg_irline_vec_t irlines;
dbg_var_vec_t vars;
int loaded;
} dbg_map_t;
static void dbg_map_load(dbg_map_t *m, const char *text) {
memset(m, 0, sizeof *m);
vec_init(m->irlines);
vec_init(m->vars);
m->loaded = 0;
if (!text)
return;
const char *p = strstr(text, "SPLDBG");
if (!p)
return;
p += 6;
while (p && *p) {
const char *nl = strchr(p, '\n');
size_t len = nl ? (size_t)(nl - p) : strlen(p);
char line[512];
if (len >= sizeof line)
len = sizeof line - 1;
memcpy(line, p, len);
line[len] = 0;
if (strncmp(line, "IR ", 3) == 0) {
dbg_irline_t ir;
memset(&ir, 0, sizeof ir);
sscanf(line + 3, "%zu %zu %d %63s", &ir.ip, &ir.ref, &ir.line, ir.kind);
vec_push(m->irlines, ir);
} else if (strncmp(line, "VAR ", 4) == 0) {
dbg_var_t v;
memset(&v, 0, sizeof v);
sscanf(line + 4, "%127s %127s %zu %zu %d", v.func, v.name, &v.offset, &v.tid,
&v.is_param);
vec_push(m->vars, v);
}
if (!nl)
break;
p = nl + 1;
}
m->loaded = 1;
}
/* 当前 ip 所属 IR 节点行ip 恰好是某节点首指令) */
static const dbg_irline_t *irline_at_exact(dbg_map_t *m, usize ip) {
for (usize i = 0; i < m->irlines.size; i++)
if (m->irlines.data[i].ip == ip)
return &m->irlines.data[i];
return NULL;
}
/* ================================================================
* 调试器核心
* ================================================================ */
typedef struct {
spl_vm_t *vm;
spl_prog_t *prog;
const char *entry;
dbg_map_t map;
usize last_ptr; /* p 最近读到的值x 无参重读) */
int quit;
} dbg_t;
/* ---- 位置/指令显示辅助 ---- */
static const char *fn_name_at(spl_prog_t *prog, usize ip) {
for (usize i = 0; i < vec_size(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 : "?";
}
return "?";
}
/* ip 所在函数的指令范围 [*start, *end) */
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_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;
return;
}
}
}
/* 格式化一条指令(不含行号前缀) */
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) {
spl_vm_t *vm = d->vm;
if (vm->ip >= vec_size(vm->prog->insns)) {
printf(" (end of program)\n");
return;
}
char ib[80];
fmt_insn(&vec_at(vm->prog->insns, vm->ip), ib, sizeof ib);
printf(" %s @ ip=%zu %s [sp=%zu fp=%zu cp=%zu]\n", fn_name_at(vm->prog, vm->ip), vm->ip,
ib, vm->sp, vm->fp, vm->cp);
const dbg_irline_t *ir = irline_at_exact(&d->map, vm->ip);
if (ir)
printf(" -> ir node#%zu line %d %s\n", ir->ref, ir->line, ir->kind);
}
static void dbg_handle_status(dbg_t *d, int r) {
if (r == 1) {
printf(" program halted, exit_code=%d\n", d->vm->exit_code);
d->quit = 1;
} else if (r == 2) {
printf(" breakpoint hit\n");
} else if (r == -1) {
printf(" VM error: %s\n", d->vm->error_msg[0] ? d->vm->error_msg : "(no detail)");
d->quit = 1;
}
}
/* ---- 变量查找p / x 复用) ---- */
static dbg_var_t *dbg_find_var(dbg_t *d, const char *fn, const char *name) {
for (usize i = 0; i < d->map.vars.size; i++) {
dbg_var_t *v = &d->map.vars.data[i];
if (strcmp(v->func, fn) == 0 && strcmp(v->name, name) == 0)
return v;
}
return NULL;
}
/* ================================================================
* 命令
* ================================================================ */
static int cmd_help(dbg_t *d, const char *args);
static int cmd_run(dbg_t *d, const char *args);
static int cmd_step(dbg_t *d, const char *args);
static int cmd_next(dbg_t *d, const char *args);
static int cmd_finish(dbg_t *d, const char *args);
static int cmd_break(dbg_t *d, const char *args);
static int cmd_delete(dbg_t *d, const char *args);
static int cmd_info(dbg_t *d, const char *args);
static int cmd_list(dbg_t *d, const char *args);
static int cmd_backtrace(dbg_t *d, const char *args);
static int cmd_stack(dbg_t *d, const char *args);
static int cmd_x(dbg_t *d, const char *args);
static int cmd_p(dbg_t *d, const char *args);
static int cmd_quit(dbg_t *d, const char *args);
typedef struct {
const char *name;
const char *alias;
const char *usage;
const char *help;
int (*fn)(dbg_t *, const char *);
} dbg_cmd_t;
static const dbg_cmd_t cmds[] = {
/* 会话 */
{"help", "h", "[cmd]", "list commands / help", cmd_help},
{"quit", "q", "", "quit debugger", cmd_quit},
/* 执行 */
{"run", "r", "", "run to next breakpoint or exit", cmd_run},
{"continue", "c", "", "alias of run", cmd_run},
{"step", "s", "", "step one instruction (into calls)", cmd_step},
{"next", "n", "", "step over a call", cmd_next},
{"finish", "f", "", "run until current function returns", cmd_finish},
/* 断点 */
{"break", "b", "<fn|ip>", "set breakpoint (no arg: list)", cmd_break},
{"delete", "d", "", "clear all breakpoints", cmd_delete},
/* 信息 */
{"info", "i", "b|stack|locals|args|var", "breakpoints/stack/locals", cmd_info},
{"list", "l", "[N]", "disassemble ip±N of current function", cmd_list},
{"backtrace", "bt", "", "print call stack backtrace", cmd_backtrace},
{"stack", "st", "", "dump stack words", cmd_stack},
/* 内存/变量 */
{"x", "x", "<var|addr|fp+N>", "read memory (no arg: last pointer)", cmd_x},
{"print", "p", "<var>", "print local variable (needs splc0 -g)", cmd_p},
{NULL, NULL, NULL, NULL, NULL},
};
static const dbg_cmd_t *find_cmd(const char *name) {
for (const dbg_cmd_t *c = cmds; c->name; c++)
if (!strcmp(c->name, name) || (c->alias && !strcmp(c->alias, name)))
return c;
return NULL;
}
static int cmd_help(dbg_t *d, const char *args) {
(void)d;
if (*args) {
const dbg_cmd_t *c = find_cmd(args);
if (c) {
printf(" %-10s %-22s %s", c->name, c->usage, c->help);
if (c->alias)
printf(" (alias: %s)", c->alias);
printf("\n");
} else {
printf(" unknown command '%s'\n", args);
}
return 0;
}
printf("commands:\n");
for (const dbg_cmd_t *c = cmds; c->name; c++) {
printf(" %-10s %-22s %s", c->name, c->usage, c->help);
if (c->alias)
printf(" (alias: %s)", c->alias);
printf("\n");
}
return 0;
}
/* ---- 执行 ---- */
static int ip_is_breakpoint(dbg_t *d) {
for (usize i = 0; i < vec_size(d->vm->breakpoints); i++)
if (d->vm->breakpoints.data[i] == (usize)d->vm->ip)
return 1;
return 0;
}
static int cmd_run(dbg_t *d, const char *args) {
(void)args;
if (ip_is_breakpoint(d)) /* 越过当前断点指令,避免原地重停 */
spl_vm_skip_breakpoint(d->vm);
dbg_handle_status(d, spl_vm_run_until(d->vm, 0));
return 0;
}
static int cmd_step(dbg_t *d, const char *args) {
(void)args;
dbg_handle_status(d, spl_vm_run_once(d->vm));
return 0;
}
static int cmd_next(dbg_t *d, const char *args) {
(void)args;
/* 执行 1 条若进入被调cp 增),继续执行到返回原深度 */
usize base_cp = d->vm->cp;
int r = spl_vm_run_once(d->vm);
if (r)
return dbg_handle_status(d, r), 0;
while (d->vm->cp > base_cp) {
r = spl_vm_run_once(d->vm);
if (r)
return dbg_handle_status(d, r), 0;
}
return 0;
}
static int cmd_finish(dbg_t *d, const char *args) {
(void)args;
usize base_cp = d->vm->cp;
while (d->vm->cp >= base_cp) {
int r = spl_vm_run_once(d->vm);
if (r)
return dbg_handle_status(d, r), 0;
}
return 0;
}
/* ---- 断点 ---- */
static int is_all_digits(const char *s) {
if (!*s)
return 0;
for (; *s; s++)
if (!isdigit((unsigned char)*s))
return 0;
return 1;
}
static int cmd_break(dbg_t *d, const char *args) {
if (!*args) {
printf(" ip breakpoints:\n");
for (usize i = 0; i < vec_size(d->vm->breakpoints); i++)
printf(" %zu\n", d->vm->breakpoints.data[i]);
printf(" fn breakpoints:\n");
for (usize i = 0; i < vec_size(d->vm->fn_breakpoints); i++)
printf(" %s\n", d->vm->fn_breakpoints.data[i]);
return 0;
}
while (*args && isspace((unsigned char)*args))
args++;
if (is_all_digits(args)) {
usize ip = (usize)strtoul(args, NULL, 10);
spl_vm_add_breakpoint(d->vm, ip);
printf(" breakpoint at ip=%zu\n", ip);
} else {
spl_vm_add_breakpoint_fn(d->vm, args);
printf(" breakpoint at function '%s'\n", args);
}
return 0;
}
static int cmd_delete(dbg_t *d, const char *args) {
(void)args;
spl_vm_clear_breakpoints(d->vm);
printf(" breakpoints cleared\n");
return 0;
}
/* ---- 信息 ---- */
/* 列出当前函数变量args_flag=1 列参数local_flag=1 列局部 */
static void list_vars(dbg_t *d, int args_flag, int local_flag) {
if (!d->map.loaded) {
printf(" no debug info (compile with splc0 -g)\n");
return;
}
const char *fn = fn_name_at(d->prog, d->vm->ip);
int any = 0;
for (usize i = 0; i < d->map.vars.size; i++) {
dbg_var_t *v = &d->map.vars.data[i];
if (strcmp(v->func, fn) != 0)
continue;
if ((v->is_param && !args_flag) || (!v->is_param && !local_flag))
continue;
printf(" %-20s @ fp+%-5zu %s\n", v->name, v->offset, v->is_param ? "[param]" : "[local]");
any = 1;
}
if (!any)
printf(" (no matching variables in %s)\n", fn);
}
static int cmd_info(dbg_t *d, const char *args) {
while (*args && isspace((unsigned char)*args))
args++;
if (!strncmp(args, "b", 1) || !strncmp(args, "break", 5))
return cmd_break(d, "");
if (!strncmp(args, "st", 2) || !strncmp(args, "stack", 5))
spl_vm_stackdump(d->vm, d->vm->sp);
else if (!strncmp(args, "l", 1) || !strncmp(args, "local", 5))
list_vars(d, 0, 1);
else if (!strncmp(args, "a", 1) || !strncmp(args, "arg", 3))
list_vars(d, 1, 0);
else if (!strncmp(args, "v", 1) || !strncmp(args, "var", 3))
list_vars(d, 1, 1);
else
printf(" usage: info b|stack|locals|args|var\n");
return 0;
}
/* l [N]:当前函数内 ip±N 反汇编 */
static int cmd_list(dbg_t *d, const char *args) {
usize ip = d->vm->ip;
long half = 5;
if (*args)
half = strtol(args, NULL, 10);
if (half < 0)
half = 0;
usize fstart, fend;
cur_func_bounds(d->prog, ip, &fstart, &fend);
usize lo = (ip > (usize)half) ? ip - (usize)half : fstart;
usize hi = ip + (usize)half;
if (hi >= fend)
hi = fend - 1;
if (lo < fstart)
lo = fstart;
for (usize i = lo; i <= hi; i++) {
char ib[80];
fmt_insn(&vec_at(d->prog->insns, i), ib, sizeof ib);
printf("%s%6zu: %s", i == ip ? "=>" : " ", i, ib);
const dbg_irline_t *ir = irline_at_exact(&d->map, i);
if (ir)
printf(" || node#%zu line %d %s", ir->ref, ir->line, ir->kind);
printf("\n");
}
return 0;
}
static int cmd_backtrace(dbg_t *d, const char *args) {
(void)args;
spl_vm_backtrace(d->vm, d->vm->fp);
return 0;
}
static int cmd_stack(dbg_t *d, const char *args) {
(void)args;
spl_vm_stackdump(d->vm, d->vm->sp);
return 0;
}
/* ---- 内存 / 变量 ---- */
static int cmd_x(dbg_t *d, const char *args) {
while (*args && isspace((unsigned char)*args))
args++;
unsigned long long addr = 0;
if (*args) {
if (strncmp(args, "fp+", 3) == 0 || strncmp(args, "sp+", 3) == 0) {
int is_fp = args[0] == 'f';
unsigned long long off = strtoull(args + 3, NULL, 0);
addr = (uintptr_t)((char *)&d->vm->stacks.data[is_fp ? d->vm->fp : d->vm->sp] + off);
printf(" (%s+%llu)\n", is_fp ? "fp" : "sp", off);
} else if (d->map.loaded && !isdigit((unsigned char)*args)) {
const char *fn = fn_name_at(d->prog, d->vm->ip);
dbg_var_t *v = dbg_find_var(d, fn, args);
if (v) {
addr = (uintptr_t)((char *)&d->vm->stacks.data[d->vm->fp] + v->offset);
printf(" (%s @ fp+%zu)\n", v->name, v->offset);
} else {
printf(" no variable '%s' in %s\n", args, fn);
}
} else {
addr = strtoull(args, NULL, 0);
}
} else {
addr = (unsigned long long)d->last_ptr;
}
if (!addr) {
printf(" usage: x <var|addr|fp+N> (no arg: re-read last printed pointer)\n");
return 0;
}
unsigned char *sbase = (unsigned char *)d->vm->stacks.data;
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;
printf(" ");
for (int i = 0; i < 32; i++)
printf("%02x ", p[i]);
printf("\n");
return 0;
}
static int cmd_p(dbg_t *d, const char *args) {
while (*args && isspace((unsigned char)*args))
args++;
if (!*args) {
printf(" usage: p <varname>\n");
return 0;
}
if (!d->map.loaded) {
printf(" no debug info (compile with splc0 -g)\n");
return 0;
}
const char *fn = fn_name_at(d->prog, d->vm->ip);
dbg_var_t *v = dbg_find_var(d, fn, args);
if (!v) {
printf(" no variable '%s' in %s\n", args, fn);
return 0;
}
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;
}
static int cmd_quit(dbg_t *d, const char *args) {
(void)args;
d->quit = 1;
return 0;
}
static void repl_loop(dbg_t *d) {
char line[1024];
while (!d->quit) {
dbg_show_location(d);
printf("spl-dbg> ");
fflush(stdout);
if (!fgets(line, sizeof line, stdin))
break;
char *nl = strchr(line, '\n');
if (nl)
*nl = 0;
char *p = line;
while (*p && isspace((unsigned char)*p))
p++;
if (!*p)
continue;
/* 拆命令名 + 参数 */
char *sp = p;
while (*sp && !isspace((unsigned char)*sp))
sp++;
char saved = *sp;
*sp = 0;
const dbg_cmd_t *c = find_cmd(p);
*sp = saved;
char *args = sp;
while (*args && isspace((unsigned char)*args))
args++;
if (c) {
c->fn(d, args);
} else {
printf(" unknown command '%s' (h for help)\n", p);
}
}
}
int main(int argc, const char **argv) {
cli_opts_t o;
if (parse_args(argc, argv, &o) != 0)
return 1;
spl_prog_t prog;
if (spl_prog_load_from_file(o.path, &prog) != 0) {
fprintf(stderr, "spl_cli: cannot load '%s'\n", o.path);
return 1;
}
spl_syscall_register(&prog);
spl_vm_t vm;
spl_vm_init(&vm);
if (o.debug)
spl_vm_set_debug(&vm, 1);
if (o.trace)
spl_vm_set_trace(&vm, 1);
if (spl_vm_load_prog(&vm, &prog) != 0) {
fprintf(stderr, "spl_cli: failed to load prog\n");
spl_vm_drop(&vm);
spl_prog_drop(&prog);
return 1;
}
/* spl 程序 argvargv[0]=file.sir程序名argv[1..]=args */
const char **spl_argv = (const char **)malloc(sizeof(char *) * (size_t)(o.nargs + 1));
if (!spl_argv) {
spl_vm_drop(&vm);
spl_prog_drop(&prog);
return 1;
}
spl_argv[0] = o.path;
for (int i = 0; i < o.nargs; i++)
spl_argv[i + 1] = o.args[i];
if (spl_vm_prepare(&vm, o.entry, o.nargs + 1, spl_argv, NULL) != 0) {
fprintf(stderr, "spl_cli: entry point '%s' not found\n", o.entry);
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
return 1;
}
int ret = 0;
if (o.debug_cli) {
dbg_t d;
d.vm = &vm;
d.prog = &prog;
d.entry = o.entry;
d.quit = 0;
d.last_ptr = 0;
dbg_map_load(&d.map, prog.debug);
repl_loop(&d);
vec_free(d.map.irlines);
vec_free(d.map.vars);
} else {
ret = spl_vm_run_until(&vm, 0);
if (ret == 2)
fprintf(stderr, "spl_cli: hit breakpoint (run with -g to debug)\n");
}
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
if (ret < 0)
return 1;
return (int)vm.exit_code;
}

76
stage0/spl_disasm.c Normal file
View File

@@ -0,0 +1,76 @@
/* spl_disasm.c - SIR bytecode disassembler
*
* Usage: spl_disasm <file.sir>
*/
#include "spl_mcode.h"
#include <stdio.h>
int main(int argc, const char **argv) {
if (argc < 2) {
fprintf(stderr, "Usage: spl_disasm <file.sir>\n");
return 1;
}
spl_prog_t prog;
if (spl_prog_load_from_file(argv[1], &prog) != 0) {
fprintf(stderr, "spl_disasm: cannot load '%s'\n", argv[1]);
return 1;
}
printf(";; SPL bytecode dump: %s\n", argv[1]);
printf(";; ninsns=%zu nfuncs=%zu nnatives=%zu nstrs=%zu\n\n", vec_size(prog.insns),
vec_size(prog.funcs), vec_size(prog.natives), vec_size(prog.strtab));
if (vec_size(prog.funcs) > 0) {
printf(";; --- functions ---\n");
for (usize i = 0; i < vec_size(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);
}
printf("\n");
}
if (vec_size(prog.natives) > 0) {
printf(";; --- natives ---\n");
for (int i = 0; i < (int)vec_size(prog.natives); i++) {
spl_vm_native_t *n = &vec_at(prog.natives, i);
printf(" %s\n", n->name ? n->name : "(anon)");
}
printf("\n");
}
if (vec_size(prog.strtab) > 0) {
printf(";; --- string table ---\n");
for (int i = 0; i < (int)vec_size(prog.strtab); i++) {
printf(" %d: \"%s\"\n", i, vec_at(prog.strtab, i));
}
printf("\n");
}
printf(";; --- instructions ---\n");
for (usize i = 0; i < vec_size(prog.insns); i++) {
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_vm_type_kind_name((spl_type_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);
} else if (ins->opcode == SPL_CALL) {
printf(" ; nargs=%zd, from stack", (long long)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("\n");
}
spl_prog_drop(&prog);
return 0;
}

473
stage0/spl_mcode.c Normal file
View File

@@ -0,0 +1,473 @@
/* 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)
* [FUNCS] each: name_len(8) name(padded to 8) idx_of_strtab(8)
* nargs(8) ninsns(8) address(8)
* [INSTRS] each: opcode(2) type(2) imm(8) = 12 bytes
* [NATIVES] each: name_len(8) name(padded to 8) idx_of_strtab(8)
* [STRTAB] each: slen(8) str(slen bytes, padded to 8)
*/
#include "spl_mcode.h"
void spl_prog_init(spl_prog_t *prog) {
if (!prog)
return;
vec_init(prog->insns);
vec_init(prog->funcs);
vec_init(prog->natives);
vec_init(prog->strtab);
vec_init(prog->gdata);
map_init(prog->symtab, MAP_HASH_STR, MAP_CMP_STR);
}
void spl_prog_drop(spl_prog_t *prog) {
if (!prog)
return;
vec_free(prog->insns);
/* free each func name */
vec_for(prog->funcs, i) { free(vec_at(prog->funcs, i).name); }
vec_free(prog->funcs);
/* free each native name */
vec_for(prog->natives, i) { free(vec_at(prog->natives, i).name); }
vec_free(prog->natives);
/* free each gdata entry */
vec_for(prog->gdata, i) { free(vec_at(prog->gdata, i).data); }
vec_free(prog->gdata);
/* free each strtab entry */
vec_for(prog->strtab, i) { free((void *)vec_at(prog->strtab, i)); }
vec_free(prog->strtab);
map_free(prog->symtab);
free(prog->debug);
prog->debug = NULL;
}
/* ---- LE read/write helpers ---- */
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_vm_val_t v) {
*(*p)++ = (unsigned char)(v);
*(*p)++ = (unsigned char)(v >> 8);
*(*p)++ = (unsigned char)(v >> 16);
*(*p)++ = (unsigned char)(v >> 24);
*(*p)++ = (unsigned char)(v >> 32);
*(*p)++ = (unsigned char)(v >> 40);
*(*p)++ = (unsigned char)(v >> 48);
*(*p)++ = (unsigned char)(v >> 56);
}
/* Round n up to next multiple of 8 */
#define ALIGN8(n) (((n) + 7) & ~7)
int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
FILE *f;
unsigned char *data;
long len;
const unsigned char *p;
spl_vm_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
if (!fname || !prog)
return -1;
f = fopen(fname, "rb");
if (!f)
return -1;
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, 0, SEEK_SET);
if (len < 48) {
fclose(f);
return -1;
}
data = (unsigned char *)malloc((size_t)len);
if (!data) {
fclose(f);
return -1;
}
if (fread(data, 1, (size_t)len, f) != (size_t)len) {
free(data);
fclose(f);
return -1;
}
fclose(f);
p = data;
/* magic */
if (p[0] != 'S' || p[1] != 'P' || p[2] != 'L' || p[3] != 'B' || p[4] != 'I' || p[5] != 'N' ||
p[6] != '\0' || p[7] != '\0') {
free(data);
return -1;
}
p += 8;
spl_prog_init(prog);
/* header counts */
nfuncs = rd64(&p);
ninsns = rd64(&p);
nnatives = rd64(&p);
nstrs = rd64(&p);
ndata = rd64(&p);
/* ---- function table ---- */
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);
if (!func.name) {
free(data);
return -1;
}
memcpy(func.name, p, (usize)nlen);
p += (usize)nlen + pad;
func.idx_of_strtab = rd64(&p);
func.nargs = rd64(&p);
func.ninsns = rd64(&p);
func.address = rd64(&p);
vec_push(prog->funcs, func);
}
/* ---- instructions ---- */
for (spl_vm_val_t i = 0; i < ninsns; i++) {
if ((size_t)(p - data) + 12 > (size_t)len) {
free(data);
return -1;
}
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;
ins.imm = rd64(&p);
vec_push(prog->insns, ins);
}
/* ---- native table ---- */
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);
if (!nat.name) {
free(data);
return -1;
}
memcpy(nat.name, p, (usize)nlen);
p += (usize)nlen + pad;
nat.idx_of_strtab = rd64(&p);
nat.impl_fn = NULL; /* function pointer can't be serialised */
vec_push(prog->natives, nat);
}
/* ---- string table ---- */
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) {
free(data);
return -1;
}
memcpy(s, p, (usize)slen);
s[(usize)slen] = '\0';
p += (usize)slen + pad;
vec_push(prog->strtab, s);
}
/* ---- global data ---- */
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);
if (!entry.data) {
free(data);
return -1;
}
memcpy(entry.data, p, entry.size);
p += entry.size + pad;
vec_push(prog->gdata, entry);
}
/* ---- debug 段splc0 -g 追加在文件尾部) ---- */
prog->debug = NULL;
prog->debug_size = 0;
{
ptrdiff_t used = p - data;
if (used >= 0 && (usize)used < (usize)len) {
size_t dlen = (size_t)len - (size_t)used;
char *dbg = (char *)malloc(dlen + 1);
if (dbg) {
memcpy(dbg, data + used, dlen);
dbg[dlen] = 0;
prog->debug = dbg;
prog->debug_size = dlen;
}
}
}
free(data);
return 0;
}
int spl_prog_store_to_file(const char *fname, spl_prog_t *prog) {
unsigned char *buf, *p;
spl_vm_val_t i;
size_t total;
spl_vm_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
usize nlen, pad;
if (!fname || !prog)
return -1;
nfuncs = vec_size(prog->funcs);
ninsns = vec_size(prog->insns);
nnatives = vec_size(prog->natives);
nstrs = vec_size(prog->strtab);
ndata = vec_size(prog->gdata);
/* Calculate total size */
total = 8 /* magic */
+ 8 + 8 + 8 + 8 + 8; /* 5 counts (nfuncs+ninsns+nnatives+nstrs+ndata) */
/* funcs */
for (i = 0; i < nfuncs; i++) {
nlen = strlen(vec_at(prog->funcs, i).name) + 1; /* include null */
total +=
8 + ALIGN8(nlen) + 8 + 8 + 8 + 8; /* nlen + name(pad) + idx + nargs + ninsns + addr */
}
/* insns */
total += ninsns * 12; /* opcode(2) + type(2) + imm(8) */
/* natives */
for (i = 0; i < nnatives; i++) {
nlen = strlen(vec_at(prog->natives, i).name) + 1;
total += 8 + ALIGN8(nlen) + 8; /* nlen + name(pad) + idx_of_strtab */
}
/* strtab */
for (i = 0; i < nstrs; i++) {
nlen = strlen(vec_at(prog->strtab, i));
total += 8 + ALIGN8(nlen); /* slen + str(pad) */
}
/* gdata */
for (i = 0; i < ndata; i++) {
usize dsize = vec_at(prog->gdata, i).size;
total += 8 + ALIGN8(dsize); /* dsize + data(pad) */
}
buf = (unsigned char *)malloc(total);
if (!buf)
return -1;
p = buf;
/* magic */
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
/* counts */
wr64(&p, nfuncs);
wr64(&p, ninsns);
wr64(&p, nnatives);
wr64(&p, nstrs);
wr64(&p, ndata);
/* ---- function table ---- */
for (i = 0; i < nfuncs; i++) {
const char *name = vec_at(prog->funcs, i).name;
nlen = strlen(name) + 1;
pad = ALIGN8(nlen) - nlen;
wr64(&p, nlen);
memcpy(p, name, nlen);
p += nlen;
memset(p, 0, pad);
p += pad;
wr64(&p, vec_at(prog->funcs, i).idx_of_strtab);
wr64(&p, vec_at(prog->funcs, i).nargs);
wr64(&p, vec_at(prog->funcs, i).ninsns);
wr64(&p, vec_at(prog->funcs, i).address);
}
/* ---- instructions ---- */
for (i = 0; i < ninsns; 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);
*p++ = (unsigned char)(ins->type >> 8);
wr64(&p, ins->imm);
}
/* ---- native table ---- */
for (i = 0; i < nnatives; i++) {
const char *name = vec_at(prog->natives, i).name;
nlen = strlen(name) + 1;
pad = ALIGN8(nlen) - nlen;
wr64(&p, nlen);
memcpy(p, name, nlen);
p += nlen;
memset(p, 0, pad);
p += pad;
wr64(&p, vec_at(prog->natives, i).idx_of_strtab);
}
/* ---- string table ---- */
for (i = 0; i < nstrs; i++) {
const char *s = vec_at(prog->strtab, i);
nlen = strlen(s);
pad = ALIGN8(nlen) - nlen;
wr64(&p, nlen);
memcpy(p, s, nlen);
p += nlen;
memset(p, 0, pad);
p += pad;
}
/* ---- global data ---- */
for (i = 0; i < ndata; 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);
p += entry->size;
memset(p, 0, pad);
p += pad;
}
/* Write file */
FILE *f = fopen(fname, "wb");
if (!f) {
free(buf);
return -1;
}
fwrite(buf, 1, total, f);
fclose(f);
free(buf);
return 0;
}
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_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_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_vm_native_t *native) {
if (!prog || !native)
return 0;
vec_push(prog->natives, *native);
return vec_size(prog->natives);
}
int spl_prog_add_data(spl_prog_t *prog, void *ptr, usize size) {
spl_vm_gdata_t entry;
if (!prog)
return 0;
entry.data = (unsigned char *)malloc(size);
if (!entry.data)
return 0;
memcpy(entry.data, ptr, size);
entry.size = size;
vec_push(prog->gdata, entry);
return vec_size(prog->gdata);
}
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) {
const char *match_name = vec_at(prog->funcs, i).name;
if (match_name && strcmp(match_name, name) == 0) {
return &vec_at(prog->funcs, i);
}
}
return NULL;
}
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) {
const char *match_name = vec_at(prog->natives, i).name;
if (match_name && strcmp(match_name, name) == 0) {
return &vec_at(prog->natives, i);
}
}
return NULL;
}
const char *opcode_name[] = {
#define X(opcode, name, argc, pop, push, desc) [opcode] = name,
SPL_OPCODES(X)
#undef X
};
const char *spl_vm_opcode_name(spl_vm_opcode_t opcode) { return opcode_name[opcode]; }
const char *spl_vm_type_kind_name(spl_type_t type) {
switch (type) {
case SPL_VOID:
return "void";
case SPL_BOOL:
return "bool";
case SPL_I8:
return "i8";
case SPL_U8:
return "u8";
case SPL_I16:
return "i16";
case SPL_U16:
return "u16";
case SPL_I32:
return "i32";
case SPL_U32:
return "u32";
case SPL_I64:
return "i64";
case SPL_U64:
return "u64";
case SPL_F32:
return "f32";
case SPL_F64:
return "f64";
case SPL_USIZE:
return "usize";
case SPL_ISIZE:
return "isize";
case SPL_PTR:
return "ptr";
default:
return "???";
}
}
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_vm_type_kind_name((spl_type_t)ins->type));
printf(" %zd:%zx", ins->imm, ins->imm);
printf("\n");
}

220
stage0/spl_mcode.h Normal file
View File

@@ -0,0 +1,220 @@
/* spl_mcode.h - SPL VM Machine Code: instruction set and binary format
*/
#ifndef __SPL_MCODE_H__
#define __SPL_MCODE_H__
#include "include/core_map.h"
#include "include/core_vec.h"
#include <stddef.h>
#include <stdint.h>
typedef uintptr_t usize;
typedef intptr_t isize;
typedef enum {
SPL_VOID,
SPL_BOOL,
SPL_I8,
SPL_U8,
SPL_I16,
SPL_U16,
SPL_I32,
SPL_U32,
SPL_I64,
SPL_U64,
SPL_ISIZE,
SPL_USIZE,
SPL_F32,
SPL_F64,
SPL_PTR,
SPL_TYPE_COUNT,
} spl_type_t;
/* clang-format off */
#define SPL_OPCODES(X) \
/* opcode, name, argc, pop, push, desc */ \
X(SPL_ERROR, "error", 0, 0, 0, "invalid opcode / internal error") \
/* 栈操作 */ \
X(SPL_PUSH, "push", 1, 0, 1, "push immediate") \
X(SPL_DUP, "dup", 0, 0, 1, "duplicate top of stack") \
X(SPL_DROP, "drop", 0, 1, 0, "discard top of stack") \
X(SPL_SWAP, "swap", 0, 2, 2, "swap top two elements") \
X(SPL_PICK, "pick", 1, 0, 1, "push copy of stack[imm] (0=TOS)") \
X(SPL_ROT, "rot", 0, 3, 3, "rotate top three (a b c -- b c a)") \
/* 算术 */ \
X(SPL_ADD, "add", 0, 2, 1, "integer addition") \
X(SPL_SUB, "sub", 0, 2, 1, "integer subtraction") \
X(SPL_MUL, "mul", 0, 2, 1, "integer multiplication") \
X(SPL_DIV_S, "div_s", 0, 2, 1, "signed division") \
X(SPL_DIV_U, "div_u", 0, 2, 1, "unsigned division") \
X(SPL_REM_S, "rem_s", 0, 2, 1, "signed remainder") \
X(SPL_REM_U, "rem_u", 0, 2, 1, "unsigned remainder") \
X(SPL_NEG, "neg", 0, 1, 1, "two's complement negation") \
/* 位运算 */ \
X(SPL_AND, "and", 0, 2, 1, "bitwise AND") \
X(SPL_OR, "or", 0, 2, 1, "bitwise OR") \
X(SPL_XOR, "xor", 0, 2, 1, "bitwise XOR") \
X(SPL_NOT, "not", 0, 1, 1, "bitwise NOT") \
X(SPL_SHL, "shl", 0, 2, 1, "left shift") \
X(SPL_SHR_U, "shr_u", 0, 2, 1, "logical right shift (zero-fill)") \
X(SPL_SHR_S, "shr_s", 0, 2, 1, "arithmetic right shift (sign-fill)") \
/* 比较 */ \
X(SPL_EQ, "eq", 0, 2, 1, "equal") \
X(SPL_NE, "ne", 0, 2, 1, "not equal") \
X(SPL_SLT, "slt", 0, 2, 1, "signed less than") \
X(SPL_SLE, "sle", 0, 2, 1, "signed less or equal") \
X(SPL_ULT, "ult", 0, 2, 1, "unsigned less than") \
X(SPL_ULE, "ule", 0, 2, 1, "unsigned less or equal") \
X(SPL_SGT, "sgt", 0, 2, 1, "signed greater than") \
X(SPL_SGE, "sge", 0, 2, 1, "signed greater or equal") \
X(SPL_UGT, "ugt", 0, 2, 1, "unsigned greater than") \
X(SPL_UGE, "uge", 0, 2, 1, "unsigned greater or equal") \
/* 类型转换 */ \
X(SPL_TRUNC, "trunc", 1, 1, 1, "truncate to low imm bits") \
X(SPL_SEXT, "sext", 1, 1, 1, "sign-extend from bit imm") \
X(SPL_ZEXT, "zext", 1, 1, 1, "zero-extend from bit imm") \
/* 控制流 */ \
X(SPL_JMP, "jmp", 1, 0, 0, "unconditional jump (offset isize)") \
X(SPL_BZ, "bz", 1, 1, 0, "pop; jump if zero (offset isize)") \
X(SPL_BNZ, "bnz", 1, 1, 0, "pop; jump if non-zero (offset isize)") \
X(SPL_HALT, "halt", 0, 0, 0, "stop execution") \
/* 函数调用 */ \
X(SPL_CALL, "call", 1, 0, 0, "call function pop function offset, call it") \
X(SPL_CALLI, "calli", 0, 1, 0, "indirect call: pop function address, call it") \
X(SPL_RET, "ret", 0, 0, 0, "return from function") \
/* 栈帧局部变量 */ \
X(SPL_ALLOC, "alloc", 1, 0, 0, "allocate imm zero-slots on stack") \
X(SPL_LADDR, "laddr", 1, 0, 1, "push address of local at fp + imm bytes") \
X(SPL_GADDR, "gaddr", 1, 0, 1, "push address of global at gp + imm") \
/* 间接内存访问 */ \
X(SPL_LOAD, "load", 0, 1, 1, "load sizeof(type)-bits zero-extended") \
X(SPL_STORE, "store", 0, 2, 0, "store low sizeof(type)-bits") \
/* 原生接口 */ \
X(SPL_NCALL, "ncall", 1, 0, 1, "call native function by index") \
X(SPL_NLIB, "nlib", 1, 0, 0, "dlopen library (name idx)") \
/* 调试 */ \
X(SPL_BK, "breakpoint", 0, 0, 0, "break point when exec will stop run") \
X(SPL_DBG, "dbg", 0, 0, 0, "print VM debug info (stack, backtrace, locals)")
/* clang-format on */
typedef enum {
#define X(opcode, name, argc, pop, push, desc) opcode,
SPL_OPCODES(X)
#undef X
} spl_vm_opcode_t;
/*
* Binary format (all metadata fields spl_val_t LE):
* magic[8] = "SPLBIN\0\0"
* nfuncs, ninsns, nnatives, nstrs, ndata
* [func table] each: name_len, name(pad8), idx_of_strtab, nargs, ninsns, address
* [insns] each: opcode(2) type(2) imm(8) = 12 bytes
* [natives] each: name_len, name(pad8), idx_of_strtab
* [strtab] each: slen, str(pad8)
* [gdata] each: dsize(8), data(dsize bytes, padded to 8)
*
* === Calling Convention ===
*
* Before CALL:
* - args pushed left-to-right
* - target address pushed last
*
* CALL (imm = nargs):
* 1. pop target address
* 2. callstack[cp++] = {saved_fp, saved_ip, nargs}
* 3. fp = sp - nargs (fp points to arg0)
* 4. ip = target address
*
* ALLOC k:
* sp += k (slots zeroed; local[j] = stacks.data[fp + nargs + j])
*
* LADDR imm:
* push &stacks.data[fp + imm]
* (imm < nargs accesses args; imm >= nargs accesses locals)
*
* GADDR imm:
* push prog->gdata[imm] (pointer to global data blob)
*
* RET:
* 1. pop retval if non-void type
* 2. sp = fp
* 3. pop frame; fp = saved_fp, ip = saved_ip
* 4. push retval if non-void type
*
* CALLI (indirect call):
* - stack before: ..., arg0, ..., argN-1, nargs, func_addr
* 1. pop func_addr, then pop nargs
* 2. same as CALL steps 2-4
*/
#define SPL_BINFMT_MAGIC "SPLBIN\0\0"
// All SIR stack values are ptr-bit unsigned integers
typedef usize spl_vm_val_t;
typedef struct spl_vm_ins {
uint8_t opcode;
uint8_t type;
spl_vm_val_t imm;
} spl_vm_ins_t;
typedef VEC(spl_vm_ins_t) spl_vm_ins_vec_t;
typedef struct spl_vm_func {
char *name;
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_vm_val_t (*spl_vm_fn_t)(int nargs, spl_vm_val_t *args);
typedef struct spl_vm_native {
char *name;
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_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_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;
void spl_prog_init(spl_prog_t *prog);
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_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_vm_func_t *func);
int spl_prog_add_native(spl_prog_t *prog, spl_vm_native_t *native);
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_vm_opcode_name(spl_vm_opcode_t opcode);
const char *spl_vm_type_kind_name(spl_type_t type);
void spl_vm_ins_dump(spl_vm_ins_t *ins, spl_vm_val_t addr);
#endif /* __SPL_MCODE_H__ */

406
stage0/spl_syscall.c Normal file
View File

@@ -0,0 +1,406 @@
/* 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.
*
* Simple syscalls use the SYSCALL_N macros; complex ones are written
* manually but follow the same template.
*/
#include "spl_syscall.h"
#include "include/core_map.h"
#include "include/core_vec.h"
#include "spl_mcode.h"
#include "spl_vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* =================================================================
* Macro templates
*
* 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
* 3. Evaluates the expression and returns the result as spl_val_t
* ================================================================= */
#define CHECK_NARGS(fname, expected) \
do { \
if (nargs != (expected)) { \
fprintf(stderr, fname ": expected " #expected " args, got %d\n", nargs); \
return -1; \
} \
} while (0)
#define SYSCALL_0(name, ret_expr) \
static spl_vm_val_t name(int nargs, spl_vm_val_t *args) { \
CHECK_NARGS(#name, 0); \
(void)args; \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_1(name, t1, ret_expr) \
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_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_2(name, t1, t2, ret_expr) \
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_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_3(name, t1, t2, t3, ret_expr) \
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_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_4(name, t1, t2, t3, t4, ret_expr) \
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_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_vm_val_t)0))
/* vm_putchar - write a single character to stdout */
SYSCALL_1(vm_putchar, int, putchar(a1))
/* 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_vm_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 */
SYSCALL_2(vm_fopen, const char *, const char *, (uintptr_t)fopen(a1, a2))
/* 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 */
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 */
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_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_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_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) {
fprintf(stderr, "filepath can't be null");
return 0;
}
FILE *f = fopen(path, "rb");
if (!f) {
fprintf(stderr, "filepath %s can't be open", path);
return 1;
}
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = (char *)malloc((size_t)sz + 1);
if (!buf) {
fclose(f);
return 0;
}
size_t nread = fread(buf, 1, (size_t)sz, f);
fclose(f);
buf[nread] = '\0';
return (spl_vm_val_t)(uintptr_t)buf;
}
/* 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_vm_val_t)0))
/* vm_realloc - reallocate memory (realloc) */
SYSCALL_2(vm_realloc, void *, size_t, (uintptr_t)realloc(a1, a2))
/* vm_strlen - get string length */
SYSCALL_1(vm_strlen, const char *, strlen(a1))
/* vm_strcmp - compare two strings */
SYSCALL_2(vm_strcmp, const char *, const char *, strcmp(a1, a2))
/* vm_memcpy - copy memory, returns dst */
SYSCALL_3(vm_memcpy, void *, const void *, size_t, (memcpy(a1, a2, a3), (uintptr_t)a1))
static spl_vm_val_t vm_printf(int nargs, spl_vm_val_t *args) {
(void)args;
if (nargs <= 0) {
return 0;
}
const char *fmt = (const char *)args[0];
usize fmt_len = strlen(fmt);
typedef VEC(char) string_builder_t;
string_builder_t buffer;
vec_init(buffer);
if (nargs <= 1) {
printf("%s", fmt);
return nargs;
}
int arg_idx = 0;
char tmp_buf[32];
memset(tmp_buf, 0, sizeof(tmp_buf));
for (usize i = 0; i < fmt_len; ++i) {
if (fmt[i] != '%') {
vec_push(buffer, fmt[i]);
continue;
}
arg_idx += 1;
if (++i >= fmt_len) {
continue;
}
switch (fmt[i]) {
case '.': {
Assert(i + 2 < fmt_len && arg_idx + 1 <= nargs && fmt[i + 1] == '*' &&
fmt[i + 2] == 's');
for (usize j = 0; j < args[arg_idx]; ++j) {
vec_push(buffer, ((const char *)args[arg_idx + 1])[j]);
}
arg_idx += 1; /* %.*s 消耗 2 个实参len, data遇 % 已 +1这里补 1 */
i += 2;
} break;
case 'd':
snprintf(tmp_buf, sizeof(tmp_buf), "%zd", args[arg_idx]);
for (usize j = 0; j < strlen(tmp_buf); ++j) {
vec_push(buffer, tmp_buf[j]);
}
break;
case 'c':
vec_push(buffer, (char)args[arg_idx]);
break;
case 's':
for (usize j = 0; j < strlen((const char *)args[arg_idx]); ++j) {
vec_push(buffer, ((const char *)args[arg_idx])[j]);
}
break;
default:
continue;
}
}
vec_push(buffer, '\0');
printf("%s", buffer.data);
vec_free(buffer);
return nargs;
}
/* =================================================================
* 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_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_vm_val_t)(uintptr_t)vm;
}
/* 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)
return 0;
if (vm->prog) {
spl_prog_drop(vm->prog);
free(vm->prog);
vm->prog = NULL;
}
spl_vm_drop(vm);
free(vm);
return 0;
}
/* 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];
if (!vm || !path)
return -1;
spl_prog_t *prog = (spl_prog_t *)malloc(sizeof(spl_prog_t));
if (!prog)
return -1;
if (spl_prog_load_from_file(path, prog) != 0) {
free(prog);
return -1;
}
spl_syscall_register(prog);
if (spl_vm_load_prog(vm, prog) != 0) {
spl_prog_drop(prog);
free(prog);
return -1;
}
return (spl_vm_val_t)(uintptr_t)prog;
}
/* 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_vm_val_t val = args[1];
if (!vm)
return -1;
if (vm->sp >= vm->config.max_stack_depth) {
fprintf(stderr, "vm_push: stack overflow\n");
return -1;
}
vm->stacks.data[vm->sp++] = val;
return 0;
}
/* 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.
*
* Mirrors the CALL instruction's frame setup:
* - Pushes a sentinel frame (saved_ip=-1) if cp==0 so RET halts properly
* - Pushes the actual call frame
* - Sets fp = sp - nargs (so arg0 = data[fp], arg1 = data[fp+1], ...)
* - Sets ip to the function address
*/
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_vm_val_t call_nargs = args[2];
if (!vm || !name)
return -1;
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;
}
if (vm->cp >= vm->config.max_call_depth - 1) {
fprintf(stderr, "vm_call: call stack overflow\n");
return -1;
}
/* Sentinel frame so the entry function's RET halts cleanly */
if (vm->cp == 0) {
vm->frames.data[vm->cp].saved_fp = 0;
vm->frames.data[vm->cp].saved_ip = (uintptr_t)-1;
vm->frames.data[vm->cp].nargs = 0;
vm->cp++;
}
/* Actual call frame (same logic as the CALL instruction) */
vm->frames.data[vm->cp].saved_fp = vm->fp;
vm->frames.data[vm->cp].saved_ip = vm->ip;
vm->frames.data[vm->cp].nargs = call_nargs;
vm->cp++;
vm->fp = vm->sp - call_nargs;
vm->ip = (uintptr_t)func->address;
return 0;
}
/* vm_run - run a sub-VM to completion, returns exit_code */
SYSCALL_1(vm_run, spl_vm_t *, spl_vm_run_until(a1, 0))
/* =================================================================
* Registration
*
* Called after loading a .sir file. Matches native declarations in
* prog->natives against known syscall names and hooks up impl_fn.
* ================================================================= */
void spl_syscall_register(spl_prog_t *prog) {
static spl_vm_native_t table[] = {
/* OS operations */
{"vm_exit", 0, vm_exit},
{"vm_putchar", 0, vm_putchar},
{"vm_getchar", 0, vm_getchar},
{"vm_putint", 0, vm_putint},
{"vm_putstr", 0, vm_putstr},
{"vm_fopen", 0, vm_fopen},
{"vm_fclose", 0, vm_fclose},
{"vm_fread", 0, vm_fread},
{"vm_fwrite", 0, vm_fwrite},
{"vm_fsize", 0, vm_fsize},
{"vm_stdin", 0, vm_stdin},
{"vm_stdout", 0, vm_stdout},
{"vm_stderr", 0, vm_stderr},
{"vm_read_file", 0, vm_read_file},
{"vm_alloc", 0, vm_alloc},
{"vm_free", 0, vm_free},
{"vm_realloc", 0, vm_realloc},
{"vm_strlen", 0, vm_strlen},
{"vm_strcmp", 0, vm_strcmp},
{"vm_memcpy", 0, vm_memcpy},
{"vm_printf", 0, vm_printf},
/* VM operations (comptime) */
{"vm_new", 0, vm_new},
{"vm_drop", 0, vm_drop},
{"vm_load", 0, vm_load},
{"vm_push", 0, vm_push},
{"vm_call", 0, vm_call},
{"vm_run", 0, vm_run},
};
int n = (int)(sizeof(table) / sizeof(table[0]));
if (!prog)
return;
vec_for(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++) {
if (strcmp(nat->name, table[j].name) == 0) {
nat->impl_fn = table[j].impl_fn;
break;
}
}
}
}

22
stage0/spl_syscall.h Normal file
View File

@@ -0,0 +1,22 @@
/* 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.
*
* spl_syscall_register() must be called AFTER spl_prog_load_from_file()
* and BEFORE spl_vm_run_until(). It matches native declarations in the
* loaded program against known syscall names and hooks up the C
* implementations.
*/
#ifndef __SPL_SYSCALL_H__
#define __SPL_SYSCALL_H__
#include "spl_mcode.h"
/* Register all known built-in syscalls into prog->natives[].
* Entries whose name matches a known syscall get their impl_fn set;
* unmatched entries remain NULL (will error at runtime if called). */
void spl_syscall_register(spl_prog_t *prog);
#endif /* __SPL_SYSCALL_H__ */

1225
stage0/spl_vm.c Normal file

File diff suppressed because it is too large Load Diff

78
stage0/spl_vm.h Normal file
View File

@@ -0,0 +1,78 @@
/* spl_vm.h - SIR interpreter */
#ifndef __SPL_VM_H__
#define __SPL_VM_H__
#include "include/core_vec.h"
#include "spl_mcode.h"
#include <stdint.h>
#define SPL_STACK_CANARY ((spl_vm_val_t)0xDEADBEEFCAFEBABEull)
typedef struct {
uintptr_t saved_sp;
uintptr_t saved_fp;
uintptr_t saved_ip;
spl_vm_val_t nargs;
} spl_callframe_t;
typedef VEC(spl_vm_val_t) spl_stack_vec_t;
typedef VEC(spl_callframe_t) spl_frame_vec_t;
typedef struct {
spl_stack_vec_t stacks;
spl_frame_vec_t frames;
uintptr_t gp; // global pointer
uintptr_t sp; // stack pointer
uintptr_t fp; // frame pointer
uintptr_t cp; // call pointer
uintptr_t ip; // instr pointer
int exit_code;
int trace; /* non-zero to print each instruction */
int debug; /* non-zero to enable canary checks */
int debug_addr; /* non-zero to check for low-address memory access */
int skip_bp; /* non-zero: run_once 忽略下一次断点continue 越过当前断点指令) */
VEC(usize) breakpoints; /* ip 断点执行到该指令前暂停run_once 返回 2 */
VEC(char *) fn_breakpoints; /* 函数名断点CALL/CALLI 目标函数入口暂停) */
spl_prog_t *prog;
char error_msg[1024];
struct {
uintptr_t max_stack_depth;
uintptr_t max_call_depth;
} config;
} spl_vm_t;
/* Initialize VM with default sizes (SPL_DEFAULT_STACK_SIZE /
* SPL_DEFAULT_CALL_DEPTH) */
void spl_vm_init(spl_vm_t *vm);
/* Initialize VM with custom sizes (pass 0 to use defaults) */
void spl_vm_init_ex(spl_vm_t *vm, int stack_size, int call_depth);
/* Free dynamically allocated memory in VM */
void spl_vm_drop(spl_vm_t *vm);
int spl_vm_load_prog(spl_vm_t *vm, spl_prog_t *prog);
int spl_vm_prepare(spl_vm_t *vm, const char *entry, int argc, const char **argv, const char **envp);
/* Enable/disable instruction-level tracing */
void spl_vm_set_trace(spl_vm_t *vm, int enabled);
/* Enable/disable debug mode (stack canary protection) */
void spl_vm_set_debug(spl_vm_t *vm, int enabled);
int spl_vm_run_once(spl_vm_t *vm);
int spl_vm_run_until(spl_vm_t *vm, size_t step);
/* 断点ip 断点 / 函数名断点CALL/CALLI 目标函数入口)。命中时 run_once 返回 2。 */
void spl_vm_add_breakpoint(spl_vm_t *vm, usize ip);
void spl_vm_add_breakpoint_fn(spl_vm_t *vm, const char *name);
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_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__ */

878
stage0/test_spl_vm.c Normal file
View File

@@ -0,0 +1,878 @@
/* test_spl_vm.c unit tests for SPL VM using acutest.h
*
* Constructs SIR binaries, writes to temp files, loads via
* spl_prog_load_from_file, and runs via the spl_vm_t API.
*/
#include "include/acutest.h"
#include "spl_mcode.h"
#include "spl_vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ================================================================
* Binary-writing helpers (mirrors spl_mcode.c internal format)
* ================================================================ */
/* Write spl_val_t (8 LE bytes), advance pointer */
#define LE64(p, v) \
do { \
unsigned char *_p = (p); \
spl_vm_val_t _v = (spl_vm_val_t)(v); \
*_p++ = (unsigned char)(_v); \
*_p++ = (unsigned char)(_v >> 8); \
*_p++ = (unsigned char)(_v >> 16); \
*_p++ = (unsigned char)(_v >> 24); \
*_p++ = (unsigned char)(_v >> 32); \
*_p++ = (unsigned char)(_v >> 40); \
*_p++ = (unsigned char)(_v >> 48); \
*_p++ = (unsigned char)(_v >> 56); \
(p) = _p; \
} while (0)
/* Convenience: build spl_ins_t from raw fields */
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;
return x;
}
/* 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_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 */
+ 8 + nlen + npad + 8 + 8 + 8 + 8 /* func entry */
+ (size_t)ninsns * 12; /* instructions */
unsigned char *buf = (unsigned char *)malloc(sz);
unsigned char *p = buf;
memcpy(p, "SPLBIN\0\0", 8);
p += 8; /* magic */
LE64(p, 1); /* nfuncs */
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_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_vm_val_t)ninsns);
LE64(p, 0); /* address = 0 */
for (int i = 0; i < ninsns; i++) {
*p++ = (unsigned char)(instns[i].opcode);
*p++ = (unsigned char)(instns[i].opcode >> 8);
*p++ = (unsigned char)(instns[i].type);
*p++ = (unsigned char)(instns[i].type >> 8);
LE64(p, instns[i].imm);
}
*out_len = sz;
return buf;
}
/* ================================================================
* VM test helpers (file-based prog load)
* ================================================================ */
static const char *TMPFILE = "test_spl_vm_tmp.bin";
/* Write binary buffer to temp file */
static int write_temp(const unsigned char *bin, size_t len) {
FILE *f = fopen(TMPFILE, "wb");
if (!f)
return -1;
fwrite(bin, 1, len, f);
fclose(f);
return 0;
}
/* Run a single-function program, return exit code (or -1 on failure). */
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;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
if (spl_vm_load_prog(&vm, &prog) == 0) {
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1) /* halted normally */
rc = (int)vm.exit_code;
else if (ret == 0) /* still running (shouldn't happen with halt) */
rc = -2;
}
}
}
spl_vm_drop(&vm);
remove(TMPFILE);
free(bin);
return rc;
}
/* Run with native functions registered. */
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);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
for (int i = 0; i < nnatives; i++)
spl_prog_add_native(&prog, &natives[i]);
if (spl_vm_load_prog(&vm, &prog) == 0) {
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
else if (ret == 0)
rc = -2;
}
}
}
spl_vm_drop(&vm);
remove(TMPFILE);
free(bin);
return rc;
}
/* ================================================================
* Native function for NCALL tests
* ================================================================ */
static spl_vm_val_t native_add_impl(int nargs, spl_vm_val_t *args) {
return (nargs >= 2) ? args[0] + args[1] : 0;
}
/* ================================================================
* Stack tests
* ================================================================ */
void test_push_imm(void) {
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_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_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_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);
}
void test_pick(void) {
/* push 10, 20, 30, pick 1 -> copy 20, add -> 50 */
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);
}
/* ================================================================
* Arithmetic tests
* ================================================================ */
void test_add(void) {
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_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_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_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_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_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_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I64, 42), ins(SPL_RET, SPL_I64, 0)};
TEST_CHECK(run(p, 2) == 42);
}
/* ================================================================
* Bitwise tests
* ================================================================ */
void test_and(void) {
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_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_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_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_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_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_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);
}
/* ================================================================
* Comparison tests
* ================================================================ */
void test_eq(void) {
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_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_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_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_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_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_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_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_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_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);
}
/* ================================================================
* Control flow tests (relative offset)
* ================================================================ */
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_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);
}
void test_bz_bnz(void) {
/* push 0, bz +2 (skip to ret with 1) -> return 1 */
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_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);
}
/* ================================================================
* Memory tests (ALLOC, LADDR, LD, ST)
* ================================================================ */
void test_alloc_laddr_st64_ld64(void) {
/* alloc 1 local, laddr + st64 42, laddr + ld64 back -> 42 */
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 */
ins(SPL_STORE, SPL_I64, 0), /* 3: store */
ins(SPL_LADDR, SPL_VOID, 0), /* 4: addr of local[0] */
ins(SPL_LOAD, SPL_I64, 0), /* 5: load */
ins(SPL_RET, SPL_I64, 0) /* 6: ret */
};
TEST_CHECK(run(p, 7) == 42);
}
void test_alloc_zeroed(void) {
/* alloc 1 local, laddr + ld64 -> should be 0 (zero-initialized) */
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);
}
/* ================================================================
* Indirect memory load/store tests (stack-based, no heap)
* ================================================================ */
void test_ld_st64(void) {
/* alloc 8 slots, st64 42, ld64 back -> 42 */
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)};
TEST_CHECK(run(p, 7) == 42);
}
void test_ld_st32(void) {
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)};
TEST_CHECK(run(p, 7) == (int)0xAABBCCDD);
}
void test_ld_st16(void) {
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)};
TEST_CHECK(run(p, 7) == 0xBEEF);
}
void test_ld_st8(void) {
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)};
TEST_CHECK(run(p, 7) == 0xAB);
}
/* ================================================================
* Function call tests (relative offset CALL)
* ================================================================ */
void test_call_add(void) {
/*
* add(a, b) address 0, 6 insns, 2 args
* main() address 6, 5 insns, 0 args
*
* add (ip=0):
* laddr 0 ip=0 arg0 addr
* ld64 ip=1 load arg0
* laddr 1 ip=2 arg1 addr
* ld64 ip=3 load arg1
* add i64 ip=4
* ret i64 ip=5
*
* main (ip=6):
* push 10 ip=6
* push 20 ip=7
* push 0 ip=8 target address = add at 0
* call 2 ip=9 nargs=2
* ret i64 ip=10
*/
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_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)};
int nadd = (int)(sizeof(add_insns) / sizeof(add_insns[0]));
int nmain = (int)(sizeof(main_insns) / sizeof(main_insns[0]));
int ninsns_t = nadd + nmain;
size_t nlen0 = strlen("add") + 1;
size_t npad0 = ((nlen0 + 7) / 8) * 8 - nlen0;
size_t nlen1 = strlen("main") + 1;
size_t npad1 = ((nlen1 + 7) / 8) * 8 - nlen1;
size_t sz = 8 + 8 + 8 + 8 + 8 + 8 /* magic + 5 counts */
+ 8 + nlen0 + npad0 + 8 + 8 + 8 + 8 /* func 0 */
+ 8 + nlen1 + npad1 + 8 + 8 + 8 + 8 /* func 1 */
+ (size_t)ninsns_t * 12;
unsigned char *bin = (unsigned char *)malloc(sz);
unsigned char *p = bin;
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
LE64(p, 2);
LE64(p, (spl_vm_val_t)ninsns_t);
LE64(p, 0);
LE64(p, 0);
LE64(p, 0);
/* func[0]: "add" */
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_vm_val_t)nadd);
LE64(p, 0);
/* func[1]: "main" */
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_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);
*p++ = (unsigned char)(add_insns[i].opcode >> 8);
*p++ = (unsigned char)(add_insns[i].type);
*p++ = (unsigned char)(add_insns[i].type >> 8);
LE64(p, add_insns[i].imm);
}
for (int i = 0; i < nmain; i++) {
*p++ = (unsigned char)(main_insns[i].opcode);
*p++ = (unsigned char)(main_insns[i].opcode >> 8);
*p++ = (unsigned char)(main_insns[i].type);
*p++ = (unsigned char)(main_insns[i].type >> 8);
LE64(p, main_insns[i].imm);
}
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, sz) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == 30);
}
/* ================================================================
* CALLI test
* ================================================================ */
void test_calli(void) {
/*
* add (ip=0, 2 args):
* laddr 0 ip=0
* ld64 ip=1
* laddr 1 ip=2
* ld64 ip=3
* add i64 ip=4
* ret i64 ip=5
*
* main (ip=6, 0 args):
* push 10 ip=6
* push 20 ip=7
* push 2 ip=8 (nargs)
* push 0 ip=9 (address of add)
* calli ip=10
* ret i64 ip=11
*/
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_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)};
int ninsns_t = 6 + 6;
size_t nlen0 = strlen("add") + 1;
size_t npad0 = ((nlen0 + 7) / 8) * 8 - nlen0;
size_t nlen1 = strlen("main") + 1;
size_t npad1 = ((nlen1 + 7) / 8) * 8 - nlen1;
size_t sz = 8 + 8 + 8 + 8 + 8 + 8 + 8 + nlen0 + npad0 + 8 + 8 + 8 + 8 + 8 + nlen1 + npad1 + 8 +
8 + 8 + 8 + (size_t)ninsns_t * 12;
unsigned char *bin = (unsigned char *)malloc(sz);
unsigned char *p = bin;
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
LE64(p, 2);
LE64(p, (spl_vm_val_t)ninsns_t);
LE64(p, 0);
LE64(p, 0);
LE64(p, 0);
/* func[0]: add */
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, 6);
LE64(p, 0);
/* func[1]: main */
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, 6);
LE64(p, 6);
for (int i = 0; i < 6; i++) {
*p++ = (unsigned char)(add_insns[i].opcode);
*p++ = (unsigned char)(add_insns[i].opcode >> 8);
*p++ = (unsigned char)(add_insns[i].type);
*p++ = (unsigned char)(add_insns[i].type >> 8);
LE64(p, add_insns[i].imm);
}
for (int i = 0; i < 6; i++) {
*p++ = (unsigned char)(main_insns[i].opcode);
*p++ = (unsigned char)(main_insns[i].opcode >> 8);
*p++ = (unsigned char)(main_insns[i].type);
*p++ = (unsigned char)(main_insns[i].type >> 8);
LE64(p, main_insns[i].imm);
}
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, sz) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == 30);
}
/* ================================================================
* Global data (GADDR) test
* ================================================================ */
void test_gaddr_ld32(void) {
/* Load program, add global data, GADDR + LD32 to read it back */
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);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
uint32_t val = 0xDEADBEEF;
spl_prog_add_data(&prog, &val, sizeof(val));
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == (int)0xDEADBEEF);
}
void test_gaddr_multi(void) {
/* Two global data entries: read second one via GADDR 1 */
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);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
uint32_t a = 0xAAAAAAAA, b = 0xBBBBBBBB;
spl_prog_add_data(&prog, &a, sizeof(a));
spl_prog_add_data(&prog, &b, sizeof(b));
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == (int)0xBBBBBBBB);
}
/* ================================================================
* Native call test
* ================================================================ */
void test_ncall(void) {
/* main() -> i32 { return native_add(30, 12); } */
/* NCALL imm = nargs, native index is pushed separately */
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_vm_native_t nat[] = {{"native_add", 0, native_add_impl}};
TEST_CHECK(run_with_natives(p, 5, nat, 1) == 42);
}
/* ================================================================
* Type conversion tests
* ================================================================ */
void test_trunc(void) {
/* push 0xABCD, trunc to 8 bits -> 0xCD */
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_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_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);
}
/* ================================================================
* Extended arithmetic tests (unsigned div/rem)
* ================================================================ */
void test_div_u(void) {
/* unsigned: 100 / 3 = 33 */
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_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);
}
/* ================================================================
* Edge case tests
* ================================================================ */
void test_many_ops(void) {
/* (1+2) * (3+4) = 21 */
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_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 77), ins(SPL_HALT, SPL_VOID, 0)};
TEST_CHECK(run(p, 2) == 0);
}
/* ================================================================
* Bad program tests
* ================================================================ */
void test_bad_magic(void) {
unsigned char bad[8] = {0, 0, 0, 0, 0, 0, 0, 0};
spl_prog_t prog;
if (write_temp(bad, 8) == 0) {
TEST_CHECK(spl_prog_load_from_file(TMPFILE, &prog) != 0);
remove(TMPFILE);
}
}
void test_empty(void) {
TEST_CHECK(spl_prog_load_from_file("nonexistent_file_xyz.bin", NULL) != 0);
}
/* ================================================================
* Test list
* ================================================================ */
TEST_LIST = {
{"push", test_push_imm},
{"dup", test_dup},
{"drop", test_drop},
{"swap", test_swap},
{"pick", test_pick},
{"add", test_add},
{"sub", test_sub},
{"mul", test_mul},
{"div", test_div},
{"rem", test_rem},
{"neg", test_neg},
{"i64_arith", test_i64_arith},
{"and", test_and},
{"or", test_or},
{"xor", test_xor},
{"not", test_not},
{"shl", test_shl},
{"shr", test_shr},
{"shr_s", test_shr_s},
{"eq", test_eq},
{"neq", test_neq},
{"lt", test_lt},
{"gt_signed", test_gt_signed},
{"sle", test_sle},
{"sge", test_sge},
{"ult", test_ult},
{"ule", test_ule},
{"ugt", test_ugt},
{"uge", test_uge},
{"jmp", test_jmp},
{"bz_bnz", test_bz_bnz},
{"alloc_laddr_ld_st", test_alloc_laddr_st64_ld64},
{"alloc_zeroed", test_alloc_zeroed},
{"call_add", test_call_add},
{"calli", test_calli},
{"gaddr_ld32", test_gaddr_ld32},
{"gaddr_multi", test_gaddr_multi},
{"ncall", test_ncall},
{"div_u", test_div_u},
{"rem_u", test_rem_u},
{"trunc", test_trunc},
{"sext", test_sext},
{"zext", test_zext},
{"ld_st8", test_ld_st8},
{"ld_st16", test_ld_st16},
{"ld_st32", test_ld_st32},
{"ld_st64", test_ld_st64},
{"many_ops", test_many_ops},
{"halt", test_halt},
{"bad_magic", test_bad_magic},
{"empty", test_empty},
{NULL, NULL},
};

2145
stage1/spl_ast.c Normal file

File diff suppressed because it is too large Load Diff

321
stage1/spl_ast.h Normal file
View File

@@ -0,0 +1,321 @@
#ifndef __SPL_AST_H__
#define __SPL_AST_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_lexer.h"
#include "spl_tok.h"
/* clang-format off */
#define SPL_AST_KIND_TABLE \
X(SPL_AST_NONE, V0, none) \
X(SPL_AST_CONTAINER_ITEM, V0, container_item) \
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_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) \
/* 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;
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;
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_dbg_node_t dbg;
usize resolved_def_id;
union {
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
spl_ast_node_ref_vec_t members; /* container_decl 列表 */
} container_item;
struct {
const char *ident;
spl_ast_node_ref_vec_t expr_list;
} attr_item;
struct {
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; /* 语句/尾表达式 */
} fn_decl;
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
const char *name;
spl_ast_node_ref_t type_expr;
} param_decl;
struct {
const char *name;
spl_ast_node_ref_t type_expr;
} type_decl;
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
const char *name;
spl_ast_node_ref_t type_expr;
} member_decl;
struct {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
const char *name;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t expr;
} var_const_decl;
/* 语句数据kind 决定解释哪个成员 */
struct {
spl_ast_node_ref_t expr;
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; /* 语句 */
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; /* 语句 */
} while_statement;
struct {
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; /* 语句 */
} 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; /* 语句 */
} match_statement;
struct {
spl_ast_node_ref_t expr;
} ret_statement;
struct {
} break_statement;
struct {
} continue_statement;
struct {
spl_ast_node_ref_vec_t block_or_statement; /* 语句 */
} defer_statement;
struct {
const char *ident;
const char *bind_ident;
spl_ast_node_ref_t expr;
} packed_expr;
struct {
spl_ast_node_ref_t left;
spl_ast_node_ref_t right;
} op_expr;
struct {
spl_ast_node_ref_t postfix_expr;
} prefix_expr;
struct {
spl_ast_node_ref_t primary_expr;
union {
spl_ast_node_ref_vec_t call_expr;
const char *field_expr; /* field/method */
spl_ast_node_ref_t index_expr;
struct {
spl_ast_node_ref_t begin;
spl_ast_node_ref_t end;
} slice_expr;
spl_ast_node_ref_t type_expr;
};
} postfix_expr;
struct {
isize integer_expr;
double float_expr;
char char_lit_expr;
const char *string_lit_expr; /* parsed c string */
const char *ident;
struct {
const char *name;
spl_ast_node_ref_vec_t expr; /* aggregate_init_item */
} aggregate_init;
spl_ast_node_ref_t expr;
struct {
isize integer;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_vec_t expr_list;
} array_lit_expr;
struct {
const char *ident;
spl_ast_node_ref_vec_t expr_list;
} builtin_expr;
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 attr_list; /* attr_item */
union {
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;
} fn_type;
spl_ast_node_ref_vec_t aggregate_list; /* container_decl */
};
} type_expr;
};
};
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 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);
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);
#endif /* __SPL_AST_H__ */

3248
stage1/spl_ast2ir.c Normal file

File diff suppressed because it is too large Load Diff

26
stage1/spl_ast2ir.h Normal file
View File

@@ -0,0 +1,26 @@
#ifndef __SPL_AST2IR_H__
#define __SPL_AST2IR_H__
#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 节点索引 */
int err_count;
} spl_ast2ir_t;
void spl_ast2ir_init(spl_ast2ir_t *ast2ir, const spl_sema_t *sema);
void spl_ast2ir_drop(spl_ast2ir_t *ast2ir);
void spl_ast2ir_run(spl_ast2ir_t *ast2ir);
#endif /* __SPL_AST2IR_H__ */

19
stage1/spl_dbg.h Normal file
View File

@@ -0,0 +1,19 @@
#ifndef __SPL_DBG_H__
#define __SPL_DBG_H__
#include "spl_tok.h"
typedef struct {
const char *fname;
int line;
int col;
const char *dbg_name;
// TODO
} spl_dbg_node_t;
#define SPL_FATAL(tok, fmt, ...) \
LOG_FATAL("fatal at %s:%zd:%zd " fmt, ((tok) && (tok)->fname ? (tok)->fname : "<null>"), \
((tok) ? (tok)->line : 0), ((tok) ? (tok)->col : 0), ##__VA_ARGS__)
#endif /* __SPL_DBG_H__ */

26
stage1/spl_dumptree.c Normal file
View File

@@ -0,0 +1,26 @@
/* spl_dumptree.c 可配置的树形打印模块(只用基本 ASCII*/
#include "spl_dumptree.h"
#include <stdarg.h>
const spl_dumptree_style_t spl_dumptree_ascii_style = {
"| ",
"|-",
"`-",
" ",
};
void spl_dumptree_print(const spl_dumptree_style_t *st, const char *prefix, int is_last,
const char *fmt, ...) {
va_list ap;
printf("%s%s ", prefix, is_last ? st->last_branch : st->branch);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf("\n");
}
void spl_dumptree_child_prefix(const spl_dumptree_style_t *st, const char *prefix, int is_last,
char *out, size_t cap) {
snprintf(out, cap, "%s%s", prefix, is_last ? st->space : st->vertical);
}

31
stage1/spl_dumptree.h Normal file
View File

@@ -0,0 +1,31 @@
/* spl_dumptree.h 可配置的树形打印模块(只用基本 ASCII*/
#ifndef __SPL_DUMPTREE_H__
#define __SPL_DUMPTREE_H__
#include <stddef.h>
#include <stdio.h>
/* 可配置的缩进字符串 */
typedef struct {
const char *vertical; /* "| " */
const char *branch; /* "|-" */
const char *last_branch; /* "`-" */
const char *space; /* " " */
} spl_dumptree_style_t;
/* 默认 ASCII 风格 */
extern const spl_dumptree_style_t spl_dumptree_ascii_style;
/* 打印一行节点标签prefix + 分支符 + label
* prefix 已累积的缩进骨架(不含分支符)
* is_last 本节点是否为同级最后一个子节点
* fmt printf 风格 label */
void spl_dumptree_print(const spl_dumptree_style_t *st, const char *prefix, int is_last,
const char *fmt, ...);
/* 生成子节点的缩进骨架parent_prefix + (parent_is_last ? space : vertical) */
void spl_dumptree_child_prefix(const spl_dumptree_style_t *st, const char *prefix, int is_last,
char *out, size_t cap);
#endif /* __SPL_DUMPTREE_H__ */

4
stage1/spl_emit.h Normal file
View File

@@ -0,0 +1,4 @@
#ifndef __SPL_EMIT_H__
#define __SPL_EMIT_H__
#endif /* __SPL_EMIT_H__ */

519
stage1/spl_ir.c Normal file
View File

@@ -0,0 +1,519 @@
/* spl_ir.c — function-based SIR IR (arena 容器 + 文本 dump) */
#include "spl_ir.h"
#include <stdio.h>
#include <string.h>
/* ---- 内置函数名字表(与 spl_ir_kind_t 枚举一一对应) ---- */
static const char *const ir_kind_names[] = {
#define X(a, b, c) #a,
SPL_IR_FN_TABLE
#undef X
};
void spl_ir_init(spl_ir_t *ir) {
memset(ir, 0, sizeof *ir);
vec_init(ir->funcs);
vec_init(ir->gdata);
/* func ref 0 保留为 error占位 */
spl_ir_func_t f0;
memset(&f0, 0, sizeof f0);
vec_push(ir->funcs, f0);
}
static void node_drop_vecs(spl_ir_node_t *n) {
if (!n)
return;
switch (n->kind) {
case SPL_IR_AGG_CONSTRUCT:
vec_free(n->agg_construct.fields);
break;
case SPL_IR_CONTROL_CALL:
vec_free(n->control_call.params);
break;
default:
break;
}
}
void spl_ir_drop(spl_ir_t *ir) {
for (usize i = 0; i < ir->funcs.size; i++) {
spl_ir_func_t *f = &ir->funcs.data[i];
for (usize j = 0; j < f->nodes.size; j++)
node_drop_vecs(&f->nodes.data[j]);
vec_free(f->nodes);
vec_free(f->labels);
vec_free(f->dbg_vars);
}
vec_free(ir->funcs);
for (usize i = 0; i < ir->gdata.size; i++)
node_drop_vecs(&ir->gdata.data[i]);
vec_free(ir->gdata);
}
spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir) {
spl_ir_func_t f;
memset(&f, 0, sizeof f);
vec_init(f.nodes);
vec_init(f.labels);
vec_init(f.dbg_vars);
vec_push(ir->funcs, f);
return ir->funcs.size - 1;
}
spl_ir_node_ref_t spl_ir_alloc_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id) {
if (!fn_id || fn_id >= ir->funcs.size)
return 0;
spl_ir_func_t *f = &ir->funcs.data[fn_id];
spl_ir_node_t n;
memset(&n, 0, sizeof n);
if (f->nodes.size == 0) {
vec_push(f->nodes, n); /* 占位node ref 0 保留为 error */
}
vec_push(f->nodes, n);
return f->nodes.size - 1;
}
spl_ir_node_t *spl_ir_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_node_ref_t node_id) {
if (!fn_id || fn_id >= ir->funcs.size)
return NULL;
spl_ir_func_t *f = &ir->funcs.data[fn_id];
if (!node_id || node_id >= f->nodes.size)
return NULL;
return &f->nodes.data[node_id];
}
spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id) {
if (!fn_id || fn_id >= ir->funcs.size)
return NULL;
return &ir->funcs.data[fn_id];
}
/* ================================================================
* dump
* ================================================================ */
static void ir_type_dump(const spl_type_t *ty, spl_type_id_t tid) {
spl_type_node_t *n = spl_type_node((spl_type_t *)ty, tid);
if (!n) {
printf("?");
return;
}
switch (n->kind) {
case SPL_TYPE_VOID:
printf("void");
break;
case SPL_TYPE_BOOL:
printf("bool");
break;
case SPL_TYPE_INT:
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
break;
case SPL_TYPE_FLOAT:
printf("f%zu", n->float_type.bits);
break;
case SPL_TYPE_PTR:
printf("*");
ir_type_dump(ty, n->ptr_pointee);
break;
case SPL_TYPE_SLICE:
printf("[]");
ir_type_dump(ty, n->slice_element);
break;
case SPL_TYPE_RANGE:
printf("range[");
ir_type_dump(ty, n->range_element);
printf("]");
break;
case SPL_TYPE_ARRAY:
printf("[%zu]", n->array_type.len);
ir_type_dump(ty, n->array_type.element);
break;
case SPL_TYPE_STRUCT:
printf("struct#%zu", tid);
break;
case SPL_TYPE_UNION:
printf("union#%zu", tid);
break;
case SPL_TYPE_ENUM:
printf("enum#%zu", tid);
break;
case SPL_TYPE_FN:
printf("fn<");
for (usize i = 0; i < n->fn_type.params.size; i++) {
if (i)
printf(",");
ir_type_dump(ty, n->fn_type.params.data[i]);
}
printf("->");
ir_type_dump(ty, n->fn_type.ret);
printf(">");
break;
case SPL_TYPE_ID:
ir_type_dump(ty, n->type_id);
break;
default:
printf("?%zu", tid);
break;
}
}
static const char *node_name(spl_ir_kind_t k) {
if ((usize)k < sizeof(ir_kind_names) / sizeof(ir_kind_names[0]))
return ir_kind_names[k];
return "?";
}
static int node_produces_value(spl_ir_kind_t k) {
switch (k) {
case SPL_IR_MEM_STORE:
case SPL_IR_MEM_COPY:
case SPL_IR_MEM_SET:
case SPL_IR_MEM_FENCE:
case SPL_IR_CONTROL_BR:
case SPL_IR_CONTROL_JMP:
case SPL_IR_CONTROL_RET:
case SPL_IR_CONTROL_UNREACHABLE:
case SPL_IR_CONTROL_TRAP:
case SPL_IR_DBG_BREAKPOINT:
case SPL_IR_DBG_DECLARE:
return 0;
default:
return 1;
}
}
static void dump_ref(spl_ir_node_ref_t r) { printf("%%%zu", r); }
static void dump_node(const spl_type_t *ty, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_TYPE_CONST:
printf("@type.const(");
ir_type_dump(ty, n->type_const.tid);
printf(")(");
{
spl_type_node_t *t = spl_type_node((spl_type_t *)ty, n->type_const.tid);
if (t && t->kind == SPL_TYPE_INT)
printf("%lld", (long long)n->type_const.int_lit);
else if (t && t->kind == SPL_TYPE_FLOAT)
printf("%g", n->type_const.float_lit);
else if (t && t->kind == SPL_TYPE_FN)
printf("@fn#%zu", n->type_const.fn);
else if (t && (t->kind == SPL_TYPE_PTR || t->kind == SPL_TYPE_SLICE)) {
if (n->type_const.cstr_lit)
printf("\"%s\"", n->type_const.cstr_lit);
else
printf("0");
} else if (t && t->kind == SPL_TYPE_BOOL)
printf("%lld", (long long)n->type_const.int_lit);
else
printf("?");
}
printf(")");
break;
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV:
case SPL_IR_ARITH_REM:
case SPL_IR_ARITH_AND:
case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR:
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
printf("@%s(", node_name(n->kind));
ir_type_dump(ty, n->arith.tid);
printf(")(");
dump_ref(n->arith.left);
if (n->arith.right) {
printf(", ");
dump_ref(n->arith.right);
}
printf(")");
break;
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_NOT:
printf("@%s(", node_name(n->kind));
ir_type_dump(ty, n->arith.tid);
printf(")(");
dump_ref(n->arith.left);
printf(")");
break;
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE:
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
printf("@%s(", node_name(n->kind));
ir_type_dump(ty, n->cmp.tid);
printf(")(");
dump_ref(n->cmp.a);
printf(", ");
dump_ref(n->cmp.b);
printf(")");
break;
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT:
case SPL_IR_CAST_FTRUNC:
case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT:
case SPL_IR_CAST_INT2PTR:
case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
printf("@%s(", node_name(n->kind));
ir_type_dump(ty, n->cast.from_tid);
printf(", ");
ir_type_dump(ty, n->cast.to_tid);
printf(")(");
dump_ref(n->cast.val);
printf(")");
break;
case SPL_IR_MEM_ALLOCA:
printf("@mem.alloca(");
ir_type_dump(ty, n->mem_alloc.tid);
printf(")(");
dump_ref(n->mem_alloc.count);
printf(")");
break;
case SPL_IR_MEM_LOAD:
printf("@mem.load(");
ir_type_dump(ty, n->mem_load.tid);
printf(")(");
dump_ref(n->mem_load.ptr);
printf(")");
break;
case SPL_IR_MEM_STORE:
printf("@mem.store(");
ir_type_dump(ty, n->mem_store.tid);
printf(")(");
dump_ref(n->mem_store.ptr);
printf(", ");
dump_ref(n->mem_store.val);
printf(")");
break;
case SPL_IR_MEM_OFFSET:
printf("@mem.offset(");
ir_type_dump(ty, n->mem_offset.tid);
printf(")(");
dump_ref(n->mem_offset.ptr);
printf(", ");
dump_ref(n->mem_offset.offset);
printf(")");
break;
case SPL_IR_MEM_FIELD_PTR:
printf("@mem.field_ptr(");
ir_type_dump(ty, n->mem_field_ptr.tid);
printf(", %zu)(", (size_t)n->mem_field_ptr.field_idx);
dump_ref(n->mem_field_ptr.agg);
printf(")");
break;
case SPL_IR_MEM_GLOBAL_ALLOC:
printf("@mem.global_alloc(gdata[%zu])()", (size_t)n->mem_global_alloc.const_node);
break;
case SPL_IR_MEM_COPY:
printf("@mem.copy()(");
dump_ref(n->mem_copy.dst);
printf(", ");
dump_ref(n->mem_copy.src);
printf(", ");
dump_ref(n->mem_copy.size);
printf(")");
break;
case SPL_IR_MEM_SET:
printf("@mem.set()(");
dump_ref(n->mem_set.dst);
printf(", ");
dump_ref(n->mem_set.val);
printf(", ");
dump_ref(n->mem_set.size);
printf(")");
break;
case SPL_IR_MEM_FENCE:
printf("@mem.fence()(");
dump_ref(n->mem_fence.ordering);
printf(")");
break;
case SPL_IR_TYPE_BITSIZEOF:
printf("@type.bitsizeof(");
ir_type_dump(ty, n->bitsizeof.tid);
printf(")()");
break;
case SPL_IR_TYPE_SIZEOF:
printf("@type.sizeof(");
ir_type_dump(ty, n->ir_sizeof.tid);
printf(")()");
break;
case SPL_IR_TYPE_ALIGNOF:
printf("@type.alignof(");
ir_type_dump(ty, n->ir_alignof.tid);
printf(")()");
break;
case SPL_IR_TYPE_OFFSETOF:
printf("@type.offsetof(");
ir_type_dump(ty, n->ir_offsetof.tid);
printf(")(");
dump_ref(n->ir_offsetof.field_idx);
printf(")");
break;
case SPL_IR_TYPE_FIELD_COUNT:
printf("@type.field_count(");
ir_type_dump(ty, n->field_count.tid);
printf(")()");
break;
case SPL_IR_AGG_CONSTRUCT:
printf("@agg.construct(");
ir_type_dump(ty, n->agg_construct.tid);
printf(")(");
for (usize i = 0; i < n->agg_construct.fields.size; i++) {
if (i)
printf(", ");
dump_ref(n->agg_construct.fields.data[i]);
}
printf(")");
break;
case SPL_IR_AGG_EXTRACT:
printf("@agg.extract(");
ir_type_dump(ty, n->agg_extract.tid);
printf(", %lld)(", (long long)n->agg_extract.field_idx);
dump_ref(n->agg_extract.val);
printf(")");
break;
case SPL_IR_AGG_INSERT:
printf("@agg.insert(");
ir_type_dump(ty, n->agg_insert.tid);
printf(", %lld)(", (long long)n->agg_insert.field_idx);
dump_ref(n->agg_insert.agg);
printf(", ");
dump_ref(n->agg_insert.field);
printf(")");
break;
case SPL_IR_CONTROL_SELECT:
printf("@control.select(");
ir_type_dump(ty, n->control_select.tid);
printf(")(");
dump_ref(n->control_select.cond);
printf(", ");
dump_ref(n->control_select.true_val);
printf(", ");
dump_ref(n->control_select.false_val);
printf(")");
break;
case SPL_IR_CONTROL_BR:
printf("@control.br()(");
dump_ref(n->control_br.cond);
printf(", ");
dump_ref(n->control_br.true_label);
printf(", ");
dump_ref(n->control_br.false_label);
printf(")");
break;
case SPL_IR_CONTROL_JMP:
printf("@control.jmp()(");
dump_ref(n->control_jmp.label);
printf(")");
break;
case SPL_IR_CONTROL_CALL:
printf("@control.call(");
ir_type_dump(ty, n->control_call.tid);
printf(")(");
dump_ref(n->control_call.func);
for (usize i = 0; i < n->control_call.params.size; i++) {
printf(", ");
dump_ref(n->control_call.params.data[i]);
}
printf(")");
break;
case SPL_IR_CONTROL_PARAM:
printf("@control.param(");
ir_type_dump(ty, n->control_param.tid);
printf(")(%lld)", (long long)n->control_param.idx);
break;
case SPL_IR_CONTROL_RET:
printf("@control.ret(");
ir_type_dump(ty, n->control_ret.tid);
printf(")(");
if (n->control_ret.val)
dump_ref(n->control_ret.val);
printf(")");
break;
case SPL_IR_CONTROL_UNREACHABLE:
printf("@control.unreachable()()");
break;
case SPL_IR_CONTROL_TRAP:
printf("@control.trap()()");
break;
case SPL_IR_DBG_BREAKPOINT:
printf("@dbg.breakpoint()()");
break;
case SPL_IR_DBG_DECLARE:
printf("@dbg.declare()()");
break;
default:
printf("@%s()()", node_name(n->kind));
break;
}
}
static void dump_func(const spl_type_t *ty, const spl_ir_func_t *f) {
printf("func @%s", f->name ? f->name : "?");
if (f->fn_tid) {
spl_type_node_t *t = spl_type_node((spl_type_t *)ty, f->fn_tid);
if (t && t->kind == SPL_TYPE_FN) {
printf("(");
for (usize i = 0; i < t->fn_type.params.size; i++) {
if (i)
printf(", ");
ir_type_dump(ty, t->fn_type.params.data[i]);
}
printf(") -> ");
ir_type_dump(ty, t->fn_type.ret);
}
}
printf(" {\n");
usize li = 0;
for (usize i = 1; i < f->nodes.size; i++) {
if (li < f->labels.size && f->labels.data[li] == i) {
printf("#bb%zu:\n", li);
li++;
}
printf(" ");
if (node_produces_value(f->nodes.data[i].kind))
printf("%%%zu = ", i);
dump_node(ty, &f->nodes.data[i]);
printf("\n");
}
if (li < f->labels.size && f->labels.data[li] == f->nodes.size)
printf("#bb%zu:\n", li);
printf("}\n");
}
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty) {
printf("; SPL IR module (%zu funcs)\n", ir->funcs.size - 1);
for (usize i = 1; i < ir->funcs.size; i++)
dump_func(ty, &ir->funcs.data[i]);
if (ir->gdata.size) {
printf("; global data (%zu)\n", ir->gdata.size);
for (usize i = 0; i < ir->gdata.size; i++) {
printf("; gdata[%zu] = ", i);
dump_node(ty, &ir->gdata.data[i]);
printf("\n");
}
}
}
const char *spl_ir_kind_name(spl_ir_kind_t kind) {
static const char *const names[] = {
#define X(a, b, c) #a,
SPL_IR_FN_TABLE
#undef X
};
if ((usize)kind < sizeof(names) / sizeof(names[0]))
return names[kind];
return "?";
}

270
stage1/spl_ir.h Normal file
View File

@@ -0,0 +1,270 @@
#ifndef __SPL_IR_H__
#define __SPL_IR_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_type.h"
/* clang-format off */
#define SPL_IR_FN_TABLE \
X(arith.add, V0, SPL_IR_ARITH_ADD) \
X(arith.sub, V0, SPL_IR_ARITH_SUB) \
X(arith.mul, V0, SPL_IR_ARITH_MUL) \
X(arith.div, V0, SPL_IR_ARITH_DIV) \
X(arith.rem, V0, SPL_IR_ARITH_REM) \
X(arith.neg, V0, SPL_IR_ARITH_NEG) \
X(arith.abs, V0, SPL_IR_ARITH_ABS) \
X(arith.and, V0, SPL_IR_ARITH_AND) \
X(arith.or, V0, SPL_IR_ARITH_OR) \
X(arith.xor, V0, SPL_IR_ARITH_XOR) \
X(arith.shl, V0, SPL_IR_ARITH_SHL) \
X(arith.shr, V0, SPL_IR_ARITH_SHR) \
X(arith.not, V0, SPL_IR_ARITH_NOT) \
X(cmp.eq, V0, SPL_IR_CMP_EQ) \
X(cmp.ne, V0, SPL_IR_CMP_NE) \
X(cmp.lt, V0, SPL_IR_CMP_LT) \
X(cmp.le, V0, SPL_IR_CMP_LE) \
X(cmp.gt, V0, SPL_IR_CMP_GT) \
X(cmp.ge, V0, SPL_IR_CMP_GE) \
X(cast.trunc, V0, SPL_IR_CAST_TRUNC) \
X(cast.zext, V0, SPL_IR_CAST_ZEXT) \
X(cast.sext, V0, SPL_IR_CAST_SEXT) \
X(cast.fext, V0, SPL_IR_CAST_FEXT) \
X(cast.ftrunc, V0, SPL_IR_CAST_FTRUNC) \
X(cast.bitcast, V0, SPL_IR_CAST_BITCAST) \
X(cast.ptr2int, V0, SPL_IR_CAST_PTR2INT) \
X(cast.int2ptr, V0, SPL_IR_CAST_INT2PTR) \
X(cast.bool2int, V0, SPL_IR_CAST_BOOL2INT) \
X(case.int2float, V0, SPL_IR_CASE_INT2FLOAT) \
X(case.float2int, V0, SPL_IR_CASE_FLOAT2INT) \
X(mem.alloca, V0, SPL_IR_MEM_ALLOCA) \
X(mem.global_alloc, V0, SPL_IR_MEM_GLOBAL_ALLOC) \
X(mem.load, V0, SPL_IR_MEM_LOAD) \
X(mem.store, V0, SPL_IR_MEM_STORE) \
X(mem.offset, V0, SPL_IR_MEM_OFFSET) \
X(mem.field, V0, SPL_IR_MEM_FIELD_PTR) \
X(mem.copy, V0, SPL_IR_MEM_COPY) \
X(mem.set, V0, SPL_IR_MEM_SET) \
X(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) \
X(type.alignof, V0, SPL_IR_TYPE_ALIGNOF) \
X(type.offsetof, V0, SPL_IR_TYPE_OFFSETOF) \
X(type.field_count, V0, SPL_IR_TYPE_FIELD_COUNT) \
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) \
X(control.call, V0, SPL_IR_CONTROL_CALL) \
X(control.param, V0, SPL_IR_CONTROL_PARAM) \
X(control.ret, V0, SPL_IR_CONTROL_RET) \
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
#undef X
#endif
#define X(a, b, c) c,
SPL_IR_FN_TABLE
#undef X
} spl_ir_kind_t;
/* clang-format on */
typedef usize spl_ir_node_ref_t; /* 0 is error */
typedef VEC(spl_ir_node_ref_t) spl_ir_node_ref_vec_t;
typedef usize spl_ir_func_ref_t; /* 0 is error */
typedef struct {
spl_ir_kind_t kind;
spl_dbg_node_t dbg;
union {
struct {
spl_type_id_t tid;
spl_ir_node_ref_t left;
spl_ir_node_ref_t right;
} arith;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t a;
spl_ir_node_ref_t b;
} cmp;
struct {
spl_type_id_t from_tid;
spl_type_id_t to_tid;
spl_ir_node_ref_t val;
} cast;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t count;
} mem_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t const_node;
} mem_global_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
} mem_load;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t val;
} mem_store;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t offset;
} mem_offset;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t agg;
usize field_idx;
} mem_field_ptr;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t src;
spl_ir_node_ref_t size;
} mem_copy;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t val;
spl_ir_node_ref_t size;
} mem_set;
struct {
spl_ir_node_ref_t ordering;
} mem_fence;
struct {
spl_type_id_t tid;
union {
usize int_lit;
double float_lit;
const char *cstr_lit;
char ch_lit;
spl_ir_func_ref_t fn;
};
} type_const;
struct {
spl_type_id_t tid;
} bitsizeof;
struct {
spl_type_id_t tid;
} ir_sizeof;
struct {
spl_type_id_t tid;
} ir_alignof;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t field_idx;
} ir_offsetof;
struct {
spl_type_id_t tid;
} field_count;
struct {
spl_type_id_t tid;
spl_ir_node_ref_vec_t fields;
} agg_construct;
struct {
spl_type_id_t tid;
spl_type_id_t field_tid;
usize field_idx;
spl_ir_node_ref_t val;
} agg_extract;
struct {
spl_type_id_t tid;
usize field_idx;
spl_ir_node_ref_t agg;
spl_ir_node_ref_t field;
} agg_insert;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t cond;
spl_ir_node_ref_t true_val;
spl_ir_node_ref_t false_val;
} control_select;
struct {
spl_ir_node_ref_t cond;
spl_ir_node_ref_t true_label;
spl_ir_node_ref_t false_label;
} control_br;
struct {
spl_ir_node_ref_t label;
} control_jmp;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t func;
spl_ir_node_ref_vec_t params;
} control_call;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t idx;
} control_param;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t val;
} control_ret;
};
} spl_ir_node_t;
typedef VEC(spl_ir_node_t) spl_ir_node_vec_t;
typedef struct {
enum {
SPL_IR_ATTR_NONE,
SPL_IR_ATTR_LINK, /* 不实现 */
SPL_IR_ATTR_ABI, /* 只有 C ABI 支持 */
SPL_IR_ATTR_SYMBOL, /* 不实现 */
SPL_IR_ATTR_NAKED, /* 不实现 */
SPL_IR_ATTR_NOINLINE, /* 不实现 */
SPL_IR_ATTR_ALWAYSINLINE, /* 不实现 */
};
} spl_ir_attr_t;
typedef VEC(spl_ir_attr_t) spl_ir_attr_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_func_t;
typedef VEC(spl_ir_func_t) spl_ir_func_vec_t;
typedef struct {
spl_ir_func_vec_t funcs;
spl_ir_node_vec_t gdata;
} spl_ir_t;
void spl_ir_init(spl_ir_t *ir);
void spl_ir_drop(spl_ir_t *ir);
spl_ir_node_ref_t spl_ir_alloc_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir);
spl_ir_node_t *spl_ir_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_node_ref_t node_id);
spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty);
const char *spl_ir_kind_name(spl_ir_kind_t kind);
#endif /* __SPL_IR_H__ */

1426
stage1/spl_ir2vm.c Normal file

File diff suppressed because it is too large Load Diff

101
stage1/spl_ir2vm.h Normal file
View File

@@ -0,0 +1,101 @@
#ifndef __SPL_IR2VM_H__
#define __SPL_IR2VM_H__
#include "spl_ir.h"
#include "spl_type.h"
/*
* ================================================================
* SPL VM ABI (ir2vm 的正式约定;布局知识唯一来源)
* ================================================================
*
* 栈值槽 spl_val_t = sizeof(usize) = 8 字节。
* SIR 指令 type 只表达标量 tagSPL_I8..SPL_PTR聚合无 tag——
* 聚合值在 vreg 中是字节块,整体搬运用 NCALL vm_memcpy。
*
* ── 函数栈帧(字节坐标系,基址 = (char*)&stacks[fp])─────────────
*
* [canary] fp-8 .. 0 VM CALL 自动插入ir2vm 不触碰)
* [params 区] fp+0 .. fp+Na Na = C ABI 参数区字节数)
* [locals / vreg] fp+Na .. fp+Na+L
*
* ALLOC ceil((Na+L)/8) 一条 prologueepilogue 走 RET。
* LADDR(imm) 的 imm 是字节偏移canary 在 fp-1 槽,编译码不可见。
*
* ── 参数区 = C ABI聚合值按值 ─────────────────────────────────
* 标量参数align_up(off,8) 后占 8 字节(一槽)。
* 聚合参数:按聚合 size 排布跨多槽align8 + size
* 调用方:标量 ld/PUSH 一槽;聚合逐 8 字节块压栈(聚合 vreg 强制 8 对齐)。
* 被调方:标量参数映射参数槽;聚合参数在 prologue memcpy 参数区 → param vreg
* emit_value(param) 取 vreg 地址。参数槽数 = ceil(param_bytes/8) = CALL nargs。
*
* ── locals = 虚拟寄存器区 ────────────────────────────────────────
* 每个产生值的 IR 节点 = 一个 vreglocals 区按类型对齐的字节块)。
* 纯值节点type.const / mem.global_alloc / mem.alloca / 折叠 sizeof 等)不落 vreg
* 引用处重算PUSH / GADDR / LADDR其余产生值节点落 vreg引用处 LOAD。
* 聚合 vreg 引用处返回其地址LADDR搬运经 vm_memcpy。
* mem.alloca(tid)(cnt) 的 vreg 槽即缓冲区本体,节点值 = LADDR(vreg_off)。
* 所有运算走 load/storeld A; ld B; op; st Dst立即数直接 PUSH。
*
* ── 调用 ──────────────────────────────────────────────────────────
* 调用方:逐参数压栈(标量一槽;聚合按 C ABI 逐 8 字节块)→ push fn_addr(或
* native_idx) → CALL n / NCALL n。返回值落 call 节点 vreg。
* 原生函数IR 中 nodes 为空的函数(@extern 声明)→ 注册进 prog.natives
* 加载时由 spl_syscall_register 填 impl调用改 PUSH nat_idx + NCALL。
* 变参 nargs = 实际参数槽数。
*
* ── enum不展开直接保留─────────────────────────────────────
* IR 层保留 enum 类型(不再展开为 struct。enum 布局 = tag(usize, offset 0)
* + payload(offset 8最大变体。构造agg.construct(enum)(tag, payload)
* match先取 tag 判定变体,再 extract(enum, 1) 一跳取 payload
* field_tid = 变体具体类型(由 ast2ir 传入)。
*
* ── 返回 ──────────────────────────────────────────────────────────
* 标量ld vreg(val); RET(tag)RET 的 type 决定 VM 是否弹出返回值)。
* 聚合返回 = sret自展开不改 VM
* 被调函数签名尾部追加隐藏 *T 参数(最后一个);返回时把聚合 vreg
* memcpy 到 sret 地址RET(void)。
* 调用方在 locals 预留聚合槽(= call 节点 vreg压其地址为最后实参
* call 完成后聚合值已在该槽。
* 返回 voidRET(SPL_VOID)。
*
* ── 全局数据 ──────────────────────────────────────────────────────
* 任何聚合类型下(含 $root 顶层)的 var/const 属全局数据区。gdata 是
* spl_ir_node_vec_t每条 = 一个 value 节点type.const标量折叠值
* 聚合/无 init 零。ir2vm 遍历求值 → SIR gdata 条目(字节 blob
* mem.global_alloc(tid, const_node) 的 const_node = gdata 向量索引,
* 降级为 GADDR(idx)。符号(def) → gdata 索引的解析在 ast2ir 收集期
* gdata_ref 表ir2vm 按索引直接用。
*
* ── 类型布局C ABI唯一实现处────────────────────────────────
* type_align / type_size / field_offset标量按 bits/8 对齐;
* struct 顺序对齐 + 尾填充union 取最大字段enum = tag(8) + 最大 payload
* slice/range = [ptr, len] 各 8 字节array = len * elem。
*
* ── 分支 ──────────────────────────────────────────────────────────
* control.br/jmp/select 的 label 是 IR node ref基本块首指令。两遍发射
* 第一遍逐节点发指令并记录 label 节点 → 指令地址;第二遍回填
* JMP/BZ/BNZ 相对偏移 imm = target_addr - (jmp_addr + 1)。
* ================================================================
*/
/* 调试映射:每函数 IR 节点 → 首条指令 ip调试器显示当前 IR 节点用) */
typedef struct {
spl_ir_func_ref_t fid;
VEC(usize) node_first_ip; /* 索引 = IR 节点 ref值 = 该节点首指令绝对 ip */
} spl_ir2vm_fdbg_t;
typedef VEC(spl_ir2vm_fdbg_t) spl_ir2vm_fdbg_vec_t;
typedef struct {
const spl_ir_t *ir;
const spl_type_t *type;
spl_ir2vm_fdbg_vec_t fdbg; /* ir2vm_run 后填充splc0 -g 读取生成 debug 段 */
} spl_ir2vm_t;
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type);
void spl_ir2vm_drop(spl_ir2vm_t *ctx);
int spl_ir2vm_run(spl_ir2vm_t *ctx, const char *outpath); /* 返回错误数 */
void spl_ir2vm_dump(spl_ir2vm_t *ctx);
#endif /* __SPL_IR2VM_H__ */

0
stage1/spl_layout.c Normal file
View File

0
stage1/spl_layout.h Normal file
View File

538
stage1/spl_lexer.c Normal file
View File

@@ -0,0 +1,538 @@
/* spl_lexer.c - SPL lexical analyzer */
#include "spl_lexer.h"
#include "spl_tok.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/* Character classification */
static int is_ident_start(char c) { return isalpha((unsigned char)c) || c == '_'; }
static int is_ident_cont(char c) { return isalnum((unsigned char)c) || c == '_'; }
/* Keyword lookup: if ident is a keyword, return its token type, else TOK_IDENT */
static spl_tok_type_t keyword_type(const char *ident, usize len) {
#define X(name, enum_name, dummy) \
if (len == sizeof(#name) - 1 && memcmp(ident, #name, len) == 0) \
return enum_name;
KEYWORD_TABLE
#undef X
return TOK_IDENT;
}
/* 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) {
if (**s != '\\') {
*out = **s;
(*s)++;
return 0;
}
(*s)++; /* skip backslash */
switch (**s) {
case 'n':
*out = '\n';
break;
case 't':
*out = '\t';
break;
case 'r':
*out = '\r';
break;
case '\\':
*out = '\\';
break;
case '"':
*out = '"';
break;
case '\'':
*out = '\'';
break;
case '0':
*out = '\0';
break;
case 'x': {
(*s)++;
char hex[3] = {0, 0, 0};
int i;
for (i = 0; i < 2 && isxdigit((unsigned char)**s); i++, (*s)++) {
hex[i] = **s;
}
if (i == 0)
return -1;
*out = (char)strtol(hex, NULL, 16);
return 0;
}
default:
return -1;
}
(*s)++;
return 0;
}
spl_tok_vec_t spl_lex(const char *source, const char *fname) {
spl_tok_vec_t toks;
vec_init(toks);
usize line = 1;
usize col = 1;
usize offset = 0;
usize len = strlen(source);
while (offset < len) {
const char *start = source + offset;
char c = *start;
/* Skip whitespace (but not newlines - emit TOK_ENDLINE) */
if (c == ' ' || c == '\t' || c == '\r') {
offset++;
col++;
continue;
}
/* Newline */
if (c == '\n') {
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_ENDLINE;
tok.lexeme = start;
tok.len = 1;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
offset++;
line++;
col = 1;
continue;
}
/* Line comment */
if (c == '/' && offset + 1 < len && source[offset + 1] == '/') {
const char *nl = (const char *)memchr(start, '\n', len - offset);
usize clen = nl ? (usize)(nl - start) : (len - offset);
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_LINE_COMMENT;
tok.lexeme = start;
tok.len = clen;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
offset += clen;
col += clen;
continue;
}
/* Block comment */
if (c == '/' && offset + 1 < len && source[offset + 1] == '*') {
offset += 2;
col += 2;
usize depth = 1;
while (offset + 1 < len && depth > 0) {
if (source[offset] == '*' && source[offset + 1] == '/') {
depth--;
offset += 2;
col += 2;
if (depth == 0)
break;
} else if (source[offset] == '/' && source[offset + 1] == '*') {
depth++;
offset += 2;
col += 2;
} else {
if (source[offset] == '\n') {
line++;
col = 1;
} else {
col++;
}
offset++;
}
}
continue;
}
/* Char literal: 'x' */
if (c == '\'') {
offset++;
col++;
char buf[16];
int bi = 0;
memset(buf, 0, sizeof(buf));
if (offset < len) {
const char *cp = source + offset;
if (spl_decode_escape(&cp, &buf[bi])) {
buf[bi] = source[offset];
cp = source + offset + 1;
}
bi++;
offset = (usize)(cp - source);
col += (usize)(cp - (start + 1));
}
if (offset < len && source[offset] == '\'') {
offset++;
col++;
}
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_CHAR_LITERAL;
tok.lexeme = start;
tok.len = (usize)((source + offset) - start);
tok.fname = fname;
tok.offset = start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
/* String literal: "..." */
if (c == '"') {
offset++;
col++;
while (offset < len) {
if (source[offset] == '\\') {
offset++;
col++;
if (offset < len) {
offset++;
col++;
}
} else if (source[offset] == '"') {
offset++;
col++;
break;
} else if (source[offset] == '\n') {
line++;
col = 1;
offset++;
} else {
offset++;
col++;
}
}
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_STRING_LITERAL;
tok.lexeme = start;
tok.len = (usize)((source + offset) - start);
tok.fname = fname;
tok.offset = start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
/* Identifiers and keywords */
if (is_ident_start(c)) {
const char *id_start = start;
usize id_len = 0;
while (offset < len && is_ident_cont(source[offset])) {
offset++;
id_len++;
col++;
}
spl_tok_type_t tt = keyword_type(id_start, id_len);
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = tt;
tok.lexeme = id_start;
tok.len = id_len;
tok.fname = fname;
tok.offset = id_start - source;
tok.line = line;
tok.col = col - id_len;
vec_push(toks, tok);
continue;
}
/* Numbers: integers and floats */
if (isdigit((unsigned char)c)) {
const char *num_start = start;
int is_float = 0;
/* Check for hex/bin/oct prefix */
if (c == '0' && offset + 1 < len) {
char nc = source[offset + 1];
if (nc == 'x' || nc == 'X') {
/* Hex literal */
offset += 2;
col += 2;
while (offset < len &&
(isxdigit((unsigned char)source[offset]) || source[offset] == '_')) {
offset++;
col++;
}
goto emit_int;
}
if (nc == 'b' || nc == 'B') {
/* Binary literal */
offset += 2;
col += 2;
while (offset < len && (source[offset] == '0' || source[offset] == '1' ||
source[offset] == '_')) {
offset++;
col++;
}
goto emit_int;
}
if (nc == 'o' || nc == 'O') {
/* Octal literal */
offset += 2;
col += 2;
while (offset < len && ((source[offset] >= '0' && source[offset] <= '7') ||
source[offset] == '_')) {
offset++;
col++;
}
goto emit_int;
}
}
/* Decimal integer or float */
while (offset < len &&
(isdigit((unsigned char)source[offset]) || source[offset] == '_')) {
offset++;
col++;
}
if (offset < len && source[offset] == '.' && offset + 1 < len &&
isdigit((unsigned char)source[offset + 1])) {
is_float = 1;
offset++;
col++;
while (offset < len && isdigit((unsigned char)source[offset])) {
offset++;
col++;
}
}
if (is_float) {
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_FLOAT_LITERAL;
tok.lexeme = num_start;
tok.len = (usize)((source + offset) - num_start);
tok.fname = fname;
tok.offset = num_start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
emit_int: {
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_INT_LITERAL;
tok.lexeme = num_start;
tok.len = (usize)((source + offset) - num_start);
tok.fname = fname;
tok.offset = num_start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
}
/* Multi-character operators (longest match) */
/* Helper: try to match a two-char operator */
#define TRY_OP2(c1, c2, tok2, tok1) \
if (c == (c1) && offset + 1 < len && source[offset + 1] == (c2)) { \
spl_tok_type_t op_type = (tok2); \
usize op_len = 2; \
spl_tok_t tok; \
memset(&tok, 0, sizeof(tok)); \
tok.type = op_type; \
tok.lexeme = start; \
tok.len = op_len; \
tok.fname = fname; \
tok.offset = offset; \
tok.line = line; \
tok.col = col; \
vec_push(toks, tok); \
offset += op_len; \
col += op_len; \
continue; \
}
#define TRY_OP3(c1, c2, c3, tok3, tok2, tok1) \
if (c == (c1) && offset + 1 < len && source[offset + 1] == (c2)) { \
spl_tok_type_t op_type = (tok2); \
usize op_len = 2; \
if (offset + 2 < len && source[offset + 2] == (c3)) { \
op_type = (tok3); \
op_len = 3; \
} \
spl_tok_t tok; \
memset(&tok, 0, sizeof(tok)); \
tok.type = op_type; \
tok.lexeme = start; \
tok.len = op_len; \
tok.fname = fname; \
tok.offset = offset; \
tok.line = line; \
tok.col = col; \
vec_push(toks, tok); \
offset += op_len; \
col += op_len; \
continue; \
}
/* Three-char operators first */
TRY_OP3('<', '<', '=', TOK_ASSIGN_L_SH, TOK_L_SH, TOK_LT)
TRY_OP3('>', '>', '=', TOK_ASSIGN_R_SH, TOK_R_SH, TOK_GT)
TRY_OP3('.', '.', '.', TOK_ELLIPSIS, TOK_RANGE, TOK_DOT)
/* Two-char operators */
TRY_OP2('=', '=', TOK_EQ, TOK_ASSIGN)
TRY_OP2('=', '>', TOK_FAT_ARROW, TOK_ASSIGN)
TRY_OP2('!', '=', TOK_NEQ, TOK_NOT)
TRY_OP2('<', '=', TOK_LE, TOK_LT)
TRY_OP2('>', '=', TOK_GE, TOK_GT)
TRY_OP2('&', '&', TOK_AND_AND, TOK_AND)
TRY_OP2('|', '|', TOK_OR_OR, TOK_OR)
TRY_OP2('+', '=', TOK_ASSIGN_ADD, TOK_ADD)
TRY_OP2('-', '=', TOK_ASSIGN_SUB, TOK_SUB)
TRY_OP2('*', '=', TOK_ASSIGN_MUL, TOK_MUL)
TRY_OP2('/', '=', TOK_ASSIGN_DIV, TOK_DIV)
TRY_OP2('%', '=', TOK_ASSIGN_MOD, TOK_MOD)
TRY_OP2('&', '=', TOK_ASSIGN_AND, TOK_AND)
TRY_OP2('|', '=', TOK_ASSIGN_OR, TOK_OR)
TRY_OP2('^', '=', TOK_ASSIGN_XOR, TOK_XOR)
TRY_OP2('<', '-', TOK_LEFT_ARRAY, TOK_LT)
TRY_OP2('-', '>', TOK_RIGHT_ARRAY, TOK_SUB)
TRY_OP2(':', '=', TOK_COLON_ASSIGN, TOK_COLON)
/* Single-character operators */
{
spl_tok_type_t tt = TOK_UNKNOWN;
switch (c) {
case '+':
tt = TOK_ADD;
break;
case '-':
tt = TOK_SUB;
break;
case '*':
tt = TOK_MUL;
break;
case '/':
tt = TOK_DIV;
break;
case '%':
tt = TOK_MOD;
break;
case '&':
tt = TOK_AND;
break;
case '|':
tt = TOK_OR;
break;
case '^':
tt = TOK_XOR;
break;
case '~':
tt = TOK_BIT_NOT;
break;
case '!':
tt = TOK_NOT;
break;
case '<':
tt = TOK_LT;
break;
case '>':
tt = TOK_GT;
break;
case '=':
tt = TOK_ASSIGN;
break;
case '.':
tt = TOK_DOT;
break;
case ',':
tt = TOK_COMMA;
break;
case ';':
tt = TOK_SEMICOLON;
break;
case ':':
tt = TOK_COLON;
break;
case '(':
tt = TOK_L_PAREN;
break;
case ')':
tt = TOK_R_PAREN;
break;
case '[':
tt = TOK_L_BRACKET;
break;
case ']':
tt = TOK_R_BRACKET;
break;
case '{':
tt = TOK_L_BRACE;
break;
case '}':
tt = TOK_R_BRACE;
break;
case '#':
tt = TOK_SHARP;
break;
case '@':
tt = TOK_AT;
break;
case '?':
tt = TOK_COND;
break;
default:
tt = TOK_UNKNOWN;
break;
}
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = tt;
tok.lexeme = start;
tok.len = 1;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
offset++;
col++;
}
}
/* EOF token */
{
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_EOF;
tok.lexeme = source + offset;
tok.len = 0;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
}
return toks;
}

13
stage1/spl_lexer.h Normal file
View File

@@ -0,0 +1,13 @@
/* spl_lexer.h - 独立词法分析器 */
#ifndef __SPL_LEXER_H__
#define __SPL_LEXER_H__
#include "spl_tok.h"
/* Lexer entry point */
spl_tok_vec_t spl_lex(const char *source, const char *fname);
/* Decode escape sequence, advance *s past it. Returns 0 on success. */
int spl_decode_escape(const char **s, char *out);
#endif /* __SPL_LEXER_H__ */

2018
stage1/spl_sema.c Normal file

File diff suppressed because it is too large Load Diff

35
stage1/spl_sema.h Normal file
View File

@@ -0,0 +1,35 @@
#ifndef __SPL_SEMA_H__
#define __SPL_SEMA_H__
#include "spl_ast.h"
#include "spl_type.h"
typedef usize spl_scope_id_t; /* 0 is error */
typedef struct {
spl_scope_id_t parent;
MAP(const char *, spl_def_id_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;
int error_count;
} spl_sema_t;
void spl_sema_init(spl_sema_t *sema);
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);
#endif /* __SPL_SEMA_H__ */

127
stage1/spl_tok.h Normal file
View File

@@ -0,0 +1,127 @@
/* spl_tok.h - Token type definitions (extracted from spl_lexer.h) */
#ifndef __SPL_TOK_H__
#define __SPL_TOK_H__
#include "../stage0/include/utils.h"
/* clang-format off */
#define KEYWORD_TABLE \
X(as , KW_AS , SPL_V0) \
X(bool , KW_BOOL , SPL_V0) \
X(break , KW_BREAK , SPL_V0) \
X(catch , KW_CATCH , SPL_V0) \
X(comptime , KW_COMPTIME , SPL_V0) \
X(const , KW_CONST , SPL_V0) \
X(continue , KW_CONTINUE , SPL_V0) \
X(defer , KW_DEFER , SPL_V0) \
X(else , KW_ELSE , SPL_V0) \
X(enum , KW_ENUM , SPL_V0) \
X(errdefer , KW_ERRDEFER , SPL_V0) \
X(false , KW_FALSE , SPL_V0) \
X(fn , KW_FN , SPL_V0) \
X(for , KW_FOR , SPL_V0) \
X(if , KW_IF , SPL_V0) \
X(loop , KW_LOOP , SPL_V0) \
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) \
X(while , KW_WHILE , SPL_V0) \
X(_ , KW_ANY , SPL_V0) \
// KEYWORD_TABLE
#define TOKEN_TABLE \
X(unknown , TOK_UNKNOWN , SPL_V0 ) \
X(EOF , TOK_EOF , SPL_V0 ) \
X(blank , TOK_BLANK , SPL_V0 ) \
X(endline , TOK_ENDLINE , SPL_V0 ) \
X("#" , TOK_SHARP , SPL_V0 ) \
X("@" , TOK_AT , SPL_V0 ) \
X("==" , TOK_EQ , SPL_V0 ) \
X("=" , TOK_ASSIGN , SPL_V0 ) \
X("+=" , TOK_ASSIGN_ADD , SPL_V0 ) \
X("+" , TOK_ADD , SPL_V0 ) \
X("-=" , TOK_ASSIGN_SUB , SPL_V0 ) \
X("->" , TOK_RIGHT_ARRAY , SPL_V0 ) \
X("<-" , TOK_LEFT_ARRAY , SPL_V0 ) \
X("-" , TOK_SUB , SPL_V0 ) \
X("*=" , TOK_ASSIGN_MUL , SPL_V0 ) \
X("*" , TOK_MUL , SPL_V0 ) \
X("/=" , TOK_ASSIGN_DIV , SPL_V0 ) \
X("/" , TOK_DIV , SPL_V0 ) \
X("//" , TOK_LINE_COMMENT , SPL_V0 ) \
X("/* */" , TOK_BLOCK_COMMENT , SPL_V0 ) \
X("%=" , TOK_ASSIGN_MOD , SPL_V0 ) \
X("%" , TOK_MOD , SPL_V0 ) \
X("&&" , TOK_AND_AND , SPL_V0 ) \
X("&=" , TOK_ASSIGN_AND , SPL_V0 ) \
X("&" , TOK_AND , SPL_V0 ) \
X("||" , TOK_OR_OR , SPL_V0 ) \
X("|=" , TOK_ASSIGN_OR , SPL_V0 ) \
X("|" , TOK_OR , SPL_V0 ) \
X("^=" , TOK_ASSIGN_XOR , SPL_V0 ) \
X("^" , TOK_XOR , SPL_V0 ) \
X("<<=" , TOK_ASSIGN_L_SH , SPL_V0 ) \
X("<<" , TOK_L_SH , SPL_V0 ) \
X("<=" , TOK_LE , SPL_V0 ) \
X("<" , TOK_LT , SPL_V0 ) \
X(">>=" , TOK_ASSIGN_R_SH , SPL_V0 ) \
X(">>" , TOK_R_SH , SPL_V0 ) \
X(">=" , TOK_GE , SPL_V0 ) \
X(">" , TOK_GT , SPL_V0 ) \
X("!" , TOK_NOT , SPL_V0 ) \
X("!=" , TOK_NEQ , SPL_V0 ) \
X("~" , TOK_BIT_NOT , SPL_V0 ) \
X("[" , TOK_L_BRACKET , SPL_V0 ) \
X("]" , TOK_R_BRACKET , SPL_V0 ) \
X("(" , TOK_L_PAREN , SPL_V0 ) \
X(")" , TOK_R_PAREN , SPL_V0 ) \
X("{" , TOK_L_BRACE , SPL_V0 ) \
X("}" , TOK_R_BRACE , SPL_V0 ) \
X(";" , TOK_SEMICOLON , SPL_V0 ) \
X("," , TOK_COMMA , SPL_V0 ) \
X(":" , TOK_COLON , SPL_V0 ) \
X(":=" , TOK_COLON_ASSIGN , SPL_V0 ) \
X("." , TOK_DOT , SPL_V0 ) \
X(".." , TOK_RANGE , SPL_V0 ) \
X("..." , TOK_ELLIPSIS , SPL_V0 ) \
X("=>" , TOK_FAT_ARROW , SPL_V0 ) \
X("?" , TOK_COND , SPL_V0 ) \
X(ident , TOK_IDENT , SPL_V0 ) \
X(int , TOK_INT_LITERAL , SPL_V0 ) \
X(float , TOK_FLOAT_LITERAL , SPL_V0 ) \
X(char , TOK_CHAR_LITERAL , SPL_V0 ) \
X(string , TOK_STRING_LITERAL , SPL_V0 ) \
// TOKEN_TABLE
/* clang-format on */
typedef enum {
#define X(name, enum_name, dummy) enum_name,
KEYWORD_TABLE
#undef X
#define X(name, enum_name, dummy) enum_name,
TOKEN_TABLE
#undef X
} spl_tok_type_t;
typedef struct {
spl_tok_type_t type;
const char *lexeme;
usize len;
const char *fname;
usize offset;
usize line;
usize col;
} spl_tok_t;
typedef VEC(spl_tok_t) spl_tok_vec_t;
#endif /* __SPL_TOK_H__ */

257
stage1/spl_type.c Normal file
View File

@@ -0,0 +1,257 @@
#include "spl_type.h"
static usize spl_type_hash(spl_type_node_t n) { return 0; }
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) { return 1; }
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t type_node) {
spl_type_id_t ret = 0;
int ok = map_get(type->type_map, type_node, &ret);
if (ok) {
return ret;
}
map_put(type->type_map, type_node, vec_size(type->type_table));
vec_push(type->type_table, type_node);
return vec_size(type->type_table) - 1;
}
spl_type_id_t spl_type_def_alloc(spl_type_t *type) {
vec_push(type->def_table, (spl_def_node_t){0});
return vec_size(type->def_table) - 1;
}
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_hash, spl_type_eq);
vec_init(type->def_table);
vec_push(type->def_table, (spl_def_node_t){0});
spl_type_node_push(type, (spl_type_node_t){.kind = SPL_TYPE_VOID});
spl_type_node_push(type, (spl_type_node_t){.kind = SPL_TYPE_BOOL});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 8,
.int_type.is_signed = false,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 16,
.int_type.is_signed = false,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 32,
.int_type.is_signed = false,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 64,
.int_type.is_signed = false,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 8,
.int_type.is_signed = true,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 16,
.int_type.is_signed = true,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 32,
.int_type.is_signed = true,
});
spl_type_node_push(type, (spl_type_node_t){
.kind = SPL_TYPE_INT,
.int_type.bits = 64,
.int_type.is_signed = true,
});
spl_type_node_push(type, (spl_type_node_t){.kind = SPL_TYPE_FLOAT, .float_type.bits = 32});
spl_type_node_push(type, (spl_type_node_t){.kind = SPL_TYPE_FLOAT, .float_type.bits = 64});
}
void spl_type_drop(spl_type_t *type) {
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);
break;
case SPL_TYPE_ENUM:
vec_free(n->adt_type.variants);
break;
case SPL_TYPE_FN:
vec_free(n->fn_type.params);
break;
default:
break;
}
}
vec_for(type->def_table, i) {
spl_def_node_t *d = &vec_at(type->def_table, 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_node_t *spl_type_node(spl_type_t *type, spl_type_id_t id) {
if (!id || id >= vec_size(type->type_table))
return NULL;
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 >= vec_size(type->def_table))
return NULL;
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)");
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_INT:
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
break;
case SPL_TYPE_FLOAT:
printf("f%zu", n->float_type.bits);
break;
case SPL_TYPE_PTR:
printf("*");
spl_type_pure_dump(type, n->ptr_pointee);
break;
case SPL_TYPE_SLICE:
printf("[]");
spl_type_pure_dump(type, n->slice_element);
break;
case SPL_TYPE_RANGE:
printf("range[");
spl_type_pure_dump(type, n->range_element);
printf("]");
break;
case SPL_TYPE_ARRAY:
printf("[%zu]", n->array_type.len);
spl_type_pure_dump(type, n->array_type.element);
break;
case SPL_TYPE_STRUCT:
printf("struct{%zu fields}", n->agg_field_types.size);
break;
case SPL_TYPE_UNION:
printf("union{%zu fields}", n->agg_field_types.size);
break;
case SPL_TYPE_ENUM:
printf("enum{%zu variants}", n->adt_type.variants.size);
break;
case SPL_TYPE_FN: {
printf("fn(");
for (usize i = 0; i < n->fn_type.params.size; i++) {
if (i)
printf(",");
spl_type_pure_dump(type, n->fn_type.params.data[i]);
}
printf(") -> ");
spl_type_pure_dump(type, n->fn_type.ret);
break;
}
case SPL_TYPE_ID:
printf("id#%zu", n->type_id);
break;
}
}
void spl_type_def_dump(spl_type_t *type, spl_def_id_t id) {
spl_def_node_t *node = spl_type_def(type, id);
if (!node) {
printf("(err)");
return;
}
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:
def_kind_name = "member";
break;
case SPL_DEF_VAR:
def_kind_name = "var";
break;
case SPL_DEF_FN_PARAMS:
def_kind_name = "params";
break;
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", def_kind_name, node->type_id);
switch (node->kind) {
case SPL_DEF_VAR:
printf(" var=%s", node->var_def.name ? node->var_def.name : "?");
break;
case SPL_DEF_MEMBER:
printf(" member=%s", node->var_def.name ? node->var_def.name : "?");
break;
case SPL_DEF_ALIAS:
case SPL_DEF_DISTINCT:
printf(" type=%s", node->type_def.name ? node->type_def.name : "?");
break;
case SPL_DEF_AGG:
printf(" agg{");
for (usize i = 0; i < node->agg_def.size; i++) {
if (i)
printf(",");
printf("%s", node->agg_def.data[i].name ? node->agg_def.data[i].name : "?");
}
printf("}");
break;
case SPL_DEF_FN_PARAMS:
printf(" fn(");
for (usize i = 0; i < node->fn_params_def.size; i++) {
if (i)
printf(",");
printf("%s", node->fn_params_def.data[i].name ? node->fn_params_def.data[i].name : "?");
}
printf(")");
break;
default:
break;
}
}

110
stage1/spl_type.h Normal file
View File

@@ -0,0 +1,110 @@
#ifndef __SPL_TYPE_H__
#define __SPL_TYPE_H__
#include "../stage0/include/utils.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 {
SPL_TYPE_ERROR,
SPL_TYPE_VOID,
SPL_TYPE_BOOL,
SPL_TYPE_INT,
SPL_TYPE_FLOAT,
SPL_TYPE_PTR,
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;
struct {
enum { AUTO, EXTERN_C, PACKED } mode;
usize fixed_align_bits;
} layout;
union {
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
spl_type_id_t ptr_pointee;
spl_type_id_t slice_element;
spl_type_id_t range_element;
struct {
spl_type_id_t element;
usize len;
} array_type;
spl_type_id_vec_t agg_field_types;
struct {
spl_type_id_vec_t variants;
spl_type_id_t tag_type;
} adt_type; // ADT
struct {
spl_type_id_vec_t params;
spl_type_id_t ret;
} fn_type;
spl_type_id_t type_id;
};
} 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;
} spl_var_def_t;
typedef VEC(spl_var_def_t) spl_var_def_vec_t;
typedef struct {
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_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;
};
} spl_def_node_t;
typedef VEC(spl_def_node_t) spl_def_node_vec_t;
typedef MAP(spl_type_node_t, usize) spl_type_node_map_t;
typedef struct {
spl_type_node_vec_t type_table;
// TODO hashconsing
spl_type_node_map_t type_map;
spl_def_node_vec_t def_table;
} spl_type_t;
void spl_type_init(spl_type_t *type);
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_node_t *spl_type_node(spl_type_t *type, spl_type_id_t id);
spl_def_node_t *spl_type_def(spl_type_t *type, spl_def_id_t id);
spl_type_id_t spl_type_def_alloc(spl_type_t *type);
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t type_node);
#endif /* __SPL_TYPE_H__ */

291
stage1/splc0.c Normal file
View File

@@ -0,0 +1,291 @@
/* splc0.c - SPL compiler CLI (stage 1, 引导用)
*
* splc0 --dump tokens|ast|all <file> dump 前端产物
* splc0 <in> <out> 编译 (阶段 B 实现)
*/
#define __SCC_LOG_IMPL_IMPORT_SRC__
#include "../stage0/include/utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spl_ast.h"
#include "spl_ast2ir.h"
#include "spl_ir2vm.h"
#include "spl_lexer.h"
#include "spl_sema.h"
#include "spl_tok.h"
static char *read_file(const char *path, long *out_len) {
FILE *f = fopen(path, "rb");
if (!f) {
perror("fopen");
return NULL;
}
fseek(f, 0, SEEK_END);
long len = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = malloc((size_t)len + 1);
if (!buf) {
fclose(f);
return NULL;
}
fread(buf, 1, (size_t)len, f);
fclose(f);
buf[len] = '\0';
*out_len = len;
return buf;
}
static const char *const tok_type_names[] = {
#define X(name, enum_name, dummy) #enum_name,
KEYWORD_TABLE
#undef X
#define X(name, enum_name, dummy) #enum_name,
TOKEN_TABLE
#undef X
};
static void dump_tokens(const char *src, const char *fname) {
spl_tok_vec_t toks = spl_lex(src, fname);
printf("tokens got (%zu)\n", toks.size);
for (usize i = 0; i < toks.size; i++) {
const spl_tok_t *t = &toks.data[i];
printf("[%s] %.*s (%zu:%zu)\n", tok_type_names[t->type], (int)t->len, t->lexeme, t->line,
t->col);
}
vec_free(toks);
}
static void dump_ast(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 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);
return 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);
// return 1;
// }
// 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, no output\n", sema.error_count);
// spl_sema_drop(&sema);
// spl_ast_drop(&ast);
// return 1;
// }
// spl_ast2ir_t a2ir;
// spl_ast2ir_init(&a2ir, &sema);
// spl_ast2ir_run(&a2ir);
// if (a2ir.err_count) {
// printf("ast2ir errors=%d, no output\n", a2ir.err_count);
// spl_ast2ir_drop(&a2ir);
// spl_sema_drop(&sema);
// 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;
return 0;
}
int main(int argc, char **argv) {
if (argc < 2) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
LOG_INFO("splc0 <in> <out> compile (.spl -> .sir, stage B)");
LOG_INFO("splc0 --dump <flags> <file> dump: tokens,ast,sema,ir,all");
return 0;
}
int argi = 1;
if (argi >= argc) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
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]);
}
/* splc0 [-g] <in> <out> */
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] or splc0 --dump <flags> <file>\n");
return 1;
}
int gen_debug = 0;
if (strcmp(argv[argi], "-g") == 0) {
gen_debug = 1;
argi++;
}
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] or splc0 --dump <flags> <file>\n");
return 1;
}
long len;
char *src = read_file(argv[argi], &len);
if (!src)
return 1;
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug);
free(src);
return rc;
}