Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit 58b1a8f5893b418282cb3512daa326e3a7062395
parent 5d2aded2dab6f6e395ea7e0374130c21c20dca28
Author: sentomk <sentomk@proton.me>
Date:   Fri,  9 Oct 2026 17:16:41 +0800

feat: add a test mode to the builder

`kumoko test [name]` builds and runs every tests/**/*_test.cpp. Each one
is a program of its own, linked with all the sources except the entry
point, and passes if it exits with status 0. The optional name selects
tests whose path contains it.

New kumo.toml keys: `entry`, the file holding main(), and `tests`, the
directory of test programs. Both are checked like `src` and `out`, and
`tests` must not nest with either. A `_test` suffix is ignored when
deciding which platform a file belongs to, so window_mac_test.cpp is for
macOS only.

Planning, compiling and linking move out of main() into plan_units(),
compile_stale() and link_if_needed(), shared by the build and test modes.
Objects are now sorted by path, and tests are listed in compile_commands.json
for clangd.

Diffstat:
Mkumo.toml | 2++
Mkumo_builder.cpp | 330+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
2 files changed, 260 insertions(+), 72 deletions(-)

diff --git a/kumo.toml b/kumo.toml @@ -7,6 +7,8 @@ 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 +entry = "src/main.cpp" # the file with main(); `kumoko test` leaves it out +tests = "tests" # test programs: tests/**/*_test.cpp, run by `kumoko test` # Flags for every compile command. flags = [ diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -21,6 +21,8 @@ /// ./kumoko # incremental build /// ./kumoko run # incremental build, then run the executable /// ./kumoko clean # delete all build output +/// ./kumoko test [name] # build and run the tests, only those whose name +/// # contains `name` if one is given /// @endcode /// /// Platform-specific source files are marked by their name, see @@ -146,6 +148,10 @@ static const fs::path CONFIG_FILE = "kumo.toml"; /// - `compiler`: the C++ compiler (default: `clang++`); /// - `src`: the source tree, searched recursively (default: `src`); /// - `out`: where all build output goes (default: `build`); +/// - `entry`: the source file that holds `main` of the program (default: +/// `main.cpp` inside `src`); `test` mode leaves it out, because every test +/// program has a `main` of its own; +/// - `tests`: the directory of test programs, see "Tests" (default: `tests`); /// - `flags`: compile flags for every source file; /// - `objcxx_flags`: extra compile flags for `.mm` files only; /// - `link`: link flags. @@ -166,10 +172,12 @@ 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. + fs::path entry; ///< The source file with `main`, inside #src_dir. + fs::path tests_dir; ///< Directory of test programs. + 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 Reports a problem with #CONFIG_FILE and exits. @@ -455,6 +463,8 @@ static Config load_config() { cfg.compiler = take_string("compiler", "clang++"); cfg.src_dir = take_string("src", "src"); cfg.out_dir = take_string("out", "build"); + cfg.entry = take_string("entry", (cfg.src_dir / "main.cpp").string()); + cfg.tests_dir = take_string("tests", "tests"); cfg.flags = take_list("flags"); cfg.objcxx_flags = take_list("objcxx_flags"); cfg.link_flags = take_list("link"); @@ -504,6 +514,22 @@ static Config load_config() { "'out' and 'src' must not be the same directory or " "contain one another"); } + if (!is_within(cfg.entry, cfg.src_dir) || + cfg.entry.lexically_normal() == cfg.src_dir.lexically_normal()) { + config_error(0, "'entry' must be a file inside 'src'"); + } + if (!is_inside_project(cfg.tests_dir)) { + config_error(0, + "'tests' must be a relative path inside the project, and " + "not the project directory itself"); + } + for (const fs::path* other : {&cfg.src_dir, &cfg.out_dir}) { + if (is_within(cfg.tests_dir, *other) || is_within(*other, cfg.tests_dir)) { + config_error(0, + "'tests' must not be the same directory as 'src' or 'out', " + "nor inside or around either of them"); + } + } cfg.exe = cfg.out_dir / (name + EXE_SUFFIX); return cfg; } @@ -524,6 +550,9 @@ static Config load_config() { /// Everything else builds everywhere. The suffix test is purely textual, so /// avoid ending a portable file's name with one of them (e.g. `big_win.cpp`). /// +/// A `_test` at the end of the name is ignored first, so `window_mac_test.cpp` +/// belongs to macOS like `window_mac.cpp` does. +/// /// @param src Path of the source file. /// @return `true` if the file must be compiled on this platform. static bool is_built_here(const fs::path& src) { @@ -537,7 +566,8 @@ static bool is_built_here(const fs::path& src) { {"_linux", Platform::Linux}, {"_win", Platform::Windows}, }; - const std::string stem = src.stem().string(); + std::string stem = src.stem().string(); + if (stem.ends_with("_test")) stem.resize(stem.size() - 5); for (const auto& entry : SUFFIXES) { if (stem.ends_with(entry.suffix)) return entry.platform == HOST; } @@ -861,19 +891,147 @@ static void write_compile_commands(const std::vector<fs::path>& sources, /// @} +/// @name Compiling and linking +/// The steps shared by building the program and building the tests. +/// @{ + +/// @brief One source file and how it is compiled. +struct Unit { + fs::path src; + fs::path obj; ///< Where the compiled object goes. + Cmd cmd; ///< The command that compiles #src into #obj. + bool stale; ///< Whether #obj is out of date. +}; + +/// @brief Plans the compilation of the sources found under a directory. +/// +/// Nothing is compiled here. The result is sorted by path, so that the order of +/// the output and of the link line does not depend on the file system. +/// +/// @param cfg Project settings. +/// @param dir Directory searched recursively for `.cpp` and `.mm`. +/// @param tests_only Take only files whose name ends in `_test`. +/// @param extra_flags Flags added after the project's compile flags. +/// @param flags_time Modification time of whatever the flags come from. +/// @return One unit per file that is built on this platform. +static std::vector<Unit> plan_units(const Config& cfg, const fs::path& dir, + bool tests_only, const Cmd& extra_flags, + fs::file_time_type flags_time) { + std::vector<Unit> units; + for (const fs::directory_entry& entry : + fs::recursive_directory_iterator(dir)) { + fs::path src = entry.path(); + if (src.extension() != ".cpp" && src.extension() != ".mm") continue; + if (tests_only && !src.stem().string().ends_with("_test")) continue; + if (!is_built_here(src)) 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 = 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 = {cfg.compiler}; + cmd.insert(cmd.end(), cfg.flags.begin(), cfg.flags.end()); + cmd.insert(cmd.end(), extra_flags.begin(), extra_flags.end()); + if (src.extension() == ".mm") { + 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()}); + + units.push_back({src, obj, cmd, needs_compile(obj, dep, flags_time)}); + } + std::sort(units.begin(), units.end(), + [](const Unit& a, const Unit& b) { return a.src < b.src; }); + return units; +} + +/// @brief Compiles those of the given units that are stale, in parallel. +/// +/// @param units The units to consider; the up to date ones are skipped. +/// @return `true` if every compilation succeeded. +static bool compile_stale(const std::vector<const Unit*>& units) { + std::vector<Cmd> cmds; + for (const Unit* unit : units) { + if (!unit->stale) continue; + std::printf("[cc] %s\n", unit->src.generic_string().c_str()); + cmds.push_back(unit->cmd); + } + // hardware_concurrency may return 0, meaning "unknown". + unsigned jobs = std::thread::hardware_concurrency(); + return run_all(cmds, jobs ? jobs : 4); +} + +/// @brief Links object files into an executable, unless it is up to date. +/// +/// "Did we compile anything this time?" is not a valid test for being up to +/// date: if the last run compiled successfully but failed to link, nothing is +/// stale now and yet the link is still needed. So the executable is compared +/// with the objects themselves. +/// +/// @param cfg Project settings. +/// @param objects The objects to link. +/// @param exe The executable to produce. +/// @return `true` if the executable is up to date afterwards. +static bool link_if_needed(const Config& cfg, + const std::vector<fs::path>& objects, + const fs::path& exe) { + bool needed = !fs::exists(exe); + for (const fs::path& obj : objects) { + if (!needed && fs::last_write_time(obj) > fs::last_write_time(exe)) { + needed = true; + } + } + if (!needed) return true; + + std::printf("[link] %s\n", exe.generic_string().c_str()); + fs::create_directories(exe.parent_path()); + Cmd link = {cfg.compiler}; + for (const fs::path& obj : objects) link.push_back(obj.string()); + link.insert(link.end(), cfg.link_flags.begin(), cfg.link_flags.end()); + link.insert(link.end(), {"-o", exe.string()}); + return run(link); +} + +/// @} + +/// @name Tests +/// Every `*_test.cpp` under the tests directory is a program of its own. It is +/// linked with all the sources of the project except the entry point, and it +/// passes if it exits with status 0. +/// @{ + +/// @brief The name a test is listed and selected by: its path inside the tests +/// directory, without the extension (`render/raster_test`). +static std::string test_name(const Config& cfg, const fs::path& src) { + fs::path name = src.lexically_relative(cfg.tests_dir); + name.replace_extension(""); + return name.generic_string(); +} + +/// @brief Where the executable of a test is put. +static fs::path test_exe(const Config& cfg, const fs::path& src) { + return cfg.out_dir / "tests" / (test_name(cfg, src) + EXE_SUFFIX); +} + +/// @} + /// @name Entry point /// @{ /// @brief Recompiles and restarts the builder if its source has changed. /// -/// If #SELF_SRC is newer than the builder's executable, it is recompiled and -/// the new binary takes over with the same arguments. The new binary is always -/// newer than the source, so this cannot loop forever. +/// If #SELF_SRC is newer than the builder's executable, it is recompiled +/// and the new binary takes over with the same arguments. The new binary is +/// always newer than the source, so this cannot loop forever. /// /// On macOS and Linux `execv` replaces the current process. Windows has no -/// equivalent, so the running executable is renamed out of the way, the new one -/// is built under the original name, and it is then run as a child whose exit -/// status becomes ours. +/// equivalent, so the running executable is renamed out of the way, the new +/// one is built under the original name, and it is then run as a child +/// whose exit status becomes ours. /// /// @param argc Argument count of main(). /// @param argv Argument vector of main(), forwarded to the new binary. @@ -918,11 +1076,13 @@ static void rebuild_self([[maybe_unused]] int argc, char** argv) { #endif } -/// @brief Builds the project. +/// @brief Builds the project, runs it, or builds and runs its tests. /// /// @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. +/// @param argv `argv[1]` selects the mode: `build` (default), `run`, `test` or +/// `clean`. In `test` mode `argv[2]` may select tests by name. +/// @return 0 on success, 1 if compiling, linking or running failed or a test +/// failed. int main(int argc, char** argv) { rebuild_self(argc, argv); const Config cfg = load_config(); @@ -932,86 +1092,112 @@ int main(int argc, char** argv) { fs::remove_all(cfg.out_dir); return 0; } + const bool testing = mode == "test"; + const std::string filter = testing && argc > 2 ? argv[2] : ""; if (!fs::is_directory(cfg.src_dir)) { config_error(0, "the source directory '" + cfg.src_dir.string() + "' (key 'src') does not exist"); } + const bool has_tests = fs::is_directory(cfg.tests_dir); + if (testing && !has_tests) { + config_error(0, "the tests directory '" + cfg.tests_dir.string() + + "' (key 'tests') 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. - 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(cfg.src_dir)) { - fs::path src = entry.path(); - if (src.extension() != ".cpp" && src.extension() != ".mm") continue; - if (!is_built_here(src)) continue; + // Step 1: plan the compilation of the sources and of the tests, and tell + // clangd about all of them whatever the mode. + std::vector<Unit> units = plan_units(cfg, cfg.src_dir, false, {}, flags_time); + std::vector<Unit> tests; + if (has_tests) { + tests = plan_units(cfg, cfg.tests_dir, true, + {"-I" + cfg.tests_dir.generic_string()}, flags_time); + } + std::vector<fs::path> sources; + std::vector<Cmd> all_cmds; + for (const std::vector<Unit>* group : {&units, &tests}) { + for (const Unit& unit : *group) { + sources.push_back(unit.src); + all_cmds.push_back(unit.cmd); + } + } + write_compile_commands(sources, all_cmds); - // 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 = cfg.out_dir / "obj" / (src.string() + ".o"); - fs::path dep = cfg.out_dir / "obj" / (src.string() + ".d"); - fs::create_directories(obj.parent_path()); + // Step 2: decide what to compile. In test mode the entry point is left out + // of the program's objects, because every test has a `main` of its own. + std::vector<const Unit*> to_compile; + std::vector<fs::path> objects; // what a final link gets, tests excluded + bool found_entry = false; + for (const Unit& unit : units) { + if (testing && + unit.src.lexically_normal() == cfg.entry.lexically_normal()) { + found_entry = true; + continue; + } + objects.push_back(unit.obj); + to_compile.push_back(&unit); + } + if (testing && !found_entry) { + config_error(0, "the entry file '" + cfg.entry.string() + + "' (key 'entry') is not among the sources"); + } - // -MD -MF <dep>: write the dependency list to dep while compiling. - Cmd cmd = {cfg.compiler}; - cmd.insert(cmd.end(), cfg.flags.begin(), cfg.flags.end()); - if (src.extension() == ".mm") { - cmd.insert(cmd.end(), cfg.objcxx_flags.begin(), cfg.objcxx_flags.end()); + std::vector<const Unit*> selected; // the tests to build and run + if (testing) { + for (const Unit& test : tests) { + if (test_name(cfg, test.src).find(filter) == std::string::npos) continue; + selected.push_back(&test); + to_compile.push_back(&test); } - cmd.insert(cmd.end(), {"-MD", "-MF", dep.string(), "-c", src.string(), "-o", - obj.string()}); + if (selected.empty()) { + std::printf("no tests found%s%s\n", filter.empty() ? "" : " matching ", + filter.c_str()); + return 1; + } + } - if (needs_compile(obj, dep, flags_time)) { - std::printf("[cc] %s\n", src.generic_string().c_str()); - stale_cmds.push_back(cmd); + // Step 3: compile whatever is stale, in parallel. + if (!compile_stale(to_compile)) return 1; + + // Step 4: link and run. + if (!testing) { + if (!link_if_needed(cfg, objects, cfg.exe)) return 1; + if (mode == "run") { + // Windows wants backslashes in the path of a program to start. + fs::path program = cfg.exe; + program.make_preferred(); + return run({program.string()}) ? 0 : 1; } - sources.push_back(src); - objects.push_back(obj); - all_cmds.push_back(cmd); + return 0; } - 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; + std::vector<std::string> failed; + for (const Unit* test : selected) { + std::vector<fs::path> test_objects = {test->obj}; + test_objects.insert(test_objects.end(), objects.begin(), objects.end()); + const fs::path exe = test_exe(cfg, test->src); + if (!link_if_needed(cfg, test_objects, exe)) 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(cfg.exe); - for (const fs::path& obj : objects) { - 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", 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(), cfg.link_flags.begin(), cfg.link_flags.end()); - link.insert(link.end(), {"-o", cfg.exe.string()}); - if (!run(link)) return 1; + const std::string name = test_name(cfg, test->src); + std::printf("[test] %s\n", name.c_str()); + fs::path program = exe; + program.make_preferred(); + if (!run({program.string()})) failed.push_back(name); } - if (mode == "run") { - // Windows wants backslashes in the path of a program to start. - fs::path program = cfg.exe; - program.make_preferred(); - return run({program.string()}) ? 0 : 1; + if (failed.empty()) { + std::printf("all %zu test programs passed\n", selected.size()); + return 0; } - return 0; + std::printf("%zu of %zu test programs failed:\n", failed.size(), + selected.size()); + for (const std::string& name : failed) std::printf(" %s\n", name.c_str()); + return 1; } /// @}