diff --git a/AGENTS.template.md b/AGENTS.template.md index 3f41e6b..5f92432 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, 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. +- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, clang-scan-deps, 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 `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()`. @@ -40,7 +40,7 @@ Partitions and what they own: The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop. -Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. +Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime, and `clang-scan-deps`, which a build reads what each C++ source declares and imports with), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. ```bash ./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/ @@ -93,6 +93,7 @@ Conventions the existing tests follow: - Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"` and removes it on the next run. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. - Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. - Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. +- `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first. - A test that needs the host's flatpak goes through `RunHostFlatpak`, skips (77) with the reason `HostFlatpakUnavailable` gives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a private `FLATPAK_USER_DIR` under its fixture's `build/`, as `FlatpakInstall` does. It never runs an installed app: `flatpak run` makes `~/.var/app/` in the real home. - A test that packages a Flatpak stages the runtime: it writes a `.flatpak-info` whose `[Application]` group has a `runtime=runtime/org.freedesktop.Sdk/x86_64/26.08` line, as the parser takes only that group's, and points `CRAFTER_BUILD_FLATPAK_INFO` at it with `setenv`, first thing in `main`, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak; `FlatpakNative` stages an empty one for the native case. @@ -205,7 +206,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - 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. +- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. A scan is kept in the build directory as an object is, in `scans/` or, for a source outside `cfg.path`, in `scans-outside/`, as JSON holding the command it was taken with and what clang-scan-deps wrote, with a dependency file beside it, and taken again when the command differs, when the source or a file the dependency file lists is newer, and when it cannot be read. A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build. - 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 bff76b7..3b367e3 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -23,229 +23,467 @@ using namespace Crafter; namespace { - // Map one `import X;` name onto either a module this Configuration owns or - // one exported by a Configuration reachable through its dependency DAG, - // appending the matching staleness edge. False means nothing in reach - // provides X — either it's supplied from outside the graph (`std`) or the - // dependency isn't wired up *yet*, which is why callers remember the name. - bool ResolveImportName(Configuration& cfg, const std::string& importName, std::vector& localDeps, std::vector>& externalDeps) { - for(const std::unique_ptr& interface : cfg.interfaces) { - if(interface->name == importName) { - localDeps.push_back(interface.get()); + // A JSON value: what clang-scan-deps writes of a source, and what Build() + // keeps of that. The members of an object are its `items`, each with + // its `key`. + struct Json { + enum class Kind { Null, Boolean, Number, String, Array, Object }; + Kind kind = Kind::Null; + bool boolean = false; + // A string's value, or a number as it is written. + std::string text; + std::vector items; + std::string key; + + // The member of an object named `name`; nullptr when the object has + // none, and for a value that is no object. + const Json* Member(std::string_view name) const { + if (kind != Kind::Object) return nullptr; + for (const Json& item : items) { + if (item.key == name) return &item; + } + return nullptr; + } + }; + + // Reads the one JSON value (RFC 8259) a text holds. There is no JSON + // library in the tree, and what clang-scan-deps writes is JSON. + class JsonReader { + public: + explicit JsonReader(std::string_view text) : text(text) {} + + // The value, with nothing after it but white space; nullopt for a + // text that holds anything else. + std::optional Read() { + Json value; + if (!Value(value, 0)) return std::nullopt; + SkipSpace(); + if (at != text.size()) return std::nullopt; + return value; + } + + private: + // Deeper than anything clang-scan-deps writes, and shallow enough + // that a text which is not its output cannot exhaust the stack. + static constexpr std::size_t MaxDepth = 64; + + bool Value(Json& value, std::size_t depth) { + SkipSpace(); + if (at == text.size() || depth > MaxDepth) return false; + if (text[at] == '{') return Object(value, depth); + if (text[at] == '[') return Array(value, depth); + if (text[at] == '"') { + value.kind = Json::Kind::String; + return String(value.text); + } + if (Word("true")) { + value.kind = Json::Kind::Boolean; + value.boolean = true; return true; } + if (Word("false")) { + value.kind = Json::Kind::Boolean; + return true; + } + if (Word("null")) return true; + return Number(value); + } + + bool Object(Json& value, std::size_t depth) { + value.kind = Json::Kind::Object; + ++at; + SkipSpace(); + if (Take('}')) return true; + do { + SkipSpace(); + Json member; + if (!String(member.key)) return false; + SkipSpace(); + if (!Take(':') || !Value(member, depth + 1)) return false; + value.items.push_back(std::move(member)); + SkipSpace(); + } while (Take(',')); + return Take('}'); + } + + bool Array(Json& value, std::size_t depth) { + value.kind = Json::Kind::Array; + ++at; + SkipSpace(); + if (Take(']')) return true; + do { + Json element; + if (!Value(element, depth + 1)) return false; + value.items.push_back(std::move(element)); + SkipSpace(); + } while (Take(',')); + return Take(']'); + } + + // The string that starts at the cursor, its escapes undone, into + // `out`. + bool String(std::string& out) { + if (!Take('"')) return false; + while (at < text.size()) { + const char c = text[at++]; + if (c == '"') return true; + // A control character is only ever escaped. + if (static_cast(c) < 0x20) return false; + if (c != '\\') { + out.push_back(c); + continue; + } + if (at == text.size()) return false; + switch (text[at++]) { + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case '/': out.push_back('/'); break; + case 'b': out.push_back('\b'); break; + case 'f': out.push_back('\f'); break; + case 'n': out.push_back('\n'); break; + case 'r': out.push_back('\r'); break; + case 't': out.push_back('\t'); break; + case 'u': { + std::uint32_t code = 0; + if (!Hex(code)) return false; + // A character past the first 65,536 is written as + // two escapes, a high surrogate and then a low one. + if (code >= 0xD800 && code <= 0xDBFF) { + std::uint32_t low = 0; + if (!Take('\\') || !Take('u') || !Hex(low) || low < 0xDC00 || low > 0xDFFF) return false; + code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00); + } else if (code >= 0xDC00 && code <= 0xDFFF) { + return false; + } + AppendUtf8(out, code); + break; + } + default: return false; + } + } + return false; + } + + // The four hexadecimal digits at the cursor, as the number they + // spell, into `code`. + bool Hex(std::uint32_t& code) { + if (text.size() - at < 4) return false; + for (const std::size_t end = at + 4; at < end; ++at) { + const char c = text[at]; + std::uint32_t digit = 0; + if (c >= '0' && c <= '9') { + digit = static_cast(c - '0'); + } else if (c >= 'a' && c <= 'f') { + digit = static_cast(c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + digit = static_cast(c - 'A' + 10); + } else { + return false; + } + code = code * 16 + digit; + } + return true; + } + + static void AppendUtf8(std::string& out, std::uint32_t code) { + if (code < 0x80) { + out.push_back(static_cast(code)); + } else if (code < 0x800) { + out.push_back(static_cast(0xC0 | (code >> 6))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } else if (code < 0x10000) { + out.push_back(static_cast(0xE0 | (code >> 12))); + out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } else { + out.push_back(static_cast(0xF0 | (code >> 18))); + out.push_back(static_cast(0x80 | ((code >> 12) & 0x3F))); + out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } } - std::unordered_set seen; - std::function walk = [&](Configuration* depCfg) -> bool { - if (!seen.insert(depCfg).second) return false; - for(const std::unique_ptr& depInterface : depCfg->interfaces) { - if(depInterface->name == importName) { - fs::path depPcmPath = std::format("{}.pcm", (depCfg->PcmDir() / depInterface->path.filename()).string()); - externalDeps.emplace_back(depInterface.get(), std::move(depPcmPath)); - return true; - } + // The number at the cursor, kept as it is written: no number that + // clang-scan-deps writes is read. + bool Number(Json& value) { + const std::size_t start = at; + Take('-'); + if (!Digits()) return false; + if (Take('.') && !Digits()) return false; + if (Take('e') || Take('E')) { + if (!Take('+')) Take('-'); + if (!Digits()) return false; } - for(Configuration* sub : depCfg->dependencies) { - if (walk(sub)) return true; + value.kind = Json::Kind::Number; + value.text = std::string(text.substr(start, at - start)); + return true; + } + + bool Digits() { + const std::size_t start = at; + while (at < text.size() && text[at] >= '0' && text[at] <= '9') ++at; + return at > start; + } + + bool Word(std::string_view word) { + if (!text.substr(at).starts_with(word)) return false; + at += word.size(); + return true; + } + + bool Take(char c) { + if (at == text.size() || text[at] != c) return false; + ++at; + return true; + } + + void SkipSpace() { + while (at < text.size() && (text[at] == ' ' || text[at] == '\t' || text[at] == '\n' || text[at] == '\r')) ++at; + } + + std::string_view text; + std::size_t at = 0; + }; + + // What one source declares and imports, as clang-scan-deps read it. + struct ScannedUnit { + // The unit of a module it is by its declaration: `X` for the primary + // interface of module X, `X:P` for X's partition P. Empty for a + // source that is neither, as an implementation unit of X written + // `module X;` is, which imports X instead. + std::string provides; + // The modules and partitions it imports, each by its whole name: an + // `import :P;` in a unit of X is `X:P`. + std::vector imports; + }; + + // The unit `document` describes, as clang-scan-deps describes a single + // source in its P1689 format; nullopt for a document of any other shape. + std::optional ReadP1689(const Json& document) { + const Json* rules = document.Member("rules"); + if (rules == nullptr || rules->kind != Json::Kind::Array || rules->items.size() != 1) return std::nullopt; + const Json& rule = rules->items.front(); + // The logical name of each entry of the rule's array `name`, which + // need not be there; false when it is there and is not such an + // array. + const auto names = [&rule](std::string_view name, std::vector& out) { + const Json* entries = rule.Member(name); + if (entries == nullptr) return true; + if (entries->kind != Json::Kind::Array) return false; + for (const Json& entry : entries->items) { + const Json* logical = entry.Member("logical-name"); + if (logical == nullptr || logical->kind != Json::Kind::String) return false; + out.push_back(logical->text); + } + return true; + }; + std::vector provided; + ScannedUnit unit; + if (!names("provides", provided) || provided.size() > 1 || !names("requires", unit.imports)) return std::nullopt; + if (!provided.empty()) unit.provides = std::move(provided.front()); + return unit; + } + + std::optional ReadWholeFile(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + if (!in) return std::nullopt; + std::stringstream buffer; + buffer << in.rdbuf(); + return std::move(buffer).str(); + } + + // The dependency file of the scan Build() keeps at `scan`, beside it: the + // source and every file it included, as a rule for `scan`. + fs::path ScanDepfile(const fs::path& scan) { + return fs::path(scan) += ".d"; + } + + // The scan of a source that Build() keeps at `scan`, when it holds for + // `command`: it was taken with that command, after the source and every + // file the source included were last written (NewestPrerequisite of + // its dependency file). nullopt when it does not, and when it cannot be + // read; the source is then scanned again. + std::optional CurrentScan(const fs::path& scan, std::string_view command) { + std::error_code ec; + const fs::file_time_type written = fs::last_write_time(scan, ec); + if (ec || NewestPrerequisite(ScanDepfile(scan)) >= written) return std::nullopt; + const std::optional text = ReadWholeFile(scan); + if (!text) return std::nullopt; + const std::optional kept = JsonReader(*text).Read(); + if (!kept) return std::nullopt; + const Json* scannedWith = kept->Member("command"); + const Json* p1689 = kept->Member("p1689"); + if (scannedWith == nullptr || scannedWith->kind != Json::Kind::String || scannedWith->text != command || p1689 == nullptr) return std::nullopt; + return ReadP1689(*p1689); + } + + // A unit's name split at its colon: {"X", ""} for the module X, + // {"X", "P"} for X's partition P. + std::pair SplitUnitName(std::string_view name) { + const std::size_t colon = name.find(':'); + if (colon == std::string_view::npos) return {name, {}}; + return {name.substr(0, colon), name.substr(colon + 1)}; + } + + Module* FindModule(std::span> modules, std::string_view name) { + for (const std::unique_ptr& candidate : modules) { + if (candidate->name == name) return candidate.get(); + } + return nullptr; + } + + // The configuration whose build the pass ran for the directory a + // dependency is built into, and so the one that holds the modules of + // that build (BuildResult::built): the dependency itself, or another + // configuration of its directory. + using BuiltConfiguration = std::function; + + // Adds the staleness edge of an import of the module `name` by a unit of + // a configuration whose own modules are `local` and which is built on + // `dependencies`: to the module among `local`, else to the first found + // among the modules of the dependencies and of what they are built on, + // each as `builtIn` gives it, with the BMI that one's build writes, + // unless the unit has that edge already. A module none of them has, + // `std` or one from outside the build, gets no edge. The dependencies + // have been built when this is called, and so have read their sources: + // their modules are known. + void AddImport(std::span> local, std::span dependencies, const BuiltConfiguration& builtIn, std::string_view name, std::vector& localDeps, std::vector>& externalDeps) { + if (Module* own = FindModule(local, name)) { + if (!std::ranges::contains(localDeps, own)) localDeps.push_back(own); + return; + } + std::unordered_set seen; + std::function walk = [&](const Configuration& listed) -> bool { + const Configuration& depCfg = builtIn(listed); + if (!seen.insert(&depCfg).second) return false; + if (Module* found = FindModule(depCfg.interfaces, name)) { + if (!std::ranges::contains(externalDeps, found, &std::pair::first)) { + externalDeps.emplace_back(found, std::format("{}.pcm", (depCfg.PcmDir() / found->path.filename()).string())); + } + return true; + } + for (const Configuration* sub : depCfg.dependencies) { + if (walk(*sub)) return true; } return false; }; - - for(Configuration* depCfg : cfg.dependencies) { - if (walk(depCfg)) return true; + for (const Configuration* depCfg : dependencies) { + if (walk(*depCfg)) return; } - return false; } -} -void Configuration::ResolvePendingImports() { - // Same resolution the scan used, and against both dependency kinds — a - // second GetInterfacesAndImplementations call can add interfaces that an - // earlier batch's import was looking for, so a pending name may land on a - // local module and not just an external one. - auto sweep = [this](std::vector& pending, std::vector& localDeps, std::vector>& externalDeps) { - std::erase_if(pending, [&](const std::string& name) { - return ResolveImportName(*this, name, localDeps, externalDeps); - }); + // The modules and units of a configuration as the scans of its sources + // describe them, before Build() gives them to the configuration. + struct ModuleGraph { + std::vector> interfaces; + std::vector implementations; }; - for(const std::unique_ptr& interface : interfaces) { - sweep(interface->pendingImports, interface->moduleDependencies, interface->externalModuleDependencies); - for(const std::unique_ptr& partition : interface->partitions) { - sweep(partition->pendingImports, partition->moduleDependencies, partition->externalModuleDependencies); + + // Makes the modules and units of `config` from `interfaceScans` and + // `implementationScans`, the scans of its interfaceSources and of its + // implementationSources in the order they are listed in, with its + // dependencies as `builtIn` gives them. Returns why it could not, empty + // when it could. + std::string MakeModuleGraph(const Configuration& config, std::span interfaceScans, std::span implementationScans, const BuiltConfiguration& builtIn, ModuleGraph& graph) { + // A unit is named by its source without the extension. + const auto stem = [](const fs::path& source) { + fs::path stemmed = source; + stemmed.replace_extension(); + return stemmed; + }; + // The unit each interface source is: its module, and for a + // partition the partition as well. + std::vector moduleOf(interfaceScans.size(), nullptr); + std::vector partitionOf(interfaceScans.size(), nullptr); + // The primary interfaces first, so that a partition finds its module + // in whatever order the two are listed. + for (std::size_t i = 0; i < interfaceScans.size(); ++i) { + const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); + if (moduleName.empty()) return std::format("No module declaration found in {}", config.interfaceSources[i].string()); + if (!partitionName.empty()) continue; + graph.interfaces.push_back(std::make_unique(std::string(moduleName), stem(config.interfaceSources[i]))); + moduleOf[i] = graph.interfaces.back().get(); } - } - for(Implementation& implementation : implementations) { - sweep(implementation.pendingImports, implementation.moduleDependencies, implementation.externalModuleDependencies); + for (std::size_t i = 0; i < interfaceScans.size(); ++i) { + const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); + if (partitionName.empty()) continue; + Module* owner = FindModule(graph.interfaces, moduleName); + if (owner == nullptr) return std::format("Module {} not found, referenced in {}", moduleName, config.interfaceSources[i].string()); + owner->partitions.push_back(std::make_unique(std::string(partitionName), stem(config.interfaceSources[i]))); + moduleOf[i] = owner; + partitionOf[i] = owner->partitions.back().get(); + } + + // The partition an import of `X:P` names: a partition of the module + // X among this configuration's interface sources. X is the importing + // unit's own module, since only its partitions can be imported. + // nullptr when there is none. + const auto partitionNamed = [&graph](std::string_view moduleName, std::string_view partitionName) -> ModulePartition* { + const Module* owner = FindModule(graph.interfaces, moduleName); + if (owner == nullptr) return nullptr; + for (const std::unique_ptr& partition : owner->partitions) { + if (partition->name == partitionName) return partition.get(); + } + return nullptr; + }; + + for (std::size_t i = 0; i < interfaceScans.size(); ++i) { + ModulePartition* partition = partitionOf[i]; + for (const std::string& name : interfaceScans[i].imports) { + const auto [moduleName, partitionName] = SplitUnitName(name); + if (partitionName.empty()) { + if (partition != nullptr) { + AddImport(graph.interfaces, config.dependencies, builtIn, name, partition->moduleDependencies, partition->externalModuleDependencies); + } else { + AddImport(graph.interfaces, config.dependencies, builtIn, name, moduleOf[i]->moduleDependencies, moduleOf[i]->externalModuleDependencies); + } + continue; + } + ModulePartition* imported = partitionNamed(moduleName, partitionName); + if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, config.interfaceSources[i].string()); + // A primary interface needs no edge to its own partitions: it + // is checked and built after every one of them (Module::Check, + // Module::Schedule). + if (partition != nullptr && !std::ranges::contains(partition->partitionDependencies, imported)) partition->partitionDependencies.push_back(imported); + } + } + + for (std::size_t i = 0; i < implementationScans.size(); ++i) { + const fs::path& source = config.implementationSources[i]; + Implementation& implementation = graph.implementations.emplace_back(stem(source)); + // A source that is a unit of a module by its declaration, as an + // implementation partition (`module X:P;`) is, belongs to a + // module of this configuration. + if (const std::string_view moduleName = SplitUnitName(implementationScans[i].provides).first; !moduleName.empty() && FindModule(graph.interfaces, moduleName) == nullptr) { + return std::format("Module {} not found, referenced in {}", moduleName, source.string()); + } + for (const std::string& name : implementationScans[i].imports) { + const auto [moduleName, partitionName] = SplitUnitName(name); + if (partitionName.empty()) { + AddImport(graph.interfaces, config.dependencies, builtIn, name, implementation.moduleDependencies, implementation.externalModuleDependencies); + continue; + } + ModulePartition* imported = partitionNamed(moduleName, partitionName); + if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, source.string()); + if (!std::ranges::contains(implementation.partitionDependencies, imported)) implementation.partitionDependencies.push_back(imported); + } + } + return ""; } } void Configuration::GetInterfacesAndImplementations(std::span interfaces, std::span implementations) { - auto resolveImport = [this](const std::string& importName, std::vector& localDeps, std::vector>& externalDeps, std::vector& pending) { - if (!ResolveImportName(*this, importName, localDeps, externalDeps)) { - pending.push_back(importName); - } - }; - - std::vector> tempModulePaths = std::vector>(interfaces.size()); - for(std::uint16_t i = 0; i < interfaces.size(); i++){ - // Resolve to absolute now so the stored path survives cwd changes - // (matters for GitProject deps loaded from a different working dir). - fs::path file = fs::absolute(path / interfaces[i]).lexically_normal(); - file += ".cppm"; - std::ifstream t(file); - std::stringstream buffer; - buffer << t.rdbuf(); - std::string fileContent = buffer.str(); - fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); - fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); - tempModulePaths[i] = {file, fileContent, nullptr, nullptr}; + // Absolute now, so that a path stays the same file when the working + // directory changes, as it does around the load of a GitProject. + for (const fs::path& listed : interfaces) { + fs::path source = fs::absolute(path / listed).lexically_normal(); + source += ".cppm"; + interfaceSources.push_back(std::move(source)); } - - // Primary interface units first, so the partition pass below can find their - // parent Module. They stay in tempModulePaths — a primary unit's own - // `import X;` lines are layout dependencies exactly like a partition's, and - // dropping the entry here is what left them unrecorded (issue #26). Marked - // by a null partition slot with the Module slot filled in. - for(std::tuple& file : tempModulePaths) { - std::smatch match; - if (std::regex_search(std::get<1>(file), match, std::regex(R"(export module ([a-zA-Z0-9_\.\-]+);)"))) { - fs::path pthCpy = std::get<0>(file); - pthCpy.replace_extension(""); - this->interfaces.push_back(std::make_unique(std::move(match[1].str()), std::move(pthCpy))); - std::get<3>(file) = this->interfaces.back().get(); - } - } - - for(std::uint16_t i = 0; i < tempModulePaths.size(); i++) { - std::smatch match; - if (std::get<3>(tempModulePaths[i]) != nullptr) { - continue; - } - if (std::regex_search(std::get<1>(tempModulePaths[i]), match, std::regex(R"(export module ([a-zA-Z_0-9\.\-]+):([a-zA-Z_0-9\.\-]+);)"))) { - for(const std::unique_ptr& modulee : this->interfaces) { - if(modulee->name == match[1]) { - std::string name = match[2].str(); - fs::path pthCpy = std::get<0>(tempModulePaths[i]); - pthCpy.replace_extension(""); - std::unique_ptr partition = std::make_unique(std::move(name), std::move(pthCpy)); - std::get<2>(tempModulePaths[i]) = partition.get(); - modulee->partitions.push_back(std::move(partition)); - std::get<3>(tempModulePaths[i]) = modulee.get(); - goto next; - } - } - throw std::runtime_error(std::format("Module {} not found, referenced in {}", match[1].str(), std::get<0>(tempModulePaths[i]).string())); - } else { - throw std::runtime_error(std::format("No module declaration found in {}", std::get<0>(tempModulePaths[i]).string())); - } - next:; - } - - for(std::tuple& file : tempModulePaths) { - ModulePartition* partition = std::get<2>(file); - Module* parentModule = std::get<3>(file); - const std::string& fileContent = std::get<1>(file); - - // 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::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); - std::sregex_iterator primaryLast; - while (primaryCurrent != primaryLast) { - std::smatch match = *primaryCurrent; - resolveImport(match[1].str(), parentModule->moduleDependencies, parentModule->externalModuleDependencies, parentModule->pendingImports); - ++primaryCurrent; - } - continue; - } - - std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); - std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); - std::sregex_iterator lastMatch; - while (currentMatch != lastMatch) { - std::smatch match = *currentMatch; - for(std::unique_ptr& sibling : parentModule->partitions) { - if(sibling->name == match[1]) { - partition->partitionDependencies.push_back(sibling.get()); - goto next2; - } - } - throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", parentModule->name, match[1].str(), std::get<0>(file).string())); - next2: ++currentMatch; - } - - std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); - std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); - while (modCurrent != lastMatch) { - std::smatch match = *modCurrent; - resolveImport(match[1].str(), partition->moduleDependencies, partition->externalModuleDependencies, partition->pendingImports); - ++modCurrent; - } - } - - for(const fs::path& tempFile : implementations) { - fs::path file = fs::absolute(path / tempFile).lexically_normal(); - file += ".cpp"; - std::ifstream t(file); - std::stringstream buffer; - buffer << t.rdbuf(); - std::string fileContent = buffer.str(); - fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); - fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); - std::smatch match; - fs::path fileCopy = file; - fileCopy.replace_extension(""); - Implementation& implementation = this->implementations.emplace_back(std::move(fileCopy)); - if (std::regex_search(fileContent, match, std::regex(R"(module ([a-zA-Z0-9_\.\-]+)(:[a-zA-Z0-9_\.\-]+)?\s*;)"))) { - const bool isPartitionImpl = match[2].length() > 0; - for(const std::unique_ptr& interface : this->interfaces) { - if(interface->name == match[1]) { - if (!isPartitionImpl) { - implementation.moduleDependencies.push_back(interface.get()); - } - std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); - std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); - std::sregex_iterator lastMatch; - while (currentMatch != lastMatch) { - std::smatch match2 = *currentMatch; - for(const std::unique_ptr& partition : interface->partitions) { - if(partition->name == match2[1]) { - implementation.partitionDependencies.push_back(partition.get()); - goto next3; - } - } - throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", match[1].str(), match2[1].str(), file.string())); - next3: ++currentMatch; - } - - std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); - std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); - while (modCurrent != lastMatch) { - std::smatch match2 = *modCurrent; - if (match2[1] != match[1]) { - resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); - } - ++modCurrent; - } - goto next4; - } - } - throw std::runtime_error(std::format("Module {} not found not found, referenced in {}", match[1].str(), file.string())); - next4:; - } else { - std::regex pattern(R"(import ([a-zA-Z_\-0-9\.]+);)"); - std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), pattern); - std::sregex_iterator lastMatch; - while (currentMatch != lastMatch) { - std::smatch match2 = *currentMatch; - resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); - ++currentMatch; - } - } + for (const fs::path& listed : implementations) { + fs::path source = fs::absolute(path / listed).lexically_normal(); + source += ".cpp"; + implementationSources.push_back(std::move(source)); } } @@ -340,10 +578,12 @@ namespace { } // ObjectPath's rule for the sources of one configuration, with what it - // takes from the configuration worked out once for all of them. + // takes from the configuration worked out once for all of them, and the + // same rule for where Build() keeps the scan of each interface and + // implementation source. class SourceLayout { public: - SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside") {} + SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside"), scansInside(buildDir / "scans"), scansOutside(buildDir / "scans-outside") {} // The object of the source a configuration lists as `listed`, which // is its path without its extension, `extension`. @@ -354,14 +594,32 @@ namespace { return within.empty() ? outside / object.relative_path() : inside / within; } + // Where the scan of `source`, given with its extension, is kept: + // named as Object() names an object, under scans/ and + // scans-outside/, by the source's own name with .json after it, as + // in scans/a/Thing.cppm.json, so that a .cppm and a .cpp of one + // name have one each. + fs::path Scan(const fs::path& source) const { + fs::path scan = fs::absolute(source).lexically_normal(); + scan += ".json"; + const fs::path within = Within(scan); + return within.empty() ? scansOutside / scan.relative_path() : scansInside / within; + } + // That source as the progress line of its compile names it: by its // path from the configuration's directory, or by its whole path // when it lies outside that directory. std::string Shown(const fs::path& listed, std::string_view extension) const { fs::path source = fs::absolute(listed).lexically_normal(); source += extension; - const fs::path within = Within(source); - return within.empty() ? source.string() : within.string(); + return Shown(source); + } + + // The same for a source given with its extension. + std::string Shown(const fs::path& source) const { + const fs::path resolved = fs::absolute(source).lexically_normal(); + const fs::path within = Within(resolved); + return within.empty() ? resolved.string() : within.string(); } private: @@ -376,6 +634,8 @@ namespace { fs::path directory; fs::path inside; fs::path outside; + fs::path scansInside; + fs::path scansOutside; }; } @@ -591,8 +851,13 @@ namespace { // that it was the build they had been compiled against. The program then // linked code compiled against two layouts of the same types, and ran // (issue #41). Empty when the dependencies agree, otherwise the error, - // naming the path to each of the two builds. - std::string DuplicateModuleError(const Configuration& config) { + // naming the path to each of the two builds. Asked once Build() has read + // the sources of `config`: the modules of a configuration are what the + // build that read its sources found (Configuration::interfaces), and + // those of each dependency are known once it is built. A dependency is + // taken as `builtIn` gives it, so two configurations that the pass + // builds into one directory are one build of their modules, not two. + std::string DuplicateModuleError(const Configuration& config, const BuiltConfiguration& builtIn) { struct Owner { const Configuration* cfg; std::string chain; @@ -603,7 +868,8 @@ namespace { std::unordered_map owners; std::unordered_set visited; std::string error; - std::function walk = [&](const Configuration& c, const std::string& chain) { + std::function walk = [&](const Configuration& listed, const std::string& chain) { + const Configuration& c = &listed == &config ? config : builtIn(listed); if (!error.empty() || !visited.insert(&c).second) return; for (const std::unique_ptr& iface : c.interfaces) { const auto [it, inserted] = owners.emplace(iface->name, Owner{ &c, chain }); @@ -625,11 +891,6 @@ namespace { // 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 - // (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; @@ -679,7 +940,7 @@ namespace { }; 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); + 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.", config.name, round); } // What a wasm32 configuration cannot be built with now that every unit @@ -875,6 +1136,92 @@ namespace { quoted.push_back('"'); return quoted; } + + // Has `scanner`, clang-scan-deps, read `source` as `command` compiles it, + // and keeps what it found at `scan` for CurrentScan: a JSON object of the + // command and of the P1689 description the scanner wrote, with the + // dependency file of what the source included beside it. Both are + // written beside their places and moved into them (WrittenBeside), as + // another crafter-build may be reading them. Returns what went wrong, + // empty when nothing did, and then leaves what it found in `found`. + std::string ScanSource(const fs::path& scanner, std::string_view command, const fs::path& source, const fs::path& scan, ScannedUnit& found) { + std::error_code ec; + fs::create_directories(scan.parent_path()); + const fs::path description = WrittenBeside(scan); + const fs::path depfile = WrittenBeside(ScanDepfile(scan)); + // -w: what the preprocessor warns of, the compile of the source + // reports. The command's own output is named `scan`, so that the + // dependency file is the rule for the scan. + const std::string failed = RunBuildCommand(std::format("{} -format=p1689 -o {} -- {} -w {} -c -MD -MF {} -o {}", ShellQuote(scanner.string()), ShellQuote(description.string()), command, ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string()))); + const std::optional written = ReadWholeFile(description); + fs::remove(description, ec); + if (!failed.empty()) { + fs::remove(depfile, ec); + return failed; + } + const std::optional document = written ? JsonReader(*written).Read() : std::nullopt; + std::optional unit = document ? ReadP1689(*document) : std::nullopt; + if (!unit) { + fs::remove(depfile, ec); + return std::format("clang-scan-deps wrote no description of {} that crafter-build can read: {}", source.string(), written.value_or("")); + } + const fs::path kept = WrittenBeside(scan); + std::ofstream out(kept, std::ios::binary | std::ios::trunc); + out << std::format("{{\"command\": {}, \"p1689\": {}}}\n", JsonQuote(command), *written); + out.close(); + if (out.fail()) { + fs::remove(kept, ec); + fs::remove(depfile, ec); + return std::format("cannot write {}, the scan of {}", kept.string(), source.string()); + } + // The dependency file first. Should the second move fail, the scan + // of before is left beside the dependency file of now, which lists + // what the source includes now; the other way round, the scan of + // now would be left beside the dependency file of before, which may + // miss a header the source includes now, and an edit of that header + // would not have the source scanned again. + if (std::string moved = MoveIntoPlace(depfile, ScanDepfile(scan)); !moved.empty()) { + fs::remove(kept, ec); + return moved; + } + if (std::string moved = MoveIntoPlace(kept, scan); !moved.empty()) return moved; + found = std::move(*unit); + return ""; + } + + // Reads what each interface and implementation source of `config` + // declares and imports, with `command`, the command they are compiled + // with, and gives the configuration the modules and units that makes. A + // source whose scan is current (CurrentScan) is not read again; the + // others are scanned at once, each a job on the workers of the process. + // Returns why it could not, empty when it could; the configuration then + // keeps the modules and units it had. Its dependencies are taken as + // `builtIn` gives them. + std::string ReadSources(Configuration& config, std::string_view command, const SourceLayout& layout, const BuiltConfiguration& builtIn) { + std::vector sources = config.interfaceSources; + sources.insert(sources.end(), config.implementationSources.begin(), config.implementationSources.end()); + std::vector scans(sources.size()); + { + JobGroup scanning; + for (std::size_t i = 0; i < sources.size(); ++i) { + fs::path scan = layout.Scan(sources[i]); + if (std::optional current = CurrentScan(scan, command)) { + scans[i] = std::move(*current); + continue; + } + scanning.Add(std::format("Scanning {}", layout.Shown(sources[i])), [&scans, i, scanner = GetToolchain().clangScanDeps, command = std::string(command), source = sources[i], scan = std::move(scan)] { + return ScanSource(scanner, command, source, scan, scans[i]); + }); + } + if (std::string failed = scanning.Wait(); !failed.empty()) return failed; + } + const std::span scanned(scans); + ModuleGraph graph; + if (std::string error = MakeModuleGraph(config, scanned.first(config.interfaceSources.size()), scanned.subspan(config.interfaceSources.size()), builtIn, graph); !error.empty()) return error; + config.interfaces = std::move(graph.interfaces); + config.implementations = std::move(graph.implementations); + return ""; + } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { @@ -883,63 +1230,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapchecked = false; - iface->scheduled = false; - iface->precompileJob.reset(); - for (auto& part : iface->partitions) { - part->checked = false; - part->scheduled = false; - part->precompileJob.reset(); - } - } - - // Sources were scanned when they were declared, which for most callers is - // before `dependencies` exists — AddTest resolves tests//main.cpp and - // only then hands back a builder whose .Dependencies() supplies the library. - // Any `import ;` in such a TU resolved to nothing and so carried - // no staleness edge, which meant a member added to a dependency's interface - // rebuilt the library, relinked the consumer, and silently kept the - // consumer's object compiled against the *old* class layout (issue #27). - // Re-resolving here — the last point before mtimes are compared, with the - // DAG fully wired — closes that window for every caller rather than for the - // ones that remember to declare in the right order. - config.ResolvePendingImports(); - // With every import placed, and before this configuration makes a - // directory or builds a dependency. A configuration built on this one - // has started its own build by then: the imports just placed are this - // Build()'s to read, so no other configuration's can check them for it. - if (std::string cycle = ImportCycleError(config); !cycle.empty()) { - return {std::move(cycle), false, {}}; - } - - // As early as the duplicate-module check, so a refused build leaves no + // Before anything is spawned as well, so a refused build leaves no // directory behind and starts no thread. A Flatpak asked of a target that // cannot be one says so before anything the target itself would refuse: // that is the request to change. @@ -952,7 +1243,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map externalFloor) externalFloor = ext.latestArtifact; } + // What the interface and implementation sources declare and import, read + // only now: clang-scan-deps preprocesses each with the command it is + // compiled with, which is complete from here on, with the include paths + // of the dependencies and external dependencies just built, whose + // headers a source may include. Their modules, which the imports are + // looked up among, are known by now too, as each dependency's Build() + // has read its own sources. A Build() makes the modules and units of its + // own configuration alone: those of a dependency are its own Build()'s + // to make, and the builds of other configurations built on it may be + // reading them at this moment. + // + // A dependency's modules are those of the build the pass ran for its + // directory, which need not have been the dependency's own: OncePerPass + // builds a directory once, for whichever configuration of it asked + // first, and a configuration it did not build has no modules (see + // BuildResult::built). Every dependency has its result in the pass by + // now. + const BuiltConfiguration builtIn = [&depResults, &depMutex](const Configuration& dependency) -> const Configuration& { + std::shared_future built; + { + std::lock_guard lock(depMutex); + if (const auto found = depResults.find(dependency.PcmDir()); found != depResults.end()) built = found->second; + } + if (built.valid() && built.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { + // A build that threw has failed this one already, before it got + // here, and is taken as the dependency's own. + try { + if (const Configuration* ran = built.get().built) return *ran; + } catch (...) { + } + } + return dependency; + }; + if (std::string error = ReadSources(config, command, layout, builtIn); !error.empty()) { + jobs.Fail(std::move(error)); + return {jobs.Wait(), false, {}}; + } + buildResult.built = &config; + // Both before any .cppm or .cpp of the configuration is compiled, and + // only now that its modules are known. Its C and CUDA sources, whose + // compiles started beside the dependencies' builds, may have been. + if (std::string duplicate = DuplicateModuleError(config, builtIn); !duplicate.empty()) { + jobs.Fail(std::move(duplicate)); + return {jobs.Wait(), false, {}}; + } + if (std::string cycle = ImportCycleError(config); !cycle.empty()) { + jobs.Fail(std::move(cycle)); + return {jobs.Wait(), false, {}}; + } + // 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 diff --git a/implementations/Crafter.Build-Implementation.cpp b/implementations/Crafter.Build-Implementation.cpp index 132c0cd..84bbe18 100644 --- a/implementations/Crafter.Build-Implementation.cpp +++ b/implementations/Crafter.Build-Implementation.cpp @@ -17,8 +17,8 @@ namespace Crafter { std::string objPath = object.string(); std::string cppPath = std::format("{}.cpp", path.string()); // The depfile clang wrote beside the object lists the headers this TU - // included; nothing else in the configuration knows about them, since - // the source scanner only reads `import` lines. + // included when the object was compiled: inputs of the object as + // much as the source and the BMIs it imports. if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) { return true; } diff --git a/implementations/Crafter.Build-Interface.cpp b/implementations/Crafter.Build-Interface.cpp index 4a56fe0..14636dd 100644 --- a/implementations/Crafter.Build-Interface.cpp +++ b/implementations/Crafter.Build-Interface.cpp @@ -185,10 +185,10 @@ namespace Crafter { 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. + // names: Build() records no edge for its `import :Part;` lines (see + // Module::moduleDependencies). 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); } diff --git a/implementations/Crafter.Build-Lint.cpp b/implementations/Crafter.Build-Lint.cpp index 619fc8c..948b9e4 100644 --- a/implementations/Crafter.Build-Lint.cpp +++ b/implementations/Crafter.Build-Lint.cpp @@ -903,15 +903,10 @@ namespace { // First owner wins, matching the root-first rule dedup: a source // reachable through two configurations parses with the nearer one. auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); }; - for (const std::unique_ptr& mod : c.interfaces) { - own(fs::path(std::format("{}.cppm", mod->path.string()))); - for (const std::unique_ptr& part : mod->partitions) { - own(fs::path(std::format("{}.cppm", part->path.string()))); - } - } - for (const Implementation& impl : c.implementations) { - own(fs::path(std::format("{}.cpp", impl.path.string()))); - } + // The sources as they are listed: which module each one is a unit + // of, only a build reads. + for (const fs::path& source : c.interfaceSources) own(source); + for (const fs::path& source : c.implementationSources) own(source); // cFiles/cuda resolve against cwd at build time (see Build's compile // loops); mirror that here. for (const fs::path& cf : c.cFiles) { @@ -1206,7 +1201,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would. for (const auto& [file, owner] : files) { std::ifstream in(file, std::ios::binary); - if (!in) continue; // config parse already read it; a vanished file fails the build first + if (!in) continue; // a listed file that is not there is the build's to report std::stringstream buffer; buffer << in.rdbuf(); LintContext ctx; diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index 484300a..ab75ead 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -444,18 +444,7 @@ TestBuilder& TestBuilder::Define(std::string n, std::string v) { TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; } TestBuilder& TestBuilder::Args(std::vector a) { Ref().args = std::move(a); return *this; } TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; } -TestBuilder& TestBuilder::Dependencies(std::vector d) { - Ref().config.dependencies = std::move(d); - // AddTest already scanned tests//main.cpp, at which point this test - // had no dependencies, so every `import ;` in it came back - // unresolved. Place them now that the libraries are known — without this - // the test's object carries no staleness edge to the interfaces it consumes - // and survives a layout change to them (issue #27). Build() re-runs the - // same sweep as a backstop; doing it here keeps the Configuration coherent - // for anyone inspecting it before the build. - Ref().config.ResolvePendingImports(); - return *this; -} +TestBuilder& TestBuilder::Dependencies(std::vector d) { Ref().config.dependencies = std::move(d); return *this; } TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; } diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index 5714b3f..0edbd84 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -207,11 +207,13 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { tc.clang = "clang"; tc.llvmAr = "llvm-ar"; tc.llvmReadelf = "llvm-readelf"; + tc.clangScanDeps = "clang-scan-deps"; } else { tc.clangxx = tc.prefix / "bin" / "clang++"; tc.clang = tc.prefix / "bin" / "clang"; tc.llvmAr = tc.prefix / "bin" / "llvm-ar"; tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf"; + tc.clangScanDeps = tc.prefix / "bin" / "clang-scan-deps"; if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) { tc.llvmIncludeDir = tc.prefix / "include"; } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index d33e52a..f73973b 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -69,6 +69,15 @@ export namespace Crafter { // path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from // these directories into files/lib. std::set runPaths; + // The configuration this is the build of: the one whose Build() ran. + // A build pass builds a directory once, so of two configurations + // that would be built into one, as the same project loaded along two + // paths with its args in two orders is, only one is built, and only + // that one has the modules the build read in the sources + // (Configuration::interfaces). What is built on the other finds them + // through this. Null where Build() stopped before it read the + // sources. + const struct Configuration* built = nullptr; }; struct Define { @@ -509,6 +518,26 @@ export namespace Crafter { // sandbox permissions any configuration may declare for the // executables built on it. FlatpakApp flatpak; + // The module interface units (.cppm) and the implementation units + // (.cpp) of the configuration, as GetInterfacesAndImplementations + // lists them: absolute, with their extensions. + std::vector interfaceSources; + std::vector implementationSources; + // What those sources are, as Build() found them the last time it read + // all of them without an error: each module whose primary interface + // unit is among interfaceSources, with its partitions, and a unit for + // each of implementationSources, with what each of them imports. + // Build() takes what a source declares and imports from + // clang-scan-deps, which preprocesses the source with the command it + // is compiled with, so it reads them as the compiler does: one in a + // string literal, in a comment or in a branch that #if leaves out is + // not there. It reads them once the configuration's dependencies and + // external dependencies are built, since the command takes their + // include paths and a source may include their headers. Empty until a + // Build() has read the sources. A pass builds a directory once, so a + // configuration whose directory it built for another keeps what it + // had, and what is built on it finds the modules of that build + // through BuildResult::built. std::vector> interfaces; std::vector implementations; std::vector cFiles; @@ -602,16 +631,14 @@ export namespace Crafter { // 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; + // Adds the units `interfaces` and `implementations` name to + // interfaceSources and implementationSources. Each is named without + // its extension, .cppm for an interface unit and .cpp for an + // implementation unit, and resolved against `path` and the working + // directory as they are at the call. Reads none of them: Build() + // does, with the command the configuration has by then, its defines, + // flags and dependencies set after this call included. void GetInterfacesAndImplementations(std::span interfaces, std::span implementations); - // Retry the `import X;` names GetInterfacesAndImplementations could not - // place, against the dependency DAG as it stands now. Sources are - // scanned when they're declared, but `dependencies` is often assigned - // afterwards (AddTest does exactly this), and an import that resolved to - // nothing leaves no staleness edge — so a dependency's interface could - // change and this Configuration's objects would be silently reused - // against the new layout. Build() calls this before checking mtimes; - // calling it again is harmless. - void ResolvePendingImports(); // Declare a test. Sources default to `tests//main.cpp` resolved // against this Configuration's path; target/march/mtune/sysroot/debug // and cudaArch are inherited from this Configuration so cross-arch diff --git a/interfaces/Crafter.Build-Implementation.cppm b/interfaces/Crafter.Build-Implementation.cppm index f18f0a9..a1f7785 100644 --- a/interfaces/Crafter.Build-Implementation.cppm +++ b/interfaces/Crafter.Build-Implementation.cppm @@ -11,12 +11,11 @@ namespace Crafter { export class ModulePartition; export class Implementation { public: + // What this unit imports, as in ModulePartition: for a unit of a + // module (`module X;`), the module's primary interface among them. std::vector moduleDependencies; std::vector partitionDependencies; std::vector> externalModuleDependencies; - // See ModulePartition::pendingImports — imports this TU declared that - // no reachable Configuration provided when the source was scanned. - std::vector pendingImports; fs::path path; Implementation(fs::path&& path); // Whether `object`, the object Build() keeps for this unit diff --git a/interfaces/Crafter.Build-Interface.cppm b/interfaces/Crafter.Build-Interface.cppm index dcfe960..065c9b3 100644 --- a/interfaces/Crafter.Build-Interface.cppm +++ b/interfaces/Crafter.Build-Interface.cppm @@ -10,20 +10,19 @@ namespace Crafter { export class Module; export class ModulePartition { public: + // What this unit imports, as the Build() that made it read the + // source: modules of its own configuration, partitions of its own + // module, and modules of the configurations it is built on, each of + // those with the BMI that configuration's build writes. An import of + // anything else, `std` or a module from outside the build, has no + // entry. std::vector moduleDependencies; std::vector partitionDependencies; std::vector> externalModuleDependencies; - // Names from `import X;` that matched neither a module in this - // Configuration nor one reachable through its dependencies at the time - // the source was scanned. Retried by ResolvePendingImports (see - // Crafter.Build:Clang) so a dependency wired up after - // GetInterfacesAndImplementations still produces a staleness edge. - // Names that never resolve (`std`, module-mapped externals) stay here. - std::vector pendingImports; - // 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. + // The state of the Build() that made this unit: 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; @@ -58,13 +57,14 @@ namespace Crafter { public: // 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 Schedule() - // can order itself behind a sibling module in the same Configuration - // (issue #26). + // same line in a partition. Recorded as a partition records the + // modules it imports, with the same meanings, so Check() can see + // through them and Schedule() can order itself behind a sibling + // module in the same Configuration (issue #26). The partitions it + // imports need no entry: it is checked and built after all of its + // module's partitions. std::vector moduleDependencies; std::vector> externalModuleDependencies; - std::vector pendingImports; // As in ModulePartition. bool needsRecompiling = false; bool checked = false; diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index 24d98fb..1573d9a 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -164,10 +164,10 @@ namespace Crafter { // derives /share/crafter-build from the running executable's path. export fs::path GetCrafterBuildHome(); // Newest mtime among the prerequisites a compiler recorded in `depFile` - // (clang's `-MD -MF .d`). This is how a build step learns which - // headers its source pulled in: the module scanner only reads `import` - // lines, so an `#include`d file is invisible to it until the compiler - // reports what it actually opened. + // (clang's `-MD -MF .d`), or clang-scan-deps for the scan of + // a C++ source. This is how a build step learns which headers its + // source pulled in: only the tool that preprocessed the source knows + // which files its #includes opened. // // Returns file_time_type::max() when freshness cannot be proven — no // depfile (nothing has compiled this artifact since depfiles were emitted, diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index ff82b4f..2988b6a 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -24,8 +24,8 @@ export namespace Crafter { // interfaces. The builder only mutates compile state, deps, runtime // args, and requires; it deliberately does NOT expose Sources() to // avoid the double-`GetInterfacesAndImplementations` footgun (calling - // it twice would re-parse the same .cppm files into duplicate Module - // entries). + // it twice would list the same .cppm files twice, and the build would + // make a Module entry of each listing). struct TestBuilder { Configuration* parent; std::size_t index; diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 606de15..24cb930 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -7,11 +7,11 @@ namespace fs = std::filesystem; export namespace Crafter { // The compiler crafter-build drives and what sits next to it, resolved - // once per process by GetToolchain(). Every clang++, clang and llvm-ar - // the tool spawns, the libclang the linter dlopens, the std module - // source and the default sysroots come from here, so a toolchain - // installed anywhere other than /usr (the Flatpak carries its own under - // /app) needs no per-call-site knowledge. + // once per process by GetToolchain(). Every clang++, clang, llvm-ar and + // clang-scan-deps the tool spawns, the libclang the linter dlopens, the + // std module source and the default sysroots come from here, so a + // toolchain installed anywhere other than /usr (the Flatpak carries its + // own under /app) needs no per-call-site knowledge. struct Toolchain { // LLVM install prefix. Empty when the tools are bare names on PATH. fs::path prefix; @@ -20,6 +20,9 @@ export namespace Crafter { fs::path llvmAr; // What a packaged program's shared libraries are read with. fs::path llvmReadelf; + // What reads the module a C++ source declares and the modules it + // imports, by preprocessing it with its compile command (Build). + fs::path clangScanDeps; // Where clang-c/Index.h lives when it is not on the default include // path; empty otherwise. fs::path llvmIncludeDir; diff --git a/tests/ConcurrentDependencyReset/main.cpp b/tests/ConcurrentDependencyReset/main.cpp index 5a59330..76eba55 100644 --- a/tests/ConcurrentDependencyReset/main.cpp +++ b/tests/ConcurrentDependencyReset/main.cpp @@ -8,10 +8,12 @@ using namespace Crafter; // Regression for the concurrent dependency-reset deadlock (issue #16). // -// 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 +// Each Module/ModulePartition holds the state of one build (`checked`, +// `scheduled` and the job that precompiles the unit). Build() used to reset +// it so a reused Configuration re-evaluates mtimes, and now makes the units +// anew from what it reads in the sources. Either way that MUST stay scoped +// to the configuration being built. The reset 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 @@ -30,11 +32,11 @@ using namespace Crafter; // 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. +// its dependencies, or made their units anew, would leave the dependency's +// module with `checked` and `scheduled` false and, because the dependency +// never rebuilds, they would stay false. The consumer makes only its own +// units, 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"; @@ -58,11 +60,6 @@ int main() { dep.GetInterfacesAndImplementations(ifaces, impls); } - if (dep.interfaces.size() != 1) { - std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size()); - return 1; - } - { std::unordered_map> depResults; std::mutex depMutex; @@ -71,6 +68,10 @@ int main() { std::println(std::cerr, "dependency build failed: {}", r.result); return 1; } + if (dep.interfaces.size() != 1) { + std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size()); + return 1; + } 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; diff --git a/tests/DependencyLink/main.cpp b/tests/DependencyLink/main.cpp index d2c9461..eedc3e1 100644 --- a/tests/DependencyLink/main.cpp +++ b/tests/DependencyLink/main.cpp @@ -38,6 +38,15 @@ int main() { app.GetInterfacesAndImplementations(ifaces, impls); } + std::unordered_map> depResults; + std::mutex depMutex; + BuildResult r = Build(app, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "build failed: {}", r.result); + return 1; + } + + // What the build read in the sources. if (app.implementations.size() != 1) { std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size()); return 1; @@ -56,14 +65,6 @@ int main() { return 1; } - std::unordered_map> depResults; - std::mutex depMutex; - BuildResult r = Build(app, depResults, depMutex); - if (!r.result.empty()) { - std::println(std::cerr, "build failed: {}", r.result); - return 1; - } - fs::path libArchive = lib->BinDir() / "libcalc.a"; if (!fs::exists(libArchive)) { std::println(std::cerr, "dep archive not produced at {}", libArchive.string()); diff --git a/tests/DuplicateModule/main.cpp b/tests/DuplicateModule/main.cpp index b0bb3f2..6a05d73 100644 --- a/tests/DuplicateModule/main.cpp +++ b/tests/DuplicateModule/main.cpp @@ -8,13 +8,14 @@ using namespace Crafter; // A program can hold one module of each name, so Build() refuses a graph in // which two configurations export the same module: the same project loaded -// along two paths with two arg lists, say. It used to build both and put -// both on the consumer's module path. Clang took the first for every import -// of the module, the ones inside the other build's consumers included, and -// the program linked code compiled against two layouts of one struct: it -// built cleanly, then read garbage or crashed (issue #41). The fixture is -// P -> M and P -> A -> M. With --split, P gives M its args without --wide, -// which changes what M declares, while A passes them on whole. +// along two paths with two arg lists, say. It used to build both and compile +// the consumer with both on its module path. Clang took the first for every +// import of the module, the ones inside the other build's consumers +// included, and the program linked code compiled against two layouts of one +// struct: it built cleanly, then read garbage or crashed (issue #41). The +// fixture is P -> M and P -> A -> M. With --split, P gives M its args +// without --wide, which changes what M declares, while A passes them on +// whole. namespace { std::int32_t Failures = 0; @@ -53,7 +54,9 @@ int main() { const fs::path cwd = fs::current_path(); fs::current_path(scratch / "p"); try { - // Two lists for M: refused before anything is built. + // Two lists for M: refused before P compiles anything of its own. + // The modules of a configuration are known once it is built, so M is + // built twice, and A on one of the two, before P can tell. { std::array args = { "--wide", "--split" }; Configuration cfg = LoadProject("project.cpp", args); @@ -61,7 +64,7 @@ int main() { Check(!built.result.empty(), "a graph with two builds of one module fails to build"); Check(built.result.contains("module M is built twice for P"), std::format("the error names the module and the program (got: {})", built.result)); Check(built.result.contains("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result)); - Check(!fs::exists(scratch / "m" / "bin") && !fs::exists(scratch / "a" / "bin") && !fs::exists(scratch / "p" / "bin"), "nothing was built"); + Check(!fs::exists(ObjectPath(cfg, scratch / "p" / "main.cpp")) && !fs::exists(ExpectedOutput(cfg)), "P compiled and linked nothing"); } // One list along both paths: one M, and the build goes through. diff --git a/tests/ImportCycle/main.cpp b/tests/ImportCycle/main.cpp index 618d8e3..2eecefc 100644 --- a/tests/ImportCycle/main.cpp +++ b/tests/ImportCycle/main.cpp @@ -6,11 +6,11 @@ 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. +// Interface units that import each other are refused before any .cppm or +// .cpp of their configuration is compiled, 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 @@ -28,9 +28,9 @@ namespace { // 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. + // build that gets past the refusal can compile units 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); @@ -49,9 +49,13 @@ namespace { 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())); + // Refused once the build has read what the units import, which is + // before it compiles any of them: no unit has a BMI or an object. + for (const fs::path& interface : interfaces) { + const fs::path bmi = cfg.PcmDir() / std::format("{}.pcm", interface.string()); + const fs::path object = cfg.BuildDir() / std::format("{}.o", interface.string()); + Check(!fs::exists(bmi) && !fs::exists(object), std::format("{}: the refused build compiled {}", dir, interface.string())); + } return built.result; } } @@ -61,9 +65,6 @@ 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" }; diff --git a/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm b/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm index 3240a22..0f75562 100644 --- a/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm +++ b/tests/IncrementalHeaderChange/fixture/lib/Widget.cppm @@ -2,9 +2,9 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; -// The whole point of the fixture: an input to this interface unit that the -// module scanner cannot see. WIDGET_SLOTS comes from a header, so the class -// layout below changes without Widget.cppm being touched. +// The whole point of the fixture: an input to this interface unit that is +// not its own source. WIDGET_SLOTS comes from a header, so the class layout +// below changes without Widget.cppm being touched. #include "widget-layout.h" export module Widget; import std; diff --git a/tests/IncrementalHeaderChange/main.cpp b/tests/IncrementalHeaderChange/main.cpp index ae946ca..97368b8 100644 --- a/tests/IncrementalHeaderChange/main.cpp +++ b/tests/IncrementalHeaderChange/main.cpp @@ -8,7 +8,7 @@ using namespace Crafter; // Editing a header must rebuild everything that #includes it. The staleness // check used to compare an artifact against its own source and its module -// imports only — and the module scanner reads `import` lines, so a header was +// imports only — and the module scanner read `import` lines, so a header was // invisible to it. A build after a header-only edit reported nothing to do and // left objects compiled against the previous contents: the same silent // mixed-layout binary as issue #27, reached through #include instead. diff --git a/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in b/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in index e1616a2..ec86e18 100644 --- a/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in +++ b/tests/IncrementalInterfaceChange/fixture/lib/Widget-grown.cppm.in @@ -3,10 +3,7 @@ // Copied over lib/Widget.cppm mid-test to stand in for the interface edit from // issue #27: one extra data member, every signature and mangled name unchanged. -// Kept as a .cppm.in so the module scanner never treats it as a source of its -// own — and so the text does not have to live in a string literal inside the -// test, where `export module Widget;` would make the test itself look like an -// implementation unit of Widget. +// Kept as a .cppm.in so that no build takes it for a source of its own. export module Widget; import std; diff --git a/tests/IncrementalInterfaceChange/main.cpp b/tests/IncrementalInterfaceChange/main.cpp index 92c2d3d..98fe100 100644 --- a/tests/IncrementalInterfaceChange/main.cpp +++ b/tests/IncrementalInterfaceChange/main.cpp @@ -7,15 +7,17 @@ namespace fs = std::filesystem; using namespace Crafter; // Adding a data member to a class in a module interface must rebuild every -// object compiled against the old layout. The dangerous shape (issue #27) is a +// object compiled against the old layout. The dangerous shape (issue #27) was a // consumer whose sources were scanned *before* its `dependencies` were assigned: // its `import ;` matched nothing, so its object carried no staleness // edge to the interface, and a layout change rebuilt the library, relinked the // consumer, and produced a binary mixing both layouts with no error or warning. // -// `AddTest` is exactly that shape — it scans tests//main.cpp and only then +// `AddTest` is exactly that shape — it lists tests//main.cpp and only then // returns a builder whose .Dependencies() supplies the library — which is why // the original report saw the corruption in test executables specifically. +// A build reads the sources now, once the dependencies are built, so the order +// they were declared in no longer matters; the cases below hold it to that. namespace { std::int32_t Failures = 0; @@ -36,10 +38,7 @@ namespace { return staged; } - // Swap in the variant carrying the extra member. Comes from a file rather - // than a string literal here: the module scanner reads raw source, so an - // `export module Widget;` spelled inside this test would make the test look - // like an implementation unit of Widget. + // Swap in the variant carrying the extra member, kept beside the original. void GrowWidget(const fs::path& staged) { fs::copy_file(staged / "lib" / "Widget-grown.cppm.in", staged / "lib" / "Widget.cppm", fs::copy_options::overwrite_existing); // copy_file carries the source's mtime across, which would leave the @@ -60,9 +59,9 @@ namespace { return lib; } - // Scan first, wire the dependency up afterwards — the ordering that used to - // silently drop the staleness edge. - Configuration MakeConsumerScannedBeforeDependencies(const fs::path& staged, Configuration* lib) { + // Sources first, the dependency wired up afterwards — the ordering that + // used to silently drop the staleness edge. + Configuration MakeConsumerListedBeforeDependencies(const fs::path& staged, Configuration* lib) { Configuration app; app.path = staged; app.name = "widget-app"; @@ -94,45 +93,31 @@ namespace { int main() { { - // The scan leaves the unmatched import recorded rather than forgotten, - // and ResolvePendingImports places it once the library is reachable. + // The build places the consumer's import on the library's module, + // although the library became a dependency after the consumer's + // sources were listed. fs::path staged = StageFixture(); std::unique_ptr lib = MakeLib(staged); - Configuration app; - app.path = staged; - app.name = "widget-app"; - app.outputName = "widget-app"; - app.target = HostTarget(); - app.type = ConfigurationType::Executable; - std::array ifaces = {}; - std::array impls = { "main" }; - app.GetInterfacesAndImplementations(ifaces, impls); - - Check(app.implementations.size() == 1, "consumer has one implementation"); - if (app.implementations.size() == 1) { - const Implementation& impl = app.implementations[0]; - Check(impl.externalModuleDependencies.empty(), "no external dep resolvable before dependencies are assigned"); - Check(std::ranges::find(impl.pendingImports, "Widget") != impl.pendingImports.end(), "unresolved 'import Widget;' is recorded as pending"); - - app.dependencies = { lib.get() }; - app.ResolvePendingImports(); - - Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports adds the external module dep"); - if (impl.externalModuleDependencies.size() == 1) { - Check(impl.externalModuleDependencies[0].first->name == "Widget", "external dep is the Widget module"); - Check(impl.externalModuleDependencies[0].second == lib->PcmDir() / "Widget.pcm", "external dep points at the library's BMI"); + Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get()); + if (BuildOk(app, "consumer with the dependency wired up last")) { + Check(app.implementations.size() == 1, "consumer has one implementation"); + if (app.implementations.size() == 1) { + const Implementation& impl = app.implementations[0]; + Check(impl.externalModuleDependencies.size() == 1, "the import of the library's module is one external module dep"); + if (impl.externalModuleDependencies.size() == 1) { + Check(impl.externalModuleDependencies[0].first->name == "Widget", "external dep is the Widget module"); + Check(impl.externalModuleDependencies[0].second == lib->PcmDir() / "Widget.pcm", "external dep points at the library's BMI"); + } + } + // A second build makes the units anew: the edge is there once. + if (BuildOk(app, "consumer built again")) { + Check(app.implementations.size() == 1 && app.implementations[0].externalModuleDependencies.size() == 1, "a second build has the one edge again"); } - Check(std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "resolved import is no longer pending"); - - // Idempotent: a second sweep must not duplicate the edge (Build - // runs one unconditionally, on top of whatever callers already did). - app.ResolvePendingImports(); - Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent"); } } { - // AddTest is the reported path: it scans the test source, then hands + // AddTest is the reported path: it lists the test source, then hands // back a builder whose .Dependencies() names the library. fs::path staged = StageFixture(); fs::create_directories(staged / "tests" / "Consumer"); @@ -146,28 +131,31 @@ int main() { app.target = HostTarget(); app.type = ConfigurationType::Executable; // AddTest resolves tests//main against the cwd, which for a real - // run is the directory holding project.cpp. Stand in the staged project - // for the declaration so the fixture's test source is the one scanned. + // run is the directory holding project.cpp, and the test's "./" path + // is read against it when the test is built. Stand in the staged + // project for both, so the fixture's test source is the one listed + // and the test builds beside it. fs::path restore = fs::current_path(); fs::current_path(staged); app.AddTest("Consumer").Dependencies({ lib.get() }); - fs::current_path(restore); - Check(app.tests.size() == 1, "one test declared"); - if (app.tests.size() == 1 && app.tests[0].config.implementations.size() == 1) { - const Implementation& impl = app.tests[0].config.implementations[0]; - Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() resolves the test's import of the library module"); - Check(impl.pendingImports.empty() || std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "test's 'import Widget;' is no longer pending"); + if (app.tests.size() == 1 && BuildOk(app.tests[0].config, "test declared with AddTest")) { + Check(app.tests[0].config.implementations.size() == 1, "the test has one implementation"); + if (app.tests[0].config.implementations.size() == 1) { + const Implementation& impl = app.tests[0].config.implementations[0]; + Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() gives the test's import of the library module its edge"); + } } + fs::current_path(restore); } { - // End to end, and deliberately without calling ResolvePendingImports: - // the guarantee under test is that Build() closes the window on its own, - // for consumers that never knew they had to ask. + // End to end: the guarantee under test is that a build of a consumer + // declared in that order recompiles it, for consumers that never knew + // the order mattered. fs::path staged = StageFixture(); std::unique_ptr lib = MakeLib(staged); - Configuration app = MakeConsumerScannedBeforeDependencies(staged, lib.get()); + Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get()); fs::path binary = app.BinDir() / "widget-app"; fs::path consumerObject = ObjectPath(app, staged / "main.cpp"); diff --git a/tests/JobLimit/main.cpp b/tests/JobLimit/main.cpp index a6ce449..00dad75 100644 --- a/tests/JobLimit/main.cpp +++ b/tests/JobLimit/main.cpp @@ -54,13 +54,6 @@ namespace { 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 @@ -83,10 +76,10 @@ namespace { // 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"))); + Write(root / "Limit-Low.cppm", "export module Limit:Low;\nexport int Low() { return 1; }\n"); + Write(root / "Limit-High.cppm", "export module Limit:High;\nimport :Low;\nexport int High() { return Low() + 1; }\n"); + Write(root / "Limit.cppm", "export module Limit;\nexport import :Low;\nexport import :High;\nexport int Top();\n"); + Write(root / "Limit-impl.cpp", "module Limit;\nint Top() { return High() + 1; }\n"); std::string declarations; std::string sum; @@ -101,7 +94,7 @@ namespace { 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)); + Write(root / "main.cpp", std::format("import std;\nimport Limit;\n{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", declarations, sum)); std::array interfaces = { "Limit", "Limit-Low", "Limit-High" }; cfg->GetInterfacesAndImplementations(interfaces, implementations); diff --git a/tests/Lint/main.cpp b/tests/Lint/main.cpp index d5cffc5..8db7f3b 100644 --- a/tests/Lint/main.cpp +++ b/tests/Lint/main.cpp @@ -697,9 +697,8 @@ int main() { // is five of this repo's own interfaces, 677 lines. Blanking the keyword is // byte-length preserving, so the lines reported here must match the file. // - // The source lives in fixture/ExportNamespace.cppm.in rather than inline: - // an `export module` spelled in this file's own text would be picked up by - // the build's module scanner as a real interface of this project. + // The source lives in fixture/ExportNamespace.cppm.in, copied into the + // scratch directory as Demo.cppm. { Scratch s("ast-module"); fs::copy_file(fs::current_path() / "tests" / "Lint" / "fixture" / "ExportNamespace.cppm.in", s.dir / "Demo.cppm", fs::copy_options::overwrite_existing); diff --git a/tests/MingwSysroot/main.cpp b/tests/MingwSysroot/main.cpp index 3964b36..0b5ebcd 100644 --- a/tests/MingwSysroot/main.cpp +++ b/tests/MingwSysroot/main.cpp @@ -83,10 +83,7 @@ int main() { Write(mingw / "include" / "_mingw.h", ""); Write(mingw / "include" / "crafter_probe_error.h", "#error stopped in a mingw-w64 header\n"); Write(mingw / "include" / "c++" / "15.1.0" / "memory", ""); - // Through std::format because the build's import scanner reads string - // literals as code: one holding "module std;" made this file a unit of a - // module std, and the test did not build. - Write(mingw / "include" / "c++" / "15.1.0" / "bits" / "std.cc", std::format("export module {};\n", "std")); + Write(mingw / "include" / "c++" / "15.1.0" / "bits" / "std.cc", "export module std;\n"); Write(mingw / "lib" / "libstdc++.modules.json", R"({"version": 1, "modules": [{"logical-name": "std", "source-path": "../include/c++/15.1.0/bits/std.cc", "is-std-library": true}]})"); { diff --git a/tests/ModuleInterface/main.cpp b/tests/ModuleInterface/main.cpp index baa6e7a..03ea3be 100644 --- a/tests/ModuleInterface/main.cpp +++ b/tests/ModuleInterface/main.cpp @@ -21,8 +21,16 @@ int main() { std::array impls = { "main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); - // Implementation should have picked up the import Greeter; through the - // interface list resolution in GetInterfacesAndImplementations. + std::unordered_map> depResults; + std::mutex depMutex; + BuildResult r = Build(cfg, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "build failed: {}", r.result); + return 1; + } + + // The build read main.cpp's import of Greeter and placed it on the + // module among the configuration's own interfaces. if (cfg.implementations.size() != 1) { std::println(std::cerr, "expected 1 implementation, got {}", cfg.implementations.size()); return 1; @@ -36,14 +44,6 @@ int main() { return 1; } - std::unordered_map> depResults; - std::mutex depMutex; - BuildResult r = Build(cfg, depResults, depMutex); - if (!r.result.empty()) { - std::println(std::cerr, "build failed: {}", r.result); - return 1; - } - fs::path bin = cfg.BinDir() / "greeter-app"; if (!fs::exists(bin)) { std::println(std::cerr, "binary not produced at {}", bin.string()); diff --git a/tests/StaticLib/main.cpp b/tests/StaticLib/main.cpp index 3e0a37b..54e7235 100644 --- a/tests/StaticLib/main.cpp +++ b/tests/StaticLib/main.cpp @@ -7,9 +7,9 @@ namespace fs = std::filesystem; using namespace Crafter; // Build a tiny module-only static library and confirm libgreet.a lands in -// BinDir(). Exercises ConfigurationType::LibraryStatic, interface module -// parsing via GetInterfacesAndImplementations, and the ar/llvm-lib archive -// step in Crafter.Build-Clang.cpp. +// BinDir(). Exercises ConfigurationType::LibraryStatic, the module a build +// reads in a source GetInterfacesAndImplementations lists, and the +// ar/llvm-lib archive step in Crafter.Build-Clang.cpp. int main() { Configuration cfg; cfg.path = fs::current_path() / "tests" / "StaticLib" / "fixture"; @@ -22,6 +22,14 @@ int main() { std::array impls = {}; cfg.GetInterfacesAndImplementations(ifaces, impls); + std::unordered_map> depResults; + std::mutex depMutex; + BuildResult r = Build(cfg, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "build failed: {}", r.result); + return 1; + } + if (cfg.interfaces.size() != 1) { std::println(std::cerr, "expected 1 interface, got {}", cfg.interfaces.size()); return 1; @@ -31,14 +39,6 @@ int main() { return 1; } - std::unordered_map> depResults; - std::mutex depMutex; - BuildResult r = Build(cfg, depResults, depMutex); - if (!r.result.empty()) { - std::println(std::cerr, "build failed: {}", r.result); - return 1; - } - fs::path archive = cfg.BinDir() / "libgreet.a"; if (!fs::exists(archive)) { std::println(std::cerr, "archive not produced at {}", archive.string()); diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index 108ee5a..60a18bf 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -436,6 +436,10 @@ int main() { prefixed.env.emplace("CRAFTER_BUILD_LLVM_DIR", full.string()); const Toolchain withPrefix = ResolveToolchain(prefixed); Check(withPrefix.llvmReadelf == full / "bin" / "llvm-readelf", "llvm-readelf comes from the prefix"); + // So does clang-scan-deps, which reads what a source declares and + // imports. + Check(ResolveToolchain({}).clangScanDeps == "clang-scan-deps", "the PATH fallback names clang-scan-deps bare"); + Check(withPrefix.clangScanDeps == full / "bin" / "clang-scan-deps", "clang-scan-deps comes from the prefix"); Check(withPrefix.LibcxxSearchFlags() == std::format(" -L{}", (full / "lib").string()), std::format("the search flags are -L alone (got '{}')", withPrefix.LibcxxSearchFlags())); } diff --git a/tests/TransitiveInterfaceChange/main.cpp b/tests/TransitiveInterfaceChange/main.cpp index 4c423a6..e326ed3 100644 --- a/tests/TransitiveInterfaceChange/main.cpp +++ b/tests/TransitiveInterfaceChange/main.cpp @@ -45,10 +45,8 @@ namespace { return staged; } - // Swap in the Base variant carrying the extra member. From a file rather - // than a string literal: the module scanner reads raw source, so a module - // declaration spelled inside this test would make the test itself look like - // an implementation unit of Base. + // Swap in the Base variant carrying the extra member, kept beside the + // original. void GrowBase(const fs::path& staged) { fs::copy_file(staged / "base" / "Base-grown.cppm.in", staged / "base" / "Base.cppm", fs::copy_options::overwrite_existing); // copy_file carries the source's mtime across, which would leave the @@ -115,36 +113,24 @@ namespace { int main() { return 0; { - // The scan records a primary interface unit's imports, and the - // pending/resolve machinery reaches them the same way it reaches a - // partition's. + // The build records a primary interface unit's imports, and places + // them on a dependency's module the same way it places a partition's. fs::path staged = StageFixture(); std::unique_ptr base = MakeBaseLib(staged); std::unique_ptr widget = MakeWidgetLib(staged); + widget->dependencies = { base.get() }; - Module* mod = FindModule(*widget, "Widget"); - Check(mod != nullptr, "the primary interface unit registered a module named Widget"); - if (mod != nullptr) { - Check(mod->partitions.empty(), "Widget has no partitions, so nothing else could carry the edge"); - Check(mod->externalModuleDependencies.empty(), "nothing resolvable before dependencies are assigned"); - Check(std::ranges::find(mod->pendingImports, "Base") != mod->pendingImports.end(), "the unresolved import of Base is remembered as pending"); - Check(std::ranges::find(mod->pendingImports, "std") != mod->pendingImports.end(), "std stays pending — it is supplied from outside the graph"); - - widget->dependencies = { base.get() }; - widget->ResolvePendingImports(); - - Check(mod->externalModuleDependencies.size() == 1, "ResolvePendingImports places the external module edge"); - if (mod->externalModuleDependencies.size() == 1) { - Check(mod->externalModuleDependencies[0].first->name == "Base", "the edge names the Base module"); - Check(mod->externalModuleDependencies[0].second == base->PcmDir() / "Base.pcm", "the edge points at the dependency's BMI"); + if (BuildOk(*widget, "widget on base")) { + Module* mod = FindModule(*widget, "Widget"); + Check(mod != nullptr, "the primary interface unit registered a module named Widget"); + if (mod != nullptr) { + Check(mod->partitions.empty(), "Widget has no partitions, so nothing else could carry the edge"); + Check(mod->externalModuleDependencies.size() == 1, "the import of Base is one external module edge; std, supplied from outside the graph, has none"); + if (mod->externalModuleDependencies.size() == 1) { + Check(mod->externalModuleDependencies[0].first->name == "Base", "the edge names the Base module"); + Check(mod->externalModuleDependencies[0].second == base->PcmDir() / "Base.pcm", "the edge points at the dependency's BMI"); + } } - Check(std::ranges::find(mod->pendingImports, "Base") == mod->pendingImports.end(), "the resolved name is no longer pending"); - Check(std::ranges::find(mod->pendingImports, "std") != mod->pendingImports.end(), "std is still pending after the sweep"); - - // Build() runs a sweep unconditionally on top of whatever callers - // already did, so a repeat must not duplicate the edge. - widget->ResolvePendingImports(); - Check(mod->externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent"); } } @@ -164,6 +150,18 @@ int main() { std::array impls = { "widget/Widget", "base/Base", "main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); + // Widget's import of its sibling is also the compile-ordering + // guarantee: Widget's precompile needs Base.pcm on disk. Repeated from + // scratch because the failure was a thread race, and one lucky pass + // proves nothing. + for (std::int32_t attempt = 0; attempt < 4; ++attempt) { + fs::remove_all(cfg.BuildDir()); + fs::remove_all(cfg.BinDir()); + if (!BuildOk(cfg, std::format("sibling pass {}", attempt))) break; + CheckAgrees(cfg.BinDir() / "sibling", std::format("sibling pass {}", attempt)); + } + + // The edge itself, as the last pass read it. Module* widgetMod = FindModule(cfg, "Widget"); Module* baseMod = FindModule(cfg, "Base"); Check(widgetMod != nullptr && baseMod != nullptr, "both sibling modules registered"); @@ -172,16 +170,6 @@ int main() { Check(widgetMod->externalModuleDependencies.empty(), "a sibling in the same Configuration is not an external edge"); Check(baseMod->moduleDependencies.empty(), "Base imports no sibling"); } - - // That edge is also the compile-ordering guarantee: Widget's precompile - // needs Base.pcm on disk. Repeated from scratch because the failure was - // a thread race, and one lucky pass proves nothing. - for (std::int32_t attempt = 0; attempt < 4; ++attempt) { - fs::remove_all(cfg.BuildDir()); - fs::remove_all(cfg.BinDir()); - if (!BuildOk(cfg, std::format("sibling pass {}", attempt))) break; - CheckAgrees(cfg.BinDir() / "sibling", std::format("sibling pass {}", attempt)); - } } {