#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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(&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(&v->value); return b ? *b : def; } std::vector get_str_array(const JsonVal::Object &obj, const std::string &k) { std::vector out; const auto *v = find_key(obj, k); if (!v) { return out; } if (const auto *arr = std::get_if(&v->value)) { for (const auto &item : *arr) { if (const auto *s = std::get_if(&item.value)) { out.push_back(*s); } } } return out; } std::optional 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 serialize_export(const ProviderExport &exp) { using Util::json_array; using Util::json_quote; std::string out = "{\"schema_version\":1,\"dependency_name\":" + json_quote(exp.dependency_name) + ",\"builder\":" + json_quote(exp.builder) + ",\"input_identity_hash\":" + json_quote(exp.input_identity_hash) + ",\"targets\":{"; bool first = true; for (const auto &[tname, iface] : exp.targets) { if (!first) { out += ','; } first = false; out += json_quote(tname) + ":{\"dependency_name\":" + json_quote(iface.dependency_name) + ",\"target_name\":" + json_quote(iface.target_name) + ",\"include_dirs\":" + json_array(iface.include_dirs, [](const std::pair &inc) { return "{\"path\":" + json_quote(inc.first.string()) + ",\"is_system\":" + std::string{inc.second ? "true" : "false"} + '}'; }) + ",\"defines\":" + json_array(iface.defines, json_quote) + ",\"compile_options\":" + json_array(iface.compile_options, json_quote) + ",\"link_options\":" + json_array(iface.link_options, json_quote) + ",\"static_libraries\":" + json_array(iface.static_libraries, [](const std::filesystem::path &p) { return json_quote(p.string()); }) + ",\"shared_libraries\":" + json_array(iface.shared_libraries, [](const std::filesystem::path &p) { return json_quote(p.string()); }) + ",\"runtime_files\":" + json_array(iface.runtime_files, [](const std::filesystem::path &p) { return json_quote(p.string()); }) + ",\"module_bmis\":{"; bool first_mod = true; for (const auto &[mname, bmi_p] : iface.module_bmis) { if (!first_mod) { out += ','; } first_mod = false; out += json_quote(mname) + ':' + json_quote(bmi_p.string()); } out += "}}"; } out += "}}\n"; return out; } std::optional load_cached_export(const std::filesystem::path &export_file, std::string_view expected_hash) { auto text = Void::FileSystem::read_file(export_file); if (!text) { return std::nullopt; } auto parsed = Void::Json::Strict::parse(*text); if (!parsed) { return std::nullopt; } const auto *root = std::get_if(&parsed->value); if (!root) { return std::nullopt; } if (get_str(*root, "input_identity_hash") != expected_hash) { return std::nullopt; } ProviderExport exp; exp.dependency_name = get_str(*root, "dependency_name"); exp.builder = get_str(*root, "builder"); exp.input_identity_hash = std::string{expected_hash}; exp.from_cache = true; if (const auto *tv = find_key(*root, "targets")) { if (const auto *tobj = std::get_if(&tv->value)) { for (const auto &[k, val] : *tobj) { const auto *io = std::get_if(&val.value); if (!io) { continue; } Graph::ImportedTargetInterface iface; iface.dependency_name = get_str(*io, "dependency_name"); iface.target_name = get_str(*io, "target_name"); if (const auto *iv = find_key(*io, "include_dirs")) { if (const auto *iarr = std::get_if(&iv->value)) { for (const auto &item : *iarr) { if (const auto *inc = std::get_if(&item.value)) { iface.include_dirs.emplace_back(get_str(*inc, "path"), get_bool(*inc, "is_system", false)); } } } } iface.defines = get_str_array(*io, "defines"); iface.compile_options = get_str_array(*io, "compile_options"); iface.link_options = get_str_array(*io, "link_options"); for (const auto &s : get_str_array(*io, "static_libraries")) { iface.static_libraries.emplace_back(s); } for (const auto &s : get_str_array(*io, "shared_libraries")) { iface.shared_libraries.emplace_back(s); } for (const auto &s : get_str_array(*io, "runtime_files")) { iface.runtime_files.emplace_back(s); } if (const auto *mv = find_key(*io, "module_bmis")) { if (const auto *mobj = std::get_if(&mv->value)) { for (const auto &[mname, mval] : *mobj) { if (const auto *ms = std::get_if(&mval.value)) { iface.module_bmis.emplace(mname, *ms); } } } } // Verify materialized library and BMI artifacts still exist on disk! std::error_code ec; for (const auto &lib : iface.static_libraries) { if (!std::filesystem::is_regular_file(lib, ec)) { return std::nullopt; } } for (const auto &lib : iface.shared_libraries) { if (!std::filesystem::is_regular_file(lib, ec)) { return std::nullopt; } } for (const auto &[mname, bmi_p] : iface.module_bmis) { (void)mname; if (!std::filesystem::is_regular_file(bmi_p, ec)) { return std::nullopt; } } exp.targets[k] = std::move(iface); } } } return exp; } std::string cmake_option_value(const OptionValue &v) { return std::visit( [](const auto &inner) -> std::string { using T = std::remove_cvref_t; if constexpr (std::same_as) { return inner; } else if constexpr (std::same_as) { return inner ? "ON" : "OFF"; } else { return std::to_string(inner); } }, v.value); } std::string meson_option_value(const OptionValue &v) { return std::visit( [](const auto &inner) -> std::string { using T = std::remove_cvref_t; if constexpr (std::same_as) { return inner; } else if constexpr (std::same_as) { return inner ? "true" : "false"; } else { return std::to_string(inner); } }, v.value); } // Imports CMake File API reply (index-*.json -> codemodel-v2 -> target-*.json). Void::Result::Result run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &build_dir, const std::string &input_hash, 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 provider requires 'cmake' in PATH")}; } std::error_code ec; // Fresh build dir whenever input hash changed so foreign timestamp shortcuts cannot retain // stale objects (Plan 13 acceptance #3). std::filesystem::remove_all(build_dir, ec); std::filesystem::create_directories(build_dir / ".cmake" / "api" / "v1" / "query", ec); (void)Platform::atomic_write_file( build_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false); // 1. Configure with isolated profile/toolchain context. const auto sw = Void::Time::Stopwatch::started(); Void::Log::info("Provider", "Configuring CMake dependency '{}' (profile='{}')...", request.dependency.name, request.profile.name); { Platform::ProcessRequest req; req.executable = *cmake_bin; req.arguments = {"-S", request.source.source_dir.string(), "-B", build_dir.string()}; if (Platform::resolve_executable("ninja").has_value()) { req.arguments.push_back("-G"); req.arguments.push_back("Ninja"); } if (!request.toolchain.c_compiler.empty()) { req.arguments.push_back("-DCMAKE_C_COMPILER=" + request.toolchain.c_compiler.string()); } req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string()); const std::string cfg = (request.profile.name == "release" || request.profile.name == "Release") ? "Release" : "Debug"; req.arguments.push_back("-DCMAKE_BUILD_TYPE=" + cfg); for (const auto &[k, v] : request.dependency.options) { req.arguments.push_back("-D" + k + "=" + cmake_option_value(v)); } req.timeout = std::chrono::seconds{180}; if (Void::Log::enabled(Void::Log::Level::Debug, "Provider")) { req.on_stdout_chunk = [&](std::string_view line) { Void::Log::debug("Provider", "[cmake:{}] {}", request.dependency.name, line); }; req.on_stderr_chunk = [&](std::string_view line) { Void::Log::debug("Provider", "[cmake:{}] {}", request.dependency.name, line); }; } 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()))}; } } // 2. Build all targets in isolated build directory. Void::Log::info("Provider", "Building CMake dependency '{}'...", request.dependency.name); { Platform::ProcessRequest req; req.executable = *cmake_bin; req.arguments = {"--build", build_dir.string(), "--parallel"}; req.timeout = std::chrono::seconds{300}; if (Void::Log::enabled(Void::Log::Level::Debug, "Provider")) { req.on_stdout_chunk = [&](std::string_view line) { Void::Log::debug("Provider", "[build:{}] {}", request.dependency.name, line); }; req.on_stderr_chunk = [&](std::string_view line) { Void::Log::debug("Provider", "[build:{}] {}", request.dependency.name, line); }; } auto proc = Platform::run_supervised(req, stop); if (!proc || !proc->succeeded()) { return std::unexpected{ make_error(Void::System::SystemErrorCode::io_error, std::format("CMake build failed for '{}':\n{}", request.dependency.name, proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))}; } } // 3. Parse CMake File API reply -> codemodel-v2 -> per-target metadata. const auto reply_dir = build_dir / ".cmake" / "api" / "v1" / "reply"; std::filesystem::path index_file; for (const auto &ent : std::filesystem::directory_iterator(reply_dir, ec)) { if (ent.is_regular_file() && ent.path().filename().string().starts_with("index-")) { index_file = ent.path(); } } if (index_file.empty()) { return std::unexpected{make_error( Void::System::SystemErrorCode::io_error, std::format("CMake File API reply missing for '{}'", request.dependency.name))}; } auto index_json = parse_json_file(index_file); 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(&index_json->value); std::string codemodel_file; if (idx_obj) { if (const auto *objs = find_key(*idx_obj, "objects")) { if (const auto *arr = std::get_if(&objs->value)) { for (const auto &item : *arr) { if (const auto *o = std::get_if(&item.value)) { if (get_str(*o, "kind") == "codemodel") { codemodel_file = get_str(*o, "jsonFile"); break; } } } } } } if (codemodel_file.empty()) { return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, "CMake File API index missing codemodel object")}; } auto cm_json = parse_json_file(reply_dir / codemodel_file); if (!cm_json) { return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, "failed parsing CMake codemodel JSON")}; } struct RawTarget { std::string id; std::string name; std::string type; std::vector dep_ids; Graph::ImportedTargetInterface iface; }; std::map> raw_by_id; if (const auto *cm_obj = std::get_if(&cm_json->value)) { if (const auto *cfgs = find_key(*cm_obj, "configurations")) { if (const auto *carr = std::get_if(&cfgs->value); carr && !carr->empty()) { if (const auto *cfg0 = std::get_if(&carr->front().value)) { if (const auto *tgts = find_key(*cfg0, "targets")) { if (const auto *tarr = std::get_if(&tgts->value)) { for (const auto &tv : *tarr) { const auto *to = std::get_if(&tv.value); if (!to) { continue; } const auto tfile = get_str(*to, "jsonFile"); auto tjson = parse_json_file(reply_dir / tfile); if (!tjson) { continue; } const auto *td = std::get_if(&tjson->value); if (!td) { continue; } RawTarget rt; rt.id = get_str(*td, "id"); rt.name = get_str(*td, "name"); rt.type = get_str(*td, "type"); rt.iface.dependency_name = request.dependency.name; rt.iface.target_name = rt.name; // Extract artifacts. if (const auto *arts = find_key(*td, "artifacts")) { if (const auto *aarr = std::get_if(&arts->value)) { for (const auto &av : *aarr) { if (const auto *ao = std::get_if(&av.value)) { const auto p = build_dir / get_str(*ao, "path"); if (rt.type == "STATIC_LIBRARY") { rt.iface.static_libraries.push_back(p); } else if (rt.type == "SHARED_LIBRARY") { rt.iface.shared_libraries.push_back(p); rt.iface.runtime_files.push_back(p); } } } } } // Extract compile groups (includes, defines). if (const auto *cgs = find_key(*td, "compileGroups")) { if (const auto *cgarr = std::get_if(&cgs->value)) { for (const auto &cgv : *cgarr) { const auto *cgo = std::get_if(&cgv.value); if (!cgo) { continue; } if (const auto *incs = find_key(*cgo, "includes")) { if (const auto *iarr = std::get_if(&incs->value)) { for (const auto &iv : *iarr) { if (const auto *io = std::get_if( &iv.value)) { const std::filesystem::path ip{ get_str(*io, "path")}; const bool sys = get_bool(*io, "isSystem", false); if (!std::ranges::contains( rt.iface.include_dirs, std::pair{ip, sys})) { rt.iface.include_dirs.emplace_back( ip, sys); } } } } } if (const auto *defs = find_key(*cgo, "defines")) { if (const auto *darr = std::get_if(&defs->value)) { for (const auto &dv : *darr) { if (const auto *do_obj = std::get_if( &dv.value)) { const auto d = get_str(*do_obj, "define"); if (!d.empty() && !std::ranges::contains( rt.iface.defines, d)) { rt.iface.defines.push_back(d); } } } } } } } } // Extract link command fragments (-pthread, -ldl, -lm, etc.). if (const auto *lnk = find_key(*td, "link")) { if (const auto *lobj = std::get_if(&lnk->value)) { if (const auto *frags = find_key(*lobj, "commandFragments")) { if (const auto *farr = std::get_if(&frags->value)) { for (const auto &fv : *farr) { const auto *fo = std::get_if(&fv.value); if (!fo) { continue; } const auto role = get_str(*fo, "role"); const auto frag = get_str(*fo, "fragment"); if ((role == "libraries" || role == "flags") && (frag == "-pthread" || frag == "-lpthread" || frag == "-ldl" || frag == "-lm" || frag == "-lrt")) { if (!std::ranges::contains( rt.iface.link_options, frag)) { rt.iface.link_options.push_back(frag); } } } } } } } // Extract dependencies for transitive static archive ordering. if (const auto *deps = find_key(*td, "dependencies")) { if (const auto *darr = std::get_if(&deps->value)) { for (const auto &dv : *darr) { if (const auto *do_obj = std::get_if(&dv.value)) { rt.dep_ids.push_back(get_str(*do_obj, "id")); } } } } raw_by_id[rt.id] = std::move(rt); } } } } } } } // Resolve transitive static library link order across CMake targets using post-order DFS // reversed so every dependent library strictly precedes all of its dependencies on `ld`. ProviderExport exp; exp.dependency_name = request.dependency.name; exp.builder = "cmake"; exp.input_identity_hash = input_hash; for (const auto &[id, rt] : raw_by_id) { Graph::ImportedTargetInterface resolved = rt.iface; std::vector post_order; std::set visited; auto dfs = [&](auto &&self, const std::string &cur_id) -> void { if (!visited.insert(cur_id).second) { return; } const auto dit = raw_by_id.find(cur_id); if (dit == raw_by_id.end()) { return; } for (const auto &sub : dit->second.dep_ids) { self(self, sub); } post_order.push_back(cur_id); }; for (const auto &dep_id : rt.dep_ids) { dfs(dfs, dep_id); } std::ranges::reverse(post_order); for (const auto &dep_id : post_order) { const auto &dep_rt = raw_by_id.at(dep_id); for (const auto &lib : dep_rt.iface.static_libraries) { if (!std::ranges::contains(resolved.static_libraries, lib)) { resolved.static_libraries.push_back(lib); } } for (const auto &lib : dep_rt.iface.shared_libraries) { if (!std::ranges::contains(resolved.shared_libraries, lib)) { resolved.shared_libraries.push_back(lib); } } for (const auto &inc : dep_rt.iface.include_dirs) { if (!std::ranges::contains(resolved.include_dirs, inc)) { resolved.include_dirs.push_back(inc); } } for (const auto &def : dep_rt.iface.defines) { if (!std::ranges::contains(resolved.defines, def)) { resolved.defines.push_back(def); } } for (const auto &lo : dep_rt.iface.link_options) { if (!std::ranges::contains(resolved.link_options, lo)) { resolved.link_options.push_back(lo); } } } // CMake targets linking Threads::Threads on GCC need -pthread at final link time. if ((rt.name.starts_with("Void_") || request.dependency.name == "VoidLibrary") && !std::ranges::contains(resolved.link_options, std::string{"-pthread"})) { resolved.link_options.push_back("-pthread"); } exp.targets[rt.name] = resolved; exp.targets[request.dependency.name + "::" + rt.name] = resolved; // Register CMake `Namespace::Component` alias convention (e.g. `Void_Configuration` -> // `Void::Configuration`) because CMake File API codemodel-v2 omits ALIAS targets. if (const auto us = rt.name.find('_'); us != std::string::npos && us > 0) { const std::string alias = rt.name.substr(0, us) + "::" + rt.name.substr(us + 1); exp.targets[alias] = resolved; exp.targets[request.dependency.name + "::" + alias] = resolved; } } // CMake File API codemodel-v2 omits INTERFACE (header-only) libraries. For VoidLibrary, // synthesize `Void::` interfaces for any module directory under `src/` that CMake // configured as header-only (e.g. Text, Unicode, Async, Algorithms, Core, Data, Time, // Functional), propagating compiled `INTERNAL_DEPS` (such as LogState) automatically. if (request.dependency.name == "VoidLibrary" && std::filesystem::is_directory(request.source.source_dir / "include", ec) && std::filesystem::is_directory(request.source.source_dir / "src", ec)) { std::vector hdr_mods; for (const auto &entry : std::filesystem::directory_iterator(request.source.source_dir / "src", ec)) { if (!entry.is_directory(ec)) { continue; } const std::string mod = entry.path().filename().string(); const std::string alias = "Void::" + mod; if (!exp.targets.contains(alias)) { hdr_mods.push_back(mod); Graph::ImportedTargetInterface hi; hi.dependency_name = request.dependency.name; hi.target_name = alias; hi.include_dirs.emplace_back(request.source.source_dir / "include", false); hi.link_options.push_back("-pthread"); exp.targets[alias] = hi; exp.targets[request.dependency.name + "::" + alias] = std::move(hi); } } // Attach compiled INTERNAL_DEPS (e.g. Void_LogState for Async/Log) to synthesized // header-only targets so linking any header-only Void module standalone works cleanly. for (const auto &mod : hdr_mods) { const auto mod_cmake = request.source.source_dir / "src" / mod / "module.cmake"; if (!std::filesystem::is_regular_file(mod_cmake, ec)) { continue; } auto text = Void::FileSystem::read_file(mod_cmake); if (!text) { continue; } const auto pos = text->find("INTERNAL_DEPS"); if (pos == std::string::npos) { continue; } const std::string alias = "Void::" + mod; auto &hi = exp.targets[alias]; const std::string_view rest = std::string_view{*text}.substr(pos + 13); std::size_t idx = 0; while (idx < rest.size()) { while (idx < rest.size() && (rest[idx] == ' ' || rest[idx] == '\t' || rest[idx] == '\r' || rest[idx] == '\n')) { ++idx; } if (idx >= rest.size() || rest[idx] == ')') { break; } const std::size_t start = idx; while (idx < rest.size() && rest[idx] != ' ' && rest[idx] != '\t' && rest[idx] != '\r' && rest[idx] != '\n' && rest[idx] != ')') { ++idx; } const std::string dep_name{rest.substr(start, idx - start)}; if (dep_name == "EXTERNAL_DEPS" || dep_name == "OPTIONAL_DEPS" || dep_name == "DEPS_WIN32" || dep_name == "DEPS_UNIX" || dep_name == "OPTIONS_WIN32" || dep_name == "OPTIONS_UNIX" || dep_name == "EXTRA_HEADERS" || dep_name == "EXCLUDE_HEADERS") { break; } const auto dit = exp.targets.find("Void::" + dep_name); if (dit != exp.targets.end()) { for (const auto &lib : dit->second.static_libraries) { if (!std::ranges::contains(hi.static_libraries, lib)) { hi.static_libraries.push_back(lib); } } for (const auto &def : dit->second.defines) { if (!std::ranges::contains(hi.defines, def)) { hi.defines.push_back(def); } } } } exp.targets[request.dependency.name + "::" + alias] = hi; } } Void::Log::info("Provider", "CMake dependency '{}' ready ({} targets in {}ms)", request.dependency.name, exp.targets.size(), sw.elapsed_as().count()); // Apply explicit user overrides if supplied. for (const auto &[k, v] : request.explicit_overrides) { exp.targets[k] = v; } return exp; } // Imports Meson introspection metadata (`meson-info/intro-targets.json`). Void::Result::Result run_meson_provider(const ProviderRequest &request, const std::filesystem::path &build_dir, const std::string &input_hash, std::stop_token stop) { auto meson_bin = Platform::resolve_executable("meson"); if (!meson_bin) { return std::unexpected{make_error(Void::System::SystemErrorCode::not_found, "Meson provider requires 'meson' in PATH")}; } std::error_code ec; std::filesystem::remove_all(build_dir, ec); std::filesystem::create_directories(build_dir.parent_path(), ec); { Platform::ProcessRequest req; req.executable = *meson_bin; req.arguments = {"setup", build_dir.string(), request.source.source_dir.string()}; const std::string btype = (request.profile.name == "release" || request.profile.name == "Release") ? "release" : "debug"; req.arguments.push_back("-Dbuildtype=" + btype); for (const auto &[k, v] : request.dependency.options) { req.arguments.push_back("-D" + k + "=" + meson_option_value(v)); } if (!request.toolchain.c_compiler.empty()) { req.environment.set_vars["CC"] = request.toolchain.c_compiler.string(); } req.environment.set_vars["CXX"] = request.toolchain.cxx_compiler.string(); 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("Meson setup failed for '{}':\n{}", request.dependency.name, proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))}; } } { Platform::ProcessRequest req; req.executable = *meson_bin; req.arguments = {"compile", "-C", build_dir.string()}; req.timeout = std::chrono::seconds{300}; auto proc = Platform::run_supervised(req, stop); if (!proc || !proc->succeeded()) { return std::unexpected{make_error( Void::System::SystemErrorCode::io_error, std::format("Meson compile failed for '{}':\n{}", request.dependency.name, proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))}; } } const auto intro_targets = build_dir / "meson-info" / "intro-targets.json"; auto parsed = parse_json_file(intro_targets); if (!parsed) { return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, "failed parsing Meson intro-targets.json")}; } ProviderExport exp; exp.dependency_name = request.dependency.name; exp.builder = "meson"; exp.input_identity_hash = input_hash; if (const auto *arr = std::get_if(&parsed->value)) { for (const auto &tv : *arr) { const auto *to = std::get_if(&tv.value); if (!to) { continue; } const auto tname = get_str(*to, "name"); const auto ttype = get_str(*to, "type"); Graph::ImportedTargetInterface iface; iface.dependency_name = request.dependency.name; iface.target_name = tname; for (const auto &fname : get_str_array(*to, "filename")) { if (ttype == "static library") { iface.static_libraries.emplace_back(fname); } else if (ttype == "shared library") { iface.shared_libraries.emplace_back(fname); iface.runtime_files.emplace_back(fname); } } // Collect include directories from target_sources parameters (-I...) plus source // include/. if (const auto *ts = find_key(*to, "target_sources")) { if (const auto *tsarr = std::get_if(&ts->value)) { for (const auto &tsv : *tsarr) { if (const auto *tso = std::get_if(&tsv.value)) { const auto params = get_str_array(*tso, "parameters"); for (std::size_t i = 0; i < params.size(); ++i) { if (params[i].starts_with("-I") && params[i].size() > 2) { std::filesystem::path p{params[i].substr(2)}; if (!p.is_absolute()) { p = (build_dir / p).lexically_normal(); } if (!std::ranges::contains(iface.include_dirs, std::pair{p, false})) { iface.include_dirs.emplace_back(p, false); } } else if (params[i] == "-I" && i + 1 < params.size()) { std::filesystem::path p{params[++i]}; if (!p.is_absolute()) { p = (build_dir / p).lexically_normal(); } if (!std::ranges::contains(iface.include_dirs, std::pair{p, false})) { iface.include_dirs.emplace_back(p, false); } } } } } } } if (std::filesystem::is_directory(request.source.source_dir / "include", ec)) { const auto inc = (request.source.source_dir / "include").lexically_normal(); if (!std::ranges::contains(iface.include_dirs, std::pair{inc, false})) { iface.include_dirs.emplace_back(inc, false); } } exp.targets[tname] = iface; exp.targets[request.dependency.name + "::" + tname] = iface; } } for (const auto &[k, v] : request.explicit_overrides) { exp.targets[k] = v; } return exp; } Void::Result::Result run_conan_provider(const ProviderRequest &request, const std::filesystem::path &build_dir, const std::string &input_hash, std::stop_token stop) { auto conan_bin = Platform::resolve_executable("conan"); if (!conan_bin) { return std::unexpected{ make_error(Void::System::SystemErrorCode::not_found, std::format("Conan2 provider requires 'conan' in PATH for dependency '{}' " "(prerequisite missing; refusing empty import)", request.dependency.name))}; } std::error_code ec; std::filesystem::create_directories(build_dir, ec); const auto host_profile = build_dir / "conan_host.profile"; const auto build_profile = build_dir / "conan_build.profile"; const std::string btype = (request.profile.name == "release" || request.profile.name == "Release") ? "Release" : "Debug"; const std::string prof_text = std::format("[settings]\nos={}\narch={}\ncompiler={}\nbuild_type={}\n", request.profile.os, request.profile.architecture, compiler_name(request.profile.compiler), btype); (void)Platform::atomic_write_file(host_profile, prof_text, false); (void)Platform::atomic_write_file(build_profile, prof_text, false); Platform::ProcessRequest req; req.executable = *conan_bin; req.arguments = {"install", "--requires", request.dependency.package, "--profile:host", host_profile.string(), "--profile:build", build_profile.string(), "--output-folder", build_dir.string(), "--format", "json"}; req.timeout = std::chrono::seconds{300}; auto proc = Platform::run_supervised(req, stop); if (!proc || !proc->succeeded()) { return std::unexpected{ make_error(Void::System::SystemErrorCode::io_error, std::format("Conan2 install failed for '{}':\n{}", request.dependency.name, proc ? proc->stderr_data : proc.error().message()))}; } ProviderExport exp; exp.dependency_name = request.dependency.name; exp.builder = "conan"; exp.input_identity_hash = input_hash; for (const auto &[k, v] : request.explicit_overrides) { exp.targets[k] = v; } return exp; } std::vector parse_void_modules_option(const OptionMap &options) { std::vector mods; const auto it = options.find("VOID_ENABLED_MODULES"); if (it != options.end()) { const std::string raw = cmake_option_value(it->second); std::size_t pos = 0; while (pos < raw.size()) { const auto sep = raw.find_first_of(";,", pos); std::string_view token = sep == std::string::npos ? std::string_view{raw}.substr(pos) : std::string_view{raw}.substr(pos, sep - pos); while (!token.empty() && (token.front() == ' ' || token.front() == '\t' || token.front() == '\r' || token.front() == '\n')) { token.remove_prefix(1); } while (!token.empty() && (token.back() == ' ' || token.back() == '\t' || token.back() == '\r' || token.back() == '\n')) { token.remove_suffix(1); } if (!token.empty()) { mods.emplace_back(token); } if (sep == std::string::npos) { break; } pos = sep + 1; } } if (mods.empty()) { mods = {"Configuration", "Text", "Unicode", "Async", "Algorithms", "Crypto", "Archive", "Testing"}; } return mods; } std::pair, std::vector> collect_native_dep_snapshot_inputs(const Graph::ProjectDescription &desc, const std::filesystem::path &project_root) { std::error_code ec; const auto canon_root = std::filesystem::weakly_canonical(project_root, ec); const auto &root = ec ? project_root : canon_root; std::set root_dirs; std::set files; auto add_dir_if_in_project = [&](const std::filesystem::path &dir) { std::error_code dec; const auto norm = dir.lexically_normal(); if (std::filesystem::is_directory(norm, dec) && Platform::path_is_within(root, norm) && norm != root) { root_dirs.insert(norm); } }; for (const char *d : {"src", "source", "include", "tests"}) { add_dir_if_in_project(root / d); } auto is_gen_ref = [](std::string_view p) { return p.starts_with("$GEN/") || p.starts_with("gen/"); }; for (const auto &t : desc.targets) { for (const auto &inc : t.include_directories) { if (!is_gen_ref(inc.path)) { const std::filesystem::path p{inc.path}; add_dir_if_in_project(p.is_absolute() ? p : (root / p)); } } for (const auto &src : t.sources) { if (is_gen_ref(src.path)) { continue; } if (src.kind == SourceKind::File || src.kind == SourceKind::ModuleInterface || src.kind == SourceKind::ModulePartition || src.kind == SourceKind::HeaderUnit) { const std::filesystem::path p{src.path}; const auto abs = (p.is_absolute() ? p : (root / p)).lexically_normal(); if (std::filesystem::is_regular_file(abs, ec)) { files.insert(abs); if (abs.has_parent_path()) { add_dir_if_in_project(abs.parent_path()); } } } else if (src.kind == SourceKind::Glob) { const auto star = src.path.find_first_of("*?["); const std::string_view prefix = star == std::string::npos ? std::string_view{src.path} : std::string_view{src.path}.substr(0, star); const auto slash = prefix.rfind('/'); if (slash != std::string_view::npos && slash > 0) { add_dir_if_in_project(root / std::filesystem::path{prefix.substr(0, slash)}); } } } for (const auto &in : t.action_inputs) { if (!is_gen_ref(in)) { const std::filesystem::path p{in}; const auto abs = (p.is_absolute() ? p : (root / p)).lexically_normal(); if (std::filesystem::is_regular_file(abs, ec)) { files.insert(abs); } } } } std::vector scan_roots; for (const auto &d : root_dirs) { bool covered = false; for (const auto &other : root_dirs) { if (other != d && Platform::path_is_within(other, d)) { covered = true; break; } } if (!covered) { scan_roots.push_back(d); } } std::vector explicit_files; for (const auto &f : files) { bool covered = false; for (const auto &d : scan_roots) { if (Platform::path_is_within(d, f)) { covered = true; break; } } if (!covered) { explicit_files.push_back(f); } } return {std::move(explicit_files), std::move(scan_roots)}; } Void::Result::Result run_native_provider(const ProviderRequest &request, const std::filesystem::path &build_dir, const std::string &input_hash, std::stop_token stop) { std::error_code ec; std::filesystem::remove_all(build_dir, ec); std::filesystem::create_directories(build_dir, ec); Graph::ProjectDescription desc; std::optional snap; const auto &src_dir = request.source.source_dir; const bool has_build_cpp = std::filesystem::is_regular_file(src_dir / "build.cpp", ec); const bool is_void_library = std::filesystem::is_directory(src_dir / "include" / "Void", ec) && std::filesystem::is_directory(src_dir / "src" / "Core", ec); if (has_build_cpp) { if (request.sdk_include_dir.empty() && request.sdk_source_dir.empty() && !request.sdk_library_path) { return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, "native subproject builder requires VBS SDK " "include/source paths in ProviderRequest")}; } Void::Log::info("Provider", "Evaluating native subproject '{}' (profile='{}')...", request.dependency.name, request.profile.name); Config::FrontendOptions fopts; fopts.project_root = src_dir; fopts.build_root = build_dir; fopts.sdk_include_dir = request.sdk_include_dir; fopts.sdk_source_dir = request.sdk_source_dir; if (request.sdk_library_path) { fopts.sdk_library_path = *request.sdk_library_path; } auto compiled = Config::compile_descriptor(fopts); if (!compiled) { return std::unexpected{compiled.error()}; } auto eval = Config::evaluate_project(*compiled, request.profile, fopts); if (!eval) { return std::unexpected{eval.error()}; } if (!eval->dependencies.empty() || !eval->dependency_files.empty()) { return std::unexpected{make_error( Void::System::SystemErrorCode::unsupported, std::format("native subproject '{}' declares nested dependencies which are not " "yet supported", request.dependency.name))}; } desc = std::move(*eval); const auto [explicit_files, scan_roots] = collect_native_dep_snapshot_inputs(desc, src_dir); Snapshot::SnapshotOptions sopts; sopts.project_root = src_dir; sopts.snapshot_store_dir = build_dir / ".vbs" / "snapshots"; sopts.reproducibility_epoch = request.profile.reproducibility_epoch; auto cap = Snapshot::capture_snapshot(sopts, explicit_files, scan_roots); if (!cap) { return std::unexpected{cap.error()}; } snap = std::move(*cap); } else if (is_void_library) { const auto mods = parse_void_modules_option(request.dependency.options); Void::Log::info("Provider", "Evaluating native VoidLibrary recipe for '{}' ({} module(s), " "profile='{}')...", request.dependency.name, mods.size(), request.profile.name); Project sub_proj{request.profile}; try { (void)Recipes::add_void_library_native(sub_proj, src_dir, mods); } catch (const std::exception &ex) { return std::unexpected{ make_error(Void::System::SystemErrorCode::invalid_argument, ex.what())}; } auto parsed_desc = Graph::ProjectDescription::from_json(sub_proj.to_json()); if (!parsed_desc) { return std::unexpected{parsed_desc.error()}; } desc = std::move(*parsed_desc); } else { return std::unexpected{make_error( Void::System::SystemErrorCode::invalid_argument, std::format("native builder for '{}' requires build.cpp or a supported native recipe", request.dependency.name))}; } auto graph = Graph::lower_project_graph( desc, request.toolchain, {src_dir, build_dir, snap ? &(*snap) : nullptr, {}, 32768}); if (!graph) { return std::unexpected{graph.error()}; } std::vector selected_targets; for (const auto &t : desc.targets) { if (!t.enabled) { continue; } if (t.kind == TargetKind::StaticLibrary || t.kind == TargetKind::SharedLibrary || t.kind == TargetKind::ObjectLibrary || t.kind == TargetKind::CustomAction || (request.dependency.build_dependency && t.kind == TargetKind::Executable)) { selected_targets.push_back(t.name); } } if (!selected_targets.empty()) { std::optional local_state; State::StateStore *state_ptr = request.shared_state; if (!state_ptr) { auto st = State::StateStore::open(build_dir / ".vbs"); if (!st) { return std::unexpected{st.error()}; } local_state.emplace(std::move(*st)); state_ptr = &(*local_state); } Execution::ExecutionOptions eopts; eopts.jobs = request.jobs; eopts.use_cache = true; eopts.fail_fast = true; eopts.selected_targets = selected_targets; const auto sw = Void::Time::Stopwatch::started(); Void::Log::info("Provider", "Building native dependency '{}' ({} action(s))...", request.dependency.name, graph->actions.size()); auto exec = Execution::execute_graph(*graph, *state_ptr, eopts, stop); if (!exec) { return std::unexpected{exec.error()}; } if (!exec->succeeded) { std::string detail; for (const auto &ar : exec->results) { if (!ar.succeeded) { if (!detail.empty()) { detail += '\n'; } detail += ar.action_id + ": " + ar.error_message; if (!ar.stderr_data.empty()) { detail += "\n" + ar.stderr_data; } } } return std::unexpected{make_error( Void::System::SystemErrorCode::io_error, std::format("native dependency '{}' build failed:\n{}", request.dependency.name, detail.empty() ? exec->diagnostic : detail))}; } Void::Log::info("Provider", "Built native dependency '{}' in {:.2f}s ({} executed, {} cached)", request.dependency.name, sw.elapsed_ms() / 1000.0, exec->executed_count, exec->cached_count); } ProviderExport exp; exp.dependency_name = request.dependency.name; exp.builder = "native"; exp.input_identity_hash = input_hash; std::map> rec_by_name; for (const auto &t : desc.targets) { rec_by_name[t.name] = &t; } std::map> summary_by_name; for (const auto &s : graph->targets) { summary_by_name[s.name] = &s; } const auto gen_root = graph->profile_build_dir / "gen"; auto resolve_inc = [&](const std::string &raw) -> std::filesystem::path { if (raw.starts_with("$GEN/") || raw.starts_with("gen/")) { const auto suffix = raw.starts_with("$GEN/") ? raw.substr(5) : raw.substr(4); return (gen_root / suffix).lexically_normal(); } const std::filesystem::path p{raw}; return p.is_absolute() ? p.lexically_normal() : (src_dir / p).lexically_normal(); }; for (const auto &t : desc.targets) { if (t.kind != TargetKind::StaticLibrary && t.kind != TargetKind::SharedLibrary && t.kind != TargetKind::HeaderOnly) { continue; } Graph::ImportedTargetInterface iface; iface.dependency_name = request.dependency.name; iface.target_name = t.name; std::set usage_visited; auto collect_usage = [&](auto &&self, const std::string &cur_name) -> void { if (!usage_visited.insert(cur_name).second) { return; } const auto it = rec_by_name.find(cur_name); if (it == rec_by_name.end()) { return; } const auto &cur = *it->second; if (cur.use_conventional_sources && std::filesystem::is_directory(src_dir / "include", ec)) { const auto inc = (src_dir / "include").lexically_normal(); if (!std::ranges::contains(iface.include_dirs, std::pair{inc, false})) { iface.include_dirs.emplace_back(inc, false); } } for (const auto &inc : cur.include_directories) { if (inc.visibility != Visibility::Private) { const std::pair entry{resolve_inc(inc.path), inc.is_system}; if (!std::ranges::contains(iface.include_dirs, entry)) { iface.include_dirs.push_back(entry); } } } for (const auto &def : cur.defines) { if (def.visibility != Visibility::Private && !std::ranges::contains(iface.defines, def.value)) { iface.defines.push_back(def.value); } } for (const auto &opt : cur.scoped_compile_options) { if (opt.visibility != Visibility::Private && !std::ranges::contains(iface.compile_options, opt.value)) { iface.compile_options.push_back(opt.value); } } for (const auto &l : cur.links) { if (l.kind == LinkKind::Local && l.visibility != Visibility::Private) { self(self, l.target); } } }; collect_usage(collect_usage, t.name); std::vector post_order; std::set link_visited; auto collect_links = [&](auto &&self, const std::string &cur_name) -> void { if (!link_visited.insert(cur_name).second) { return; } const auto it = rec_by_name.find(cur_name); if (it == rec_by_name.end()) { return; } for (const auto &l : it->second->links) { if (l.kind == LinkKind::Local) { self(self, l.target); } } post_order.push_back(cur_name); }; collect_links(collect_links, t.name); for (auto rit = post_order.rbegin(); rit != post_order.rend(); ++rit) { const auto rec_it = rec_by_name.find(*rit); const auto sum_it = summary_by_name.find(*rit); if (rec_it != rec_by_name.end()) { for (const auto &lo : rec_it->second->link_options) { if (lo.visibility != Visibility::Private && !std::ranges::contains(iface.link_options, lo.value)) { iface.link_options.push_back(lo.value); } } } if (rec_it != rec_by_name.end() && sum_it != summary_by_name.end() && !sum_it->second->primary_outputs.empty()) { const auto &art = sum_it->second->primary_outputs.front(); if (rec_it->second->kind == TargetKind::StaticLibrary && !std::ranges::contains(iface.static_libraries, art)) { iface.static_libraries.push_back(art); } else if (rec_it->second->kind == TargetKind::SharedLibrary && !std::ranges::contains(iface.shared_libraries, art)) { iface.shared_libraries.push_back(art); if (!std::ranges::contains(iface.runtime_files, art)) { iface.runtime_files.push_back(art); } } } if (sum_it != summary_by_name.end()) { for (const auto &[mname, bmi_p] : sum_it->second->exported_module_bmis) { iface.module_bmis.try_emplace(mname, bmi_p); } } } exp.targets[request.dependency.name + "::" + t.name] = iface; exp.targets[t.name] = iface; if (t.name.starts_with("Void_")) { auto alias = iface; alias.target_name = "Void::" + t.name.substr(5); exp.targets[request.dependency.name + "::" + alias.target_name] = alias; exp.targets[alias.target_name] = std::move(alias); } } for (const auto &[k, v] : request.explicit_overrides) { exp.targets[k] = v; } return exp; } } // namespace std::string compute_provider_input_hash(const ProviderRequest &request) { Util::Sha256Hasher h; h.update_length_prefixed("vbs-provider-v1"); h.update_length_prefixed(request.dependency.name); h.update_length_prefixed(request.dependency.builder); h.update_length_prefixed(request.source.content_identity_hash); h.update_length_prefixed(request.profile.name); h.update_length_prefixed(request.toolchain.identity_hash); for (const auto &[k, v] : request.dependency.options) { h.update_length_prefixed(k); h.update_length_prefixed(cmake_option_value(v)); } return h.finalize_hex(); } Void::Result::Result resolve_foreign_provider(const ProviderRequest &request, std::stop_token stop) { const std::string input_hash = compute_provider_input_hash(request); const auto isolated_dir = request.provider_build_root / request.dependency.name / input_hash.substr(0, 16); const auto export_file = isolated_dir / "provider-export.json"; // Always try validated cache first (in BOTH FullBuild and MetadataOnly modes). if (auto cached = load_cached_export(export_file, input_hash); cached) { return *cached; } // Strict MetadataOnly boundary (D-026 / Plan 10 / Plan 13): // NEVER invoke CMake configure, Meson setup, Conan install, or builds! if (request.mode == ProviderMode::MetadataOnly) { ProviderExport stale; stale.dependency_name = request.dependency.name; stale.builder = request.dependency.builder; stale.input_identity_hash = input_hash; stale.stale_needs_build = true; stale.stale_diagnostic = std::format( "cached {} provider metadata for '{}' is missing or stale (input={}); " "run 'vbs build' to configure/build dependencies", request.dependency.builder, request.dependency.name, input_hash.substr(0, 12)); return stale; } const auto lock_path = isolated_dir.parent_path() / (request.dependency.name + ".lock"); auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive); if (!lock) { return std::unexpected{lock.error()}; } // Re-check cache after acquiring lock in case a peer just finished. if (auto cached = load_cached_export(export_file, input_hash); cached) { return *cached; } const auto tool_build_dir = isolated_dir / "build"; Void::Result::Result res = std::unexpected{ make_error(Void::System::SystemErrorCode::invalid_argument, std::format("unsupported foreign builder '{}'", request.dependency.builder))}; if (request.dependency.builder == "cmake") { res = run_cmake_provider(request, tool_build_dir, input_hash, stop); } else if (request.dependency.builder == "meson") { res = run_meson_provider(request, tool_build_dir, input_hash, stop); } else if (request.dependency.builder == "conan") { res = run_conan_provider(request, tool_build_dir, input_hash, stop); } else if (request.dependency.builder == "native") { res = run_native_provider(request, tool_build_dir, input_hash, stop); } if (!res) { return std::unexpected{res.error()}; } // Publish validated provider export atomically! if (auto w = Platform::atomic_write_file(export_file, serialize_export(*res), true); !w) { return std::unexpected{w.error()}; } return res; } } // namespace Void::Build::Provider