Kumo
A hand-rolled game engine.
git clone https://git.sentomk.me/Kumo.git
commit 54c367d7560996d4eeb52caaa73261078e064966 parent 448303d61eab4672324241e70fff4aedb104b76b Author: sentomk <sentomk@proton.me> Date: Wed, 7 Oct 2026 00:47:47 +0800 feat: read project settings from kumo.toml Move the source and output directories, executable name, compiler and compile/link flags out of kumo_builder.cpp into a kumo.toml in the project root. Per-platform additions go in [mac], [linux] and [windows] tables. The builder parses a small TOML subset itself, so it still has no dependencies. Syntax errors, wrong value types and unknown keys are reported with their line number, and a missing source directory is now a clear error instead of an uncaught exception. Editing kumo.toml makes the next build recompile everything, because the compile flags now come from it as well as from the builder. Diffstat:
| A | kumo.toml | | | 35 | +++++++++++++++++++++++++++++++++++ |
| M | kumo_builder.cpp | | | 418 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------- |
2 files changed, 401 insertions(+), 52 deletions(-)
diff --git a/kumo.toml b/kumo.toml @@ -0,0 +1,35 @@ +# Project configuration, read by the builder (kumoko). +# +# Paths are relative to the project root. Only the keys below exist; the +# builder rejects anything else, so that a typo is not silently ignored. + +name = "kumo" # executable name; ".exe" is added on Windows +compiler = "clang++" +src = "src" # source tree, searched recursively for .cpp and .mm +out = "build" # all build output; `kumoko clean` deletes it + +# Flags for every compile command. +flags = [ + "-std=c++20", "-g", "-O0", "-Wall", "-Wextra", + "-fno-exceptions", "-fno-rtti", + "-Isrc", # allows includes relative to src/, e.g. #include "core/math.h" +] + +# Extra flags for Objective-C++ (.mm) files only. ARC makes the compiler insert +# retain/release calls for Objective-C objects. +objcxx_flags = ["-fobjc-arc"] + +# Flags for the link command. +link = [] + +# Per-platform additions: `flags` and `link` here are appended to the lists +# above, on that platform only. Linux will need "-lX11" and Windows +# "-luser32", "-lgdi32" once the window code for those platforms exists. + +[mac] +link = ["-framework", "Cocoa", "-framework", "Metal", "-framework", "QuartzCore"] + +[windows] +# The MSVC standard library must be told explicitly that exceptions are off, +# otherwise its headers still contain `try` blocks. +flags = ["-D_HAS_EXCEPTIONS=0"] diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -5,6 +5,10 @@ /// The builder is built on the machine that uses it, so the host is also the /// target; cross-compilation is not supported. /// +/// How the project is organized and compiled is described by `kumo.toml` in the +/// project root, see "Project configuration" below; this file only holds the +/// logic. +/// /// Bootstrap (once, from the project root): /// @code /// clang++ -std=c++20 kumo_builder.cpp -o kumoko # macOS, Linux @@ -23,6 +27,8 @@ /// /// @note There is no need to bootstrap again after editing this file: on the /// next run the builder notices it is out of date and recompiles itself. +/// Editing `kumo.toml` needs no bootstrap either; it recompiles the +/// project. /// @warning The Windows code paths have not been run on a real Windows /// machine yet. @@ -37,11 +43,14 @@ #endif #include <algorithm> +#include <cctype> #include <cerrno> +#include <cstddef> #include <cstdio> #include <cstdlib> #include <filesystem> #include <fstream> +#include <map> #include <sstream> #include <string> #include <system_error> @@ -63,8 +72,9 @@ namespace fs = std::filesystem; /// containing spaces or quotes need no escaping. using Cmd = std::vector<std::string>; -/// @name Configuration -/// Every build setting of the project lives here. +/// @name Builder constants +/// What belongs to the builder itself. The settings of the project it builds +/// live in `kumo.toml`, see "Project configuration". /// @{ /// @brief Operating systems the builder knows about. @@ -81,11 +91,20 @@ static constexpr Platform HOST = Platform::Windows; #error "kumo_builder supports only macOS, Linux and Windows" #endif +/// @brief The name of #HOST in `kumo.toml`, as a table header. +static constexpr const char* HOST_NAME = HOST == Platform::Mac ? "mac" + : HOST == Platform::Linux ? "linux" + : "windows"; + /// @brief File name extension of executables on this platform. static constexpr const char* EXE_SUFFIX = HOST == Platform::Windows ? ".exe" : ""; -static const char* const CXX = "clang++"; +/// @brief The compiler that rebuilds the builder itself. +/// +/// Fixed, because it is needed before `kumo.toml` is read. The compiler of the +/// project is the `compiler` key of that file. +static const char* const SELF_CXX = "clang++"; static const fs::path SELF_SRC = "kumo_builder.cpp"; /// @brief Path of the builder's own executable. @@ -99,46 +118,332 @@ static const fs::path SELF_EXE = std::string("kumoko") + EXE_SUFFIX; /// Windows refuses to overwrite a running executable but allows renaming it. static const fs::path SELF_OLD_EXE = std::string("kumoko.old") + EXE_SUFFIX; -static const fs::path SRC_DIR = "src"; +/// @brief The project configuration file, in the project root. +static const fs::path CONFIG_FILE = "kumo.toml"; + +/// @} + +/// @name Project configuration +/// Reading `kumo.toml`, which says how the project is organized and compiled. +/// +/// The file is a small subset of TOML (https://toml.io). The builder has no +/// dependencies, so it parses the file itself, and accepts only this: +/// - `#` starts a comment that runs to the end of the line; +/// - `key = "text"` assigns a string; inside double quotes only `\\` and `\"` +/// are escapes, and single quotes (`'C:\dir'`) take everything literally; +/// - `key = ["a", "b"]` assigns a list of strings; it may span several lines, +/// end with a comma and contain comments; +/// - `[mac]`, `[linux]` and `[windows]` start a table whose keys apply to that +/// platform only. +/// +/// Anything else (numbers, booleans, dates, inline tables, dotted keys, +/// multi-line strings) is a syntax error. So is a key the builder does not +/// know, so that a typo is never silently ignored. +/// +/// All keys are optional: +/// - `name`: name of the executable, without the `.exe` that Windows adds +/// (default: the name of the project directory); +/// - `compiler`: the C++ compiler (default: `clang++`); +/// - `src`: the source tree, searched recursively (default: `src`); +/// - `out`: where all build output goes (default: `build`); +/// - `flags`: compile flags for every source file; +/// - `objcxx_flags`: extra compile flags for `.mm` files only; +/// - `link`: link flags. +/// +/// A platform table may hold `flags` and `link`. On that platform they are +/// appended to the lists above. +/// @{ -/// @brief Output root. +/// @brief The settings of the project, as read from #CONFIG_FILE. /// -/// Layout: +/// Output layout, for `src = "src"`, `out = "build"` and `name = "kumo"`: /// @code /// build/obj/src/foo/bar.cpp.o object file (mirrors the source tree) /// build/obj/src/foo/bar.cpp.d list of headers that file depends on /// build/kumo final executable (kumo.exe on Windows) /// @endcode -static const fs::path OUT_DIR = "build"; -static const fs::path EXE = OUT_DIR / (std::string("kumo") + EXE_SUFFIX); - -/// @brief Flags passed to every compile command. -static const Cmd CXX_FLAGS = { - "-std=c++20", "-g", "-O0", "-Wall", "-Wextra", - "-fno-exceptions", "-fno-rtti", - "-Isrc", // allows includes relative to src/, e.g. #include "core/math.h" +struct Config { + std::string compiler; + fs::path src_dir; + fs::path out_dir; + fs::path exe; ///< The final executable, inside #out_dir. + Cmd flags; ///< Compile flags, with those of this platform added. + Cmd objcxx_flags; ///< Extra compile flags for `.mm` files. + Cmd link_flags; ///< Link flags, with those of this platform added. }; -/// @brief Extra compile flags that only some platforms need. +/// @brief Reports a problem with #CONFIG_FILE and exits. /// -/// On Windows the MSVC standard library must be told explicitly that -/// exceptions are off, otherwise its headers still contain `try` blocks. -static const Cmd PLATFORM_CXX_FLAGS = - HOST == Platform::Windows ? Cmd{"-D_HAS_EXCEPTIONS=0"} : Cmd{}; +/// @param line 1-based line the problem is on, or 0 if it is not about a line. +/// @param msg What is wrong. +[[noreturn]] static void config_error(int line, const std::string& msg) { + const std::string file = CONFIG_FILE.string(); + if (line > 0) { + std::fprintf(stderr, "%s:%d: %s\n", file.c_str(), line, msg.c_str()); + } else { + std::fprintf(stderr, "%s: %s\n", file.c_str(), msg.c_str()); + } + std::exit(EXIT_FAILURE); +} + +/// @brief One `key = value` pair of the file. +struct Entry { + bool is_list = false; ///< Which of #text and #list holds the value. + std::string text; + Cmd list; + int line = 0; ///< Where the pair was written, for error messages. +}; + +/// @brief Every pair of the file; a key inside a table is stored as +/// `"table.key"`. +using Table = std::map<std::string, Entry>; -/// @brief Extra flags for Objective-C++ (`.mm`) files only. +/// @brief Parser for the TOML subset described above. /// -/// ARC makes the compiler insert retain/release calls for Objective-C objects. -static const Cmd OBJCXX_FLAGS = {"-fobjc-arc"}; +/// Reports a syntax error with config_error(), which exits. +class ConfigParser { + public: + explicit ConfigParser(const std::string& text) : text_(text) { + // Some Windows editors start a UTF-8 file with a byte order mark. + if (text_.starts_with("\xEF\xBB\xBF")) text_.erase(0, 3); + } + + /// @brief Parses the whole text. + Table parse() { + Table table; + std::string section; // the table being filled; empty at the top level + for (skip_blank(true); pos_ < text_.size(); skip_blank(true)) { + if (text_[pos_] == '[') { + section = parse_header(); + } else { + parse_pair(section, table); + } + } + return table; + } + + private: + std::string text_; + size_t pos_ = 0; // next character to read + + /// @brief The 1-based line @ref pos_ is on. + int line_here() const { + auto end = text_.begin() + static_cast<std::ptrdiff_t>(pos_); + return 1 + static_cast<int>(std::count(text_.begin(), end, '\n')); + } + + [[noreturn]] void fail(const std::string& msg) const { + config_error(line_here(), msg); + } + + /// @brief The next character, or `'\0'` at the end of the text. + char peek() const { return pos_ < text_.size() ? text_[pos_] : '\0'; } + + /// @brief Skips spaces, `\r` and comments, and newlines too if asked. + /// + /// A comment stops before its newline, so with @p newlines false the parser + /// ends up at the end of the line. + void skip_blank(bool newlines) { + while (pos_ < text_.size()) { + char c = text_[pos_]; + if (c == '#') { + while (pos_ < text_.size() && text_[pos_] != '\n') ++pos_; + } else if (c == ' ' || c == '\t' || c == '\r' || + (newlines && c == '\n')) { + ++pos_; + } else { + break; + } + } + } + + /// @brief Requires that nothing but a comment is left on this line. + void end_line() { + skip_blank(false); + if (pos_ < text_.size() && text_[pos_] != '\n') { + fail("unexpected text at the end of the line"); + } + } + + /// @brief Reads a key or table name: letters, digits, `_` and `-`. + /// + /// @param what What was expected, for the error message. + std::string parse_name(const char* what) { + size_t start = pos_; + while (pos_ < text_.size() && + (std::isalnum(static_cast<unsigned char>(text_[pos_])) || + text_[pos_] == '_' || text_[pos_] == '-')) { + ++pos_; + } + if (pos_ == start) fail(std::string("expected ") + what); + return text_.substr(start, pos_ - start); + } + + /// @brief Reads a `[name]` line and returns the name. + std::string parse_header() { + ++pos_; // '[' + skip_blank(false); + std::string name = parse_name("a table name"); + skip_blank(false); + if (peek() != ']') fail("expected ']'"); + ++pos_; + end_line(); + return name; + } -/// @brief Flags passed to the link command. + /// @brief Reads one `key = value` line into @p table. + /// + /// @param section The table the pair belongs to; empty at the top level. + /// @param table Receives the pair. + void parse_pair(const std::string& section, Table& table) { + Entry entry; + entry.line = line_here(); + std::string key = parse_name("a key"); + skip_blank(false); + if (peek() != '=') fail("expected '=' after the key"); + ++pos_; + skip_blank(false); + if (peek() == '[') { + entry.is_list = true; + entry.list = parse_array(); + } else { + entry.text = parse_string(); + } + end_line(); + + std::string full = section.empty() ? key : section + "." + key; + if (!table.emplace(full, entry).second) { + config_error(entry.line, "duplicate key '" + full + "'"); + } + } + + /// @brief Reads a string in double or single quotes. + std::string parse_string() { + char quote = peek(); + if (quote != '"' && quote != '\'') fail("expected a quoted string"); + ++pos_; + + std::string out; + for (;; ++pos_) { + if (pos_ >= text_.size() || text_[pos_] == '\n') { + fail("unterminated string"); + } + char c = text_[pos_]; + if (c == quote) break; + if (quote == '"' && c == '\\') { + char next = pos_ + 1 < text_.size() ? text_[pos_ + 1] : '\0'; + if (next != '\\' && next != '"') { + fail("unsupported escape; only \\\\ and \\\" are allowed"); + } + c = next; + ++pos_; + } + out += c; + } + ++pos_; // the closing quote + return out; + } + + /// @brief Reads `[ "a", "b", ... ]`, possibly over several lines. + Cmd parse_array() { + ++pos_; // '[' + Cmd items; + for (;;) { + skip_blank(true); + if (pos_ >= text_.size()) fail("unterminated array"); + if (text_[pos_] == ']') { + ++pos_; + return items; + } + items.push_back(parse_string()); + skip_blank(true); + if (peek() == ',') { + ++pos_; + } else if (peek() != ']') { + fail(pos_ >= text_.size() ? "unterminated array" + : "expected ',' or ']'"); + } + } + } +}; + +/// @brief Reads and checks #CONFIG_FILE. +/// +/// Exits with a message if the file is missing, malformed or contains a key +/// the builder does not know. /// -/// Linux needs "-lX11" and Windows needs "-luser32", "-lgdi32" once the window -/// code for those platforms exists. -static const Cmd LINK_FLAGS = - HOST == Platform::Mac ? Cmd{"-framework", "Cocoa", "-framework", - "Metal", "-framework", "QuartzCore"} - : Cmd{}; +/// @return The settings, with the table of the current platform merged in. +static Config load_config() { + std::ifstream file(CONFIG_FILE); + if (!file) { + config_error(0, "cannot read it; run the builder from the project root"); + } + std::stringstream buffer; + buffer << file.rdbuf(); + Table table = ConfigParser(buffer.str()).parse(); + + // Each take_*() removes the key from the table, so that what is left at the + // end is exactly the unknown keys. + auto take_string = [&table](const std::string& key, + const std::string& fallback) -> std::string { + auto it = table.find(key); + if (it == table.end()) return fallback; + if (it->second.is_list) { + config_error(it->second.line, "'" + key + "' must be a string"); + } + std::string value = it->second.text; + table.erase(it); + return value; + }; + auto take_list = [&table](const std::string& key) -> Cmd { + auto it = table.find(key); + if (it == table.end()) return {}; + if (!it->second.is_list) { + config_error(it->second.line, + "'" + key + "' must be a list, e.g. [\"a\", \"b\"]"); + } + Cmd value = it->second.list; + table.erase(it); + return value; + }; + + Config cfg; + std::string name = + take_string("name", fs::current_path().filename().string()); + cfg.compiler = take_string("compiler", "clang++"); + cfg.src_dir = take_string("src", "src"); + cfg.out_dir = take_string("out", "build"); + cfg.flags = take_list("flags"); + cfg.objcxx_flags = take_list("objcxx_flags"); + cfg.link_flags = take_list("link"); + + // Every platform's table is read, so that it counts as known, but only the + // one of this platform is used. + for (const char* platform : {"mac", "linux", "windows"}) { + const std::string section = platform; + Cmd flags = take_list(section + ".flags"); + Cmd link = take_list(section + ".link"); + if (section == HOST_NAME) { + cfg.flags.insert(cfg.flags.end(), flags.begin(), flags.end()); + cfg.link_flags.insert(cfg.link_flags.end(), link.begin(), link.end()); + } + } + + // Report the unknown key that was written first. + const Entry* first = nullptr; + std::string first_key; + for (const auto& [key, entry] : table) { + if (!first || entry.line < first->line) { + first = &entry; + first_key = key; + } + } + if (first) config_error(first->line, "unknown key '" + first_key + "'"); + + if (name.empty()) config_error(0, "'name' must not be empty"); + cfg.exe = cfg.out_dir / (name + EXE_SUFFIX); + return cfg; +} /// @} @@ -420,21 +725,22 @@ static std::vector<fs::path> read_depfile(const fs::path& path) { /// /// Any one of these is enough: /// -# @p obj or @p dep is missing (never built, or cleaned); -/// -# the builder is newer than @p obj (compile flags live in this file, so a -/// rebuilt builder may mean changed flags); +/// -# the builder or `kumo.toml` is newer than @p obj (the compile flags come +/// from those two, so a change to either may mean different flags); /// -# some dependency (the source itself or a header it includes) is newer /// than @p obj, or has been deleted. /// /// @param obj Path of the object file. /// @param dep Path of the dependency file written alongside it. -/// @param self_time Modification time of the builder binary. +/// @param flags_time Modification time of whatever the flags come from: the +/// newer of the builder binary and `kumo.toml`. /// @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) { + fs::file_time_type flags_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; + if (flags_time > obj_time) return true; for (const fs::path& d : read_depfile(dep)) { if (!fs::exists(d) || fs::last_write_time(d) > obj_time) return true; @@ -520,7 +826,7 @@ static void rebuild_self([[maybe_unused]] int argc, char** argv) { std::printf("[self] %s changed, rebuilding\n", SELF_SRC.generic_string().c_str()); - const Cmd compile = {CXX, "-std=c++20", SELF_SRC.string(), "-o", + const Cmd compile = {SELF_CXX, "-std=c++20", SELF_SRC.string(), "-o", SELF_EXE.string()}; #if defined(_WIN32) @@ -556,14 +862,23 @@ static void rebuild_self([[maybe_unused]] int argc, char** argv) { /// @return 0 on success, 1 if compiling, linking or running failed. int main(int argc, char** argv) { rebuild_self(argc, argv); + const Config cfg = load_config(); std::string mode = argc > 1 ? argv[1] : "build"; if (mode == "clean") { - fs::remove_all(OUT_DIR); + fs::remove_all(cfg.out_dir); return 0; } - fs::file_time_type self_time = fs::last_write_time(SELF_EXE); + if (!fs::is_directory(cfg.src_dir)) { + config_error(0, "the source directory '" + cfg.src_dir.string() + + "' (key 'src') does not exist"); + } + + // The compile flags come from the builder and from kumo.toml, so an object + // file older than either is stale. + fs::file_time_type flags_time = + std::max(fs::last_write_time(SELF_EXE), fs::last_write_time(CONFIG_FILE)); // Step 1: scan the sources, build a compile command for each one, and pick // out the stale ones. @@ -573,7 +888,7 @@ int main(int argc, char** argv) { 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::recursive_directory_iterator(cfg.src_dir)) { fs::path src = entry.path(); if (src.extension() != ".cpp" && src.extension() != ".mm") continue; if (!is_built_here(src)) continue; @@ -581,21 +896,20 @@ int main(int argc, char** argv) { // 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::path obj = cfg.out_dir / "obj" / (src.string() + ".o"); + fs::path dep = cfg.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(), PLATFORM_CXX_FLAGS.begin(), PLATFORM_CXX_FLAGS.end()); + Cmd cmd = {cfg.compiler}; + cmd.insert(cmd.end(), cfg.flags.begin(), cfg.flags.end()); if (src.extension() == ".mm") { - cmd.insert(cmd.end(), OBJCXX_FLAGS.begin(), OBJCXX_FLAGS.end()); + cmd.insert(cmd.end(), cfg.objcxx_flags.begin(), cfg.objcxx_flags.end()); } cmd.insert(cmd.end(), {"-MD", "-MF", dep.string(), "-c", src.string(), "-o", obj.string()}); - if (needs_compile(obj, dep, self_time)) { + if (needs_compile(obj, dep, flags_time)) { std::printf("[cc] %s\n", src.generic_string().c_str()); stale_cmds.push_back(cmd); } @@ -614,23 +928,23 @@ int main(int argc, char** argv) { // "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); + bool link_needed = !fs::exists(cfg.exe); for (const fs::path& obj : objects) { - if (!link_needed && fs::last_write_time(obj) > fs::last_write_time(EXE)) + if (!link_needed && fs::last_write_time(obj) > fs::last_write_time(cfg.exe)) link_needed = true; } if (link_needed) { - std::printf("[link] %s\n", EXE.generic_string().c_str()); - Cmd link = {CXX}; + std::printf("[link] %s\n", cfg.exe.generic_string().c_str()); + Cmd link = {cfg.compiler}; 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()}); + link.insert(link.end(), cfg.link_flags.begin(), cfg.link_flags.end()); + link.insert(link.end(), {"-o", cfg.exe.string()}); if (!run(link)) return 1; } if (mode == "run") { // Windows wants backslashes in the path of a program to start. - fs::path program = EXE; + fs::path program = cfg.exe; program.make_preferred(); return run({program.string()}) ? 0 : 1; }
