Compare commits

..

5 Commits

17 changed files with 5109 additions and 784 deletions

1
.gitignore vendored
View File

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

417
build.py
View File

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

294
nob.c Normal file
View File

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

3390
nob.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,52 +0,0 @@
vm = [
"stage0/spl_mcode.c",
"stage0/spl_syscall.c",
"stage0/spl_vm.c",
]
splc0_part = [
"stage1/spl_ast.c",
"stage1/spl_lexer.c",
"stage1/spl_dumptree.c",
"stage1/spl_type.c",
"stage1/spl_sema.c",
"stage1/spl_ir.c",
"stage1/spl_ast2ir.c",
# "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"},
}

View File

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

View File

@@ -59,14 +59,14 @@ int main(int argc, const char **argv) {
/* annotate jumps / calls */
if (ins->opcode == SPL_JMP || ins->opcode == SPL_BZ || ins->opcode == SPL_BNZ) {
long long target = (long long)i + 1 + (long long)ins->imm;
printf(" ; -> %zd", target);
spl_vm_val_t target = i + 1 + ins->imm;
printf(" ; -> %zu", target);
} else if (ins->opcode == SPL_CALL) {
printf(" ; nargs=%zd, from stack", (long long)ins->imm);
printf(" ; nargs=%zu, from stack", ins->imm);
} else if (ins->opcode == SPL_CALLI) {
printf(" ; indirect call");
} else if (ins->opcode == SPL_GADDR) {
printf(" ; gdata[%zd]", (long long)ins->imm);
printf(" ; gdata[%zu]", ins->imm);
}
printf("\n");
}

View File

