builder 更改构建方式从python换成nob.h
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,5 +8,6 @@ build/
|
|||||||
*.o
|
*.o
|
||||||
*.obj
|
*.obj
|
||||||
|
|
||||||
|
*.old
|
||||||
*.exe
|
*.exe
|
||||||
*.out
|
*.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,52 +0,0 @@
|
|||||||
vm = [
|
|
||||||
"stage0/spl_mcode.c",
|
|
||||||
"stage0/spl_syscall.c",
|
|
||||||
"stage0/spl_vm.c",
|
|
||||||
]
|
|
||||||
|
|
||||||
splc0_part = [
|
|
||||||
"stage1/spl_ast.c",
|
|
||||||
"stage1/spl_lexer.c",
|
|
||||||
"stage1/spl_dumptree.c",
|
|
||||||
"stage1/spl_type.c",
|
|
||||||
"stage1/spl_sema.c",
|
|
||||||
"stage1/spl_ir.c",
|
|
||||||
"stage1/spl_ast2ir.c",
|
|
||||||
# "stage1/spl_ir2vm.c",
|
|
||||||
]
|
|
||||||
|
|
||||||
exe = {
|
|
||||||
"spl_cli": ["stage0/spl_cli.c"] + vm,
|
|
||||||
"splc0": ["stage1/splc0.c"] + vm + splc0_part,
|
|
||||||
"test": ["stage0/test_spl_vm.c"] + vm,
|
|
||||||
"spl_disasm": ["stage0/spl_disasm.c"] + vm,
|
|
||||||
}
|
|
||||||
|
|
||||||
pipeline = {
|
|
||||||
"splc0b": {"compiler": "splc0", "runner": "spl_cli"},
|
|
||||||
"splc0r": {"compiler": "splc0", "runner": "spl_cli"},
|
|
||||||
"splc0d": {"compiler": "splc0", "runner": "spl_disasm"},
|
|
||||||
|
|
||||||
"splc1b": {"compiler": "splc0", "runner": "spl_cli"},
|
|
||||||
"splc1r": {"compiler": "splc1", "runner": "spl_cli"},
|
|
||||||
"splc1d": {"compiler": "splc1", "runner": "spl_disasm"},
|
|
||||||
|
|
||||||
"splc2b": {"compiler": "splc1", "runner": "spl_cli"},
|
|
||||||
"splc2r": {"compiler": "splc2", "runner": "spl_cli"},
|
|
||||||
"splc2d": {"compiler": "splc2", "runner": "spl_disasm"},
|
|
||||||
|
|
||||||
"splc3b": {"compiler": "splc2", "runner": "spl_cli"},
|
|
||||||
"splc3r": {"compiler": "splc3", "runner": "spl_cli"},
|
|
||||||
"splc3d": {"compiler": "splc3", "runner": "spl_disasm"},
|
|
||||||
|
|
||||||
"splc4b": {"compiler": "splc3", "runner": "spl_cli"},
|
|
||||||
"splc4r": {"compiler": "splc4", "runner": "spl_cli"},
|
|
||||||
"splc4d": {"compiler": "splc4", "runner": "spl_disasm"},
|
|
||||||
}
|
|
||||||
|
|
||||||
spl = {
|
|
||||||
"splc1": {"src": "stage2/splc1.spl", "pipeline": "splc0r"},
|
|
||||||
"splc2": {"src": "stage2/splc2.spl", "pipeline": "splc1r"},
|
|
||||||
"splc3": {"src": "stage3/splc3.spl", "pipeline": "splc2r"},
|
|
||||||
"splc4": {"src": "stage4/splc4.spl", "pipeline": "splc3r"},
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user