From fdba70d176189138da931782fd98463198eca456 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 01/53] fix(cuda): look for nvcc instead of leaving it to PATH cfg.cuda compiled with a bare "nvcc", which the shell looked up on PATH. In crafter-build's Flatpak PATH is /app/bin:/usr/bin, as its manifest sets it, which never holds the host's toolkit, so with it every build with CUDA sources stopped at "sh: line 1: nvcc: command not found", although the sandbox sees /opt/cuda through --filesystem=host. ResolveToolchain now finds nvcc as it finds clang++: CUDA_PATH, which is exclusive as CRAFTER_BUILD_LLVM_DIR is, else /opt/cuda (Arch's package) or /usr/local/cuda (NVIDIA's installer and packages), else the absolute entries of PATH, which it searches itself so that a build without a toolkit can say where it looked. A relative CUDA_PATH is made absolute there, once, as CRAFTER_MINGW_DIR is, since nvcc runs later from whatever working directory a build is in. The sandbox shows the host's /usr and /etc under /run/host, with its own runtime at /usr, and NVIDIA's /usr/local/cuda is a link, to /usr/local/cuda- or through /etc/alternatives. A link to an absolute path names a path of the host, /opt/cuda pointing at /usr/local/cuda- too, and the sandbox would look it up in its own root, so where the path of a toolkit, CUDA_PATH, /opt/cuda or /usr/local/cuda, is such a link, HostPath follows it, and the link its target is in turn, each taken as the host's; a link partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. A missing toolkit is reported by the build that has a .cu to compile and not by GetToolchain(), so no other build fails for want of one. crafter-build --version prints the nvcc it found, whether or not the compiler could be resolved. --- AGENTS.template.md | 2 +- implementations/Crafter.Build-Clang.cpp | 24 +++++- implementations/Crafter.Build-Toolchain.cpp | 89 +++++++++++++++++++++ interfaces/Crafter.Build-Toolchain.cppm | 21 ++++- 4 files changed, 132 insertions(+), 4 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 119eaa4..2a93992 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -23,7 +23,7 @@ crafter-build is a C++26 modules build system. A project is described by a `proj Partitions and what they own: -- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. +- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. - `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. - `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code. - `:Interface` and `:Implementation` model module units, their staleness checks and their compiles. diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 26b5cb0..20567d6 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -1147,11 +1147,19 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath))) { - threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled]() { + const Toolchain& toolchain = GetToolchain(); + if (toolchain.nvcc.empty()) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError); + } + break; + } + threads.emplace_back([&cFile, &buildError, &buildCancelled, &toolchain, srcPath, objPath]() { Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string())); if (buildCancelled.load(std::memory_order_relaxed)) return; - std::string result = RunBuildCommand(std::format("nvcc {}.cu -c -o {}_source.o -O3 -arch=sm_89", cFile.string(), (buildDir / cFile.filename()).string())); + std::string result = RunBuildCommand(std::format("{} {} -c -o {} -O3 -arch=sm_89", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(objPath))); if (result.empty()) return; bool expected = false; @@ -2049,8 +2057,15 @@ std::vector Crafter::CleanProject(const fs::path& projectFile) { static void PrintVersion() { std::println("crafter-build {}", CrafterBuildVersion()); const Toolchain& tc = GetToolchain(); + // nvcc only when there is one: most projects have no CUDA sources, and the + // build that has some says where it looked. Found apart from the compiler, + // so printed whether or not that was resolved. + const auto cuda = [&tc]() { + if (!tc.nvcc.empty()) std::println("nvcc {}", tc.nvcc.string()); + }; if (!tc.error.empty()) { std::println("compiler: {}", tc.error); + cuda(); return; } std::println("compiler {} ({})", tc.clangVersion, tc.clangxx.string()); @@ -2069,6 +2084,7 @@ static void PrintVersion() { std::println("libc++ {}{}", LibcxxVersionString(tc.libcxxVersion), also.empty() ? std::string() : std::format(" (std module sources for sysroots also for{})", also.substr(1))); } std::println("host {}", tc.hostTriple); + cuda(); } static void PrintHelp(std::string_view argv0) { @@ -2202,6 +2218,10 @@ Project args: Environment: CRAFTER_BUILD_MARCH Override -march (default: native). CRAFTER_BUILD_MTUNE Override -mtune (default: native). + CUDA_PATH CUDA toolkit whose bin/nvcc compiles + cfg.cuda. Default: /opt/cuda, then + /usr/local/cuda (in the Flatpak, the + host's), then nvcc on PATH. CRAFTER_BUILD_RUNNER_ Default test runner for a target triple. Replace '-' and '.' with '_' in the triple. CLI --runner= overrides this. diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index 1167f8c..f023c62 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -23,6 +23,8 @@ namespace { "CRAFTER_BUILD_WASI_SYSROOT", "CRAFTER_BUILD_FLATPAK_INFO", "CRAFTER_MINGW_DIR", + "CUDA_PATH", + "PATH", }; // The arch and branch of the runtime=runtime/// line @@ -100,6 +102,48 @@ namespace { return normal; } + // A regular file someone may run, as the shell's PATH lookup wants one. + bool IsProgram(const fs::path& file) { + std::error_code ec; + if (!fs::is_regular_file(file, ec)) return false; + constexpr fs::perms Exec = fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec; + return (fs::status(file, ec).permissions() & Exec) != fs::perms::none; + } + + // `path`, as the host names it, where this process finds it. A sandbox + // shows the host's /usr and /etc, and the directories beside them its + // own runtime has (bin, sbin, lib, lib64), under hostRoot, and + // everything else, /opt and /home among it, where the host has it. A + // link to an absolute path names the host's path wherever the link is, + // and the sandbox would look it up in its own root instead: NVIDIA's + // /usr/local/cuda is a link, to /usr/local/cuda- or through + // /etc/alternatives, and an /opt/cuda can be one to such a directory. + // So where the path is a link, it is followed here, and so is its + // target where that is one, each taken as the host's. Outside a + // sandbox, `path` itself. + fs::path HostPath(fs::path path, const fs::path& hostRoot) { + if (hostRoot.empty()) return path; + fs::path shown = path; + // As many links as the kernel follows before it gives up on a loop. + for (std::int32_t hops = 0; hops < 40; ++hops) { + if (!path.is_absolute()) return path; + // Without a trailing separator, which has readlink follow the + // link instead of reading it. + path = path.lexically_normal(); + if (!path.has_filename() && path.has_relative_path()) path = path.parent_path(); + const fs::path relative = path.relative_path(); + const fs::path top = relative.empty() ? fs::path() : *relative.begin(); + const bool underHostRoot = top == "usr" || top == "etc" || top == "bin" || top == "sbin" || top == "lib" || top == "lib64"; + shown = underHostRoot ? hostRoot / relative : path; + std::error_code ec; + const fs::path target = fs::read_symlink(shown, ec); + if (ec) return shown; + path = target.is_absolute() ? target : (path.parent_path() / target).lexically_normal(); + } + // Still a link after all of them: a loop, which opens as nothing. + return shown; + } + // The view MingwSysroot() made and the prefix it shows, for // MingwViewToPrefix. Written once, before ViewMade is set. fs::path MadeView; @@ -221,6 +265,50 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { tc.mingwPrefix = PrefixPath(in.hostRoot / "usr"); tc.mingwPrefixIsSystem = true; } + + // 5. nvcc, for cfg.cuda. CUDA_PATH is exclusive, as CRAFTER_BUILD_LLVM_DIR + // is: it names the toolkit, and one without nvcc is an error rather + // than a reason to use another. PATH is searched here, not by the + // shell: in crafter-build's Flatpak it is /app/bin:/usr/bin, which + // never holds the host's toolkit, and every CUDA build there stopped + // at "nvcc: command not found", which named no place to put one. + if (std::string_view cudaPath = Env(in, "CUDA_PATH"); !cudaPath.empty()) { + // Absolute and spelled one way, once, as CRAFTER_MINGW_DIR is: nvcc + // runs later, from whatever working directory a build is in. + const fs::path named = PrefixPath(fs::path(cudaPath)); + if (const fs::path nvcc = HostPath(named, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) { + tc.nvcc = nvcc; + } else { + tc.nvccError = std::format("no nvcc at {} (CUDA_PATH)", (named / "bin" / "nvcc").string()); + } + } else { + std::vector lookedAt; + for (const fs::path& root : in.cudaRoots) { + if (const fs::path nvcc = HostPath(root, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) { + tc.nvcc = nvcc; + break; + } + lookedAt.push_back((root / "bin" / "nvcc").string()); + } + const std::string_view path = Env(in, "PATH"); + for (std::size_t at = 0; tc.nvcc.empty() && at <= path.size();) { + std::size_t end = path.find(':', at); + if (end == std::string_view::npos) end = path.size(); + // An empty or a relative entry names a directory under whatever + // the working directory is, and this lookup is made once per + // process: only an absolute one names a place. + if (const std::string_view dir = path.substr(at, end - at); fs::path(dir).is_absolute() && IsProgram(fs::path(dir) / "nvcc")) { + tc.nvcc = fs::path(dir) / "nvcc"; + } + at = end + 1; + } + if (tc.nvcc.empty()) { + lookedAt.push_back(std::format("nvcc on PATH ({})", path.empty() ? std::string_view("unset") : path)); + std::string places = lookedAt.front(); + for (std::size_t i = 1; i < lookedAt.size(); ++i) places += std::format("{}{}", i + 1 == lookedAt.size() ? " and " : ", ", lookedAt[i]); + tc.nvccError = std::format("no CUDA toolkit found: looked for {}; set CUDA_PATH to the directory a toolkit is installed in", places); + } + } std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); return tc; } @@ -239,6 +327,7 @@ const Toolchain& Crafter::GetToolchain() { in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path(); } catch (const std::exception&) {} if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; + in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" }; { auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO"); const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info"); diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 84c0194..604f6d1 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -55,6 +55,18 @@ export namespace Crafter { // its mingw-w64 parts; any other prefix is the sysroot itself, and // Windows libraries installed into its include/ and lib/ are found. bool mingwPrefixIsSystem = false; + // The nvcc that compiles cfg.cuda: /bin/nvcc when CUDA_PATH + // is set, else bin/nvcc of the first toolkit that has one among + // ToolchainInputs::cudaRoots, else the first nvcc in an absolute entry + // of PATH. In a sandbox, a toolkit is looked up as the host has it: + // under hostRoot where it is in the host's /usr or /etc, and, where + // its path is a link, through that link and the link its target is in + // turn, each taken as the host's, wherever they point. Empty when + // there is none, and nvccError says where it was looked for; only a + // build with a .cu to compile reports that, so no other build fails + // for want of a CUDA toolkit. + fs::path nvcc; + std::string nvccError; // The Flatpak runtime crafter-build runs on, from the // runtime=runtime/// line of /.flatpak-info: // "x86_64" and "26.08" in the Flatpak, both empty outside one. A @@ -98,7 +110,8 @@ export namespace Crafter { // What ResolveToolchain reads, so a test can feed it a staged layout. struct ToolchainInputs { - // The CRAFTER_* variables, present only when set and non-empty. + // The CRAFTER_* variables, CUDA_PATH and PATH, present only when set + // and non-empty. std::map> env; // The of /share/crafter-build; empty when unknown. fs::path crafterPrefix; @@ -108,10 +121,16 @@ export namespace Crafter { // What /.flatpak-info holds, or the file CRAFTER_BUILD_FLATPAK_INFO // names; empty outside a Flatpak. std::string flatpakInfo; + // Where a CUDA toolkit is installed when CUDA_PATH names none, in the + // order they are tried and as the host names them: GetToolchain() + // passes /opt/cuda, Arch's, and /usr/local/cuda, NVIDIA's installers'. + std::vector cudaRoots; }; // Pure path resolution: an env override wins, then a toolchain installed // beside crafter-build (/bin/clang++), then bare names on // PATH. Never runs a process, so hostTriple and clangVersion stay empty. + // nvcc is not left to the shell's PATH lookup but searched for here, + // PATH included, so a build that cannot find one can say where it looked. Toolchain ResolveToolchain(const ToolchainInputs& inputs); // ResolveToolchain over the real environment plus the two clang probes, // computed once and cached. Never throws. From 2fd45133a0afa6a9cdb74080a64e8b90d63858eb Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 02/53] test(cuda): resolve nvcc on staged toolkits ToolchainResolve stages toolkit roots, a PATH and a host root, and checks the order (CUDA_PATH, then the roots, then PATH), that a CUDA_PATH without an nvcc is an error and not a fallback, that a relative one names an absolute nvcc, that a file that cannot be run is no nvcc and a relative PATH entry no place to look, what the error says when there is none, and that a toolkit resolves under the host root through a link: /usr/local/cuda in the host's /usr to an absolute path, named with a trailing slash too, through /etc/alternatives and to a relative path, and a link outside the host's /usr that leads into it. A link to itself finds nothing. --- tests/ToolchainResolve/main.cpp | 114 ++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index 2ef5abf..849c36a 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -26,6 +26,12 @@ namespace { std::ofstream(file) << ""; } + // An empty file that may be run, as an nvcc found on PATH has to be. + void Program(const fs::path& file) { + Touch(file); + fs::permissions(file, fs::perms::owner_exec, fs::perm_options::add); + } + bool Contains(std::string_view haystack, std::string_view needle) { return haystack.find(needle) != std::string_view::npos; } @@ -188,6 +194,114 @@ int main() { Check(ResolveToolchain(in).mingwPrefix == "/opt/mingw", "CRAFTER_MINGW_DIR wins over the host's"); fs::remove_all(host); } + { + // nvcc, for cfg.cuda: the toolkit CUDA_PATH names, else the first + // root with a bin/nvcc, else the first nvcc that can be run in an + // absolute PATH entry. + const fs::path cuda = scratch / "cuda"; + const fs::path first = cuda / "first"; + const fs::path second = cuda / "second"; + const fs::path onPath = cuda / "on-path"; + Program(second / "bin/nvcc"); + Program(onPath / "nvcc"); + Program(cuda / "named/bin/nvcc"); + Touch(cuda / "not-a-program/nvcc"); + ToolchainInputs in; + in.cudaRoots = { first, second }; + in.env["PATH"] = std::format("{}::{}:{}", (cuda / "not-a-program").string(), (cuda / "nothing").string(), onPath.string()); + Toolchain tc = ResolveToolchain(in); + Check(tc.nvcc == second / "bin/nvcc" && tc.nvccError.empty(), std::format("the first toolkit root with a bin/nvcc wins over PATH (got '{}')", tc.nvcc.string())); + Program(first / "bin/nvcc"); + Check(ResolveToolchain(in).nvcc == first / "bin/nvcc", "the toolkit roots are tried in order"); + in.cudaRoots.clear(); + Check(ResolveToolchain(in).nvcc == onPath / "nvcc", std::format("without a toolkit root, the first nvcc that can be run in an absolute PATH entry (got '{}')", ResolveToolchain(in).nvcc.string())); + { + // A relative entry names a directory under whatever the + // working directory is: passed over, as an empty one is. + const fs::path cwd = fs::current_path(); + fs::current_path(cuda); + ToolchainInputs relative; + relative.env["PATH"] = std::format("on-path:{}", onPath.string()); + Check(ResolveToolchain(relative).nvcc == onPath / "nvcc", std::format("a relative PATH entry is passed over (got '{}')", ResolveToolchain(relative).nvcc.string())); + relative.env["PATH"] = "on-path"; + Check(ResolveToolchain(relative).nvcc.empty(), "a PATH of relative entries finds no nvcc"); + fs::current_path(cwd); + } + in.cudaRoots = { first }; + in.env["CUDA_PATH"] = (cuda / "named").string(); + Check(ResolveToolchain(in).nvcc == cuda / "named/bin/nvcc", "CUDA_PATH wins over the toolkit roots and PATH"); + in.env["CUDA_PATH"] = (cuda / "missing").string(); + tc = ResolveToolchain(in); + Check(tc.nvcc.empty() && tc.nvccError == std::format("no nvcc at {} (CUDA_PATH)", (cuda / "missing/bin/nvcc").string()), std::format("a CUDA_PATH without bin/nvcc is an error naming it, not a fallback (got '{}')", tc.nvccError)); + Check(tc.error.empty(), "no nvcc is no toolchain error: only a build with CUDA sources needs one"); + { + // A relative CUDA_PATH is taken against the working directory + // once, as CRAFTER_MINGW_DIR is: nvcc runs later, from whatever + // directory a build is in. + const fs::path cwd = fs::current_path(); + fs::current_path(cuda); + ToolchainInputs relative; + relative.env["CUDA_PATH"] = "named"; + const fs::path found = ResolveToolchain(relative).nvcc; + fs::current_path(cwd); + Check(found.is_absolute() && fs::equivalent(found, cuda / "named/bin/nvcc"), std::format("a relative CUDA_PATH names an absolute nvcc (got '{}')", found.string())); + } + } + { + // Nothing anywhere: the error says where it looked and what to set. + ToolchainInputs in; + in.cudaRoots = { "/nonexistent/opt-cuda", "/nonexistent/local-cuda" }; + in.env["PATH"] = (scratch / "no-nvcc").string(); + const Toolchain tc = ResolveToolchain(in); + const std::string expected = std::format("no CUDA toolkit found: looked for /nonexistent/opt-cuda/bin/nvcc, /nonexistent/local-cuda/bin/nvcc and nvcc on PATH ({}); set CUDA_PATH to the directory a toolkit is installed in", (scratch / "no-nvcc").string()); + Check(tc.nvcc.empty() && tc.nvccError == expected, std::format("the error names every place looked at (got '{}')", tc.nvccError)); + Check(ResolveToolchain({}).nvccError.contains("nvcc on PATH (unset)"), "an unset PATH is said to be unset"); + } + { + // Sandboxed, the host's /usr and /etc show under the host root, and + // a link there to an absolute path names a path of the host, which + // the sandbox would look up in its own root. + const fs::path host = fs::temp_directory_path() / "crafter-build-toolchain-cuda-host"; + fs::remove_all(host); + const fs::path installed = host / "usr/local/cuda-13.0/bin/nvcc"; + Program(installed); + ToolchainInputs in; + in.hostRoot = host; + in.cudaRoots = { "/usr/local/cuda" }; + fs::create_directory_symlink("/usr/local/cuda-13.0", host / "usr/local/cuda"); + Check(ResolveToolchain(in).nvcc == installed, std::format("an absolute link is followed under the host root (got '{}')", ResolveToolchain(in).nvcc.string())); + in.cudaRoots = { "/usr/local/cuda/" }; + Check(ResolveToolchain(in).nvcc == installed, std::format("and so is one named with a trailing separator, which readlink follows instead of reading (got '{}')", ResolveToolchain(in).nvcc.string())); + in.cudaRoots = { "/usr/local/cuda" }; + fs::remove(host / "usr/local/cuda"); + fs::create_directories(host / "etc/alternatives"); + fs::create_directory_symlink("/usr/local/cuda-13.0", host / "etc/alternatives/cuda"); + fs::create_directory_symlink("/etc/alternatives/cuda", host / "usr/local/cuda"); + Check(ResolveToolchain(in).nvcc == installed, "so is a link through /etc/alternatives"); + fs::remove(host / "usr/local/cuda"); + fs::create_directory_symlink("cuda-13.0", host / "usr/local/cuda"); + Check(ResolveToolchain(in).nvcc == installed, "and a relative link"); + in.cudaRoots.clear(); + in.env["CUDA_PATH"] = "/usr/local/cuda"; + Check(ResolveToolchain(in).nvcc == installed, "CUDA_PATH names a path of the host too"); + // Outside its /usr and /etc, the host's files are where the host has + // them, as /opt/cuda is. + in.env["CUDA_PATH"] = (scratch / "cuda/named").string(); + Check(ResolveToolchain(in).nvcc == scratch / "cuda/named/bin/nvcc", "a toolkit outside the host's /usr is taken where it is"); + // A link there that names a path of the host's /usr is followed + // under the host root, as one in it is: an /opt/cuda pointing at + // NVIDIA's /usr/local/cuda-. + fs::create_directory_symlink("/usr/local/cuda-13.0", scratch / "opt-cuda"); + in.env["CUDA_PATH"] = (scratch / "opt-cuda").string(); + Check(ResolveToolchain(in).nvcc == installed, std::format("a link outside the host's /usr into it is followed under the host root (got '{}')", ResolveToolchain(in).nvcc.string())); + // A link to itself, under a name no machine's own root has: the + // kernel, which follows it in this process's root, must not reach a + // toolkit through it either. + fs::create_directory_symlink("/usr/local/crafter-build-cuda-loop", host / "usr/local/crafter-build-cuda-loop"); + in.env["CUDA_PATH"] = "/usr/local/crafter-build-cuda-loop"; + Check(ResolveToolchain(in).nvcc.empty(), "a link to itself ends, and finds nothing"); + fs::remove_all(host); + } { // The cache key separates toolchains that would build different // PCMs and nothing else. From 967dd12b06cfe257e40b99e22d1d2adede107311 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 03/53] feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now. --- AGENTS.template.md | 2 +- implementations/Crafter.Build-Clang.cpp | 40 +++++++++++--- implementations/Crafter.Build-Platform.cpp | 5 +- implementations/Crafter.Build-Test.cpp | 2 + implementations/Crafter.Build-Toolchain.cpp | 42 +++++++++++++++ interfaces/Crafter.Build-Clang.cppm | 41 ++++++++++++-- interfaces/Crafter.Build-Toolchain.cppm | 24 +++++++++ tests/StandardArgs/main.cpp | 26 +++++++++ tests/ToolchainResolve/main.cpp | 59 +++++++++++++++++++++ tests/VariantId/main.cpp | 36 +++++++++++++ 10 files changed, 262 insertions(+), 15 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index 2a93992..6a8ea07 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -122,7 +122,7 @@ Beyond the rules: - There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. - Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. -- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`) and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. +- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. ## Design rules diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 20567d6..e7e04a1 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -1145,7 +1145,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath))) { const Toolchain& toolchain = GetToolchain(); if (toolchain.nvcc.empty()) { @@ -1155,11 +1156,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map& seen, bool linked = true) { + if (!seen.insert(&config).second) return false; + if (linked && !config.cuda.empty() && config.cudaArch == "native") return true; + return std::ranges::any_of(config.dependencies, [&seen](const Configuration* dep) { return HasNativeCuda(*dep, seen, dep->type != ConfigurationType::Executable); }); + } +} + std::string Crafter::BundleFlatpakApp(const Configuration& config) { if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused; const FlatpakExport app = ExportOf(config); @@ -1753,6 +1769,9 @@ std::string Crafter::BundleFlatpakApp(const Configuration& config) { if (config.march == "native") { Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string())); } + if (std::unordered_set seen; HasNativeCuda(config, seen)) { + Progress::Diagnostic(std::format("{} holds CUDA code built with --cuda-arch=native, for this machine's GPUs and with no PTX, so it may not run on another machine's GPU; for others, build with --cuda-arch=all-major", bundle.string())); + } if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string()); return ""; } @@ -2000,6 +2019,9 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span gpus; + std::error_code ec; + for (fs::directory_iterator it(in.pciDevices, ec), end; !ec && it != end; it.increment(ec)) { + const auto field = [&it](std::string_view name) { + std::string value; + std::ifstream(it->path() / name) >> value; + return value; + }; + if (field("vendor") == "0x10de" && field("class").starts_with("0x03")) gpus.push_back(std::format("{}={}", it->path().filename().string(), field("device"))); + } + std::ranges::sort(gpus); + const auto spelled = [](const std::optional& value) { return value ? std::format("={}", *value) : std::string("unset"); }; + tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder)); + } std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); return tc; } @@ -328,6 +367,9 @@ const Toolchain& Crafter::GetToolchain() { } catch (const std::exception&) {} if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" }; + in.pciDevices = "/sys/bus/pci/devices"; + if (const char* value = std::getenv("CUDA_VISIBLE_DEVICES")) in.cudaVisibleDevices = value; + if (const char* value = std::getenv("CUDA_DEVICE_ORDER")) in.cudaDeviceOrder = value; { auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO"); const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info"); diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index 19a7047..d8b8901 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -504,6 +504,16 @@ export namespace Crafter { std::vector implementations; std::vector cFiles; std::vector cuda; + // The GPU architecture nvcc compiles `cuda` for, as its -arch takes + // one. "native", the default, compiles for the GPUs of the machine + // that builds, as march's default does for its CPU; with none to be + // seen, nvcc warns and uses its own default. Like -march=native it is + // for a program that runs where it is built: it carries no PTX, which + // a newer GPU could compile when it loads the program. "sm_89" is one + // architecture with its PTX; "all-major" or "all" is for a program + // that runs elsewhere. ApplyStandardArgs sets it from + // CRAFTER_BUILD_CUDA_ARCH and --cuda-arch=. + std::string cudaArch = "native"; std::vector dependencies; std::vector files; // Build-time-only source files this configuration exposes to its own @@ -593,9 +603,9 @@ export namespace Crafter { void ResolvePendingImports(); // Declare a test. Sources default to `tests//main.cpp` resolved // against this Configuration's path; target/march/mtune/sysroot/debug - // are inherited from this Configuration so cross-arch projects don't - // have to re-specify. Returns a builder for chaining defines, deps, - // etc. Defined in Crafter.Build:Test. + // and cudaArch are inherited from this Configuration so cross-arch + // projects don't have to re-specify. Returns a builder for chaining + // defines, deps, etc. Defined in Crafter.Build:Test. struct TestBuilder AddTest(std::string_view name); // Same as AddTest, but compiles the parent's `interfaces` directly // into this test's Configuration (rather than going through a dep). @@ -625,7 +635,7 @@ export namespace Crafter { // Suffix that uniquely identifies this Configuration's compile state. // target+march+mtune are spelled out for readability; the rest // (type, debug, sysroot, defines, compileFlags, the std module, the - // toolchain) + // toolchain, the GPU architecture and the nvcc of CUDA sources) // collapse into a short hash so two Configurations sharing a path but // with different compile state can't clobber each other's outputs. std::string VariantId() const { return VariantId(GetToolchain()); } @@ -690,6 +700,25 @@ export namespace Crafter { } compileKey += "|T:"; compileKey += toolchain.Key(); + // The GPU architecture decides what a .cu compiles into, and so + // does the toolkit whose nvcc compiles it, which CUDA_PATH can + // switch and an update can replace at the same path, so the nvcc + // is keyed by what it is (Toolchain::nvccStamp), and native by the + // GPUs it resolves to (Toolchain::cudaNativeKey). None of them + // need touch the files whose times decide whether a .cu is + // compiled again, so each needs a directory of its own. Only keyed + // with CUDA sources, so every other configuration keeps the + // directory it had. + if (!cuda.empty()) { + compileKey += "|C:"; + compileKey += cudaArch; + compileKey += '|'; + compileKey += toolchain.nvccStamp; + if (cudaArch == "native") { + compileKey += '|'; + compileKey += toolchain.cudaNativeKey; + } + } // A Flatpak lays its bin dir out unlike the executable as linked, // so the two never share one. Only keyed for a Flatpak, so every // other configuration keeps the directory it had. @@ -867,6 +896,7 @@ export namespace Crafter { // --target= cfg.target = // --march= cfg.march = // --mtune= cfg.mtune = + // --cuda-arch= cfg.cudaArch = // --lib cfg.type promoted Executable → LibraryStatic // --shared cfg.type promoted LibraryStatic → LibraryDynamic // --packaging= cfg.packaging = None or Flatpak (none, flatpak), @@ -878,7 +908,8 @@ export namespace Crafter { // LibraryDynamic regardless of arg order; each is a no-op when the // baseline doesn't match (e.g. --shared on an Executable, or --lib on a // pre-set library). - // $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE seed march/mtune. + // $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE / $CRAFTER_BUILD_CUDA_ARCH + // seed march/mtune/cudaArch. // Env applies first, then args, so CLI wins over env wins over caller's // pre-set defaults. Returns an ArgQuery over the same span so projects // can query their own flags (`--timing`, ...) without re-rolling the diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 604f6d1..e3bb39b 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -67,6 +67,17 @@ export namespace Crafter { // for want of a CUDA toolkit. fs::path nvcc; std::string nvccError; + // What that nvcc is, for VariantId: its canonical path, size and + // modification time, which change when the toolkit is updated or + // replaced at the same path, as the path alone does not. Empty + // without an nvcc. + std::string nvccStamp; + // What -arch=native compiles for on this machine, for VariantId: the + // NVIDIA display devices the PCI bus lists, by address and device ID, + // and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose among + // them and number them, each unset apart from empty. Empty without an + // nvcc. + std::string cudaNativeKey; // The Flatpak runtime crafter-build runs on, from the // runtime=runtime/// line of /.flatpak-info: // "x86_64" and "26.08" in the Flatpak, both empty outside one. A @@ -125,6 +136,19 @@ export namespace Crafter { // order they are tried and as the host names them: GetToolchain() // passes /opt/cuda, Arch's, and /usr/local/cuda, NVIDIA's installers'. std::vector cudaRoots; + // The PCI devices sysfs lists, one directory each with its vendor, + // device and class: GetToolchain() passes /sys/bus/pci/devices, which + // the sandbox shows too. What -arch=native compiles for is keyed by + // the NVIDIA display devices among them. + fs::path pciDevices; + // CUDA_VISIBLE_DEVICES, which chooses the GPUs -arch=native compiles + // for, when it is set: set but empty hides them all, which is not the + // same as unset, so it is kept apart from env, which holds non-empty + // values alone. + std::optional cudaVisibleDevices; + // CUDA_DEVICE_ORDER, when it is set: it decides which GPU a number in + // CUDA_VISIBLE_DEVICES means, by PCI address or by speed. + std::optional cudaDeviceOrder; }; // Pure path resolution: an env override wins, then a toolchain installed // beside crafter-build (/bin/clang++), then bare names on diff --git a/tests/StandardArgs/main.cpp b/tests/StandardArgs/main.cpp index 3a21241..e7d6d25 100644 --- a/tests/StandardArgs/main.cpp +++ b/tests/StandardArgs/main.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +#include import std; import Crafter.Build; using namespace Crafter; @@ -33,6 +34,31 @@ int main() { Check(cfg.mtune == "cortex-a72", "--mtune= should overwrite cfg.mtune"); } + // --cuda-arch= is nvcc's -arch for cfg.cuda, as --march= is the CPU's, + // and it defaults to native as march does. + { + Configuration plain; + Check(plain.cudaArch == "native", "the GPU architecture defaults to native, like march"); + Configuration cfg; + std::array raw = { "--cuda-arch=all-major" }; + ApplyStandardArgs(cfg, raw); + Check(cfg.cudaArch == "all-major", "--cuda-arch= sets cfg.cudaArch"); + Check(cfg.projectArgs.empty(), "--cuda-arch= is not a project arg"); + } + { + // CRAFTER_BUILD_CUDA_ARCH sets it as CRAFTER_BUILD_MARCH sets march, + // and the command line wins over it. + setenv("CRAFTER_BUILD_CUDA_ARCH", "sm_86", 1); + Configuration fromEnv; + ApplyStandardArgs(fromEnv, {}); + Check(fromEnv.cudaArch == "sm_86", "CRAFTER_BUILD_CUDA_ARCH sets cfg.cudaArch"); + Configuration both; + std::array raw = { "--cuda-arch=sm_120" }; + ApplyStandardArgs(both, raw); + Check(both.cudaArch == "sm_120", "--cuda-arch= wins over CRAFTER_BUILD_CUDA_ARCH"); + unsetenv("CRAFTER_BUILD_CUDA_ARCH"); + } + // --sysroot= sets cfg.sysroot (cross-compiles against a foreign root, // e.g. an Alpine aarch64 tree; also picked up by the std.cppm lookup // and the qemu test-runner's QEMU_LD_PREFIX). diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index 849c36a..6ab8186 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -302,6 +302,65 @@ int main() { Check(ResolveToolchain(in).nvcc.empty(), "a link to itself ends, and finds nothing"); fs::remove_all(host); } + { + // What VariantId keys a CUDA configuration's nvcc by: its canonical + // path, size and time, which an nvcc replaced at its path changes, + // as it does not change the path. + const fs::path toolkit = scratch / "stamped"; + Program(toolkit / "bin/nvcc"); + ToolchainInputs in; + in.env["CUDA_PATH"] = toolkit.string(); + const std::string before = ResolveToolchain(in).nvccStamp; + Check(before.starts_with(std::format("{}|", fs::canonical(toolkit / "bin/nvcc").string())), std::format("the stamp names the nvcc where its links lead (got '{}')", before)); + std::ofstream(toolkit / "bin/nvcc", std::ios::app) << "13.5"; + Check(ResolveToolchain(in).nvccStamp != before, "an nvcc replaced at its path stamps differently"); + Check(ResolveToolchain({}).nvccStamp.empty(), "no nvcc, no stamp"); + } + { + // What VariantId keys -arch=native by: the NVIDIA display devices the + // PCI bus lists, by slot and model, and CUDA_VISIBLE_DEVICES and + // CUDA_DEVICE_ORDER. Another GPU, the same GPUs in each other's slots, + // or another choice or numbering among them keys it differently; a + // GPU's audio function, another NVIDIA class, and another vendor's GPU + // do not count. + const fs::path toolkit = scratch / "native/toolkit"; + Program(toolkit / "bin/nvcc"); + const fs::path pci = scratch / "native/pci"; + const auto device = [&pci](std::string_view address, std::string_view vendor, std::string_view id, std::string_view type) { + fs::create_directories(pci / address); + std::ofstream(pci / address / "vendor") << vendor << "\n"; + std::ofstream(pci / address / "device") << id << "\n"; + std::ofstream(pci / address / "class") << type << "\n"; + }; + device("0000:34:00.0", "0x10de", "0x2684", "0x030000"); + device("0000:34:00.1", "0x10de", "0x22ba", "0x040300"); + device("0000:00:02.0", "0x8086", "0xa780", "0x030000"); + ToolchainInputs in; + in.env["CUDA_PATH"] = toolkit.string(); + in.pciDevices = pci; + const std::string one = ResolveToolchain(in).cudaNativeKey; + Check(one.contains("0x2684") && !one.contains("0x22ba") && !one.contains("0xa780"), std::format("native is keyed by the NVIDIA display devices alone (got '{}')", one)); + device("0000:ca:00.0", "0x10de", "0x2b85", "0x030200"); + const std::string two = ResolveToolchain(in).cudaNativeKey; + Check(two != one && two.contains("0x2b85"), std::format("another GPU keys it differently (got '{}')", two)); + in.cudaVisibleDevices = "1"; + const std::string chosen = ResolveToolchain(in).cudaNativeKey; + Check(chosen != two, "and so does CUDA_VISIBLE_DEVICES"); + in.cudaVisibleDevices = ""; + const std::string hidden = ResolveToolchain(in).cudaNativeKey; + Check(hidden != two && hidden != chosen, std::format("an empty CUDA_VISIBLE_DEVICES, which hides every GPU, keys apart from an unset one (got '{}')", hidden)); + in.cudaVisibleDevices.reset(); + Check(ResolveToolchain(in).cudaNativeKey == two, "unset again, the key is as it was"); + in.cudaDeviceOrder = "PCI_BUS_ID"; + Check(ResolveToolchain(in).cudaNativeKey != two, "CUDA_DEVICE_ORDER, which numbers the GPUs, keys it differently"); + in.cudaDeviceOrder.reset(); + device("0000:34:00.0", "0x10de", "0x2b85", "0x030200"); + device("0000:ca:00.0", "0x10de", "0x2684", "0x030000"); + const std::string swapped = ResolveToolchain(in).cudaNativeKey; + Check(swapped != two, std::format("so do the same GPUs in each other's slots (got '{}')", swapped)); + in.env.erase("CUDA_PATH"); + Check(ResolveToolchain(in).cudaNativeKey.empty(), "no nvcc, no key"); + } { // The cache key separates toolchains that would build different // PCMs and nothing else. diff --git a/tests/VariantId/main.cpp b/tests/VariantId/main.cpp index 0fc170c..11ab9ff 100644 --- a/tests/VariantId/main.cpp +++ b/tests/VariantId/main.cpp @@ -128,6 +128,42 @@ int main() { b.march = "x86-64-v3"; Check(a.VariantId() != b.VariantId(), "march change perturbs VariantId"); } + { + // The GPU architecture decides what a .cu compiles into, and it need + // not touch the files whose times decide whether a .cu is compiled + // again, so it keys the directory of a configuration with CUDA + // sources, and only of one. + Configuration a = MakeBase(); + a.cuda = { "/tmp/variant-id-test/kernel" }; + Configuration b = MakeBase(); + b.cuda = a.cuda; + b.cudaArch = "sm_89"; + Check(a.VariantId() != b.VariantId(), "cudaArch change perturbs the VariantId of a configuration with CUDA sources"); + Configuration c = MakeBase(); + Configuration d = MakeBase(); + d.cudaArch = "sm_89"; + Check(c.VariantId() == d.VariantId(), "without CUDA sources, cudaArch leaves VariantId alone"); + // So does the nvcc that compiles them, by what it is: CUDA_PATH can + // name another toolkit, and an update can replace one at its path, + // and the old one's objects must not pass for the new one's. + const Toolchain one = GetToolchain(); + Toolchain other = one; + other.nvccStamp = "/opt/other-cuda/bin/nvcc|1|1"; + Toolchain updated = other; + updated.nvccStamp = "/opt/other-cuda/bin/nvcc|2|2"; + Check(a.VariantId(one) != a.VariantId(other), "another nvcc perturbs the VariantId of a configuration with CUDA sources"); + Check(a.VariantId(other) != a.VariantId(updated), "so does an nvcc updated at the same path"); + Check(c.VariantId(one) == c.VariantId(other), "without CUDA sources, the nvcc leaves VariantId alone"); + // native is what nvcc finds on the machine, so the GPUs it finds key + // it as well, and only it. + Toolchain first = one; + first.cudaNativeKey = "0x2684|"; + Toolchain swapped = one; + swapped.cudaNativeKey = "0x2b85|"; + Check(a.VariantId(first) != a.VariantId(swapped), "another GPU perturbs the VariantId of a configuration with CUDA sources for native"); + Check(b.VariantId(first) == b.VariantId(swapped), "but not for a named architecture"); + Check(c.VariantId(first) == c.VariantId(swapped), "nor without CUDA sources"); + } { // A project flag the framework can't interpret still decides what gets // compiled and bundled, so it has to key into VariantId. Otherwise both From ad021ee652c514ea08b0a2f8b5bcc20ea402d7ce Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 04/53] test(cuda): build a .cu with the toolkit CUDA_PATH names, and with none CudaCompile puts an nvcc on PATH that fails, names a toolkit through CUDA_PATH whose nvcc writes down its arguments and runs the real one, and builds an executable from a C++ unit and a .cu: with the default architecture, then with another one, which compiles the unchanged .cu again in a directory of its own, then with nothing changed, which compiles nothing. With the bare "nvcc" of before, the first build runs the nvcc on PATH and fails. It needs a real toolkit, which it looks for as crafter-build does, with ResolveToolchain and the inputs GetToolchain() gives it, and it skips without one. Nothing in CI installs one, so AGENTS.template.md says to run it in the native loop. CudaMissing needs none, so CI runs it: with CUDA_PATH naming an empty directory, a build with a .cu fails with "cannot compile kernel.cu: no nvcc at /bin/nvcc (CUDA_PATH)", and a build without CUDA sources in the same process still succeeds. With the bare "nvcc" of before, that build ran whatever nvcc PATH held, and where PATH held none, as in the Flatpak, failed with "sh: line 1: nvcc: command not found". AGENTS.template.md names it beside CudaCompile. --- AGENTS.template.md | 1 + project.cpp | 2 + tests/CudaCompile/fixture/kernel.cu | 20 +++++ tests/CudaCompile/fixture/main.cpp | 13 +++ tests/CudaCompile/main.cpp | 129 ++++++++++++++++++++++++++++ tests/CudaMissing/fixture/kernel.cu | 5 ++ tests/CudaMissing/fixture/main.cpp | 8 ++ tests/CudaMissing/main.cpp | 73 ++++++++++++++++ 8 files changed, 251 insertions(+) create mode 100644 tests/CudaCompile/fixture/kernel.cu create mode 100644 tests/CudaCompile/fixture/main.cpp create mode 100644 tests/CudaCompile/main.cpp create mode 100644 tests/CudaMissing/fixture/kernel.cu create mode 100644 tests/CudaMissing/fixture/main.cpp create mode 100644 tests/CudaMissing/main.cpp diff --git a/AGENTS.template.md b/AGENTS.template.md index 6a8ea07..a98a37d 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -207,5 +207,6 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`. - The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib//eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`. - `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`. +- `CudaCompile` builds with a real CUDA toolkit and skips where there is none, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, run it in the native loop on a machine with a toolkit. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either. - `VariantId()` names the output directory, so CI globs `bin/crafter.build-exe---*/` rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay in `bin/` and `build/` until `clean`, and such a glob matches both. - AGENTS.md is build output: the self-host build and `test` write it from `AGENTS.template.md`, with the `AGENTS.consumer.md` of each dependency that ships one (Crafter.Math, today) merged in, and it is gitignored. Edit the template; an edit made in AGENTS.md is gone after the next build. A fresh clone or worktree has no AGENTS.md until its first `./bin/crafter-build` or `test`, since `./build.sh` does not write it. A harness from before the template (3.0.0 and older) never creates one and keeps its section in one it finds; the next build with a current harness writes it over. diff --git a/project.cpp b/project.cpp index dd7112f..cd1e206 100644 --- a/project.cpp +++ b/project.cpp @@ -260,6 +260,8 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("ShaderCompile").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderVariantBuild").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderIncludeChange").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("CudaCompile").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("CudaMissing").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("MingwMissing").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("MingwSysroot").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("GitSubmodules").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/CudaCompile/fixture/kernel.cu b/tests/CudaCompile/fixture/kernel.cu new file mode 100644 index 0000000..8faa343 --- /dev/null +++ b/tests/CudaCompile/fixture/kernel.cu @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +#include + +__global__ void Double(float* values, std::int32_t count) { + const std::int32_t i = static_cast(blockIdx.x * blockDim.x + threadIdx.x); + if (i < count) values[i] = 2.0f * static_cast(i); +} + +extern "C" std::int32_t LaunchDouble(std::int32_t count, float* values) { + float* device = nullptr; + cudaError_t status = cudaMalloc(&device, sizeof(float) * count); + if (status != cudaSuccess) return status; + Double<<<1, 32>>>(device, count); + status = cudaMemcpy(values, device, sizeof(float) * count, cudaMemcpyDeviceToHost); + cudaFree(device); + return status; +} diff --git a/tests/CudaCompile/fixture/main.cpp b/tests/CudaCompile/fixture/main.cpp new file mode 100644 index 0000000..e1c3a7a --- /dev/null +++ b/tests/CudaCompile/fixture/main.cpp @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +// In kernel.cu: doubles every index into `values` on the GPU, and returns +// cudaSuccess (0) or the CUDA error. +extern "C" std::int32_t LaunchDouble(std::int32_t count, float* values); + +int main() { + std::array values{}; + return LaunchDouble(static_cast(values.size()), values.data()); +} diff --git a/tests/CudaCompile/main.cpp b/tests/CudaCompile/main.cpp new file mode 100644 index 0000000..01b9acc --- /dev/null +++ b/tests/CudaCompile/main.cpp @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// cfg.cuda is compiled with the nvcc ResolveToolchain finds, for the GPU +// architecture cfg.cudaArch names. It used to be whatever "nvcc" meant to the +// shell, for sm_89 alone: crafter-build's Flatpak sets PATH to +// /app/bin:/usr/bin, and with that PATH every CUDA build there stopped at +// "nvcc: command not found" with the host's toolkit in reach at /opt/cuda. +// +// The test puts an nvcc on PATH that fails, names a toolkit through CUDA_PATH +// whose nvcc writes down its arguments and runs the real one, and builds an +// executable from a C++ unit and a .cu: with the default architecture, which +// is native, then with another one, which compiles the unchanged .cu again in +// a directory of its own, then once more with nothing changed, which compiles +// nothing. Where nvcc is looked for is ToolchainResolve's to check; this is +// the build that uses it. Skips without a CUDA toolkit, which CI does not +// have. +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // The nvcc crafter-build finds in this environment, looked for with the + // inputs GetToolchain() gives ResolveToolchain, the host's /usr under + // /run/host in a sandbox included, before the test changes CUDA_PATH and + // PATH. ResolveToolchain is pure: GetToolchain()'s cache stays empty. + Toolchain RealToolkit() { + ToolchainInputs in; + for (const std::string_view name : {"CUDA_PATH", "PATH"}) { + if (const char* value = std::getenv(std::string(name).c_str()); value && *value) in.env.emplace(std::string(name), value); + } + if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; + in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" }; + return ResolveToolchain(in); + } + + void WriteProgram(const fs::path& file, std::string_view text) { + fs::create_directories(file.parent_path()); + std::ofstream(file) << text; + fs::permissions(file, fs::perms::owner_exec, fs::perm_options::add); + } + + std::vector Lines(const fs::path& file) { + std::vector lines; + std::ifstream in(file); + for (std::string line; std::getline(in, line);) lines.push_back(line); + return lines; + } + + std::string Joined(const std::vector& lines) { + return std::views::join_with(lines, std::string(" | ")) | std::ranges::to(); + } +} + +int main() { + const Toolchain real = RealToolkit(); + if (real.nvcc.empty()) { + std::println("SKIP: {}", real.nvccError); + return 77; + } + const fs::path nvcc = real.nvcc; + + const fs::path scratch = fs::temp_directory_path() / "crafter-build-cuda-compile"; + std::error_code ec; + fs::remove_all(scratch, ec); + fs::create_directories(scratch); + const fs::path project = scratch / "project"; + fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", project, fs::copy_options::recursive); + + const fs::path log = scratch / "nvcc.log"; + const fs::path toolkit = scratch / "toolkit"; + WriteProgram(toolkit / "bin" / "nvcc", std::format("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nexec {} \"$@\"\n", ShellQuote(log.string()), ShellQuote(nvcc.string()))); + const fs::path decoy = scratch / "decoy"; + WriteProgram(decoy / "nvcc", "#!/bin/sh\necho 'the nvcc on PATH ran' >&2\nexit 1\n"); + // Before anything resolves the toolchain, which reads the environment + // once per process: the first Configuration does, for its target. + setenv("CUDA_PATH", toolkit.c_str(), 1); + const char* path = std::getenv("PATH"); + setenv("PATH", std::format("{}:{}", decoy.string(), path ? path : "").c_str(), 1); + + // The CUDA runtime the .cu calls into, from the real toolkit. + const std::string runtimeDir = std::format("-L{}", (nvcc.parent_path().parent_path() / "lib64").string()); + const auto build = [&](std::optional arch) { + Configuration app; + app.path = project; + app.name = "cuda"; + app.outputName = "cuda"; + app.type = ConfigurationType::Executable; + if (arch) app.cudaArch = *arch; + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + app.cuda = { project / "kernel" }; + app.linkFlags = { runtimeDir, "-lcudart" }; + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult result = Build(app, depResults, depMutex); + return std::pair{ result.result, app.BinDir() / "cuda" }; + }; + + const auto [native, nativeBinary] = build(std::nullopt); + Check(native.empty(), std::format("the build with the default architecture succeeds: {}", native)); + Check(fs::exists(nativeBinary), "it links the executable"); + std::vector runs = Lines(log); + Check(runs.size() == 1 && runs.front().contains("-arch=native"), std::format("CUDA_PATH's nvcc compiles the .cu once, with -arch=native (ran: {})", Joined(runs))); + + const auto [other, otherBinary] = build("sm_86"); + Check(other.empty(), std::format("the build for sm_86 succeeds: {}", other)); + runs = Lines(log); + Check(runs.size() == 2 && runs.back().contains("-arch=sm_86"), std::format("another architecture compiles the unchanged .cu again, for it (ran: {})", Joined(runs))); + Check(fs::exists(otherBinary) && otherBinary.parent_path() != nativeBinary.parent_path(), "in a directory of its own"); + + const auto [again, againBinary] = build("sm_86"); + Check(again.empty() && Lines(log).size() == 2, std::format("an unchanged build compiles nothing (ran: {})", Joined(Lines(log)))); + + fs::remove_all(scratch, ec); + return Failures == 0 ? 0 : 1; +} diff --git a/tests/CudaMissing/fixture/kernel.cu b/tests/CudaMissing/fixture/kernel.cu new file mode 100644 index 0000000..84c3e03 --- /dev/null +++ b/tests/CudaMissing/fixture/kernel.cu @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Never compiled: CudaMissing's CUDA_PATH names a directory without an nvcc. +__global__ void Kernel() {} diff --git a/tests/CudaMissing/fixture/main.cpp b/tests/CudaMissing/fixture/main.cpp new file mode 100644 index 0000000..ef53493 --- /dev/null +++ b/tests/CudaMissing/fixture/main.cpp @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// CudaMissing's program: nothing in it needs CUDA, so it builds without an +// nvcc where its configuration has no CUDA sources. +int main() { + return 0; +} diff --git a/tests/CudaMissing/main.cpp b/tests/CudaMissing/main.cpp new file mode 100644 index 0000000..efdddd3 --- /dev/null +++ b/tests/CudaMissing/main.cpp @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A build with CUDA sources and no nvcc to compile them fails, saying where +// nvcc was looked for. It used to run a bare "nvcc" through the shell, which +// in crafter-build's Flatpak, whose PATH as its manifest sets it holds no host +// toolkit, stopped such builds at "sh: line 1: nvcc: command not found", +// naming no place to put one. CUDA_PATH names an empty directory here, so the +// test needs no CUDA toolkit and runs in CI, where CudaCompile skips: the +// build with a .cu fails naming that directory's bin/nvcc and CUDA_PATH, and a +// build without CUDA sources in the same process still succeeds, as only a .cu +// needs an nvcc. + +extern "C" int setenv(const char* name, const char* value, int overwrite); + +namespace { + std::int32_t failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++failures; + } + } + + BuildResult BuildOnce(const fs::path& project, std::string_view name, bool withCuda) { + Configuration app; + app.path = project; + app.name = name; + app.outputName = name; + app.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + if (withCuda) app.cuda = { project / "kernel" }; + std::unordered_map> depResults; + std::mutex depMutex; + return Build(app, depResults, depMutex); + } +} + +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-cuda-missing"; + fs::remove_all(scratch); + fs::create_directories(scratch); + const fs::path project = scratch / "project"; + fs::copy(fs::current_path() / "tests" / "CudaMissing" / "fixture", project, fs::copy_options::recursive); + // A toolkit directory without a bin/nvcc, named before anything resolves + // the toolchain, which reads CUDA_PATH once per process. + const fs::path toolkit = scratch / "toolkit"; + fs::create_directories(toolkit); + setenv("CUDA_PATH", toolkit.c_str(), 1); + + const BuildResult missing = BuildOnce(project, "cuda", true); + const std::string expected = std::format("cannot compile kernel.cu: no nvcc at {} (CUDA_PATH)", (toolkit.lexically_normal() / "bin" / "nvcc").string()); + Check(missing.result == expected, std::format("a build with a .cu and no nvcc fails, saying where it looked (expected '{}', got '{}')", expected, missing.result)); + + const BuildResult plain = BuildOnce(project, "plain", false); + Check(plain.result.empty(), std::format("a build without CUDA sources needs no nvcc: {}", plain.result)); + + std::error_code ec; + fs::remove_all(scratch, ec); + if (failures > 0) { + std::println(std::cerr, "{} assertions failed", failures); + return 1; + } + return 0; +} From c2338d112285381f430b7e584ae2da8b650ebde3 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 05/53] fix(cuda): rebuild a .cu when a header it includes changes A .cu was compiled again only when it was newer than its object, so one whose header changed kept the object built from the old header. The C and C++ paths ask the compiler for a depfile and check every prerequisite in it; nvcc was left out because its -MD and -MF had never been run here. They work with CUDA 13.4 as they do with clang: the depfile lists the .cu and every header it read, the toolkit's and the system's included. nvcc puts a space before the rule's colon, which NewestPrerequisite reads as a target token like any other. An object from before has no depfile and is compiled once more. --- implementations/Crafter.Build-Clang.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index e7e04a1..254a4e5 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -1142,12 +1142,14 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath))) { + // nvcc writes the depfile clang writes for a C source (-MD -MF): the + // .cu and every header it read, the toolkit's and the system's among + // them, as a Make rule NewestPrerequisite reads as it reads clang's, + // although nvcc puts a space before the colon. Without it, a .cu + // whose header changed kept its old object. cfg.cudaArch needs no + // check: it is part of VariantId, so another one builds in another + // directory. + if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { const Toolchain& toolchain = GetToolchain(); if (toolchain.nvcc.empty()) { bool expected = false; @@ -1160,7 +1162,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 06/53] test(cuda): a changed header compiles the .cu again CudaCompile's .cu includes a header of its own now. After the unchanged build, the test makes the header newer than the object and builds once more, which has to run nvcc again. Before nvcc wrote a depfile, it did not, and the object built from the old header stayed. --- tests/CudaCompile/fixture/kernel.cu | 3 ++- tests/CudaCompile/fixture/kernel.h | 8 ++++++++ tests/CudaCompile/main.cpp | 14 +++++++++++--- 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 tests/CudaCompile/fixture/kernel.h diff --git a/tests/CudaCompile/fixture/kernel.cu b/tests/CudaCompile/fixture/kernel.cu index 8faa343..a1b299f 100644 --- a/tests/CudaCompile/fixture/kernel.cu +++ b/tests/CudaCompile/fixture/kernel.cu @@ -1,12 +1,13 @@ // SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +#include "kernel.h" #include #include __global__ void Double(float* values, std::int32_t count) { const std::int32_t i = static_cast(blockIdx.x * blockDim.x + threadIdx.x); - if (i < count) values[i] = 2.0f * static_cast(i); + if (i < count) values[i] = Factor * static_cast(i); } extern "C" std::int32_t LaunchDouble(std::int32_t count, float* values) { diff --git a/tests/CudaCompile/fixture/kernel.h b/tests/CudaCompile/fixture/kernel.h new file mode 100644 index 0000000..1ce22df --- /dev/null +++ b/tests/CudaCompile/fixture/kernel.h @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#pragma once + +// What kernel.cu multiplies every index by: a header of the .cu's own, which +// the test makes newer than the object built from it. +constexpr float Factor = 2.0f; diff --git a/tests/CudaCompile/main.cpp b/tests/CudaCompile/main.cpp index 01b9acc..bfc6374 100644 --- a/tests/CudaCompile/main.cpp +++ b/tests/CudaCompile/main.cpp @@ -18,9 +18,11 @@ using namespace Crafter; // executable from a C++ unit and a .cu: with the default architecture, which // is native, then with another one, which compiles the unchanged .cu again in // a directory of its own, then once more with nothing changed, which compiles -// nothing. Where nvcc is looked for is ToolchainResolve's to check; this is -// the build that uses it. Skips without a CUDA toolkit, which CI does not -// have. +// nothing, and once its header is newer than its object, which compiles it +// again: nvcc's depfile is the record of what the .cu includes, and before +// nvcc wrote one, a changed header left the old object in place. Where nvcc +// is looked for is ToolchainResolve's to check; this is the build that uses +// it. Skips without a CUDA toolkit, which CI does not have. namespace { std::int32_t Failures = 0; @@ -124,6 +126,12 @@ int main() { const auto [again, againBinary] = build("sm_86"); Check(again.empty() && Lines(log).size() == 2, std::format("an unchanged build compiles nothing (ran: {})", Joined(Lines(log)))); + fs::last_write_time(project / "kernel.h", fs::file_time_type::clock::now()); + const auto [touched, touchedBinary] = build("sm_86"); + Check(touched.empty(), std::format("the build after the header changed succeeds: {}", touched)); + runs = Lines(log); + Check(runs.size() == 3 && runs.back().contains("-arch=sm_86"), std::format("a changed header compiles the .cu again (ran: {})", Joined(runs))); + fs::remove_all(scratch, ec); return Failures == 0 ? 0 : 1; } From 22ea97406dbbafe066c90886b3f9f63c125a3e35 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 07/53] feat(cuda): link the CUDA runtime of the toolkit that compiles the .cu A program with CUDA sources needs the CUDA runtime, which cfg.linkFlags had to name: -L/opt/cuda/lib64 -lcudart for Arch's toolkit, a path into it. In the Flatpak that holds for /opt/cuda but not for the host's /usr/local/cuda, which is under /run/host there, at a path crafter-build resolves for nvcc and a project.cpp does not know. Jorijn chose to have crafter-build link it. A configuration with CUDA sources links the static runtime of the toolkit whose nvcc compiles them, by its path, with the -lrt -lpthread -ldl that nvcc's own link line puts after it. ResolveToolchain finds it with nvcc, as Toolchain::cudaRuntime: libcudart_static.a in the lib64 beside nvcc's bin, looked for without starting a process, so a test can stage a toolkit for it as for nvcc, and crafter-build --version prints it. The static one, so no run path into the toolkit ends up in the program; libcuda.so.1, which the runtime loads, comes with the driver. By its path, not through a -L of the lib64, which would put the toolkit's libraries, such as Arch's libcheckpoint.so, in the way of a project's own of the same name. It goes into BuildResult::runtimeLibs, which a configuration hands its consumers as it does libs and every link puts after them, so whatever is built on a library with CUDA sources links the runtime too, and a -lcudart a project names itself comes first. Where that lib64 holds none, as where a distribution keeps the toolkit's libraries in its own directories, cudaRuntime is empty and nothing is linked, as before: a -lcudart_static the linker could not find would fail the link even of a project that names its own -lcudart. The archive is looked for without throwing, so a lib64 that cannot be looked into, through a link loop or for want of permission, counts as one without it. --- AGENTS.template.md | 2 +- implementations/Crafter.Build-Clang.cpp | 30 +++++++++++++++++++-- implementations/Crafter.Build-Platform.cpp | 12 ++++++--- implementations/Crafter.Build-Toolchain.cpp | 8 ++++++ interfaces/Crafter.Build-Clang.cppm | 7 +++++ interfaces/Crafter.Build-Toolchain.cppm | 6 +++++ 6 files changed, 58 insertions(+), 7 deletions(-) diff --git a/AGENTS.template.md b/AGENTS.template.md index a98a37d..941ff27 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -23,7 +23,7 @@ crafter-build is a C++26 modules build system. A project is described by a `proj Partitions and what they own: -- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. +- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. - `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. - `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code. - `:Interface` and `:Implementation` model module units, their staleness checks and their compiles. diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 254a4e5..7ca09c0 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -1054,6 +1054,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map libSet; + std::set runtimeSet; std::set publicFlagSet; std::set runPathSet; std::mutex fileMutex; @@ -1070,6 +1071,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map configs; std::string compileFlags; // " -fprebuilt-module-path=…" for each dependency and its transitive deps - // Every dependency's BuildResult.libs, verbatim, then a run path per - // directory of its runPaths (RunPathFlags), as Build() links a - // program: the shared libraries a pragma dependency is built on are - // found there when LoadProject dlopens project.so. + // Every dependency's BuildResult.libs, verbatim, then its runtimeLibs, + // the CUDA runtime, then a run path per directory of its runPaths + // (RunPathFlags), as Build() links a program: the shared libraries a + // pragma dependency is built on are found there when LoadProject + // dlopens project.so. std::string linkFlags; fs::file_time_type newestArtifact = fs::file_time_type::min(); }; @@ -529,6 +530,7 @@ namespace { std::unordered_set forced; std::unordered_set walked; std::set libs; + std::set runtimeLibs; std::set runPaths; for (const PragmaDependency& pragma : pragmas) { @@ -574,6 +576,7 @@ namespace { if (!built.result.empty()) PragmaError(absProject, pragma.line, std::format("project dependency '{}' failed to build: {}", cfg->name, built.result)); out.configs.push_back(cfg); libs.insert(built.libs.begin(), built.libs.end()); + runtimeLibs.insert(built.runtimeLibs.begin(), built.runtimeLibs.end()); runPaths.insert(built.runPaths.begin(), built.runPaths.end()); // The module path needs the dependency and everything it depends @@ -590,6 +593,7 @@ namespace { walk(cfg); } for (const std::string& lib : libs) out.linkFlags += std::format(" {}", lib); + for (const std::string& lib : runtimeLibs) out.linkFlags += std::format(" {}", lib); for (const std::string& dir : runPaths) out.linkFlags += RunPathFlags(dir); return out; } diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index f8fb9e2..5714b3f 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -348,6 +348,14 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { const auto spelled = [](const std::optional& value) { return value ? std::format("={}", *value) : std::string("unset"); }; tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder)); } + // The static runtime beside that nvcc, for the link of a configuration + // with CUDA sources. Looked for without throwing: a lib64 that cannot be + // looked into, through a link loop or for want of permission, counts as + // one without it. + if (!tc.nvcc.empty()) { + const fs::path archive = tc.nvcc.parent_path().parent_path() / "lib64" / "libcudart_static.a"; + if (std::error_code ec; fs::exists(archive, ec)) tc.cudaRuntime = archive; + } std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); return tc; } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index d8b8901..c253079 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -49,6 +49,13 @@ export namespace Crafter { // recorded last time, so they come out the same however the // dependency threads that fill them happen to finish. std::set libs; + // The CUDA runtime that a configuration with CUDA sources, or one it + // is built on, links: Toolchain::cudaRuntime by its path and the -lrt + // -lpthread -ldl it needs, or nothing where the toolkit has none. By + // its path, so no directory of the toolkit's is searched for a + // project's own libraries; after libs on every link, so a -lcudart a + // project names itself is the one the linker takes. + std::set runtimeLibs; // Compile flags (typically -I include paths) the dep wants its // consumers to see — sourced from its external dependencies' include // dirs so headers a dep exposes in its public modules are reachable diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index e3bb39b..606de15 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -78,6 +78,12 @@ export namespace Crafter { // them and number them, each unset apart from empty. Empty without an // nvcc. std::string cudaNativeKey; + // The static CUDA runtime a configuration with CUDA sources links: + // libcudart_static.a in the lib64 beside nvcc's bin. Empty without an + // nvcc, and where that lib64 holds none, as where a distribution keeps + // the toolkit's libraries in its own directories, or cannot be looked + // into: then nothing is linked, and cfg.linkFlags names the runtime. + fs::path cudaRuntime; // The Flatpak runtime crafter-build runs on, from the // runtime=runtime/// line of /.flatpak-info: // "x86_64" and "26.08" in the Flatpak, both empty outside one. A From 99653194ba9679fbf05ba1deb063c4e587fed9d4 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 08/53] test(cuda): build a .cu without link flags, and through a library CudaCompile's builds name no CUDA library now, but for the last. The toolkit it names through CUDA_PATH has a lib64 beside its nvcc with the real toolkit's libcudart_static.a, so the executable links only if crafter-build links the runtime, and the recorded link names that archive. Another build puts the .cu in a static library and the C++ unit in an executable built on it, which links only if the library hands the runtime on. That lib64 also holds a libcheckpoint.so and a libm.so that are no libraries, as Arch's lib64 holds a real libcheckpoint.so and a libOpenCL.so: another build links an executable with CUDA sources on a library of the project's named checkpoint, and clang++ adds -lm to every C++ link, so a link that searched the toolkit's lib64 would stop on one of them wherever its -L stood. The last names -L -lcudart, as a project with CUDA sources had to, and has that -lcudart ahead of the static archive, so the shared runtime is the one the linker takes. The test skips where the real toolkit's lib64 holds no static runtime, since crafter-build then links none. Before crafter-build linked the runtime, the link failed on an undefined CUDA runtime symbol. ToolchainResolve checks where the runtime is looked for, on staged toolkits, so that it runs in CI: the archive in the lib64 beside nvcc's bin, none where that lib64 holds none, none where it links to itself, which a look that threw would have stopped the test on, and none without an nvcc. CudaCompile is the only check of the runtime link itself, and it skips without such a toolkit, so AGENTS.template.md's note on when to run it names the link as well as the compile, and gives the lookup to ToolchainResolve. --- AGENTS.template.md | 2 +- tests/CudaCompile/fixture/checkpoint.cpp | 9 ++ tests/CudaCompile/main.cpp | 162 ++++++++++++++++++++--- tests/ToolchainResolve/main.cpp | 24 ++++ 4 files changed, 179 insertions(+), 18 deletions(-) create mode 100644 tests/CudaCompile/fixture/checkpoint.cpp diff --git a/AGENTS.template.md b/AGENTS.template.md index 941ff27..a99827a 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -207,6 +207,6 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`. - The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib//eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`. - `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`. -- `CudaCompile` builds with a real CUDA toolkit and skips where there is none, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, run it in the native loop on a machine with a toolkit. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either. +- `CudaCompile` builds with a real CUDA toolkit whose `lib64` beside `bin/nvcc` holds `libcudart_static.a`, and skips everywhere else, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, or how the CUDA runtime is linked and handed on through `BuildResult::runtimeLibs`, run it in the native loop on a machine with such a toolkit, as Arch's `/opt/cuda` is. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere, and so is whether the `lib64` beside it holds the static runtime. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either. - `VariantId()` names the output directory, so CI globs `bin/crafter.build-exe---*/` rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay in `bin/` and `build/` until `clean`, and such a glob matches both. - AGENTS.md is build output: the self-host build and `test` write it from `AGENTS.template.md`, with the `AGENTS.consumer.md` of each dependency that ships one (Crafter.Math, today) merged in, and it is gitignored. Edit the template; an edit made in AGENTS.md is gone after the next build. A fresh clone or worktree has no AGENTS.md until its first `./bin/crafter-build` or `test`, since `./build.sh` does not write it. A harness from before the template (3.0.0 and older) never creates one and keeps its section in one it finds; the next build with a current harness writes it over. diff --git a/tests/CudaCompile/fixture/checkpoint.cpp b/tests/CudaCompile/fixture/checkpoint.cpp new file mode 100644 index 0000000..ec756da --- /dev/null +++ b/tests/CudaCompile/fixture/checkpoint.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// A library of the project's own, named like one a CUDA toolkit's lib64 +// can hold (Arch's holds a libcheckpoint.so): CudaCompile checks that the +// link takes this one. +extern "C" int SaveCheckpoint() { + return 0; +} diff --git a/tests/CudaCompile/main.cpp b/tests/CudaCompile/main.cpp index bfc6374..05531f9 100644 --- a/tests/CudaCompile/main.cpp +++ b/tests/CudaCompile/main.cpp @@ -20,9 +20,19 @@ using namespace Crafter; // a directory of its own, then once more with nothing changed, which compiles // nothing, and once its header is newer than its object, which compiles it // again: nvcc's depfile is the record of what the .cu includes, and before -// nvcc wrote one, a changed header left the old object in place. Where nvcc -// is looked for is ToolchainResolve's to check; this is the build that uses -// it. Skips without a CUDA toolkit, which CI does not have. +// nvcc wrote one, a changed header left the old object in place. Those builds +// name no CUDA library: the configuration links the runtime of the toolkit +// itself, the static archive in its lib64 by its path. Another build puts the +// .cu in a static library and the C++ unit in an executable built on it, which +// links only if the library hands the runtime on. That lib64 also holds a +// libcheckpoint.so and a libm.so that are no libraries, so a link that +// searched it would stop on one: an executable with CUDA sources built on a +// library of the project's named checkpoint has to take the project's, and +// clang++ adds -lm to every C++ link. A last build names the shared runtime +// itself, as a project with CUDA sources had to, and has its -lcudart ahead of +// the static archive. Where nvcc is looked for, and the runtime beside it, is +// ToolchainResolve's to check; this is the build that uses them. Skips without +// a CUDA toolkit whose lib64 holds the static runtime; CI has none. namespace { std::int32_t Failures = 0; @@ -53,6 +63,11 @@ namespace { fs::permissions(file, fs::perms::owner_exec, fs::perm_options::add); } + std::string Read(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + } + std::vector Lines(const fs::path& file) { std::vector lines; std::ifstream in(file); @@ -63,6 +78,13 @@ namespace { std::string Joined(const std::vector& lines) { return std::views::join_with(lines, std::string(" | ")) | std::ranges::to(); } + + struct Built { + std::string error; + fs::path binary; + // The link command the build recorded, beside its objects. + fs::path linkRecord; + }; } int main() { @@ -72,6 +94,14 @@ int main() { return 77; } const fs::path nvcc = real.nvcc; + // The static runtime crafter-build links, from the lib64 beside nvcc's + // bin. A toolkit without one there gets none linked, and the runtime link + // has nothing to show. + const fs::path realArchive = real.cudaRuntime; + if (realArchive.empty()) { + std::println("SKIP: no libcudart_static.a in the lib64 beside {}, so crafter-build links no CUDA runtime for this toolkit", nvcc.parent_path().string()); + return 77; + } const fs::path scratch = fs::temp_directory_path() / "crafter-build-cuda-compile"; std::error_code ec; @@ -80,9 +110,23 @@ int main() { const fs::path project = scratch / "project"; fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", project, fs::copy_options::recursive); + // The toolkit CUDA_PATH names: an nvcc that writes down how it was run and + // runs the real one, and a lib64 with the real toolkit's static runtime + // and a libcheckpoint.so and a libm.so that are no libraries at all. A + // toolkit's lib64 can hold a library named like a project's own (Arch's + // holds a libcheckpoint.so) or like one the link takes from the system (a + // libOpenCL.so), and a link that searched it would take that one: the + // libm.so stands for those, as clang++ adds -lm to every C++ link. const fs::path log = scratch / "nvcc.log"; const fs::path toolkit = scratch / "toolkit"; WriteProgram(toolkit / "bin" / "nvcc", std::format("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nexec {} \"$@\"\n", ShellQuote(log.string()), ShellQuote(nvcc.string()))); + fs::create_directories(toolkit / "lib64"); + fs::create_symlink(realArchive, toolkit / "lib64" / "libcudart_static.a"); + std::ofstream(toolkit / "lib64" / "libcheckpoint.so") << "not a library\n"; + std::ofstream(toolkit / "lib64" / "libm.so") << "not a library\n"; + // What a link names the runtime by: the archive in the toolkit's lib64, by + // its path. + const std::string runtime = (toolkit / "lib64" / "libcudart_static.a").string(); const fs::path decoy = scratch / "decoy"; WriteProgram(decoy / "nvcc", "#!/bin/sh\necho 'the nvcc on PATH ran' >&2\nexit 1\n"); // Before anything resolves the toolchain, which reads the environment @@ -91,8 +135,6 @@ int main() { const char* path = std::getenv("PATH"); setenv("PATH", std::format("{}:{}", decoy.string(), path ? path : "").c_str(), 1); - // The CUDA runtime the .cu calls into, from the real toolkit. - const std::string runtimeDir = std::format("-L{}", (nvcc.parent_path().parent_path() / "lib64").string()); const auto build = [&](std::optional arch) { Configuration app; app.path = project; @@ -104,34 +146,120 @@ int main() { std::array impls = { "main" }; app.GetInterfacesAndImplementations(ifaces, impls); app.cuda = { project / "kernel" }; - app.linkFlags = { runtimeDir, "-lcudart" }; std::unordered_map> depResults; std::mutex depMutex; const BuildResult result = Build(app, depResults, depMutex); - return std::pair{ result.result, app.BinDir() / "cuda" }; + return Built{ result.result, app.BinDir() / "cuda", app.BuildDir() / "cuda.link" }; }; - const auto [native, nativeBinary] = build(std::nullopt); - Check(native.empty(), std::format("the build with the default architecture succeeds: {}", native)); - Check(fs::exists(nativeBinary), "it links the executable"); + const Built native = build(std::nullopt); + Check(native.error.empty(), std::format("the build with the default architecture succeeds: {}", native.error)); + Check(fs::exists(native.binary), "it links the executable"); + const std::string record = Read(native.linkRecord); + Check(record.contains(runtime), std::format("with the static runtime from the toolkit's lib64, though no link flag names it (link: {})", record)); std::vector runs = Lines(log); Check(runs.size() == 1 && runs.front().contains("-arch=native"), std::format("CUDA_PATH's nvcc compiles the .cu once, with -arch=native (ran: {})", Joined(runs))); - const auto [other, otherBinary] = build("sm_86"); - Check(other.empty(), std::format("the build for sm_86 succeeds: {}", other)); + const Built other = build("sm_86"); + Check(other.error.empty(), std::format("the build for sm_86 succeeds: {}", other.error)); runs = Lines(log); Check(runs.size() == 2 && runs.back().contains("-arch=sm_86"), std::format("another architecture compiles the unchanged .cu again, for it (ran: {})", Joined(runs))); - Check(fs::exists(otherBinary) && otherBinary.parent_path() != nativeBinary.parent_path(), "in a directory of its own"); + Check(fs::exists(other.binary) && other.binary.parent_path() != native.binary.parent_path(), "in a directory of its own"); - const auto [again, againBinary] = build("sm_86"); - Check(again.empty() && Lines(log).size() == 2, std::format("an unchanged build compiles nothing (ran: {})", Joined(Lines(log)))); + const Built again = build("sm_86"); + Check(again.error.empty() && Lines(log).size() == 2, std::format("an unchanged build compiles nothing (ran: {})", Joined(Lines(log)))); fs::last_write_time(project / "kernel.h", fs::file_time_type::clock::now()); - const auto [touched, touchedBinary] = build("sm_86"); - Check(touched.empty(), std::format("the build after the header changed succeeds: {}", touched)); + const Built touched = build("sm_86"); + Check(touched.error.empty(), std::format("the build after the header changed succeeds: {}", touched.error)); runs = Lines(log); Check(runs.size() == 3 && runs.back().contains("-arch=sm_86"), std::format("a changed header compiles the .cu again (ran: {})", Joined(runs))); + { + // The .cu in a static library, the C++ unit in an executable built on + // it: neither names a CUDA library, and the executable's link has the + // runtime only from what the library hands on. + const fs::path split = scratch / "split"; + fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", split, fs::copy_options::recursive); + Configuration kernels; + kernels.path = split; + kernels.name = "kernels"; + kernels.outputName = "kernels"; + kernels.type = ConfigurationType::LibraryStatic; + kernels.cuda = { split / "kernel" }; + Configuration program; + program.path = split; + program.name = "program"; + program.outputName = "program"; + program.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main" }; + program.GetInterfacesAndImplementations(ifaces, impls); + program.dependencies = { &kernels }; + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult built = Build(program, depResults, depMutex); + Check(built.result.empty(), std::format("an executable built on a library with CUDA sources links: {}", built.result)); + Check(Read(program.BuildDir() / "program.link").contains(runtime), "with the runtime the library hands on"); + } + { + // An executable with CUDA sources built on a library of the + // project's named like one in the toolkit's lib64: the linker has to + // take the project's, and stops on the toolkit's file if it searches + // the toolkit's lib64 first. + const fs::path named = scratch / "named"; + fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", named, fs::copy_options::recursive); + Configuration checkpoint; + checkpoint.path = named; + checkpoint.name = "checkpoint"; + checkpoint.outputName = "checkpoint"; + checkpoint.type = ConfigurationType::LibraryStatic; + { + std::array ifaces = {}; + std::array impls = { "checkpoint" }; + checkpoint.GetInterfacesAndImplementations(ifaces, impls); + } + Configuration app; + app.path = named; + app.name = "named"; + app.outputName = "named"; + app.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + app.cuda = { named / "kernel" }; + app.dependencies = { &checkpoint }; + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult built = Build(app, depResults, depMutex); + Check(built.result.empty(), std::format("an executable with CUDA sources links a library of its project's named like one in the toolkit's lib64: {}", built.result)); + } + { + // A project that names the shared runtime itself, as every project.cpp + // with CUDA sources had to: its -lcudart comes ahead of the static + // archive on the link line, so the linker takes the shared runtime. + const fs::path own = scratch / "own"; + fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", own, fs::copy_options::recursive); + Configuration app; + app.path = own; + app.name = "own"; + app.outputName = "own"; + app.type = ConfigurationType::Executable; + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + app.cuda = { own / "kernel" }; + app.linkFlags = { std::format("-L{}", ShellQuote(realArchive.parent_path().string())), "-lcudart" }; + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult built = Build(app, depResults, depMutex); + Check(built.result.empty(), std::format("a build that names -lcudart itself links: {}", built.result)); + const std::string link = Read(app.BuildDir() / "own.link"); + const std::size_t shared = link.find(" -lcudart "); + const std::size_t archive = link.find(runtime); + Check(shared != std::string::npos && archive != std::string::npos && shared < archive, std::format("with its -lcudart ahead of the static runtime (link: {})", link)); + } + fs::remove_all(scratch, ec); return Failures == 0 ? 0 : 1; } diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index 6ab8186..108ee5a 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -247,6 +247,30 @@ int main() { Check(found.is_absolute() && fs::equivalent(found, cuda / "named/bin/nvcc"), std::format("a relative CUDA_PATH names an absolute nvcc (got '{}')", found.string())); } } + { + // The static runtime beside the nvcc found: lib64/libcudart_static.a + // where it is there, else none, as for a lib64 that holds none or + // cannot be looked into, here one that links to itself, which has to + // be looked into without throwing. + const fs::path kits = scratch / "runtime"; + Program(kits / "with/bin/nvcc"); + Touch(kits / "with/lib64/libcudart_static.a"); + Program(kits / "without/bin/nvcc"); + fs::create_directories(kits / "without/lib64"); + Program(kits / "looped/bin/nvcc"); + fs::create_directory_symlink("lib64", kits / "looped/lib64"); + ToolchainInputs in; + in.env["CUDA_PATH"] = (kits / "with").string(); + const fs::path found = ResolveToolchain(in).cudaRuntime; + std::error_code ec; + Check(!found.empty() && fs::equivalent(found, kits / "with/lib64/libcudart_static.a", ec), std::format("the static runtime in the lib64 beside nvcc's bin (got '{}')", found.string())); + in.env["CUDA_PATH"] = (kits / "without").string(); + Check(ResolveToolchain(in).cudaRuntime.empty(), "none where that lib64 holds none"); + in.env["CUDA_PATH"] = (kits / "looped").string(); + Check(ResolveToolchain(in).cudaRuntime.empty(), "none where the lib64 cannot be looked into"); + in.env["CUDA_PATH"] = (kits / "missing").string(); + Check(ResolveToolchain(in).cudaRuntime.empty(), "and none without an nvcc"); + } { // Nothing anywhere: the error says where it looked and what to set. ToolchainInputs in; From df79dcd46d1dab228948049bd2bf0c2be39081ca Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 09/53] docs: a CUDA section in the README cfg.cuda had no section of its own, only mentions in passing. The new one says how sources are listed and linked, where the toolkit is found and what the Flatpak sees of it, what cfg.cudaArch picks, and what nvcc is not given: the include paths, defines and compile flags of the C and C++ compiles, and -g. The Flatpak output section's advice for other machines names a --cuda-arch= other than native, such as all-major, beside --march=x86-64-v3. --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f956f98..5f22263 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ cfg.flatpak.modules = { "packaging/flatpak/node.yaml" }; // flatpak-builder modu - **Share entries** are files of the project the program reads from `/app/share` instead of from beside itself: data it finds at `/../share/`, licences. `files/share` is the build's own, so they are kept there as long as they are listed and removed once they are not, and anything else put there is removed too. `-r` runs the program from `files/bin`, so the same `../share` lookup finds them. Any file can be one, a second desktop entry or an add-on's metainfo among them: what flatpak exports of an app's `share/`, it exports of them too, by its own rules, such as an icon, D-Bus service, MIME package, search provider or KRunner plugin named after the app-id. `flatpak build-export` refuses an exported icon that is not a square image and a D-Bus service that is not a key file, and warns of the app's own desktop entry where `desktop-file-validate` rejects it; a second desktop entry, a MIME package or metainfo it exports as it is. A directory entry places every regular file in it, and every link to one, at its path inside it; anything else in it is left out: empty directories, links to directories, dangling links, FIFOs and sockets. Two files for one path in `share/`, a field's own file among them, or a file where another entry needs a directory, fail the build. The app's desktop entry, `applications/.desktop`, is held to `desktopFile`'s checks whichever placed it. A directory that holds what the build writes fails too, since it would be copied into itself, growing each time the app is built or exported: `files/`, and the app's directory in `build/flatpak-apps/`, where `install` and `bundle` put another copy of `files/` and the exported app, the project's own directory holding both, as written and where links lead, so also where `bin/` is a link elsewhere. So does one that lies in them, which is the build's own output. - **Modules** are for what the app needs in `/app` besides the program: a runtime it starts, a tool it runs, data built from source. They are flatpak-builder module files in Flatpak's own format, which crafter-build names and never reads. With any, `install` and `bundle` have the host's flatpak-builder (or the `org.flatpak.Builder` app) make the app with `org.freedesktop.Sdk//26.08`, which the host then needs as well as the runtime, from a manifest in `build/flatpak-apps//` that lists them and copies the built program in last, so it is not compiled again; flatpak-builder's defaults then also strip it and split its debug info into a `.Debug` extension. Translations under `share/locale` stay in the app rather than going into a `.Locale` extension, which a bundle would leave out. `-r` runs the program without them. - **What cannot be a Flatpak** fails the build saying why: Windows and wasm targets, which keep their `.exe` and `.wasm`; a build against a sysroot, which links that sysroot's libraries and not the runtime's, or one for musl, a C library no runtime has; an architecture other than the runtime's; a build against `CRAFTER_BUILD_LIBCXX_DIR`, since a Flatpak carries the toolchain's own libc++, built against the runtime's glibc; and a build by a native crafter-build, whose programs link the host's glibc, unless `CRAFTER_BUILD_FLATPAK_INFO`, which the tests set, names a runtime. A dependency's executables stay as linked even when `--packaging=flatpak` reaches their project, since their consumers run them by path, and tests are never packaged. A dependency that sets `cfg.packaging` in its own `project.cpp` is packaged, and the files its `cfg.flatpak` names are found in its own directory, as its `cfg.files` are. -- **For other machines**, build with `--march=x86-64-v3` rather than the default `native`, which can crash with SIGILL on an older CPU. Pass it on the command line or in `CRAFTER_BUILD_MARCH`: either reaches every configuration of the program that `ApplyStandardArgs` is called on, a sibling's whose `project.cpp` calls it included, while CMake externals are compiled without `-march`, and a `#pragma crafter dependency`, tooling built for `project.so` alone, with `-march=native`. +- **For other machines**, build with `--march=x86-64-v3` rather than the default `native`, which can crash with SIGILL on an older CPU. Pass it on the command line or in `CRAFTER_BUILD_MARCH`: either reaches every configuration of the program that `ApplyStandardArgs` is called on, a sibling's whose `project.cpp` calls it included, while CMake externals are compiled without `-march`, and a `#pragma crafter dependency`, tooling built for `project.so` alone, with `-march=native`. A program with CUDA sources also needs a `--cuda-arch=` other than `native`, such as `all-major` (see CUDA), and `bundle` warns of a bundle built for either `native`. Without packaging (`Packaging::None`, and for now `Default`), a program is the executable as linked: it runs inside crafter-build's sandbox (`-r`, `test`, `run` scripts), and on a host only where the host has what it links. @@ -206,6 +206,21 @@ What a build then writes: Three things never count: the project's own `AGENTS.consumer.md`; its tests' dependencies, since a plain build never looks at the tests; and a dependency's `#pragma crafter dependency` tooling, which is about how the dependency is built, not how it is used. +## CUDA + +`cfg.cuda` lists CUDA sources, named without `.cu`. A relative name is read from the directory crafter-build runs in, except in a project loaded through `GitProject` or `LocalProject`, whose relative names crafter-build rebases onto that project's directory: + +```cpp +cfg.cuda = { fs::absolute("kernels/blur") }; // kernels/blur.cu +``` + +nvcc compiles each into an object that joins the configuration's other objects, and the configuration links the CUDA runtime of nvcc's toolkit, as does whatever is built on it: `libcudart_static.a` from the toolkit's `lib64`, with the `-lrt -lpthread -ldl` nvcc's own link puts after it. Being static, it takes no run path into the toolkit. It comes after `cfg.linkFlags` and the libraries of what the configuration is built on, so a `-lcudart` named there is the one the linker takes. A toolkit whose `lib64` holds no `libcudart_static.a`, as where a distribution keeps the toolkit's libraries in its own directories, gets no runtime linked: `cfg.linkFlags` names it, as before. + +- **The toolkit** is the one `CUDA_PATH` names, else the first of `/opt/cuda`, where Arch's package installs it, and `/usr/local/cuda`, the link NVIDIA's installer and packages make to theirs, that has a `bin/nvcc`, else the first `nvcc` in an absolute entry of `PATH`. A `CUDA_PATH` without a `bin/nvcc` is an error, not a reason to look elsewhere. `crafter-build --version` prints the nvcc it found and, where there is one, the static runtime beside it; a build with a `.cu` to compile and no nvcc says where it looked. +- **In the Flatpak**, `/opt` and your home are where the host has them, the host's `/usr/local/cuda` is found under `/run/host`, as is the toolkit it is a link to, and `PATH` is the sandbox's own `/app/bin:/usr/bin`, so for a toolkit anywhere else, set `CUDA_PATH`. nvcc compiles the host code with the Sdk's `g++` (GCC 16.2), not the host's: `NVCC_CCBIN` still applies, and names a path inside the sandbox. The programs `-r` and `test` start find the driver's `libcuda.so.1` in the runtime's NVIDIA GL extension for the host's driver. +- **The GPU architecture** is `cfg.cudaArch`, nvcc's `-arch`. It defaults to `native`, the GPUs of the machine that builds, as `march` defaults to its CPU; where there is none, nvcc warns and uses its own default (sm_75 in CUDA 13.4). Like `-march=native`, it is for a program that runs where it is built: it carries no PTX, which a GPU of a newer architecture compiles when it loads the program. For other machines, build with `--cuda-arch=all-major`, nvcc's major architectures (`sm_*0`) and its earliest, with the PTX of the newest major, or name one, such as `sm_89`, which comes with its own PTX. `--cuda-arch=` and `CRAFTER_BUILD_CUDA_ARCH` set it where `project.cpp` calls `ApplyStandardArgs`, as `--march=` and `CRAFTER_BUILD_MARCH` set `march`, and a test inherits it. Another architecture builds in a directory of its own, and so does `native` when the GPUs change: the NVIDIA GPUs on the machine's PCI bus (its display devices, PCI class 0x03), the slots they are in, `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` key it. That is crafter-build's reading of the machine, not nvcc's own: after a change it cannot see, such as a GPU bound to another driver, run `crafter-build clean`, or build with a named architecture, which depends on nothing on the machine. +- **nvcc gets** `-O3` and `-arch`, beside `-c`, the `.cu` and its outputs (`-o`, and `-MD -MF` for the depfile): none of the include paths, defines and `cfg.compileFlags` the C and C++ compiles get, and no `-g` for `cfg.debug`. A `.cu` compiles again when it, or a header it includes, is newer than its object, as a C or C++ source does. + ## Tests Tests live under `tests//`. The simplest case is a single C++ file: From 5b75df3b19f99e3cd5673e555d3427a38a314587 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 11 Nov 2026 19:34:52 +0100 Subject: [PATCH 10/53] docs(packaging): add the 6.2.0 release entry 6.2.0 makes CUDA sources compile in the Flatpak: crafter-build finds nvcc itself, under CUDA_PATH, /opt/cuda or the host's /usr/local/cuda, or in an absolute entry of PATH, where it used to run whatever the sandbox's PATH gave, which never holds the host's toolkit, and it links that toolkit's static CUDA runtime itself where the toolkit's lib64 holds it. The GPU architecture CUDA sources compile for is configurable and native by default, and a .cu compiles again when a header it includes changes. A minor, by the version rule: the notes have New and Fixes and nothing Breaking, and Jorijn's "6.2.0 is fine" settled it. The default architecture moves from sm_89, which carries its PTX, to native, which carries none, so a program built for native has no PTX for a GPU of a newer architecture. That is under New rather than Breaking because no Flatpak release compiled a .cu with the PATH its manifest sets: each ran a bare nvcc in the sandbox, whose PATH, /app/bin:/usr/bin, holds no toolkit, so a project had to set another PATH itself to compile one. A program for other machines takes another architecture, such as --cuda-arch=all-major, as the notes say. A project that names -lcudart in cfg.linkFlags keeps building, with its shared runtime first on the link line. VariantId changes for no configuration without CUDA sources but one built with --cuda-arch=, which was a project argument and is crafter-build's own now; a configuration with CUDA sources builds once in new bin/ and build/ directories, keyed by its architecture, for native by crafter-build's reading of the machine's GPUs, and by its nvcc. --- .../net.catcrafts.CrafterBuild.metainfo.xml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml index 23bbff2..d16aeaf 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml @@ -25,6 +25,20 @@ + + +

New

+
    +
  • CUDA sources compile for the GPU architecture cfg.cudaArch names, nvcc's -arch, which --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH set where project.cpp calls ApplyStandardArgs. It defaults to native, the GPUs of the machine that builds, as march defaults to its CPU; it was sm_89 for every build. A program built for native carries no PTX for newer GPUs, so build one that runs elsewhere with --cuda-arch=all-major; crafter-build bundle warns of a bundle whose CUDA code is built for native. Another architecture builds in a directory of its own, and so does native on other GPUs. The README's new CUDA section has the details.
  • +
  • A configuration with CUDA sources links the static CUDA runtime of the toolkit whose nvcc compiles them, where the toolkit's lib64 holds it, and so does whatever is built on it: cfg.linkFlags then needs no -lcudart and no path into the toolkit, which inside the Flatpak lies under /run/host for the host's /usr/local/cuda. crafter-build --version prints it next to nvcc.
  • +
+

Fixes

+
    +
  • CUDA sources compile in the Flatpak. With the PATH its manifest sets, every build with cfg.cuda there stopped at nvcc: command not found, because that PATH does not hold the host's toolkit. crafter-build now looks for nvcc itself: in $CUDA_PATH/bin, else in /opt/cuda/bin or the host's /usr/local/cuda/bin, else in an absolute entry of PATH. A build that finds none says where it looked, and crafter-build --version prints the one it found.
  • +
  • A .cu compiles again when a header it includes changes, as a C or C++ source does. It used to compile again only when the .cu itself changed, and kept the object built from the old header.
  • +
+
+

New

From e87dc4f015487f6820a61268e4fa5a9335a765cc Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:55 +0100 Subject: [PATCH 11/53] fix(build): refuse interface units that import each other Two partitions that import each other, a partition that imports its own module, and two modules of one configuration that import each other cannot be built in any order. Build() compiles each stale unit on a thread that first waits for the units its unit imports, and a primary interface waits for every stale partition of its module as well, so a build that found every unit of such a round stale, as a first build of them does, hung: every thread waiting, no compiler running, no error. ImportCycleError follows the imports of a configuration's interface units at the top of that configuration's Build(), before it makes a directory or builds a dependency, and Build() returns an error naming the units of the first round it finds in the order they wait in, "Ring:First -> Ring:Second -> Ring:First". A primary interface counts as coming after each partition of its module, whether it imports that one or not, since that is how it is built. A configuration built on the one refused has started its own build by then: the check reads the imports ResolvePendingImports has just placed, which are that Build()'s to read while it runs. The imports are the ones the source scanner reads, and it reads one in a string literal, in a comment that spans lines or under #if 0 as it reads any other (issue #45), so the units the error names are where to look for one of those too. The error says so, since the compiler sees no round in such a project, and AGENTS.template.md has it under Gotchas. --- AGENTS.template.md | 1 + implementations/Crafter.Build-Clang.cpp | 71 +++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/AGENTS.template.md b/AGENTS.template.md index a99827a..b6b1678 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -198,6 +198,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. - A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. - `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. +- The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then. - Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - A CMake external whose recorded configure inputs (`/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. - The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps. diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 7ca09c0..a2fe898 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -533,6 +533,70 @@ namespace { return error; } + // Interface units of `config` that are each built after the next, round + // to the first again: partitions that import each other, a partition that + // imports its own module, sibling modules that import each other. Empty + // when there are none, otherwise the error naming the round. No order + // builds such units: each is compiled on a thread that first waits for + // the units it imports, a primary interface for the partitions of its + // module as well, so such a build hung with no compiler running. + // + // The imports are the scanner's, which reads one in a string literal, in + // a comment that spans lines or under `#if 0` as it reads any other + // (issue #45): the units named are where to look for one of those as + // well, and the error says so, since the compiler sees no round there. + std::string ImportCycleError(const Configuration& config) { + struct Unit { + std::string name; + std::vector builtAfter; + bool entered = false; + bool left = false; + }; + // By address: a module and a partition are different types, and a + // unit's imports name either. Walked in the order the units were + // declared, so the same project gets the same message every time. + std::unordered_map units; + std::vector declared; + for (const std::unique_ptr& module : config.interfaces) { + declared.push_back(module.get()); + Unit& primary = units[module.get()]; + primary.name = module->name; + for (const Module* imported : module->moduleDependencies) primary.builtAfter.push_back(imported); + for (const std::unique_ptr& partition : module->partitions) { + // The primary interface is built after every partition of + // its module, whether it imports that one or not. + primary.builtAfter.push_back(partition.get()); + declared.push_back(partition.get()); + Unit& unit = units[partition.get()]; + unit.name = std::format("{}:{}", module->name, partition->name); + for (const ModulePartition* imported : partition->partitionDependencies) unit.builtAfter.push_back(imported); + for (const Module* imported : partition->moduleDependencies) unit.builtAfter.push_back(imported); + } + } + std::vector chain; + std::string round; + std::function visit = [&](Unit& unit) { + if (!round.empty() || unit.left) return; + if (unit.entered) { + // Back at a unit this walk is still inside of: the round is + // the chain from where it was entered. + for (auto it = std::ranges::find(chain, &unit); it != chain.end(); ++it) round += std::format("{} -> ", (*it)->name); + round += unit.name; + return; + } + unit.entered = true; + chain.push_back(&unit); + for (const void* before : unit.builtAfter) { + if (const auto found = units.find(before); found != units.end()) visit(found->second); + } + chain.pop_back(); + unit.left = true; + }; + for (const void* unit : declared) visit(units.at(unit)); + if (round.empty()) return ""; + return std::format("{}: these interface units are each built after the next, so none can be built first: {}. A unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. The imports are read from the source text without compiling it: one in a string literal, in a comment that spans lines or under #if 0 counts too.", config.name, round); + } + // What a wasm32 configuration cannot be built with now that every unit // has C++ exceptions, and what its sysroot has to have for that; empty // for any other target and when nothing is wrong. Each would otherwise @@ -733,6 +797,13 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map Date: Fri, 13 Nov 2026 17:59:55 +0100 Subject: [PATCH 12/53] test(build): interface units that import each other are refused ImportCycle builds three fixtures as static libraries, each on a fresh copy outside the checkout: two partitions that import each other, a partition that imports its own module, and two modules that import each other. Each build has to return an error that holds its round, "Ring:First -> Ring:Second -> Ring:First", "Own -> Own:Part -> Own" and "East -> West -> East", and leave neither a build nor a bin directory. Before the refusal the test ran into its timeout: the first of those builds never returned. --- project.cpp | 1 + .../fixture/own-module/Own-Part.cppm | 7 ++ tests/ImportCycle/fixture/own-module/Own.cppm | 5 ++ .../fixture/partitions/Ring-First.cppm | 7 ++ .../fixture/partitions/Ring-Second.cppm | 7 ++ .../ImportCycle/fixture/partitions/Ring.cppm | 6 ++ tests/ImportCycle/fixture/siblings/East.cppm | 7 ++ tests/ImportCycle/fixture/siblings/West.cppm | 7 ++ tests/ImportCycle/main.cpp | 79 +++++++++++++++++++ 9 files changed, 126 insertions(+) create mode 100644 tests/ImportCycle/fixture/own-module/Own-Part.cppm create mode 100644 tests/ImportCycle/fixture/own-module/Own.cppm create mode 100644 tests/ImportCycle/fixture/partitions/Ring-First.cppm create mode 100644 tests/ImportCycle/fixture/partitions/Ring-Second.cppm create mode 100644 tests/ImportCycle/fixture/partitions/Ring.cppm create mode 100644 tests/ImportCycle/fixture/siblings/East.cppm create mode 100644 tests/ImportCycle/fixture/siblings/West.cppm create mode 100644 tests/ImportCycle/main.cpp diff --git a/project.cpp b/project.cpp index cd1e206..6674515 100644 --- a/project.cpp +++ b/project.cpp @@ -332,6 +332,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); } diff --git a/tests/ImportCycle/fixture/own-module/Own-Part.cppm b/tests/ImportCycle/fixture/own-module/Own-Part.cppm new file mode 100644 index 0000000..5da0aee --- /dev/null +++ b/tests/ImportCycle/fixture/own-module/Own-Part.cppm @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Own:Part; +import Own; + +export bool Part(); diff --git a/tests/ImportCycle/fixture/own-module/Own.cppm b/tests/ImportCycle/fixture/own-module/Own.cppm new file mode 100644 index 0000000..89bcb52 --- /dev/null +++ b/tests/ImportCycle/fixture/own-module/Own.cppm @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Own; +export import :Part; diff --git a/tests/ImportCycle/fixture/partitions/Ring-First.cppm b/tests/ImportCycle/fixture/partitions/Ring-First.cppm new file mode 100644 index 0000000..808b35e --- /dev/null +++ b/tests/ImportCycle/fixture/partitions/Ring-First.cppm @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Ring:First; +import :Second; + +export bool First(); diff --git a/tests/ImportCycle/fixture/partitions/Ring-Second.cppm b/tests/ImportCycle/fixture/partitions/Ring-Second.cppm new file mode 100644 index 0000000..5bee378 --- /dev/null +++ b/tests/ImportCycle/fixture/partitions/Ring-Second.cppm @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Ring:Second; +import :First; + +export bool Second(); diff --git a/tests/ImportCycle/fixture/partitions/Ring.cppm b/tests/ImportCycle/fixture/partitions/Ring.cppm new file mode 100644 index 0000000..34c7c71 --- /dev/null +++ b/tests/ImportCycle/fixture/partitions/Ring.cppm @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Ring; +export import :First; +export import :Second; diff --git a/tests/ImportCycle/fixture/siblings/East.cppm b/tests/ImportCycle/fixture/siblings/East.cppm new file mode 100644 index 0000000..141d14b --- /dev/null +++ b/tests/ImportCycle/fixture/siblings/East.cppm @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module East; +import West; + +export bool East(); diff --git a/tests/ImportCycle/fixture/siblings/West.cppm b/tests/ImportCycle/fixture/siblings/West.cppm new file mode 100644 index 0000000..0f0e7d3 --- /dev/null +++ b/tests/ImportCycle/fixture/siblings/West.cppm @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module West; +import East; + +export bool West(); diff --git a/tests/ImportCycle/main.cpp b/tests/ImportCycle/main.cpp new file mode 100644 index 0000000..618d8e3 --- /dev/null +++ b/tests/ImportCycle/main.cpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// Interface units that import each other are refused before their +// configuration builds anything, with an error naming them. No order builds +// them. Before the refusal such a build hung with no compiler running, each +// unit waiting for the units it imports, which is how this test failed then: +// by running into its timeout. +// +// Three ways round: two partitions that import each other, a partition that +// imports its own module, whose primary interface is built after all of its +// partitions, and two modules of one configuration that import each other. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // Builds the interfaces of the fixture in `dir` as a library and returns + // Build()'s error. On a copy outside the checkout, made anew each run: a + // build that gets past the refusal has made its directories before it + // fails, and in the checkout the next run would find them there and + // report them against a refusal that works. + std::string BuildError(std::string_view dir, std::span interfaces) { + const fs::path staged = fs::temp_directory_path() / "crafter-build-import-cycle" / dir; + fs::remove_all(staged); + fs::create_directories(staged.parent_path()); + fs::copy(fs::current_path() / "tests" / "ImportCycle" / "fixture" / dir, staged, fs::copy_options::recursive); + + Configuration cfg; + cfg.path = staged; + cfg.name = std::format("cycle-{}", dir); + cfg.outputName = cfg.name; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::LibraryStatic; + std::array implementations = {}; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult built = Build(cfg, depResults, depMutex); + // Refused like a graph with a module built twice: before a directory + // is made for it. + Check(!fs::exists(cfg.BuildDir()) && !fs::exists(cfg.BinDir()), std::format("{}: the refused build left {} or {} behind", dir, cfg.BuildDir().string(), cfg.BinDir().string())); + return built.result; + } +} + +int main() { + { + std::array interfaces = { "Ring", "Ring-First", "Ring-Second" }; + const std::string error = BuildError("partitions", interfaces); + Check(error.contains("Ring:First -> Ring:Second -> Ring:First"), std::format("partitions that import each other are named in the order they wait in, got: '{}'", error)); + // The scanner reads imports the compiler does not see, so the error + // has to say where a round nobody wrote can come from. + Check(error.contains("string literal") && error.contains("#if 0"), std::format("the error says which text the scanner reads as an import, got: '{}'", error)); + } + { + std::array interfaces = { "Own", "Own-Part" }; + const std::string error = BuildError("own-module", interfaces); + Check(error.contains("Own -> Own:Part -> Own"), std::format("a partition that imports its own module is named with it, got: '{}'", error)); + } + { + std::array interfaces = { "East", "West" }; + const std::string error = BuildError("siblings", interfaces); + Check(error.contains("East -> West -> East"), std::format("modules that import each other are named, got: '{}'", error)); + } + return Failures == 0 ? 0 : 1; +} From eff9868b68d5a92e00f4a91b28ef6d75de396e67 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:55 +0100 Subject: [PATCH 13/53] docs: interface units that import each other stop the build The README says in "Writing a project.cpp" that a unit is built after the modules and partitions it imports, that interface units of one configuration that import each other are refused with an error naming them, and that the imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under #if 0 counts too and can make such a round in a project the compiler accepts. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5f22263..e06b24c 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ extern "C" Configuration CrafterBuildProject(std::span a Run `crafter-build` in that directory, outputs land at `bin/myapp----/myapp` and intermediates at `build/myapp----/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build, in its own directory, where its shaders, `cfg.files` and assets are; a wasm32 one runs under wasmtime, or wasmer where there is no wasmtime, with no directory given to it, and one built for the browser (`EnableWasiBrowserRuntime`) is served over HTTP from that directory instead. +crafter-build orders a configuration's units by the `import` lines of its sources: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused before anything of it is built, with an error that names the units in the order they wait. The imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under `#if 0` counts too, and such text can make a round in a project the compiler accepts. + ## Flatpak output A program crafter-build's Flatpak links for Linux without a sysroot takes the libc++, libc++abi and libunwind of its LLVM and the glibc of its runtime, so outside the Flatpak it starts only on a host that has those libraries and a glibc with every symbol version they and the program reference, 2.38 or newer for the bundled libc++. A build lays the program out as a Flatpak of its own when it is packaged: From 913310da8638e2b49f038cd3455366d1d17b87a5 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:55 +0100 Subject: [PATCH 14/53] feat(build): run a build's steps on one worker per hardware thread Build() started a thread for every stale shader, asset, C, CUDA and C++ unit, and Module::Compile one more for every stale partition, and nothing bounded how many of them ran their step at once. Jorijn asked for the amount of parallelism to be limited by the amount of threads instead of just starting one per file; the threads are taken here to be the machine's hardware threads. The new :Jobs partition holds the two pieces. JobPool is worker threads behind one queue, started as jobs need them up to a fixed number, and JobPool::Process() is the pool of the process: at most a worker per hardware thread, one where std::thread::hardware_concurrency does not know. JobGroup is the jobs of one build on a pool. A job starts once the jobs it was added after have finished; the first job to fail keeps the ones that have not started from starting, and Wait() returns its error. No job waits for another job, and a JobGroup made on a worker of its own pool throws: a worker that waited for a job still in the queue would hold the thread that job needs. Build() adds what it did on those threads to a JobGroup instead, and the group's first error replaces the buildCancelled and buildError pair the threads set. The module units no longer block on the `compiled` flag of the units they import: Schedule() replaces Compile() on Module, ModulePartition and Implementation and adds a unit's jobs after the jobs that write the BMIs it imports. An interface unit is two jobs, its BMI and then its object from the BMI, so the units importing it start when the first is done, as they did when one thread ran both commands and raised the flag in between. A primary interface now waits for the BMIs of its partitions and no longer for their objects. Each of the two jobs has a progress line, "Precompiling X.cppm" and "Compiling X.cppm" for every interface unit, where a module and its partitions shared one "Compiling interface X". RunBuildCommand runs its command on a worker of the process's pool: on the calling thread when that is one, otherwise it waits for one. A link, an archive, the std module's precompile and project.cpp's compile are steps under the limit that way. The threads Build() starts per dependency and per external dependency stay: one of the first runs the dependency's own Build(), or waits for the thread that does, and one of the second runs git and cmake. With the BMI and the object as two jobs, a build that fails between them has written the BMI and skips the object, and Check, which reads staleness off the BMI, would call the unit built from then on. Schedule() therefore adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build interrupted between the two commands, or one whose second command failed, left the same behind before, and it stayed: the link took the object of the source before the edit, or failed on the missing one. ImportCycleError is now what keeps Schedule() from following a round of imports without end. The limit is on steps. Outside it, as AGENTS.template.md lists: an ExternalDependency's cmake --build, which keeps its own --parallel of as many jobs as there are hardware threads; the tests RunTests runs, --jobs= of them at once as before; the Crafter.Build modules EnsureCrafterBuildPcms precompiles one after another; and the threads a step starts for itself, which lld does for a link and Crafter.Asset's GDeflate compressor for an asset. The pool is one process's. The --help text says what a build runs at once and that test --jobs= counts tests. ConcurrentDependencyReset read the `compiled` flag, which is gone. It asserts on `checked` and `scheduled` instead, the state a reset from another build's thread would clear now, with a unit scheduled twice as the result, and the comment in its fixture says what the implementation unit comes after now. TransitiveInterfaceChange's comment names Schedule() where it named Compile() as what honours a partition's imports. Two comments in :Platform that spoke of worker threads, a word that now means the pool's, name the threads they mean. The bug-prover lens's section said shaders compile on a thread of their own each, and describes the pool now. --- .review-gates/lenses/repo-bug-prover.md | 22 +- AGENTS.template.md | 6 +- build.sh | 2 +- implementations/Crafter.Build-Clang.cpp | 313 +++++++----------- .../Crafter.Build-Implementation.cpp | 26 +- implementations/Crafter.Build-Interface.cpp | 189 +++++------ implementations/Crafter.Build-Jobs.cpp | 218 ++++++++++++ implementations/Crafter.Build-Platform.cpp | 74 +++-- interfaces/Crafter.Build-Implementation.cppm | 6 +- interfaces/Crafter.Build-Interface.cppm | 42 ++- interfaces/Crafter.Build-Jobs.cppm | 129 ++++++++ interfaces/Crafter.Build-Platform.cppm | 5 + interfaces/Crafter.Build-Progress.cppm | 6 +- interfaces/Crafter.Build-Test.cppm | 4 + interfaces/Crafter.Build.cppm | 1 + project.cpp | 6 +- .../fixture/deplib/DepMod-impl.cpp | 6 +- tests/ConcurrentDependencyReset/main.cpp | 44 +-- tests/TransitiveInterfaceChange/main.cpp | 8 +- 19 files changed, 728 insertions(+), 379 deletions(-) create mode 100644 implementations/Crafter.Build-Jobs.cpp create mode 100644 interfaces/Crafter.Build-Jobs.cppm diff --git a/.review-gates/lenses/repo-bug-prover.md b/.review-gates/lenses/repo-bug-prover.md index 13c9531..8934e98 100644 --- a/.review-gates/lenses/repo-bug-prover.md +++ b/.review-gates/lenses/repo-bug-prover.md @@ -13,9 +13,25 @@ The execution contexts to enumerate, beside the charter's: Running a test or a built artifact is a shell command too (`:Test`, `:Clang`). A path, file name or flag that reaches one with a space or a shell metacharacter in it is an input to attack. Other steps run inside - the process, among them glslang's shader compiles, on a thread of their - own per stale shader (`:Shader`), and lint's parse through the libclang - the linter dlopens (`:Lint`). + the process, among them glslang's shader compiles (`:Shader`), the + compression of an asset in Crafter.Asset, which starts threads of its own + (`:Asset`), and lint's parse through the libclang the linter dlopens + (`:Lint`). +- A build's steps run as jobs on the workers of `JobPool::Process()` + (`:Jobs`): up to as many threads as the machine has hardware threads, one + where that is one or unknown. The compiles of a configuration's stale + shaders, C, CUDA and C++ units, the compression of its stale assets, and + its copies of `cfg.files` and of the other files of an asset directory + go through the `JobGroup` of its `Build()`, which starts a job once the + jobs it was added after have finished; a `RunBuildCommand` waits for a + worker when its caller is not one. Jobs are waited for by threads that + are not workers, among them one that runs a `Build()` (its caller's, one + of `RunTests`', one a `Build()` starts per dependency) and the one that + runs `LoadProject`, for the compiles of the std module and of + `project.cpp`. The threads a `Build()` starts per external dependency are + not workers either and wait for no job: they run git and cmake. An + executable's copies of what its dependencies forward run on the thread of + its `Build()`. - Several crafter-build processes share `~/.cache/crafter.build/` at once: the std and Crafter.Build PCMs per target and march (the `ConcurrentCacheRace` test), and the external clones with their `.lock` diff --git a/AGENTS.template.md b/AGENTS.template.md index b6b1678..86c4b15 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -26,7 +26,8 @@ Partitions and what they own: - `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. - `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. - `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code. -- `:Interface` and `:Implementation` model module units, their staleness checks and their compiles. +- `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`. +- `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`). - `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. - `:Test` holds `AddTest`, `RunTests` and `TestRunner`. - `:Lint` is the lint/format driver plus the libclang token and AST layer. @@ -121,6 +122,7 @@ Beyond the rules: - Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule. - There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. +- Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its `JobGroup` in `Build()`, after the jobs whose output it reads; run a step that stands by itself, as a link does, through `RunBuildCommand`, which runs on a worker of `JobPool::Process()` whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: a `JobGroup` made on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group. - Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. - Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. @@ -198,6 +200,8 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. - A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. - `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. +- The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel ` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. +- An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. - The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then. - Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - A CMake external whose recorded configure inputs (`/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. diff --git a/build.sh b/build.sh index e72ead1..6e48b9f 100755 --- a/build.sh +++ b/build.sh @@ -47,7 +47,7 @@ cp wasi-runtime/index.html.in share/crafter-build/wasi-runtime/ # Partition order is the import order: every unit is listed before the # units that import it, and the umbrella last. -PARTITIONS="Toolchain Shader Platform Flatpak Interface Implementation External Agents Clang Test Lint Script Progress Asset" +PARTITIONS="Toolchain Shader Platform Flatpak Jobs Interface Implementation External Agents Clang Test Lint Script Progress Asset" cp interfaces/Crafter.Build.cppm share/crafter-build/ for p in $PARTITIONS; do diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index a2fe898..d95625f 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -17,6 +17,7 @@ import :Agents; import :Progress; import :Asset; import :Flatpak; +import :Jobs; namespace fs = std::filesystem; using namespace Crafter; @@ -148,8 +149,8 @@ void Configuration::GetInterfacesAndImplementations(std::span interfac // Primary interface unit: record only its module imports. Its // `[export] import :Part;` lines need no edge — Module::Check walks - // every partition it owns and Module::Compile builds them all before - // precompiling itself, so partitions are covered wholesale. + // every partition it owns and Module::Schedule puts the primary + // interface after all of them, so partitions are covered wholesale. if (partition == nullptr) { std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern); @@ -537,9 +538,10 @@ namespace { // to the first again: partitions that import each other, a partition that // imports its own module, sibling modules that import each other. Empty // when there are none, otherwise the error naming the round. No order - // builds such units: each is compiled on a thread that first waits for - // the units it imports, a primary interface for the partitions of its - // module as well, so such a build hung with no compiler running. + // builds such units. Schedule() works the order out before it adds a + // unit's jobs, by following the imports, and would follow a round of + // them without end. When each unit had a thread that waited for the + // units it imports, such a build hung with no compiler running. // // The imports are the scanner's, which reads one in a string literal, in // a comment that spans lines or under `#if 0` as it reads any other @@ -767,22 +769,26 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapchecked = false; - iface->compiled.store(false); + iface->scheduled = false; + iface->precompileJob.reset(); for (auto& part : iface->partitions) { part->checked = false; - part->compiled.store(false); + part->scheduled = false; + part->precompileJob.reset(); } } @@ -874,7 +880,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map shaderIncludeDirs; @@ -894,11 +900,23 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map threads; - threads.reserve(config.shaders.size() + 1 + config.interfaces.size() + config.implementations.size()); + // A stale shader, asset to compress, C, CUDA or C++ unit is a job of this + // group; each used to get a thread of its own the moment it was found + // stale. The copies of cfg.files and of the other files of an asset + // directory are jobs as well. The jobs run on the workers every build of + // the process shares, so no more of them run at once than the machine + // has hardware threads. + // + // The group also holds the first error among its jobs and what this + // build reports to it (Fail), the dependency and external builds below + // among it, and none of its jobs starts after one. What goes wrong once + // the jobs are done, at the link, is not the group's. + // + // Declared after everything its jobs use by reference: leaving Build() + // waits for them before any of that is destroyed. A job gets a copy of + // whatever it uses that is declared below here. + JobGroup jobs; - std::string buildError; - std::atomic buildCancelled{false}; // Two entries with the same output name would compile in parallel into // one file: whichever finished last won, the build reported success, and // Check() then called both up to date. The usual way in is one source @@ -909,28 +927,18 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapsecond->path.string(), shader.path.string(), existing->first); - buildCancelled.store(true); + jobs.Fail(std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first)); break; } } for (const Shader& shader : config.shaders) { - if (buildCancelled.load(std::memory_order_relaxed)) break; + if (jobs.Failed()) break; place(outputDir / shader.OutputName(), {}); if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue; - threads.emplace_back([&shader, &outputDir, &buildDir, &shaderIncludeDirs, &buildError, &buildCancelled]() { - // A source registered more than once shows up once per variant; - // name the variant so the lines can be told apart. - Progress::Task task(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant)); - if (buildCancelled.load(std::memory_order_relaxed)) return; - - std::string result = shader.Compile(outputDir, buildDir, shaderIncludeDirs); - if (result.empty()) return; - - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); - } + // A source registered more than once shows up once per variant; + // name the variant so the lines can be told apart. + jobs.Add(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant), [&shader, &outputDir, &buildDir, &shaderIncludeDirs] { + return shader.Compile(outputDir, buildDir, shaderIncludeDirs); }); } @@ -942,23 +950,19 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map> assetPassthroughs; @@ -978,73 +982,58 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map outName = CompressedAssetName(asset); if (!outName) { - buildCancelled.store(true); - buildError = std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string()); + jobs.Fail(std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string())); break; } submitCompress(asset, *outName); } } if (!assetPassthroughs.empty()) { - threads.emplace_back([passthroughs = std::move(assetPassthroughs), &outputDir, &buildCancelled, &buildError]() { - Progress::Task task("Copying asset passthrough files"); - if (buildCancelled.load(std::memory_order_relaxed)) return; - try { - for (const auto& [src, rel] : passthroughs) { - fs::path dst = outputDir / rel; - fs::create_directories(dst.parent_path()); - if (!fs::exists(dst)) { - fs::copy_file(src, dst); - } else if (fs::last_write_time(src) > fs::last_write_time(dst)) { - fs::copy_file(src, dst, fs::copy_options::overwrite_existing); - } - } - } catch (const std::exception& e) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = e.what(); + // What a copy throws is the job's error (JobGroup::Add), here and + // for cfg.files below. + jobs.Add("Copying asset passthrough files", [passthroughs = std::move(assetPassthroughs), &outputDir]() -> std::string { + for (const auto& [src, rel] : passthroughs) { + fs::path dst = outputDir / rel; + fs::create_directories(dst.parent_path()); + if (!fs::exists(dst)) { + fs::copy_file(src, dst); + } else if (fs::last_write_time(src) > fs::last_write_time(dst)) { + fs::copy_file(src, dst, fs::copy_options::overwrite_existing); } } + return {}; }); } for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile); - threads.emplace_back([&config, &outputDir, &buildCancelled, &buildError]() { - Progress::Task task(std::format("Copying files for {}", config.name)); - if (buildCancelled.load(std::memory_order_relaxed)) return; - try { - for (const fs::path& additionalFile : config.files) { - fs::path destination = outputDir / additionalFile.filename(); - if (fs::is_directory(additionalFile)) { - for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) { - const fs::path& sourcePath = entry.path(); - fs::path relativePath = fs::relative(sourcePath, additionalFile); - fs::path destPath = destination / relativePath; - if (entry.is_directory()) { - if (!fs::exists(destPath)) fs::create_directories(destPath); - } else if (entry.is_regular_file()) { - fs::create_directories(destPath.parent_path()); - if (!fs::exists(destPath)) { - fs::copy_file(sourcePath, destPath); - } else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) { - fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing); - } + jobs.Add(std::format("Copying files for {}", config.name), [&config, &outputDir]() -> std::string { + for (const fs::path& additionalFile : config.files) { + fs::path destination = outputDir / additionalFile.filename(); + if (fs::is_directory(additionalFile)) { + for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) { + const fs::path& sourcePath = entry.path(); + fs::path relativePath = fs::relative(sourcePath, additionalFile); + fs::path destPath = destination / relativePath; + if (entry.is_directory()) { + if (!fs::exists(destPath)) fs::create_directories(destPath); + } else if (entry.is_regular_file()) { + fs::create_directories(destPath.parent_path()); + if (!fs::exists(destPath)) { + fs::copy_file(sourcePath, destPath); + } else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) { + fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing); } } - } else { - if (!fs::exists(destination)) { - fs::copy_file(additionalFile, destination); - } else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) { - fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing); - } + } + } else { + if (!fs::exists(destination)) { + fs::copy_file(additionalFile, destination); + } else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) { + fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing); } } - } catch(std::exception& e) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = e.what(); - } } + return {}; }); std::vector externalResults(config.externalDependencies.size()); @@ -1054,7 +1043,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map built = OncePerPass(depResults, depMutex, dep->PcmDir(), [&] { return Build(*dep, depResults, depMutex); }); const BuildResult& result = built.get(); @@ -1146,20 +1131,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mappath.string(), e.what()); - } + jobs.Fail(std::format("dep build for {} threw: {}", dep->path.string(), e.what())); } }); } @@ -1196,17 +1173,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { - threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled, &config, &includeFlags, &defineFlags, &userFlags, &cArchFlags, <oCompileFlags]() { - Progress::Task task(std::format("Compiling {}.c", cFile.filename().string())); - if (buildCancelled.load(std::memory_order_relaxed)) return; - - std::string result = RunBuildCommand(std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())); - if (result.empty()) return; - - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); - } + jobs.Add(std::format("Compiling {}.c", cFile.filename().string()), [command = std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())] { + return RunBuildCommand(command); }); } } @@ -1225,23 +1193,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { const Toolchain& toolchain = GetToolchain(); if (toolchain.nvcc.empty()) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError); - } + jobs.Fail(std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError)); break; } - threads.emplace_back([&cFile, &buildError, &buildCancelled, &config, &toolchain, srcPath, objPath]() { - Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string())); - if (buildCancelled.load(std::memory_order_relaxed)) return; - - std::string result = RunBuildCommand(std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))); - if (result.empty()) return; - - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); - } + jobs.Add(std::format("Compiling {}.cu", cFile.filename().string()), [command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] { + return RunBuildCommand(command); }); } } @@ -1253,9 +1209,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map externalFloor) externalFloor = ext.latestArtifact; } - // Check every interface before compiling any of them. Module::Compile waits - // on the `compiled` flag of each sibling module it imports, and that flag is - // set either by a Compile that runs or by the Check that decides none is - // needed — so a Check still pending while another module's thread is already - // waiting would block on a flag nothing goes on to raise. - std::vector staleInterfaces; + // Check every interface before scheduling any of them. Schedule() puts a + // unit after the stale units it imports and reads their needsRecompiling + // for that, which a unit's own Check need not have set: a partition's + // returns at the first stale import it finds. for(std::unique_ptr& interface : config.interfaces) { if(interface->Check(pcmDir, externalFloor)) { - staleInterfaces.push_back(interface.get()); buildResult.repack = true; } files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string()); @@ -1406,45 +1359,24 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mappath.filename().string())); - try { - mod->Compile(command, pcmDir, buildDir, buildCancelled, buildError); - } catch (const std::exception& e) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::format("Module::Compile threw: {}", e.what()); - } - } - }); + // Every interface, and with each its partitions, not only the stale + // ones: a unit whose BMI is up to date can still be without the object + // made from it, which Schedule() then adds alone. No repack for that + // here: the link below runs again for an object newer than its output. + for(std::unique_ptr& interface : config.interfaces) { + interface->Schedule(jobs, command, pcmDir, buildDir); } for(Implementation& implementation : config.implementations) { if(implementation.Check(buildDir, pcmDir, externalFloor)) { buildResult.repack = true; - Implementation* impl = &implementation; - threads.emplace_back([impl, &command, &buildDir, &buildCancelled, &buildError]() { - Progress::Task task(std::format("Compiling {}.cpp", impl->path.filename().string())); - try { - impl->Compile(command, buildDir, buildCancelled, buildError); - } catch (const std::exception& e) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::format("Implementation::Compile threw: {}", e.what()); - } - } - }); + implementation.Schedule(jobs, command, pcmDir, buildDir); } files += std::format(" {}/{}_impl.o", buildDir.string(), implementation.path.filename().string()); } - for(std::thread& thread : threads) { - thread.join(); - } - - if(buildCancelled.load()) { - return {buildError, false, {}}; + if (std::string failed = jobs.Wait(); !failed.empty()) { + return {std::move(failed), false, {}}; } std::string linkExtras; @@ -2228,6 +2160,13 @@ object, and invokes its CrafterBuildProject() to obtain a Configuration that drives the build. Outputs land at bin/--/, intermediates at build/--/. +A build runs at most as many of its steps at once as the machine has hardware +threads: the compiles of its sources, its shaders and assets, and its links +and archives, counted together for the project and the dependencies it is +built on. An external dependency's CMake build is not among them, nor are the +tests `test` runs. A step counts as one whatever threads it starts for itself, +as a link and the compression of an asset do. + Build options: -r Run the produced executable after a successful build: one for the host in its own directory, a wasm32 one @@ -2244,7 +2183,9 @@ Build options: Test options (after the `test` subcommand): --list Enumerate matching tests without running them. - --jobs= Parallel job count (default: hardware_concurrency). + --jobs= Tests built and run at once (default: one per + hardware thread). The steps of their builds share + the one limit a build has. --timeout= Per-test timeout override. --runner= Override the test runner for this run. Specs: local diff --git a/implementations/Crafter.Build-Implementation.cpp b/implementations/Crafter.Build-Implementation.cpp index 6f0b355..afc0ecf 100644 --- a/implementations/Crafter.Build-Implementation.cpp +++ b/implementations/Crafter.Build-Implementation.cpp @@ -5,6 +5,7 @@ module Crafter.Build:Implementation_impl; import std; import :Implementation; import :Interface; +import :Jobs; import :Platform; namespace fs = std::filesystem; @@ -35,33 +36,22 @@ namespace Crafter { } return false; } - void Implementation::Compile(const std::string_view clang, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) const { + void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const { + std::vector after; for(ModulePartition* dependency : partitionDependencies) { - if(!dependency->compiled.load()) { - dependency->compiled.wait(false); - } + if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); } for(Module* dependency : moduleDependencies) { - if(!dependency->compiled.load()) { - dependency->compiled.wait(false); - } + if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); } - - if (buildCancelled.load(std::memory_order_relaxed)) { - return; - } - // -MD leaves _impl.o.d beside the object for Check to read, and // -fmodule-file-deps puts the BMIs the unit imported in it with the // headers. The driver adds that for --precompile only, so a std // module rebuilt in place, for a mingw-w64 or libc++ update under // the same compiler, left the objects importing it as they were, and // the next build only relinked them. - std::string result = RunBuildCommand(std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())); - - bool expected = false; - if(!result.empty() && buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); - } + jobs.Add(std::format("Compiling {}.cpp", path.filename().string()), [command = std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())] { + return RunBuildCommand(command); + }, after); } } diff --git a/implementations/Crafter.Build-Interface.cpp b/implementations/Crafter.Build-Interface.cpp index 2fb7b37..4a56fe0 100644 --- a/implementations/Crafter.Build-Interface.cpp +++ b/implementations/Crafter.Build-Interface.cpp @@ -4,11 +4,55 @@ module Crafter.Build:Interface_impl; import std; import :Interface; +import :Jobs; import :Platform; namespace fs = std::filesystem; +namespace { + // The job that makes an interface unit's object from its BMI, once the + // jobs in `after` have finished. The command is put together here, as in + // the functions below, so the job owns the one it runs. + void AddObjectJob(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span after) { + jobs.Add(std::format("Compiling {}.cppm", path.filename().string()), [command = std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())] { + return Crafter::RunBuildCommand(command); + }, after); + } + + // The two compiler runs of a stale interface unit, as jobs of `jobs`: its + // BMI once the jobs in `after` have finished, then its object from that + // BMI. Returns the first, the one the units importing this one come + // after: the object is the link's alone to wait for. + Crafter::JobGroup::Job AddInterfaceJobs(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span after) { + // -MD records every header the preamble pulled in, next to the BMI as + // .pcm.d, so the next Check can see an edit to one of them. + const Crafter::JobGroup::Job precompile = jobs.Add(std::format("Precompiling {}.cppm", path.filename().string()), [command = std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())] { + return Crafter::RunBuildCommand(command); + }, after); + const std::array precompiled = {precompile}; + AddObjectJob(jobs, clang, path, pcmDir, buildDir, precompiled); + return precompile; + } + + // For a unit whose BMI is up to date: the object job alone, when the + // object is missing or older than the BMI it is made from. The two are + // written by two commands, and a build can end between them: by an error + // elsewhere, which keeps the second from starting, by the second failing, + // or by being interrupted. An object written in the same tick of the + // file system's clock as its BMI is taken to be the later of the two, + // which it is whenever the command that writes it ran. + void AddObjectJobIfStale(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir) { + std::error_code ec; + const fs::file_time_type pcmTime = fs::last_write_time(std::format("{}.pcm", (pcmDir/path.filename()).string()), ec); + // No BMI to make it from; Check does not call such a unit up to date. + if (ec) return; + const fs::file_time_type objectTime = fs::last_write_time(std::format("{}.o", (buildDir/path.filename()).string()), ec); + if (!ec && objectTime >= pcmTime) return; + AddObjectJob(jobs, clang, path, pcmDir, buildDir, {}); + } +} + namespace Crafter { - ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} + ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {} bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { if(!checked) { @@ -44,11 +88,6 @@ namespace Crafter { } } needsRecompiling = false; - compiled.store(true); - // Nothing waits on `compiled` until the compile threads start, - // which is after every Check has run — but notify anyway so the - // flag is never left set without a wake-up behind it. - compiled.notify_all(); return false; } else { needsRecompiling = true; @@ -59,52 +98,25 @@ namespace Crafter { } } - void ModulePartition::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) { - for(ModulePartition* dependency : partitionDependencies) { - if(!dependency->compiled.load()) { - dependency->compiled.wait(false); + std::optional ModulePartition::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) { + if (scheduled) return precompileJob; + if (needsRecompiling) { + std::vector after; + for (ModulePartition* dependency : partitionDependencies) { + if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); } - } - for(Module* dependency : moduleDependencies) { - if(!dependency->compiled.load()) { - dependency->compiled.wait(false); - } - } - - if (buildCancelled.load(std::memory_order_relaxed)) { - compiled.store(true); - compiled.notify_all(); - return; - } - - // -MD records every header the preamble pulled in, next to the BMI as - // .pcm.d, so the next Check can see an edit to one of them. - std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())); - - if (!result.empty()) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); - compiled.store(true); - compiled.notify_all(); - return; - } - } - - compiled.store(true); - compiled.notify_all(); - - result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())); - - if (!result.empty()) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); + for (Module* dependency : moduleDependencies) { + if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); } + precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after); + } else { + AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir); } + scheduled = true; + return precompileJob; } - Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} + Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {} bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { if(!checked) { @@ -116,7 +128,7 @@ namespace Crafter { if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) { fs::file_time_type pcmTime = fs::last_write_time(pcmPath); // Every partition gets Check()ed even once one is known stale: - // Compile() drives partition rebuilds off their own + // Schedule() drives partition rebuilds off their own // needsRecompiling flags, so short-circuiting here would leave // the later ones unevaluated and silently unbuilt. bool depCheck = false; @@ -149,14 +161,12 @@ namespace Crafter { return true; } else { needsRecompiling = false; - compiled.store(true); - compiled.notify_all(); return false; } } else { // Already known stale, but the dependencies still need - // evaluating: an unchecked local module would never get built, - // and Compile() below waits on its `compiled` flag. + // evaluating: Schedule() below reads their needsRecompiling, + // and an unchecked local module would never get built. for(std::unique_ptr& partition : partitions) { partition->Check(pcmDir, sourceFloor); } @@ -171,60 +181,29 @@ namespace Crafter { } } - void Module::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) { - // A sibling module in the same Configuration that this interface unit - // imports has to have its PCM on disk before we precompile against it. - // Safe to block here: Build() Checks every interface before it spawns - // any compile thread, so a dependency that needs no rebuild already has - // `compiled` set and this returns immediately. - for(Module* dependency : moduleDependencies) { - if(!dependency->compiled.load()) { - dependency->compiled.wait(false); - } - } - - std::vector threads; - threads.reserve(partitions.size()); - for(std::unique_ptr& part : partitions) { - if(part->needsRecompiling) { - threads.emplace_back(&ModulePartition::Compile, part.get(), clang, pcmDir, buildDir, std::ref(buildCancelled), std::ref(buildError)); - } - } - - for(std::thread& thread : threads){ - thread.join(); - } - - if (buildCancelled.load(std::memory_order_relaxed)) { - compiled.store(true); - compiled.notify_all(); - return; - } - - // -MD records every header the preamble pulled in, next to the BMI as - // .pcm.d, so the next Check can see an edit to one of them. - std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())); - - if (!result.empty()) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); - compiled.store(true); - compiled.notify_all(); - return; - } - } - - compiled.store(true); - compiled.notify_all(); - - result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())); - - if (!result.empty()) { - bool expected = false; - if (buildCancelled.compare_exchange_strong(expected, true)) { - buildError = std::move(result); + std::optional Module::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) { + if (scheduled) return precompileJob; + std::vector after; + // All of the module's partitions, not the ones the primary interface + // names: the scanner records no edge for its `import :Part;` lines + // (see GetInterfacesAndImplementations). And of a module that is up + // to date as well: this is where its partitions are scheduled, and + // one of them may be without its object. + for (const std::unique_ptr& partition : partitions) { + if (const std::optional job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); + } + if (needsRecompiling) { + // A sibling module in the same Configuration that this interface + // unit imports has to have its PCM on disk before we precompile + // against it. + for (Module* dependency : moduleDependencies) { + if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); } + precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after); + } else { + AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir); } + scheduled = true; + return precompileJob; } } diff --git a/implementations/Crafter.Build-Jobs.cpp b/implementations/Crafter.Build-Jobs.cpp new file mode 100644 index 0000000..82b0835 --- /dev/null +++ b/implementations/Crafter.Build-Jobs.cpp @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +module Crafter.Build:Jobs_impl; +import std; +import :Jobs; +import :Progress; + +namespace { + // The pool this thread is a worker of; null on every other thread. + thread_local const Crafter::JobPool* WorkerOf = nullptr; +} + +namespace Crafter { + JobPool::JobPool(std::uint32_t workers) : limit(std::max(workers, 1u)) {} + + JobPool::~JobPool() { + { + std::lock_guard lock(mutex); + stopping = true; + } + wake.notify_all(); + for (std::thread& thread : threads) thread.join(); + } + + JobPool& JobPool::Process() { + static JobPool* const pool = new JobPool(std::thread::hardware_concurrency()); + return *pool; + } + + std::uint32_t JobPool::Workers() const { + return limit; + } + + void JobPool::Submit(std::function job) { + std::lock_guard lock(mutex); + queue.push_back(std::move(job)); + if (queue.size() <= idle || threads.size() >= limit) { + wake.notify_one(); + return; + } + try { + threads.emplace_back([this] { Work(); }); + } catch (...) { + // The system has no thread to give. The workers there are take + // the job when they get to it. With none it would stay queued + // for good, and whoever waits for it with it. + if (!threads.empty()) return; + queue.pop_back(); + throw; + } + } + + void JobPool::Work() { + WorkerOf = this; + std::unique_lock lock(mutex); + for (;;) { + while (queue.empty() && !stopping) { + ++idle; + wake.wait(lock); + --idle; + } + if (queue.empty()) return; + std::function job = std::move(queue.front()); + queue.pop_front(); + lock.unlock(); + job(); + // Before the lock is taken again: what the job captured is + // released without holding up the queue. + job = nullptr; + lock.lock(); + } + } + + void JobPool::Run(const std::function& work) { + if (WorkerOf == this) { + work(); + return; + } + // Shared with the job, not a local of this function: this thread + // goes on as soon as the value is set, which is before set_value has + // returned on the worker. + const std::shared_ptr> done = std::make_shared>(); + std::future finished = done->get_future(); + Submit([&work, done] { + try { + work(); + done->set_value(); + } catch (...) { + done->set_exception(std::current_exception()); + } + }); + finished.get(); + } + + struct JobGroup::Node { + std::string label; + std::function work; + std::unique_ptr task; + // The jobs added after this one that it has yet to release, and how + // many jobs this one still waits for. Both under the group's mutex; + // the members above belong to whoever runs the job. + std::vector dependents; + std::size_t waiting = 0; + bool finished = false; + }; + + JobGroup::JobGroup(JobPool& pool) : pool(pool) { + if (WorkerOf == &pool) throw std::logic_error("a JobGroup cannot be made on a worker of its own pool: it would wait there for jobs that need that worker"); + } + + JobGroup::~JobGroup() { + std::unique_lock lock(mutex); + failed = true; + settled.wait(lock, [this] { return unfinished == 0; }); + } + + JobGroup::Job JobGroup::Add(std::string label, std::function work, std::span after) { + std::unique_ptr made = std::make_unique(); + // Counted from here on, not from when it starts: the total a build + // shows is then what it has queued, and not only what the workers + // have got to. + made->task = std::make_unique(label); + made->label = std::move(label); + made->work = std::move(work); + + std::lock_guard lock(mutex); + // Room for the new job in each list it may join, made before the + // group knows of it: from there to the count below nothing can throw, + // so no job is ever waited on by half of what it comes after. + for (const Job job : after) { + if (job >= nodes.size()) throw std::out_of_range("JobGroup::Add: a job can only come after jobs added before it"); + std::vector& dependents = nodes[job]->dependents; + dependents.reserve(dependents.size() + after.size()); + } + const Job id = nodes.size(); + Node& node = *nodes.emplace_back(std::move(made)); + for (const Job job : after) { + Node& before = *nodes[job]; + if (before.finished) continue; + before.dependents.push_back(&node); + ++node.waiting; + } + ++unfinished; + if (node.waiting != 0) return id; + try { + Start(node); + } catch (...) { + // Not queued (JobPool::Submit), so nothing will ever finish it: + // it is taken back, or Wait() would never return. + node.work = nullptr; + node.task.reset(); + node.finished = true; + if (--unfinished == 0) settled.notify_all(); + throw; + } + return id; + } + + void JobGroup::Start(Node& node) { + pool.Submit([this, &node] { Execute(node); }); + } + + void JobGroup::Execute(Node& node) { + bool skipped = false; + { + std::lock_guard lock(mutex); + skipped = failed; + } + std::string result; + if (!skipped) { + try { + result = node.work(); + } catch (const std::exception& e) { + result = std::format("{}: {}", node.label, e.what()); + } catch (...) { + result = std::format("{}: threw something that isn't a std::exception", node.label); + } + } + // Both before the group hears of it: what the work captured is gone, + // and the step counted as done, by the time Wait() returns. + node.work = nullptr; + node.task.reset(); + + // Nothing of the group is touched once this lock is released: with + // the last job finished, whoever waited may destroy it. + std::lock_guard lock(mutex); + if (!result.empty() && !failed) { + failed = true; + error = std::move(result); + } + node.finished = true; + // Released after a failure as well: they are skipped when they run, + // which is what counts them as finished. + for (Node* dependent : node.dependents) { + if (--dependent->waiting == 0) Start(*dependent); + } + if (--unfinished == 0) settled.notify_all(); + } + + void JobGroup::Fail(std::string why) { + std::lock_guard lock(mutex); + if (failed) return; + failed = true; + error = std::move(why); + } + + bool JobGroup::Failed() const { + std::lock_guard lock(mutex); + return failed; + } + + std::string JobGroup::Wait() { + std::unique_lock lock(mutex); + settled.wait(lock, [this] { return unfinished == 0; }); + return error; + } +} diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index b7c001a..2c47d92 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -18,6 +18,7 @@ import :Toolchain; import :Clang; import :Interface; import :External; +import :Jobs; import :Progress; namespace fs = std::filesystem; using namespace Crafter; @@ -25,7 +26,7 @@ using namespace Crafter; namespace { // Exclusive advisory lock over one PCM cache dir (`/-/`), // held for the duration of a (re)build. Concurrent crafter-build invocations — - // and the worker threads inside a single invocation — that share a cache + // and the threads of a single invocation that build at once — that share a cache // serialize their builds through it: the first builder to acquire the lock // precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else // blocks, then re-checks freshness and reuses the finished file instead of @@ -276,34 +277,46 @@ bool Crafter::MatchAny(std::span globs, std::string_view name return false; } -// See the declaration in Crafter.Build-Platform.cppm for why this branches on -// the exit code rather than on whether the command said anything. +namespace { + // RunBuildCommand's command, run on the thread that calls. See the + // declaration in Crafter.Build-Platform.cppm for why this branches on the + // exit code rather than on whether the command said anything. + std::string RunBuildStep(std::string_view cmd) { + Progress::EchoCommand(cmd); + CommandResult r = RunCommandChecked(cmd); + // A mingw build against a system prefix sees mingw-w64 through a view in + // the cache, and clang names every header by the path it found it at. + r.output = MingwViewToPrefix(std::move(r.output)); + + if (r.exitCode == 0) { + // Warnings from a step that succeeded. Show them — until now they were + // invisible on an incremental build and fatal on a cold one. + if (!r.output.empty()) Progress::Diagnostic(r.output); + return ""; + } + + // A compiler killed outright (the OOM killer is the common one) prints + // nothing, so the old "output means failure" rule read it as success and + // let the build carry on with a missing object. Say what happened instead. + if (r.output.empty()) { + return r.crashed + ? std::format("terminated by signal {}: {}", r.signal, cmd) + : std::format("exited with code {}: {}", r.exitCode, cmd); + } + if (r.crashed) { + return std::format("{}\nterminated by signal {}", r.output, r.signal); + } + return r.output; + } +} + std::string Crafter::RunBuildCommand(std::string_view cmd) { - Progress::EchoCommand(cmd); - CommandResult r = RunCommandChecked(cmd); - // A mingw build against a system prefix sees mingw-w64 through a view in - // the cache, and clang names every header by the path it found it at. - r.output = MingwViewToPrefix(std::move(r.output)); - - if (r.exitCode == 0) { - // Warnings from a step that succeeded. Show them — until now they were - // invisible on an incremental build and fatal on a cold one. - if (!r.output.empty()) Progress::Diagnostic(r.output); - return ""; - } - - // A compiler killed outright (the OOM killer is the common one) prints - // nothing, so the old "output means failure" rule read it as success and - // let the build carry on with a missing object. Say what happened instead. - if (r.output.empty()) { - return r.crashed - ? std::format("terminated by signal {}: {}", r.signal, cmd) - : std::format("exited with code {}: {}", r.exitCode, cmd); - } - if (r.crashed) { - return std::format("{}\nterminated by signal {}", r.output, r.signal); - } - return r.output; + // A job is on a worker already and runs the command where it is. A link, + // or the precompile of the std module, comes from the thread of a Build() + // or a LoadProject and waits here for its turn among the jobs. + std::string result; + JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); }); + return result; } // --- Dependencies of project.cpp itself ------------------------------------- @@ -874,7 +887,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { // and, when clang finds no gcc directory, an empty entry that would // name a manifest in the working directory. A toolchain that isn't // there is a build error, not an exception: Build() runs this with - // its worker threads started. + // the threads of its external dependencies started. const Toolchain& tc = GetToolchain(); const std::string where = tc.mingwPrefix.empty() ? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH") @@ -995,11 +1008,12 @@ std::string Crafter::GetBaseCommand(const Configuration& config) { } namespace { - constexpr std::array CrafterBuildModules = { + constexpr std::array CrafterBuildModules = { "Crafter.Build-Toolchain", "Crafter.Build-Shader", "Crafter.Build-Platform", "Crafter.Build-Flatpak", + "Crafter.Build-Jobs", "Crafter.Build-Interface", "Crafter.Build-Implementation", "Crafter.Build-External", diff --git a/interfaces/Crafter.Build-Implementation.cppm b/interfaces/Crafter.Build-Implementation.cppm index 7c9c631..f6e06a7 100644 --- a/interfaces/Crafter.Build-Implementation.cppm +++ b/interfaces/Crafter.Build-Implementation.cppm @@ -3,6 +3,7 @@ export module Crafter.Build:Implementation; import std; +import :Jobs; namespace fs = std::filesystem; namespace Crafter { @@ -19,6 +20,9 @@ namespace Crafter { fs::path path; Implementation(fs::path&& path); bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const; - void Compile(const std::string_view clang, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) const; + // Adds the job that compiles this unit to `jobs`, after the BMIs of + // the stale interface units it imports (ModulePartition::Schedule, + // Module::Schedule). For a unit Check found stale. + void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const; }; } diff --git a/interfaces/Crafter.Build-Interface.cppm b/interfaces/Crafter.Build-Interface.cppm index 27eb298..dcfe960 100644 --- a/interfaces/Crafter.Build-Interface.cppm +++ b/interfaces/Crafter.Build-Interface.cppm @@ -3,6 +3,7 @@ export module Crafter.Build:Interface; import std; +import :Jobs; namespace fs = std::filesystem; namespace Crafter { @@ -19,14 +20,38 @@ namespace Crafter { // GetInterfacesAndImplementations still produces a staleness edge. // Names that never resolve (`std`, module-mapped externals) stay here. std::vector pendingImports; - std::atomic compiled; + // The state of one Build(), which clears it before it checks: whether + // Check has run, what it found, whether Schedule has added this + // unit's jobs, and the one among them that writes its BMI, which is + // the job the units importing it come after. bool needsRecompiling = false; bool checked = false; + bool scheduled = false; + std::optional precompileJob; std::string name; fs::path path; ModulePartition(std::string&& name, fs::path&& path); + // Whether this unit's BMI has to be written again. The object made + // from the BMI is not Check's to judge: see Schedule. bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()); - void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError); + // Adds the jobs this unit needs to `jobs`, once however often it is + // called, and returns the one that writes its BMI, if there is one. + // + // A unit Check found stale gets two, one for each run of `clang`: the + // BMI, after the BMIs of the stale units this one imports, which are + // scheduled here as well, and then the object from that BMI, which + // only the link waits for, so that the units importing this one start + // when the first is done. + // + // A unit whose BMI is up to date gets the second job alone when its + // object is missing or older than the BMI. A build that fails or is + // interrupted between the two leaves a unit like that, and by its BMI + // alone every build after it would call the unit built: the link then + // took the object of the source before the edit, or found none. + // + // Every unit this one imports must have been checked: Build() checks + // all of a configuration's interfaces before it schedules any. + std::optional Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir); }; export class Module { @@ -34,20 +59,27 @@ namespace Crafter { // A primary module interface unit imports things too — `import Base;` // in `export module Widget;` is as much a layout dependency as the // same line in a partition. Recorded on the same three vectors, with - // the same meanings, so Check() can see through them and Compile() + // the same meanings, so Check() can see through them and Schedule() // can order itself behind a sibling module in the same Configuration // (issue #26). std::vector moduleDependencies; std::vector> externalModuleDependencies; std::vector pendingImports; - std::atomic compiled; + // As in ModulePartition. bool needsRecompiling = false; bool checked = false; + bool scheduled = false; + std::optional precompileJob; std::vector> partitions; std::string name; fs::path path; Module(std::string&& name, fs::path&& path); bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()); - void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError); + // As ModulePartition::Schedule, for the primary interface, and + // schedules every partition of the module with it. The primary + // interface comes after every stale partition of the module, + // whichever of them it imports, and after the stale sibling modules + // it imports. + std::optional Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir); }; } diff --git a/interfaces/Crafter.Build-Jobs.cppm b/interfaces/Crafter.Build-Jobs.cppm new file mode 100644 index 0000000..c436145 --- /dev/null +++ b/interfaces/Crafter.Build-Jobs.cppm @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Crafter.Build:Jobs; +import std; + +export namespace Crafter { + // The threads build steps run on: a fixed number of workers taking jobs + // from one queue, so that no more steps run at once than there are + // workers, whichever builds they belong to. Process() is the pool every + // build in this process shares, with a worker per hardware thread. + // + // A job is one step of a build: one compiler, linker or archiver run, one + // shader or asset compiled in process. The pool bounds the steps that run + // at once, not the threads a step starts for itself, as lld does for a + // link and the compressor of Crafter.Asset for an asset. + // + // A job never waits for another job. Whatever waits does so on a + // thread that is not a worker: a Build() for the builds of its + // dependencies, a step for the steps it comes after (JobGroup holds it + // back instead). A worker that waited for a job still in the queue would + // keep from it the very thread it needs, and with every worker waiting + // like that nothing would run again. + // + // Before this, Build() started a thread for every stale shader, asset + // to compress, C, CUDA and C++ unit, and nothing bounded how many of + // them ran at once. + class JobPool { + public: + // At most `workers` jobs at once, at least one. The threads are + // started as jobs need them: a build with two stale files starts two. + explicit JobPool(std::uint32_t workers); + // Runs what is still queued, then joins the workers. Nothing may be + // handing it jobs any more: every group on it is gone by then. + ~JobPool(); + JobPool(const JobPool&) = delete; + JobPool& operator=(const JobPool&) = delete; + + // The pool of this process: one worker per hardware thread + // (std::thread::hardware_concurrency), and one where that is not + // known. Never destroyed, so that its workers are not joined while + // the statics the last job may still be using are being destroyed. + static JobPool& Process(); + + std::uint32_t Workers() const; + + // Runs `work` on a worker and returns when it has finished; what it + // throws is thrown here. For a step that stands by itself, as + // RunBuildCommand uses it for a link. Called on a worker of this + // pool it runs `work` there and then, since that thread is the one + // the step would have occupied. + void Run(const std::function& work); + + private: + friend class JobGroup; + // Queues `job`, which must not throw. Throws only when the pool has + // no thread and cannot start one, and then `job` is not queued. + void Submit(std::function job); + void Work(); + + const std::uint32_t limit; + std::mutex mutex; + std::condition_variable wake; + std::deque> queue; + std::vector threads; + // Workers waiting for a job. A job queued while one waits is its to + // take, so a thread is only started for a job beyond those. + std::uint32_t idle = 0; + bool stopping = false; + }; + + // The jobs of one piece of work, such as the build of a configuration, + // on the workers of a pool. A job starts once every job it was added + // after has finished, so the order steps need (a unit after the BMIs it + // imports) costs no thread while it is waited for. + // + // The first job to fail fails the group: no job of it starts after that, + // the ones already running finish, and Wait() returns that first error. + // Fail() does the same for work done outside the jobs, so one group + // holds the outcome of everything a build runs at once. + class JobGroup { + public: + using Job = std::size_t; + + // Throws std::logic_error on a worker of `pool`: a job that waited + // for jobs of its own would occupy a worker they need (see JobPool). + explicit JobGroup(JobPool& pool = JobPool::Process()); + // Keeps what has not started from starting and waits for what is + // running, so a job never outlives what it was given by reference, + // whichever way the scope that made the group is left. + ~JobGroup(); + JobGroup(const JobGroup&) = delete; + JobGroup& operator=(const JobGroup&) = delete; + + // Adds a job, counted as a Progress::Task under `label` from now + // until it has finished or been skipped. It starts once every job in + // `after` has finished, at once when there is none; `after` names + // jobs of this group, so a job can only come after ones added before + // it and no two can wait for each other. `work` returns what went + // wrong, empty when nothing did; an exception it throws is its error + // too. It runs on a worker: it must not wait for other jobs, and it + // must own what it uses or use only what outlives the group. + Job Add(std::string label, std::function work, std::span after = {}); + + // Fails the group with `error`, as a job returning it would. Without + // effect on a group that has already failed. + void Fail(std::string error); + bool Failed() const; + + // Returns once every job added so far has finished or been skipped: + // the first error, empty when there was none. + std::string Wait(); + + private: + struct Node; + void Start(Node& node); + void Execute(Node& node); + + JobPool& pool; + mutable std::mutex mutex; + std::condition_variable settled; + // Owned through pointers: a job on a worker holds on to its node + // while Add() grows the vector. + std::vector> nodes; + std::size_t unfinished = 0; + bool failed = false; + std::string error; + }; +} diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index dbdc64d..ace7947 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -42,6 +42,11 @@ namespace Crafter { // Returns an empty string on success (any warnings go to the user via // Progress::Diagnostic), otherwise the compiler's diagnostics. Callers // therefore keep the `if (!result.empty())` shape they already had. + // + // The command runs on a worker of JobPool::Process(), so no more of these + // steps run at once than that pool has workers: called on one of its + // workers it runs there, called from any other thread it waits for one. + // A step that runs a compiler any other way is not counted. std::string RunBuildCommand(std::string_view command); export CommandResult RunCommandWithTimeout(std::string_view command, std::chrono::seconds timeout); // Runs `command` through sh with this process's own stdin, stdout and diff --git a/interfaces/Crafter.Build-Progress.cppm b/interfaces/Crafter.Build-Progress.cppm index 123e53b..2dc173f 100644 --- a/interfaces/Crafter.Build-Progress.cppm +++ b/interfaces/Crafter.Build-Progress.cppm @@ -12,8 +12,10 @@ export namespace Crafter::Progress { // RAII work-unit marker. Construction inflates the running total; destruction // increments completed and (on Default + TTY) redraws the status line. Move - // semantics are disabled — keep these as plain stack locals inside the worker - // lambda so the destructor fires when that thread's work ends. + // semantics are disabled — keep these as plain stack locals around the work + // they count, so the destructor fires when it ends. A job of a JobGroup + // gets one from Add(), made when the job is queued, which is what puts + // work that has not started yet in the total. class Task { public: explicit Task(std::string label); diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index 52f1d1c..d08d51f 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -57,6 +57,10 @@ export namespace Crafter { struct RunTestsOptions { std::vector globs; + // Tests built and run at once, from --jobs=; 0 is one per hardware + // thread. It counts tests, not build steps: the steps of their builds + // run on JobPool::Process() under that pool's own limit, and a test + // that is running is not one of them. std::int32_t jobs = 0; std::optional timeoutOverride; bool listOnly = false; diff --git a/interfaces/Crafter.Build.cppm b/interfaces/Crafter.Build.cppm index 03fbe44..220f823 100644 --- a/interfaces/Crafter.Build.cppm +++ b/interfaces/Crafter.Build.cppm @@ -6,6 +6,7 @@ export import :Toolchain; export import :Flatpak; export import :Clang; export import :Platform; +export import :Jobs; export import :Implementation; export import :Shader; export import :External; diff --git a/project.cpp b/project.cpp index 6674515..82eb74b 100644 --- a/project.cpp +++ b/project.cpp @@ -173,12 +173,13 @@ extern "C" Configuration CrafterBuildProject(std::span a // it reaches clang, which must still see a string literal. CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)}); { - std::array interfaces = { + std::array interfaces = { "interfaces/Crafter.Build", "interfaces/Crafter.Build-Toolchain", "interfaces/Crafter.Build-Shader", "interfaces/Crafter.Build-Platform", "interfaces/Crafter.Build-Flatpak", + "interfaces/Crafter.Build-Jobs", "interfaces/Crafter.Build-Interface", "interfaces/Crafter.Build-Implementation", "interfaces/Crafter.Build-External", @@ -190,11 +191,12 @@ extern "C" Configuration CrafterBuildProject(std::span a "interfaces/Crafter.Build-Progress", "interfaces/Crafter.Build-Asset", }; - std::array implementations = { + std::array implementations = { "implementations/Crafter.Build-Toolchain", "implementations/Crafter.Build-Shader", "implementations/Crafter.Build-Platform", "implementations/Crafter.Build-Flatpak", + "implementations/Crafter.Build-Jobs", "implementations/Crafter.Build-Interface", "implementations/Crafter.Build-Implementation", "implementations/Crafter.Build-External", diff --git a/tests/ConcurrentDependencyReset/fixture/deplib/DepMod-impl.cpp b/tests/ConcurrentDependencyReset/fixture/deplib/DepMod-impl.cpp index 465669d..96ca119 100644 --- a/tests/ConcurrentDependencyReset/fixture/deplib/DepMod-impl.cpp +++ b/tests/ConcurrentDependencyReset/fixture/deplib/DepMod-impl.cpp @@ -5,6 +5,8 @@ module DepMod; // Implementation unit of the DepMod interface. Because it declares // `module DepMod;` it gains an intra-config module dependency on the DepMod -// interface, so its compile waits on DepMod's `compiled` flag — the exact -// flag a stale recursive reset used to clobber (issue #16). +// interface, so its compile job comes after the job that writes DepMod's BMI +// (Implementation::Schedule), which reads DepMod's per-build state: what a +// recursive reset would clear. Its compile used to wait on DepMod's +// `compiled` flag, the flag such a reset clobbered (issue #16). int dep_value() { return 21; } diff --git a/tests/ConcurrentDependencyReset/main.cpp b/tests/ConcurrentDependencyReset/main.cpp index 792da50..5a59330 100644 --- a/tests/ConcurrentDependencyReset/main.cpp +++ b/tests/ConcurrentDependencyReset/main.cpp @@ -8,26 +8,33 @@ using namespace Crafter; // Regression for the concurrent dependency-reset deadlock (issue #16). // -// Build() resets each Module/ModulePartition's per-build `compiled` /`checked` -// flags so a reused Configuration re-evaluates mtimes. That reset MUST stay -// scoped to the configuration being built. It used to recurse into -// cfg.dependencies — but dependency Configurations are shared across the build -// DAG and each is compiled concurrently by its own Build() call. A parent's -// recursive reset could therefore clear a dependency's module `compiled` flag +// Build() resets each Module/ModulePartition's per-build state (`checked`, +// `scheduled` and the job that precompiles the unit) so a reused Configuration +// re-evaluates mtimes. That reset MUST stay scoped to the configuration being +// built. It used to recurse into cfg.dependencies — but dependency +// Configurations are shared across the build DAG and each is built +// concurrently by its own Build() call. Every unit then had a thread of its +// own and a `compiled` flag that the units importing it waited on, and a +// parent's recursive reset could clear a dependency's module `compiled` flag // *after* that dependency's module-compile thread had set it true and exited, // but before an intra-config waiter (its impl / a dependent partition) ran // `compiled.wait(false)`. The waiter then blocked forever on a flag nothing // re-signalled: the build froze mid-compile, idle, with no compiler process // alive. // +// Units are jobs now and wait on no flag, but the state is still the building +// configuration's alone: cleared from outside between two Schedule() calls of +// its own build, a unit is scheduled twice and compiled twice at once. +// // This test pins the invariant deterministically, without depending on thread -// timing: build a static-lib dependency fully (its module ends up compiled), -// then build a consumer that depends on it while the dependency is already -// cached in depResults (so it is NOT rebuilt). Before the fix, the consumer's -// recursive reset flipped the dependency's module `compiled` flag back to false -// and, because the dependency never rebuilds, it stayed false. After the fix -// the consumer resets only its own modules, so the dependency's flag is left -// intact. We assert it is still set once the consumer build completes. +// timing: build a static-lib dependency fully (its module ends up checked and +// scheduled), then build a consumer that depends on it while the dependency is +// already cached in depResults (so it is NOT rebuilt). A consumer that reset +// its dependencies would flip the dependency's module `checked` and +// `scheduled` flags back to false and, because the dependency never rebuilds, +// they would stay false. The consumer resets only its own modules, so the +// dependency's flags are left intact. We assert both are still set once the +// consumer build completes. int main() { fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture"; @@ -64,8 +71,8 @@ int main() { std::println(std::cerr, "dependency build failed: {}", r.result); return 1; } - if (!dep.interfaces[0]->compiled.load()) { - std::println(std::cerr, "dependency module not marked compiled after its own build"); + if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) { + std::println(std::cerr, "dependency module not marked checked and scheduled after its own build"); return 1; } // Seed a consumer-facing cache so the consumer reuses this build instead @@ -98,10 +105,9 @@ int main() { } // The core regression assertion: building the consumer must not have - // reset the (cached, never-rebuilt) dependency's module flag. Before the - // fix this was false and an intra-config waiter would have deadlocked. - if (!dep.interfaces[0]->compiled.load()) { - std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module 'compiled' " "flag (issue #16 regression) — this is the state that deadlocks a " "concurrent build"); + // reset the (cached, never-rebuilt) dependency's module state. + if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) { + std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module state " "(issue #16 regression): done while that dependency is building, " "this compiles its units twice at once"); return 1; } diff --git a/tests/TransitiveInterfaceChange/main.cpp b/tests/TransitiveInterfaceChange/main.cpp index 4476d6e..1449319 100644 --- a/tests/TransitiveInterfaceChange/main.cpp +++ b/tests/TransitiveInterfaceChange/main.cpp @@ -17,12 +17,12 @@ using namespace Crafter; // layouts with no diagnostic. That is the reported failure: rebuild the // dependency, relink the test, crash somewhere unrelated. // -// * `Module::Compile` waited on nothing. Two modules in one Configuration -// compile on concurrent threads, so importing a sibling was a coin flip -// between working and "module 'Base' not found". +// * `Module::Compile`, as it was then, waited on nothing. Two modules in +// one Configuration compiled on concurrent threads, so importing a sibling +// was a coin flip between working and "module 'Base' not found". // // Partitions never had either problem — they carry the same three vectors and -// Check/Compile honour them — which is why the gap only shows up on a module +// Check/Schedule honour them — which is why the gap only shows up on a module // whose interface is one flat unit. tests/IncrementalInterfaceChange covers the // neighbouring consumer-side edge (issue #27). From 6087ce81dbb49e2f80733253279f944516aa8471 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:55 +0100 Subject: [PATCH 15/53] test(build): build many units at once and count the threads it takes JobLimit makes two projects and one more for every 32 hardware threads and builds them from nothing at once, each from a thread of its own, as RunTests builds its tests, while it counts the threads of its own process. A project is 69 sources: 64 that import nothing, half C and half C++, then a module of two partitions, one importing the other, with its implementation unit, and a main.cpp that imports the module. It is the same size on every machine, so that no command of its build grows with the machine. The builds together may add as many threads as the machine has hardware threads, and have to add at least two where there are two; every program is then run and has to print 995: what its 64 C and C++ functions return and the module's Top(), which is built on the two partitions' functions. On 5b75df3 it fails: on a machine with 56 hardware threads, "3 builds of 207 sources in all ran on 205 threads at once". The count sees the steps that are jobs. A link is none: its Build() runs it through RunBuildCommand from a thread that was there before the count, which does not tell whether the link waited for a worker. JobGroup drives pools of its own, of one to four workers. Twelve jobs on three workers run three at once and no more; a job starts after the ones it was added after, in a graph of four jobs and in one of 300; the first error keeps a job that comes after it and the jobs added later from starting, and so does Fail(); what a job throws is its error; a chain gets through one worker; Run() runs its work on a worker, on the calling thread when that is one, where a JobGroup is refused; and leaving a group's scope waits for the job that runs and starts no other. It also holds the process's pool to a worker per hardware thread. --- project.cpp | 2 + tests/JobGroup/main.cpp | 308 ++++++++++++++++++++++++++++++++++++++++ tests/JobLimit/main.cpp | 177 +++++++++++++++++++++++ 3 files changed, 487 insertions(+) create mode 100644 tests/JobGroup/main.cpp create mode 100644 tests/JobLimit/main.cpp diff --git a/project.cpp b/project.cpp index 82eb74b..f3518dd 100644 --- a/project.cpp +++ b/project.cpp @@ -334,6 +334,8 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); } diff --git a/tests/JobGroup/main.cpp b/tests/JobGroup/main.cpp new file mode 100644 index 0000000..970837b --- /dev/null +++ b/tests/JobGroup/main.cpp @@ -0,0 +1,308 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// JobPool and JobGroup, which every build step runs on. A pool runs as many +// jobs at once as it has workers and no more; a job of a group starts when the +// jobs it was added after have finished; the first error keeps what has not +// started from starting; and nothing that waits for jobs does so on a worker, +// where it would keep from them the thread they need. +// +// The pools here are the test's own, of one to four workers, so what is +// counted does not depend on the machine. Build() runs on the process's pool: +// tests/JobLimit holds a whole build to that one. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // Twelve jobs on three workers. Each holds its worker until three run at + // once, so the pool is seen to reach its limit however the threads are + // scheduled, and then a moment longer with the lock released, counted as + // running all the while: jobs a pool let in beyond its workers would be + // counted on top of the ones in that moment. A pool that never gets to + // three is waited on once, then given up on. + void RunsAsManyAsItHasWorkers() { + constexpr std::int32_t workers = 3; + constexpr std::int32_t count = 12; + JobPool pool(workers); + std::mutex mutex; + std::condition_variable changed; + std::int32_t running = 0; + std::int32_t peak = 0; + std::int32_t ran = 0; + bool gaveUp = false; + JobGroup jobs(pool); + for (std::int32_t i = 0; i < count; ++i) { + jobs.Add(std::format("gauge {}", i), [&]() -> std::string { + std::unique_lock lock(mutex); + ++running; + peak = std::max(peak, running); + changed.notify_all(); + if (!changed.wait_for(lock, std::chrono::seconds(20), [&] { return peak >= workers || gaveUp; })) gaveUp = true; + lock.unlock(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + lock.lock(); + --running; + ++ran; + return {}; + }); + } + Check(jobs.Wait().empty(), "jobs that return nothing leave the group without an error"); + Check(ran == count, std::format("every job runs: {} of {} did", ran, count)); + Check(peak == workers, std::format("a pool of {} workers runs {} jobs at once, not {}", workers, workers, peak)); + } + + // a, then b and c, then d: each records when it runs. The ones that + // others wait for take a moment first, so a group that started everything + // at once would record them last. + void StartsAJobAfterTheOnesItComesAfter() { + JobPool pool(3); + std::mutex mutex; + std::vector order; + const auto record = [&mutex, &order](std::string name, std::int32_t milliseconds) { + return [&mutex, &order, name = std::move(name), milliseconds]() -> std::string { + std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); + std::lock_guard lock(mutex); + order.push_back(name); + return {}; + }; + }; + const auto position = [&order](std::string_view name) { + return std::ranges::find(order, name) - order.begin(); + }; + JobGroup jobs(pool); + const JobGroup::Job a = jobs.Add("a", record("a", 60)); + const std::array afterA = {a}; + const JobGroup::Job b = jobs.Add("b", record("b", 30), afterA); + const JobGroup::Job c = jobs.Add("c", record("c", 0), afterA); + const std::array afterBoth = {b, c}; + const JobGroup::Job d = jobs.Add("d", record("d", 0), afterBoth); + Check(jobs.Wait().empty(), "the ordered jobs leave no error"); + Check(order.size() == 4, std::format("all four ordered jobs run: {}", order)); + Check(position("a") < position("b") && position("a") < position("c"), std::format("b and c start after a has finished: {}", order)); + Check(position("b") < position("d") && position("c") < position("d"), std::format("d starts after both b and c have finished: {}", order)); + + // After jobs that finished long ago: nothing is left to release it, + // so it has to start by itself. + const std::array afterDone = {a, d}; + jobs.Add("e", record("e", 0), afterDone); + Check(jobs.Wait().empty() && order.size() == 5, std::format("a job added after finished jobs runs: {}", order)); + + bool refused = false; + try { + const std::array afterNone = {JobGroup::Job(99)}; + jobs.Add("f", record("f", 0), afterNone); + } catch (const std::out_of_range&) { + refused = true; + } + Check(refused, "a job cannot be added after one the group does not have"); + Check(jobs.Wait().empty() && order.size() == 5, std::format("the refused job never runs: {}", order)); + } + + // Three hundred jobs on four workers, each after up to three picked among + // the ones added before it, the same pick every run: every job runs + // once, and none before a job it comes after has finished. + void KeepsTheOrderOfALargerGraph() { + constexpr std::int32_t count = 300; + JobPool pool(4); + std::vector> runs(count); + std::atomic early{0}; + std::mt19937 random(20261112); + JobGroup jobs(pool); + std::vector added; + for (std::int32_t i = 0; i < count; ++i) { + std::vector after; + std::vector before; + for (std::int32_t pick = 0; i > 0 && pick < 3; ++pick) { + if (random() % 2 == 0) continue; + const std::int32_t chosen = static_cast(random() % static_cast(i)); + after.push_back(added[chosen]); + before.push_back(chosen); + } + added.push_back(jobs.Add(std::format("node {}", i), [&runs, &early, before = std::move(before), i]() -> std::string { + for (const std::int32_t earlier : before) { + if (runs[earlier].load() != 1) ++early; + } + ++runs[i]; + return {}; + }, after)); + } + Check(jobs.Wait().empty(), "the larger graph leaves no error"); + const std::int64_t once = std::ranges::count_if(runs, [](const std::atomic& ran) { return ran.load() == 1; }); + Check(once == count, std::format("each of {} jobs runs once: {} did", count, once)); + Check(early.load() == 0, std::format("no job starts before the ones it comes after have finished: {} did", early.load())); + } + + void TheFirstErrorStopsTheRest() { + JobPool pool(2); + { + JobGroup jobs(pool); + std::atomic dependentRan{false}; + std::atomic lateRan{false}; + const JobGroup::Job failing = jobs.Add("failing", [] { return std::string("boom"); }); + const std::array afterFailing = {failing}; + jobs.Add("dependent", [&dependentRan]() -> std::string { + dependentRan = true; + return {}; + }, afterFailing); + Check(jobs.Wait() == "boom", "Wait returns what the failed job returned"); + Check(jobs.Failed(), "a group with a failed job has failed"); + Check(!dependentRan, "a job that comes after a failed one does not run"); + jobs.Add("late", [&lateRan]() -> std::string { + lateRan = true; + return {}; + }); + jobs.Add("second", [] { return std::string("second"); }); + Check(jobs.Wait() == "boom", "the first error stays the group's error"); + Check(!lateRan, "a job added to a failed group does not run"); + } + { + JobGroup jobs(pool); + jobs.Add("thrower", []() -> std::string { throw std::runtime_error("bang"); }); + const std::string error = jobs.Wait(); + Check(error == "thrower: bang", std::format("what a job throws is its error, under its label: '{}'", error)); + } + { + JobGroup jobs(pool); + std::atomic ran{false}; + Check(!jobs.Failed(), "a new group has not failed"); + jobs.Fail("outside"); + jobs.Fail("again"); + jobs.Add("after", [&ran]() -> std::string { + ran = true; + return {}; + }); + Check(jobs.Wait() == "outside", "Fail gives the group its error, the first time"); + Check(!ran, "no job starts in a group failed from outside"); + } + } + + // One worker and jobs that wait for each other: a job held back costs no + // thread, so the chain gets through on the one there is. + void OneWorkerIsEnough() { + JobPool pool(1); + std::mutex mutex; + std::int32_t running = 0; + std::int32_t peak = 0; + std::vector order; + JobGroup jobs(pool); + std::vector previous; + for (std::int32_t i = 0; i < 6; ++i) { + const auto work = [&mutex, &running, &peak, &order, i]() -> std::string { + { + std::lock_guard lock(mutex); + ++running; + peak = std::max(peak, running); + } + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + std::lock_guard lock(mutex); + --running; + order.push_back(i); + return {}; + }; + // Every second one independent of the chain. + const JobGroup::Job job = i % 2 == 0 ? jobs.Add(std::format("link {}", i), work, previous) : jobs.Add(std::format("free {}", i), work); + if (i % 2 == 0) previous = {job}; + } + Check(jobs.Wait().empty(), "the chain on one worker leaves no error"); + Check(order.size() == 6 && peak == 1, std::format("six jobs run one at a time on one worker: {} ran, {} at once", order.size(), peak)); + const auto position = [&order](std::int32_t i) { + return std::ranges::find(order, i) - order.begin(); + }; + Check(position(0) < position(2) && position(2) < position(4), std::format("the chain runs in its order: {}", order)); + } + + void RunIsOneJob() { + JobPool pool(1); + const std::thread::id here = std::this_thread::get_id(); + std::thread::id ranOn = here; + pool.Run([&ranOn] { ranOn = std::this_thread::get_id(); }); + Check(ranOn != here, "Run runs the work on a worker and returns once it has"); + + bool rethrown = false; + try { + pool.Run([] { throw std::runtime_error("from the work"); }); + } catch (const std::runtime_error& e) { + rethrown = std::string_view(e.what()) == "from the work"; + } + Check(rethrown, "what the work throws, Run throws"); + + // On the pool's only worker: queued, the inner step would wait for + // the thread its caller holds. + std::thread::id outer; + std::thread::id inner; + JobGroup jobs(pool); + jobs.Add("outer", [&pool, &outer, &inner]() -> std::string { + outer = std::this_thread::get_id(); + pool.Run([&inner] { inner = std::this_thread::get_id(); }); + return {}; + }); + Check(jobs.Wait().empty() && outer == inner && outer != here, "Run on a worker of the pool runs the work on that worker"); + + // And a group there is refused, where it would have waited the same way. + jobs.Add("nested", [&pool]() -> std::string { + JobGroup nested(pool); + return {}; + }); + const std::string error = jobs.Wait(); + Check(error.starts_with("nested: ") && error.contains("JobGroup"), std::format("a JobGroup on a worker of its own pool is refused: '{}'", error)); + } + + // Leaving the scope of a group without Wait(), as an early return does: + // the job that runs is waited for, the one behind it never starts. The + // scope is left once the first runs, and the first goes on until the + // group has failed, which is what its destructor does first, so the + // second cannot have started before. + void LeavingWaitsForWhatRuns() { + JobPool pool(1); + std::atomic firstStarted{false}; + std::atomic firstFinished{false}; + std::atomic secondRan{false}; + { + JobGroup jobs(pool); + jobs.Add("first", [&jobs, &firstStarted, &firstFinished]() -> std::string { + firstStarted = true; + firstStarted.notify_all(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20); + while (!jobs.Failed() && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + firstFinished = true; + return {}; + }); + jobs.Add("second", [&secondRan]() -> std::string { + secondRan = true; + return {}; + }); + firstStarted.wait(false); + } + Check(firstFinished, "leaving a group waits for the job that is running"); + Check(!secondRan, "leaving a group keeps the jobs that have not started from starting"); + } +} + +int main() { + // The labels of a few dozen jobs say nothing here. + Progress::SetVerbosity(Progress::Verbosity::Quiet); + + const std::uint32_t hardware = std::max(1u, std::thread::hardware_concurrency()); + Check(JobPool::Process().Workers() == hardware, std::format("the process's pool has a worker per hardware thread: {} for {}", JobPool::Process().Workers(), hardware)); + Check(JobPool(0).Workers() == 1, "a pool has at least one worker"); + + RunsAsManyAsItHasWorkers(); + StartsAJobAfterTheOnesItComesAfter(); + KeepsTheOrderOfALargerGraph(); + TheFirstErrorStopsTheRest(); + OneWorkerIsEnough(); + RunIsOneJob(); + LeavingWaitsForWhatRuns(); + return Failures == 0 ? 0 : 1; +} diff --git a/tests/JobLimit/main.cpp b/tests/JobLimit/main.cpp new file mode 100644 index 0000000..a6ce449 --- /dev/null +++ b/tests/JobLimit/main.cpp @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// Builds run at most as many of their steps at once as the machine has +// hardware threads, however many files are stale and however many builds run +// side by side. Build() used to start a thread for every stale unit, and +// nothing bounded how many of them ran their compiler at once, on 8 hardware +// threads as on 56. +// +// Several projects are made here and built at once, each from a thread of +// this test, as RunTests builds its tests: enough of them to have two stale +// sources and more for every hardware thread. A project is 69 sources: 64 +// that import nothing, half C and half C++, then a module of two partitions, +// one importing the other, with its implementation unit, and a main.cpp that +// imports the module, so that steps waiting for other steps queue with the +// rest. It is the same size on every machine, so no command of its build +// grows with the machine; the number of projects does. While they build from +// nothing, the threads of this process are counted: a job occupies a worker +// for as long as it runs, so the builds may add as many threads as there are +// hardware threads and no more. Before, they added one per source. A link is +// no job: its Build() runs it through RunBuildCommand from a thread that was +// there before the count, which therefore does not tell whether it waited +// for a worker. Every program is then run, since a limit kept by leaving +// steps out would pass the count as well. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // The threads of this process, as the kernel counts them: one read, so + // no thread is counted twice or missed between two of them. + std::int32_t ThreadCount() { + std::ifstream status("/proc/self/status"); + std::string line; + while (std::getline(status, line)) { + constexpr std::string_view key = "Threads:"; + if (line.starts_with(key)) return std::stoi(line.substr(key.size())); + } + return 0; + } + + void Write(const fs::path& file, std::string_view text) { + std::ofstream(file, std::ios::binary | std::ios::trunc) << text; + } + + // One module or import declaration of a generated source. Put together + // here because the source scanner reads one spelled out in a string + // literal as a declaration of this file's own (issue #45). + std::string Declare(std::string_view keywords, std::string_view name) { + return std::format("{} {};\n", keywords, name); + } + + // The C sources of one project, and as many C++ ones. + constexpr std::int32_t PerKind = 32; + // The units of one project: those sources, the module's primary + // interface, two partitions and implementation unit, and main.cpp. + constexpr std::int32_t Units = 2 * PerKind + 5; + // What a project's program prints: every C unit returns its index and so + // does every C++ one; Top() is 3. + constexpr std::int32_t Printed = 3 + PerKind * (PerKind - 1); + + // Writes one project into `root` and returns its configuration. + std::unique_ptr MakeProject(const fs::path& root) { + fs::create_directories(root); + std::unique_ptr cfg = std::make_unique(); + cfg->path = root; + cfg->name = "job-limit"; + cfg->outputName = "job-limit"; + cfg->target = HostTarget(); + cfg->type = ConfigurationType::Executable; + + // Limit:High imports Limit:Low, the primary interface both, the + // module's implementation unit the primary interface, and main.cpp + // the module. + Write(root / "Limit-Low.cppm", std::format("{}export int Low() {{ return 1; }}\n", Declare("export module", "Limit:Low"))); + Write(root / "Limit-High.cppm", std::format("{}{}export int High() {{ return Low() + 1; }}\n", Declare("export module", "Limit:High"), Declare("import", ":Low"))); + Write(root / "Limit.cppm", std::format("{}{}{}export int Top();\n", Declare("export module", "Limit"), Declare("export import", ":Low"), Declare("export import", ":High"))); + Write(root / "Limit-impl.cpp", std::format("{}int Top() {{ return High() + 1; }}\n", Declare("module", "Limit"))); + + std::string declarations; + std::string sum; + std::vector implementations = { "main", "Limit-impl" }; + for (std::int32_t i = 0; i < PerKind; ++i) { + Write(root / std::format("c{}.c", i), std::format("int c_unit_{0}(void) {{ return {0}; }}\n", i)); + // Without the extension and absolute: cFiles resolve against the + // working directory, not cfg.path. + cfg->cFiles.push_back(root / std::format("c{}", i)); + Write(root / std::format("x{}.cpp", i), std::format("int cpp_unit_{0}() {{ return {0}; }}\n", i)); + implementations.emplace_back(std::format("x{}", i)); + declarations += std::format("extern \"C\" int c_unit_{0}(void);\nint cpp_unit_{0}();\n", i); + sum += std::format(" + c_unit_{0}() + cpp_unit_{0}()", i); + } + Write(root / "main.cpp", std::format("{}{}{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", Declare("import", "std"), Declare("import", "Limit"), declarations, sum)); + + std::array interfaces = { "Limit", "Limit-Low", "Limit-High" }; + cfg->GetInterfacesAndImplementations(interfaces, implementations); + return cfg; + } +} + +int main() { + const std::int32_t workers = static_cast(std::max(1u, std::thread::hardware_concurrency())); + // Two projects and one more for every 32 hardware threads: 64 sources + // each, so twice as many sources as hardware threads, and more. + const std::int32_t count = workers / PerKind + 2; + + const fs::path root = fs::temp_directory_path() / "crafter-build-job-limit"; + fs::remove_all(root); + + std::vector> projects; + for (std::int32_t i = 0; i < count; ++i) projects.push_back(MakeProject(root / std::to_string(i))); + + // What went wrong in each build; empty where nothing did. + std::vector errors(projects.size()); + std::atomic start{false}; + std::atomic peak{0}; + std::int32_t before = 0; + { + std::jthread sampler([&peak](std::stop_token stop) { + while (!stop.stop_requested()) { + const std::int32_t seen = ThreadCount(); + if (seen > peak.load()) peak.store(seen); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + }); + std::vector builders; + for (std::size_t i = 0; i < projects.size(); ++i) { + builders.emplace_back([&projects, &errors, &start, i] { + start.wait(false); + try { + std::unordered_map> depResults; + std::mutex depMutex; + errors[i] = Build(*projects[i], depResults, depMutex).result; + } catch (const std::exception& e) { + errors[i] = std::format("Build() threw: {}", e.what()); + } + }); + } + // With the sampler running and every builder waiting to start, so + // that they are part of what was there before the builds. + before = ThreadCount(); + start = true; + start.notify_all(); + // Leaving the scope joins the builders, then stops the sampler. + } + const std::int32_t added = peak.load() - before; + + bool built = true; + for (std::size_t i = 0; i < projects.size(); ++i) { + Check(errors[i].empty(), std::format("the build of project {} failed: {}", i, errors[i])); + built = built && errors[i].empty(); + } + Check(added <= workers, std::format("{} builds of {} sources in all ran on {} threads at once, on a machine with {} hardware threads", count, count * Units, added, workers)); + // The other way round: builds that ran one step at a time would keep + // the limit too. + Check(added >= std::min(workers, 2), std::format("the builds never had two steps running at once: {} thread(s) at most, with {} hardware threads", added, workers)); + + if (built) { + for (std::size_t i = 0; i < projects.size(); ++i) { + const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(*projects[i]).string()), std::chrono::seconds(30)); + Check(run.exitCode == 0 && run.output == std::to_string(Printed), std::format("the program of project {} printed '{}' (exit {}), expected {}: a unit is missing from it or was built out of order", i, run.output, run.exitCode, Printed)); + } + } + + return Failures == 0 ? 0 : 1; +} From f9d0ec24febd195993434ac7138b9223f52859d6 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:56 +0100 Subject: [PATCH 16/53] test(incremental): an interface unit without its object is built again IncrementalInterfaceObject builds a module with a partition and a program that prints what the module's function returns, without optimisation, so that what it prints says which object was linked. It edits the primary interface, builds, and puts the object of before the edit back dated two seconds before the new BMI. A build with the program still there has to make the object again and link the program again; after the old object is put back once more and the program deleted, a build has to make the object again and the program print the edited value. Then it deletes both objects and the program and builds: both objects have to be back. A last build of the intact tree has to leave the objects as they are. On 5b75df3 the old object is never made again, and the build without the program links it: the program prints 11 where the source says 12. The build without the objects fails at the link with "no such file or directory" for each of the two. --- project.cpp | 1 + .../fixture/Value-Part.cppm | 7 + .../fixture/Value-edited.cppm.in | 8 + .../fixture/Value.cppm | 8 + .../fixture/main.cpp | 9 ++ tests/IncrementalInterfaceObject/main.cpp | 144 ++++++++++++++++++ 6 files changed, 177 insertions(+) create mode 100644 tests/IncrementalInterfaceObject/fixture/Value-Part.cppm create mode 100644 tests/IncrementalInterfaceObject/fixture/Value-edited.cppm.in create mode 100644 tests/IncrementalInterfaceObject/fixture/Value.cppm create mode 100644 tests/IncrementalInterfaceObject/fixture/main.cpp create mode 100644 tests/IncrementalInterfaceObject/main.cpp diff --git a/project.cpp b/project.cpp index f3518dd..3b33cee 100644 --- a/project.cpp +++ b/project.cpp @@ -254,6 +254,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("IncrementalInterfaceChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("TransitiveInterfaceChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("IncrementalInterfaceObject").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StdPcmRebuild").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("CompilerWarning").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("CleanProject").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/IncrementalInterfaceObject/fixture/Value-Part.cppm b/tests/IncrementalInterfaceObject/fixture/Value-Part.cppm new file mode 100644 index 0000000..bdb4cf6 --- /dev/null +++ b/tests/IncrementalInterfaceObject/fixture/Value-Part.cppm @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Value:Part; +import std; + +export std::int32_t Part() { return 10; } diff --git a/tests/IncrementalInterfaceObject/fixture/Value-edited.cppm.in b/tests/IncrementalInterfaceObject/fixture/Value-edited.cppm.in new file mode 100644 index 0000000..4edc898 --- /dev/null +++ b/tests/IncrementalInterfaceObject/fixture/Value-edited.cppm.in @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Value; +import std; +export import :Part; + +export std::int32_t Value() { return Part() + 2; } diff --git a/tests/IncrementalInterfaceObject/fixture/Value.cppm b/tests/IncrementalInterfaceObject/fixture/Value.cppm new file mode 100644 index 0000000..14a55e0 --- /dev/null +++ b/tests/IncrementalInterfaceObject/fixture/Value.cppm @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Value; +import std; +export import :Part; + +export std::int32_t Value() { return Part() + 1; } diff --git a/tests/IncrementalInterfaceObject/fixture/main.cpp b/tests/IncrementalInterfaceObject/fixture/main.cpp new file mode 100644 index 0000000..a61d493 --- /dev/null +++ b/tests/IncrementalInterfaceObject/fixture/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Value; + +int main() { + std::print("{}", Value()); +} diff --git a/tests/IncrementalInterfaceObject/main.cpp b/tests/IncrementalInterfaceObject/main.cpp new file mode 100644 index 0000000..7307c55 --- /dev/null +++ b/tests/IncrementalInterfaceObject/main.cpp @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// An interface unit takes two compiler runs: one writes its BMI, the other +// the object made from the BMI. Whether a unit is stale is read off the BMI, +// so a unit left with a current BMI and the object of its source before an +// edit, or no object at all, was called built by every build after: the link +// took the old object without a word, or failed on the missing file until the +// source was touched. A build ends between the two runs when it is +// interrupted, when the second run fails, and, with the two as jobs of their +// own, when another step fails first and keeps the second from starting. +// +// The fixture is a module with a partition and a program that prints what +// the module's function returns. Built without optimisation, so the program +// gets that function from the unit's object alone and what it prints says +// which object was linked. First the primary interface is edited and, once +// that is built, its object put back as it was before the edit, dated before +// the new BMI: once with the program still there, which has to be linked +// again, and once with the program deleted, so that it is linked from +// whatever object is there. Then both objects and the program are deleted. A +// last build of the intact tree has to leave the objects alone. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // The fixture is edited during the run, so work on a copy outside the repo. + fs::path StageFixture() { + fs::path source = fs::current_path() / "tests" / "IncrementalInterfaceObject" / "fixture"; + fs::path staged = fs::temp_directory_path() / "crafter-build-incremental-interface-object"; + fs::remove_all(staged); + fs::copy(source, staged, fs::copy_options::recursive); + // An earlier run in the checkout may have left these; the copy starts cold. + fs::remove_all(staged / "bin"); + fs::remove_all(staged / "build"); + return staged; + } + + bool BuildOk(Configuration& app, std::string_view label) { + // A fresh depResults per pass, so every pass checks everything again. + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult built = Build(app, depResults, depMutex); + Check(built.result.empty(), std::format("{}: the build failed: {}", label, built.result)); + return built.result.empty(); + } + + std::string Printed(const Configuration& app) { + const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30)); + return run.exitCode == 0 ? run.output : std::format("", run.exitCode, run.output); + } +} + +int main() { + const fs::path staged = StageFixture(); + + Configuration app; + app.path = staged; + app.name = "value-app"; + app.outputName = "value-app"; + app.target = HostTarget(); + app.type = ConfigurationType::Executable; + app.debug = true; + std::array interfaces = { "Value", "Value-Part" }; + std::array implementations = { "main" }; + app.GetInterfacesAndImplementations(interfaces, implementations); + + const fs::path primaryPcm = app.PcmDir() / "Value.pcm"; + const fs::path primaryObject = app.BuildDir() / "Value.o"; + const fs::path partitionObject = app.BuildDir() / "Value-Part.o"; + const fs::path program = ExpectedOutput(app); + + if (!BuildOk(app, "the first build")) return 1; + Check(Printed(app) == "11", std::format("the first build's program prints 11, got '{}'", Printed(app))); + if (!fs::exists(primaryObject) || !fs::exists(partitionObject) || !fs::exists(primaryPcm)) { + std::println(std::cerr, "FAIL: the first build left no {}, {} or {}", primaryObject.string(), partitionObject.string(), primaryPcm.string()); + return 1; + } + const fs::path oldObject = staged / "Value.o.before-edit"; + fs::copy_file(primaryObject, oldObject, fs::copy_options::overwrite_existing); + + // After an edit, the BMI of the new source next to the object of the old + // one: what a build that ends between the two runs leaves of a unit that + // was built before. + fs::copy_file(staged / "Value-edited.cppm.in", staged / "Value.cppm", fs::copy_options::overwrite_existing); + if (!BuildOk(app, "the build after the edit")) return 1; + Check(Printed(app) == "12", std::format("the edited program prints 12, got '{}'", Printed(app))); + + const auto putOldObjectBack = [&] { + fs::copy_file(oldObject, primaryObject, fs::copy_options::overwrite_existing); + fs::last_write_time(primaryObject, fs::last_write_time(primaryPcm) - std::chrono::seconds(2)); + }; + + // With the program the last build linked still there, as a build that + // failed leaves it: nothing but the object made again is newer than it. + putOldObjectBack(); + if (BuildOk(app, "the build with the object of before the edit")) { + Check(fs::last_write_time(primaryObject) >= fs::last_write_time(primaryPcm), "an object older than its BMI is made again"); + Check(fs::last_write_time(program) >= fs::last_write_time(primaryObject), "the program is linked again from the object made again"); + Check(Printed(app) == "12", std::format("the program linked again prints 12, got '{}'", Printed(app))); + } + + // And with the program gone, so that the link takes whatever object is + // there. + putOldObjectBack(); + fs::remove(program); + if (BuildOk(app, "the build with the object of before the edit and no program")) { + Check(fs::last_write_time(primaryObject) >= fs::last_write_time(primaryPcm), "an object older than its BMI is made again, with no program either"); + Check(Printed(app) == "12", std::format("the program is linked from the object of the edited source and prints 12, got '{}'", Printed(app))); + } + + // BMIs and no objects: what such a build leaves of units it built for + // the first time. + fs::remove(primaryObject); + fs::remove(partitionObject); + fs::remove(program); + if (BuildOk(app, "the build after the objects went missing")) { + Check(fs::exists(primaryObject) && fs::exists(partitionObject), "a unit with a BMI and no object gets its object back"); + Check(Printed(app) == "12", std::format("the program linked from the restored objects prints 12, got '{}'", Printed(app))); + } + + // What follows reads the objects the builds above should have left. + if (Failures != 0) return 1; + + // With every object newer than its BMI there is nothing to make again. + const fs::file_time_type primaryTime = fs::last_write_time(primaryObject); + const fs::file_time_type partitionTime = fs::last_write_time(partitionObject); + if (BuildOk(app, "the build of the intact tree")) { + Check(fs::last_write_time(primaryObject) == primaryTime && fs::last_write_time(partitionObject) == partitionTime, "objects that are newer than their BMIs are left as they are"); + } + + return Failures == 0 ? 0 : 1; +} From 621438de5ffa6b9053bb115ca7f435a1020189b3 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:56 +0100 Subject: [PATCH 17/53] docs: say how many steps a build runs at once The README says in "Writing a project.cpp" that a build runs at most as many of its steps at once as the machine has hardware threads, which steps those are, and that an ExternalDependency's CMake build and the tests are not among them. Under Tests, --jobs= is named as what counts the tests, and --jobs=1 as one test at a time where it said "serial mode": the steps of that one test's build still run side by side. --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e06b24c..e309d18 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ Run `crafter-build` in that directory, outputs land at `bin/myapp--.log`. - A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run. @@ -253,7 +255,7 @@ crafter-build test 'Unit*' # glob-filter te crafter-build test --list # enumerate without running crafter-build test --target=x86_64-w64-mingw32 # only tests for this target crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine -crafter-build test --jobs=1 # serial mode +crafter-build test --jobs=1 # one test at a time crafter-build test --timeout=5 # override per-test timeout ``` From 12e8b908f62d2149f5025efb9d8b1936e24c4c64 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 13 Nov 2026 17:59:56 +0100 Subject: [PATCH 18/53] docs(packaging): add the 6.3.0 release entry 6.3.0 holds a build to as many steps at once as the machine has hardware threads, where every stale shader, asset to compress, C, CUDA and C++ unit got a thread of its own and nothing bounded how many ran at once. It makes the object of a module interface unit that an earlier build left with its BMI alone, or with the object of before an edit, and it refuses interface units of one configuration that import each other, whose first build hung. A minor, by the version rule: the notes have New and Fixes and nothing Breaking, and Jorijn's "6.3.0, that's internal and not user facing" settled it. What he was asked about: the range takes Compile() off Module, ModulePartition and Implementation, and the `compiled` flag off the first two, all of which interfaces/ exports. They are what Build() itself compiled a unit with, and none of the 35 project.cpp files of this checkout and the ones beside it reads the flag or calls Compile(). --- .../flatpak/net.catcrafts.CrafterBuild.metainfo.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml index d16aeaf..364d382 100644 --- a/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml @@ -25,6 +25,19 @@ + + +

New

+
    +
  • A build runs at most as many of its steps at once as the machine has hardware threads: the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. Until now every stale source and shader, and every asset to compress, got a thread of its own, and nothing bounded how many compilers ran side by side. An ExternalDependency's CMake build is not among those steps and keeps that many jobs of its own, and crafter-build test --jobs= counts the tests built and run at once, as before. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. Progress has two lines for every module interface unit, Precompiling X.cppm and Compiling X.cppm, where a module and its partitions shared one Compiling interface X.
  • +
+

Fixes

+
    +
  • A module interface unit left with its BMI and without the object made from it, or with the object of its source before an edit, is given its object by the next build. A build interrupted between the two compiler runs, or whose second run failed, left a unit like that, and every later build called it up to date: the link took the old object, or failed with no such file or directory until the source was touched.
  • +
  • Module interface units that import each other are refused with an error that names them: two partitions, a partition and its own module, or two modules of one configuration. A first build of them used to hang with no compiler running.
  • +
+
+

New

From 8baf14068ea434b46cf63e5c2565374755e7014c Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sat, 14 Nov 2026 20:19:19 +0100 Subject: [PATCH 19/53] fix(external): keep a sibling project's Configuration where it was built A project file may take pointers to the Configuration it returns. The usual one belongs to a test that links the library the file describes, cfg.AddTest("T").Dependencies({ &cfg }): where the compiler constructs the local the file returns in place of the return value, &cfg is the address of what CrafterBuildProject returns. For the project crafter-build is pointed at, that address stays good: Run() initialises its Configuration with the call. For a project loaded through GitProject or LocalProject it did not. LoadProjectFromRoot assigned the call's result to a local, and from there the Configuration was moved into the project cache, so what a consumer got was not the object the project file had built, and every pointer the file had taken to that one pointed at an object that no longer existed. RunLint follows such a pointer: for a sibling whose path lies inside the project's directory it works out the compile command of each of the sibling's tests when a rule needs an AST, and GetCompileCommand walks the dependencies of the configuration it is given. LoadProjectFromRoot now makes the Configuration on the heap with the call as its initialiser, and StoreProject takes the unique_ptr, so the Configuration is constructed where the cache keeps it and is never moved. --- implementations/Crafter.Build-External.cpp | 30 ++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/implementations/Crafter.Build-External.cpp b/implementations/Crafter.Build-External.cpp index 3fb8fe9..0a0c7a2 100644 --- a/implementations/Crafter.Build-External.cpp +++ b/implementations/Crafter.Build-External.cpp @@ -348,17 +348,28 @@ namespace { // absolute so Build() can run from any cwd without misresolving them. // The mutex is NOT held across LoadProject — the dep may itself call // GitProject/LocalProject, and a non-recursive lock would deadlock. - Configuration LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span args) { + // + // The Configuration is made on the heap with the call as its + // initialiser, so it is constructed where the cache keeps it and is + // never moved. A project file takes pointers to the Configuration it + // returns, for a test that links the library it describes + // (cfg.AddTest(...).Dependencies({ &cfg })), and they are pointers to + // this object when the compiler constructed the local the file returns + // in place of the return value, as clang does for a function that + // returns one local. Assigned to a local here and moved into the cache + // from there, the Configuration left every such pointer behind. + std::unique_ptr LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span args) { fs::path savedCwd = fs::current_path(); - Configuration cfg; + std::unique_ptr made; fs::current_path(depRoot); try { - cfg = LoadProject(projectPath, args); + made.reset(new Configuration(LoadProject(projectPath, args))); } catch (...) { fs::current_path(savedCwd); throw; } fs::current_path(savedCwd); + Configuration& cfg = *made; cfg.path = fs::absolute(depRoot / cfg.path).lexically_normal(); auto abs = [&](const fs::path& p) -> fs::path { return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal(); @@ -378,20 +389,19 @@ namespace { for (auto& entry : cfg.flatpak.share) { if (!entry.source.empty()) entry.source = abs(entry.source); } - return cfg; + return made; } // Into ProjectCache under `fullHash`, with `loaded` recorded beside it. // When another thread stored the same spec first, its Configuration // wins and `cfg` is dropped. - Configuration* StoreProject(std::string fullHash, Configuration cfg, LoadedProject loaded) { + Configuration* StoreProject(std::string fullHash, std::unique_ptr cfg, LoadedProject loaded) { std::lock_guard lock(ProjectCacheMutex); if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { return it->second.get(); } - auto stored = std::make_unique(std::move(cfg)); - Configuration* ptr = stored.get(); - ProjectCache.emplace(std::move(fullHash), std::move(stored)); + Configuration* ptr = cfg.get(); + ProjectCache.emplace(std::move(fullHash), std::move(cfg)); LoadedProjects.emplace(ptr, std::move(loaded)); return ptr; } @@ -461,7 +471,7 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) { } std::vector argViews(spec.args.begin(), spec.args.end()); - Configuration cfg = LoadProjectFromRoot(projectPath, cloneDir, argViews); + std::unique_ptr cfg = LoadProjectFromRoot(projectPath, cloneDir, argViews); const fs::path projectInRepo = spec.projectFile.lexically_normal(); const fs::path below = projectInRepo.parent_path(); @@ -522,7 +532,7 @@ Configuration* Crafter::LocalProject(const LocalProjectSpec& spec) { fs::path depRoot = canonical.parent_path(); std::vector argViews(spec.args.begin(), spec.args.end()); - Configuration cfg = LoadProjectFromRoot(canonical, depRoot, argViews); + std::unique_ptr cfg = LoadProjectFromRoot(canonical, depRoot, argViews); return StoreProject(std::move(fullHash), std::move(cfg), { .projectFile = canonical, From 1440e20231c8efc67806145fa79c5a26f5043043 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sat, 14 Nov 2026 23:42:47 +0100 Subject: [PATCH 20/53] test(external): a sibling's pointers to its own Configuration hold SiblingOwnPointers loads a fixture through LocalProject, on a fresh copy outside the checkout: a library whose project file declares a test with cfg.AddTest("OwnTest").Dependencies({ &cfg }). The one dependency of that test has to be the Configuration LocalProject returns. The test reads the dependency out of that Configuration and compares the two addresses, without following the dependency. Against the loader as it was before the fix the test fails: the dependency is not that Configuration. --- project.cpp | 2 + tests/SiblingOwnPointers/fixture/project.cpp | 20 ++++++++ .../fixture/tests/OwnTest/main.cpp | 6 +++ tests/SiblingOwnPointers/main.cpp | 49 +++++++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 tests/SiblingOwnPointers/fixture/project.cpp create mode 100644 tests/SiblingOwnPointers/fixture/tests/OwnTest/main.cpp create mode 100644 tests/SiblingOwnPointers/main.cpp diff --git a/project.cpp b/project.cpp index 3b33cee..2aceae7 100644 --- a/project.cpp +++ b/project.cpp @@ -334,6 +334,8 @@ extern "C" Configuration CrafterBuildProject(std::span a .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); + cfg.AddTest("SiblingOwnPointers").Dependencies({ CrafterBuildLib.get() }) + .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/SiblingOwnPointers/fixture/project.cpp b/tests/SiblingOwnPointers/fixture/project.cpp new file mode 100644 index 0000000..b766a0c --- /dev/null +++ b/tests/SiblingOwnPointers/fixture/project.cpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// A library whose test depends on it: the test's dependency is a pointer to +// the Configuration this function returns. A library with no sources is +// enough, since the test that loads this file reads the pointer and builds +// nothing. +extern "C" Configuration CrafterBuildProject(std::span) { + Configuration cfg; + cfg.path = "./"; + cfg.name = "own"; + cfg.outputName = "own"; + cfg.type = ConfigurationType::LibraryStatic; + cfg.AddTest("OwnTest").Dependencies({ &cfg }); + return cfg; +} diff --git a/tests/SiblingOwnPointers/fixture/tests/OwnTest/main.cpp b/tests/SiblingOwnPointers/fixture/tests/OwnTest/main.cpp new file mode 100644 index 0000000..97eb9af --- /dev/null +++ b/tests/SiblingOwnPointers/fixture/tests/OwnTest/main.cpp @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +int main() { + return 0; +} diff --git a/tests/SiblingOwnPointers/main.cpp b/tests/SiblingOwnPointers/main.cpp new file mode 100644 index 0000000..60348cb --- /dev/null +++ b/tests/SiblingOwnPointers/main.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A project file may keep pointers to the Configuration it returns: a test +// that links the library the file describes is declared with +// cfg.AddTest("T").Dependencies({ &cfg }). Loaded by another project through +// LocalProject or GitProject, that Configuration has to stay where the +// project file built it. +// +// The loader moved it: out of the call's return value, and then into its +// cache. The test's dependency was left pointing at an object that no +// longer existed, and whatever followed it read freed memory. +// `crafter-build lint` follows it for a sibling inside the project's own +// directory, when it works out the compile command of each of the sibling's +// tests for a rule that needs an AST. +int main() { + const fs::path installedHome = GetCrafterBuildHome(); + if (!fs::exists(installedHome / "Crafter.Build.cppm")) { + std::println(std::cerr, "SKIP: no module sources at {}", installedHome.string()); + return 77; + } + + // Staged because the load drops a build/ tree next to the project file. + const fs::path scratch = fs::temp_directory_path() / "crafter-build-sibling-own-pointers"; + std::error_code ec; + fs::remove_all(scratch, ec); + fs::copy(fs::current_path() / "tests" / "SiblingOwnPointers" / "fixture", scratch, fs::copy_options::recursive); + + Configuration* sibling = nullptr; + try { + sibling = LocalProject({ .projectFile = scratch / "project.cpp" }); + } catch (const std::exception& e) { + std::println(std::cerr, "FAIL: loading the sibling threw: {}", e.what()); + return 1; + } + // Compared, never followed: where the two differ, the pointer leads + // nowhere. + if (sibling->tests.size() != 1 || sibling->tests[0].config.dependencies != std::vector{sibling}) { + std::println(std::cerr, "FAIL: the pointer a sibling's project file took to the Configuration it returns is not the Configuration its consumers get"); + return 1; + } + fs::remove_all(scratch, ec); + return 0; +} From 1ddba745cf19d4adf781b3888c5d4af0c73227fa Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sat, 14 Nov 2026 23:42:47 +0100 Subject: [PATCH 21/53] fix(wasm): resolve the WASI sysroot where it is read, not in Build() A wasm32 configuration that names no sysroot is built against the toolchain's WASI sysroot. ApplyStandardArgs stores that sysroot in cfg.sysroot, for a project file that calls it. For a configuration whose project file sets the target itself, Build() stored it on its way in. VariantId hashes the sysroot, so such a configuration had one BuildDir, BinDir and PcmDir until its build started and others from then on. A build pass records each dependency's build under its PcmDir, and a configuration asks for a dependency by the PcmDir it has at that moment. A wasm32 library that two configurations of one pass are built on was recorded under the first directory for the one that asked first. One that asked after the library's build had started asked under the second directory, found nothing there, and built the library again. Configuration::ResolvedSysroot now gives what cfg.sysroot comes to: the toolchain's WASI sysroot for a wasm32 configuration that names none, cfg.sysroot as it stands for every other, as ResolvedPackaging gives what `packaging` comes to. VariantId, the std module's flags, key and source, the compile and link commands and the check that refuses a wasm build without a usable sysroot read it, and Build() no longer stores the sysroot in the configuration. ApplyStandardArgs still does: what a project file reads in cfg.sysroot after the call stays what it was. The directories a build writes keep their names: a configuration that named no sysroot was built into the ones its VariantId named once Build() had stored it, which are the ones it names now. StdPcmFlags takes the toolchain, as StdPcmKey does, so that a VariantId asked for under a toolchain resolves the sysroot under that one. --- implementations/Crafter.Build-Clang.cpp | 51 ++++++++++------------ implementations/Crafter.Build-Platform.cpp | 8 ++-- interfaces/Crafter.Build-Clang.cppm | 31 ++++++++++--- 3 files changed, 51 insertions(+), 39 deletions(-) diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index d95625f..ae6d10b 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -249,14 +249,15 @@ void Configuration::GetInterfacesAndImplementations(std::span interfac } } -std::string Crafter::StdPcmFlags(const Configuration& config) { +std::string Crafter::StdPcmFlags(const Configuration& config, const Toolchain& toolchain) { if (config.target == "x86_64-w64-mingw32") { // -femulated-tls keeps PCM TLS access matching libstdc++'s emutls // definitions; a mismatch surfaces as undefined std::__once_callable. return std::format(" --target={} -march={} -mtune={} -femulated-tls -O3 -std=c++26 -Wno-reserved-identifier -Wno-reserved-module-identifier", config.target, config.march, config.mtune); } const bool isWasm = config.target.starts_with("wasm32"); - const std::string sysrootFlag = config.sysroot.empty() ? std::string() : std::format(" --sysroot={}", config.sysroot); + const std::string sysroot = config.ResolvedSysroot(toolchain); + const std::string sysrootFlag = sysroot.empty() ? std::string() : std::format(" --sysroot={}", sysroot); // wasm32 rejects -march, and the std module has to be compiled the way // the units importing it are, a variant pass's flags (e.g. // -mrelaxed-simd) included, or the BMI is not feature-compatible. @@ -265,8 +266,8 @@ std::string Crafter::StdPcmFlags(const Configuration& config) { // libc++ headers (/../include/c++/v1) above --sysroot, so the // PCM would mix host libc++ with the foreign libc. Force the sysroot's // copy. - if (!isWasm && !config.sysroot.empty()) { - archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", config.sysroot); + if (!isWasm && !sysroot.empty()) { + archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", sysroot); } return std::format(" --target={} -std=c++26{}{} -O3 -Wno-reserved-identifier -Wno-reserved-module-identifier", config.target, sysrootFlag, archFlags); } @@ -281,7 +282,7 @@ std::string Crafter::StdPcmKey(const Configuration& config, const Toolchain& too // releases sharing a cache, as the Flatpak's branches do, each time under // the PCMs built against the previous one, which clang crashes on rather // than rejecting. - std::string compiled = StdPcmFlags(config); + std::string compiled = StdPcmFlags(config, toolchain); // The base command's part: the toolchain's key covers the compiler and // libc++, and for the mingw target what clang finds mingw-w64 through is // the prefix, given whole or through a view (MingwSysroot), named here by @@ -335,8 +336,8 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { : std::format(" -march={} -mtune={}", config.march, config.mtune); out.command = std::format("{} --target={}{} -std=c++26 -D CRAFTER_BUILD_CONFIGURATION_TARGET=\\\"{}\\\" -D CRAFTER_BUILD_CONFIGURATION_TARGET_{} -fprebuilt-module-path={} -fprebuilt-module-path={}", GetBaseCommand(config), config.target, archFlags, editedTarget, editedTarget, out.stdPcmDir.string(), out.pcmDir.string()); - if (!config.sysroot.empty()) { - out.command += std::format(" --sysroot={}", config.sysroot); + if (const std::string sysroot = config.ResolvedSysroot(GetToolchain()); !sysroot.empty()) { + out.command += std::format(" --sysroot={}", sysroot); // Same reason as in BuildStdPcm: the driver ranks the host // toolchain's own libc++ headers (/../include/c++/v1) above // --sysroot. A unit that only does `import std;` never notices, but @@ -350,7 +351,7 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { // option in compileFlags) on sysroot builds. Not for mingw, which // uses libstdc++ and has no libc++ in its sysroot. if (!isWasm && config.target != "x86_64-w64-mingw32") { - out.command += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1 -Wno-unused-command-line-argument", config.sysroot); + out.command += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1 -Wno-unused-command-line-argument", sysroot); } } if (isWasm) { @@ -627,7 +628,7 @@ namespace { if (config.type == ConfigurationType::LibraryDynamic) { return std::format("{}: wasm32 shared libraries are not supported: the exception-enabled libc++ they would link has static archives only", config.name); } - const fs::path sysroot = config.sysroot; + const fs::path sysroot = config.ResolvedSysroot(GetToolchain()); if (!fs::is_directory(sysroot)) { return std::format("no WASI sysroot at {}: the Flatpak bundles one, and CRAFTER_BUILD_WASI_SYSROOT selects another", sysroot.string()); } @@ -811,17 +812,10 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map/usr/share/libc++/v1/. std::string stdCppm; if (isWasm) { - stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.sysroot); + stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.ResolvedSysroot(GetToolchain())); } else if (config.sysroot.empty()) { stdCppm = GetToolchain().stdCppm.string(); } else { @@ -968,7 +968,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { // mtimes: an installed std.cppm can be dated at the epoch (OSTree), // and a libc++ update under the same clang changes the bytes but // not the path. - std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config), stdCppm, stdPcm.string()); + std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm, stdPcm.string()); std::string stamp = HashStamp(command + '\0' + FileBytes(stdCppm)); if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return ""; std::string result = RunBuildCommand(command); @@ -1003,7 +1003,7 @@ std::string Crafter::GetBaseCommand(const Configuration& config) { command += " -stdlib=libc++"; // A sysroot build (wasm, a cross rootfs) takes libc++ from the sysroot; // only host builds can be pointed at an explicit libc++ install. - if (config.sysroot.empty()) command += tc.LibcxxCompileFlags(); + if (config.ResolvedSysroot(tc).empty()) command += tc.LibcxxCompileFlags(); return command; } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index c253079..0ae6ab9 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -662,7 +662,7 @@ export namespace Crafter { compileKey += '|'; compileKey += debug ? '1' : '0'; compileKey += '|'; - compileKey += sysroot; + compileKey += ResolvedSysroot(toolchain); for (const Define& d : defines) { compileKey += "|D:"; compileKey += d.name; @@ -748,6 +748,25 @@ export namespace Crafter { Packaging ResolvedPackaging() const { return type == ConfigurationType::Executable && packaging == Packaging::Flatpak ? Packaging::Flatpak : Packaging::None; } + // What `sysroot` comes to for this configuration under `toolchain`: + // the toolchain's WASI sysroot for a wasm32 target that names none, + // `sysroot` as it stands for every other configuration. The + // commands that compile and link a wasm32 configuration and the + // names of its directories read the sysroot through here, so the + // configuration is the same thing before its build as during it and + // after. Build() used to store the WASI sysroot in `sysroot` on its + // way in instead, and VariantId hashes the sysroot: a wasm32 + // configuration whose target was set without ApplyStandardArgs, + // which stores it when the project file is loaded, had one + // BuildDir, BinDir and PcmDir until its build started and others + // from then on. A build pass records a dependency's build under its + // PcmDir, so one that two configurations of the pass were built on + // was looked up under the first directory by the one that asked + // before its build had started and under the second by the one + // that asked after, and was built a second time. + std::string ResolvedSysroot(const Toolchain& toolchain) const { + return sysroot.empty() && target.starts_with("wasm32") ? toolchain.wasiSysroot.string() : sysroot; + } fs::path PcmDir() const { return type == ConfigurationType::Executable ? BuildDir() : BinDir(); } @@ -930,9 +949,9 @@ namespace Crafter { // compile command and of the std module's, which have to agree flag for // flag. std::string WasmCompileFlags(const Configuration& config); - // The flags BuildStdPcm compiles the std module with, after the base - // command and before the source, each with a leading space. StdPcmKey - // hashes the same string, so the command and the directory it writes to - // cannot disagree about what decides the BMI. - std::string StdPcmFlags(const Configuration& config); + // The flags BuildStdPcm compiles the std module with under `toolchain`, + // after the base command and before the source, each with a leading + // space. StdPcmKey hashes the same string, so the command and the + // directory it writes to cannot disagree about what decides the BMI. + std::string StdPcmFlags(const Configuration& config, const Toolchain& toolchain); } From a7aa22220b25978135efcddce75e1780d59ca560 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sat, 14 Nov 2026 23:42:47 +0100 Subject: [PATCH 22/53] test(wasm): a configuration is the same with its WASI sysroot named or not WasmSysrootKey makes two wasm32 configurations that differ in one thing: one names no sysroot and the other names the toolchain's WASI sysroot. They have to be one configuration: the same VariantId, PcmDir and BuildDir, the same std module key, and the same compile command, which names the WASI sysroot. A third, with a sysroot of its own, has another VariantId. It then builds two programs for the host in one pass, each on the same wasm32 library, which names no sysroot. The library carries -fno-exceptions, which a wasm build is refused for before it makes a directory, so the case does not depend on the machine having a WASI sysroot. The library's PcmDir has to be the same after the first program's build as before it, and the pass has to hold the library once. Against the engine as it was before the fix the test fails on each of the three: the two configurations have different VariantIds, the library's PcmDir changes with the first build, and the pass holds the library twice. --- project.cpp | 1 + tests/WasmSysrootKey/main.cpp | 108 ++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 tests/WasmSysrootKey/main.cpp diff --git a/project.cpp b/project.cpp index 2aceae7..1452eb6 100644 --- a/project.cpp +++ b/project.cpp @@ -308,6 +308,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("WasmExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasiSysrootWithoutExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); // LoadProject dlopens the synthesized project.so, which references // Crafter:: symbols (HostTarget, Configuration ctors) that have to be diff --git a/tests/WasmSysrootKey/main.cpp b/tests/WasmSysrootKey/main.cpp new file mode 100644 index 0000000..afe6abc --- /dev/null +++ b/tests/WasmSysrootKey/main.cpp @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A wasm32 configuration that names no sysroot is built against the +// toolchain's WASI sysroot, and it is the same configuration whether its +// `sysroot` says so or not: the same directories, the same compile command. +// +// Build() used to store the WASI sysroot in the configuration as it started +// building it, and the sysroot is part of what names a configuration's +// directories. A wasm32 configuration whose project file set its target +// without ApplyStandardArgs, which stores the sysroot at load time, so had +// one PcmDir before its build and another once it had started. A build pass +// records a dependency's build under its PcmDir: a library that two programs +// of one pass were built on was recorded under the first directory for the +// program that asked first, not found under the second by the program that +// asked next, and built again. +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // A wasm32 library without sources that names no sysroot. + Configuration MakeLibrary(const fs::path& dir, std::string_view name) { + Configuration cfg; + cfg.path = dir; + cfg.name = name; + cfg.outputName = name; + cfg.target = "wasm32-wasip1"; + cfg.type = ConfigurationType::LibraryStatic; + return cfg; + } + + // A program for the host without sources, built on `library`. + Configuration MakeProgram(const fs::path& dir, std::string_view name, Configuration& library) { + Configuration cfg; + cfg.path = dir; + cfg.name = name; + cfg.outputName = name; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::Executable; + cfg.dependencies = { &library }; + return cfg; + } +} + +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-wasm-sysroot-key"; + std::error_code ec; + fs::remove_all(scratch, ec); + fs::create_directories(scratch); + const Toolchain& toolchain = GetToolchain(); + + // Named or not, the WASI sysroot makes one configuration. + { + const Configuration unnamed = MakeLibrary(scratch, "keyed"); + Configuration named = MakeLibrary(scratch, "keyed"); + named.sysroot = toolchain.wasiSysroot.string(); + Check(unnamed.VariantId() == named.VariantId(), std::format("a wasm32 configuration that names no sysroot is the one that names the toolchain's WASI sysroot ({} and {})", unnamed.VariantId(), named.VariantId())); + Check(unnamed.PcmDir() == named.PcmDir() && unnamed.BuildDir() == named.BuildDir(), "and is built into the same directories"); + Check(StdPcmKey(unnamed, toolchain) == StdPcmKey(named, toolchain), "against the same std module"); + Check(GetCompileCommand(unnamed).command == GetCompileCommand(named).command, std::format("with the same compile command:\n{}\n{}", GetCompileCommand(unnamed).command, GetCompileCommand(named).command)); + Check(GetCompileCommand(unnamed).command.contains(std::format("--sysroot={}", toolchain.wasiSysroot.string())), "which names the WASI sysroot"); + + Configuration other = MakeLibrary(scratch, "keyed"); + other.sysroot = (scratch / "another-sysroot").string(); + Check(other.VariantId() != unnamed.VariantId(), "a wasm32 configuration with a sysroot of its own is still another configuration"); + } + + // Building it leaves it where it was, so a pass that two programs ask + // for it in builds it once. The library has a flag no wasm build + // accepts: its build is refused on every machine, with or without a + // WASI sysroot, before it makes a directory, and a refused build is + // recorded in the pass like any other. + { + Configuration library = MakeLibrary(scratch, "shared"); + library.compileFlags.push_back("-fno-exceptions"); + Configuration first = MakeProgram(scratch, "first", library); + Configuration second = MakeProgram(scratch, "second", library); + const fs::path before = library.PcmDir(); + + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult one = Build(first, depResults, depMutex); + Check(one.result.contains("-fno-exceptions"), std::format("the first program's build asks for the library, whose build is refused: {}", one.result)); + Check(library.PcmDir() == before, std::format("a build leaves a configuration's directories where they were ({} before, {} after)", before.string(), library.PcmDir().string())); + const BuildResult two = Build(second, depResults, depMutex); + Check(two.result == one.result, "the second program gets the same answer"); + const auto builds = std::ranges::count_if(depResults, [](const auto& entry) { return entry.first.filename().string().starts_with("shared-wasm32"); }); + Check(builds == 1, std::format("one pass builds the library once for both programs (recorded {} times)", builds)); + } + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + fs::remove_all(scratch, ec); + return 0; +} From 4283a3ecd298591a4cfac8e7c98ff92cd4d6b457 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 15 Nov 2026 02:16:06 +0100 Subject: [PATCH 23/53] feat: let a project file return several configurations A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration. --- .review-gates/lenses/repo-bug-prover.md | 5 +- AGENTS.template.md | 17 +- implementations/Crafter.Build-Agents.cpp | 151 ++++++++-- implementations/Crafter.Build-Clang.cpp | 315 +++++++++++++++++++-- implementations/Crafter.Build-External.cpp | 184 +++++++----- implementations/Crafter.Build-Lint.cpp | 41 ++- implementations/Crafter.Build-Platform.cpp | 143 ++++++++-- implementations/Crafter.Build-Script.cpp | 47 ++- implementations/Crafter.Build-Test.cpp | 121 ++++++-- interfaces/Crafter.Build-Agents.cppm | 15 +- interfaces/Crafter.Build-Clang.cppm | 43 ++- interfaces/Crafter.Build-External.cppm | 66 +++-- interfaces/Crafter.Build-Lint.cppm | 9 +- interfaces/Crafter.Build-Platform.cppm | 40 ++- interfaces/Crafter.Build-Script.cppm | 9 +- interfaces/Crafter.Build-Test.cppm | 23 +- 16 files changed, 987 insertions(+), 242 deletions(-) diff --git a/.review-gates/lenses/repo-bug-prover.md b/.review-gates/lenses/repo-bug-prover.md index 8934e98..10b4f5f 100644 --- a/.review-gates/lenses/repo-bug-prover.md +++ b/.review-gates/lenses/repo-bug-prover.md @@ -26,8 +26,9 @@ The execution contexts to enumerate, beside the charter's: jobs it was added after have finished; a `RunBuildCommand` waits for a worker when its caller is not one. Jobs are waited for by threads that are not workers, among them one that runs a `Build()` (its caller's, one - of `RunTests`', one a `Build()` starts per dependency) and the one that - runs `LoadProject`, for the compiles of the std module and of + of `RunTests`', one of `BuildAll`'s, one a `Build()` starts per + dependency) and the one that loads a project file (`LoadConfigurations`, + `LoadProject`), for the compiles of the std module and of `project.cpp`. The threads a `Build()` starts per external dependency are not workers either and wait for no job: they run git and cmake. An executable's copies of what its dependencies forward run on the thread of diff --git a/AGENTS.template.md b/AGENTS.template.md index 86c4b15..b282736 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -4,7 +4,7 @@ Guidance for coding agents and contributors working on crafter-build itself. The ## Project overview -crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process. +crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`, or several of them; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process. | Path | What lives there | |---|---| @@ -25,14 +25,14 @@ Partitions and what they own: - `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. - `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. -- `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code. +- `:Platform` runs commands, implements `LoadConfigurations` and `LoadProject` (compile and load `project.cpp`), the host PCM cache and `#pragma crafter dependency`. - `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`. - `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`). - `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. - `:Test` holds `AddTest`, `RunTests` and `TestRunner`. - `:Lint` is the lint/format driver plus the libclang token and AST layer. -- `:Script` is the driver behind `crafter-build run`: it looks a name up in `cfg.scripts`, calls the callback and turns what it returns into the exit code. -- `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configuration `GitProject` and `LocalProject` return has its `path` rebased. +- `:Script` is the driver behind `crafter-build run`: it looks a name up in the `scripts` of the configurations it is given, calls the callback and turns what it returns into the exit code. +- `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configurations returned by a project file that `GitProject` or `LocalProject` loaded have their `path` rebased. - `:Progress` is console output. `:Shader` compiles shaders through glslang. `:Asset` is the hook into Crafter.Asset. - `:Flatpak` is an executable packaged as a Flatpak: `FlatpakApp` (app-id, runtime, permissions, desktop file, metainfo, icons, share entries, modules), the writer of its `files/`, which becomes `/app` in the app's sandbox, and what makes the app of that for `install` and `bundle`: the host's `flatpak build-finish`, which writes the metadata and `export/` by flatpak's own rules, then `flatpak build-export` into a repo, or flatpak-builder from a generated manifest when there are modules. It works on plain data; `Build()` and the `InstallFlatpakApp` and `BundleFlatpakApp` of `:Clang` gather it from the Configuration. The host's flatpak and flatpak-builder are reached through `RunHostFlatpak` and `RunHostFlatpakBuilder` in `:Platform`. @@ -51,7 +51,7 @@ Three things to know about this loop: - `bin/crafter-build` is the bootstrap binary and the harness for every command below. The self-host build writes to `bin/crafter.build-exe-/crafter-build` and does not replace it. - Changes under `implementations/` are picked up by the self-host build and by the tests, which link the local library. Changes under `interfaces/` are not: the harness compiles against the copies in `share/crafter-build/` and the PCM cache built from them, so a new or changed declaration is invisible until you run `./build.sh` again. The symptom is `use of undeclared identifier` for the symbol you just added. A changed default member initialiser has no symptom at all: `project.cpp` compiles against the old one and quietly gets the old default, as `project.cpp`'s sibling loads do with a harness that predates `GitProjectSpec::args = ProjectArgs()`. -- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and `LoadProject` fails with an undefined symbol. +- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and loading `project.cpp` fails with an undefined symbol. `./build.sh` clones and builds glslang on first run and takes several minutes; later runs are faster. `./bin/crafter-build clean` deletes `bin/` and `build/` without loading `project.cpp`. That takes `bin/crafter-build` itself with it, and `build/flatpak`, the state of the local Flatpak build (see "CI and publishing"): about 4 GB after a first run, and the next `run flatpak` rebuilds LLVM. Set `CRAFTER_BUILD_HOME` only when running a binary from outside this tree; `CRAFTER_BUILD_MARCH` and `CRAFTER_BUILD_MTUNE` default to `native`. @@ -81,7 +81,7 @@ Tests are declared, not discovered. Each one is a line in `project.cpp`: cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() }); ``` -The source is `tests//main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so `import Crafter.Build;` resolves to the code in this checkout. A test that calls `LoadProject` also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today. +The source is `tests//main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so the engine it calls is the one built from this checkout. A test that loads a project file, through `LoadConfigurations`, `LoadProject`, `LocalProject`, `GitProject` or `Run()`, also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today. A test is an ordinary `int main()`. Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout. @@ -159,7 +159,7 @@ These were decided deliberately. Do not undo them without the maintainer's say-s - `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters. - Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built. - `--runner=cmd:` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests. -- `crafter-build run ` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's; keep it that way. +- `crafter-build run ` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's: `run` leaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (`KeptBy`); keep it that way. - The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. - crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. - CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. @@ -198,8 +198,9 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - A new partition is listed in four places, in import order: `PARTITIONS` in `build.sh`, `CrafterBuildModules` in `Crafter.Build-Platform.cpp`, both arrays in `project.cpp`, and the umbrella `Crafter.Build.cppm`. Then `./build.sh`. - A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. -- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. +- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because loading a project file fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. - `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. +- A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. - The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel ` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. - An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. - The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then. diff --git a/implementations/Crafter.Build-Agents.cpp b/implementations/Crafter.Build-Agents.cpp index bddd41b..acb73bf 100644 --- a/implementations/Crafter.Build-Agents.cpp +++ b/implementations/Crafter.Build-Agents.cpp @@ -345,18 +345,60 @@ namespace { return DependencyNote{ .name = name, .text = std::move(note.text) }; } - // The loaded projects `configs` lead to without passing through another - // loaded project, in the order the configurations name them: one ring - // further out. `walked` spans the whole collection, so each - // Configuration is looked at once however many paths reach it. - std::vector NextRing(std::span configs, std::unordered_set& walked) { + // Tells a configuration of another project from one of the project + // whose AGENTS.md is written, the one of the project file it is made + // with. GitProject and LocalProject hold the configurations of a project + // file they loaded, so held or not does not tell the two apart: the + // project whose notes are written may itself have been loaded through + // one of them, by a program that then writes its AGENTS.md for it. Two + // files are one project file when they resolve to one path, which is + // how the loader tells project files apart: a hard link to the project + // file in another directory is another project's. Each loaded project's + // file is compared with the project file once and the answer kept, so a + // configuration is the same thing every time one collection asks, + // whatever happens to the files meanwhile. + class OtherProjects { + public: + explicit OtherProjects(const fs::path& projectFile) { + // Left empty when the file cannot be resolved, and then no + // loaded project's file is it. + std::error_code ec; + projectFile_ = fs::canonical(projectFile, ec); + if (ec) projectFile_.clear(); + } + // The project `cfg` was loaded from when that is another one; + // nullopt for a configuration the project's own file made. + std::optional Of(const Configuration& cfg) { + std::optional loaded = LoadedProjectOf(cfg); + if (!loaded) return loaded; + const auto [known, added] = same_.try_emplace(loaded->projectFile, false); + if (added && !projectFile_.empty()) { + std::error_code ec; + const fs::path file = fs::canonical(loaded->projectFile, ec); + known->second = !ec && file == projectFile_; + } + if (known->second) loaded.reset(); + return loaded; + } + private: + // The project file, resolved. + fs::path projectFile_; + // By a loaded project's file: whether it is projectFile_. + std::unordered_map same_; + }; + + // The other projects `configs` lead to without passing through another + // of them, in the order the configurations name them: one ring further + // out. `walked` spans the whole collection, so each Configuration is + // looked at once however many paths reach it. + std::vector NextRing(std::span configs, std::unordered_set& walked, OtherProjects& others) { std::vector ring; std::vector pending(configs.rbegin(), configs.rend()); while (!pending.empty()) { const Configuration* cfg = pending.back(); pending.pop_back(); if (!cfg || !walked.insert(cfg).second) continue; - if (LoadedProjectOf(*cfg)) { + if (others.Of(*cfg)) { ring.push_back(cfg); continue; } @@ -365,21 +407,72 @@ namespace { return ring; } - // The AGENTS.consumer.md of every project `project` depends on, as - // project.dependencyNotes selects them, ring by ring: first the loaded - // projects (the ones GitProject and LocalProject returned) that its - // `#pragma crafter dependency` lines and its configurations name, in - // that order, then the ones those depend on. Its own configurations, and - // a dependency's internal ones, are only walked through. Direct stops - // after the first ring. + // The AGENTS.consumer.md of every project the project is built against, + // as the dependencyNotes of `configurations`, the configurations its + // project file returns, select them, ring by ring: first the other + // projects (the ones GitProject and LocalProject loaded from another + // project file) that its `#pragma crafter dependency` lines and its + // configurations name, in that order, then the ones those depend on. + // Its own configurations, and a dependency's internal ones, are only + // walked through. + // + // Each configuration the file made itself selects for what it is built + // against: None nothing, Direct the first ring from it, Transitive every + // ring. Another project therefore has its own dependencies followed + // when a Transitive configuration leads to it, at whatever depth, and + // not when only Direct ones do. The pragma lines belong to the file and + // not to one configuration, and a configuration the file loaded from + // another project and returns is a project of the first ring itself, + // with a setting that is that project's own: both go by the widest + // setting among the configurations the file made, and by Transitive + // when it made none. // // Never walked: the project's tests, since a plain build never touches - // them and a test's dependency can point at the Configuration the project - // file returned by value, which has since moved; and a dependency's own - // pragma tooling, which is about how the dependency is built, not how it - // is used, and is no `dependencies` edge to begin with. - std::vector CollectNotes(const Configuration& project, const fs::path& projectFile, const fs::path& projectDir) { - std::unordered_set walked = { &project }; + // them and a test's dependency can point at the Configuration a + // CrafterBuildProject returned by value, which a caller of LoadProject + // may have moved since; and a dependency's own pragma tooling, which is + // about how the dependency is built, not how it is used, and is no + // `dependencies` edge to begin with. + std::vector CollectNotes(std::span configurations, const fs::path& projectFile, const fs::path& projectDir) { + OtherProjects others(projectFile); + const auto made = [&](const Configuration* cfg) { return !others.Of(*cfg); }; + const auto asks = [&](DependencyNotes setting) { + return std::ranges::any_of(configurations, [&](const Configuration* cfg) { return made(cfg) && cfg->dependencyNotes == setting; }); + }; + const bool transitive = asks(DependencyNotes::Transitive) || std::ranges::none_of(configurations, made); + if (!transitive && !asks(DependencyNotes::Direct)) return {}; + + // Where the walk starts, and the starts that ask for every ring. + std::vector start; + std::vector deep; + for (const Configuration* dep : PragmaDependencies(projectFile)) { + start.push_back(dep); + if (transitive) deep.push_back(dep); + } + for (const Configuration* cfg : configurations) { + const DependencyNotes setting = made(cfg) ? cfg->dependencyNotes : transitive ? DependencyNotes::Transitive : DependencyNotes::Direct; + if (setting == DependencyNotes::None) continue; + start.push_back(cfg); + if (setting == DependencyNotes::Transitive) deep.push_back(cfg); + } + // Every other project those lead to: the ones whose own + // dependencies are followed. Worked out ahead of the walk below, + // which meets each project once, at its nearest ring, and that can + // be a ring a Direct configuration put it in. + std::unordered_set followed; + { + std::unordered_set reached; + for (std::vector ring = NextRing(deep, reached, others); !ring.empty();) { + std::vector next; + for (const Configuration* cfg : ring) { + followed.insert(cfg); + next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end()); + } + ring = NextRing(next, reached, others); + } + } + + std::unordered_set walked; // The project's own notes are for its consumers, so they never go // into its own AGENTS.md, whatever dependency they sit beside. Both // places count for a symlinked project file. @@ -389,13 +482,11 @@ namespace { std::unordered_set identities; std::vector notes; - std::vector start; - for (const Configuration* dep : PragmaDependencies(projectFile)) start.push_back(dep); - start.insert(start.end(), project.dependencies.begin(), project.dependencies.end()); - for (std::vector ring = NextRing(start, walked); !ring.empty();) { + for (std::vector ring = NextRing(start, walked, others); !ring.empty();) { std::vector next; for (const Configuration* cfg : ring) { - const std::optional loaded = LoadedProjectOf(*cfg); + // Another project's, or NextRing had walked through it. + const std::optional loaded = others.Of(*cfg); const fs::path file = loaded->projectFile.parent_path() / NotesFileName; // One library under two specs (a pin here, another revision // further down) is described once, as the ring nearest the @@ -403,10 +494,9 @@ namespace { if (identities.insert(loaded->identity).second && files.insert(file).second) { if (std::optional note = ReadNote(file, loaded->name)) notes.push_back(std::move(*note)); } - next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end()); + if (followed.contains(cfg)) next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end()); } - if (project.dependencyNotes == DependencyNotes::Direct) break; - ring = NextRing(next, walked); + ring = NextRing(next, walked, others); } return notes; } @@ -504,6 +594,11 @@ std::string Crafter::MergeDependencyNotes(std::string_view templateMd, std::span } bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& projectFile) { + std::array one = { &project }; + return UpdateAgentsMd(std::span(one), projectFile); +} + +bool Crafter::UpdateAgentsMd(std::span configurations, const fs::path& projectFile) { std::error_code ec; // Beside the project file as it was named, so a symlinked project.cpp // keeps the AGENTS.md beside the link. @@ -527,7 +622,7 @@ bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& proje return false; } - const std::vector notes = project.dependencyNotes == DependencyNotes::None ? std::vector() : CollectNotes(project, projectFile, projectDir); + const std::vector notes = CollectNotes(configurations, projectFile, projectDir); std::string wanted; try { wanted = std::format("{}{}{}", GeneratedLine, LineEnd(templateMd), MergeDependencyNotes(templateMd, notes)); diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index ae6d10b..f512509 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -479,6 +479,21 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { } namespace { + // Two of `configurations` that would be built into one directory, as + // the error that names them; empty when no two would. Built side by + // side they are two builds writing the same files, and a pass that has + // built one of them hands it to whatever is built on the other. + std::string SameDirectoryError(std::span configurations) { + std::unordered_map builtInto; + for (const Configuration* cfg : configurations) { + const auto [known, added] = builtInto.try_emplace(fs::absolute(cfg->PcmDir()).lexically_normal(), cfg); + if (!added && known->second != cfg) { + return std::format("two configurations named {} would both be built into {}: give each a name of its own", cfg->name, known->first.string()); + } + } + return ""; + } + // The outcome of `work` for `key` in this build pass. The first caller // runs it; every other caller, whether at the same time or later, waits // for that run and gets its result or its exception. The keys are the @@ -1667,6 +1682,175 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map roots; + // For each of `roots`, the others it is built after, by their places + // in `roots`. + std::vector> waitsFor; + // The places in `roots`, each after the ones it waits for. + std::vector order; + // Whether a wasm executable that declares variants is among them or + // among what they are built on, so that they are built one after the + // other. + bool rewrites = false; + // Why the list is not built, as BuildAll returns it; empty when it + // is. + std::string refused; + }; + + BuildPlan PlanBuild(std::span configurations) { + BuildPlan plan; + for (Configuration* cfg : configurations) { + if (!std::ranges::contains(plan.roots, cfg)) plan.roots.push_back(cfg); + } + const std::span roots = plan.roots; + const std::size_t count = roots.size(); + const auto directory = [](const Configuration& cfg) { return fs::absolute(cfg.PcmDir()).lexically_normal(); }; + + // The directory each of them is built into, and the directories of + // everything it is built on. A wasm executable that declares + // variants builds everything it is built on once more for each of + // them, and says which variant by rewriting those configurations in + // place (the end of Build()). A library that two of these share + // would change under whichever is still building its baseline, so + // with such a configuration anywhere among them they are built one + // after the other. + std::vector builtInto(count); + std::vector> builtOn(count); + for (std::size_t index = 0; index < count; ++index) { + builtInto[index] = directory(*roots[index]); + std::unordered_set seen = { roots[index] }; + std::vector pending = { roots[index] }; + while (!pending.empty()) { + const Configuration& cfg = *pending.back(); + pending.pop_back(); + if (cfg.type == ConfigurationType::Executable && cfg.target.starts_with("wasm32") && !cfg.wasmVariants.empty()) plan.rewrites = true; + for (const Configuration* dep : cfg.dependencies) { + if (!seen.insert(dep).second) continue; + builtOn[index].insert(directory(*dep)); + pending.push_back(dep); + } + } + } + + plan.refused = SameDirectoryError(roots); + if (!plan.refused.empty()) return plan; + + // One that another is built on, which is to say that something the + // other is built on is built into its directory, is built before + // the other starts: the other then finds it built, in the record of + // the pass, instead of building it a second time beside this build + // of it. + plan.waitsFor.resize(count); + for (std::size_t index = 0; index < count; ++index) { + for (std::size_t other = 0; other < count; ++other) { + if (other != index && builtOn[index].contains(builtInto[other])) plan.waitsFor[index].push_back(other); + } + } + // One that is itself built on something of its own directory makes + // two builds for that directory, its dependency's and its own, and + // the record of the pass holds one result for a directory: another + // of them that looks there for what it is built on would be given + // one of the two, whichever it had asked for. By itself, or with no + // other of them built on that directory, it builds as it does for + // Build(). + for (std::size_t index = 0; index < count; ++index) { + if (!builtOn[index].contains(builtInto[index])) continue; + for (std::size_t other = 0; other < count; ++other) { + if (other == index || !builtOn[other].contains(builtInto[index])) continue; + plan.refused = std::format("{} and a configuration it is built on would both be built into {}, where {} looks for what it is built on: give each a name of its own", roots[index]->name, builtInto[index].string(), roots[other]->name); + return plan; + } + } + std::vector ordered(count, false); + for (bool placed = true; placed;) { + placed = false; + for (std::size_t index = 0; index < count; ++index) { + if (ordered[index] || !std::ranges::all_of(plan.waitsFor[index], [&](std::size_t other) { return ordered[other]; })) continue; + ordered[index] = true; + plan.order.push_back(index); + placed = true; + } + } + if (plan.order.size() != count) { + std::string names; + for (std::size_t index = 0; index < count; ++index) { + if (ordered[index]) continue; + if (!names.empty()) names += ", "; + names += roots[index]->name; + } + plan.refused = std::format("{}: each of these is built on something that would be built into the directory of another of them, so none of them can be built first", names); + } + return plan; + } +} + +std::string Crafter::BuildAll(std::span configurations, std::unordered_map>& depResults, std::mutex& depMutex) { + const BuildPlan plan = PlanBuild(configurations); + if (!plan.refused.empty()) return plan.refused; + const std::size_t count = plan.roots.size(); + + std::vector errors(count); + const auto build = [&](std::size_t index) { + Configuration& cfg = *plan.roots[index]; + // By Build() itself, as a project's one configuration always was, + // and only then put into the record of the pass, where a + // configuration that depends on this one looks for it, with what + // the build returned or threw. Recorded while it is still being + // built, it would be handed to a dependency of its own that is + // built into the same directory, which would wait for the build + // that is waiting for it. Such a dependency has left its own result + // under that directory by now, and this one's takes its place: no + // other of them is built on that directory, or the set was refused. + std::promise built; + try { + BuildResult result = Build(cfg, depResults, depMutex); + errors[index] = result.result; + built.set_value(std::move(result)); + } catch (const std::exception& e) { + errors[index] = std::format("build of {} threw: {}", cfg.name, e.what()); + built.set_exception(std::current_exception()); + } catch (...) { + errors[index] = std::format("build of {} threw something that is not a std::exception", cfg.name); + built.set_exception(std::current_exception()); + } + const std::lock_guard lock(depMutex); + depResults.insert_or_assign(cfg.PcmDir(), built.get_future().share()); + }; + + if (plan.rewrites) { + for (const std::size_t index : plan.order) build(index); + } else { + std::vector> finishes(count); + std::vector> finished; + finished.reserve(count); + for (std::promise& finish : finishes) finished.push_back(finish.get_future().share()); + const auto buildInTurn = [&](std::size_t index) { + for (const std::size_t other : plan.waitsFor[index]) finished[other].wait(); + build(index); + finishes[index].set_value(); + }; + // The first on this thread, so a project of one configuration is + // built where it always was. + std::vector others; + others.reserve(count); + for (std::size_t index = 1; index < count; ++index) others.emplace_back(buildInTurn, index); + if (count > 0) buildInTurn(0); + } + + std::string failed; + for (auto error = errors.begin(); error != errors.end(); ++error) { + if (error->empty() || std::ranges::contains(errors.begin(), error, *error)) continue; + if (!failed.empty()) failed += '\n'; + failed += *error; + } + return failed; +} + namespace { FlatpakExport ExportOf(const Configuration& config) { FlatpakExport app; @@ -1700,6 +1884,41 @@ namespace { return ""; } + // The names of `configurations`, as a message lists them. + std::string NamesOf(std::span configurations) { + std::string names; + for (const Configuration* cfg : configurations) { + if (!names.empty()) names += ", "; + names += cfg->name; + } + return names; + } + + // What install or bundle exports of the configurations a project file + // returns: the only one, or of several the one packaged as a Flatpak. + struct ExportChoice { + // Null when none of several is packaged, or more than one is. + const Configuration* config = nullptr; + // Why `config` cannot be exported, or why there is none; empty when + // it can be. + std::string refused; + }; + + ExportChoice ChooseExport(std::span configurations, std::string_view verb) { + std::vector packaged; + for (const Configuration* cfg : configurations) { + if (cfg->ResolvedPackaging() == Packaging::Flatpak) packaged.push_back(cfg); + } + if (packaged.size() > 1) { + return { nullptr, std::format("crafter-build {0}: {1} are each packaged as a Flatpak, and {0} exports one app", verb, NamesOf(packaged)) }; + } + if (packaged.empty() && configurations.size() > 1) { + return { nullptr, std::format("crafter-build {0}: none of {1} is packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp on the one to {0}", verb, NamesOf(configurations)) }; + } + const Configuration* const config = packaged.empty() ? configurations.front() : packaged.front(); + return { config, ExportRefusal(*config, verb) }; + } + // A repo's path as the file:// URL of a remote: percent-encoded, since // `remote-modify --url=` stores what it is given as it is. std::string FileUrl(const fs::path& path) { @@ -2151,7 +2370,9 @@ R"(Usage: Loads ./project.cpp (override with --project=), compiles it to a shared object, and invokes its CrafterBuildProject() to obtain a Configuration that drives the build. Outputs land at bin/--/, intermediates -at build/--/. +at build/--/. A project of several configurations +defines CrafterBuildConfigurations() instead, which returns them all and gets +the same args, and every one of them is built. A build runs at most as many of its steps at once as the machine has hardware threads: the compiles of its sources, its shaders and assets, and its links @@ -2165,7 +2386,8 @@ Build options: one for the host in its own directory, a wasm32 one under wasmtime or wasmer, or one built for the browser served over HTTP from its directory. - Libraries cannot be run. + Libraries cannot be run, and of several + configurations one has to be the only executable. -v, --verbose Verbose progress output. -q, --quiet Suppress progress output. --project= Path to the project file (default: ./project.cpp). @@ -2244,7 +2466,9 @@ Install and bundle (after the `install` or `bundle` subcommand): run the host's flatpak, inside crafter-build's Flatpak through flatpak-spawn --host, and refuse a project whose bin/ and build/ the host does not see where crafter-build does, as in the sandbox's own /tmp, /var, - /usr, /etc and /app, which they ask the host before building. + /usr, /etc and /app, which they ask the host before building. Of several + configurations they export the one that is packaged as a Flatpak, and + refuse before building when none is, or more than one. Clean (after the `clean` subcommand): Removes bin/ and build/ next to the project file. Does not load project.cpp, @@ -2263,14 +2487,14 @@ AGENTS.md: Direct, or None. Project args: - Any flag not consumed above is forwarded verbatim to CrafterBuildProject as - part of its `args` span. Project-specific flags (e.g. --target=, custom - feature toggles) live there. ApplyStandardArgs reads --debug, --target=, - --march=, --mtune=, --cuda-arch=, --sysroot=, --lib, --shared and - --packaging=none|flatpak, the last for the project crafter-build was pointed - at only. Flags it does not itself interpret are folded into the variant - hash, so switching one lands in its own bin/ and build/ directory instead of - overwriting the other setting's. + Any flag not consumed above is forwarded verbatim to the project file's + entry point as part of its `args` span. Project-specific flags (e.g. + --target=, custom feature toggles) live there. ApplyStandardArgs reads + --debug, --target=, --march=, --mtune=, --cuda-arch=, --sysroot=, --lib, + --shared and --packaging=none|flatpak, the last for the project + crafter-build was pointed at only. Flags it does not itself interpret are + folded into the variant hash, so switching one lands in its own bin/ and + build/ directory instead of overwriting the other setting's. Environment: CRAFTER_BUILD_MARCH Override -march (default: native). @@ -2436,7 +2660,7 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { return 1; } - // Ahead of LoadProject on purpose — see CleanProject. + // Ahead of the load on purpose — see CleanProject. if (verb == Verb::Clean) { std::vector removed = CleanProject(projectFile); if (removed.empty()) { @@ -2447,19 +2671,31 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { return 0; } - Configuration config = LoadProject(projectFile, projectArgs); - SetParentProject(&config); + // What the project file describes: one configuration, or several + // that are all built. + const std::vector configurations = LoadConfigurations(projectFile, projectArgs); + // The ones the file made itself: every one but those that another + // project's file returned to GitProject or LocalProject. One of + // those, returned here in turn, is built with the rest, and -r, + // install and bundle count it among them, but its tests and its + // scripts stay that project's: `run` still reaches no script but + // those of the project crafter-build was pointed at. + std::vector own; + for (Configuration* cfg : configurations) { + if (!LoadedProjectOf(*cfg)) own.push_back(cfg); + } + SetParentProject(configurations); if (verb == Verb::Run) { scriptOpts.projectFile = fs::absolute(projectFile).lexically_normal(); - return RunScript(config, scriptOpts); + return RunScript(own, scriptOpts); } if (verb == Verb::Lint || verb == Verb::Format) { // lexically_normal: fs::absolute keeps a "./" component, which // would leak into displayed paths and the project-root derivation. lintOpts.projectFile = fs::absolute(projectFile).lexically_normal(); - LintSummary lintSummary = RunLint(config, lintOpts); + LintSummary lintSummary = RunLint(configurations, lintOpts); if (verb == Verb::Lint) return lintSummary.Clean() ? 0 : 1; if (lintSummary.noRulesDefined || lintSummary.errors > 0) return 1; // Apply: formatting files is success (gofmt convention). @@ -2469,51 +2705,76 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { // What install and bundle cannot export they refuse here, before // anything is built: a project that is not packaged as a Flatpak, or - // a host flatpak out of reach, is known from the loaded project. + // a host flatpak out of reach, is known from the loaded project, and + // so is which of several configurations is the app. + ExportChoice exported; if (verb == Verb::Install || verb == Verb::Bundle) { - if (const std::string refused = ExportRefusal(config, verb == Verb::Install ? "install" : "bundle"); !refused.empty()) { - std::println(std::cerr, "{}", refused); + exported = ChooseExport(configurations, verb == Verb::Install ? "install" : "bundle"); + if (!exported.refused.empty()) { + std::println(std::cerr, "{}", exported.refused); return 1; } } + // What the list itself rules out is refused here too, before any of + // it is built and before AGENTS.md is written: two returned + // configurations of one directory for every verb that builds, and + // for the verbs that build the configurations themselves whatever + // else BuildAll refuses a list for. `test` builds its tests with + // Build() and never comes to BuildAll, which makes these refusals + // again for whoever calls it. + if (const std::string refused = verb == Verb::Test ? SameDirectoryError(configurations) : PlanBuild(configurations).refused; !refused.empty()) { + Progress::Clear(); + std::println(std::cerr, "{}", refused); + return 1; + } + // Builds and test runs only: lint and `format --check` promise to // write nothing, `format` rewrites the project's sources and nothing // else, `run` is for chores and `test --list` only lists. Here, // before compiling, because loading has just fetched every // dependency, so the notes are current, and an agent fixing a build // that fails needs them. - if (!testOpts.listOnly) UpdateAgentsMd(config, projectFile); + if (!testOpts.listOnly) UpdateAgentsMd(configurations, projectFile); if (verb == Verb::Test) { - TestSummary summary = RunTests(config, testOpts, projectArgs); + TestSummary summary = RunTests(own, testOpts, projectArgs); return summary.AllPassed() ? 0 : 1; } std::unordered_map> depResults; std::mutex depMutex; - BuildResult result = Build(config, depResults, depMutex); - - if (!result.result.empty()) { + if (const std::string failed = BuildAll(configurations, depResults, depMutex); !failed.empty()) { Progress::Clear(); - std::println(std::cerr, "{}", result.result); + std::println(std::cerr, "{}", failed); return 1; } Progress::Finalize(); if (verb == Verb::Install || verb == Verb::Bundle) { - const std::string failed = verb == Verb::Install ? InstallFlatpakApp(config) : BundleFlatpakApp(config); + const std::string failed = verb == Verb::Install ? InstallFlatpakApp(*exported.config) : BundleFlatpakApp(*exported.config); if (failed.empty()) return 0; std::println(std::cerr, "{}", failed); return 1; } if (runAfterBuild) { - if (config.type != ConfigurationType::Executable) { + std::vector executables; + for (const Configuration* cfg : configurations) { + if (cfg->type == ConfigurationType::Executable) executables.push_back(cfg); + } + if (executables.empty()) { std::println(std::cerr, "-r: cannot run a library"); return 1; } + // Everything is built by now, as without -r. Which one to run + // would be a guess. + if (executables.size() > 1) { + std::println(std::cerr, "-r: {} are executables, and -r runs one", NamesOf(executables)); + return 1; + } + const Configuration& config = *executables.front(); fs::path dir = config.ProgramDir(); fs::path artifact = fs::absolute(ExpectedOutput(config)); fs::path absDir = fs::absolute(dir); diff --git a/implementations/Crafter.Build-External.cpp b/implementations/Crafter.Build-External.cpp index 0a0c7a2..8469828 100644 --- a/implementations/Crafter.Build-External.cpp +++ b/implementations/Crafter.Build-External.cpp @@ -336,40 +336,33 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std: namespace { std::mutex ProjectCacheMutex; - std::unordered_map> ProjectCache; - // Keyed by the Configurations ProjectCache owns, which live as long as - // the process does, so the pointers never dangle. Guarded by - // ProjectCacheMutex as well. + // What each project file loaded here returned, in the file's order, by + // spec and args. An entry is never changed or removed once it is in. + std::unordered_map> ProjectCache; + // Keyed by the Configurations ProjectCache holds, which live as long as + // the process does (see LoadConfigurations), so the pointers never + // dangle. Guarded by ProjectCacheMutex as well. std::unordered_map LoadedProjects; + // The configurations a loaded project keeps to itself, with the project: + // what the configurations its file returned led to when the file was + // loaded and the file did not return. A configuration leads to what it + // is built on and to the configurations of its tests, and each of those + // leads on in the same way. Taken down at that moment, since a consumer + // may add to the `dependencies` of a configuration it was given, and + // what it adds is its own. Guarded by ProjectCacheMutex as well. + std::unordered_map KeptConfigurations; - // Run the dep's project.cpp from its own directory so its relative paths - // (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep - // root, then rebase cfg.path and all other relative path collections to - // absolute so Build() can run from any cwd without misresolving them. - // The mutex is NOT held across LoadProject — the dep may itself call - // GitProject/LocalProject, and a non-recursive lock would deadlock. - // - // The Configuration is made on the heap with the call as its - // initialiser, so it is constructed where the cache keeps it and is - // never moved. A project file takes pointers to the Configuration it - // returns, for a test that links the library it describes - // (cfg.AddTest(...).Dependencies({ &cfg })), and they are pointers to - // this object when the compiler constructed the local the file returns - // in place of the return value, as clang does for a function that - // returns one local. Assigned to a local here and moved into the cache - // from there, the Configuration left every such pointer behind. - std::unique_ptr LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span args) { - fs::path savedCwd = fs::current_path(); - std::unique_ptr made; - fs::current_path(depRoot); - try { - made.reset(new Configuration(LoadProject(projectPath, args))); - } catch (...) { - fs::current_path(savedCwd); - throw; - } - fs::current_path(savedCwd); - Configuration& cfg = *made; + // What the cache holds under `fullHash`, or nullptr. + const std::vector* CachedProject(const std::string& fullHash) { + const std::lock_guard lock(ProjectCacheMutex); + const auto it = ProjectCache.find(fullHash); + return it == ProjectCache.end() ? nullptr : &it->second; + } + + // cfg.path and every other relative path collection of `cfg`, made + // absolute against `depRoot`, so Build() can run from any cwd without + // misresolving them. + void RebaseOnto(Configuration& cfg, const fs::path& depRoot) { cfg.path = fs::absolute(depRoot / cfg.path).lexically_normal(); auto abs = [&](const fs::path& p) -> fs::path { return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal(); @@ -389,21 +382,81 @@ namespace { for (auto& entry : cfg.flatpak.share) { if (!entry.source.empty()) entry.source = abs(entry.source); } - return made; } - // Into ProjectCache under `fullHash`, with `loaded` recorded beside it. - // When another thread stored the same spec first, its Configuration - // wins and `cfg` is dropped. - Configuration* StoreProject(std::string fullHash, std::unique_ptr cfg, LoadedProject loaded) { - std::lock_guard lock(ProjectCacheMutex); - if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { - return it->second.get(); + // Run the dep's project.cpp from its own directory so its relative paths + // (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep + // root, then rebase every configuration it returns onto that root. + // The mutex is NOT held across the load — the dep may itself call + // GitProject/LocalProject, and a non-recursive lock would deadlock. + std::vector LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span args) { + fs::path savedCwd = fs::current_path(); + std::vector configurations; + fs::current_path(depRoot); + try { + configurations = LoadConfigurations(projectPath, args); + } catch (...) { + fs::current_path(savedCwd); + throw; } - Configuration* ptr = cfg.get(); - ProjectCache.emplace(std::move(fullHash), std::move(cfg)); - LoadedProjects.emplace(ptr, std::move(loaded)); - return ptr; + fs::current_path(savedCwd); + for (Configuration* cfg : configurations) { + // One the file loaded from another project file and returns + // itself was rebased onto that project's root when it was + // loaded, and other consumers may be reading it by now. + if (!LoadedProjectOf(*cfg)) RebaseOnto(*cfg, depRoot); + } + return configurations; + } + + // Into ProjectCache under `fullHash`, with `loaded` recorded beside each + // configuration that is not another project's already, and beside what + // those are built on and the file kept to itself. When another thread + // stored the same spec first, what it stored wins. + const std::vector& StoreProject(std::string fullHash, std::vector configurations, const LoadedProject& loaded) { + const std::lock_guard lock(ProjectCacheMutex); + if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { + return it->second; + } + // What this file returned, and then what each of those leads to: + // what it is built on and the configurations of its tests. One that + // another project's file returned is that project's, and so is what + // is found from there. + std::vector pending; + const auto leadsTo = [&pending](const Configuration& cfg) { + pending.insert(pending.end(), cfg.dependencies.begin(), cfg.dependencies.end()); + for (const Test& test : cfg.tests) pending.push_back(&test.config); + }; + for (const Configuration* cfg : configurations) { + if (LoadedProjects.try_emplace(cfg, loaded).second) leadsTo(*cfg); + } + while (!pending.empty()) { + const Configuration* kept = pending.back(); + pending.pop_back(); + if (!kept || LoadedProjects.contains(kept) || !KeptConfigurations.try_emplace(kept, loaded).second) continue; + leadsTo(*kept); + } + return ProjectCache.emplace(std::move(fullHash), std::move(configurations)).first->second; + } + + // The one of `configurations` a spec asks for by `name`: the first for + // an empty name. `what` names the spec in the error for a name that none + // has, or that two have. + Configuration* PickConfiguration(std::span configurations, std::string_view name, std::string_view what) { + if (name.empty()) return configurations.front(); + Configuration* picked = nullptr; + for (Configuration* cfg : configurations) { + if (cfg->name != name) continue; + if (picked) throw std::runtime_error(std::format("{}: two of its configurations are named '{}', so the name picks neither", what, name)); + picked = cfg; + } + if (picked) return picked; + std::string names; + for (const Configuration* cfg : configurations) { + if (!names.empty()) names += ", "; + names += cfg->name; + } + throw std::runtime_error(std::format("{}: no configuration named '{}' (it has: {})", what, name, names)); } // `url` as it names a repository: without user info, which is where a @@ -425,10 +478,11 @@ namespace { Configuration* Crafter::GitProject(const GitProjectSpec& spec) { // Two hashes: the clone is shared across specs that point at the same // source revision (forwarded args don't change what gets cloned, just - // how the dep's project.cpp interprets them at runtime), while the - // in-memory Configuration is keyed by the full spec so each (args) - // permutation gets its own Configuration object, and host tooling one - // apart from the target's even for the same args. + // how the dep's project.cpp interprets them at runtime), while what the + // file returned is keyed by the args as well, so each (args) + // permutation gets its own Configuration objects, and host tooling ones + // apart from the target's even for the same args. Which configuration + // the spec picks is in neither: it chooses among what one load returned. std::string srcKey = std::format("git|{}|{}|{}|{}", spec.source.url, spec.source.branch, spec.source.commit, spec.projectFile.string()); std::string srcHash = std::format("{:016x}", std::hash{}(srcKey)); @@ -438,12 +492,10 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) { fullKey += a; } std::string fullHash = std::format("{:016x}", std::hash{}(fullKey)); + const std::string what = std::format("GitProject({})", spec.source.url); - { - std::lock_guard lock(ProjectCacheMutex); - if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { - return it->second.get(); - } + if (const std::vector* cached = CachedProject(fullHash)) { + return PickConfiguration(*cached, spec.configuration, what); } std::string name = DeriveName(spec.source); @@ -471,15 +523,15 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) { } std::vector argViews(spec.args.begin(), spec.args.end()); - std::unique_ptr cfg = LoadProjectFromRoot(projectPath, cloneDir, argViews); + std::vector configurations = LoadProjectFromRoot(projectPath, cloneDir, argViews); const fs::path projectInRepo = spec.projectFile.lexically_normal(); const fs::path below = projectInRepo.parent_path(); - return StoreProject(std::move(fullHash), std::move(cfg), { + return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), { .projectFile = projectPath.lexically_normal(), .name = below.empty() ? name : std::format("{}/{}", name, below.generic_string()), .identity = std::format("git|{}|{}", RepositoryKey(spec.source.url), projectInRepo.generic_string()), - }); + }), spec.configuration, what); } fs::path Crafter::GitFetch(const GitSource& source) { @@ -522,23 +574,21 @@ Configuration* Crafter::LocalProject(const LocalProjectSpec& spec) { fullKey += a; } std::string fullHash = std::format("{:016x}", std::hash{}(fullKey)); + const std::string what = std::format("LocalProject({})", canonical.string()); - { - std::lock_guard lock(ProjectCacheMutex); - if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { - return it->second.get(); - } + if (const std::vector* cached = CachedProject(fullHash)) { + return PickConfiguration(*cached, spec.configuration, what); } fs::path depRoot = canonical.parent_path(); std::vector argViews(spec.args.begin(), spec.args.end()); - std::unique_ptr cfg = LoadProjectFromRoot(canonical, depRoot, argViews); + std::vector configurations = LoadProjectFromRoot(canonical, depRoot, argViews); - return StoreProject(std::move(fullHash), std::move(cfg), { + return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), { .projectFile = canonical, .name = depRoot.filename().string(), .identity = std::format("local|{}", canonical.string()), - }); + }), spec.configuration, what); } std::optional Crafter::LoadedProjectOf(const Configuration& cfg) { @@ -546,3 +596,9 @@ std::optional Crafter::LoadedProjectOf(const Configuration& cfg) if (auto it = LoadedProjects.find(&cfg); it != LoadedProjects.end()) return it->second; return std::nullopt; } + +std::optional Crafter::KeptBy(const Configuration& cfg) { + const std::lock_guard lock(ProjectCacheMutex); + if (const auto it = KeptConfigurations.find(&cfg); it != KeptConfigurations.end()) return it->second; + return std::nullopt; +} diff --git a/implementations/Crafter.Build-Lint.cpp b/implementations/Crafter.Build-Lint.cpp index d1b1258..619fc8c 100644 --- a/implementations/Crafter.Build-Lint.cpp +++ b/implementations/Crafter.Build-Lint.cpp @@ -866,18 +866,28 @@ namespace { // whose path lies inside the project root — GitProject / external deps // live under the global cache and are foreign code: they contribute // neither rules nor files. Root-first order so the root's rules win the - // by-name dedup. - std::vector CollectLocalConfigs(Configuration& root, const fs::path& projectRoot) { + // by-name dedup. Of several roots, the configurations a project file + // returns, every root comes first, in the order given, and what they + // depend on after them: walked one root's graph after another, a root + // that an earlier one depends on would come before the roots between + // the two, and its rule would win over theirs. + std::vector CollectLocalConfigs(std::span roots, const fs::path& projectRoot) { std::vector local; std::unordered_set seen; - std::function walk = [&](Configuration* c) { - if (!seen.insert(c).second) return; - if (PathInsideRoot(fs::absolute(c->path), projectRoot)) { - local.push_back(c); - } - for (Configuration* dep : c->dependencies) walk(dep); + const auto keep = [&](Configuration* c) { + if (PathInsideRoot(fs::absolute(c->path), projectRoot)) local.push_back(c); }; - walk(&root); + std::function below = [&](Configuration* c) { + for (Configuration* dep : c->dependencies) { + if (!seen.insert(dep).second) continue; + keep(dep); + below(dep); + } + }; + for (Configuration* root : roots) { + if (seen.insert(root).second) keep(root); + } + for (Configuration* root : roots) below(root); return local; } @@ -1069,6 +1079,11 @@ void Configuration::AddAstLintRule(std::string name, std::function one = { &projectCfg }; + return RunLint(std::span(one), opts); +} + +LintSummary Crafter::RunLint(std::span configurations, const RunLintOptions& opts) { LintSummary summary; // libclang backs the lexer every rule reads through, so a failed load is @@ -1081,10 +1096,10 @@ LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& op } fs::path projectRoot = opts.projectFile.empty() - ? fs::absolute(projectCfg.path) + ? fs::absolute(configurations.empty() ? fs::path() : configurations.front()->path) : opts.projectFile.parent_path(); - std::vector localConfigs = CollectLocalConfigs(projectCfg, projectRoot); + std::vector localConfigs = CollectLocalConfigs(configurations, projectRoot); // The tests' compile commands are worked out as RunTests builds them. for (Configuration* c : localConfigs) UnpackageTests(*c); @@ -1133,7 +1148,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would. CollectConfigSources(*c, files); for (const Test& t : c->tests) CollectConfigSources(t.config, files); } - // project.cpp is not built by Build() at all — LoadProject compiles it + // project.cpp is not built by Build() at all — its load compiles it // against the host PCM cache with its own flags, so it is owned by nothing // here and gets no compile command. Token rules still cover it. if (!opts.projectFile.empty()) files.emplace(opts.projectFile, nullptr); @@ -1217,7 +1232,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would. continue; } // No compile command means this file is not a translation unit - // of the build graph — project.cpp, which LoadProject compiles + // of the build graph — project.cpp, which its load compiles // with its own flags, or a header. A semantic rule does not // apply there, the same way a rule self-filters by extension, // so skip it quietly. That is a different thing from a file we diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index fec4cfa..45aabae 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -313,7 +313,7 @@ namespace { std::string Crafter::RunBuildCommand(std::string_view cmd) { // A job is on a worker already and runs the command where it is. A link, // or the precompile of the std module, comes from the thread of a Build() - // or a LoadProject and waits here for its turn among the jobs. + // or of a project file's load and waits here for its turn among the jobs. std::string result; JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); }); return result; @@ -328,7 +328,7 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) { // file, so this is a directive next to the `import` it enables — where // `#include` lives. Each one is fetched, built for the host, and put on // project.so's module path and link line before project.cpp is compiled. The -// dependency's own project.cpp goes through LoadProject, so its pragmas +// dependency's own project.cpp is loaded the same way, so its pragmas // resolve recursively. namespace { struct PragmaDependency { @@ -429,18 +429,18 @@ namespace { struct ProjectFileFrame { fs::path project; - // What LoadProject was given, for ProjectArgs(), and only once - // CrafterBuildProject is about to be called (see LoadProject). A view - // is enough: the caller's storage outlives LoadProject, and the frame - // is popped before LoadProject returns. + // What the load was given, for ProjectArgs(), and only once the + // entry point is about to be called (see OpenProjectFile). A view + // is enough: the caller's storage outlives the load, and the frame + // is popped before the load returns. std::span args; std::vector dependencies; }; - // LoadProject nests: a dependency's project.cpp loads inside its - // consumer's pre-pass, and GitProject inside CrafterBuildProject nests - // again. Several threads may also load at once (ConcurrentCacheRace), so - // the stack is per thread. ProjectDependency() reads the top frame. + // Loads nest: a dependency's project.cpp loads inside its consumer's + // pre-pass, and GitProject inside an entry point nests again. Several + // threads may also load at once (ConcurrentCacheRace), so the stack is + // per thread. ProjectDependency() reads the top frame. thread_local std::vector LoadingFrames; // A frame's dependencies, kept past the frame for PragmaDependencies(). @@ -450,7 +450,7 @@ namespace { std::mutex PragmaDependenciesMutex; std::unordered_map> PragmaDependenciesByProject; - // Held for the whole of one LoadProject call. Pushing a file that is + // Held for the whole of one load of a project file. Pushing one that is // already on the stack is a cycle, which used to recurse forever. class ProjectFileGuard { public: @@ -491,7 +491,7 @@ namespace { // A pre-dependency is host tooling: project.so is loaded into the running // crafter-build, so the dependency is built for the host and against the - // same PCM cache LoadProject populates — the hostConfig LoadProject itself + // same PCM cache a load populates — the hostConfig the load itself // compiles project.so with, so the dependency's std/Crafter.Build PCMs // land in the cache dir project.so is built against. Recursive, because // the dependency's project.cpp is loaded with no arguments and so passes @@ -523,7 +523,7 @@ namespace { // Every dependency's BuildResult.libs, verbatim, then its runtimeLibs, // the CUDA runtime, then a run path per directory of its runPaths // (RunPathFlags), as Build() links a program: the shared libraries a - // pragma dependency is built on are found there when LoadProject + // pragma dependency is built on are found there when the load // dlopens project.so. std::string linkFlags; fs::file_time_type newestArtifact = fs::file_time_type::min(); @@ -548,7 +548,7 @@ namespace { for (const PragmaDependency& pragma : pragmas) { // Neither spec sets args, and the tool still gets none of the - // consumer's: this pre-pass runs before LoadProject hands the + // consumer's: this pre-pass runs before the load hands the // frame its args, so ProjectArgs() is empty. Given the consumer's // --target=, the tool's project.cpp would pick sources and flags // for the wrong triple, and its flags would split the tool's @@ -566,7 +566,7 @@ namespace { cfg = GitProject(spec); } else { if (!pragma.branch.empty() || !pragma.commit.empty()) PragmaError(absProject, pragma.line, "'branch' and 'commit' only apply to a git source"); - // Relative to the project file, not the cwd: LoadProject runs + // Relative to the project file, not the cwd: the load runs // from wherever the consumer was invoked. fs::path local = (absProject.parent_path() / pragma.source).lexically_normal(); if (fs::is_directory(local)) { @@ -1067,10 +1067,32 @@ namespace { } } -Configuration Crafter::LoadProject(const fs::path& projectFile, std::span args) { - RequireToolchain(); - fs::path absProject = fs::canonical(projectFile); - ProjectFileGuard guard(absProject); +namespace { + using ProjectFn = Configuration (*)(std::span); + using ConfigurationsFn = std::vector (*)(std::span); + + // The entry point of a loaded project file: one of the two is set. + struct ProjectEntry { + ProjectFn one = nullptr; + ConfigurationsFn several = nullptr; + }; + + // Every Configuration a CrafterBuildProject returned to + // LoadConfigurations, kept for the rest of the process like the ones a + // CrafterBuildConfigurations returns, which its project file keeps: + // whoever holds a pointer LoadConfigurations gave out, the project cache + // or a consumer's `dependencies`, holds it that long. + std::mutex ReturnedConfigurationsMutex; + std::vector> ReturnedConfigurations; +} + +// Compiles the project file `guard` holds into project.so, unless the one +// there is current, loads it and finds its entry point. The frame holds +// `args` once this returns, for the call the caller makes next. +static ProjectEntry OpenProjectFile(ProjectFileGuard& guard, std::span args) { + // A copy: the loads of the file's dependencies push frames of their own, + // which can move this one. + const fs::path absProject = guard.Frame().project; fs::path buildDir = absProject.parent_path() / "build"; if (!fs::exists(buildDir)) { fs::create_directories(buildDir); @@ -1154,11 +1176,20 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span); - dlerror(); - auto fn = reinterpret_cast(dlsym(handle, "CrafterBuildProject")); - if (const char* err = dlerror()) { - throw std::runtime_error(std::format("CrafterBuildProject not found in {}: {}", soPath.string(), err)); + // Looked up in project.so and the libraries it links, which is where + // dlsym searches for a handle: every project file this process has + // loaded exports an entry point under one of these two names, and none + // of the others is found here. + ProjectEntry entry; + entry.one = reinterpret_cast(dlsym(handle, "CrafterBuildProject")); + entry.several = reinterpret_cast(dlsym(handle, "CrafterBuildConfigurations")); + if (!entry.one && !entry.several) { + throw std::runtime_error(std::format("{} defines neither CrafterBuildProject nor CrafterBuildConfigurations (looked in {})", absProject.string(), soPath.string())); + } + // Calling the first would leave what the second returns unbuilt, and + // the other way around, without a word. + if (entry.one && entry.several) { + throw std::runtime_error(std::format("{} defines both CrafterBuildProject and CrafterBuildConfigurations; a project file has one entry point", absProject.string())); } // The args only for the call itself, unlike the dependencies. A static @@ -1168,5 +1199,67 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span args) { + RequireToolchain(); + const fs::path absProject = fs::canonical(projectFile); + ProjectFileGuard guard(absProject); + const ProjectEntry entry = OpenProjectFile(guard, args); + if (!entry.one) { + throw std::runtime_error(std::format("{} defines CrafterBuildConfigurations, which LoadProject cannot return by value; load it with LoadConfigurations", absProject.string())); + } + return entry.one(args); +} + +std::vector Crafter::LoadConfigurations(const fs::path& projectFile, std::span args) { + RequireToolchain(); + const fs::path absProject = fs::canonical(projectFile); + ProjectFileGuard guard(absProject); + const ProjectEntry entry = OpenProjectFile(guard, args); + if (entry.one) { + // The call's return value is the initialiser of the new-expression, + // so the Configuration is constructed where it stays and is never + // moved; std::make_unique would move a temporary into place. A + // project file takes pointers to the configuration it returns, for a + // test that links the library it describes (cfg.AddTest(...) + // .Dependencies({ &cfg })), and they are pointers to this object + // when the compiler constructed the local the file returns in place + // of the return value, as clang does for a function that returns one + // local. + std::unique_ptr returned(new Configuration(entry.one(args))); + Configuration* const configuration = returned.get(); + const std::lock_guard lock(ReturnedConfigurationsMutex); + ReturnedConfigurations.push_back(std::move(returned)); + return { configuration }; + } + + std::vector configurations = entry.several(args); + if (configurations.empty()) { + throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned no configuration", absProject.string())); + } + std::unordered_set seen; + for (const Configuration* configuration : configurations) { + if (!configuration) { + throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned a null pointer", absProject.string())); + } + // Most often a pasted `&lib` where `&tool` was meant, which would + // leave `tool` unbuilt without a word. + if (!seen.insert(configuration).second) { + throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {} twice", absProject.string(), configuration->name)); + } + // One that a project GitProject or LocalProject loaded keeps to + // itself, taken out of the `dependencies` or the `tests` of what + // that project's file returned. Returned from here it would count + // as one this file + // made: `test` would run its tests and `run` offer its scripts, + // which are that project's. And only the configurations a project + // file returns are rebased onto its directory, so this one would be + // built wherever its relative `path` leads from here. + if (const std::optional keeper = KeptBy(*configuration)) { + throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {}, which {} keeps to itself: a project file returns the configurations it makes and the ones GitProject or LocalProject returned", absProject.string(), configuration->name, keeper->name)); + } + } + return configurations; } diff --git a/implementations/Crafter.Build-Script.cpp b/implementations/Crafter.Build-Script.cpp index f08d219..bbeff51 100644 --- a/implementations/Crafter.Build-Script.cpp +++ b/implementations/Crafter.Build-Script.cpp @@ -11,11 +11,18 @@ namespace fs = std::filesystem; using namespace Crafter; namespace { - std::string JoinNames(std::span scripts) { + // A script and the configuration it is declared on, which is the + // project its callback is handed. + struct Declared { + const Script* script; + Configuration* owner; + }; + + std::string JoinNames(std::span scripts) { std::string out; - for (const Script& script : scripts) { + for (const Declared& declared : scripts) { if (!out.empty()) out += ", "; - out += script.name; + out += declared.script->name; } return out; } @@ -29,10 +36,22 @@ std::int32_t ScriptContext::Run(std::string_view command) const { } std::int32_t Crafter::RunScript(Configuration& projectCfg, const RunScriptOptions& opts) { + std::array one = { &projectCfg }; + return RunScript(std::span(one), opts); +} + +std::int32_t Crafter::RunScript(std::span configurations, const RunScriptOptions& opts) { // Loading the project may have left an in-place status line behind. Progress::Clear(); - const std::span scripts = projectCfg.scripts; + std::vector scripts; + std::unordered_set listed; + for (Configuration* cfg : configurations) { + // Once, however often the list names it: its scripts are not names + // declared twice. + if (!listed.insert(cfg).second) continue; + for (const Script& script : cfg->scripts) scripts.push_back({ &script, cfg }); + } if (scripts.empty()) { std::println(std::cerr, R"msg(No scripts defined. @@ -51,7 +70,8 @@ returned; ctx.args holds the arguments.)msg"); // declaration is reported the first time anyone uses `run` and not only // when that one name is asked for. std::unordered_set seen; - for (const Script& script : scripts) { + for (const Declared& declared : scripts) { + const Script& script = *declared.script; if (script.name.empty() || script.name.starts_with('-')) { std::println(std::cerr, "script name '{}' cannot be run: a name must not be empty or start with '-'", script.name); return 1; @@ -69,36 +89,37 @@ returned; ctx.args holds the arguments.)msg"); } if (opts.listOnly || !opts.named) { - for (const Script& script : scripts) std::println("{}", script.name); + for (const Declared& declared : scripts) std::println("{}", declared.script->name); return 0; } - const auto found = std::ranges::find(scripts, opts.name, &Script::name); + const auto found = std::ranges::find_if(scripts, [&](const Declared& declared) { return declared.script->name == opts.name; }); if (found == scripts.end()) { std::println(std::cerr, "No script named '{}'. Scripts: {}", opts.name, JoinNames(scripts)); return 1; } + const Script& script = *found->script; ScriptContext ctx{ - .project = projectCfg, + .project = *found->owner, // lexically_normal: fs::absolute keeps a "./" component. - .projectDir = opts.projectFile.empty() ? fs::absolute(projectCfg.path).lexically_normal() : opts.projectFile.parent_path(), + .projectDir = opts.projectFile.empty() ? fs::absolute(found->owner->path).lexically_normal() : opts.projectFile.parent_path(), .args = opts.args, }; try { - const std::int32_t code = found->run(ctx); + const std::int32_t code = script.run(ctx); if (code >= 0 && code <= 255) return code; - std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", found->name, code); + std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", script.name, code); return 1; } catch (const std::exception& e) { // Never let a script's exception unwind across the project.so // boundary and out of Run: report it as this script's failure. Progress::Clear(); - std::println(std::cerr, "script '{}' failed: {}", found->name, e.what()); + std::println(std::cerr, "script '{}' failed: {}", script.name, e.what()); return 1; } catch (...) { Progress::Clear(); - std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", found->name); + std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", script.name); return 1; } } diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index c0b6c66..484300a 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -111,7 +111,8 @@ namespace { } namespace { - std::atomic ParentProject{nullptr}; + std::mutex ParentProjectsMutex; + std::vector ParentProjects; Configuration* FindLibInTree(Configuration* root, std::string_view name, std::unordered_set& seen) { if (!seen.insert(root).second) return nullptr; @@ -124,17 +125,31 @@ namespace { } void Crafter::SetParentProject(Configuration* parent) { - ParentProject.store(parent); + SetParentProject(parent ? std::span(&parent, 1) : std::span()); +} + +void Crafter::SetParentProject(std::span parents) { + const std::lock_guard lock(ParentProjectsMutex); + ParentProjects.assign(parents.begin(), parents.end()); } Configuration* Crafter::ParentLib(std::string_view name) { - Configuration* root = ParentProject.load(); - if (!root) { + std::vector roots; + { + const std::lock_guard lock(ParentProjectsMutex); + roots = ParentProjects; + } + if (roots.empty()) { throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name)); } std::unordered_set seen; - if (auto found = FindLibInTree(root, name, seen)) return found; - throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, root->name)); + std::string names; + for (Configuration* root : roots) { + if (auto found = FindLibInTree(root, name, seen)) return found; + if (!names.empty()) names += ", "; + names += root->name; + } + throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, names)); } TestRunner TestRunner::Local() { @@ -449,9 +464,22 @@ void Crafter::UnpackageTests(Configuration& cfg) { } TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span projectArgs) { - UnpackageTests(projectCfg); + std::array one = { &projectCfg }; + return RunTests(std::span(one), opts, projectArgs); +} + +TestSummary Crafter::RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs) { + // Each of them once, however often the list names it: named twice, a + // configuration would have each of its tests built twice at once. + std::vector distinct; + for (Configuration* cfg : configurations) { + if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg); + } + if (distinct.size() != configurations.size()) return RunTests(distinct, opts, projectArgs); + + for (Configuration* cfg : configurations) UnpackageTests(*cfg); // Multi-target sweep: when no --target= was given, the run covers every - // distinct target declared across projectCfg.tests plus the host target. + // distinct target declared across the tests plus the host target. // Lets a bare `crafter-build test` exercise cross-arch tests without the // user having to know which targets exist. An explicit --target=X // bypasses the sweep and runs that target only. @@ -461,8 +489,10 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& // the one shown and filtered on. std::map sweep; sweep.emplace(NormalizeTarget(HostTarget()), HostTarget()); - for (const Test& t : projectCfg.tests) { - if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target); + for (const Configuration* cfg : configurations) { + for (const Test& t : cfg->tests) { + if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target); + } } TestSummary aggregate; for (const auto& [normalized, target] : sweep) { @@ -472,7 +502,7 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& Progress::Clear(); std::println("\n=== target: {} ===", target); } - TestSummary s = RunTests(projectCfg, perTarget, projectArgs); + TestSummary s = RunTests(configurations, perTarget, projectArgs); aggregate.passed += s.passed; aggregate.failed += s.failed; aggregate.crashed += s.crashed; @@ -490,17 +520,22 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& // time) because runnerOverride and FromEnv resolution depend on the // run's options, which the project.cpp doesn't know about. std::vector filtered; - filtered.reserve(projectCfg.tests.size()); - for (auto& test : projectCfg.tests) { - if (!SameTarget(test.config.target, opts.targetFilter)) continue; - if (!MatchAny(opts.globs, test.config.name)) continue; - test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config)); - if (opts.runnerOverride) { - if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) { - test.runner = std::move(*r); + // The configuration that declares each of them, whose path its log is + // written under. + std::vector owners; + for (Configuration* cfg : configurations) { + for (auto& test : cfg->tests) { + if (!SameTarget(test.config.target, opts.targetFilter)) continue; + if (!MatchAny(opts.globs, test.config.name)) continue; + test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config)); + if (opts.runnerOverride) { + if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) { + test.runner = std::move(*r); + } } + filtered.push_back(&test); + owners.push_back(cfg); } - filtered.push_back(&test); } if (opts.listOnly) { @@ -515,6 +550,38 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& return summary; } + // A test is built in a directory named after the test and what it is + // compiled as, not after the configuration that declares it, and its + // sources are tests/ whichever one does. Two configurations that + // each declare a test of one name, compiled alike, would have the two + // built in that one directory, at once when the run has the jobs for + // it, each with the dependencies and link flags of its own declaration. + // Neither is built: both fail, and say which configurations declare + // them. Only tests of different configurations are looked at: a test + // one configuration declares twice is as it was. + std::vector clashes(filtered.size()); + { + std::unordered_map> builtInto; + for (std::size_t i = 0; i < filtered.size(); ++i) { + builtInto[fs::absolute(filtered[i]->config.PcmDir()).lexically_normal()].push_back(i); + } + for (const auto& [directory, sharing] : builtInto) { + std::vector declaring; + for (const std::size_t i : sharing) { + if (!std::ranges::contains(declaring, owners[i])) declaring.push_back(owners[i]); + } + if (declaring.size() < 2) continue; + std::string names; + for (const Configuration* cfg : declaring) { + if (!names.empty()) names += ", "; + names += cfg->name; + } + for (const std::size_t i : sharing) { + clashes[i] = std::format("{} each declare a test named {}, which would be built for each of them in {}: give each test a name of its own", names, filtered[i]->config.name, directory.string()); + } + } + } + std::int32_t jobs = opts.jobs > 0 ? opts.jobs : std::max(1u, std::thread::hardware_concurrency()); @@ -549,6 +616,18 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& TestResult r; r.name = t.config.name; + if (!clashes[i].empty()) { + r.outcome = TestOutcome::Fail; + r.output = clashes[i]; + r.exitCode = -1; + { + std::lock_guard lk(printMutex); + PrintResult(r, t.runner.name); + } + results[i] = std::move(r); + continue; + } + // Declarative preconditions set via TestBuilder::Requires. Evaluated // before the build so a missing tool/file/env turns into a Skip without // paying the compile cost. Reports the first failure only — once one @@ -632,7 +711,7 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& } if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) { - WriteLog(projectCfg.path, r.name, r.output); + WriteLog(owners[i]->path, r.name, r.output); } { diff --git a/interfaces/Crafter.Build-Agents.cppm b/interfaces/Crafter.Build-Agents.cppm index 11762fe..1660526 100644 --- a/interfaces/Crafter.Build-Agents.cppm +++ b/interfaces/Crafter.Build-Agents.cppm @@ -70,7 +70,7 @@ export namespace Crafter { // Write the AGENTS.md beside `projectFile` from the AGENTS.template.md // beside it, with the AGENTS.consumer.md of every dependency // project.dependencyNotes selects merged in. `project` is the - // Configuration that file returned, after LoadProject: loading is what + // Configuration that file returned, once it is loaded: loading is what // found the dependencies. Creates AGENTS.md when it is missing, and // replaces only one a build wrote: an AGENTS.md someone wrote is left // alone, with a warning. Without a template it writes nothing, and only @@ -81,4 +81,17 @@ export namespace Crafter { // a dependency's unusable notes are warnings: the notes never fail a // build, and nothing is reported when nothing would have been written. bool UpdateAgentsMd(const Configuration& project, const fs::path& projectFile); + // The same for a project file that returned several configurations. + // Each one the file made itself selects, by its dependencyNotes, among + // the projects that one is built against, and the notes are merged: a + // dependency's are in when a configuration that asks for them leads to + // it. The file's `#pragma crafter dependency` lines, and a + // configuration it loaded from another project and returns, which + // counts as a dependency here, go by the widest of those settings, and + // by Transitive when the file made no configuration itself. A + // configuration is another project's when GitProject or LocalProject + // loaded it from another project file than `projectFile`, two files + // being one when they resolve to one path: one they loaded from + // `projectFile` itself is that file's own. + bool UpdateAgentsMd(std::span configurations, const fs::path& projectFile); } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index 0ae6ab9..5146bb9 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -440,9 +440,11 @@ export namespace Crafter { // What a Script's callback is handed when `crafter-build run ` // starts it. struct ScriptContext { - // The Configuration project.cpp returned. Read the project through - // this rather than capturing the local in CrafterBuildProject by - // reference: that local is gone by the time a script runs. + // The Configuration the script is declared on: the one project.cpp + // returned, or of several the one whose `scripts` holds it. Read the + // project through this rather than capturing a local of the entry + // point by reference: the local need not be the object that the + // entry point returned. Configuration& project; // Absolute directory of the project file. Commands run in the // directory crafter-build was started from, like everything else it @@ -595,8 +597,10 @@ export namespace Crafter { // Crafter.Build:Agents): // cfg.dependencyNotes = DependencyNotes::Direct; // Only read on the Configuration project.cpp returns; a dependency's - // setting decides nothing for its consumers. Not part of VariantId: - // the notes change nothing that is compiled. + // setting decides nothing for its consumers. Of several returned + // configurations, each one the project file made itself has its own + // read, for what that one is built against (see UpdateAgentsMd). Not + // part of VariantId: the notes change nothing that is compiled. DependencyNotes dependencyNotes = DependencyNotes::Transitive; void GetInterfacesAndImplementations(std::span interfaces, std::span implementations); // Retry the `import X;` names GetInterfacesAndImplementations could not @@ -867,6 +871,35 @@ export namespace Crafter { // checks everything again and pulls unpinned externals again. BuildResult Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex); + // Builds every one of `configurations`, the configurations a project + // file returns, in the pass `depResults` records. Each is built by + // Build(), as a project's one configuration is, and its result then + // goes into the record under its PcmDir, where Build() records a + // dependency. What two of them depend on is built once, and so is one + // that another of them is built on: it is built before the other + // starts, and the other finds it in the record. The first is built on + // the calling thread and each other one on a thread of its own, all of + // them to the end: one that fails stops none of the others. Returns the + // errors of the ones that failed, in the order given and each message + // once, so a dependency that failed for three of them is reported once, + // and an empty string when all were built. A configuration the list + // names twice is built once. + // + // With a wasm executable that declares wasmVariants among them, or + // among what they are built on, they are built one after the other on + // the calling thread instead: its build rewrites the configurations it + // is built on for each variant, which no other build may be reading. + // + // Refuses, before building anything, two of them that would be built + // into one directory (same path, name, target and compile state), which + // would be two builds writing the same files at once; a set of them in + // which each is built on something that is built into the directory of + // another, so that none could be built first; and one that is built on + // something of its own directory when another of them is built on that + // directory too, since the record holds one result for a directory and + // the other could be given either. + std::string BuildAll(std::span configurations, std::unordered_map>& depResults, std::mutex& depMutex); + // Takes main's argv verbatim so the CLI entry point is a one-liner; // the shape is inherited from the language, not chosen here. // lint-disable-next-line no-char-pointer diff --git a/interfaces/Crafter.Build-External.cppm b/interfaces/Crafter.Build-External.cppm index f21dc47..f9e8aa0 100644 --- a/interfaces/Crafter.Build-External.cppm +++ b/interfaces/Crafter.Build-External.cppm @@ -76,14 +76,14 @@ export namespace Crafter { // clone can still differ in includeDirs, libDirs and libs. ExternalBuildResult ExternalOutputs(const ExternalDependency& dep, std::string_view target); - // The args the project file now running its CrafterBuildProject was - // loaded with: everything that function receives, --target=, --debug and + // The args the project file now running its entry point was loaded + // with: everything that function receives, --target=, --debug and // the other standard flags included. Not cfg.projectArgs, which holds // only what ApplyStandardArgs left uninterpreted: `.args = // cfg.projectArgs` would drop the target and the build type. Empty - // everywhere else, because it reads the stack LoadProject keeps per + // everywhere else, because it reads the stack the loader keeps per // thread, as IsTopLevelProject does: outside a project file, on any - // thread but the one running it, once CrafterBuildProject has returned + // thread but the one running it, once the entry point has returned // (a script runs later), and before it is called, which covers the // file's static initialisers and its `#pragma crafter dependency` // pre-pass. The specs below default their args to it. Defined beside @@ -97,7 +97,7 @@ export namespace Crafter { // GitSource picks the revision: leave branch + commit empty for the // remote's default branch HEAD (sloppy but convenient), set branch to // track a branch tip, or set commit to pin to an immutable SHA. args are - // what the dep's CrafterBuildProject receives. They default to this + // what the dep's entry point receives. They default to this // project's own, read when the spec is made, so --target=, --march=, // --debug and the project's own flags reach every sibling down a chain // without being passed. Set them to forward something else: {} for @@ -105,19 +105,28 @@ export namespace Crafter { // a flag only this project reads. Give such a list to every sibling: // Build() refuses a graph in which two paths load one project with two // different lists, since the program would end up with both builds. + // configuration picks among the configurations of a project file that + // returns several (CrafterBuildConfigurations), by Configuration::name. + // Left empty it is the first one the file returns, so a project that + // grows a second configuration puts it after the one its consumers + // already get. struct GitProjectSpec { GitSource source; fs::path projectFile = "project.cpp"; std::vector args = ProjectArgs(); + std::string configuration; }; - // Clones the spec's git URL into the external cache, recursively - // LoadProject's the remote's project.cpp, and returns a stable - // Configuration* you can drop into cfg.dependencies. The clone is keyed by - // url+branch+commit+projectFile alone, so every arg list builds in the - // same working tree, each into variant directories of its own. The - // Configuration is owned by an internal cache for the lifetime of the - // build, keyed by the clone and the args: identical specs share one. + // Clones the spec's git URL into the external cache, loads the remote's + // project.cpp in turn, and returns a stable Configuration* you can drop + // into cfg.dependencies: the configuration the spec picks of the ones + // that file describes. The clone is keyed by url+branch+commit+projectFile + // alone, so every arg list builds in the same working tree, each into + // variant directories of its own. What the file describes is kept in an + // internal cache for the lifetime of the build, keyed by the clone and + // the args: identical specs share one Configuration, and two that differ + // only in `configuration` share one load of the file. Throws when the + // file has no configuration of the name the spec asks for, or two. Configuration* GitProject(const GitProjectSpec& spec); // Specification for a local sibling crafter-build project (e.g. an @@ -126,12 +135,13 @@ export namespace Crafter { struct LocalProjectSpec { fs::path projectFile; // relative to cwd or absolute std::vector args = ProjectArgs(); // as GitProjectSpec::args + std::string configuration; // as GitProjectSpec::configuration }; // Same as GitProject but for a local on-disk project — no fetch, no // cache copy. Resolves projectFile to its canonical absolute path and - // recursively LoadProject's it. Returns a stable Configuration* owned - // by the same internal cache as GitProject. + // loads it in turn. Returns a stable Configuration* kept by the same + // internal cache as GitProject. Configuration* LocalProject(const LocalProjectSpec& spec); // Clone (or update) the given git source into the shared external @@ -147,11 +157,11 @@ export namespace Crafter { namespace Crafter { // Where GitProject or LocalProject loaded a Configuration from. The - // loader keeps this beside the cache that owns the Configuration, since - // the Configuration itself cannot say: only the one they return has its - // path rebased, and the configurations a dependency's project file makes - // for itself keep a path such as "./", which resolves against the - // consumer's directory. + // loader keeps this beside the cache that holds the Configuration, since + // the Configuration itself cannot say: only the ones its project file + // returns have their paths rebased, and the configurations a + // dependency's project file makes for itself and does not return keep a + // path such as "./", which resolves against the consumer's directory. struct LoadedProject { fs::path projectFile; // absolute // What a consumer's AGENTS.md calls it: the repository's name for a @@ -166,8 +176,20 @@ namespace Crafter { // Two specs that pin one library differently are one library. std::string identity; }; - // The LoadedProject behind a Configuration that GitProject or - // LocalProject returned; nullopt for any other: the project crafter-build - // was pointed at, and every configuration a project file makes itself. + // The LoadedProject behind a Configuration that a project file GitProject + // or LocalProject loaded returned, the ones the spec did not pick + // included; nullopt for any other: what the project file crafter-build + // was pointed at makes itself, and what a loaded project file makes for + // itself and does not return. std::optional LoadedProjectOf(const Configuration& cfg); + // The project that keeps `cfg` to itself: one GitProject or LocalProject + // loaded whose project file did not return `cfg`, while a configuration + // that file did return led to it when the file was loaded. A + // configuration leads to what it is built on (`dependencies`) and to + // the configurations of its tests (`tests`), and through each of those + // to what that one leads to. nullopt for every other configuration: one + // a loaded project file returned, and one that nothing a loaded project + // file returned led to, such as what the project file crafter-build was + // pointed at makes itself. + std::optional KeptBy(const Configuration& cfg); } diff --git a/interfaces/Crafter.Build-Lint.cppm b/interfaces/Crafter.Build-Lint.cppm index bbe9398..9d856bb 100644 --- a/interfaces/Crafter.Build-Lint.cppm +++ b/interfaces/Crafter.Build-Lint.cppm @@ -30,7 +30,8 @@ export namespace Crafter { // Absolute path of the loaded project.cpp. It is linted too, and its // parent directory is the project root that decides which dependency // Configurations contribute rules/files (GitProject / cache-dir deps - // are foreign code and skipped). Empty => fall back to cfg.path. + // are foreign code and skipped). Empty => fall back to cfg.path, of + // several configurations the first one's. std::filesystem::path projectFile; }; @@ -62,4 +63,10 @@ export namespace Crafter { // findings compiler-style (Report), would-change paths (Check), or // formatted paths (Apply), plus a summary line. LintSummary RunLint(Configuration& projectCfg, const RunLintOptions& opts); + // The same for the several configurations a project file returns, as + // one run over all of them: each is a root, and the roots come before + // what any of them depends on, in the order given. A rule two of them + // register under one name runs once, as the first of them in that order + // registered it, and a source two of them reach is linted once. + LintSummary RunLint(std::span configurations, const RunLintOptions& opts); } diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index ace7947..24d98fb 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -98,17 +98,47 @@ namespace Crafter { // or the org.flatpak.Builder app where the host has none. std::int32_t RunHostFlatpakBuilder(std::string_view arguments); std::string GetBaseCommand(const Configuration& config); + // The configurations `projectFile` describes, in the order it gives them. + // Compiles the file into a shared object in the build/ beside it, unless + // the one there is current, loads that into this process and calls the + // file's entry point with `args`. A project file defines one of two: + // extern "C" Configuration CrafterBuildProject(std::span args); + // extern "C" std::vector CrafterBuildConfigurations(std::span args); + // The first is a project of one configuration, which comes back as a + // list of one. The second is a project of several that need not have + // anything to do with each other, such as a library and a tool, or the + // programs of one repository; they come back as the file returned them. + // The two names are how a loaded file says which it is: both are C + // symbols, which carry no return type, so one name with two return types + // would be called as whichever the loader guessed. Throws for a file + // that defines neither or both, and for a CrafterBuildConfigurations + // that returns nothing, a null pointer, one configuration twice, or one + // that a project GitProject or LocalProject loaded keeps to itself + // (KeptBy): every configuration in the list is one the file made or one + // those two returned. + // + // The pointers are used for as long as the process runs. What a + // CrafterBuildConfigurations returns is its project file's to keep that + // long, at addresses that do not change: in a std::deque the file only + // adds to, one new set per call, or what GitProject and LocalProject + // gave it. What a CrafterBuildProject returns is kept here, constructed + // by that call and never moved. + export std::vector LoadConfigurations(const fs::path& projectFile, std::span args); + // What the CrafterBuildProject of `projectFile` returns, loaded as + // LoadConfigurations loads it. Throws for a project file that defines + // CrafterBuildConfigurations: the configurations that one returns stay + // where the file keeps them and cannot be returned by value. export Configuration LoadProject(const fs::path& projectFile, std::span args); - // A dependency the project file currently running its CrafterBuildProject + // A dependency the project file currently running its entry point // declared with `#pragma crafter dependency`, so it can also be wired // into the build graph (a test that links the same module, say) without // spelling the source twice. `name` is the dependency's Configuration // name or any module it exports — whatever the project file `import`s. // Throws when no such dependency was declared, or when called from - // anywhere other than inside LoadProject. + // anywhere other than inside a project file's load. export Configuration* ProjectDependency(std::string_view name); // True while the project file crafter-build was pointed at runs its - // CrafterBuildProject, and when no project file is running at all; false + // entry point, and when no project file is running at all; false // inside a dependency's project file (a `#pragma crafter dependency`, // GitProject or LocalProject target). Wire anything only the project's // own build or test run needs behind it. The case that forced it: a @@ -117,9 +147,9 @@ namespace Crafter { // project file in turn and the two recurse until the cycle guard throws. export bool IsTopLevelProject(); // What the `#pragma crafter dependency` lines of `projectFile` resolved - // to the last time LoadProject loaded it in this process, in file order; + // to the last time it was loaded in this process, in file order; // empty when it has none or was never loaded. Unlike ProjectDependency - // this still answers once LoadProject has returned, which is when the + // this still answers once the load has returned, which is when the // dependency notes of the project crafter-build was pointed at are // gathered (Crafter.Build:Agents). std::vector PragmaDependencies(const fs::path& projectFile); diff --git a/interfaces/Crafter.Build-Script.cppm b/interfaces/Crafter.Build-Script.cppm index fad052d..91ed3b9 100644 --- a/interfaces/Crafter.Build-Script.cppm +++ b/interfaces/Crafter.Build-Script.cppm @@ -19,7 +19,8 @@ export namespace Crafter { // Print the script names instead of running one. bool listOnly = false; // Absolute path of the loaded project.cpp; its directory becomes - // ScriptContext::projectDir. Empty => fall back to cfg.path. + // ScriptContext::projectDir. Empty => fall back to the path of the + // configuration the script is declared on. std::filesystem::path projectFile; }; @@ -37,4 +38,10 @@ export namespace Crafter { // (a raw wait status passed along by mistake) would otherwise wrap to // success. std::int32_t RunScript(Configuration& projectCfg, const RunScriptOptions& opts); + // The same over the scripts of several configurations, the ones a + // project file returns, as one list in the order given: a name two of + // them declare is a name declared twice, and a configuration the list + // names twice counts once. The script's ScriptContext::project is the + // configuration it is declared on. + std::int32_t RunScript(std::span configurations, const RunScriptOptions& opts); } diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index d08d51f..ff82b4f 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -88,15 +88,26 @@ export namespace Crafter { }; TestSummary RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span projectArgs = {}); + // The tests of several configurations, those a project file returns, as + // one run: one sweep over the targets they declare, one summary, and + // one build pass per target, so a library that tests of two of them link + // is built once. The log a failed, crashed or timed-out test leaves + // goes under the path of the configuration that declares it. A test + // belongs to one configuration: where two of them each declare one that + // would be built into the same directory, which two tests of one name + // compiled alike are, both fail without being built and name the + // configurations. A configuration the list names twice counts once. + TestSummary RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs = {}); TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout); - // Parent-project access for test fixtures. Run() sets the pointer to the - // root project's Configuration before discovery; fixtures call ParentLib() - // to obtain a Configuration* for one of the parent's libraries (or the - // parent itself) so they can declare it as a dependency without rebuilding - // the lib config from scratch. Lookup is by Configuration::name and - // recurses through the parent's dependency graph. + // The configurations of the project crafter-build was pointed at, by + // name. Run() hands SetParentProject what the project file returned, + // once it has loaded. ParentLib() then finds a Configuration* by + // Configuration::name among them and what they depend on, searching the + // dependency graph of each in the order the file returned them, and + // throws when none has that name or no project is set. void SetParentProject(Configuration* parent); + void SetParentProject(std::span parents); Configuration* ParentLib(std::string_view name); } From 5795b666f5a5d607b36deefc06dd703b85a5a053 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 15 Nov 2026 02:16:07 +0100 Subject: [PATCH 24/53] test: several configurations from one project file BuildAll builds configurations the test makes itself, on a fresh copy of its fixture outside the checkout. A library, a program built on it and an unrelated program all come out built, each in the record of the pass under its PcmDir, and a list that names one configuration twice builds it from nothing, what the build before left of it being removed first, and leaves it in the record of the pass once. A library built on another library of its own name, path and type, so that the two are built into one directory, builds, with both archives in that directory; returned beside a program that is built on it, the pair is refused, both by name, before the program is built or anything is recorded. Two libraries that are each built on a configuration of the other's directory are refused by name, and nothing of them is built or recorded. A wasm32 library that names no sysroot and a program for the host built on it leave the library in the record once, under the directory it has after the pass, and its refusal comes back once; it is refused for its -fno-exceptions, so the case needs no WASI sysroot. Of two programs built on a library that does not compile and a third that has nothing to do with it, the third is built, the two are not, and the library's error comes back once. Two configurations that would be built into one directory are refused, and neither is built. With a wasm executable that declares a variant among them, a program of one source is linked no earlier than the program and library given before it; the wasm one is refused for its -fno-exceptions before it builds anything, so the case needs no WASI sysroot. ProjectConfigurations loads fixture project files staged outside the checkout. A file with CrafterBuildConfigurations comes back as the three configurations it returns, with the pointer the file took from the second to the first intact, and as two when its args say so; LoadProject refuses it. A file with CrafterBuildProject comes back as a list of one whose test still depends on that Configuration, and that test builds and passes. A file with both entry points, one with neither, and ones whose CrafterBuildConfigurations returns nothing, a null pointer or one configuration twice are refused, each with a message that says which. Then crafter-build's verbs, through Run() and RunTests, on the file of three: a build builds all three; -r refuses to pick between its two executables, and runs the one executable there is when the file returns two configurations; RunTests runs the tests of the first and the third configuration in one run, and when the first declares the third's test as well, that test fails for both, naming the two, and is not built, while the first's own test passes, and a list that names the first configuration twice runs its test once; with a fourth configuration of the third's name and path, a test run and a build are each refused for the two that would be built into one directory, and neither writes the AGENTS.md that a build which is not refused writes from the template the test puts beside the project file; `run` reaches a script of the first and of the third configuration and hands each the configuration that declares it; install refuses the project while none of the three is packaged, bundle refuses it when two are, and with one packaged executable beside the library bundle does not take the library for the app. SiblingConfigurations loads such a file as another project's sibling. A spec without `configuration` gets the first, a spec that names one gets that one, and the three specs share one load: the dependency of the second is the first as LocalProject returned it. All three are rebased onto the sibling's directory. A name the sibling does not have throws with the names it has, and a name that two configurations of another fixture share throws too, while a spec without a name still gets the first of those two. Building the second builds the first with it and leaves the third unbuilt. A file that returns something a sibling keeps to itself is refused when it is loaded, the configuration and the sibling named: the library the sibling's program is built on, the configuration of that program's test, and a helper only that test is built on, none of which the sibling's file returns. A project that returns the sibling's third configuration beside one of its own builds both, cannot run the sibling's script and runs its own, and its test run leaves the sibling's test alone. DependencyNotes gains a project of two configurations and a fixture, outer, that builds against lib: two Direct configurations give what each of them names; a project a Direct one names is followed when a Transitive one leads to it; a configuration under None keeps out what only it is built against; with both under None, AGENTS.md is the template's text; and a returned configuration of another project is one of the projects the notes come from, followed further only under Transitive, which is also what a file that made no configuration gets. For outer's own AGENTS.md, written from the Configuration LocalProject returned and outer's project file, outer's own setting selects: lib under Direct, lib and base under Transitive, nothing under None. Script runs a script of each of two configurations, each handed the configuration that declares it, refuses a name both declare without running anything, and, given a list that names one configuration twice, runs the script asked for, which a name declared twice would have kept it from. Lint formats the sources of two configurations in one run, counts a rule both register as one, and runs a rule only one of them registers over the sources of both. Of two returned configurations that register a rule under one name the earlier one's runs, over the sources of all three, though the configuration returned ahead of both depends on the later one. --- project.cpp | 15 +- tests/BuildAll/fixture/broken/Broken.cppm | 10 + tests/BuildAll/fixture/first/main.cpp | 9 + tests/BuildAll/fixture/good/main.cpp | 9 + tests/BuildAll/fixture/greeter/Greeter.cppm | 11 + tests/BuildAll/fixture/hello/main.cpp | 10 + tests/BuildAll/fixture/second/main.cpp | 9 + tests/BuildAll/fixture/tool/main.cpp | 9 + tests/BuildAll/fixture/twins/Lower.cppm | 11 + tests/BuildAll/fixture/twins/Upper.cppm | 10 + tests/BuildAll/main.cpp | 273 ++++++++++++++++++ .../fixture/outer/AGENTS.consumer.md | 3 + .../DependencyNotes/fixture/outer/project.cpp | 21 ++ tests/DependencyNotes/main.cpp | 80 +++++ tests/Lint/main.cpp | 46 +++ .../fixture/both/project.cpp | 16 + .../fixture/empty/project.cpp | 11 + .../fixture/neither/project.cpp | 11 + .../fixture/null/project.cpp | 11 + .../fixture/several/greeter/Greeter.cppm | 11 + .../fixture/several/hello/main.cpp | 12 + .../fixture/several/project.cpp | 94 ++++++ .../several/tests/GreeterTest/main.cpp | 9 + .../fixture/several/tests/ToolTest/main.cpp | 11 + .../fixture/several/tool/main.cpp | 9 + .../fixture/single/Single.cppm | 11 + .../fixture/single/project.cpp | 22 ++ .../fixture/single/tests/SelfTest/main.cpp | 9 + .../fixture/twice/project.cpp | 17 ++ tests/ProjectConfigurations/main.cpp | 228 +++++++++++++++ tests/Script/main.cpp | 32 ++ .../fixture/digger/project.cpp | 20 ++ .../fixture/keeper/project.cpp | 39 +++ .../fixture/sibling/greeter/Greeter.cppm | 11 + .../fixture/sibling/hello/main.cpp | 10 + .../fixture/sibling/project.cpp | 60 ++++ .../fixture/sibling/tests/ToolTest/main.cpp | 11 + .../fixture/sibling/tool/main.cpp | 9 + .../fixture/twins/project.cpp | 24 ++ .../fixture/umbrella/main.cpp | 9 + .../fixture/umbrella/project.cpp | 34 +++ tests/SiblingConfigurations/main.cpp | 165 +++++++++++ 42 files changed, 1427 insertions(+), 5 deletions(-) create mode 100644 tests/BuildAll/fixture/broken/Broken.cppm create mode 100644 tests/BuildAll/fixture/first/main.cpp create mode 100644 tests/BuildAll/fixture/good/main.cpp create mode 100644 tests/BuildAll/fixture/greeter/Greeter.cppm create mode 100644 tests/BuildAll/fixture/hello/main.cpp create mode 100644 tests/BuildAll/fixture/second/main.cpp create mode 100644 tests/BuildAll/fixture/tool/main.cpp create mode 100644 tests/BuildAll/fixture/twins/Lower.cppm create mode 100644 tests/BuildAll/fixture/twins/Upper.cppm create mode 100644 tests/BuildAll/main.cpp create mode 100644 tests/DependencyNotes/fixture/outer/AGENTS.consumer.md create mode 100644 tests/DependencyNotes/fixture/outer/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/both/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/empty/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/neither/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/null/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/several/greeter/Greeter.cppm create mode 100644 tests/ProjectConfigurations/fixture/several/hello/main.cpp create mode 100644 tests/ProjectConfigurations/fixture/several/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/several/tests/GreeterTest/main.cpp create mode 100644 tests/ProjectConfigurations/fixture/several/tests/ToolTest/main.cpp create mode 100644 tests/ProjectConfigurations/fixture/several/tool/main.cpp create mode 100644 tests/ProjectConfigurations/fixture/single/Single.cppm create mode 100644 tests/ProjectConfigurations/fixture/single/project.cpp create mode 100644 tests/ProjectConfigurations/fixture/single/tests/SelfTest/main.cpp create mode 100644 tests/ProjectConfigurations/fixture/twice/project.cpp create mode 100644 tests/ProjectConfigurations/main.cpp create mode 100644 tests/SiblingConfigurations/fixture/digger/project.cpp create mode 100644 tests/SiblingConfigurations/fixture/keeper/project.cpp create mode 100644 tests/SiblingConfigurations/fixture/sibling/greeter/Greeter.cppm create mode 100644 tests/SiblingConfigurations/fixture/sibling/hello/main.cpp create mode 100644 tests/SiblingConfigurations/fixture/sibling/project.cpp create mode 100644 tests/SiblingConfigurations/fixture/sibling/tests/ToolTest/main.cpp create mode 100644 tests/SiblingConfigurations/fixture/sibling/tool/main.cpp create mode 100644 tests/SiblingConfigurations/fixture/twins/project.cpp create mode 100644 tests/SiblingConfigurations/fixture/umbrella/main.cpp create mode 100644 tests/SiblingConfigurations/fixture/umbrella/project.cpp create mode 100644 tests/SiblingConfigurations/main.cpp diff --git a/project.cpp b/project.cpp index 1452eb6..adaaddf 100644 --- a/project.cpp +++ b/project.cpp @@ -310,13 +310,13 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); - // LoadProject dlopens the synthesized project.so, which references - // Crafter:: symbols (HostTarget, Configuration ctors) that have to be - // visible from the test exe — same wiring crafter-build itself uses - // for project.so. + // Loading a project file dlopens the project.so compiled from it, + // which references Crafter:: symbols (HostTarget, Configuration + // ctors) that have to be visible from the test exe — same wiring + // crafter-build itself uses for project.so. cfg.AddTest("ConcurrentCacheRace").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); - // Same LoadProject wiring as ConcurrentCacheRace above. + // Same wiring as ConcurrentCacheRace above. cfg.AddTest("HostCacheSourceStamp").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("HostCacheToolchainKey").Dependencies({ CrafterBuildLib.get() }) @@ -337,10 +337,15 @@ extern "C" Configuration CrafterBuildProject(std::span a .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("SiblingOwnPointers").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); + cfg.AddTest("ProjectConfigurations").Dependencies({ CrafterBuildLib.get() }) + .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); + cfg.AddTest("SiblingConfigurations").Dependencies({ CrafterBuildLib.get() }) + .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); } diff --git a/tests/BuildAll/fixture/broken/Broken.cppm b/tests/BuildAll/fixture/broken/Broken.cppm new file mode 100644 index 0000000..45ade4e --- /dev/null +++ b/tests/BuildAll/fixture/broken/Broken.cppm @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Broken; +import std; + +// Does not compile: the library two of the test's programs are built on. +export std::int32_t Value() { + return Undeclared; +} diff --git a/tests/BuildAll/fixture/first/main.cpp b/tests/BuildAll/fixture/first/main.cpp new file mode 100644 index 0000000..58a7a9c --- /dev/null +++ b/tests/BuildAll/fixture/first/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Broken; + +int main() { + return Value(); +} diff --git a/tests/BuildAll/fixture/good/main.cpp b/tests/BuildAll/fixture/good/main.cpp new file mode 100644 index 0000000..5736637 --- /dev/null +++ b/tests/BuildAll/fixture/good/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +int main() { + std::println("good"); + return 0; +} diff --git a/tests/BuildAll/fixture/greeter/Greeter.cppm b/tests/BuildAll/fixture/greeter/Greeter.cppm new file mode 100644 index 0000000..4e0c093 --- /dev/null +++ b/tests/BuildAll/fixture/greeter/Greeter.cppm @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Greeter; +import std; + +export namespace Greeter { + std::string Greet(std::string_view name) { + return std::format("hello {}", name); + } +} diff --git a/tests/BuildAll/fixture/hello/main.cpp b/tests/BuildAll/fixture/hello/main.cpp new file mode 100644 index 0000000..60df1dc --- /dev/null +++ b/tests/BuildAll/fixture/hello/main.cpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Greeter; + +int main() { + std::println("{}", Greeter::Greet("world")); + return 0; +} diff --git a/tests/BuildAll/fixture/second/main.cpp b/tests/BuildAll/fixture/second/main.cpp new file mode 100644 index 0000000..58a7a9c --- /dev/null +++ b/tests/BuildAll/fixture/second/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Broken; + +int main() { + return Value(); +} diff --git a/tests/BuildAll/fixture/tool/main.cpp b/tests/BuildAll/fixture/tool/main.cpp new file mode 100644 index 0000000..3d03672 --- /dev/null +++ b/tests/BuildAll/fixture/tool/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +int main() { + std::println("tool"); + return 0; +} diff --git a/tests/BuildAll/fixture/twins/Lower.cppm b/tests/BuildAll/fixture/twins/Lower.cppm new file mode 100644 index 0000000..e5f6378 --- /dev/null +++ b/tests/BuildAll/fixture/twins/Lower.cppm @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Lower; +import std; + +// Built by a configuration with the name, path and type of the one that +// builds Upper, which is built on this one. +export std::int32_t Lower() { + return 1; +} diff --git a/tests/BuildAll/fixture/twins/Upper.cppm b/tests/BuildAll/fixture/twins/Upper.cppm new file mode 100644 index 0000000..f8d1ceb --- /dev/null +++ b/tests/BuildAll/fixture/twins/Upper.cppm @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Upper; +import std; +import Lower; + +export std::int32_t Upper() { + return Lower() + 1; +} diff --git a/tests/BuildAll/main.cpp b/tests/BuildAll/main.cpp new file mode 100644 index 0000000..85678aa --- /dev/null +++ b/tests/BuildAll/main.cpp @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// BuildAll builds the configurations a project file returns, which need not +// have anything to do with each other, in one pass: every one of them, and +// what two of them share once. +// +// What it guards against is a configuration that goes missing or is built +// wrongly without a word: left unbuilt because another one failed, or +// because it shares an output directory with another and was taken for it; +// built twice at once because another one depends on it, each build +// writing what the other reads; and built at once with a wasm executable +// that declares variants, which rewrites the configurations it is built on +// while it builds. And against a build that never ends: a configuration +// waiting for a build of its own directory that is waiting for it. +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + std::size_t Count(std::string_view text, std::string_view needle) { + std::size_t count = 0; + for (std::size_t pos = text.find(needle); pos != std::string_view::npos; pos = text.find(needle, pos + needle.size())) ++count; + return count; + } + + // A library made of `dir`/`interface`.cppm. + void MakeLibrary(Configuration& cfg, const fs::path& dir, std::string_view name, std::string_view interface) { + cfg.path = dir; + cfg.name = name; + cfg.outputName = name; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::LibraryStatic; + std::array interfaces = { interface }; + std::array implementations = {}; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + } + + // A program made of `dir`/main.cpp. + void MakeProgram(Configuration& cfg, const fs::path& dir, std::string_view name) { + cfg.path = dir; + cfg.name = name; + cfg.outputName = name; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::Executable; + std::array interfaces = {}; + std::array implementations = { "main" }; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + } +} + +int main() { + // Staged: the cases below compare what a build left behind, so each run + // starts from sources alone. + const fs::path scratch = fs::temp_directory_path() / "crafter-build-build-all"; + std::error_code ec; + fs::remove_all(scratch, ec); + fs::copy(fs::current_path() / "tests" / "BuildAll" / "fixture", scratch, fs::copy_options::recursive); + + // Every one of them is built and left in the record of the pass, where + // a configuration that depends on it looks for it. hello depends on + // greeter, and greeter built from here as well as through hello was two + // builds of it at once, one of which archived the objects while the + // other was still writing them. + { + Configuration greeter; + MakeLibrary(greeter, scratch / "greeter", "greeter", "Greeter"); + Configuration hello; + hello.dependencies = { &greeter }; + MakeProgram(hello, scratch / "hello", "hello"); + Configuration tool; + MakeProgram(tool, scratch / "tool", "tool"); + + std::array all = { &greeter, &hello, &tool }; + std::unordered_map> depResults; + std::mutex depMutex; + const std::string failed = BuildAll(all, depResults, depMutex); + Check(failed.empty(), std::format("a library, a program built on it and an unrelated program build: {}", failed)); + for (const Configuration* cfg : all) { + Check(fs::exists(ExpectedOutput(*cfg)), std::format("{} was built", cfg->name)); + Check(depResults.contains(cfg->PcmDir()), std::format("{} is in the record of the pass, where a configuration that depends on it finds its build", cfg->name)); + } + + // A list that names one of them twice builds it like any other: + // once, from nothing here, since what the build above left of it is + // removed first. + fs::remove_all(tool.BinDir(), ec); + fs::remove_all(tool.BuildDir(), ec); + std::array twice = { &tool, &tool }; + std::unordered_map> twiceResults; + Check(BuildAll(twice, twiceResults, depMutex).empty() && fs::exists(ExpectedOutput(tool)), "a configuration the list names twice is built"); + Check(twiceResults.size() == 1 && twiceResults.contains(tool.PcmDir()), std::format("and is in the record of the pass once ({} entries)", twiceResults.size())); + } + + // A configuration built on another of its own name, path and type: the + // two are built into one directory, the dependency first, as they were + // when a project had one configuration and Build() was all there was. + // In the record of the pass while it is still being built, the first + // would be what the record hands its dependency, which would wait for + // it while it waits for the dependency: a build that never ends. + { + Configuration lower; + MakeLibrary(lower, scratch / "twins", "twins", "Lower"); + lower.outputName = "lower"; + Configuration upper; + upper.dependencies = { &lower }; + MakeLibrary(upper, scratch / "twins", "twins", "Upper"); + + std::array one = { &upper }; + std::unordered_map> depResults; + std::mutex depMutex; + const std::string failed = BuildAll(one, depResults, depMutex); + Check(failed.empty(), std::format("a configuration built on another of the same directory builds: {}", failed)); + Check(upper.PcmDir() == lower.PcmDir() && fs::exists(ExpectedOutput(upper)) && fs::exists(ExpectedOutput(lower)), "both into that one directory"); + + // With a program built on the upper one returned beside it, that + // directory holds two builds and the record of the pass one result: + // the program would be handed the lower one's, and be linked without + // the library it names. + Configuration program; + program.dependencies = { &upper }; + MakeProgram(program, scratch / "good", "on-twins"); + std::array both = { &program, &upper }; + std::unordered_map> bothResults; + const std::string refused = BuildAll(both, bothResults, depMutex); + Check(refused.contains("twins and a configuration it is built on would both be built into") && refused.contains("where on-twins looks"), std::format("a configuration built on that one, returned beside it, is refused, both by name: {}", refused)); + Check(bothResults.empty() && !fs::exists(program.BuildDir()) && !fs::exists(program.BinDir()), "and refused before anything is built"); + } + + // Two that are each built on something of the other's directory cannot + // be put in an order, and are refused before either is built. Nothing + // here has a source: the refusal comes first. + { + const auto named = [&](Configuration& cfg, std::string_view name) { + cfg.path = scratch / "crossed"; + cfg.name = name; + cfg.outputName = name; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::LibraryStatic; + }; + Configuration left; + Configuration right; + Configuration leftAgain; + Configuration rightAgain; + named(left, "left"); + named(right, "right"); + named(leftAgain, "left"); + named(rightAgain, "right"); + left.dependencies = { &rightAgain }; + right.dependencies = { &leftAgain }; + + std::array crossed = { &left, &right }; + std::unordered_map> depResults; + std::mutex depMutex; + const std::string refused = BuildAll(crossed, depResults, depMutex); + Check(refused.contains("left, right") && refused.contains("none of them can be built first"), std::format("two configurations that each wait for the other's directory are refused, by name: {}", refused)); + Check(depResults.empty() && !fs::exists(scratch / "crossed" / "bin") && !fs::exists(scratch / "crossed" / "build"), "and refused before anything is built"); + } + + // A wasm32 library whose target is set here and not by + // ApplyStandardArgs, so that it names no sysroot, and a program built on + // it: the program finds the library's build in the record, under the + // directory the library has before its build and after it alike. The + // library has a flag no wasm build accepts, so its build is refused on + // every machine, with a WASI sysroot or without, and a refused build is + // recorded like any other. The program is one for the host, whose own + // build gets as far as asking for the library wherever the test runs. + { + Configuration library; + MakeLibrary(library, scratch / "greeter", "wasm-greeter", "Greeter"); + library.target = "wasm32-wasip1"; + library.compileFlags.push_back("-fno-exceptions"); + Configuration program; + program.dependencies = { &library }; + MakeProgram(program, scratch / "hello", "on-wasm-greeter"); + + std::array all = { &program, &library }; + std::unordered_map> depResults; + std::mutex depMutex; + const std::string failed = BuildAll(all, depResults, depMutex); + Check(Count(failed, "wasm-greeter: -fno-exceptions") == 1, std::format("the library's refusal comes back once, for the two of them: {}", failed)); + const auto recorded = std::ranges::count_if(depResults, [](const auto& entry) { return entry.first.filename().string().starts_with("wasm-greeter-"); }); + Check(recorded == 1 && depResults.contains(library.PcmDir()), std::format("and the library is in the record of the pass once, under the directory it has now ({} times)", recorded)); + } + + // One that fails stops none of the others, and what failed is said + // once: two programs built on a library that does not compile, and a + // third that has nothing to do with it. + { + Configuration broken; + MakeLibrary(broken, scratch / "broken", "broken", "Broken"); + Configuration first; + first.dependencies = { &broken }; + MakeProgram(first, scratch / "first", "first"); + Configuration second; + second.dependencies = { &broken }; + MakeProgram(second, scratch / "second", "second"); + Configuration good; + MakeProgram(good, scratch / "good", "good"); + + std::array all = { &first, &second, &good }; + std::unordered_map> depResults; + std::mutex depMutex; + const std::string failed = BuildAll(all, depResults, depMutex); + Check(failed.contains("Undeclared"), std::format("the library's compile error comes back: {}", failed)); + Check(Count(failed, "error:") == 1, std::format("a dependency that failed for two configurations is reported once: {}", failed)); + Check(fs::exists(ExpectedOutput(good)), "a configuration that has nothing to do with the failure is still built"); + Check(!fs::exists(ExpectedOutput(first)) && !fs::exists(ExpectedOutput(second)), "the two built on the broken library are not"); + + // Two configurations in one directory would be one piece of work to + // the pass, which would build the first and hand the second its + // result. + Configuration twin; + MakeProgram(twin, scratch / "good", "good"); + std::array clash = { &good, &twin }; + fs::remove_all(good.BinDir(), ec); + fs::remove_all(good.BuildDir(), ec); + std::unordered_map> clashResults; + const std::string refused = BuildAll(clash, clashResults, depMutex); + Check(refused.contains("would both be built into"), std::format("two configurations that build into one directory are refused: {}", refused)); + Check(!fs::exists(good.BinDir()), "and refused before either is built"); + } + + // A wasm executable with variants rewrites the configurations it is + // built on, once for each variant, so with one among them the + // configurations are built one after the other: built at once, a + // library two of them share would change under the other's build. The + // slow one comes first here, a program and the library it is built on, + // and the quick one, a single source, is only linked once the slow one + // is. The wasm one is refused before it builds anything, on every + // machine, for its -fno-exceptions, so no wasm build is waited for. + { + Configuration library; + MakeLibrary(library, scratch / "greeter", "ordered-greeter", "Greeter"); + Configuration slow; + slow.dependencies = { &library }; + MakeProgram(slow, scratch / "hello", "ordered-slow"); + Configuration quick; + MakeProgram(quick, scratch / "good", "ordered-quick"); + Configuration variants; + MakeProgram(variants, scratch / "good", "ordered-variants"); + variants.target = "wasm32-wasip1"; + variants.compileFlags.push_back("-fno-exceptions"); + EnableWasiRelaxedSimdVariant(variants); + + std::array all = { &slow, &quick, &variants }; + std::unordered_map> depResults; + std::mutex depMutex; + const std::string failed = BuildAll(all, depResults, depMutex); + Check(failed.contains("-fno-exceptions"), std::format("the wasm configuration is the one that is refused: {}", failed)); + const fs::file_time_type slowBuilt = fs::last_write_time(ExpectedOutput(slow), ec); + Check(!ec, "the slow configuration is built"); + const fs::file_time_type quickBuilt = fs::last_write_time(ExpectedOutput(quick), ec); + Check(!ec && quickBuilt >= slowBuilt, "with a wasm executable that declares variants among them, a configuration is built once the one before it is"); + } + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + fs::remove_all(scratch, ec); + return 0; +} diff --git a/tests/DependencyNotes/fixture/outer/AGENTS.consumer.md b/tests/DependencyNotes/fixture/outer/AGENTS.consumer.md new file mode 100644 index 0000000..71c3eb9 --- /dev/null +++ b/tests/DependencyNotes/fixture/outer/AGENTS.consumer.md @@ -0,0 +1,3 @@ +## outer + +outer wraps lib. diff --git a/tests/DependencyNotes/fixture/outer/project.cpp b/tests/DependencyNotes/fixture/outer/project.cpp new file mode 100644 index 0000000..dbd05cd --- /dev/null +++ b/tests/DependencyNotes/fixture/outer/project.cpp @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// A project that builds against lib, and so against base one ring further +// out. app does not name it: the test loads it for the cases in which a +// project has several configurations, where it is what a second +// configuration names. +extern "C" Configuration CrafterBuildProject(std::span) { + Configuration cfg; + cfg.path = "./"; + cfg.name = "outer"; + cfg.outputName = "outer"; + cfg.type = ConfigurationType::LibraryStatic; + // Loaded from outer/, so this resolves against it. + cfg.dependencies = { LocalProject({ .projectFile = "../lib/project.cpp" }) }; + return cfg; +} diff --git a/tests/DependencyNotes/main.cpp b/tests/DependencyNotes/main.cpp index 58d9247..7481688 100644 --- a/tests/DependencyNotes/main.cpp +++ b/tests/DependencyNotes/main.cpp @@ -294,6 +294,86 @@ int main() { Check(Read(agents) == generated, "under None, AGENTS.md holds the template's text alone"); cfg.dependencyNotes = DependencyNotes::Transitive; + // A project file that returns several configurations: each one's setting + // selects among what that one is built against, and the notes are + // merged. `second` stands in for a second configuration of app's project + // file, and outer is a project that builds against lib, and so against + // base one ring further out. + { + Configuration* outer = nullptr; + try { + outer = LocalProject({ .projectFile = scratch / "outer" / "project.cpp" }); + } catch (const std::exception& e) { + std::println(std::cerr, "FAIL: loading outer threw: {}", e.what()); + return 1; + } + Configuration* const baseProject = cfg.dependencies[0]->dependencies[0]; + Configuration second; + std::array both = { &cfg, &second }; + // The projects the section names, in its order, once AGENTS.md is + // written for `configurations`. + const auto named = [&](std::span configurations) { + (void)UpdateAgentsMd(configurations, projectFile); + const std::string now = Read(agents); + constexpr std::string_view from = "", pos) - pos - from.size())); + } + return names; + }; + using Names = std::vector; + + cfg.dependencyNotes = DependencyNotes::Direct; + second.dependencies = { outer }; + second.dependencyNotes = DependencyNotes::Direct; + Check(named(both) == Names{"tool", "lib", "outer"}, std::format("two Direct configurations give what each of them names (got {})", named(both))); + // lib is in the first ring through app, which asks for no more. The + // second configuration reaches it through outer and asks for + // everything, so what lib builds against is in. + second.dependencyNotes = DependencyNotes::Transitive; + Check(named(both) == Names{"tool", "lib", "outer", "base"}, std::format("a project a Direct configuration names is followed when a Transitive one leads to it (got {})", named(both))); + cfg.dependencyNotes = DependencyNotes::None; + second.dependencies = { baseProject }; + Check(named(both) == Names{"tool", "base"}, std::format("a configuration under None keeps out what only it is built against (got {})", named(both))); + second.dependencyNotes = DependencyNotes::None; + Check(named(both).empty() && Read(agents) == generated, "with every configuration under None, AGENTS.md holds the template's text alone"); + + // A configuration the file loaded from another project and returns + // is one of the projects it is built against, and its own setting + // counts for nothing here: it goes by the widest of the others. + std::array withOuter = { &cfg, outer }; + cfg.dependencyNotes = DependencyNotes::Direct; + Check(named(withOuter) == Names{"tool", "lib", "outer"}, std::format("a returned configuration of another project is in the first ring, and under Direct no more of it (got {})", named(withOuter))); + cfg.dependencyNotes = DependencyNotes::Transitive; + Check(named(withOuter) == Names{"tool", "lib", "outer", "base"}, std::format("under Transitive what it builds against follows (got {})", named(withOuter))); + std::array onlyOuter = { outer }; + Check(named(onlyOuter) == Names{"tool", "outer", "lib", "base"}, std::format("a file that made no configuration itself gets everything (got {})", named(onlyOuter))); + + // The same Configuration, for outer's own AGENTS.md: outer's project + // file made it, so here its setting is the one that selects, though + // a loader holds it. Told apart by being held, it was another + // project's configuration to its own file, and got everything. + const fs::path outerFile = scratch / "outer" / "project.cpp"; + const fs::path outerAgents = scratch / "outer" / "AGENTS.md"; + Write(scratch / "outer" / "AGENTS.template.md", templateText); + const auto outerNamed = [&](DependencyNotes setting) { + outer->dependencyNotes = setting; + (void)UpdateAgentsMd(*outer, outerFile); + const std::string now = Read(outerAgents); + constexpr std::string_view from = "", pos) - pos - from.size())); + } + return names; + }; + Check(outerNamed(DependencyNotes::Direct) == Names{"lib"}, std::format("a project loaded by another gets what its own Direct selects in its own AGENTS.md (got {})", outerNamed(DependencyNotes::Direct))); + Check(outerNamed(DependencyNotes::Transitive) == Names{"lib", "base"}, std::format("and what its Transitive does (got {})", outerNamed(DependencyNotes::Transitive))); + Check(outerNamed(DependencyNotes::None).empty() && Read(outerAgents) == generated, "and under None the template's text alone"); + outer->dependencyNotes = DependencyNotes::Transitive; + } + // Linked to the template, AGENTS.md would have every build write the // file that is committed. fs::remove(agents); diff --git a/tests/Lint/main.cpp b/tests/Lint/main.cpp index 4e07d94..d5cffc5 100644 --- a/tests/Lint/main.cpp +++ b/tests/Lint/main.cpp @@ -246,6 +246,52 @@ int main() { Check(s.Read("a") == "hello \n", "Check mode never writes"); } + // The configurations a project file returns: one run over the rules and + // the sources of all of them. The second lies inside the first's + // directory, which is the project root when no project file is given. + { + Scratch first("several"); + Scratch second("several/second"); + first.Write("a", "one \n"); + second.Write("b", "two \n"); + Configuration one = first.Config({"a"}); + Configuration two = second.Config({"b"}); + AddTrimRule(one); + AddTrimRule(two); + std::int32_t noted = 0; + two.AddLintRule("note", [¬ed](LintContext&) { ++noted; }); + std::array both = { &one, &two }; + LintSummary sum = RunLint(both, Mode(LintMode::Apply)); + Check(first.Read("a") == "one\n" && second.Read("b") == "two\n", "several: the sources of every configuration are formatted"); + Check(sum.rulesRun == 2, "several: a rule two configurations register under one name is one rule"); + Check(noted == 2, "several: a rule one configuration registers runs over the sources of all"); + } + + // A rule two of the returned configurations register under one name is + // the one the first of them registered, in the order the file returned + // them, whatever depends on the other: app depends on tools, so a walk + // of one configuration's graph after another's meets tools before + // `other` and would run its rule. + { + Scratch appDir("order"); + Scratch otherDir("order/other"); + Scratch toolsDir("order/tools"); + appDir.Write("a", "app\n"); + otherDir.Write("b", "other\n"); + toolsDir.Write("c", "tools\n"); + Configuration app = appDir.Config({"a"}); + Configuration other = otherDir.Config({"b"}); + Configuration tools = toolsDir.Config({"c"}); + app.dependencies = { &tools }; + std::atomic otherRan = 0; + std::atomic toolsRan = 0; + other.AddLintRule("pick", [&otherRan](LintContext&) { ++otherRan; }); + tools.AddLintRule("pick", [&toolsRan](LintContext&) { ++toolsRan; }); + std::array roots = { &app, &other, &tools }; + const LintSummary sum = RunLint(roots, Mode(LintMode::Report)); + Check(sum.rulesRun == 1 && otherRan == 3 && toolsRan == 0, std::format("several: the rule of the first configuration that registers the name runs, over every source (rules {}, the first's {} times, the later one's {} times)", sum.rulesRun, otherRan.load(), toolsRan.load())); + } + // Chaining: rule2 sees rule1's output; both attributed in Report mode. { Scratch s("chain"); diff --git a/tests/ProjectConfigurations/fixture/both/project.cpp b/tests/ProjectConfigurations/fixture/both/project.cpp new file mode 100644 index 0000000..d330144 --- /dev/null +++ b/tests/ProjectConfigurations/fixture/both/project.cpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// Both entry points: whichever the loader called, what the other returns +// would go unbuilt. +extern "C" Configuration CrafterBuildProject(std::span) { + return {}; +} + +extern "C" std::vector CrafterBuildConfigurations(std::span) { + return {}; +} diff --git a/tests/ProjectConfigurations/fixture/empty/project.cpp b/tests/ProjectConfigurations/fixture/empty/project.cpp new file mode 100644 index 0000000..37a17eb --- /dev/null +++ b/tests/ProjectConfigurations/fixture/empty/project.cpp @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// Returns nothing to build. +extern "C" std::vector CrafterBuildConfigurations(std::span) { + return {}; +} diff --git a/tests/ProjectConfigurations/fixture/neither/project.cpp b/tests/ProjectConfigurations/fixture/neither/project.cpp new file mode 100644 index 0000000..ef78490 --- /dev/null +++ b/tests/ProjectConfigurations/fixture/neither/project.cpp @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// No entry point: the function has a name the loader does not look for. +extern "C" Configuration CrafterBuildProjects(std::span) { + return {}; +} diff --git a/tests/ProjectConfigurations/fixture/null/project.cpp b/tests/ProjectConfigurations/fixture/null/project.cpp new file mode 100644 index 0000000..7731811 --- /dev/null +++ b/tests/ProjectConfigurations/fixture/null/project.cpp @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// Returns a pointer to nothing. +extern "C" std::vector CrafterBuildConfigurations(std::span) { + return { nullptr }; +} diff --git a/tests/ProjectConfigurations/fixture/several/greeter/Greeter.cppm b/tests/ProjectConfigurations/fixture/several/greeter/Greeter.cppm new file mode 100644 index 0000000..4e0c093 --- /dev/null +++ b/tests/ProjectConfigurations/fixture/several/greeter/Greeter.cppm @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Greeter; +import std; + +export namespace Greeter { + std::string Greet(std::string_view name) { + return std::format("hello {}", name); + } +} diff --git a/tests/ProjectConfigurations/fixture/several/hello/main.cpp b/tests/ProjectConfigurations/fixture/several/hello/main.cpp new file mode 100644 index 0000000..690dfe8 --- /dev/null +++ b/tests/ProjectConfigurations/fixture/several/hello/main.cpp @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Greeter; + +// -r runs this in its own directory, where it leaves what it would have +// printed for the test to find. +int main() { + std::ofstream("hello.ran") << Greeter::Greet("world"); + return 0; +} diff --git a/tests/ProjectConfigurations/fixture/several/project.cpp b/tests/ProjectConfigurations/fixture/several/project.cpp new file mode 100644 index 0000000..63d7b6a --- /dev/null +++ b/tests/ProjectConfigurations/fixture/several/project.cpp @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// A project of three configurations: a library, a program built on it, and +// a tool that shares nothing with either. The library and the tool each +// declare a test and a script. --no-tool leaves the tool out, which leaves +// one executable for -r to run. --packaged packages both programs as +// Flatpaks, for install and bundle to choose between, and makes them wasm +// builds, which a build refuses to package wherever the test runs: nothing +// is ever exported, let alone installed. --twin-test has the library +// declare the tool's test as well, which a test run refuses to build. +// --twin adds a fourth configuration of the tool's name and path, which +// would be built into the tool's directory. +namespace { + // One new set per call, at addresses that never change: whoever loads + // this file keeps the pointers it returns. + std::deque Owned; + + // Leaves `