fix(build): read what a source declares and imports with clang-scan-deps

GetInterfacesAndImplementations found the module declarations and the
imports of a configuration's sources by searching their text with
regular expressions, after deleting the comments that fit on one line.
The expressions skipped neither string literals nor comments that span
lines, knew nothing of the preprocessor, and wanted one space after
`import` and none before its semicolon (#45). An implementation source
that held "export module std;" in a string literal was taken for a unit
of a module std, and listing it threw "Module std not found not found".
An import in a comment that spans lines or under #if 0 was followed.
`import  X;` and `import X ;` were missed, so their unit had no edge to
the module it imports and could be compiled before that module's BMI was
written.

What a .cppm or .cpp declares and imports now comes from clang-scan-deps
-format=p1689, which preprocesses the source with the configuration's
C++ compile command, the one Build() compiles every unit of it with:
strings, comments, spacing, macros and #if come out as they do for the
compiler. GetInterfacesAndImplementations only lists the sources, in the
new interfaceSources and implementationSources. Build() reads them
(ReadSources) once the configuration's dependencies and external
dependencies are built: the command takes their include paths, and a
source may include headers of an external dependency, which are not
there before it is fetched. From what it read, Build() makes the
configuration's modules and units, its `interfaces` and
`implementations`, and places each import on a module of the
configuration or of what it is built on, whose own Build() has read its
sources by then. It makes those of its own configuration alone, as the
reset of the units' state did before it.

A build pass builds a directory once, for whichever configuration of it
asks first, and the loader can make two configurations of one directory:
one project loaded along two paths with its args in two orders, which it
keeps apart and VariantId, sorting the args, does not. Only the one that
was built has the modules that build read, so the result of a build now
names the configuration it ran on (BuildResult::built), and a
dependency's modules are looked up through the pass's record of its
directory. 6.4.1 had every configuration's modules from the listing and
took such a graph for one with two builds of a module, which it refused;
it is now built, once, and the units of both sides have their edges.

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 of the command it
was taken with and of what clang-scan-deps wrote, with the dependency
file clang-scan-deps wrote beside it, which lists the source and every
file it included. A build scans a source again unless its scan is newer
than every file that dependency file lists, was taken with the same
command and can be read, so a build with nothing changed runs no
clang-scan-deps. Both files are written beside their places and renamed
into them, as the archive and the list of objects are, for another
crafter-build that may be building the same clone.

A configuration's modules are known only once its build has read its
sources, so the refusals of a module that two configurations of the
graph build (DuplicateModuleError, #41) and of interface units that
import each other (ImportCycleError) now come there: once the
dependencies are built, before any .cppm or .cpp of the configuration is
compiled. They came before the configuration made a directory or built a
dependency. The contributor guide names clang-scan-deps among the
prerequisites and among what :Toolchain resolves, has a test look at the
modules of a configuration only after building it, and has the gotcha
for the new order.

ResolvePendingImports and the pendingImports of the unit classes go.
They placed the imports that a scan at listing time could not, once the
dependencies were wired up, and with the imports placed when the
dependencies are built there is nothing pending. The tests that looked
at a configuration's modules and units before building now look after it
(DependencyLink, ModuleInterface, StaticLib, ConcurrentDependencyReset
and the disabled TransitiveInterfaceChange), IncrementalInterfaceChange
checks the edge that the build of a consumer gives it when its
dependency was assigned after its sources were listed, and ImportCycle
and DuplicateModule check that the refused configuration compiled
nothing of its own. The workarounds for the old scanner are not needed:
MingwSysroot writes its stand-in std module as a plain literal again,
JobLimit writes the declarations of the sources it generates as plain
literals, and Lint's comment on its fixture file no longer gives the
scanner as the reason for it.

The messages of the regex code stay where they still apply. The one for
a source that declares a unit of a module the configuration does not
have loses its doubled "not found", and applies to an implementation
source that declares one, such as an implementation partition
(`module X:P;`). An implementation unit written `module X;` declares no
unit for clang-scan-deps but imports X, and an import needs no module of
the configuration: the compile reports a module no one builds. A .cppm
that declares an implementation partition is built as a partition of its
module, where it was refused as declaring no module.

The Toolchain gains clangScanDeps, resolved as llvm-ar is: in the bin/
of the LLVM prefix, else by name on PATH. The Flatpak has
/app/bin/clang-scan-deps.

Fixes #45
This commit is contained in:
Jorijn van der Graaf 2026-11-27 09:25:53 +01:00
commit 3c8f4ddb54
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
28 changed files with 851 additions and 521 deletions

View file

@ -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/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"` 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/<app-id>` 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 <hardware threads>` 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 (`<build>/.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.

View file

@ -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<Module*>& localDeps, std::vector<std::pair<Module*, fs::path>>& externalDeps) {
for(const std::unique_ptr<Module>& 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<Json> 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<Json> 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<std::uint8_t>(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<std::uint32_t>(c - '0');
} else if (c >= 'a' && c <= 'f') {
digit = static_cast<std::uint32_t>(c - 'a' + 10);
} else if (c >= 'A' && c <= 'F') {
digit = static_cast<std::uint32_t>(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<char>(code));
} else if (code < 0x800) {
out.push_back(static_cast<char>(0xC0 | (code >> 6)));
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
} else if (code < 0x10000) {
out.push_back(static_cast<char>(0xE0 | (code >> 12)));
out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
} else {
out.push_back(static_cast<char>(0xF0 | (code >> 18)));
out.push_back(static_cast<char>(0x80 | ((code >> 12) & 0x3F)));
out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
}
}
std::unordered_set<Configuration*> seen;
std::function<bool(Configuration*)> walk = [&](Configuration* depCfg) -> bool {
if (!seen.insert(depCfg).second) return false;
for(const std::unique_ptr<Module>& 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<std::string> 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<ScannedUnit> 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<std::string>& 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<std::string> 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<std::string> 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<ScannedUnit> 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<std::string> text = ReadWholeFile(scan);
if (!text) return std::nullopt;
const std::optional<Json> 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<std::string_view, std::string_view> 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<const std::unique_ptr<Module>> modules, std::string_view name) {
for (const std::unique_ptr<Module>& 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<const Configuration&(const Configuration&)>;
// 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<const std::unique_ptr<Module>> local, std::span<Configuration* const> dependencies, const BuiltConfiguration& builtIn, std::string_view name, std::vector<Module*>& localDeps, std::vector<std::pair<Module*, fs::path>>& externalDeps) {
if (Module* own = FindModule(local, name)) {
if (!std::ranges::contains(localDeps, own)) localDeps.push_back(own);
return;
}
std::unordered_set<const Configuration*> seen;
std::function<bool(const Configuration&)> 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<Module*, fs::path>::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<std::string>& pending, std::vector<Module*>& localDeps, std::vector<std::pair<Module*, fs::path>>& 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<std::unique_ptr<Module>> interfaces;
std::vector<Implementation> implementations;
};
for(const std::unique_ptr<Module>& interface : interfaces) {
sweep(interface->pendingImports, interface->moduleDependencies, interface->externalModuleDependencies);
for(const std::unique_ptr<ModulePartition>& 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<const ScannedUnit> interfaceScans, std::span<const ScannedUnit> 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<Module*> moduleOf(interfaceScans.size(), nullptr);
std::vector<ModulePartition*> 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<Module>(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<ModulePartition>(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<ModulePartition>& 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<fs::path> interfaces, std::span<fs::path> implementations) {
auto resolveImport = [this](const std::string& importName, std::vector<Module*>& localDeps, std::vector<std::pair<Module*, fs::path>>& externalDeps, std::vector<std::string>& pending) {
if (!ResolveImportName(*this, importName, localDeps, externalDeps)) {
pending.push_back(importName);
}
};
std::vector<std::tuple<fs::path, std::string, ModulePartition*, Module*>> tempModulePaths = std::vector<std::tuple<fs::path, std::string, ModulePartition*, Module*>>(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<fs::path, std::string, ModulePartition*, Module*>& 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<Module>(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<Module>& 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<ModulePartition> partition = std::make_unique<ModulePartition>(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<fs::path, std::string, ModulePartition*, Module*>& 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<ModulePartition>& 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<Module>& 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<ModulePartition>& 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<std::string, Owner> owners;
std::unordered_set<const Configuration*> visited;
std::string error;
std::function<void(const Configuration&, const std::string&)> walk = [&](const Configuration& c, const std::string& chain) {
std::function<void(const Configuration&, const std::string&)> 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<Module>& 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<std::string> written = ReadWholeFile(description);
fs::remove(description, ec);
if (!failed.empty()) {
fs::remove(depfile, ec);
return failed;
}
const std::optional<Json> document = written ? JsonReader(*written).Read() : std::nullopt;
std::optional<ScannedUnit> 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<fs::path> sources = config.interfaceSources;
sources.insert(sources.end(), config.implementationSources.begin(), config.implementationSources.end());
std::vector<ScannedUnit> 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<ScannedUnit> 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<const ScannedUnit> 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<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex) {
@ -883,63 +1230,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
if (const Toolchain& tc = GetToolchain(); !tc.error.empty()) {
return {tc.error, false, {}};
}
// Before any directory is made or dependency built, so a refused graph
// leaves nothing behind.
if (std::string duplicate = DuplicateModuleError(config); !duplicate.empty()) {
return {std::move(duplicate), false, {}};
}
// Reset per-build cached state on every Module/ModulePartition so that
// successive Build() calls on the same Configuration re-evaluate mtimes
// (incremental-rebuild test scenarios).
//
// Reset ONLY this configuration's own modules — never recurse into
// dependencies. Configuration objects are shared across the dependency DAG
// (diamond deps point at the same Configuration*), and every config in the
// tree gets its own Build() call: the per-PcmDir builder registered in
// depResults resets its own state here, at the top of its own Build(),
// sequenced before that config's units are checked and scheduled.
// Recursing into dependencies from here would clear a shared dependency's
// state from a parent/sibling thread *while that dependency's own Build()
// is using it*: a unit whose `scheduled` is cleared between two of that
// build's Schedule() calls is scheduled a second time, and two compilers
// write one BMI. When every unit had a thread of its own that waited on a
// `compiled` flag of each unit it imports, the reset cleared that flag
// under a waiter, which then blocked forever on a flag nothing
// re-signalled: the build froze mid-compile, idle, with no compiler
// process alive (issue #16). Cross-config module state is consulted only via
// PCM file mtimes and the depResults futures, never via this state, so the
// narrower reset is correct.
for (auto& iface : config.interfaces) {
iface->checked = 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/<name>/main.cpp and
// only then hands back a builder whose .Dependencies() supplies the library.
// Any `import <DepModule>;` 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<fs::path, s
fs::path buildDir = config.BuildDir();
// Where the object of each .cpp, .c and .cu of this configuration goes,
// and what its compile is called (ObjectPath).
// what its compile is called (ObjectPath), and where the scan of each
// .cppm and .cpp is kept.
const SourceLayout layout(config.path, buildDir);
// Everything this configuration produces lands here: a library's archive
// and module PCMs, an executable and the files it reads at run time.
@ -1482,6 +1774,56 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
if (ext.latestArtifact > 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<BuildResult> 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

View file

@ -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;
}

View file

@ -185,10 +185,10 @@ namespace Crafter {
if (scheduled) return precompileJob;
std::vector<JobGroup::Job> 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<ModulePartition>& partition : partitions) {
if (const std::optional<JobGroup::Job> job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}

View file

@ -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<Module>& mod : c.interfaces) {
own(fs::path(std::format("{}.cppm", mod->path.string())));
for (const std::unique_ptr<ModulePartition>& 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;

View file

@ -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<std::string> 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<Configuration*> d) {
Ref().config.dependencies = std::move(d);
// AddTest already scanned tests/<name>/main.cpp, at which point this test
// had no dependencies, so every `import <DepModule>;` 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<Configuration*> 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; }

View file

@ -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";
}

View file

@ -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<std::string> 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<fs::path> interfaceSources;
std::vector<fs::path> 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<std::unique_ptr<Module>> interfaces;
std::vector<Implementation> implementations;
std::vector<fs::path> 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<fs::path> interfaces, std::span<fs::path> 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/<name>/main.cpp` resolved
// against this Configuration's path; target/march/mtune/sysroot/debug
// and cudaArch are inherited from this Configuration so cross-arch

View file

@ -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<Module*> moduleDependencies;
std::vector<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
// See ModulePartition::pendingImports — imports this TU declared that
// no reachable Configuration provided when the source was scanned.
std::vector<std::string> pendingImports;
fs::path path;
Implementation(fs::path&& path);
// Whether `object`, the object Build() keeps for this unit

View file

@ -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<Module*> moduleDependencies;
std::vector<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> 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<std::string> 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<Module*> moduleDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
std::vector<std::string> pendingImports;
// As in ModulePartition.
bool needsRecompiling = false;
bool checked = false;

View file

@ -164,10 +164,10 @@ namespace Crafter {
// derives <prefix>/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 <artifact>.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 <artifact>.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,

View file

@ -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;

View file

@ -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;

View file

@ -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<fs::path, std::shared_future<BuildResult>> 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;

View file

@ -38,6 +38,15 @@ int main() {
app.GetInterfacesAndImplementations(ifaces, impls);
}
std::unordered_map<fs::path, std::shared_future<BuildResult>> 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<fs::path, std::shared_future<BuildResult>> 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());

View file

@ -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<std::string_view, 2> 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.

View file

@ -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<fs::path> 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<fs::path, std::shared_future<BuildResult>> 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<fs::path, 3> 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<fs::path, 2> interfaces = { "Own", "Own-Part" };

View file

@ -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;

View file

@ -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.

View file

@ -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;

View file

@ -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 <DepModule>;` 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/<name>/main.cpp and only then
// `AddTest` is exactly that shape — it lists tests/<name>/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<Configuration> 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<fs::path, 0> ifaces = {};
std::array<fs::path, 1> 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/<name>/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<Configuration> 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");

View file

@ -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<fs::path, 3> interfaces = { "Limit", "Limit-Low", "Limit-High" };
cfg->GetInterfacesAndImplementations(interfaces, implementations);

View file

@ -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);

View file

@ -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}]})");
{

View file

@ -21,8 +21,16 @@ int main() {
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
// Implementation should have picked up the import Greeter; through the
// interface list resolution in GetInterfacesAndImplementations.
std::unordered_map<fs::path, std::shared_future<BuildResult>> 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<fs::path, std::shared_future<BuildResult>> 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());

View file

@ -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<fs::path, 0> impls = {};
cfg.GetInterfacesAndImplementations(ifaces, impls);
std::unordered_map<fs::path, std::shared_future<BuildResult>> 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<fs::path, std::shared_future<BuildResult>> 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());

View file

@ -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()));
}

View file

@ -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<Configuration> base = MakeBaseLib(staged);
std::unique_ptr<Configuration> 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<fs::path, 3> 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));
}
}
{