feat: add Plan 20 Slice 1 CMake native translation, self-test smoke target, VL-009 VOID_TEST check, and warm-cache hardening
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 5s

This commit is contained in:
faumaray committed 2026-11-27 05:38:18 +03:00
1 parent 363fb8200e
commit d3d2666965
19 files changed
+1466 -65

No files matched your search

+856
View File
@@ -0,0 +1,856 @@
#include <Void/Build/Provider/Translator.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Stopwatch.hpp>
#include <algorithm>
#include <format>
#include <set>
#include <type_traits>
namespace Void::Build::Provider {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, 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{};
}
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
const auto *v = find_key(obj, k);
if (!v) {
return def;
}
const auto *b = std::get_if<bool>(&v->value);
return b ? *b : def;
}
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &k) {
const auto *v = find_key(obj, k);
if (!v) {
return std::nullopt;
}
const auto *i = std::get_if<std::int64_t>(&v->value);
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
}
std::optional<JsonVal> parse_json_file(const std::filesystem::path &path) {
auto text = Void::FileSystem::read_file(path);
if (!text) {
return std::nullopt;
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return std::nullopt;
}
return std::move(*parsed);
}
std::string cmake_option_value(const OptionValue &v) {
return std::visit(
[](const auto &inner) -> std::string {
using T = std::remove_cvref_t<decltype(inner)>;
if constexpr (std::same_as<T, std::string>) {
return inner;
} else if constexpr (std::same_as<T, bool>) {
return inner ? "ON" : "OFF";
} else {
return std::to_string(inner);
}
},
v.value);
}
std::vector<std::string> split_shell_tokens(std::string_view text) {
std::vector<std::string> tokens;
std::string cur;
bool in_single = false;
bool in_double = false;
bool escaped = false;
for (const char c : text) {
if (escaped) {
cur.push_back(c);
escaped = false;
continue;
}
if (c == '\\' && !in_single) {
escaped = true;
continue;
}
if (c == '\'' && !in_double) {
in_single = !in_single;
continue;
}
if (c == '"' && !in_single) {
in_double = !in_double;
continue;
}
if (!in_single && !in_double && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
if (!cur.empty()) {
tokens.push_back(std::move(cur));
cur.clear();
}
continue;
}
cur.push_back(c);
}
if (!cur.empty()) {
tokens.push_back(std::move(cur));
}
return tokens;
}
bool is_safe_system_link_flag(std::string_view tok) {
return tok == "-pthread" || tok == "-lpthread" || tok == "-ldl" || tok == "-lm" ||
tok == "-lrt" || tok.starts_with("-Wl,");
}
struct ParsedCMakeTarget {
std::string id;
std::string name;
std::string type;
std::vector<std::filesystem::path> sources;
std::vector<std::pair<std::filesystem::path, bool>> includes;
std::vector<std::string> defines;
std::vector<std::string> compile_options;
std::vector<std::string> link_options;
CxxStandard cxx_standard{CxxStandard::Default};
std::vector<std::string> dep_ids;
std::vector<std::string> artifact_rel_paths;
};
struct ParsedCMakeCodemodel {
std::filesystem::path source_root;
std::filesystem::path build_root;
TranslationAuditReport audit;
std::map<std::string, ParsedCMakeTarget, std::less<>> targets_by_id;
std::vector<std::string> target_order;
};
Void::Result::Result<ParsedCMakeCodemodel, Void::Result::Error>
load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
const auto reply_dir = configure_dir / ".cmake" / "api" / "v1" / "reply";
std::error_code ec;
if (!std::filesystem::is_directory(reply_dir, ec)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("CMake File API reply directory missing at '{}'", reply_dir.string()))};
}
std::vector<std::filesystem::path> indices;
for (const auto &entry : std::filesystem::directory_iterator(reply_dir, ec)) {
const auto name = entry.path().filename().string();
if (name.starts_with("index-") && name.ends_with(".json")) {
indices.push_back(entry.path());
}
}
std::ranges::sort(indices);
if (indices.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
"CMake File API reply contains no index-*.json")};
}
auto index_json = parse_json_file(indices.back());
if (!index_json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"failed parsing CMake File API index JSON")};
}
const auto *idx_obj = std::get_if<JsonVal::Object>(&index_json->value);
const auto *reply_v = idx_obj ? find_key(*idx_obj, "reply") : nullptr;
const auto *reply_obj = reply_v ? std::get_if<JsonVal::Object>(&reply_v->value) : nullptr;
const auto *cm_v = reply_obj ? find_key(*reply_obj, "codemodel-v2") : nullptr;
const auto *cm_obj = cm_v ? std::get_if<JsonVal::Object>(&cm_v->value) : nullptr;
const std::string cm_file = cm_obj ? get_str(*cm_obj, "jsonFile") : std::string{};
if (cm_file.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
"CMake File API index missing codemodel-v2 entry")};
}
auto cm_json = parse_json_file(reply_dir / cm_file);
if (!cm_json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"failed parsing CMake codemodel-v2 JSON")};
}
const auto *cm_root = std::get_if<JsonVal::Object>(&cm_json->value);
if (!cm_root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"CMake codemodel-v2 root must be a JSON object")};
}
ParsedCMakeCodemodel out;
if (const auto *paths_v = find_key(*cm_root, "paths")) {
if (const auto *pobj = std::get_if<JsonVal::Object>(&paths_v->value)) {
out.source_root = std::filesystem::path{get_str(*pobj, "source")}.lexically_normal();
out.build_root = std::filesystem::path{get_str(*pobj, "build")}.lexically_normal();
}
}
auto add_unsupported = [&](std::string target_name, std::string kind, std::string detail) {
out.audit.status = TranslationStatus::Unsupported;
out.audit.unsupported.push_back(
UnsupportedConstruct{std::move(target_name), std::move(kind), std::move(detail)});
};
// First pass: load all target JSON files and collect known artifact basenames/paths.
std::vector<std::pair<std::string, JsonVal>> raw_target_docs;
std::set<std::string> known_target_artifacts;
if (const auto *cfgs_v = find_key(*cm_root, "configurations")) {
if (const auto *carr = std::get_if<JsonVal::Array>(&cfgs_v->value)) {
if (carr->size() > 1) {
add_unsupported(
"<codemodel>", "multi_config",
"multi-configuration generators are outside the bounded single-config "
"translation subset");
}
if (!carr->empty()) {
if (const auto *cobj = std::get_if<JsonVal::Object>(&carr->front().value)) {
if (const auto *targets_v = find_key(*cobj, "targets")) {
if (const auto *tarr = std::get_if<JsonVal::Array>(&targets_v->value)) {
for (const auto &tv : *tarr) {
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
if (!to) {
continue;
}
const auto jf = get_str(*to, "jsonFile");
if (jf.empty()) {
continue;
}
auto tdoc = parse_json_file(reply_dir / jf);
if (!tdoc) {
add_unsupported(get_str(*to, "name"), "missing_target_json",
"failed reading target JSON '" + jf + "'");
continue;
}
if (const auto *td = std::get_if<JsonVal::Object>(&tdoc->value)) {
if (const auto *arts = find_key(*td, "artifacts")) {
if (const auto *aarr =
std::get_if<JsonVal::Array>(&arts->value)) {
for (const auto &av : *aarr) {
if (const auto *ao =
std::get_if<JsonVal::Object>(&av.value)) {
const auto p = get_str(*ao, "path");
if (!p.empty()) {
known_target_artifacts.insert(p);
known_target_artifacts.insert(
std::filesystem::path{p}
.filename()
.string());
}
}
}
}
}
}
raw_target_docs.emplace_back(jf, std::move(*tdoc));
}
}
}
}
}
}
}
// Second pass: audit every target strictly and build ParsedCMakeTarget records.
for (const auto &[jf, tdoc] : raw_target_docs) {
const auto *td = std::get_if<JsonVal::Object>(&tdoc.value);
if (!td) {
continue;
}
ParsedCMakeTarget pt;
pt.id = get_str(*td, "id");
pt.name = get_str(*td, "name");
pt.type = get_str(*td, "type");
if (pt.type == "UTILITY" || pt.type == "GLOBAL_TARGET") {
add_unsupported(
pt.name, "utility_target",
std::format("CMake target '{}' has type '{}' (custom command/utility "
"targets cannot be faithfully translated from codemodel-v2)",
pt.name, pt.type));
continue;
}
if (pt.type != "STATIC_LIBRARY" && pt.type != "SHARED_LIBRARY" &&
pt.type != "OBJECT_LIBRARY" && pt.type != "EXECUTABLE") {
add_unsupported(
pt.name, "unsupported_target_type",
std::format("CMake target '{}' has unsupported type '{}'", pt.name, pt.type));
continue;
}
// Reject foreign C++20 module fileSets (dynamic module edges require explicit build rules).
if (const auto *fsets = find_key(*td, "fileSets")) {
if (const auto *farr = std::get_if<JsonVal::Array>(&fsets->value)) {
for (const auto &fv : *farr) {
if (const auto *fo = std::get_if<JsonVal::Object>(&fv.value)) {
const auto ftype = get_str(*fo, "type");
if (ftype == "CXX_MODULES") {
add_unsupported(
pt.name, "cxx_modules_fileset",
std::format("target '{}' uses CMake CXX_MODULES fileSet '{}'",
pt.name, get_str(*fo, "name")));
}
}
}
}
}
// Collect sources and detect any generated sources (e.g. from add_custom_command).
struct RawSource {
std::filesystem::path abs_path;
bool is_generated{false};
std::optional<std::int64_t> compile_group_index;
};
std::vector<RawSource> raw_sources;
if (const auto *srcs = find_key(*td, "sources")) {
if (const auto *sarr = std::get_if<JsonVal::Array>(&srcs->value)) {
for (const auto &sv : *sarr) {
if (const auto *so = std::get_if<JsonVal::Object>(&sv.value)) {
RawSource rs;
const std::filesystem::path raw_p{get_str(*so, "path")};
rs.abs_path = (raw_p.is_absolute() ? raw_p : (out.source_root / raw_p))
.lexically_normal();
rs.is_generated = get_bool(*so, "isGenerated", false);
rs.compile_group_index = get_i64(*so, "compileGroupIndex");
if (rs.is_generated) {
add_unsupported(
pt.name, "generated_source",
std::format("target '{}' depends on generated source '{}' "
"(foreign custom-command producer is not translated)",
pt.name, get_str(*so, "path")));
}
raw_sources.push_back(std::move(rs));
}
}
}
}
// Audit & extract compileGroups.
if (const auto *cgs = find_key(*td, "compileGroups")) {
if (const auto *cgarr = std::get_if<JsonVal::Array>(&cgs->value)) {
if (cgarr->size() > 1) {
add_unsupported(
pt.name, "multiple_compile_groups",
std::format("target '{}' has {} distinct compileGroups (mixed languages or "
"per-group flags exceed bounded single-group subset)",
pt.name, cgarr->size()));
}
for (const auto &cgv : *cgarr) {
const auto *cgo = std::get_if<JsonVal::Object>(&cgv.value);
if (!cgo) {
continue;
}
const auto lang = get_str(*cgo, "language");
if (lang != "CXX") {
add_unsupported(
pt.name, "unsupported_language",
std::format("target '{}' compiles language '{}' (bounded subset "
"supports CXX only)",
pt.name, lang));
}
if (const auto *pchs = find_key(*cgo, "precompileHeaders")) {
if (const auto *parr = std::get_if<JsonVal::Array>(&pchs->value);
parr && !parr->empty()) {
add_unsupported(
pt.name, "precompiled_header",
std::format("target '{}' uses CMake precompileHeaders", pt.name));
}
}
if (const auto *lstd = find_key(*cgo, "languageStandard")) {
if (const auto *lo = std::get_if<JsonVal::Object>(&lstd->value)) {
const auto std_str = get_str(*lo, "standard");
if (std_str == "17") {
pt.cxx_standard = CxxStandard::Cxx17;
} else if (std_str == "20") {
pt.cxx_standard = CxxStandard::Cxx20;
} else if (std_str == "23") {
pt.cxx_standard = CxxStandard::Cxx23;
} else if (std_str == "26") {
pt.cxx_standard = CxxStandard::Cxx26;
}
}
}
if (const auto *incs = find_key(*cgo, "includes")) {
if (const auto *iarr = std::get_if<JsonVal::Array>(&incs->value)) {
for (const auto &iv : *iarr) {
if (const auto *io = std::get_if<JsonVal::Object>(&iv.value)) {
const std::filesystem::path ip{get_str(*io, "path")};
const bool sys = get_bool(*io, "isSystem", false);
if (!std::ranges::contains(pt.includes, std::pair{ip, sys})) {
pt.includes.emplace_back(ip, sys);
}
}
}
}
}
if (const auto *defs = find_key(*cgo, "defines")) {
if (const auto *darr = std::get_if<JsonVal::Array>(&defs->value)) {
for (const auto &dv : *darr) {
if (const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value)) {
const auto d = get_str(*do_obj, "define");
if (!d.empty() && !std::ranges::contains(pt.defines, d)) {
pt.defines.push_back(d);
}
}
}
}
}
if (const auto *frags = find_key(*cgo, "compileCommandFragments")) {
if (const auto *farr = std::get_if<JsonVal::Array>(&frags->value)) {
for (const auto &fv : *farr) {
if (const auto *fo = std::get_if<JsonVal::Object>(&fv.value)) {
for (const auto &tok :
split_shell_tokens(get_str(*fo, "fragment"))) {
if (tok == "-fPIC" || tok == "-fpic" ||
tok.starts_with("-std=")) {
continue;
}
if (!std::ranges::contains(pt.compile_options, tok)) {
pt.compile_options.push_back(tok);
}
}
}
}
}
}
if (const auto *sidxs = find_key(*cgo, "sourceIndexes")) {
if (const auto *siarr = std::get_if<JsonVal::Array>(&sidxs->value)) {
for (const auto &iv : *siarr) {
if (const auto *idx = std::get_if<std::int64_t>(&iv.value)) {
const auto u = static_cast<std::size_t>(*idx);
if (u < raw_sources.size() && !raw_sources[u].is_generated) {
pt.sources.push_back(raw_sources[u].abs_path);
}
}
}
}
}
}
}
}
// Audit link fragments so external/untracked linker inputs are never silently dropped.
if (const auto *lnk = find_key(*td, "link")) {
if (const auto *lobj = std::get_if<JsonVal::Object>(&lnk->value)) {
if (const auto *frags = find_key(*lobj, "commandFragments")) {
if (const auto *farr = std::get_if<JsonVal::Array>(&frags->value)) {
for (const auto &fv : *farr) {
const auto *fo = std::get_if<JsonVal::Object>(&fv.value);
if (!fo) {
continue;
}
const auto role = get_str(*fo, "role");
const auto frag = get_str(*fo, "fragment");
if (role == "flags") {
for (const auto &tok : split_shell_tokens(frag)) {
if (is_safe_system_link_flag(tok) &&
!std::ranges::contains(pt.link_options, tok)) {
pt.link_options.push_back(tok);
}
}
} else if (role == "libraries") {
for (const auto &tok : split_shell_tokens(frag)) {
if (tok.empty()) {
continue;
}
if (is_safe_system_link_flag(tok)) {
if (!std::ranges::contains(pt.link_options, tok)) {
pt.link_options.push_back(tok);
}
} else if (known_target_artifacts.contains(tok) ||
known_target_artifacts.contains(
std::filesystem::path{tok}
.filename()
.string())) {
// Internal translated target dependency (wired via
// dep_ids).
} else if (tok.starts_with("-Wl,-rpath")) {
// Handled natively by VBS RPATH lowering.
} else {
add_unsupported(
pt.name, "unsupported_link_fragment",
std::format("target '{}' has untranslated library link "
"fragment '{}'",
pt.name, tok));
}
}
}
}
}
}
}
}
if (const auto *deps = find_key(*td, "dependencies")) {
if (const auto *darr = std::get_if<JsonVal::Array>(&deps->value)) {
for (const auto &dv : *darr) {
if (const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value)) {
const auto dep_id = get_str(*do_obj, "id");
if (!dep_id.empty()) {
pt.dep_ids.push_back(dep_id);
}
}
}
}
}
if (const auto *arts = find_key(*td, "artifacts")) {
if (const auto *aarr = std::get_if<JsonVal::Array>(&arts->value)) {
for (const auto &av : *aarr) {
if (const auto *ao = std::get_if<JsonVal::Object>(&av.value)) {
const auto rel = get_str(*ao, "path");
if (!rel.empty()) {
pt.artifact_rel_paths.push_back(rel);
}
}
}
}
}
out.audit.supported_targets.push_back(pt.name);
out.target_order.push_back(pt.id);
out.targets_by_id[pt.id] = std::move(pt);
}
// Verify every dependency edge points to a translated target (never a dropped utility target!).
for (const auto &tid : out.target_order) {
const auto &pt = out.targets_by_id.at(tid);
for (const auto &dep_id : pt.dep_ids) {
if (!out.targets_by_id.contains(dep_id)) {
add_unsupported(pt.name, "untranslated_dependency_edge",
std::format("target '{}' depends on untranslated CMake target '{}'",
pt.name, dep_id));
}
}
}
if (out.audit.is_supported()) {
out.audit.summary = std::format("all {} CMake target(s) fit the bounded native subset",
out.audit.supported_targets.size());
} else {
out.audit.summary =
std::format("{} unsupported construct(s) detected across CMake codemodel",
out.audit.unsupported.size());
}
return out;
}
std::string format_unsupported_diagnostics(const TranslationAuditReport &audit) {
std::string msg = "CMake native graph translation unsupported (" + audit.summary + "):";
for (const auto &u : audit.unsupported) {
msg += std::format("\n - [{}] {}: {}", u.construct_kind, u.target_name, u.detail);
}
return msg;
}
} // namespace
Void::Result::Result<std::filesystem::path, Void::Result::Error>
configure_cmake_for_translation(const ProviderRequest &request,
const std::filesystem::path &configure_dir, std::stop_token stop) {
auto cmake_bin = Platform::resolve_executable("cmake");
if (!cmake_bin) {
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
"CMake translation requires 'cmake' in PATH")};
}
std::error_code ec;
std::filesystem::remove_all(configure_dir, ec);
std::filesystem::create_directories(configure_dir / ".cmake" / "api" / "v1" / "query", ec);
if (auto w = Platform::atomic_write_file(
configure_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false);
!w) {
return std::unexpected{w.error()};
}
Void::Log::info("Translate", "Configuring CMake dependency '{}' for native graph audit...",
request.dependency.name);
Platform::ProcessRequest req;
req.executable = *cmake_bin;
req.arguments = {"-S", request.source.source_dir.string(), "-B", configure_dir.string()};
if (Platform::resolve_executable("ninja").has_value()) {
req.arguments.push_back("-G");
req.arguments.push_back("Ninja");
}
req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string());
const std::string btype =
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
: "Debug";
req.arguments.push_back("-DCMAKE_BUILD_TYPE=" + btype);
for (const auto &[k, v] : request.dependency.options) {
req.arguments.push_back("-D" + k + "=" + cmake_option_value(v));
}
req.timeout = std::chrono::seconds{180};
auto proc = Platform::run_supervised(req, stop);
if (!proc || !proc->succeeded()) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("CMake configure failed for '{}':\n{}", request.dependency.name,
proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))};
}
return configure_dir / ".cmake" / "api" / "v1" / "reply";
}
Void::Result::Result<TranslationAuditReport, Void::Result::Error>
audit_cmake_codemodel(const std::filesystem::path &configure_dir) {
auto loaded = load_and_audit_codemodel(configure_dir);
if (!loaded) {
return std::unexpected{loaded.error()};
}
return std::move(loaded->audit);
}
Void::Result::Result<TranslatedCMakeGraph, Void::Result::Error> translate_cmake_to_native_graph(
const ProviderRequest &request, const std::filesystem::path &configure_dir,
const std::filesystem::path &native_build_root, const Snapshot::InputSnapshot *snapshot) {
auto loaded = load_and_audit_codemodel(configure_dir);
if (!loaded) {
return std::unexpected{loaded.error()};
}
if (!loaded->audit.is_supported()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported,
format_unsupported_diagnostics(loaded->audit))};
}
Graph::ProjectDescription desc;
desc.profile = request.profile;
// Preserve foreign project's exact configured flags instead of injecting parent profile flags
// twice; keep profile identity/toolchain/reproducibility epoch intact.
desc.profile.compile_options.clear();
desc.profile.defines.clear();
for (const auto &tid : loaded->target_order) {
const auto &pt = loaded->targets_by_id.at(tid);
TargetRecord tr;
tr.name = pt.name;
if (pt.type == "STATIC_LIBRARY") {
tr.kind = TargetKind::StaticLibrary;
} else if (pt.type == "SHARED_LIBRARY") {
tr.kind = TargetKind::SharedLibrary;
} else if (pt.type == "OBJECT_LIBRARY") {
tr.kind = TargetKind::ObjectLibrary;
} else {
tr.kind = TargetKind::Executable;
}
tr.cxx_standard = pt.cxx_standard;
for (const auto &src : pt.sources) {
tr.sources.push_back(SourceRecord{SourceKind::File, src.string()});
}
for (const auto &[inc, is_sys] : pt.includes) {
tr.include_directories.push_back(
IncludeDirectory{inc.string(), Visibility::Public, is_sys});
}
for (const auto &def : pt.defines) {
tr.defines.push_back(ScopedOption{def, Visibility::Public});
}
for (const auto &opt : pt.compile_options) {
tr.compile_options.push_back(opt);
tr.scoped_compile_options.push_back(ScopedOption{opt, Visibility::Private});
}
for (const auto &lo : pt.link_options) {
tr.link_options.push_back(ScopedOption{lo, Visibility::Public});
}
for (const auto &dep_id : pt.dep_ids) {
const auto &dep_target = loaded->targets_by_id.at(dep_id);
tr.links.push_back(
LinkRecord{LinkKind::Local, dep_target.name, {}, Visibility::Public});
}
desc.targets.push_back(std::move(tr));
}
const auto src_root =
loaded->source_root.empty() ? request.source.source_dir : loaded->source_root;
Graph::GraphLowerOptions gopts{src_root, native_build_root, snapshot, {}, 32768};
auto graph = Graph::lower_project_graph(desc, request.toolchain, gopts);
if (!graph) {
return std::unexpected{graph.error()};
}
// Build exported ImportedTargetInterface entries pointing directly at VBS native outputs!
TranslatedCMakeGraph result;
result.audit = std::move(loaded->audit);
std::map<std::string, const Graph::ResolvedTargetSummary *, std::less<>> summary_by_name;
for (const auto &s : graph->targets) {
summary_by_name[s.name] = &s;
}
for (const auto &tid : loaded->target_order) {
const auto &pt = loaded->targets_by_id.at(tid);
const auto sit = summary_by_name.find(pt.name);
if (sit == summary_by_name.end()) {
continue;
}
Graph::ImportedTargetInterface iface;
iface.dependency_name = request.dependency.name;
iface.target_name = pt.name;
iface.include_dirs = pt.includes;
iface.defines = pt.defines;
iface.link_options = pt.link_options;
// Collect primary output + transitive static/shared outputs in dependency order.
if (!sit->second->primary_outputs.empty()) {
const auto &primary = sit->second->primary_outputs.front();
if (pt.type == "STATIC_LIBRARY") {
iface.static_libraries.push_back(primary);
} else if (pt.type == "SHARED_LIBRARY") {
iface.shared_libraries.push_back(primary);
iface.runtime_files.push_back(primary);
}
}
// Append transitive dependency libraries via DFS post-order reversed.
std::vector<std::string> post_order;
std::set<std::string> visited;
auto dfs = [&](auto &&self, const std::string &cur_id) -> void {
if (!visited.insert(cur_id).second) {
return;
}
const auto it = loaded->targets_by_id.find(cur_id);
if (it == loaded->targets_by_id.end()) {
return;
}
for (const auto &sub : it->second.dep_ids) {
self(self, sub);
}
post_order.push_back(cur_id);
};
for (const auto &dep_id : pt.dep_ids) {
dfs(dfs, dep_id);
}
std::ranges::reverse(post_order);
for (const auto &dep_id : post_order) {
const auto &dep_pt = loaded->targets_by_id.at(dep_id);
const auto dsit = summary_by_name.find(dep_pt.name);
if (dsit == summary_by_name.end() || dsit->second->primary_outputs.empty()) {
continue;
}
const auto &dep_out = dsit->second->primary_outputs.front();
if (dep_pt.type == "STATIC_LIBRARY" &&
!std::ranges::contains(iface.static_libraries, dep_out)) {
iface.static_libraries.push_back(dep_out);
} else if (dep_pt.type == "SHARED_LIBRARY" &&
!std::ranges::contains(iface.shared_libraries, dep_out)) {
iface.shared_libraries.push_back(dep_out);
iface.runtime_files.push_back(dep_out);
}
}
result.exported_targets[pt.name] = iface;
result.exported_targets[request.dependency.name + "::" + pt.name] = std::move(iface);
}
result.graph = std::move(*graph);
return result;
}
Void::Result::Result<TranslationResolution, Void::Result::Error>
resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore &state,
TranslationPolicy policy, std::stop_token stop) {
if (request.dependency.builder != "cmake") {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("resolve_cmake_with_translation requires builder='cmake', got '{}'",
request.dependency.builder))};
}
const auto sw = Void::Time::Stopwatch::started();
const std::string input_hash = compute_provider_input_hash(request);
const auto slot_dir = request.provider_build_root /
("translate_" + request.dependency.name + "_" + input_hash.substr(0, 16));
const auto cfg_dir = slot_dir / "cmake-configure";
const auto native_build_root = slot_dir / "native-build";
auto reply_dir = configure_cmake_for_translation(request, cfg_dir, stop);
if (!reply_dir) {
return std::unexpected{reply_dir.error()};
}
auto audit = audit_cmake_codemodel(cfg_dir);
if (!audit) {
return std::unexpected{audit.error()};
}
if (!audit->is_supported()) {
if (policy == TranslationPolicy::RequireNative) {
return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported,
format_unsupported_diagnostics(*audit))};
}
Void::Log::warn("Translate",
"CMake dependency '{}' has unsupported constructs ({}); falling back to "
"foreign CMake provider",
request.dependency.name, audit->summary);
auto fallback = resolve_foreign_provider(request, stop);
if (!fallback) {
return std::unexpected{fallback.error()};
}
TranslationResolution res;
res.executed_natively = false;
res.audit = std::move(*audit);
res.exported = std::move(*fallback);
return res;
}
auto translated = translate_cmake_to_native_graph(request, cfg_dir, native_build_root, nullptr);
if (!translated) {
return std::unexpected{translated.error()};
}
Void::Log::info("Translate",
"Executing CMake dependency '{}' natively ({} actions, 0 cmake --build)...",
request.dependency.name, translated->graph.actions.size());
auto exec = Execution::execute_graph(translated->graph, state, {}, stop);
if (!exec) {
return std::unexpected{exec.error()};
}
if (!exec->succeeded) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("native execution of translated CMake dependency '{}' failed: {}",
request.dependency.name, exec->diagnostic))};
}
Void::Log::info("Translate",
"Native CMake translation '{}' finished in {}ms ({} executed, {} cached)",
request.dependency.name, sw.elapsed_as<std::chrono::milliseconds>().count(),
exec->executed_count, exec->cached_count);
ProviderExport exp;
exp.dependency_name = request.dependency.name;
exp.builder = "cmake-native-translated";
exp.input_identity_hash = input_hash;
exp.from_cache = (exec->executed_count == 0);
exp.targets = std::move(translated->exported_targets);
TranslationResolution res;
res.executed_natively = true;
res.audit = std::move(translated->audit);
res.exported = std::move(exp);
res.native_execution = std::move(*exec);
return res;
}
} // namespace Void::Build::Provider