feat: add Plan 20 Slice 2A Meson native translation, DX CLI (init/clean/doctor/graph/--native-foreign), and expansion roadmap
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 7s

This commit is contained in:
faumaray committed 2026-11-27 06:14:48 +03:00
1 parent d3d2666965
commit fe0d1a6483
12 files changed
+1317 -41

No files matched your search

+400 -13
View File
@@ -15,6 +15,7 @@
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Provider/Provider.hpp>
#include <Void/Build/Provider/Translator.hpp>
#include <Void/Build/SelfHost/TestRegistryGen.hpp>
#include <Void/Build/Snapshot/Snapshot.hpp>
#include <Void/Build/State/StateStore.hpp>
@@ -496,6 +497,7 @@ struct BuildCmdOptions {
bool no_cache{false};
bool locked{false};
bool offline{false};
bool native_foreign{false};
};
int execute_build_or_test(BuildCmdOptions opts, bool run_tests) {
@@ -695,16 +697,34 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) {
build_root / ".vbs" / "providers",
Provider::ProviderMode::FullBuild,
{}};
auto exp = Provider::resolve_foreign_provider(preq);
if (!exp) {
std::cerr << "vbs: " << exp.error().message() << '\n';
return 1;
}
Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})",
prof_name, exp->targets.size(), effective_dep.name,
exp->from_cache ? "cached" : "built");
for (const auto &[k, v] : exp->targets) {
imported_targets[k] = v;
if (opts.native_foreign &&
(effective_dep.builder == "cmake" || effective_dep.builder == "meson")) {
auto tr = Provider::resolve_foreign_with_translation(
preq, *state, Provider::TranslationPolicy::FallbackToForeignBuild);
if (!tr) {
std::cerr << "vbs: " << tr.error().message() << '\n';
return 1;
}
Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})",
prof_name, tr->exported.targets.size(), effective_dep.name,
tr->executed_natively
? "native-translated"
: (tr->exported.from_cache ? "cached" : "built"));
for (const auto &[k, v] : tr->exported.targets) {
imported_targets[k] = v;
}
} else {
auto exp = Provider::resolve_foreign_provider(preq);
if (!exp) {
std::cerr << "vbs: " << exp.error().message() << '\n';
return 1;
}
Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})",
prof_name, exp->targets.size(), effective_dep.name,
exp->from_cache ? "cached" : "built");
for (const auto &[k, v] : exp->targets) {
imported_targets[k] = v;
}
}
}
}
@@ -1353,6 +1373,318 @@ int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) {
return 0;
}
struct InitCmdOptions {
std::string dir_arg;
std::optional<std::string> name_arg;
bool library{false};
bool with_toml{false};
bool force{false};
};
int execute_init_command(const InitCmdOptions &opts) {
std::error_code ec;
const std::filesystem::path target_dir = std::filesystem::path{opts.dir_arg}.lexically_normal();
std::filesystem::create_directories(target_dir, ec);
if (ec) {
std::cerr << "vbs init: cannot create directory '" << target_dir.string()
<< "': " << ec.message() << '\n';
return 1;
}
const auto canon = std::filesystem::weakly_canonical(target_dir, ec);
std::string raw_name =
(opts.name_arg && !opts.name_arg->empty()) ? *opts.name_arg : canon.filename().string();
if (raw_name.empty()) {
raw_name = "app";
}
std::string ident;
for (const char c : raw_name) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_') {
ident.push_back(c);
} else if (c == '-' || c == ' ') {
ident.push_back('_');
}
}
if (ident.empty() || (ident.front() >= '0' && ident.front() <= '9')) {
ident = "vbs_" + ident;
}
const auto build_cpp = target_dir / "build.cpp";
if (!opts.force && std::filesystem::exists(build_cpp, ec)) {
std::cerr << "vbs init: '" << build_cpp.string()
<< "' already exists (pass --force to overwrite)\n";
return 2;
}
auto write_checked = [&](const std::filesystem::path &p, std::string_view content) -> bool {
auto w = Platform::atomic_write_file(p, content, false);
if (!w) {
std::cerr << "vbs init: failed writing '" << p.string() << "': " << w.error().message()
<< '\n';
return false;
}
return true;
};
std::string build_src =
"#include <Void/Build.hpp>\n\nvoid build(Void::Build::Project &project) {\n";
if (opts.with_toml) {
build_src += " project.dependencies_file(\"vbs.deps.toml\");\n\n";
}
if (opts.library) {
build_src += " auto lib = project.static_library(\"" + raw_name +
"\");\n"
" lib.cxx_standard(Void::Build::CxxStandard::Cxx26)\n"
" .sources({\"src/" +
ident +
".cpp\"})\n"
" .include_directory(\"include\", Void::Build::Visibility::Public)\n"
" .install(\"lib\");\n"
" project.install_directory(\"include\", \"include\");\n\n"
" auto t = project.test(\"" +
ident +
"_tests\");\n"
" t.cxx_standard(Void::Build::CxxStandard::Cxx26)\n"
" .sources({\"tests/test_main.cpp\"})\n"
" .link(lib);\n";
} else {
build_src += " auto lib = project.static_library(\"" + ident +
"_lib\");\n"
" lib.cxx_standard(Void::Build::CxxStandard::Cxx26)\n"
" .sources({\"src/" +
ident +
".cpp\"})\n"
" .include_directory(\"include\", Void::Build::Visibility::Public);\n\n"
" auto app = project.executable(\"" +
raw_name +
"\");\n"
" app.cxx_standard(Void::Build::CxxStandard::Cxx26)\n"
" .sources({\"src/main.cpp\"})\n"
" .link(lib)\n"
" .install(\"bin\");\n\n"
" auto t = project.test(\"" +
ident +
"_tests\");\n"
" t.cxx_standard(Void::Build::CxxStandard::Cxx26)\n"
" .sources({\"tests/test_main.cpp\"})\n"
" .link(lib);\n";
}
build_src += "}\n";
if (!write_checked(build_cpp, build_src)) {
return 1;
}
if (!write_checked(target_dir / "include" / (ident + ".hpp"),
"#pragma once\n\nnamespace " + ident + " {\nint answer();\n}\n")) {
return 1;
}
if (!write_checked(target_dir / "src" / (ident + ".cpp"),
"#include \"" + ident + ".hpp\"\n\nnamespace " + ident +
" {\nint answer() { return 42; }\n}\n")) {
return 1;
}
if (!opts.library) {
if (!write_checked(target_dir / "src" / "main.cpp",
"#include \"" + ident +
".hpp\"\n#include <iostream>\n\nint main() {\n std::cout << \"" +
raw_name + ": answer=\" << " + ident +
"::answer() << '\\n';\n return 0;\n}\n")) {
return 1;
}
}
if (!write_checked(target_dir / "tests" / "test_main.cpp",
"#include \"" + ident + ".hpp\"\n\nint main() { return " + ident +
"::answer() == 42 ? 0 : 1; }\n")) {
return 1;
}
if (!write_checked(target_dir / ".gitignore",
"/build/\n/.vbs/\n/compile_commands.json\n.env\n")) {
return 1;
}
if (opts.with_toml) {
if (!write_checked(target_dir / "vbs.deps.toml",
"# Declarative dependency manifest for " + raw_name + "\n")) {
return 1;
}
}
Void::Log::info("Init", "Initialized VBS {} project '{}' in '{}'",
opts.library ? "library" : "application", raw_name, target_dir.string());
std::cout << "initialized " << raw_name << " in " << target_dir.string() << '\n';
return 0;
}
struct CleanCmdOptions {
std::string build_arg;
bool clean_all{false};
};
int execute_clean_command(const CleanCmdOptions &opts) {
const std::filesystem::path build_root{opts.build_arg};
std::error_code ec;
if (!std::filesystem::exists(build_root, ec)) {
std::cout << "clean: nothing to remove in " << build_root.string() << '\n';
return 0;
}
if (opts.clean_all) {
Void::Log::info("Clean", "Removing entire build directory '{}'...", build_root.string());
std::filesystem::remove_all(build_root, ec);
if (ec) {
std::cerr << "vbs clean: failed removing '" << build_root.string()
<< "': " << ec.message() << '\n';
return 1;
}
std::cout << "cleaned " << build_root.string() << " (all)\n";
return 0;
}
const auto profiles_dir = build_root / "profiles";
std::size_t removed = 0;
if (std::filesystem::exists(profiles_dir, ec)) {
Void::Log::info("Clean", "Removing profile outputs under '{}' (preserving .vbs/cache)...",
profiles_dir.string());
removed += static_cast<std::size_t>(std::filesystem::remove_all(profiles_dir, ec));
}
const auto compdb = build_root / "compile_commands.json";
if (std::filesystem::exists(compdb, ec) || std::filesystem::is_symlink(compdb, ec)) {
std::filesystem::remove(compdb, ec);
++removed;
}
std::cout << "cleaned " << removed << " path(s) in " << build_root.string()
<< " (preserved .vbs cache/state)\n";
return 0;
}
int execute_doctor_command() {
std::cout << "VoidBuildSystem " << Bootstrap::version << " (" << Bootstrap::os << "/"
<< Bootstrap::architecture << ")\n";
auto check_tool = [](std::string_view label, const char *bin, bool required) {
auto found = Platform::resolve_executable(bin);
std::cout << " " << (found ? "[ok] " : (required ? "[FAIL]" : "[opt] ")) << " " << label
<< ": " << (found ? found->string() : std::string{"not found"}) << '\n';
return found.has_value();
};
const bool has_gcc = check_tool("g++", "g++", true);
(void)check_tool("clang++", "clang++", false);
(void)check_tool("clang-scan-deps", "clang-scan-deps", false);
(void)check_tool("ar", "ar", true);
(void)check_tool("git", "git", false);
(void)check_tool("cmake", "cmake", false);
(void)check_tool("ninja", "ninja", false);
(void)check_tool("meson", "meson", false);
(void)check_tool("conan", "conan", false);
(void)check_tool("clang-format", "clang-format", false);
std::cout << " [ok] Void::Crypto built-in SHA-256: enabled\n";
std::cout << " [ok] Void::Archive built-in USTAR/PAX: enabled\n";
if (has_gcc) {
Void::FileSystem::TempDir tmp{"vbs_doc_"};
auto ctx =
default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(),
Toolchain::host_architecture_name());
if (auto tc = Toolchain::discover_and_probe(ctx, tmp.path()); tc) {
std::cout << " [ok] GCC probe: " << tc->version_banner
<< " (c++26=" << (tc->supports_cxx26 ? "yes" : "no")
<< ", reflection=" << (tc->supports_reflection ? "yes" : "no")
<< ", p1689=" << (tc->supports_p1689_scan ? "yes" : "no") << ")\n";
}
}
return has_gcc ? 0 : 1;
}
struct GraphCmdOptions {
std::string project_arg;
std::optional<std::string> build_arg;
std::string profile_name{"debug"};
std::optional<std::string> compiler_arg;
std::string format{"dot"};
};
int execute_graph_command(const GraphCmdOptions &opts) {
if (opts.format != "dot" && opts.format != "json") {
std::cerr << "vbs graph: unsupported --format '" << opts.format
<< "' (expected 'dot' or 'json')\n";
return 2;
}
std::optional<CompilerFamily> compiler_override;
if (opts.compiler_arg) {
try {
compiler_override = parse_compiler(*opts.compiler_arg);
} catch (const std::exception &ex) {
std::cerr << "vbs graph: " << ex.what() << '\n';
return 2;
}
}
const std::filesystem::path project_root{opts.project_arg};
const std::filesystem::path build_root =
opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build");
const auto fopts = make_frontend_opts(project_root, build_root, {});
auto compiled = Config::compile_descriptor(fopts);
if (!compiled) {
std::cerr << "vbs graph: " << compiled.error().message() << '\n';
return 1;
}
auto profs = Config::discover_profiles(*compiled, fopts);
if (!profs) {
std::cerr << "vbs graph: " << profs.error().message() << '\n';
return 1;
}
ProfileContext ctx;
try {
ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(),
Toolchain::host_architecture_name());
} catch (const std::exception &ex) {
std::cerr << "vbs graph: " << ex.what() << '\n';
return 2;
}
auto desc = Config::evaluate_project(*compiled, ctx, fopts);
if (!desc) {
std::cerr << "vbs graph: " << desc.error().message() << '\n';
return 1;
}
if (opts.format == "json") {
std::cout << "{\"profile\":" << Util::json_quote(desc->profile.name) << ",\"targets\":";
std::cout << Util::json_array(desc->targets, [](const TargetRecord &t) {
return "{\"name\":" + Util::json_quote(t.name) +
",\"kind\":" + Util::json_quote(target_kind_name(t.kind)) + ",\"links\":" +
Util::json_array(t.links,
[](const LinkRecord &l) {
return Util::json_quote(
l.kind == LinkKind::Imported
? (l.dependency + "::" + l.target)
: l.target);
}) +
'}';
});
std::cout << "}\n";
return 0;
}
std::cout << "digraph vbs_targets {\n";
std::cout << " rankdir=LR;\n";
for (const auto &t : desc->targets) {
std::cout << " " << Util::json_quote(t.name) << " [label="
<< Util::json_quote(t.name + "\n(" + std::string{target_kind_name(t.kind)} + ")")
<< "];\n";
}
for (const auto &t : desc->targets) {
for (const auto &pre : t.prerequisites) {
std::cout << " " << Util::json_quote(t.name) << " -> " << Util::json_quote(pre)
<< " [style=dashed];\n";
}
for (const auto &l : t.links) {
const std::string dst =
l.kind == LinkKind::Imported ? (l.dependency + "::" + l.target) : l.target;
std::cout << " " << Util::json_quote(t.name) << " -> " << Util::json_quote(dst)
<< ";\n";
}
}
std::cout << "}\n";
return 0;
}
} // namespace
int main(int argc, char **argv) {
@@ -1382,6 +1714,12 @@ int main(int argc, char **argv) {
GcCmdOptions gc_opts;
gc_opts.build_arg = (std::filesystem::path{cwd} / "build").string();
GenTestsCmdOptions gen_tests_opts;
InitCmdOptions init_opts;
init_opts.dir_arg = cwd;
CleanCmdOptions clean_opts;
clean_opts.build_arg = (std::filesystem::path{cwd} / "build").string();
GraphCmdOptions graph_opts;
graph_opts.project_arg = cwd;
auto add_log_flags = [&](Void::Argparse::Parser &p, bool allow_short_v = true) {
p.flag("--verbose", allow_short_v ? "-v" : "", "Enable verbose debug logs", verbose)
@@ -1402,7 +1740,10 @@ int main(int argc, char **argv) {
.option("--jobs", "-j", "Maximum parallel compilation/link jobs", build_opts.jobs_arg)
.flag("--locked", "", "Require existing up-to-date vbs.lock", build_opts.locked)
.flag("--offline", "", "Disallow network fetches", build_opts.offline)
.flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache);
.flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache)
.flag("--native-foreign", "",
"Translate supported CMake/Meson dependencies to native VBS actions (Plan 20)",
build_opts.native_foreign);
add_log_flags(p);
};
@@ -1536,6 +1877,39 @@ int main(int argc, char **argv) {
gen_tests_opts.out_arg);
add_log_flags(gen_tests_cmd);
auto &init_cmd =
root.subcommand("init", "Scaffold a new ready-to-build C++26 VoidBuildSystem project");
init_cmd.option_default("--dir", "-C", "Target project directory", init_opts.dir_arg, cwd)
.option("--name", "-n", "Project/target name (defaults to directory name)",
init_opts.name_arg)
.flag("--library", "", "Scaffold a static library project instead of an executable",
init_opts.library)
.flag("--with-toml", "", "Include a vbs.deps.toml dependency manifest", init_opts.with_toml)
.flag("--force", "", "Overwrite existing build.cpp if present", init_opts.force);
add_log_flags(init_cmd);
auto &clean_cmd =
root.subcommand("clean", "Remove generated profile build artifacts (preserving cache)");
clean_cmd
.option_default("--build-dir", "-B", "Build directory", clean_opts.build_arg,
clean_opts.build_arg)
.flag("--all", "", "Also delete .vbs cache, snapshots, and state store",
clean_opts.clean_all);
add_log_flags(clean_cmd);
auto &doctor_cmd =
root.subcommand("doctor", "Check host compilers, tools, and VBS runtime capabilities");
add_log_flags(doctor_cmd);
auto &graph_cmd =
root.subcommand("graph", "Export target dependency graph in Graphviz DOT or JSON format");
graph_cmd.option_default("--project", "-C", "Project directory", graph_opts.project_arg, cwd)
.option("--build-dir", "-B", "Build output directory", graph_opts.build_arg)
.option_default("--profile", "-p", "Profile name", graph_opts.profile_name, "debug")
.option("--compiler", "", "Override compiler family (gcc|clang)", graph_opts.compiler_arg)
.option_default("--format", "-f", "Output format (dot|json)", graph_opts.format, "dot");
add_log_flags(graph_cmd);
const auto parsed = root.parse_detailed(argc, argv);
if (parsed.is_help()) {
std::cout << parsed.message;
@@ -1560,8 +1934,9 @@ int main(int argc, char **argv) {
const std::string_view cmd = parsed.matched_command_path.front();
const bool machine_quiet_default =
(cmd == "describe") || (cmd == "compdb" && parsed.matched_command_path.size() >= 2 &&
parsed.matched_command_path[1] == "show");
(cmd == "describe") || (cmd == "graph") || (cmd == "doctor") ||
(cmd == "compdb" && parsed.matched_command_path.size() >= 2 &&
parsed.matched_command_path[1] == "show");
const Void::Log::Level log_level =
verbose ? Void::Log::Level::Debug
: ((quiet || machine_quiet_default) ? Void::Log::Level::Warning
@@ -1607,6 +1982,18 @@ int main(int argc, char **argv) {
if (cmd == "gen-tests") {
return execute_gen_tests_command(gen_tests_opts);
}
if (cmd == "init") {
return execute_init_command(init_opts);
}
if (cmd == "clean") {
return execute_clean_command(clean_opts);
}
if (cmd == "doctor") {
return execute_doctor_command();
}
if (cmd == "graph") {
return execute_graph_command(graph_opts);
}
std::cerr << "vbs: unhandled subcommand '" << cmd << "'\n";
return 2;
+565
View File
@@ -853,4 +853,569 @@ resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore
return res;
}
namespace {
std::string meson_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 ? "true" : "false";
} else {
return std::to_string(inner);
}
},
v.value);
}
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;
}
struct ParsedMesonTarget {
std::string id;
std::string name;
std::string type;
std::vector<std::filesystem::path> filenames;
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;
};
struct ParsedMesonModel {
TranslationAuditReport audit;
std::map<std::string, ParsedMesonTarget, std::less<>> targets_by_id;
std::vector<std::string> target_order;
};
Void::Result::Result<ParsedMesonModel, Void::Result::Error>
load_and_audit_meson(const std::filesystem::path &configure_dir) {
const auto intro_targets = configure_dir / "meson-info" / "intro-targets.json";
auto parsed = parse_json_file(intro_targets);
if (!parsed) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found,
std::format("Meson introspection file missing or invalid at '{}'",
intro_targets.string()))};
}
const auto *arr = std::get_if<JsonVal::Array>(&parsed->value);
if (!arr) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"Meson intro-targets.json root must be an array")};
}
ParsedMesonModel out;
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)});
};
// Map known output filenames (relative & absolute) -> target id for link edge recovery.
std::map<std::string, std::string, std::less<>> artifact_to_id;
for (const auto &tv : *arr) {
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
if (!to) {
continue;
}
ParsedMesonTarget pt;
pt.id = get_str(*to, "id");
pt.name = get_str(*to, "name");
pt.type = get_str(*to, "type");
if (pt.id.empty()) {
pt.id = pt.name;
}
if (pt.type == "custom" || pt.type == "run") {
add_unsupported(
pt.name, "custom_target",
std::format("Meson target '{}' has type '{}' (custom/run targets cannot be "
"faithfully translated from intro-targets.json)",
pt.name, pt.type));
continue;
}
if (pt.type != "static library" && pt.type != "shared library" && pt.type != "executable") {
add_unsupported(
pt.name, "unsupported_target_type",
std::format("Meson target '{}' has unsupported type '{}'", pt.name, pt.type));
continue;
}
for (const auto &fn : get_str_array(*to, "filename")) {
const std::filesystem::path abs_fn = std::filesystem::path{fn}.lexically_normal();
pt.filenames.push_back(abs_fn);
artifact_to_id[abs_fn.string()] = pt.id;
artifact_to_id[abs_fn.filename().string()] = pt.id;
const auto rel = abs_fn.lexically_relative(configure_dir);
if (!rel.empty() && !rel.string().starts_with("..")) {
artifact_to_id[rel.generic_string()] = pt.id;
}
}
if (const auto *ts = find_key(*to, "target_sources")) {
if (const auto *tsarr = std::get_if<JsonVal::Array>(&ts->value)) {
for (const auto &tsv : *tsarr) {
const auto *tso = std::get_if<JsonVal::Object>(&tsv.value);
if (!tso) {
continue;
}
const auto lang = get_str(*tso, "language");
const auto srcs = get_str_array(*tso, "sources");
const auto gen_srcs = get_str_array(*tso, "generated_sources");
if (!gen_srcs.empty()) {
add_unsupported(
pt.name, "generated_source",
std::format("Meson target '{}' depends on {} generated source(s) "
"(first: '{}')",
pt.name, gen_srcs.size(), gen_srcs.front()));
}
if (!srcs.empty() && lang != "cpp") {
add_unsupported(
pt.name, "unsupported_language",
std::format("Meson target '{}' compiles language '{}' (bounded subset "
"supports cpp only)",
pt.name, lang));
}
for (const auto &s : srcs) {
pt.sources.push_back(std::filesystem::path{s}.lexically_normal());
}
const auto params = get_str_array(*tso, "parameters");
for (std::size_t i = 0; i < params.size(); ++i) {
const auto &p = params[i];
if (p.starts_with("-I") && p.size() > 2) {
std::filesystem::path ip{p.substr(2)};
if (!ip.is_absolute()) {
ip = (configure_dir / ip).lexically_normal();
}
if (!std::ranges::contains(pt.includes, std::pair{ip, false})) {
pt.includes.emplace_back(ip, false);
}
} else if (p == "-I" && i + 1 < params.size()) {
std::filesystem::path ip{params[++i]};
if (!ip.is_absolute()) {
ip = (configure_dir / ip).lexically_normal();
}
if (!std::ranges::contains(pt.includes, std::pair{ip, false})) {
pt.includes.emplace_back(ip, false);
}
} else if (p == "-isystem" && i + 1 < params.size()) {
std::filesystem::path ip{params[++i]};
if (!ip.is_absolute()) {
ip = (configure_dir / ip).lexically_normal();
}
if (!std::ranges::contains(pt.includes, std::pair{ip, true})) {
pt.includes.emplace_back(ip, true);
}
} else if (p.starts_with("-D") && p.size() > 2) {
const std::string def = p.substr(2);
if (!std::ranges::contains(pt.defines, def)) {
pt.defines.push_back(def);
}
} else if (p == "-D" && i + 1 < params.size()) {
const std::string def = params[++i];
if (!std::ranges::contains(pt.defines, def)) {
pt.defines.push_back(def);
}
} else if (p == "-std=c++17" || p == "-std=gnu++17") {
pt.cxx_standard = CxxStandard::Cxx17;
} else if (p == "-std=c++20" || p == "-std=gnu++20") {
pt.cxx_standard = CxxStandard::Cxx20;
} else if (p == "-std=c++23" || p == "-std=gnu++23") {
pt.cxx_standard = CxxStandard::Cxx23;
} else if (p == "-std=c++26" || p == "-std=gnu++26") {
pt.cxx_standard = CxxStandard::Cxx26;
} else if (p == "-fPIC" || p == "-fpic" ||
p == "-fdiagnostics-color=always" || p == "-pipe" ||
p == "-D_FILE_OFFSET_BITS=64") {
continue;
} else if (p == "-pthread") {
if (!std::ranges::contains(pt.compile_options, p)) {
pt.compile_options.push_back(p);
}
if (!std::ranges::contains(pt.link_options, p)) {
pt.link_options.push_back(p);
}
} else if (!p.empty() && p[0] == '-') {
if (!std::ranges::contains(pt.compile_options, p)) {
pt.compile_options.push_back(p);
}
}
}
}
}
}
out.audit.supported_targets.push_back(pt.name);
out.target_order.push_back(pt.id);
out.targets_by_id[pt.id] = std::move(pt);
}
// Recover internal target link edges cleanly from Meson's configured `build.ninja`
// (`build <target_rel>: cpp_LINKER ... | <dep_lib>` + `LINK_ARGS = ...`).
if (auto ninja_text = Void::FileSystem::read_file(configure_dir / "build.ninja"); ninja_text) {
std::string cur_target_id;
std::size_t pos = 0;
while (pos < ninja_text->size()) {
const auto nl = ninja_text->find('\n', pos);
std::string_view line = std::string_view{*ninja_text}.substr(
pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
if (!line.empty() && line.back() == '\r') {
line.remove_suffix(1);
}
pos = (nl == std::string_view::npos) ? ninja_text->size() : (nl + 1);
if (line.starts_with("build ")) {
cur_target_id.clear();
const auto colon = line.find(':');
if (colon != std::string_view::npos) {
const auto outs_part = line.substr(6, colon - 6);
for (const auto &tok : split_shell_tokens(outs_part)) {
if (const auto ait = artifact_to_id.find(tok);
ait != artifact_to_id.end()) {
cur_target_id = ait->second;
break;
}
}
if (!cur_target_id.empty()) {
auto &pt = out.targets_by_id.at(cur_target_id);
const auto rhs = line.substr(colon + 1);
for (const auto &tok : split_shell_tokens(rhs)) {
if (const auto ait = artifact_to_id.find(tok);
ait != artifact_to_id.end() && ait->second != cur_target_id) {
if (!std::ranges::contains(pt.dep_ids, ait->second)) {
pt.dep_ids.push_back(ait->second);
}
}
}
}
}
} else if (!cur_target_id.empty() && line.starts_with(" LINK_ARGS = ")) {
auto &pt = out.targets_by_id.at(cur_target_id);
const auto args_part = line.substr(13);
for (const auto &tok : split_shell_tokens(args_part)) {
if (tok.empty() || tok == "-Wl,--as-needed" || tok == "-Wl,--no-undefined" ||
tok == "-Wl,--start-group" || tok == "-Wl,--end-group" ||
tok == "-Wl,--allow-shlib-undefined" || tok.starts_with("-Wl,-rpath") ||
tok.starts_with("-Wl,-soname") || tok == "-shared" || tok == "-fPIC") {
continue;
}
if (is_safe_system_link_flag(tok)) {
if (!std::ranges::contains(pt.link_options, tok)) {
pt.link_options.push_back(tok);
}
} else if (const auto ait = artifact_to_id.find(tok);
ait != artifact_to_id.end()) {
if (ait->second != cur_target_id &&
!std::ranges::contains(pt.dep_ids, ait->second)) {
pt.dep_ids.push_back(ait->second);
}
} else if (tok.ends_with(".a") || tok.ends_with(".so") ||
tok.starts_with("-l")) {
add_unsupported(
pt.name, "unsupported_link_fragment",
std::format("Meson target '{}' has untranslated link argument '{}'",
pt.name, tok));
}
}
} else if (line.empty()) {
cur_target_id.clear();
}
}
}
if (out.audit.is_supported()) {
out.audit.summary = std::format("all {} Meson target(s) fit the bounded native subset",
out.audit.supported_targets.size());
} else {
out.audit.summary = std::format("{} unsupported construct(s) detected across Meson project",
out.audit.unsupported.size());
}
return out;
}
} // namespace
Void::Result::Result<std::filesystem::path, Void::Result::Error>
configure_meson_for_translation(const ProviderRequest &request,
const std::filesystem::path &configure_dir, 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 translation requires 'meson' in PATH")};
}
std::error_code ec;
std::filesystem::remove_all(configure_dir, ec);
std::filesystem::create_directories(configure_dir.parent_path(), ec);
Void::Log::info("Translate", "Configuring Meson dependency '{}' for native graph audit...",
request.dependency.name);
Platform::ProcessRequest req;
req.executable = *meson_bin;
req.arguments = {"setup", configure_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));
}
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()))};
}
return configure_dir / "meson-info";
}
Void::Result::Result<TranslationAuditReport, Void::Result::Error>
audit_meson_introspection(const std::filesystem::path &configure_dir) {
auto loaded = load_and_audit_meson(configure_dir);
if (!loaded) {
return std::unexpected{loaded.error()};
}
return std::move(loaded->audit);
}
Void::Result::Result<TranslatedCMakeGraph, Void::Result::Error> translate_meson_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_meson(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;
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 {
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));
}
Graph::GraphLowerOptions gopts{
request.source.source_dir, native_build_root, snapshot, {}, 32768};
auto graph = Graph::lower_project_graph(desc, request.toolchain, gopts);
if (!graph) {
return std::unexpected{graph.error()};
}
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;
}
std::error_code ec;
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;
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);
}
}
iface.defines = pt.defines;
iface.link_options = pt.link_options;
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);
}
}
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_meson_with_translation(const ProviderRequest &request, State::StateStore &state,
TranslationPolicy policy, std::stop_token stop) {
if (request.dependency.builder != "meson") {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("resolve_meson_with_translation requires builder='meson', 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_meson_" + request.dependency.name + "_" + input_hash.substr(0, 16));
const auto cfg_dir = slot_dir / "meson-setup";
const auto native_build_root = slot_dir / "native-build";
auto info_dir = configure_meson_for_translation(request, cfg_dir, stop);
if (!info_dir) {
return std::unexpected{info_dir.error()};
}
auto audit = audit_meson_introspection(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",
"Meson dependency '{}' has unsupported constructs ({}); falling back to "
"foreign Meson 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_meson_to_native_graph(request, cfg_dir, native_build_root, nullptr);
if (!translated) {
return std::unexpected{translated.error()};
}
Void::Log::info("Translate",
"Executing Meson dependency '{}' natively ({} actions, 0 meson compile)...",
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 Meson dependency '{}' failed: {}",
request.dependency.name, exec->diagnostic))};
}
Void::Log::info("Translate",
"Native Meson 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 = "meson-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;
}
Void::Result::Result<TranslationResolution, Void::Result::Error>
resolve_foreign_with_translation(const ProviderRequest &request, State::StateStore &state,
TranslationPolicy policy, std::stop_token stop) {
if (request.dependency.builder == "cmake") {
return resolve_cmake_with_translation(request, state, policy, stop);
}
if (request.dependency.builder == "meson") {
return resolve_meson_with_translation(request, state, policy, stop);
}
auto fb = resolve_foreign_provider(request, stop);
if (!fb) {
return std::unexpected{fb.error()};
}
TranslationResolution res;
res.executed_natively = false;
res.audit.status = TranslationStatus::Unsupported;
res.audit.summary = "builder '" + request.dependency.builder + "' uses foreign provider";
res.exported = std::move(*fb);
return res;
}
} // namespace Void::Build::Provider