Crafter.Build/tests/ConcurrentDependencyReset/main.cpp
Jorijn van der Graaf 3c8f4ddb54
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
2026-11-27 09:25:53 +01:00

132 lines
6 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// Regression for the concurrent dependency-reset deadlock (issue #16).
//
// 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
// parent's recursive reset could clear a dependency's module `compiled` flag
// *after* that dependency's module-compile thread had set it true and exited,
// but before an intra-config waiter (its impl / a dependent partition) ran
// `compiled.wait(false)`. The waiter then blocked forever on a flag nothing
// re-signalled: the build froze mid-compile, idle, with no compiler process
// alive.
//
// Units are jobs now and wait on no flag, but the state is still the building
// configuration's alone: cleared from outside between two Schedule() calls of
// its own build, a unit is scheduled twice and compiled twice at once.
//
// This test pins the invariant deterministically, without depending on thread
// timing: build a static-lib dependency fully (its module ends up 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, 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";
// Cold output: a stale archive/PCM from a previous run would let the
// dependency build short-circuit and skip the module compile we rely on.
std::error_code ec;
fs::remove_all(fixtureRoot / "deplib" / "build", ec);
fs::remove_all(fixtureRoot / "deplib" / "bin", ec);
fs::remove_all(fixtureRoot / "app" / "build", ec);
fs::remove_all(fixtureRoot / "app" / "bin", ec);
Configuration dep;
dep.path = fixtureRoot / "deplib";
dep.name = "depmod";
dep.outputName = "depmod";
dep.target = HostTarget();
dep.type = ConfigurationType::LibraryStatic;
{
std::array<fs::path, 1> ifaces = { "DepMod" };
std::array<fs::path, 1> impls = { "DepMod-impl" };
dep.GetInterfacesAndImplementations(ifaces, impls);
}
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(dep, depResults, depMutex);
if (!r.result.empty()) {
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;
}
// Seed a consumer-facing cache so the consumer reuses this build instead
// of rebuilding the dependency — mirrors how a shared dep is built once
// and consumed by multiple parents through depResults.
std::promise<BuildResult> promise;
promise.set_value(std::move(r));
std::shared_future<BuildResult> ready = promise.get_future().share();
std::unordered_map<fs::path, std::shared_future<BuildResult>> consumerDeps;
consumerDeps.emplace(dep.PcmDir(), ready);
Configuration app;
app.path = fixtureRoot / "app";
app.name = "resetapp";
app.outputName = "resetapp";
app.target = HostTarget();
app.type = ConfigurationType::Executable;
app.dependencies = { &dep };
{
std::array<fs::path, 0> appIfaces = {};
std::array<fs::path, 1> appImpls = { "main" };
app.GetInterfacesAndImplementations(appIfaces, appImpls);
}
BuildResult ar = Build(app, consumerDeps, depMutex);
if (!ar.result.empty()) {
std::println(std::cerr, "consumer build failed: {}", ar.result);
return 1;
}
// The core regression assertion: building the consumer must not have
// reset the (cached, never-rebuilt) dependency's module state.
if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module state " "(issue #16 regression): done while that dependency is building, " "this compiles its units twice at once");
return 1;
}
fs::path bin = app.BinDir() / "resetapp";
if (!fs::exists(bin)) {
std::println(std::cerr, "consumer binary not produced at {}", bin.string());
return 1;
}
auto run = RunCommandWithTimeout(bin.string(), std::chrono::seconds(10));
if (run.exitCode != 0 || run.timedOut || run.crashed) {
std::println(std::cerr, "consumer exe did not exit cleanly: exit={} output={}", run.exitCode, run.output);
return 1;
}
if (run.output != "42") {
std::println(std::cerr, "expected '42', got '{}'", run.output);
return 1;
}
}
return 0;
}