Files
Build-System/src/Config/Frontend.cpp
T
faumaray 2970fbe25c
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 4s
feat(workspace): add multi-package workspace builds with shared lock and CAS
- SDK: Workspace/workspace() declaration plus Project::workspace_dependency()
- Frontend: workspace.cpp discovery/evaluation alongside build.cpp
- Main: per-member builds sharing the root vbs.lock and build/.vbs CAS, --member and --changed-since selection
- Cross-member native linking; member builds do not steal the root compile_commands.json alias
- Path-dependency snapshots exclude generated editor metadata
- Verified in Docker GCC 16: 8/8 CTest suites; 3-member workspace fixture with unified lockfile
2026-12-03 13:07:09 +03:00

892 lines
36 KiB
C++

#include <Void/Build/Config/Frontend.hpp>
#include <Void/Build/Execution/Scheduler.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 <atomic>
#include <format>
#include <set>
#include <unistd.h>
namespace Void::Build::Config {
namespace {
using JsonVal = Void::Json::Strict::Value;
std::atomic<std::uint64_t> g_req_seq{0};
Void::Result::Error make_error(std::string msg) {
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
std::move(msg));
}
bool is_cpp_file(const std::filesystem::path &p) {
const auto ext = p.extension().string();
return ext == ".cpp" || ext == ".cc" || ext == ".cxx";
}
std::string generate_driver_source(bool has_profiles_file, bool has_build_file,
bool has_workspace_file) {
std::string code = R"cpp(#include <Void/Build.hpp>
#include <Void/Build/Util/Json.hpp>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
)cpp";
if (!has_profiles_file) {
code += R"cpp(void profiles(Void::Build::Profiles &descriptions) {
descriptions = Void::Build::default_profiles();
}
)cpp";
}
if (!has_build_file) {
code += R"cpp(void build(Void::Build::Project &) {
throw std::runtime_error{"this descriptor declares no build() entry point"};
}
)cpp";
}
if (!has_workspace_file) {
code += R"cpp(void workspace(Void::Build::Workspace &) {
throw std::runtime_error{"this descriptor declares no workspace() entry point"};
}
)cpp";
}
code += R"cpp(
namespace {
std::string read_text(const std::string &path) {
std::ifstream in(path, std::ios::binary);
if (!in) {
throw std::runtime_error{"cannot open context file: " + path};
}
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
void write_text(const std::string &path, const std::string &content) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) {
throw std::runtime_error{"cannot write result file: " + path};
}
out << content;
out.flush();
if (!out) {
throw std::runtime_error{"failed flushing result file: " + path};
}
}
std::vector<std::string> split_lines(std::string_view text) {
std::vector<std::string> out;
std::size_t pos = 0;
while (pos < text.size()) {
const auto nl = text.find('\n', pos);
const auto line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
if (!line.empty()) {
out.emplace_back(line);
}
if (nl == std::string_view::npos) {
break;
}
pos = nl + 1;
}
return out;
}
Void::Build::ProfileContext parse_kv_context(std::string_view text) {
Void::Build::ProfileContext ctx;
for (const auto &line : split_lines(text)) {
const auto eq = line.find('=');
if (eq == std::string::npos) {
continue;
}
const auto key = line.substr(0, eq);
const auto val = line.substr(eq + 1);
if (key == "name") ctx.name = val;
else if (key == "compiler") ctx.compiler = Void::Build::parse_compiler(val);
else if (key == "os") ctx.os = val;
else if (key == "architecture") ctx.architecture = val;
else if (key == "c_standard") ctx.c_standard = Void::Build::parse_c_standard(val);
else if (key == "cxx_standard") ctx.cxx_standard = Void::Build::parse_cxx_standard(val);
else if (key == "lto") ctx.lto = Void::Build::parse_lto_mode(val);
else if (key == "sysroot") ctx.sysroot = val;
else if (key == "compiler_path") ctx.compiler_path = val;
else if (key == "reproducibility_epoch") ctx.reproducibility_epoch = std::stoll(val);
else if (key == "nondeterministic") ctx.nondeterministic = (val == "1" || val == "true");
else if (key == "compile_option") ctx.compile_options.push_back(val);
else if (key == "link_option") ctx.link_options.push_back(val);
else if (key == "define") ctx.defines.push_back(val);
else if (key == "sanitizer") ctx.sanitizers.push_back(Void::Build::parse_sanitizer(val));
}
return ctx;
}
} // namespace
int main(int argc, char **argv) {
try {
std::string mode;
std::string output_path;
std::string request_id;
std::string context_file;
std::string context_hash;
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (arg == "--mode" && i + 1 < argc) mode = argv[++i];
else if (arg == "--output" && i + 1 < argc) output_path = argv[++i];
else if (arg == "--request-id" && i + 1 < argc) request_id = argv[++i];
else if (arg == "--context-file" && i + 1 < argc) context_file = argv[++i];
else if (arg == "--context-hash" && i + 1 < argc) context_hash = argv[++i];
else {
std::cerr << "vbs-config-driver: unknown argument: " << arg << '\n';
return 2;
}
}
if (output_path.empty() || request_id.empty()) {
std::cerr << "vbs-config-driver: --output and --request-id are required\n";
return 2;
}
if (mode == "profiles") {
Void::Build::Profiles descriptions;
profiles(descriptions);
const std::string payload =
"{\"protocol_version\":1,\"request_id\":" +
Void::Build::Util::json_quote(request_id) +
",\"payload\":" + descriptions.to_json() + "}\n";
write_text(output_path, payload);
return 0;
}
if (mode == "describe") {
auto ctx = parse_kv_context(read_text(context_file));
Void::Build::Project project{ctx};
build(project);
const std::string payload =
"{\"protocol_version\":1,\"request_id\":" +
Void::Build::Util::json_quote(request_id) +
",\"context_hash\":" + Void::Build::Util::json_quote(context_hash) +
",\"payload\":" + project.to_json() + "}\n";
write_text(output_path, payload);
return 0;
}
if (mode == "workspace") {
Void::Build::Workspace ws;
workspace(ws);
const std::string payload =
"{\"protocol_version\":1,\"request_id\":" +
Void::Build::Util::json_quote(request_id) +
",\"payload\":" + ws.to_json() + "}\n";
write_text(output_path, payload);
return 0;
}
std::cerr << "vbs-config-driver: unknown mode '" << mode << "'\n";
return 2;
} catch (const std::exception &err) {
std::cerr << "vbs-config-driver: " << err.what() << '\n';
return 2;
}
}
)cpp";
return code;
}
std::string serialize_kv_context(const ProfileContext &ctx) {
std::string out;
out += "name=" + ctx.name + "\n";
out += "compiler=" + std::string{compiler_name(ctx.compiler)} + "\n";
out += "os=" + ctx.os + "\n";
out += "architecture=" + ctx.architecture + "\n";
out += "c_standard=" + std::string{Void::Build::c_standard_name(ctx.c_standard)} + "\n";
out += "cxx_standard=" + std::string{cxx_standard_name(ctx.cxx_standard)} + "\n";
out += "lto=" + std::string{lto_mode_name(ctx.lto)} + "\n";
out += "sysroot=" + ctx.sysroot + "\n";
out += "compiler_path=" + ctx.compiler_path + "\n";
out += "reproducibility_epoch=" + std::to_string(ctx.reproducibility_epoch) + "\n";
out += std::string{"nondeterministic="} + (ctx.nondeterministic ? "1" : "0") + "\n";
for (const auto &opt : ctx.compile_options) {
out += "compile_option=" + opt + "\n";
}
for (const auto &opt : ctx.link_options) {
out += "link_option=" + opt + "\n";
}
for (const auto &def : ctx.defines) {
out += "define=" + def + "\n";
}
for (const auto s : ctx.sanitizers) {
out += "sanitizer=" + std::string{sanitizer_name(s)} + "\n";
}
return out;
}
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::optional<std::string> get_str(const JsonVal::Object &obj, const std::string &k) {
const auto *v = find_key(obj, k);
if (!v) {
return std::nullopt;
}
const auto *s = std::get_if<std::string>(&v->value);
return s ? std::optional<std::string>{*s} : std::nullopt;
}
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::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
std::vector<std::string> out;
const auto *v = find_key(obj, k);
if (!v) {
return out;
}
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
for (const auto &item : *arr) {
if (const auto *s = std::get_if<std::string>(&item.value)) {
out.push_back(*s);
}
}
}
return out;
}
} // namespace
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
discover_config_sources(const std::filesystem::path &project_root,
const std::vector<std::filesystem::path> &extra_build_sources) {
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(project_root, ec);
if (ec || !std::filesystem::is_directory(canonical_root)) {
return std::unexpected{
make_error(std::format("project root '{}' is not a directory", project_root.string()))};
}
const auto root_build = canonical_root / "build.cpp";
const auto root_workspace = canonical_root / "workspace.cpp";
const bool has_build = std::filesystem::is_regular_file(root_build, ec);
const bool has_workspace = std::filesystem::is_regular_file(root_workspace, ec);
if (!has_build && !has_workspace) {
return std::unexpected{
make_error(std::format("missing required root description '{}' or '{}'",
root_build.string(), root_workspace.string()))};
}
std::vector<std::filesystem::path> sources;
std::set<std::filesystem::path> seen;
auto push = [&](const std::filesystem::path &p) {
const auto norm = p.lexically_normal();
if (seen.insert(norm).second) {
sources.push_back(norm);
}
};
if (has_build) {
push(root_build);
}
if (has_workspace) {
push(root_workspace);
}
const auto profiles_cpp = canonical_root / "build.profiles.cpp";
if (std::filesystem::is_regular_file(profiles_cpp, ec)) {
push(profiles_cpp);
}
// Filesystem-discovered build-support/**/*.cpp (works identically without .git!).
const auto support_dir = canonical_root / "build-support";
if (std::filesystem::is_directory(support_dir, ec)) {
std::vector<std::filesystem::path> helpers;
for (const auto &entry : std::filesystem::recursive_directory_iterator(support_dir, ec)) {
if (entry.is_regular_file(ec) && is_cpp_file(entry.path())) {
helpers.push_back(entry.path().lexically_normal());
}
}
std::ranges::sort(helpers);
for (const auto &h : helpers) {
push(h);
}
}
// Explicit --build-source inputs.
for (const auto &extra : extra_build_sources) {
const auto abs = extra.is_absolute() ? extra : (canonical_root / extra);
if (!std::filesystem::is_regular_file(abs, ec)) {
return std::unexpected{make_error(
std::format("explicit --build-source '{}' does not exist", extra.string()))};
}
push(abs);
}
return sources;
}
Void::Result::Result<CompiledDescriptor, Void::Result::Error>
compile_descriptor(const FrontendOptions &options) {
auto sources_res = discover_config_sources(options.project_root, options.extra_build_sources);
if (!sources_res) {
return std::unexpected{sources_res.error()};
}
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec);
const auto config_dir =
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config";
std::filesystem::create_directories(config_dir, ec);
auto lock =
Platform::FileLock::acquire(config_dir / "seed.lock", Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
std::filesystem::path host_cxx;
if (options.host_compiler && !options.host_compiler->empty()) {
auto resolved = Platform::resolve_executable(*options.host_compiler);
if (!resolved) {
return std::unexpected{make_error(std::format(
"configured host compiler '{}' was not found", options.host_compiler->string()))};
}
host_cxx = *resolved;
} else {
auto resolved = Platform::resolve_executable("g++");
if (!resolved) {
return std::unexpected{
make_error("host compiler 'g++' not found in PATH for compiling build.cpp")};
}
host_cxx = *resolved;
}
auto host_hash = Util::sha256_file_hex(host_cxx);
if (!host_hash) {
return std::unexpected{host_hash.error()};
}
const bool has_profiles =
std::filesystem::is_regular_file(canonical_root / "build.profiles.cpp", ec);
const bool has_build = std::filesystem::is_regular_file(canonical_root / "build.cpp", ec);
const bool has_workspace =
std::filesystem::is_regular_file(canonical_root / "workspace.cpp", ec);
const std::string driver_src = generate_driver_source(has_profiles, has_build, has_workspace);
const auto driver_cpp = config_dir / "Driver.cpp";
if (auto wrote = Platform::atomic_write_file(driver_cpp, driver_src, false); !wrote) {
return std::unexpected{wrote.error()};
}
// Compute seed identity over host compiler, SDK header/library, driver source, and config
// sources.
Util::Sha256Hasher id_hasher;
id_hasher.update_length_prefixed("vbs-seed-v1");
id_hasher.update_length_prefixed(host_cxx.string());
id_hasher.update_length_prefixed(*host_hash);
id_hasher.update_length_prefixed(driver_src);
if (!options.sdk_include_dir.empty()) {
if (auto hdr_h = Util::sha256_file_hex(options.sdk_include_dir / "Void" / "Build.hpp");
hdr_h) {
id_hasher.update_length_prefixed(*hdr_h);
}
}
if (!options.sdk_library_path.empty() &&
std::filesystem::exists(options.sdk_library_path, ec)) {
if (auto lib_h = Util::sha256_file_hex(options.sdk_library_path); lib_h) {
id_hasher.update_length_prefixed(*lib_h);
}
}
for (const auto &src : *sources_res) {
auto h = Util::sha256_file_hex(src);
if (!h) {
return std::unexpected{h.error()};
}
id_hasher.update_length_prefixed(src.string());
id_hasher.update_length_prefixed(*h);
}
const std::string seed_id = id_hasher.finalize_hex();
const auto exe_path = config_dir / ("descriptor_" + seed_id.substr(0, 16));
const auto meta_path = config_dir / ("descriptor_" + seed_id.substr(0, 16) + ".headers.json");
// Check if cached descriptor executable exists AND all previously discovered headers match!
bool up_to_date = false;
std::vector<std::filesystem::path> cached_headers;
if (std::filesystem::is_regular_file(exe_path, ec) &&
std::filesystem::is_regular_file(meta_path, ec)) {
if (auto meta_text = Void::FileSystem::read_file(meta_path); meta_text) {
if (auto parsed = Void::Json::Strict::parse(*meta_text); parsed) {
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
if (get_str(*obj, "seed_id").value_or("") == seed_id) {
bool headers_ok = true;
if (const auto *hv = find_key(*obj, "headers")) {
if (const auto *hobj = std::get_if<JsonVal::Object>(&hv->value)) {
for (const auto &[hpath, hval] : *hobj) {
const auto *expected = std::get_if<std::string>(&hval.value);
auto actual =
Util::sha256_file_hex(std::filesystem::path{hpath});
if (!expected || !actual || *actual != *expected) {
headers_ok = false;
break;
}
cached_headers.emplace_back(hpath);
}
}
}
up_to_date = headers_ok;
}
}
}
}
}
if (up_to_date) {
CompiledDescriptor desc;
desc.executable_path = exe_path;
desc.seed_identity_hash = seed_id;
desc.config_sources = *sources_res;
desc.discovered_headers = std::move(cached_headers);
desc.recompiled = false;
return desc;
}
// Compile each translation unit with depfiles so included headers enter configuration identity!
const auto obj_dir = config_dir / ("obj_" + seed_id.substr(0, 16));
std::filesystem::create_directories(obj_dir, ec);
std::vector<std::filesystem::path> compile_units = *sources_res;
compile_units.push_back(driver_cpp);
const bool use_prebuilt_sdk = !options.sdk_library_path.empty() &&
std::filesystem::is_regular_file(options.sdk_library_path, ec);
if (!use_prebuilt_sdk && !options.sdk_source_dir.empty()) {
compile_units.push_back(options.sdk_source_dir / "Build.cpp");
compile_units.push_back(options.sdk_source_dir / "Util" / "Json.cpp");
}
std::vector<std::filesystem::path> objects;
std::map<std::string, std::string, std::less<>> header_hashes;
for (std::size_t i = 0; i < compile_units.size(); ++i) {
const auto &tu = compile_units[i];
const auto obj = obj_dir / std::format("tu_{}_{}.o", i, tu.stem().string());
const auto dep = obj_dir / std::format("tu_{}_{}.d", i, tu.stem().string());
Platform::ProcessRequest req;
req.executable = host_cxx;
req.arguments = {"-std=c++26", "-O1", "-I", canonical_root.string()};
if (!options.sdk_include_dir.empty()) {
req.arguments.push_back("-I");
req.arguments.push_back(options.sdk_include_dir.string());
}
req.arguments.push_back("-MMD");
req.arguments.push_back("-MF");
req.arguments.push_back(dep.string());
req.arguments.push_back("-c");
req.arguments.push_back(tu.string());
req.arguments.push_back("-o");
req.arguments.push_back(obj.string());
req.working_directory = canonical_root;
req.timeout = std::chrono::seconds{60};
auto res = Platform::run_supervised(req);
if (!res || !res->succeeded()) {
const std::string detail =
res ? (res->stderr_data.empty() ? res->exec_error_message : res->stderr_data)
: res.error().message();
return std::unexpected{make_error(
std::format("failed compiling configuration source '{}' (note: unresolved project "
"package headers cannot be required during seed compilation):\n{}",
tu.string(), detail))};
}
objects.push_back(obj);
if (auto deps = Execution::parse_depfile(dep); deps) {
for (const auto &d : *deps) {
const auto abs = d.is_absolute() ? d.lexically_normal()
: (canonical_root / d).lexically_normal();
if (Platform::path_is_within(canonical_root, abs) ||
(!options.sdk_include_dir.empty() &&
Platform::path_is_within(options.sdk_include_dir, abs))) {
if (auto hh = Util::sha256_file_hex(abs); hh) {
header_hashes[abs.string()] = std::move(*hh);
}
}
}
}
}
// Link host descriptor executable atomically into staging then rename.
const auto staged_exe =
config_dir / std::format("descriptor_{}.stage_{}", seed_id.substr(0, 16),
static_cast<long long>(::getpid()));
{
Platform::ProcessRequest req;
req.executable = host_cxx;
req.arguments = {"-std=c++26", "-o", staged_exe.string()};
for (const auto &o : objects) {
req.arguments.push_back(o.string());
}
if (use_prebuilt_sdk) {
req.arguments.push_back(options.sdk_library_path.string());
}
req.working_directory = canonical_root;
req.timeout = std::chrono::seconds{60};
auto res = Platform::run_supervised(req);
if (!res || !res->succeeded()) {
std::filesystem::remove(staged_exe, ec);
const std::string detail =
res ? (res->stderr_data.empty() ? res->exec_error_message : res->stderr_data)
: res.error().message();
return std::unexpected{
make_error(std::format("failed linking configuration descriptor:\n{}", detail))};
}
}
std::filesystem::rename(staged_exe, exe_path, ec);
if (ec) {
std::filesystem::remove(staged_exe, ec);
return std::unexpected{make_error("failed publishing compiled descriptor executable")};
}
// Persist discovered header hashes atomically.
std::string meta_json = "{\"seed_id\":" + Util::json_quote(seed_id) + ",\"headers\":{";
bool first = true;
std::vector<std::filesystem::path> headers_list;
for (const auto &[hpath, hsha] : header_hashes) {
if (!first) {
meta_json += ',';
}
first = false;
meta_json += Util::json_quote(hpath) + ':' + Util::json_quote(hsha);
headers_list.emplace_back(hpath);
}
meta_json += "}}\n";
(void)Platform::atomic_write_file(meta_path, meta_json, false);
CompiledDescriptor desc;
desc.executable_path = exe_path;
desc.seed_identity_hash = seed_id;
desc.config_sources = *sources_res;
desc.discovered_headers = std::move(headers_list);
desc.recompiled = true;
return desc;
}
bool is_workspace_root(const std::filesystem::path &project_root) {
std::error_code ec;
return std::filesystem::is_regular_file(project_root / "workspace.cpp", ec);
}
Void::Result::Result<Profiles, Void::Result::Error>
discover_profiles(const CompiledDescriptor &descriptor, const FrontendOptions &options) {
std::error_code ec;
const auto run_dir =
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval";
std::filesystem::create_directories(run_dir, ec);
const std::string req_id = std::format("prof_{}_{}", static_cast<long long>(::getpid()),
g_req_seq.fetch_add(1, std::memory_order_relaxed));
const auto out_file = run_dir / (req_id + ".json");
Platform::ProcessRequest req;
req.executable = descriptor.executable_path;
req.arguments = {"--mode", "profiles", "--output", out_file.string(), "--request-id", req_id};
req.working_directory = options.project_root;
req.timeout = options.eval_timeout;
auto proc = Platform::run_supervised(req);
auto cleanup = [&] { std::filesystem::remove(out_file, ec); };
if (!proc) {
cleanup();
return std::unexpected{proc.error()};
}
if (!proc->succeeded()) {
cleanup();
return std::unexpected{
make_error(std::format("profile discovery failed (exit={}, signal={}): {}",
proc->exit_code, proc->term_signal, proc->stderr_data))};
}
auto text = Void::FileSystem::read_file_bounded(out_file, {16ULL * 1024ULL * 1024ULL});
cleanup();
if (!text) {
return std::unexpected{make_error("profile discovery did not write a valid result file")};
}
if (!Util::is_valid_utf8(*text)) {
return std::unexpected{make_error("profile discovery result contains invalid UTF-8")};
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return std::unexpected{make_error("profile discovery emitted malformed JSON")};
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error("profile discovery envelope must be a JSON object")};
}
if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) {
return std::unexpected{make_error("profile discovery protocol version mismatch")};
}
if (get_str(*root, "request_id").value_or("") != req_id) {
return std::unexpected{make_error("profile discovery request_id mismatch")};
}
const auto *payload_v = find_key(*root, "payload");
const auto *payload = payload_v ? std::get_if<JsonVal::Object>(&payload_v->value) : nullptr;
if (!payload) {
return std::unexpected{make_error("profile discovery missing payload")};
}
const auto *profs_v = find_key(*payload, "profiles");
const auto *arr = profs_v ? std::get_if<JsonVal::Array>(&profs_v->value) : nullptr;
if (!arr) {
return std::unexpected{make_error("profile discovery payload missing profiles array")};
}
try {
Profiles result;
for (const auto &pv : *arr) {
const auto *po = std::get_if<JsonVal::Object>(&pv.value);
if (!po) {
continue;
}
ProfileDescription pd;
pd.name = get_str(*po, "name").value_or("");
if (auto parent = get_str(*po, "parent"); parent && !parent->empty()) {
pd.parent = *parent;
}
if (auto comp = get_str(*po, "compiler"); comp && !comp->empty()) {
pd.compiler = parse_compiler(*comp);
}
if (auto std_str = get_str(*po, "c_standard"); std_str && !std_str->empty()) {
pd.c_standard = Void::Build::parse_c_standard(*std_str);
}
if (auto std_str = get_str(*po, "cxx_standard"); std_str && !std_str->empty()) {
pd.cxx_standard = parse_cxx_standard(*std_str);
}
if (auto lto_str = get_str(*po, "lto"); lto_str && !lto_str->empty()) {
pd.lto = parse_lto_mode(*lto_str);
}
pd.sysroot = get_str(*po, "sysroot").value_or("");
pd.compiler_path = get_str(*po, "compiler_path").value_or("");
if (auto ep = get_i64(*po, "reproducibility_epoch")) {
pd.reproducibility_epoch = *ep;
}
if (const auto *nd = find_key(*po, "nondeterministic")) {
if (const auto *b = std::get_if<bool>(&nd->value)) {
pd.nondeterministic = *b;
}
}
pd.compile_options = get_str_array(*po, "compile_options");
pd.link_options = get_str_array(*po, "link_options");
pd.defines = get_str_array(*po, "defines");
for (const auto &s : get_str_array(*po, "sanitizers")) {
pd.sanitizers.push_back(parse_sanitizer(s));
}
result.define(std::move(pd));
}
return result;
} catch (const std::exception &ex) {
return std::unexpected{make_error(ex.what())};
}
}
Void::Result::Result<Graph::ProjectDescription, Void::Result::Error>
evaluate_project(const CompiledDescriptor &descriptor, const ProfileContext &context,
const FrontendOptions &options) {
std::error_code ec;
const auto run_dir =
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval";
std::filesystem::create_directories(run_dir, ec);
const std::string req_id = std::format("desc_{}_{}", static_cast<long long>(::getpid()),
g_req_seq.fetch_add(1, std::memory_order_relaxed));
const auto ctx_file = run_dir / (req_id + ".ctx");
const auto out_file = run_dir / (req_id + ".json");
const std::string kv_text = serialize_kv_context(context);
const std::string ctx_hash = Util::sha256_hex(kv_text);
if (auto wrote = Platform::atomic_write_file(ctx_file, kv_text, false); !wrote) {
return std::unexpected{wrote.error()};
}
auto cleanup = [&] {
std::filesystem::remove(ctx_file, ec);
std::filesystem::remove(out_file, ec);
};
Platform::ProcessRequest req;
req.executable = descriptor.executable_path;
req.arguments = {"--mode", "describe", "--output", out_file.string(),
"--request-id", req_id, "--context-file", ctx_file.string(),
"--context-hash", ctx_hash};
req.working_directory = options.project_root;
req.timeout = options.eval_timeout;
auto proc = Platform::run_supervised(req);
if (!proc) {
cleanup();
return std::unexpected{proc.error()};
}
if (!proc->succeeded()) {
cleanup();
return std::unexpected{make_error(
std::format("project evaluation failed for profile '{}' (exit={}, signal={}): {}",
context.name, proc->exit_code, proc->term_signal, proc->stderr_data))};
}
auto text = Void::FileSystem::read_file_bounded(out_file, {64ULL * 1024ULL * 1024ULL});
cleanup();
if (!text) {
return std::unexpected{make_error("project evaluation did not produce a result file")};
}
if (!Util::is_valid_utf8(*text)) {
return std::unexpected{make_error("project evaluation result contains invalid UTF-8")};
}
// Validate envelope header fields cleanly, then slice out payload JSON directly.
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return std::unexpected{make_error("project evaluation emitted malformed JSON")};
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error("project evaluation envelope must be a JSON object")};
}
if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) {
return std::unexpected{make_error("project evaluation protocol version mismatch")};
}
if (get_str(*root, "request_id").value_or("") != req_id) {
return std::unexpected{make_error("project evaluation request_id mismatch")};
}
if (get_str(*root, "context_hash").value_or("") != ctx_hash) {
return std::unexpected{make_error("project evaluation context_hash mismatch")};
}
const auto payload_marker = text->find("\"payload\":");
if (payload_marker == std::string::npos) {
return std::unexpected{make_error("project evaluation envelope missing payload")};
}
std::string_view payload_slice{*text};
payload_slice.remove_prefix(payload_marker + 10);
while (!payload_slice.empty() &&
(payload_slice.back() == '\n' || payload_slice.back() == '\r' ||
payload_slice.back() == ' ')) {
payload_slice.remove_suffix(1);
}
if (payload_slice.empty() || payload_slice.back() != '}') {
return std::unexpected{make_error("project evaluation envelope truncated")};
}
payload_slice.remove_suffix(1); // Remove enclosing envelope '}'
auto desc = Graph::ProjectDescription::from_json(payload_slice);
if (!desc) {
return std::unexpected{desc.error()};
}
if (desc->profile.name != context.name || desc->profile.compiler != context.compiler) {
return std::unexpected{
make_error("project evaluation returned a mismatched profile context")};
}
return desc;
}
Void::Result::Result<WorkspaceDescription, Void::Result::Error>
evaluate_workspace(const CompiledDescriptor &descriptor, const FrontendOptions &options) {
std::error_code ec;
const auto run_dir =
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval";
std::filesystem::create_directories(run_dir, ec);
const std::string req_id = std::format("ws_{}_{}", static_cast<long long>(::getpid()),
g_req_seq.fetch_add(1, std::memory_order_relaxed));
const auto out_file = run_dir / (req_id + ".json");
Platform::ProcessRequest req;
req.executable = descriptor.executable_path;
req.arguments = {"--mode", "workspace", "--output", out_file.string(), "--request-id", req_id};
req.working_directory = options.project_root;
req.timeout = options.eval_timeout;
auto proc = Platform::run_supervised(req);
auto cleanup = [&] { std::filesystem::remove(out_file, ec); };
if (!proc) {
cleanup();
return std::unexpected{proc.error()};
}
if (!proc->succeeded()) {
cleanup();
return std::unexpected{
make_error(std::format("workspace evaluation failed (exit={}, signal={}): {}",
proc->exit_code, proc->term_signal, proc->stderr_data))};
}
auto text = Void::FileSystem::read_file_bounded(out_file, {16ULL * 1024ULL * 1024ULL});
cleanup();
if (!text) {
return std::unexpected{make_error("workspace evaluation did not produce a result file")};
}
if (!Util::is_valid_utf8(*text)) {
return std::unexpected{make_error("workspace evaluation result contains invalid UTF-8")};
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return std::unexpected{make_error("workspace evaluation emitted malformed JSON")};
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error("workspace evaluation envelope must be a JSON object")};
}
if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) {
return std::unexpected{make_error("workspace evaluation protocol version mismatch")};
}
if (get_str(*root, "request_id").value_or("") != req_id) {
return std::unexpected{make_error("workspace evaluation request_id mismatch")};
}
const auto *payload_v = find_key(*root, "payload");
const auto *payload = payload_v ? std::get_if<JsonVal::Object>(&payload_v->value) : nullptr;
if (!payload) {
return std::unexpected{make_error("workspace evaluation missing payload")};
}
const auto *members_v = find_key(*payload, "members");
const auto *arr = members_v ? std::get_if<JsonVal::Array>(&members_v->value) : nullptr;
if (!arr) {
return std::unexpected{make_error("workspace evaluation payload missing members array")};
}
WorkspaceDescription result;
std::set<std::string> seen;
for (const auto &mv : *arr) {
const auto *mobj = std::get_if<JsonVal::Object>(&mv.value);
if (!mobj) {
continue;
}
WorkspaceMember member;
member.name = get_str(*mobj, "name").value_or("");
member.path = get_str(*mobj, "path").value_or("");
if (member.name.empty() || member.path.empty()) {
return std::unexpected{make_error("workspace member requires nonempty name and path")};
}
if (!seen.insert(member.name).second) {
return std::unexpected{make_error("duplicate workspace member '" + member.name + "'")};
}
result.members.push_back(std::move(member));
}
return result;
}
} // namespace Void::Build::Config