@@ -599,7 +599,10 @@ void spl_vm_add_breakpoint_fn(spl_vm_t *vm, const char *name) {
for (usize i = 0; i < vec_size(vm->fn_breakpoints); i++)
if (strcmp(vm->fn_breakpoints.data[i], name) == 0)
return;
vec_push(vm->fn_breakpoints, strdup(name));
char *cpname = malloc(strlen(name) + 1);
Assert(cpname != NULL);
strcpy(cpname, name);
vec_push(vm->fn_breakpoints, cpname);
}
void spl_vm_clear_breakpoints(spl_vm_t *vm) {

View File

@@ -409,7 +409,7 @@ static spl_ast_node_ref_t parse_type_decl(parser_t *p, spl_ast_node_ref_vec_t at
if (t && (t->type == TOK_COMMA || t->type == TOK_SEMICOLON)) {
advance(p);
} else {
LOG_WARN("need comma or semicolon with member decl");
SPL_WARN(t, "need comma or semicolon with member decl");
}
return ref;
}
@@ -434,7 +434,7 @@ static spl_ast_node_ref_t parse_member_decl(parser_t *p, spl_ast_node_ref_vec_t
if (t && (t->type == TOK_COMMA || t->type == TOK_SEMICOLON)) {
advance(p);
} else {
LOG_WARN("need comma or semicolon with member decl");
SPL_WARN(t, "need comma or semicolon with member decl");
}
return ref;
}
@@ -484,7 +484,7 @@ static spl_ast_node_ref_t parse_var_const_decl(parser_t *p, spl_ast_node_ref_vec
if (t && t->type == TOK_SEMICOLON) {
advance(p);
} else {
LOG_WARN("need semicolon in decl var/const");
SPL_WARN(t, "need semicolon in decl var/const");
}
return ref;
}
@@ -1848,9 +1848,10 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
for (usize i = 0; i < vec_size(*stack); i++)
printf("%s", vec_at(*stack, i) ? " " : "| ");
printf("%s%s #%zu", last ? "`-" : "|-", spl_ast_kind_name(node->kind), node_ref);
printf("%s%s #%zu ID`%zu`", last ? "`-" : "|-", spl_ast_kind_name(node->kind), node_ref,
node->resolved_type_id);
if (node->dbg.fname)
printf(" (%d:%d)", node->dbg.line, node->dbg.col);
printf(" [%d:%d]", node->dbg.line, node->dbg.col);
printf("\n");
vec_push(*stack, last);
@@ -1867,8 +1868,10 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
case SPL_AST_FN_DEFINE:
dump_vec(ast, node->fn_decl.attr_list, stack);
dump_vec(ast, node->fn_decl.param_list, stack);
if (node->fn_decl.type_expr)
dump_node(ast, node->fn_decl.type_expr, stack, 1);
if (node->fn_decl.type_expr) {
last = node->kind == SPL_AST_FN_DECL ? 1 : 0;
dump_node(ast, node->fn_decl.type_expr, stack, last);
}
dump_vec(ast, node->fn_decl.block, stack);
break;

View File

@@ -139,7 +139,10 @@ struct spl_ast_node {
spl_ast_node_kind_t kind;
spl_dbg_node_t dbg;
union {
usize resolved_def_id;
usize resolved_type_id;
};
union {
spl_ast_node_ref_vec_t container_members; /* container_decl */
@@ -152,7 +155,7 @@ struct spl_ast_node {
spl_ast_node_ref_vec_t attr_list; /* attr_item */
const char *name;
spl_ast_node_ref_vec_t param_list; /* param_decl */
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t type_expr; /* ret type expr */
spl_ast_node_ref_vec_t block; /* 语句/尾表达式 */
} fn_decl;
struct {

View File

@@ -58,7 +58,7 @@ static spl_ir_node_ref_t transit(spl_ir_builder_t *ir, const spl_sema_t *sema,
if (n->ret_statement.expr) {
ret = transit(ir, sema, n->ret_statement.expr);
}
ret = spl_ir_builder_control_ret(ir, tid_from_def(sema, n->resolved_def_id), ret);
ret = spl_ir_builder_control_ret(ir, n->resolved_type_id, ret);
} break;
case SPL_AST_BREAK_STATEMENT:
case SPL_AST_CONTINUE_STATEMENT:
@@ -111,8 +111,7 @@ static spl_ir_node_ref_t transit(spl_ir_builder_t *ir, const spl_sema_t *sema,
TODO();
break;
case SPL_AST_EXPR_INTEGER_LIT: {
ret = spl_ir_builder_type_const_int(ir, tid_from_def(sema, n->resolved_def_id),
n->primary_expr.integer_expr);
ret = spl_ir_builder_type_const_int(ir, n->resolved_type_id, n->primary_expr.integer_expr);
break;
}
case SPL_AST_EXPR_FLOAT_LIT:

View File

@@ -10,8 +10,16 @@ typedef struct {
// 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__)
#define SPL_FATAL(dbg, fmt, ...) \
LOG_FATAL("fatal at %s:%zd:%zd " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#define SPL_ERROR(dbg, fmt, ...) \
LOG_ERROR("error at %s:%zd:%zd " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#define SPL_WARN(dbg, fmt, ...) \
LOG_ERROR("warn at %s:%zd:%zd " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#endif /* __SPL_DBG_H__ */

View File

@@ -222,7 +222,7 @@ typedef struct {
SPL_IR_ATTR_NAKED, /* 不实现 */
SPL_IR_ATTR_NOINLINE, /* 不实现 */
SPL_IR_ATTR_ALWAYSINLINE, /* 不实现 */
};
} kind;
} spl_ir_attr_t;
typedef VEC(spl_ir_attr_t) spl_ir_attr_vec_t;

File diff suppressed because it is too large Load Diff

View File

@@ -43,6 +43,8 @@ typedef struct {
spl_scope_t *scope;
spl_symbol_t root;
int error_count;
spl_scope_id_t store_scope;
spl_type_id_t current_fn_ret_tid; // TODO
} spl_sema_t;
void spl_sema_init(spl_sema_t *sema, spl_ast_t *ast, spl_type_t *type, spl_scope_t *scope);

View File

@@ -1,6 +1,60 @@
#include "spl_type.h"
static usize spl_type_hash(spl_type_node_t n) { return n.kind; }
static usize spl_type_hash(spl_type_node_t n) {
usize hash = n.kind << 20;
switch (n.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_VOID:
case SPL_TYPE_BOOL:
case SPL_TYPE_UNDEFINED:
case SPL_TYPE_NULL:
break;
case SPL_TYPE_INT:
hash += n.int_type.bits + n.int_type.is_signed;
break;
case SPL_TYPE_FLOAT:
hash += n.float_type.bits;
break;
case SPL_TYPE_PTR:
hash += n.ptr_pointee;
break;
case SPL_TYPE_SLICE:
hash += n.slice_element;
break;
case SPL_TYPE_RANGE:
hash += n.range_element;
break;
case SPL_TYPE_ARRAY:
hash += n.array_type.element + n.array_type.len;
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
hash += n.layout.mode * 31 + n.layout.fixed_align_bits;
vec_for(n.agg_members, i) {
hash += (n.agg_members.data[i].name ? map_hash_str(n.agg_members.data[i].name) : 0) +
n.agg_members.data[i].type_id;
}
break;
case SPL_TYPE_ENUM:
hash += n.layout.mode * 31 + n.layout.fixed_align_bits;
hash += n.adt_type.tag_type;
vec_for(n.adt_type.variants, i) {
hash +=
(n.adt_type.variants.data[i].name ? map_hash_str(n.adt_type.variants.data[i].name)
: 0) +
n.adt_type.variants.data[i].type_id;
}
break;
case SPL_TYPE_FN:
hash += n.fn_type.ret;
vec_for(n.fn_type.params, i) { hash += vec_at(n.fn_type.params, i); }
break;
default: // TODO
break;
}
return hash;
}
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
if (n1.kind != n2.kind)
return 1;
@@ -8,6 +62,8 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
case SPL_TYPE_ERROR:
case SPL_TYPE_VOID:
case SPL_TYPE_BOOL:
case SPL_TYPE_UNDEFINED:
case SPL_TYPE_NULL:
break;
case SPL_TYPE_INT:
if (n1.int_type.bits != n2.int_type.bits)
@@ -37,80 +93,264 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
if (n1.array_type.len != n2.array_type.len)
return 1;
break;
// TODO
default:
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
if (vec_size(n1.agg_members) != vec_size(n2.agg_members))
return 1;
vec_for(n1.agg_members, i) {
const char *na = n1.agg_members.data[i].name;
const char *nb = n2.agg_members.data[i].name;
if (strcmp(na ? na : "", nb ? nb : "") != 0)
return 1;
if (n1.agg_members.data[i].type_id != n2.agg_members.data[i].type_id)
return 1;
}
break;
case SPL_TYPE_ENUM:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
if (n1.adt_type.tag_type != n2.adt_type.tag_type)
return 1;
if (vec_size(n1.adt_type.variants) != vec_size(n2.adt_type.variants))
return 1;
vec_for(n1.adt_type.variants, i) {
const char *na = n1.adt_type.variants.data[i].name;
const char *nb = n2.adt_type.variants.data[i].name;
if (strcmp(na ? na : "", nb ? nb : "") != 0)
return 1;
if (n1.adt_type.variants.data[i].type_id != n2.adt_type.variants.data[i].type_id)
return 1;
}
break;
case SPL_TYPE_FN:
if (n1.fn_type.ret != n2.fn_type.ret)
return 1;
if (vec_size(n1.fn_type.params) != vec_size(n2.fn_type.params))
return 1;
vec_for(n1.fn_type.params, i) {
if (vec_at(n1.fn_type.params, i) != vec_at(n2.fn_type.params, i))
return 1;
}
break;
default: // TODO
return 1;
}
return 0;
}
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;
static usize spl_type_map_hash(usize k) { return MAP_HASH_INT(k); }
static int spl_type_map_cmp(usize a, usize b) { return MAP_CMP_INT(a, b); }
static void spl_type_node_free_vecs(spl_type_node_t *tn) {
switch (tn->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
vec_free(tn->agg_members);
break;
case SPL_TYPE_ENUM:
vec_free(tn->adt_type.variants);
break;
case SPL_TYPE_FN:
vec_free(tn->fn_type.params);
break;
default:
break;
}
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});
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *tn) {
usize hash = spl_type_hash(*tn);
usize idx = (usize)-1;
spl_type_id_t cand = 0;
while (map_get_continue(type->type_map, hash, &cand, &idx)) {
spl_type_node_t *existing = &vec_at(type->type_table, cand);
if (spl_type_eq(*existing, *tn) == 0) {
spl_type_node_free_vecs(tn);
return cand;
}
}
spl_type_id_t id = vec_size(type->type_table);
vec_push(type->type_table, *tn);
map_put_new(type->type_map, hash, id);
tn->kind = SPL_TYPE_ERROR;
return id;
}
static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_type_id_t tid,
const char *name, usize *out_idx) {
spl_type_node_t *n = spl_type_node(type, tid);
if (!n || !name) {
return NULL;
}
if (n->kind == SPL_TYPE_STRUCT || n->kind == SPL_TYPE_UNION) {
vec_for(n->agg_members, i) {
const char *mn = n->agg_members.data[i].name;
if (strcmp(mn ? mn : "", name) == 0) {
if (out_idx) {
*out_idx = i;
}
return &n->agg_members.data[i];
}
}
} else if (n->kind == SPL_TYPE_ENUM) {
vec_for(n->adt_type.variants, i) {
const char *mn = n->adt_type.variants.data[i].name;
if (strcmp(mn ? mn : "", name) == 0) {
if (out_idx) {
*out_idx = i;
}
return &n->adt_type.variants.data[i];
}
}
}
return NULL;
}
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid,
const char *name) {
return spl_type_agg_member_find(type, tid, name, NULL);
}
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name,
usize *out_idx) {
return spl_type_agg_member_find(type, tid, name, out_idx) != NULL;
}
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind) {
spl_type_node_t tn = {0};
tn.kind = kind;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_INT;
tn.int_type.bits = bits;
tn.int_type.is_signed = is_signed;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FLOAT;
tn.float_type.bits = bits;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_PTR;
tn.ptr_pointee = pointee;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_slice(spl_type_t *type, spl_type_id_t element) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_SLICE;
tn.slice_element = element;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_range(spl_type_t *type, spl_type_id_t element) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_RANGE;
tn.range_element = element;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_ARRAY;
tn.array_type.element = element;
tn.array_type.len = len;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
usize nparams) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FN;
vec_init(tn.fn_type.params);
for (usize i = 0; i < nparams; i++) {
vec_push(tn.fn_type.params, params[i]);
}
tn.fn_type.ret = ret;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
const spl_type_member_t *members, usize nmembers,
spl_type_id_t tag_type, spl_type_layout_t layout) {
spl_type_node_t tn = {0};
tn.kind = tk;
tn.layout = layout;
if (tk == SPL_TYPE_ENUM) {
vec_init(tn.adt_type.variants);
for (usize i = 0; i < nmembers; i++) {
vec_push(tn.adt_type.variants, members[i]);
}
tn.adt_type.tag_type = tag_type;
} else {
vec_init(tn.agg_members);
for (usize i = 0; i < nmembers; i++) {
vec_push(tn.agg_members, members[i]);
}
}
return spl_type_node_push(type, &tn);
}
spl_def_id_t spl_type_def_alloc(spl_type_t *type, spl_def_node_kind_t kind, const char *name,
spl_dbg_node_t dbg, usize ast_node_ref) {
spl_def_node_t n = {0};
n.kind = kind;
n.name = name;
n.dbg_node = dbg;
n.ast_node_ref = ast_node_ref;
vec_push(type->def_table, n);
return vec_size(type->def_table) - 1;
}
void spl_type_def_resolve(spl_type_t *type, spl_def_id_t id, spl_type_id_t tid) {
spl_def_node_t *d = spl_type_def(type, id);
if (!d) {
return;
}
d->type_id = tid;
}
spl_type_id_t spl_type_fn_param_tid(spl_type_t *type, spl_type_id_t fn_tid, usize idx) {
spl_type_node_t *n = spl_type_node(type, fn_tid);
if (!n || n->kind != SPL_TYPE_FN || idx >= vec_size(n->fn_type.params))
return 0;
return vec_at(n->fn_type.params, idx);
}
void spl_type_init(spl_type_t *type) {
vec_init(type->type_table);
vec_push(type->type_table, (spl_type_node_t){0});
map_init(type->type_map, spl_type_hash, spl_type_eq);
map_init(type->type_map, spl_type_map_hash, spl_type_map_cmp);
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});
spl_type_builder_simple(type, SPL_TYPE_VOID);
spl_type_builder_simple(type, SPL_TYPE_BOOL);
spl_type_builder_simple(type, SPL_TYPE_UNDEFINED);
spl_type_builder_simple(type, SPL_TYPE_NULL);
spl_type_builder_int(type, 8, false);
spl_type_builder_int(type, 16, false);
spl_type_builder_int(type, 32, false);
spl_type_builder_int(type, 64, false);
spl_type_builder_int(type, 8, true);
spl_type_builder_int(type, 16, true);
spl_type_builder_int(type, 32, true);
spl_type_builder_int(type, 64, true);
spl_type_builder_float(type, 32);
spl_type_builder_float(type, 64);
}
void spl_type_drop(spl_type_t *type) {
@@ -119,7 +359,7 @@ void spl_type_drop(spl_type_t *type) {
switch (n->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
vec_free(n->agg_field_types);
vec_free(n->agg_members);
break;
case SPL_TYPE_ENUM:
vec_free(n->adt_type.variants);
@@ -132,20 +372,6 @@ void spl_type_drop(spl_type_t *type) {
}
}
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);
@@ -166,7 +392,7 @@ spl_def_node_t *spl_type_def(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 *n = spl_type_node(type, id);
if (!n) {
printf("(err)");
printf("none");
return;
}
switch (n->kind) {
@@ -179,11 +405,25 @@ void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
case SPL_TYPE_BOOL:
printf("bool");
break;
case SPL_TYPE_UNDEFINED:
printf("undefined");
break;
case SPL_TYPE_NULL:
printf("null");
break;
case SPL_TYPE_INT:
if (n->int_type.bits == 0) {
printf("comptime_int");
} else {
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
}
break;
case SPL_TYPE_FLOAT:
if (n->float_type.bits == 0) {
printf("comptime_float");
} else {
printf("f%zu", n->float_type.bits);
}
break;
case SPL_TYPE_PTR:
printf("*");
@@ -203,20 +443,48 @@ void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
spl_type_pure_dump(type, n->array_type.element);
break;
case SPL_TYPE_STRUCT:
printf("struct{%zu fields}", n->agg_field_types.size);
printf("struct{");
vec_for(n->agg_members, i) {
if (i) {
printf(", ");
}
spl_type_member_t *member = &vec_at(n->agg_members, i);
printf("%s:", member->name ? member->name : "?");
spl_type_pure_dump(type, member->type_id);
}
printf("}");
break;
case SPL_TYPE_UNION:
printf("union{%zu fields}", n->agg_field_types.size);
printf("union{");
vec_for(n->agg_members, i) {
if (i) {
printf(", ");
}
spl_type_member_t *member = &vec_at(n->agg_members, i);
printf("%s:", member->name ? member->name : "?");
spl_type_pure_dump(type, member->type_id);
}
printf("}");
break;
case SPL_TYPE_ENUM:
printf("enum{%zu variants}", n->adt_type.variants.size);
printf("enum{"); // TODO tag_type
vec_for(n->adt_type.variants, i) {
if (i) {
printf(", ");
}
spl_type_member_t *member = &vec_at(n->adt_type.variants, i);
printf("%s:", member->name ? member->name : "?");
spl_type_pure_dump(type, member->type_id);
}
printf("}");
break;
case SPL_TYPE_FN: {
printf("fn(");
for (usize i = 0; i < n->fn_type.params.size; i++) {
if (i)
vec_for(n->fn_type.params, i) {
if (i) {
printf(",");
spl_type_pure_dump(type, n->fn_type.params.data[i]);
}
spl_type_pure_dump(type, vec_at(n->fn_type.params, i));
}
printf(") -> ");
spl_type_pure_dump(type, n->fn_type.ret);
@@ -231,7 +499,7 @@ void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
void spl_type_def_dump(spl_type_t *type, spl_def_id_t id) {
spl_def_node_t *node = spl_type_def(type, id);
if (!node) {
printf("(err)");
printf("none");
return;
}
@@ -250,7 +518,7 @@ void spl_type_def_dump(spl_type_t *type, spl_def_id_t id) {
def_kind_name = "var";
break;
case SPL_DEF_FN_PARAMS:
def_kind_name = "params";
def_kind_name = "fn_params";
break;
case SPL_DEF_AGG:
def_kind_name = "agg";
@@ -262,37 +530,6 @@ void spl_type_def_dump(spl_type_t *type, spl_def_id_t id) {
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;
}
printf("kind=%s type_id=%zu name=%s", def_kind_name, node->type_id,
node->name ? node->name : "?");
}

View File

@@ -9,13 +9,14 @@ typedef VEC(spl_type_id_t) spl_type_id_vec_t;
typedef usize spl_def_id_t; /* 0 is error */
typedef VEC(spl_def_id_t) spl_def_id_vec_t;
typedef struct {
enum {
typedef enum {
SPL_TYPE_ERROR,
SPL_TYPE_VOID,
SPL_TYPE_BOOL,
SPL_TYPE_INT,
SPL_TYPE_FLOAT,
SPL_TYPE_UNDEFINED, // 自动配对任意类型的字面量,值为 undefined
SPL_TYPE_NULL, // 自动配对指针/切片的字面量,值为 0
SPL_TYPE_PTR,
SPL_TYPE_SLICE, // 未来拥有泛型后删除
SPL_TYPE_RANGE, // 未来拥有泛型后删除
@@ -25,11 +26,29 @@ typedef struct {
SPL_TYPE_ENUM,
SPL_TYPE_FN,
SPL_TYPE_ID,
} kind;
struct {
enum { AUTO, EXTERN_C, PACKED } mode;
} spl_type_node_kind_t;
typedef enum {
SPL_TYPE_LAYOUT_AUTO,
SPL_TYPE_LAYOUT_EXTERN_C,
SPL_TYPE_LAYOUT_PACKED,
} spl_type_layout_mode_t;
typedef struct {
spl_type_layout_mode_t mode;
usize fixed_align_bits;
} layout;
} spl_type_layout_t;
typedef struct {
const char *name;
spl_type_id_t type_id;
usize ast_node_ref; // 回 AST member_decl 节点引用 dbg/IDE 定位用 不参与 hash
} spl_type_member_t;
typedef VEC(spl_type_member_t) spl_type_member_vec_t;
typedef struct {
spl_type_node_kind_t kind;
spl_type_layout_t layout;
union {
struct {
usize bits;
@@ -45,9 +64,9 @@ typedef struct {
spl_type_id_t element;
usize len;
} array_type;
spl_type_id_vec_t agg_field_types;
spl_type_member_vec_t agg_members;
struct {
spl_type_id_vec_t variants;
spl_type_member_vec_t variants;
spl_type_id_t tag_type;
} adt_type; // ADT
struct {
@@ -59,16 +78,7 @@ typedef struct {
} spl_type_node_t;
typedef VEC(spl_type_node_t) spl_type_node_vec_t;
typedef struct {
const char *name;
spl_def_id_t def_id;
spl_type_id_t type_id;
usize scope_id;
} spl_var_def_t;
typedef VEC(spl_var_def_t) spl_var_def_vec_t;
typedef struct {
enum {
typedef enum {
SPL_DEF_ERROR,
SPL_DEF_SCALAR,
SPL_DEF_MEMBER,
@@ -77,22 +87,20 @@ typedef struct {
SPL_DEF_AGG, // include enum variants
SPL_DEF_DISTINCT, // newtype
SPL_DEF_ALIAS, // sametypes
} kind;
} spl_def_node_kind_t;
typedef struct {
spl_def_node_kind_t kind;
const char *name;
spl_dbg_node_t dbg_node;
spl_type_id_t type_id;
union {
spl_var_def_t var_def;
spl_var_def_vec_t agg_def; // include enum variants
spl_var_def_vec_t fn_params_def;
spl_var_def_t type_def;
};
usize ast_node_ref;
} 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 MAP(usize, spl_type_id_t) 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;
@@ -106,7 +114,25 @@ 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);
spl_type_id_t spl_type_def_alloc(spl_type_t *type, spl_def_node_kind_t kind, const char *name,
spl_dbg_node_t dbg, usize ast_node_ref);
void spl_type_def_resolve(spl_type_t *type, spl_def_id_t id, spl_type_id_t tid);
spl_type_id_t spl_type_fn_param_tid(spl_type_t *type, spl_type_id_t fn_tid, usize idx);
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid, const char *name);
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name, usize *out_idx);
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *type_node);
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind);
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed);
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits);
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee);
spl_type_id_t spl_type_builder_slice(spl_type_t *type, spl_type_id_t element);
spl_type_id_t spl_type_builder_range(spl_type_t *type, spl_type_id_t element);
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len);
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
usize nparams);
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
const spl_type_member_t *members, usize nmembers,
spl_type_id_t tag_type, spl_type_layout_t layout);
#endif /* __SPL_TYPE_H__ */