Compare commits
8 Commits
78d767bf21
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| f1d86b6e34 | |||
| 0f40de43a1 | |||
| d6113a5417 | |||
| c81a57dacb | |||
| b2e6ade484 | |||
| 994a35a942 | |||
| 4d9509c167 | |||
| d3c63dab5c |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,5 +8,6 @@ build/
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
*.old
|
||||
*.exe
|
||||
*.out
|
||||
|
||||
417
build.py
417
build.py
@@ -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
294
nob.c
Normal 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;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
vm = [
|
||||
"stage0/spl_mcode.c",
|
||||
"stage0/spl_syscall.c",
|
||||
"stage0/spl_vm.c",
|
||||
]
|
||||
|
||||
splc0_part = [
|
||||
# "stage1/spl_ir.c",
|
||||
"stage1/spl_ast.c",
|
||||
"stage1/spl_lexer.c",
|
||||
"stage1/spl_dumptree.c",
|
||||
# "stage1/spl_type.c",
|
||||
# "stage1/spl_sema.c",
|
||||
# "stage1/spl_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"},
|
||||
}
|
||||
@@ -77,6 +77,8 @@ static inline usize map_hash_str(const char *s) {
|
||||
for (usize(idx) = 0; (idx) < (map).cap; ++(idx)) \
|
||||
if ((map).data[(idx)].state == __MAP_SLOT_OCCUPIED)
|
||||
|
||||
#define unsafe_map_at(map, idx) ((map).data[(idx)])
|
||||
|
||||
/**
|
||||
* 插入(若键已存在则更新值)
|
||||
* 注意:扩容使用 realloc,失败会 abort(可自行修改错误处理)
|
||||
@@ -128,6 +130,56 @@ static inline usize map_hash_str(const char *s) {
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/**
|
||||
* 插入(仅当键不存在时),若键已存在则静默跳过,不更新值
|
||||
* 与 map_put 的差异仅在"键已存在时":map_put 更新值,map_put_new 放弃
|
||||
*/
|
||||
#define map_put_new(map, _key, _val) \
|
||||
do { \
|
||||
/* 扩容 */ \
|
||||
if ((map).cap == 0 || (map).size * 128 / (map).cap >= MAP_DEFAULT_LOAD_FACTOR) { \
|
||||
usize new_cap = (map).cap == 0 ? 8 : (map).cap * 2; \
|
||||
MAP_SLOT(MAP_TYPEOF((map).data->key), MAP_TYPEOF((map).data->val)) *new_data = \
|
||||
calloc(new_cap, sizeof(*new_data)); \
|
||||
if (!new_data) \
|
||||
abort(); \
|
||||
/* 重新插入旧元素 */ \
|
||||
for (usize _i = 0; _i < (map).cap; ++_i) { \
|
||||
if ((map).data[_i].state == __MAP_SLOT_OCCUPIED) { \
|
||||
usize _h = (map).hash((map).data[_i].key) & (new_cap - 1); \
|
||||
while (new_data[_h].state == __MAP_SLOT_OCCUPIED) \
|
||||
_h = (_h + 1) & (new_cap - 1); \
|
||||
new_data[_h].key = (map).data[_i].key; \
|
||||
new_data[_h].val = (map).data[_i].val; \
|
||||
new_data[_h].state = __MAP_SLOT_OCCUPIED; \
|
||||
} \
|
||||
} \
|
||||
free((map).data); \
|
||||
(map).data = (void *)new_data; \
|
||||
(map).cap = new_cap; \
|
||||
} \
|
||||
/* 查找 */ \
|
||||
usize _mask = (map).cap - 1; \
|
||||
usize _idx = (map).hash(_key) & _mask; \
|
||||
usize _first_del = (usize) - 1; \
|
||||
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
|
||||
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
|
||||
(map).cmp((map).data[_idx].key, _key) == 0) { \
|
||||
break; /* 已存在,不更新 */ \
|
||||
} \
|
||||
if ((map).data[_idx].state == __MAP_SLOT_DELETED && _first_del == (usize) - 1) \
|
||||
_first_del = _idx; \
|
||||
_idx = (_idx + 1) & _mask; \
|
||||
} \
|
||||
if ((map).data[_idx].state == __MAP_SLOT_EMPTY) { \
|
||||
usize _target = (_first_del != (usize) - 1) ? _first_del : _idx; \
|
||||
(map).data[_target].key = _key; \
|
||||
(map).data[_target].val = _val; \
|
||||
(map).data[_target].state = __MAP_SLOT_OCCUPIED; \
|
||||
++(map).size; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/**
|
||||
* 查询:若找到,*out_val 被赋值为对应值并返回 1;否则返回 0
|
||||
*/
|
||||
@@ -150,6 +202,33 @@ static inline usize map_hash_str(const char *s) {
|
||||
_found; \
|
||||
}))
|
||||
|
||||
/**
|
||||
* 查询(续探):首次调用前将 *in_out_idx 置为 (usize)-1,
|
||||
* 则从键自身的 hash 桶开始查找;命中后 *out_val 被赋值、返回 1,
|
||||
* 且 *in_out_idx 更新为命中槽位,下次调用从该槽的下一个继续探测(碰撞续探)。
|
||||
* 扫描到空槽返回 0。用于 key 碰撞后需要回表二次比较的场景。
|
||||
*/
|
||||
#define map_get_continue(map, _key, out_val, in_out_idx) \
|
||||
(({ \
|
||||
int _found = 0; \
|
||||
if ((map).cap > 0) { \
|
||||
usize _mask = (map).cap - 1; \
|
||||
usize _idx = (*(in_out_idx) == (usize) - 1) ? (map).hash(_key) & _mask \
|
||||
: (*(in_out_idx) + 1) & _mask; \
|
||||
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
|
||||
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
|
||||
(map).cmp((map).data[_idx].key, _key) == 0) { \
|
||||
*out_val = (map).data[_idx].val; \
|
||||
*(in_out_idx) = _idx; \
|
||||
_found = 1; \
|
||||
break; \
|
||||
} \
|
||||
_idx = (_idx + 1) & _mask; \
|
||||
} \
|
||||
} \
|
||||
_found; \
|
||||
}))
|
||||
|
||||
/**
|
||||
* 删除指定键
|
||||
*/
|
||||
|
||||
@@ -54,19 +54,19 @@ int main(int argc, const char **argv) {
|
||||
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(" %s", spl_vm_type_kind_name((spl_vm_kind_t)ins->type));
|
||||
printf(" %zd", ins->imm);
|
||||
|
||||
/* annotate jumps / calls */
|
||||
if (ins->opcode == SPL_JMP || ins->opcode == SPL_BZ || ins->opcode == SPL_BNZ) {
|
||||
long long target = (long long)i + 1 + (long long)ins->imm;
|
||||
printf(" ; -> %zd", target);
|
||||
spl_vm_val_t target = i + 1 + ins->imm;
|
||||
printf(" ; -> %zu", target);
|
||||
} else if (ins->opcode == SPL_CALL) {
|
||||
printf(" ; nargs=%zd, from stack", (long long)ins->imm);
|
||||
printf(" ; nargs=%zu, from stack", ins->imm);
|
||||
} else if (ins->opcode == SPL_CALLI) {
|
||||
printf(" ; indirect call");
|
||||
} else if (ins->opcode == SPL_GADDR) {
|
||||
printf(" ; gdata[%zd]", (long long)ins->imm);
|
||||
printf(" ; gdata[%zu]", ins->imm);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
@@ -427,7 +427,7 @@ const char *opcode_name[] = {
|
||||
#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) {
|
||||
const char *spl_vm_type_kind_name(spl_vm_kind_t type) {
|
||||
switch (type) {
|
||||
case SPL_VOID:
|
||||
return "void";
|
||||
@@ -467,7 +467,7 @@ 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) {
|
||||
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(" %s", spl_vm_type_kind_name((spl_vm_kind_t)ins->type));
|
||||
printf(" %zd:%zx", ins->imm, ins->imm);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ typedef enum {
|
||||
SPL_F64,
|
||||
SPL_PTR,
|
||||
SPL_TYPE_COUNT,
|
||||
} spl_type_t;
|
||||
} spl_vm_kind_t;
|
||||
|
||||
/* clang-format off */
|
||||
#define SPL_OPCODES(X) \
|
||||
@@ -213,7 +213,7 @@ 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);
|
||||
const char *spl_vm_type_kind_name(spl_vm_kind_t type);
|
||||
|
||||
void spl_vm_ins_dump(spl_vm_ins_t *ins, spl_vm_val_t addr);
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@
|
||||
* Type helpers
|
||||
* ================================================================ */
|
||||
|
||||
static int spl_is_float(spl_type_t t) { return t == SPL_F32 || t == SPL_F64; }
|
||||
static int spl_is_signed(spl_type_t t) {
|
||||
static int spl_is_float(spl_vm_kind_t t) { return t == SPL_F32 || t == SPL_F64; }
|
||||
static int spl_is_signed(spl_vm_kind_t t) {
|
||||
switch (t) {
|
||||
case SPL_I8:
|
||||
case SPL_I16:
|
||||
@@ -41,7 +41,7 @@ static int spl_is_signed(spl_type_t t) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
static int spl_type_size(spl_type_t t) {
|
||||
static int spl_type_size(spl_vm_kind_t t) {
|
||||
switch (t) {
|
||||
case SPL_VOID:
|
||||
return 0;
|
||||
@@ -123,7 +123,7 @@ static int spl_type_size(spl_type_t t) {
|
||||
do { \
|
||||
spl_vm_val_t _b = POP(), _a = POP(); \
|
||||
spl_vm_val_t _r = 0; \
|
||||
if (spl_is_float((spl_type_t)ins->type)) { \
|
||||
if (spl_is_float((spl_vm_kind_t)ins->type)) { \
|
||||
double _da, _db, _dr; \
|
||||
if (ins->type == SPL_F32) { \
|
||||
float _fa, _fb; \
|
||||
@@ -185,7 +185,7 @@ static int spl_type_size(spl_type_t t) {
|
||||
if (_b == 0) \
|
||||
VM_ERROR("division by zero"); \
|
||||
spl_vm_val_t _r = 0; \
|
||||
if (spl_is_float((spl_type_t)ins->type)) { \
|
||||
if (spl_is_float((spl_vm_kind_t)ins->type)) { \
|
||||
double _da, _db, _dr; \
|
||||
if (ins->type == SPL_F32) { \
|
||||
float _fa, _fb; \
|
||||
@@ -545,6 +545,7 @@ LONG WINAPI UnhandledExceptionFilterImpl(EXCEPTION_POINTERS *pExceptionInfo) {
|
||||
* ================================================================ */
|
||||
void spl_vm_init_ex(spl_vm_t *vm, int stack_size, int call_depth) {
|
||||
#ifdef _WIN32
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS);
|
||||
SetUnhandledExceptionFilter(UnhandledExceptionFilterImpl);
|
||||
SetConsoleOutputCP(CP_UTF8);
|
||||
SetConsoleCP(CP_UTF8);
|
||||
@@ -598,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) {
|
||||
@@ -843,7 +847,7 @@ int spl_vm_run_once(spl_vm_t *vm) {
|
||||
|
||||
case SPL_NEG: {
|
||||
spl_vm_val_t _a = POP();
|
||||
if (spl_is_float((spl_type_t)ins->type)) {
|
||||
if (spl_is_float((spl_vm_kind_t)ins->type)) {
|
||||
double _d;
|
||||
if (ins->type == SPL_F32) {
|
||||
float _f;
|
||||
|
||||
@@ -58,6 +58,7 @@ static inline spl_ast_node_t *node_at(spl_ast_t *ast, spl_ast_node_ref_t ref) {
|
||||
static spl_ast_node_ref_t new_node(parser_t *p, spl_ast_node_kind_t kind, const spl_tok_t *tok) {
|
||||
spl_ast_node_t n = {0};
|
||||
n.kind = kind;
|
||||
n.resolved_def_id = 0;
|
||||
if (tok) {
|
||||
n.dbg.dbg_name = spl_ast_kind_name(kind);
|
||||
n.dbg.fname = tok->fname;
|
||||
@@ -408,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;
|
||||
}
|
||||
@@ -433,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;
|
||||
}
|
||||
@@ -483,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;
|
||||
}
|
||||
@@ -1792,8 +1793,8 @@ void spl_ast_prase(spl_ast_t *ast) {
|
||||
if (d)
|
||||
vec_push(members, d);
|
||||
}
|
||||
spl_ast_node_ref_t root = new_node(&p, SPL_AST_CONTAINER_ITEM, begin);
|
||||
node_at(ast, root)->container_item.members = members;
|
||||
spl_ast_node_ref_t root = new_node(&p, SPL_AST_CONTAINER_MEMBERS, begin);
|
||||
node_at(ast, root)->container_members = members;
|
||||
ast->root = root;
|
||||
ast->parsed = p.failed ? -1 : 1;
|
||||
}
|
||||
@@ -1809,6 +1810,12 @@ void spl_ast_drop(spl_ast_t *ast) {
|
||||
ast->root = 0;
|
||||
}
|
||||
|
||||
spl_ast_node_t *spl_ast_node(spl_ast_t *ast, spl_ast_node_ref_t node) {
|
||||
if (!ast || node == 0)
|
||||
return NULL;
|
||||
return &vec_at(ast->node_buckets, node);
|
||||
}
|
||||
|
||||
void spl_ast_valid(spl_ast_t *ast) {
|
||||
if (!ast)
|
||||
return;
|
||||
@@ -1827,6 +1834,7 @@ void spl_ast_dump(spl_ast_t *ast, spl_ast_node_ref_t node) {
|
||||
return;
|
||||
dump_stack_t stack;
|
||||
vec_init(stack);
|
||||
printf("AST:\n");
|
||||
dump_node(ast, node, &stack, 1);
|
||||
}
|
||||
|
||||
@@ -1840,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);
|
||||
@@ -1851,17 +1860,18 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
|
||||
UNREACHABLE();
|
||||
break;
|
||||
|
||||
case SPL_AST_CONTAINER_ITEM:
|
||||
dump_vec(ast, node->container_item.attr_list, stack);
|
||||
dump_vec(ast, node->container_item.members, stack);
|
||||
case SPL_AST_CONTAINER_MEMBERS:
|
||||
dump_vec(ast, node->container_members, stack);
|
||||
break;
|
||||
|
||||
case SPL_AST_FN_DECL:
|
||||
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;
|
||||
|
||||
@@ -2104,6 +2114,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
|
||||
case SPL_AST_TYPE_STRUCT:
|
||||
case SPL_AST_TYPE_UNION:
|
||||
case SPL_AST_TYPE_ENUM:
|
||||
case SPL_AST_TYPE_SHAPE:
|
||||
dump_vec(ast, node->type_expr.attr_list, stack);
|
||||
dump_vec(ast, node->type_expr.aggregate_list, stack);
|
||||
break;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/* 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_CONTAINER_MEMBERS, V0, container_members) \
|
||||
X(SPL_AST_FN_DECL, V0, fn_decl) \
|
||||
X(SPL_AST_FN_DEFINE, V0, fn_define) \
|
||||
X(SPL_AST_TYPE_DECL, V0, type_decl) \
|
||||
@@ -97,6 +97,7 @@
|
||||
X(SPL_AST_TYPE_SLICE, V0, type_slice) \
|
||||
X(SPL_AST_TYPE_STRUCT, V0, type_struct) \
|
||||
X(SPL_AST_TYPE_UNION, V0, type_union) \
|
||||
X(SPL_AST_TYPE_SHAPE, V0, type_shape) \
|
||||
X(SPL_AST_TYPE_ENUM, V0, type_enum) \
|
||||
X(SPL_AST_TYPE_VOID, V0, type_void) \
|
||||
X(SPL_AST_TYPE_BOOL, V0, type_bool) \
|
||||
@@ -138,12 +139,12 @@ 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;
|
||||
usize resolved_def_id;
|
||||
usize resolved_type_id;
|
||||
};
|
||||
union {
|
||||
spl_ast_node_ref_vec_t container_members; /* container_decl */
|
||||
|
||||
struct {
|
||||
const char *ident;
|
||||
@@ -154,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 {
|
||||
@@ -314,6 +315,8 @@ typedef struct {
|
||||
void spl_ast_init(spl_ast_t *ast, const spl_tok_vec_t *tok_vec /*move*/);
|
||||
void spl_ast_drop(spl_ast_t *ast);
|
||||
|
||||
spl_ast_node_t* spl_ast_node(spl_ast_t *ast, spl_ast_node_ref_t node);
|
||||
|
||||
void spl_ast_prase(spl_ast_t *ast);
|
||||
void spl_ast_valid(spl_ast_t *ast);
|
||||
void spl_ast_dump(spl_ast_t *ast, spl_ast_node_ref_t node);
|
||||
|
||||
3383
stage1/spl_ast2ir.c
3383
stage1/spl_ast2ir.c
File diff suppressed because it is too large
Load Diff
@@ -4,21 +4,13 @@
|
||||
#include "spl_ir.h"
|
||||
#include "spl_sema.h"
|
||||
|
||||
/* 全局 var/const 的 def → gdata 向量中的 value 节点索引 */
|
||||
typedef struct {
|
||||
spl_def_id_t def_id;
|
||||
usize gdata_idx;
|
||||
} spl_ast2ir_gref_t;
|
||||
|
||||
typedef struct {
|
||||
const spl_sema_t *sema;
|
||||
spl_ir_t ir;
|
||||
VEC(char *) owned_names; /* 本模块 malloc 的函数名,drop 时释放 */
|
||||
VEC(spl_ast2ir_gref_t) gdata_ref; /* def_id → gdata value 节点索引 */
|
||||
spl_ir_builder_t *ir;
|
||||
int err_count;
|
||||
} spl_ast2ir_t;
|
||||
|
||||
void spl_ast2ir_init(spl_ast2ir_t *ast2ir, const spl_sema_t *sema);
|
||||
void spl_ast2ir_init(spl_ast2ir_t *ast2ir, spl_ir_builder_t *ir, const spl_sema_t *sema);
|
||||
void spl_ast2ir_drop(spl_ast2ir_t *ast2ir);
|
||||
|
||||
void spl_ast2ir_run(spl_ast2ir_t *ast2ir);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
#ifndef __SPL_DBG_H__
|
||||
#define __SPL_DBG_H__
|
||||
|
||||
#include "spl_tok.h"
|
||||
|
||||
typedef struct {
|
||||
const char *fname;
|
||||
int line;
|
||||
@@ -12,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__ */
|
||||
|
||||
948
stage1/spl_ir.c
948
stage1/spl_ir.c
File diff suppressed because it is too large
Load Diff
159
stage1/spl_ir.h
159
stage1/spl_ir.h
@@ -5,7 +5,6 @@
|
||||
#include "spl_dbg.h"
|
||||
#include "spl_type.h"
|
||||
|
||||
|
||||
/* clang-format off */
|
||||
#define SPL_IR_FN_TABLE \
|
||||
X(arith.add, V0, SPL_IR_ARITH_ADD) \
|
||||
@@ -46,7 +45,6 @@
|
||||
X(mem.field, V0, SPL_IR_MEM_FIELD_PTR) \
|
||||
X(mem.copy, V0, SPL_IR_MEM_COPY) \
|
||||
X(mem.set, V0, SPL_IR_MEM_SET) \
|
||||
X(mem.fence, V0, SPL_IR_MEM_FENCE) \
|
||||
X(type.const, V0, SPL_IR_TYPE_CONST) \
|
||||
X(type.bitsizeof, V0, SPL_IR_TYPE_BITSIZEOF) \
|
||||
X(type.sizeof, V0, SPL_IR_TYPE_SIZEOF) \
|
||||
@@ -56,15 +54,6 @@
|
||||
X(agg.construct, V0, SPL_IR_AGG_CONSTRUCT) \
|
||||
X(agg.extract, V0, SPL_IR_AGG_EXTRACT) \
|
||||
X(agg.insert, V0, SPL_IR_AGG_INSERT) \
|
||||
X(atomic.load, V0, SPL_IR_ATOMIC_LOAD) \
|
||||
X(atomic.store, V0, SPL_IR_ATOMIC_STORE) \
|
||||
X(atomic.rmw_add, V0, SPL_IR_ATOMIC_RMW_ADD) \
|
||||
X(atomic.rmw_sub, V0, SPL_IR_ATOMIC_RMW_SUB) \
|
||||
X(atomic.rmw_and, V0, SPL_IR_ATOMIC_RMW_AND) \
|
||||
X(atomic.rmw_or, V0, SPL_IR_ATOMIC_RMW_OR) \
|
||||
X(atomic.rmw_xor, V0, SPL_IR_ATOMIC_RMW_XOR) \
|
||||
X(atomic.rmw_xchg, V0, SPL_IR_ATOMIC_RMW_XCHG) \
|
||||
X(atomic.cmpxchg, V0, SPL_IR_ATOMIC_CMPXCHG) \
|
||||
X(control.select, V0, SPL_IR_CONTROL_SELECT) \
|
||||
X(control.br, V0, SPL_IR_CONTROL_BR) \
|
||||
X(control.jmp, V0, SPL_IR_CONTROL_JMP) \
|
||||
@@ -74,7 +63,6 @@
|
||||
X(control.unreachable, V0, SPL_IR_CONTROL_UNREACHABLE) \
|
||||
X(control.trap, V0, SPL_IR_CONTROL_TRAP) \
|
||||
X(dbg.breakpoint, V0, SPL_IR_DBG_BREAKPOINT) \
|
||||
X(dbg.declare, V0, SPL_IR_DBG_DECLARE)
|
||||
|
||||
typedef enum {
|
||||
#ifdef X
|
||||
@@ -95,6 +83,7 @@ typedef struct {
|
||||
spl_ir_kind_t kind;
|
||||
spl_dbg_node_t dbg;
|
||||
union {
|
||||
spl_type_id_t tid;
|
||||
struct {
|
||||
spl_type_id_t tid;
|
||||
spl_ir_node_ref_t left;
|
||||
@@ -149,9 +138,6 @@ typedef struct {
|
||||
spl_ir_node_ref_t val;
|
||||
spl_ir_node_ref_t size;
|
||||
} mem_set;
|
||||
struct {
|
||||
spl_ir_node_ref_t ordering;
|
||||
} mem_fence;
|
||||
struct {
|
||||
spl_type_id_t tid;
|
||||
union {
|
||||
@@ -236,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;
|
||||
|
||||
@@ -267,4 +253,145 @@ spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
|
||||
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty);
|
||||
const char *spl_ir_kind_name(spl_ir_kind_t kind);
|
||||
|
||||
typedef struct {
|
||||
spl_ir_t ir;
|
||||
spl_ir_func_ref_t current_fn;
|
||||
spl_ir_node_ref_t current_node;
|
||||
spl_ir_node_ref_vec_t reloc_label;
|
||||
spl_dbg_node_t dbg;
|
||||
} spl_ir_builder_t;
|
||||
|
||||
/* clang-format off */
|
||||
#define SPL_IR_BIN_ARITH_TABLE \
|
||||
X(arith_add, SPL_IR_ARITH_ADD) \
|
||||
X(arith_sub, SPL_IR_ARITH_SUB) \
|
||||
X(arith_mul, SPL_IR_ARITH_MUL) \
|
||||
X(arith_div, SPL_IR_ARITH_DIV) \
|
||||
X(arith_rem, SPL_IR_ARITH_REM) \
|
||||
X(arith_and, SPL_IR_ARITH_AND) \
|
||||
X(arith_or, SPL_IR_ARITH_OR) \
|
||||
X(arith_xor, SPL_IR_ARITH_XOR) \
|
||||
X(arith_shl, SPL_IR_ARITH_SHL) \
|
||||
X(arith_shr, SPL_IR_ARITH_SHR)
|
||||
#define SPL_IR_UN_ARITH_TABLE \
|
||||
X(arith_neg, SPL_IR_ARITH_NEG) \
|
||||
X(arith_abs, SPL_IR_ARITH_ABS) \
|
||||
X(arith_not, SPL_IR_ARITH_NOT)
|
||||
#define SPL_IR_CMP_TABLE \
|
||||
X(cmp_eq, SPL_IR_CMP_EQ) \
|
||||
X(cmp_ne, SPL_IR_CMP_NE) \
|
||||
X(cmp_lt, SPL_IR_CMP_LT) \
|
||||
X(cmp_le, SPL_IR_CMP_LE) \
|
||||
X(cmp_gt, SPL_IR_CMP_GT) \
|
||||
X(cmp_ge, SPL_IR_CMP_GE)
|
||||
#define SPL_IR_CAST_TABLE \
|
||||
X(cast_trunc, SPL_IR_CAST_TRUNC) \
|
||||
X(cast_zext, SPL_IR_CAST_ZEXT) \
|
||||
X(cast_sext, SPL_IR_CAST_SEXT) \
|
||||
X(cast_fext, SPL_IR_CAST_FEXT) \
|
||||
X(cast_ftrunc, SPL_IR_CAST_FTRUNC) \
|
||||
X(cast_bitcast, SPL_IR_CAST_BITCAST) \
|
||||
X(cast_ptr2int, SPL_IR_CAST_PTR2INT) \
|
||||
X(cast_int2ptr, SPL_IR_CAST_INT2PTR) \
|
||||
X(cast_bool2int, SPL_IR_CAST_BOOL2INT) \
|
||||
X(case_int2float, SPL_IR_CASE_INT2FLOAT) \
|
||||
X(case_float2int, SPL_IR_CASE_FLOAT2INT)
|
||||
/* clang-format on */
|
||||
void spl_ir_builder_init(spl_ir_builder_t *b);
|
||||
void spl_ir_builder_drop(spl_ir_builder_t *b);
|
||||
|
||||
spl_ir_func_ref_t spl_ir_builder_fn_new(spl_ir_builder_t *b, const char *name,
|
||||
spl_type_id_t fn_tid);
|
||||
spl_ir_func_ref_t spl_ir_builder_cur_fn(const spl_ir_builder_t *b);
|
||||
void spl_ir_builder_set_dbg(spl_ir_builder_t *b, spl_dbg_node_t dbg);
|
||||
|
||||
spl_ir_node_ref_t spl_ir_builder_block_new(spl_ir_builder_t *b);
|
||||
|
||||
#define X(name, kind) \
|
||||
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
|
||||
spl_ir_node_ref_t left, spl_ir_node_ref_t right);
|
||||
SPL_IR_BIN_ARITH_TABLE
|
||||
#undef X
|
||||
|
||||
#define X(name, kind) \
|
||||
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
|
||||
spl_ir_node_ref_t val);
|
||||
SPL_IR_UN_ARITH_TABLE
|
||||
#undef X
|
||||
|
||||
#define X(name, kind) \
|
||||
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t tid, \
|
||||
spl_ir_node_ref_t a, spl_ir_node_ref_t b);
|
||||
SPL_IR_CMP_TABLE
|
||||
#undef X
|
||||
|
||||
#define X(name, kind) \
|
||||
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t from_tid, \
|
||||
spl_type_id_t to_tid, spl_ir_node_ref_t val);
|
||||
SPL_IR_CAST_TABLE
|
||||
#undef X
|
||||
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t count);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t const_node);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t ptr);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t agg, usize field_idx);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
|
||||
spl_ir_node_ref_t size);
|
||||
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
|
||||
spl_ir_node_ref_t size);
|
||||
|
||||
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
double val);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_const_cstr(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
const char *val);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_func_ref_t val);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t field_idx);
|
||||
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid);
|
||||
|
||||
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid);
|
||||
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
|
||||
spl_ir_node_ref_t field);
|
||||
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_type_id_t field_tid, usize field_idx,
|
||||
spl_ir_node_ref_t val);
|
||||
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
|
||||
spl_ir_node_ref_t agg, spl_ir_node_ref_t field);
|
||||
|
||||
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
|
||||
spl_ir_node_ref_t false_val);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond,
|
||||
spl_ir_node_ref_t true_label,
|
||||
spl_ir_node_ref_t false_label);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_jmp(spl_ir_builder_t *b, spl_ir_node_ref_t label);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t func);
|
||||
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t node,
|
||||
spl_ir_node_ref_t arg);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t idx);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
|
||||
spl_ir_node_ref_t val);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_unreachable(spl_ir_builder_t *b);
|
||||
spl_ir_node_ref_t spl_ir_builder_control_trap(spl_ir_builder_t *b);
|
||||
|
||||
spl_ir_node_ref_t spl_ir_builder_dbg_breakpoint(spl_ir_builder_t *b);
|
||||
|
||||
#endif /* __SPL_IR_H__ */
|
||||
|
||||
2996
stage1/spl_sema.c
2996
stage1/spl_sema.c
File diff suppressed because it is too large
Load Diff
@@ -4,32 +4,53 @@
|
||||
#include "spl_ast.h"
|
||||
#include "spl_type.h"
|
||||
|
||||
typedef enum {
|
||||
SPL_SYMBOL_KIND_ERROR,
|
||||
SPL_SYMBOL_KIND_VAR,
|
||||
SPL_SYMBOL_KIND_MEMBER,
|
||||
SPL_SYMBOL_KIND_FN,
|
||||
SPL_SYMBOL_KIND_TYPE,
|
||||
} spl_symbol_kind_t;
|
||||
typedef struct {
|
||||
const char *name;
|
||||
spl_symbol_kind_t kind;
|
||||
spl_def_id_t node;
|
||||
} spl_symbol_t;
|
||||
|
||||
typedef usize spl_scope_id_t; /* 0 is error */
|
||||
typedef struct {
|
||||
spl_scope_id_t parent;
|
||||
MAP(const char *, spl_def_id_t) symbols;
|
||||
MAP(const char *, spl_symbol_t) symbols;
|
||||
} spl_scope_node_t;
|
||||
typedef VEC(spl_scope_node_t) spl_scope_node_vec_t;
|
||||
|
||||
typedef struct {
|
||||
spl_ast_t *ast;
|
||||
spl_type_t type;
|
||||
spl_scope_node_vec_t scopes;
|
||||
spl_scope_id_t root_scope;
|
||||
spl_scope_id_t current_scope;
|
||||
spl_def_id_t root_def;
|
||||
} spl_scope_t;
|
||||
|
||||
void spl_scope_init(spl_scope_t *scope);
|
||||
void spl_scope_drop(spl_scope_t *scope);
|
||||
|
||||
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope);
|
||||
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol);
|
||||
typedef VEC(const char *) spl_symbol_path_t;
|
||||
bool spl_scope_find(spl_scope_t *scop, const char *symbol_name, spl_symbol_t *out);
|
||||
|
||||
typedef struct {
|
||||
spl_ast_t *ast;
|
||||
spl_type_t *type;
|
||||
spl_scope_t *scope;
|
||||
spl_symbol_t root;
|
||||
int error_count;
|
||||
spl_scope_id_t store_scope;
|
||||
spl_type_id_t current_fn_ret_tid; // TODO
|
||||
} spl_sema_t;
|
||||
|
||||
void spl_sema_init(spl_sema_t *sema);
|
||||
void spl_sema_init(spl_sema_t *sema, spl_ast_t *ast, spl_type_t *type, spl_scope_t *scope);
|
||||
void spl_sema_drop(spl_sema_t *sema);
|
||||
void spl_sema_run(spl_sema_t *sema);
|
||||
void spl_sema_check(spl_sema_t *sema);
|
||||
|
||||
spl_scope_id_t spl_sema_scope_alloc(spl_sema_t *sema);
|
||||
bool spl_sema_scope_insert(spl_sema_t *sema, spl_scope_id_t id, const char *symbol_name,
|
||||
spl_def_id_t symbol_val);
|
||||
typedef VEC(const char *) spl_symbol_path_t;
|
||||
spl_def_id_t spl_sema_scope_find(spl_sema_t *sema, spl_symbol_path_t path);
|
||||
void spl_sema_run(spl_sema_t *sema);
|
||||
void spl_sema_dump(spl_sema_t *sema);
|
||||
|
||||
#endif /* __SPL_SEMA_H__ */
|
||||
|
||||
@@ -1,75 +1,356 @@
|
||||
#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;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
return hash;
|
||||
}
|
||||
|
||||
spl_type_id_t spl_type_def_alloc(spl_type_t *type) {
|
||||
vec_push(type->def_table, (spl_def_node_t){0});
|
||||
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
|
||||
if (n1.kind != n2.kind)
|
||||
return 1;
|
||||
switch (n1.kind) {
|
||||
case SPL_TYPE_ERROR:
|
||||
case SPL_TYPE_VOID:
|
||||
case SPL_TYPE_BOOL:
|
||||
case SPL_TYPE_UNDEFINED:
|
||||
case SPL_TYPE_NULL:
|
||||
break;
|
||||
case SPL_TYPE_INT:
|
||||
if (n1.int_type.bits != n2.int_type.bits)
|
||||
return 1;
|
||||
if (n1.int_type.is_signed != n2.int_type.is_signed)
|
||||
return 1;
|
||||
break;
|
||||
case SPL_TYPE_FLOAT:
|
||||
if (n1.float_type.bits != n2.float_type.bits)
|
||||
return 1;
|
||||
break;
|
||||
case SPL_TYPE_PTR:
|
||||
if (n1.ptr_pointee != n2.ptr_pointee)
|
||||
return 1;
|
||||
break;
|
||||
case SPL_TYPE_SLICE:
|
||||
if (n1.slice_element != n2.slice_element)
|
||||
return 1;
|
||||
break;
|
||||
case SPL_TYPE_RANGE:
|
||||
if (n1.range_element != n2.range_element)
|
||||
return 1;
|
||||
break;
|
||||
case SPL_TYPE_ARRAY:
|
||||
if (n1.array_type.element != n2.array_type.element)
|
||||
return 1;
|
||||
if (n1.array_type.len != n2.array_type.len)
|
||||
return 1;
|
||||
break;
|
||||
case SPL_TYPE_STRUCT:
|
||||
case SPL_TYPE_UNION:
|
||||
if (n1.layout.mode != n2.layout.mode ||
|
||||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
|
||||
return 1;
|
||||
if (vec_size(n1.agg_members) != vec_size(n2.agg_members))
|
||||
return 1;
|
||||
vec_for(n1.agg_members, i) {
|
||||
const char *na = n1.agg_members.data[i].name;
|
||||
const char *nb = n2.agg_members.data[i].name;
|
||||
if (strcmp(na ? na : "", nb ? nb : "") != 0)
|
||||
return 1;
|
||||
if (n1.agg_members.data[i].type_id != n2.agg_members.data[i].type_id)
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
case SPL_TYPE_ENUM:
|
||||
if (n1.layout.mode != n2.layout.mode ||
|
||||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
|
||||
return 1;
|
||||
if (n1.adt_type.tag_type != n2.adt_type.tag_type)
|
||||
return 1;
|
||||
if (vec_size(n1.adt_type.variants) != vec_size(n2.adt_type.variants))
|
||||
return 1;
|
||||
vec_for(n1.adt_type.variants, i) {
|
||||
const char *na = n1.adt_type.variants.data[i].name;
|
||||
const char *nb = n2.adt_type.variants.data[i].name;
|
||||
if (strcmp(na ? na : "", nb ? nb : "") != 0)
|
||||
return 1;
|
||||
if (n1.adt_type.variants.data[i].type_id != n2.adt_type.variants.data[i].type_id)
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
case SPL_TYPE_FN:
|
||||
if (n1.fn_type.ret != n2.fn_type.ret)
|
||||
return 1;
|
||||
if (vec_size(n1.fn_type.params) != vec_size(n2.fn_type.params))
|
||||
return 1;
|
||||
vec_for(n1.fn_type.params, i) {
|
||||
if (vec_at(n1.fn_type.params, i) != vec_at(n2.fn_type.params, i))
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
default: // TODO
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static usize spl_type_map_hash(usize k) { return MAP_HASH_INT(k); }
|
||||
|
||||
static int spl_type_map_cmp(usize a, usize b) { return MAP_CMP_INT(a, b); }
|
||||
|
||||
static void spl_type_node_free_vecs(spl_type_node_t *tn) {
|
||||
switch (tn->kind) {
|
||||
case SPL_TYPE_STRUCT:
|
||||
case SPL_TYPE_UNION:
|
||||
vec_free(tn->agg_members);
|
||||
break;
|
||||
case SPL_TYPE_ENUM:
|
||||
vec_free(tn->adt_type.variants);
|
||||
break;
|
||||
case SPL_TYPE_FN:
|
||||
vec_free(tn->fn_type.params);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *tn) {
|
||||
usize hash = spl_type_hash(*tn);
|
||||
usize idx = (usize)-1;
|
||||
spl_type_id_t cand = 0;
|
||||
while (map_get_continue(type->type_map, hash, &cand, &idx)) {
|
||||
spl_type_node_t *existing = &vec_at(type->type_table, cand);
|
||||
if (spl_type_eq(*existing, *tn) == 0) {
|
||||
spl_type_node_free_vecs(tn);
|
||||
return cand;
|
||||
}
|
||||
}
|
||||
spl_type_id_t id = vec_size(type->type_table);
|
||||
vec_push(type->type_table, *tn);
|
||||
map_put_new(type->type_map, hash, id);
|
||||
tn->kind = SPL_TYPE_ERROR;
|
||||
return id;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -78,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);
|
||||
@@ -91,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);
|
||||
@@ -125,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) {
|
||||
@@ -138,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:
|
||||
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
|
||||
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:
|
||||
printf("f%zu", n->float_type.bits);
|
||||
if (n->float_type.bits == 0) {
|
||||
printf("comptime_float");
|
||||
} else {
|
||||
printf("f%zu", n->float_type.bits);
|
||||
}
|
||||
break;
|
||||
case SPL_TYPE_PTR:
|
||||
printf("*");
|
||||
@@ -162,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);
|
||||
@@ -190,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;
|
||||
}
|
||||
|
||||
@@ -209,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";
|
||||
@@ -221,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 : "?");
|
||||
}
|
||||
|
||||
@@ -2,33 +2,53 @@
|
||||
#define __SPL_TYPE_H__
|
||||
|
||||
#include "../stage0/include/utils.h"
|
||||
#include "spl_dbg.h"
|
||||
|
||||
typedef usize spl_type_id_t; /* 0 is error */
|
||||
typedef VEC(spl_type_id_t) spl_type_id_vec_t;
|
||||
typedef usize spl_def_id_t; /* 0 is error */
|
||||
typedef VEC(spl_def_id_t) spl_def_id_vec_t;
|
||||
|
||||
typedef enum {
|
||||
SPL_TYPE_ERROR,
|
||||
SPL_TYPE_VOID,
|
||||
SPL_TYPE_BOOL,
|
||||
SPL_TYPE_INT,
|
||||
SPL_TYPE_FLOAT,
|
||||
SPL_TYPE_UNDEFINED, // 自动配对任意类型的字面量,值为 undefined
|
||||
SPL_TYPE_NULL, // 自动配对指针/切片的字面量,值为 0
|
||||
SPL_TYPE_PTR,
|
||||
SPL_TYPE_SLICE, // 未来拥有泛型后删除
|
||||
SPL_TYPE_RANGE, // 未来拥有泛型后删除
|
||||
SPL_TYPE_ARRAY,
|
||||
SPL_TYPE_STRUCT,
|
||||
SPL_TYPE_UNION,
|
||||
SPL_TYPE_ENUM,
|
||||
SPL_TYPE_FN,
|
||||
SPL_TYPE_ID,
|
||||
} 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 {
|
||||
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;
|
||||
spl_type_layout_mode_t mode;
|
||||
usize fixed_align_bits;
|
||||
} spl_type_layout_t;
|
||||
|
||||
typedef struct {
|
||||
const char *name;
|
||||
spl_type_id_t type_id;
|
||||
usize ast_node_ref; // 回 AST member_decl 节点引用 dbg/IDE 定位用 不参与 hash
|
||||
} spl_type_member_t;
|
||||
typedef VEC(spl_type_member_t) spl_type_member_vec_t;
|
||||
|
||||
typedef struct {
|
||||
spl_type_node_kind_t kind;
|
||||
spl_type_layout_t layout;
|
||||
union {
|
||||
struct {
|
||||
usize bits;
|
||||
@@ -44,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 {
|
||||
@@ -58,39 +78,29 @@ 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 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
|
||||
} spl_def_node_kind_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_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;
|
||||
@@ -104,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__ */
|
||||
|
||||
254
stage1/splc0.c
254
stage1/splc0.c
@@ -12,14 +12,23 @@
|
||||
|
||||
#include "spl_ast.h"
|
||||
#include "spl_ast2ir.h"
|
||||
#include "spl_ir2vm.h"
|
||||
// #include "spl_ir2vm.h"
|
||||
#include "spl_lexer.h"
|
||||
#include "spl_sema.h"
|
||||
#include "spl_tok.h"
|
||||
|
||||
typedef enum {
|
||||
DUMP_NONE,
|
||||
DUMP_TOKEN,
|
||||
DUMP_AST,
|
||||
DUMP_SEMA,
|
||||
DUMP_IR,
|
||||
} dump_t;
|
||||
|
||||
static char *read_file(const char *path, long *out_len) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "path `%s` ", path);
|
||||
perror("fopen");
|
||||
return NULL;
|
||||
}
|
||||
@@ -47,8 +56,7 @@ static const char *const tok_type_names[] = {
|
||||
#undef X
|
||||
};
|
||||
|
||||
static void dump_tokens(const char *src, const char *fname) {
|
||||
spl_tok_vec_t toks = spl_lex(src, fname);
|
||||
static void dump_tokens(spl_tok_vec_t toks) {
|
||||
printf("tokens got (%zu)\n", toks.size);
|
||||
for (usize i = 0; i < toks.size; i++) {
|
||||
const spl_tok_t *t = &toks.data[i];
|
||||
@@ -58,180 +66,66 @@ static void dump_tokens(const char *src, const char *fname) {
|
||||
vec_free(toks);
|
||||
}
|
||||
|
||||
static void dump_ast(const char *src, const char *fname) {
|
||||
static int compile_spl(const char *src, const char *fname, const char *outpath, int gen_debug,
|
||||
dump_t dump) {
|
||||
spl_tok_vec_t toks = spl_lex(src, fname);
|
||||
if (dump == DUMP_TOKEN) {
|
||||
dump_tokens(toks);
|
||||
// memory leak
|
||||
return 0;
|
||||
}
|
||||
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 = *
|
||||
// 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 = *
|
||||
// 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)
|
||||
printf("parse failed, no output\n");
|
||||
// memory leak
|
||||
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;
|
||||
}
|
||||
}
|
||||
// spl_ast_valid(&ast); TODO
|
||||
if (dump == DUMP_AST) {
|
||||
spl_ast_dump(&ast, ast.root);
|
||||
// memory leak
|
||||
return 0;
|
||||
}
|
||||
spl_sema_t sema;
|
||||
spl_type_t type;
|
||||
spl_scope_t scope;
|
||||
spl_type_init(&type);
|
||||
spl_scope_init(&scope);
|
||||
spl_sema_init(&sema, &ast, &type, &scope);
|
||||
sema.ast = *
|
||||
spl_sema_run(&sema);
|
||||
if (sema.error_count) {
|
||||
printf("sema errors=%d, no output\n", sema.error_count);
|
||||
// memory leak
|
||||
return 1;
|
||||
}
|
||||
if (dump == DUMP_SEMA) {
|
||||
spl_sema_dump(&sema);
|
||||
spl_ast_dump(&ast, ast.root);
|
||||
// memory leak
|
||||
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);
|
||||
}
|
||||
spl_ast2ir_t a2ir;
|
||||
spl_ir_builder_t ir_builder;
|
||||
spl_ir_builder_init(&ir_builder);
|
||||
spl_ast2ir_init(&a2ir, &ir_builder, &sema);
|
||||
spl_ast2ir_run(&a2ir);
|
||||
if (a2ir.err_count) {
|
||||
printf("ast2ir errors=%d, no output\n", a2ir.err_count);
|
||||
spl_ast2ir_drop(&a2ir);
|
||||
spl_sema_drop(&sema);
|
||||
spl_ast_drop(&ast);
|
||||
return 1;
|
||||
}
|
||||
if (dump == DUMP_IR) {
|
||||
spl_ir_dump(&ir_builder.ir, &type);
|
||||
// memory leak
|
||||
return 0;
|
||||
}
|
||||
|
||||
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 = *
|
||||
// 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);
|
||||
@@ -252,7 +146,7 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
|
||||
LOG_INFO("splc0 <in> <out> compile (.spl -> .sir, stage B)");
|
||||
LOG_INFO("splc0 --dump <flags> <file> dump: tokens,ast,sema,ir,all");
|
||||
LOG_INFO("splc0 --dump <flags> <file> dump: lex,ast,sema,ir");
|
||||
return 0;
|
||||
}
|
||||
int argi = 1;
|
||||
@@ -260,12 +154,28 @@ int main(int argc, char **argv) {
|
||||
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
|
||||
return 1;
|
||||
}
|
||||
|
||||
dump_t dump = DUMP_NONE;
|
||||
if (strcmp(argv[argi], "--dump") == 0) {
|
||||
if (argc < argi + 3) {
|
||||
LOG_INFO("splc0: --dump need <flags> <file>");
|
||||
return 1;
|
||||
}
|
||||
return cmd_dump(argv[argi + 1], argv[argi + 2]);
|
||||
|
||||
const char *flags = argv[argi + 1];
|
||||
if (strstr(flags, "lex") != NULL) {
|
||||
dump = DUMP_TOKEN;
|
||||
}
|
||||
if (strstr(flags, "ast") != NULL) {
|
||||
dump = DUMP_AST;
|
||||
}
|
||||
if (strstr(flags, "sema") != NULL) {
|
||||
dump = DUMP_SEMA;
|
||||
}
|
||||
if (strstr(flags, "ir") != NULL) {
|
||||
dump = DUMP_IR;
|
||||
}
|
||||
argi += 2;
|
||||
}
|
||||
/* splc0 [-g] <in> <out> */
|
||||
if (argc < argi + 2) {
|
||||
@@ -285,7 +195,7 @@ int main(int argc, char **argv) {
|
||||
char *src = read_file(argv[argi], &len);
|
||||
if (!src)
|
||||
return 1;
|
||||
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug);
|
||||
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug, dump);
|
||||
free(src);
|
||||
return rc;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user