Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit a42bd1c308087a261cc44fe74e32a2518b543d1f
parent c9425892e8c81c55e636179e2af6ad6795c66f14
Author: sentomk <sentomk@proton.me>
Date:   Mon,  5 Oct 2026 01:20:50 +0800

feat: complete the self-hosting build workflow

Rebuild and restart the builder when its source changes.

Scan C++ and Objective-C++ sources, compile stale files in parallel,
and relink when the executable is missing or older than its objects.

Generate compile_commands.json for clangd and support build, run,
and clean modes.

Diffstat:
Mkumo_builder.cpp | 165++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 163 insertions(+), 2 deletions(-)

diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -23,6 +23,7 @@ #include <filesystem> #include <fstream> #include <string> +#include <thread> #include <vector> /// @brief The environment of the current process, provided by libc. @@ -201,16 +202,176 @@ static std::vector<fs::path> read_depfile(const fs::path& path) { /// @param dep Path of the dependency file written alongside it. /// @param self_time Modification time of the builder binary. /// @return `true` if the source must be recompiled. -static bool needs_compile(const fs::path& obj, const fs::path& dep, fs::file_time_type self_time) { +static bool needs_compile(const fs::path& obj, const fs::path& dep, + fs::file_time_type self_time) { if (!fs::exists(obj) || !fs::exists(dep)) return true; fs::file_time_type obj_time = fs::last_write_time(obj); if (self_time > obj_time) return true; - for (const fs::path& d : read_depfile(dep)) { + for (const fs::path& d : read_depfile(dep)) { if (!fs::exists(d) || fs::last_write_time(d) > obj_time) return true; } return false; } /// @} + +/// @name compile_commands.json +/// Tells clangd how each file is compiled. +/// @{ + +/// @brief Escapes a string for use inside a JSON string literal. +/// +/// Only double quotes and backslashes are handled; paths and flags never +/// contain control characters. +/// +/// @param s Raw string. +/// @return The escaped string, without surrounding quotes. +static std::string json_escape(const std::string& s) { + std::string out; + for (char c : s) { + if (c == '"' || c == '\\') out += '\\'; + out += c; + } + return out; +} + +/// @brief Writes `compile_commands.json` to the current directory. +/// +/// One object is written per file: +/// @code{.json} +/// {"directory": "<cwd>", "file": "<source>", "arguments": ["<argv", ...]} +/// @endcode +/// +/// @param sources Every source file. +/// @param cmds Compile commands; `cmds[i]` compiles `sources[i]`. +static void write_compile_commands(const std::vector<fs::path>& sources, + const std::vector<Cmd>& cmds) { + std::ofstream out("compile_commands.json"); + std::string dir = json_escape(fs::current_path().string()); + out << "[\n"; + for (size_t i = 0; i < sources.size(); ++i) { + out << " {\"directory\": \"" << dir << "\", \"file\": \"" + << json_escape(sources[i].string()) << "\", \"arguments\": ["; + for (size_t j = 0; j < cmds[i].size(); j++) { + out << (j ? ", " : "") << '"' << json_escape(cmds[i][j]) << '"'; + } + // JSON forbids a trailing comma, so the last entry gets none. + out << "]}" << (i + 1 < sources.size() ? "," : "") << "\n"; + } + out << "]\n"; +} + +/// @} + +/// @} + +/// @name Entry point +/// @{ + +/// @brief Recompiles and restarts the builder if its source has changed. +/// +/// If #SELF_SRC is newer than the running binary, it is recompiled and `execv` +/// replaces the current process with the new binary, which starts again from +/// main(). The new binary is always newer than the source, so this cannot +/// loop forever. +/// +/// @param argv The argument vector of main(); `argv[0]` is the binary to +/// replace, and the whole vector is forwarded to the new process. +static void rebuild_self(char** argv) { + if (fs::last_write_time(SELF_SRC) <= fs::last_write_time(argv[0])) return; + + std::printf("[self] %s changed, rebuilding\n", SELF_SRC.c_str()); + if (!run({CXX, "-std=c++20", SELF_SRC.string(), "-o", argv[0]})) std::exit(1); + + execv(argv[0], argv); + // execv does not return on success; reaching this line means it failed. + std::perror("execv"); + std::exit(1); +} + +/// @brief Builds the project. +/// +/// @param argc Argument count. +/// @param argv `argv[1]` selects the mode: `build` (default), `run` or `clean`. +/// @return 0 on success, 1 if compiling, linking or running failed. +int main(int argc, char** argv) { + // stdout is fully buffered when it is not a terminal, which would make our + // log lines appear after the output of the child processes. Line buffering + // keeps them in order. + std::setvbuf(stdout, nullptr, _IOLBF, 0); + + rebuild_self(argv); + + std::string mode = argc > 1 ? argv[1] : "build"; + if (mode == "clean") { + fs::remove_all(OUT_DIR); + return 0; + } + + fs::file_time_type self_time = fs::last_write_time(argv[0]); + + // Step 1: scan the sources, build a compile command for each one, and pick + // out the stale ones. + std::vector<fs::path> sources; // every source file + std::vector<fs::path> objects; // object file of sources[i], for linking + std::vector<Cmd> + all_cmds; // compile command of sources[i], for compile_commands.json + std::vector<Cmd> stale_cmds; // the subset that actually has to run now + for (const fs::directory_entry& entry : + fs::recursive_directory_iterator(SRC_DIR)) { + fs::path src = entry.path(); + if (src.extension() != ".cpp" && src.extension() != ".mm") continue; + + // src/foo/bar.cpp -> build/obj/src/foo/bar.cpp.o + // The full file name is kept and a suffix appended, so bar.cpp and + // bar.mm do not collide. + fs::path obj = OUT_DIR / "obj" / (src.string() + ".o"); + fs::path dep = OUT_DIR / "obj" / (src.string() + ".d"); + fs::create_directories(obj.parent_path()); + + // -MD -MF <dep>: write the dependency list to dep while compiling. + Cmd cmd = {CXX}; + cmd.insert(cmd.end(), CXX_FLAGS.begin(), CXX_FLAGS.end()); + cmd.insert(cmd.end(), {"-MD", "-MF", dep.string(), "-c", src.string(), "-o", + obj.string()}); + + if (needs_compile(obj, dep, self_time)) { + std::printf("[cc] %s\n", src.c_str()); + stale_cmds.push_back(cmd); + } + sources.push_back(src); + objects.push_back(obj); + all_cmds.push_back(cmd); + } + write_compile_commands(sources, all_cmds); + + // Step 2: compile the stale files in parallel. hardware_concurrency may + // return 0, meaning "unknown". + unsigned jobs = std::thread::hardware_concurrency(); + if (!run_all(stale_cmds, jobs ? jobs : 4)) return 1; + + // Step 3: relink if the executable is missing or any object is newer. + // "Did we compile anything this time?" is not a valid test: if the last + // run compiled successfully but failed to link, nothing is stale now and + // yet the link is still needed. + bool link_needed = !fs::exists(EXE); + for (const fs::path& obj : objects) { + if (!link_needed && fs::last_write_time(obj) > fs::last_write_time(EXE)) + link_needed = true; + } + if (link_needed) { + std::printf("[link] %s\n", EXE.c_str()); + Cmd link = {CXX}; + for (const fs::path& obj : objects) link.push_back(obj.string()); + link.insert(link.end(), LINK_FLAGS.begin(), LINK_FLAGS.end()); + link.insert(link.end(), {"-o", EXE.string()}); + if (!run(link)) return 1; + } + + if (mode == "run") return run({EXE.string()}) ? 0 : 1; + return 0; +} + +/// @}