Files
Build-System/src/Modules/ModuleScanner.cpp
T
2026-11-27 07:50:54 +03:00

467 lines
19 KiB
C++

#include <Void/Build/Modules/ModuleScanner.hpp>
#include <Void/Algorithms/Graph.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <format>
#include <set>
namespace Void::Build::Modules {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(std::string msg) {
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
std::move(msg));
}
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
const auto it = obj.find(k);
return it == obj.end() ? nullptr : &it->second;
}
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
const auto *v = find_key(obj, k);
if (!v) {
return {};
}
const auto *s = std::get_if<std::string>(&v->value);
return s ? *s : std::string{};
}
std::string sanitize_module_filename(std::string_view logical_name) {
std::string out;
out.reserve(logical_name.size());
for (const char c : logical_name) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '-' || c == '.') {
out.push_back(c);
} else {
out += "__";
}
}
return out;
}
std::string std_flag(CxxStandard standard) {
switch (standard) {
case CxxStandard::Cxx17:
return "-std=c++17";
case CxxStandard::Cxx20:
return "-std=c++20";
case CxxStandard::Cxx23:
return "-std=c++23";
case CxxStandard::Cxx26:
return "-std=c++26";
case CxxStandard::Default:
return "-std=c++20";
}
return "-std=c++20";
}
} // namespace
Void::Result::Result<ModuleScanUnit, Void::Result::Error>
parse_p1689_json(std::string_view json_text, const std::filesystem::path &source_file) {
auto parsed = Void::Json::Strict::parse(json_text);
if (!parsed) {
return std::unexpected{make_error(
std::format("failed parsing P1689 module scan JSON for '{}'", source_file.string()))};
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error("P1689 JSON root must be an object")};
}
const auto *ver_v = find_key(*root, "version");
const auto *ver = ver_v ? std::get_if<std::int64_t>(&ver_v->value) : nullptr;
if (!ver || (*ver != 0 && *ver != 1)) {
return std::unexpected{make_error("unsupported P1689 JSON version (expected 0 or 1)")};
}
ModuleScanUnit unit;
unit.source_file = source_file;
if (const auto *rules_v = find_key(*root, "rules")) {
if (const auto *rules = std::get_if<JsonVal::Array>(&rules_v->value);
rules && !rules->empty()) {
if (const auto *r0 = std::get_if<JsonVal::Object>(&rules->front().value)) {
if (const auto *prov_v = find_key(*r0, "provides")) {
if (const auto *parr = std::get_if<JsonVal::Array>(&prov_v->value)) {
for (const auto &pv : *parr) {
if (const auto *po = std::get_if<JsonVal::Object>(&pv.value)) {
const auto name = get_str(*po, "logical-name");
if (!name.empty()) {
unit.provides.push_back(name);
}
if (const auto *is_iface = find_key(*po, "is-interface")) {
if (const auto *b = std::get_if<bool>(&is_iface->value);
b && *b) {
unit.is_interface = true;
}
}
}
}
}
}
if (const auto *req_v = find_key(*r0, "requires")) {
if (const auto *rarr = std::get_if<JsonVal::Array>(&req_v->value)) {
for (const auto &rv : *rarr) {
if (const auto *ro = std::get_if<JsonVal::Object>(&rv.value)) {
const auto name = get_str(*ro, "logical-name");
if (!name.empty()) {
unit.required_modules.push_back(name);
}
}
}
}
}
}
}
}
return unit;
}
Void::Result::Result<ModuleScanUnit, Void::Result::Error>
scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain,
const std::filesystem::path &source_file,
const std::filesystem::path &scratch_dir,
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
const std::vector<std::string> &defines,
const std::vector<std::string> &compile_options, CxxStandard standard) {
if (!toolchain.supports_p1689_scan) {
return std::unexpected{make_error(
std::format("toolchain '{}' does not support P1689 module dependency scanning",
toolchain.cxx_compiler.string()))};
}
std::error_code ec;
std::filesystem::create_directories(scratch_dir, ec);
const std::string tag = Util::sha256_hex(source_file.string()).substr(0, 12);
if (toolchain.family == CompilerFamily::Gcc) {
const auto ddi_path = scratch_dir / (tag + ".ddi");
std::filesystem::remove(ddi_path, ec);
Platform::ProcessRequest req;
req.executable = toolchain.cxx_compiler;
req.arguments = {std_flag(standard),
"-fmodules",
"-E",
"-M",
"-x",
"c++",
"-fdeps-format=p1689r5",
"-fdeps-file=" + ddi_path.string(),
"-fdeps-target=" + (tag + ".o"),
"-o",
"/dev/null"};
for (const auto &[inc, is_sys] : include_dirs) {
req.arguments.push_back(is_sys ? "-isystem" : "-I");
req.arguments.push_back(inc.string());
}
for (const auto &def : defines) {
req.arguments.push_back("-D" + def);
}
for (const auto &opt : compile_options) {
req.arguments.push_back(opt);
}
req.arguments.push_back(source_file.string());
req.timeout = std::chrono::seconds{30};
auto proc = Platform::run_supervised(req);
if (!proc || !proc->succeeded()) {
return std::unexpected{make_error(
std::format("GCC P1689 module scan failed for '{}':\n{}", source_file.string(),
proc ? proc->stderr_data : proc.error().message()))};
}
auto ddi_text = Void::FileSystem::read_file(ddi_path);
if (!ddi_text) {
return std::unexpected{make_error("GCC P1689 scan did not produce .ddi file")};
}
return parse_p1689_json(*ddi_text, source_file);
}
// Clang: use clang-scan-deps --format=p1689 -- clang++ ...
if (!toolchain.module_scanner) {
return std::unexpected{make_error("Clang module scanning requires clang-scan-deps")};
}
Platform::ProcessRequest req;
req.executable = *toolchain.module_scanner;
req.arguments = {"--format=p1689",
"--",
toolchain.cxx_compiler.string(),
std_flag(standard),
"-x",
"c++",
"-c",
source_file.string(),
"-o",
(scratch_dir / (tag + ".o")).string()};
for (const auto &[inc, is_sys] : include_dirs) {
req.arguments.push_back(is_sys ? "-isystem" : "-I");
req.arguments.push_back(inc.string());
}
for (const auto &sys_inc : toolchain.default_include_dirs) {
req.arguments.push_back("-isystem");
req.arguments.push_back(sys_inc);
}
for (const auto &def : defines) {
req.arguments.push_back("-D" + def);
}
for (const auto &opt : compile_options) {
req.arguments.push_back(opt);
}
req.timeout = std::chrono::seconds{30};
auto proc = Platform::run_supervised(req);
if (!proc || !proc->succeeded()) {
return std::unexpected{make_error(
std::format("clang-scan-deps P1689 scan failed for '{}':\n{}", source_file.string(),
proc ? proc->stderr_data : proc.error().message()))};
}
return parse_p1689_json(proc->stdout_data, source_file);
}
Void::Result::Result<CollatedModulePlan, Void::Result::Error> collate_modules(
const std::vector<ModuleScanUnit> &units, const std::filesystem::path &bmi_root,
const std::string &context_isolation_key, std::string_view bmi_extension,
const std::map<std::string, std::filesystem::path, std::less<>> &external_module_bmis) {
// 1. Index module providers and reject duplicates immediately.
std::map<std::string, std::size_t, std::less<>> provider_by_name;
for (std::size_t i = 0; i < units.size(); ++i) {
for (const auto &mod : units[i].provides) {
if (external_module_bmis.contains(mod)) {
return std::unexpected{make_error(std::format(
"duplicate module provider for '{}': defined in '{}' and imported dependency",
mod, units[i].source_file.string()))};
}
const auto [it, inserted] = provider_by_name.emplace(mod, i);
if (!inserted) {
return std::unexpected{make_error(std::format(
"duplicate module provider for '{}': defined in both '{}' and '{}'", mod,
units[it->second].source_file.string(), units[i].source_file.string()))};
}
}
}
// 2. Validate every required module has a provider and build directed dependency graph
// (edge dep -> importer so providers precede importers in topological order).
std::vector<std::vector<std::size_t>> adj(units.size());
for (std::size_t i = 0; i < units.size(); ++i) {
for (const auto &req_mod : units[i].required_modules) {
const auto it = provider_by_name.find(req_mod);
if (it == provider_by_name.end()) {
if (external_module_bmis.contains(req_mod)) {
continue;
}
return std::unexpected{
make_error(std::format("missing module provider for '{}' imported by '{}'",
req_mod, units[i].source_file.string()))};
}
const std::size_t dep = it->second;
if (dep == i) {
return std::unexpected{
make_error(std::format("module '{}' cannot import itself", req_mod))};
}
if (!std::ranges::contains(adj[dep], i)) {
adj[dep].push_back(i);
}
}
}
// 3. Topological sort via Void::Algorithms::topological_order with cycle witness diagnostics.
const Void::Algorithms::AdjacencyView view{adj};
auto topo = Void::Algorithms::topological_order(view);
if (!topo) {
std::string chain;
const auto &cycle = topo.error().cycle;
for (auto it = cycle.rbegin(); it != cycle.rend(); ++it) {
if (!chain.empty()) {
chain += " -> ";
}
const auto idx = *it;
chain += units[idx].provides.empty() ? units[idx].source_file.filename().string()
: units[idx].provides.front();
}
return std::unexpected{make_error(
chain.empty() ? std::format("module import cycle detected: {}", topo.error().message)
: std::format("module import cycle detected: {}", chain))};
}
// 4. Assign isolated per-profile/compiler BMI paths and emit GCC module-mapper files.
const std::string ctx_short = Util::sha256_hex(context_isolation_key).substr(0, 12);
const auto isolated_bmi_dir = bmi_root / ctx_short;
std::error_code ec;
std::filesystem::create_directories(isolated_bmi_dir, ec);
CollatedModulePlan plan;
for (const std::size_t idx : topo->order) {
const auto &u = units[idx];
CollatedModuleNode node;
node.source_file = u.source_file;
node.provides = u.provides;
node.required_modules = u.required_modules;
if (!u.provides.empty()) {
const std::string fname =
sanitize_module_filename(u.provides.front()) + std::string{bmi_extension};
node.bmi_output_path = isolated_bmi_dir / fname;
for (const auto &mod : u.provides) {
plan.module_to_bmi[mod] = node.bmi_output_path;
}
}
// Build GCC module-mapper file mapping all required + provided (+ transitive external)
// modules.
std::string mapper;
std::set<std::string, std::less<>> mapped_names;
for (const auto &mod : u.provides) {
mapped_names.insert(mod);
mapper += mod + " " + node.bmi_output_path.string() + "\n";
}
bool uses_external = false;
for (const auto &req_mod : u.required_modules) {
std::filesystem::path bmi;
if (const auto lit = plan.module_to_bmi.find(req_mod);
lit != plan.module_to_bmi.end()) {
bmi = lit->second;
} else if (const auto eit = external_module_bmis.find(req_mod);
eit != external_module_bmis.end()) {
bmi = eit->second;
uses_external = true;
}
if (!bmi.empty()) {
node.imported_bmis.emplace_back(req_mod, bmi);
if (mapped_names.insert(req_mod).second) {
mapper += req_mod + " " + bmi.string() + "\n";
}
}
}
if (uses_external || !u.provides.empty()) {
for (const auto &[mname, bmi] : external_module_bmis) {
if (mapped_names.insert(mname).second) {
mapper += mname + " " + bmi.string() + "\n";
}
}
}
if (!mapper.empty()) {
const std::string mtag = Util::sha256_hex(u.source_file.string()).substr(0, 12);
node.module_mapper_path = isolated_bmi_dir / (mtag + ".modmap");
auto wrote = Platform::atomic_write_file(node.module_mapper_path, mapper, false);
if (!wrote) {
return std::unexpected{wrote.error()};
}
}
plan.ordered_units.push_back(std::move(node));
}
return plan;
}
Void::Result::Result<Toolchain::LoweredCommand, Void::Result::Error>
lower_header_unit_command(const Toolchain::ToolchainCapabilities &toolchain,
const std::filesystem::path &header_path,
const std::filesystem::path &bmi_output,
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
const std::vector<std::string> &defines,
const std::vector<std::string> &compile_options, CxxStandard standard) {
Toolchain::LoweredCommand cmd;
cmd.executable = toolchain.cxx_compiler;
cmd.arguments.push_back(std_flag(standard));
if (toolchain.family == CompilerFamily::Gcc) {
const auto mapper_path = std::filesystem::path{bmi_output.string() + ".modmap"};
const std::string mapper_content = header_path.string() + " " + bmi_output.string() + "\n";
if (auto w = Platform::atomic_write_file(mapper_path, mapper_content, false); !w) {
return std::unexpected{w.error()};
}
cmd.arguments.push_back("-fmodules");
cmd.arguments.push_back("-fmodule-header=user");
cmd.arguments.push_back("-fmodule-mapper=" + mapper_path.string());
cmd.arguments.push_back("-x");
cmd.arguments.push_back("c++-user-header");
cmd.arguments.push_back("-c");
} else {
cmd.arguments.push_back("-x");
cmd.arguments.push_back("c++-user-header");
cmd.arguments.push_back("--precompile");
}
for (const auto &[inc, is_sys] : include_dirs) {
cmd.arguments.push_back(is_sys ? "-isystem" : "-I");
cmd.arguments.push_back(inc.string());
}
for (const auto &def : defines) {
cmd.arguments.push_back("-D" + def);
}
for (const auto &opt : compile_options) {
cmd.arguments.push_back(opt);
}
cmd.arguments.push_back(header_path.string());
if (toolchain.family == CompilerFamily::Clang) {
cmd.arguments.push_back("-o");
cmd.arguments.push_back(bmi_output.string());
}
cmd.environment["SOURCE_DATE_EPOCH"] = "0";
cmd.environment["TZ"] = "UTC";
cmd.environment["LC_ALL"] = "C";
return cmd;
}
Void::Result::Result<UnityBatchResult, Void::Result::Error>
generate_unity_batches(const std::string &target_name,
const std::vector<std::filesystem::path> &sources,
const std::vector<std::filesystem::path> &excluded_sources,
std::size_t batch_size, const std::filesystem::path &unity_dir) {
if (batch_size == 0) {
return std::unexpected{make_error("unity batch size must be positive")};
}
std::set<std::filesystem::path> excluded;
for (const auto &ex : excluded_sources) {
excluded.insert(ex.lexically_normal());
}
std::vector<std::filesystem::path> batchable;
UnityBatchResult result;
for (const auto &src : sources) {
const auto norm = src.lexically_normal();
const auto ext = norm.extension().string();
// Exclude C sources, module interface/partition extensions and explicitly excluded files
// from unity!
if (excluded.contains(norm) || ext == ".c" || ext == ".cppm" || ext == ".ixx" ||
ext == ".ccm") {
result.standalone_files.push_back(norm);
} else {
batchable.push_back(norm);
}
}
std::error_code ec;
std::filesystem::create_directories(unity_dir, ec);
std::size_t batch_idx = 0;
for (std::size_t i = 0; i < batchable.size(); i += batch_size) {
std::string content = "// Auto-generated deterministic unity batch by VoidBuildSystem\n";
const std::size_t end = std::min(batchable.size(), i + batch_size);
for (std::size_t j = i; j < end; ++j) {
content += "#include " + Util::json_quote(batchable[j].string()) + "\n";
}
const auto batch_file =
unity_dir / std::format("{}_unity_{}.cpp", target_name, batch_idx++);
auto wrote = Platform::atomic_write_file(batch_file, content, false);
if (!wrote) {
return std::unexpected{wrote.error()};
}
result.generated_unity_files.push_back(batch_file);
}
return result;
}
} // namespace Void::Build::Modules