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:
parent
a99647ecff
commit
3c8f4ddb54
28 changed files with 851 additions and 521 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in a new issue