2635 lines
115 KiB
C++
2635 lines
115 KiB
C++
#include <Void/Build/Provider/Translator.hpp>
|
|
|
|
#include <Void/Build/Platform/FileOps.hpp>
|
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
|
#include <Void/Data/StrictJson.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/System/Path.hpp>
|
|
#include <Void/System/Types.hpp>
|
|
#include <Void/Time/Stopwatch.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <format>
|
|
#include <map>
|
|
#include <queue>
|
|
#include <set>
|
|
#include <type_traits>
|
|
|
|
namespace Void::Build::Provider {
|
|
namespace {
|
|
|
|
using JsonVal = Void::Json::Strict::Value;
|
|
|
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
|
return Void::System::make_system_error(code, std::move(msg));
|
|
}
|
|
|
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
|
const auto it = obj.find(k);
|
|
return it == obj.end() ? nullptr : &it->second;
|
|
}
|
|
|
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
|
const auto *v = find_key(obj, k);
|
|
if (!v) {
|
|
return {};
|
|
}
|
|
const auto *s = std::get_if<std::string>(&v->value);
|
|
return s ? *s : std::string{};
|
|
}
|
|
|
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
|
const auto *v = find_key(obj, k);
|
|
if (!v) {
|
|
return def;
|
|
}
|
|
const auto *b = std::get_if<bool>(&v->value);
|
|
return b ? *b : def;
|
|
}
|
|
|
|
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &k) {
|
|
const auto *v = find_key(obj, k);
|
|
if (!v) {
|
|
return std::nullopt;
|
|
}
|
|
const auto *i = std::get_if<std::int64_t>(&v->value);
|
|
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
|
|
}
|
|
|
|
std::optional<JsonVal> parse_json_file(const std::filesystem::path &path) {
|
|
auto text = Void::FileSystem::read_file(path);
|
|
if (!text) {
|
|
return std::nullopt;
|
|
}
|
|
auto parsed = Void::Json::Strict::parse(*text);
|
|
if (!parsed) {
|
|
return std::nullopt;
|
|
}
|
|
return std::move(*parsed);
|
|
}
|
|
|
|
std::string cmake_option_value(const OptionValue &v) {
|
|
return std::visit(
|
|
[](const auto &inner) -> std::string {
|
|
using T = std::remove_cvref_t<decltype(inner)>;
|
|
if constexpr (std::same_as<T, std::string>) {
|
|
return inner;
|
|
} else if constexpr (std::same_as<T, bool>) {
|
|
return inner ? "ON" : "OFF";
|
|
} else {
|
|
return std::to_string(inner);
|
|
}
|
|
},
|
|
v.value);
|
|
}
|
|
|
|
std::vector<std::string> split_shell_tokens(std::string_view text) {
|
|
std::vector<std::string> tokens;
|
|
std::string cur;
|
|
bool in_single = false;
|
|
bool in_double = false;
|
|
bool escaped = false;
|
|
for (const char c : text) {
|
|
if (escaped) {
|
|
cur.push_back(c);
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (c == '\\' && !in_single) {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (c == '\'' && !in_double) {
|
|
in_single = !in_single;
|
|
continue;
|
|
}
|
|
if (c == '"' && !in_single) {
|
|
in_double = !in_double;
|
|
continue;
|
|
}
|
|
if (!in_single && !in_double && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
|
|
if (!cur.empty()) {
|
|
tokens.push_back(std::move(cur));
|
|
cur.clear();
|
|
}
|
|
continue;
|
|
}
|
|
cur.push_back(c);
|
|
}
|
|
if (!cur.empty()) {
|
|
tokens.push_back(std::move(cur));
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
bool is_safe_system_link_flag(std::string_view tok) {
|
|
// GCC 16 ships an as-needed linker script for libgcc_s, which CMake exposes as
|
|
// `-lgcc_s_asneeded` in codemodel link fragments; it is a real system library.
|
|
return tok == "-pthread" || tok == "-lpthread" || tok == "-ldl" || tok == "-lm" ||
|
|
tok == "-lrt" || tok == "-lgcc" || tok == "-lgcc_s" || tok == "-lgcc_s_asneeded" ||
|
|
tok.starts_with("-Wl,");
|
|
}
|
|
|
|
std::string trim_copy(std::string_view sv) {
|
|
while (!sv.empty() && (sv.front() == ' ' || sv.front() == '\t' || sv.front() == '\r')) {
|
|
sv.remove_prefix(1);
|
|
}
|
|
while (!sv.empty() && (sv.back() == ' ' || sv.back() == '\t' || sv.back() == '\r')) {
|
|
sv.remove_suffix(1);
|
|
}
|
|
return std::string{sv};
|
|
}
|
|
|
|
std::optional<CStandard> parse_c_std_flag(std::string_view tok) {
|
|
if (tok == "-std=c11" || tok == "-std=gnu11") {
|
|
return CStandard::C11;
|
|
}
|
|
if (tok == "-std=c17" || tok == "-std=gnu17" || tok == "-std=c18" || tok == "-std=gnu18") {
|
|
return CStandard::C17;
|
|
}
|
|
if (tok == "-std=c23" || tok == "-std=gnu23" || tok == "-std=c2x" || tok == "-std=gnu2x") {
|
|
return CStandard::C23;
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
std::optional<CxxStandard> parse_cxx_std_flag(std::string_view tok) {
|
|
if (tok == "-std=c++17" || tok == "-std=gnu++17") {
|
|
return CxxStandard::Cxx17;
|
|
}
|
|
if (tok == "-std=c++20" || tok == "-std=gnu++20") {
|
|
return CxxStandard::Cxx20;
|
|
}
|
|
if (tok == "-std=c++23" || tok == "-std=gnu++23") {
|
|
return CxxStandard::Cxx23;
|
|
}
|
|
if (tok == "-std=c++26" || tok == "-std=gnu++26") {
|
|
return CxxStandard::Cxx26;
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
bool is_ninja_ident_char(char c) {
|
|
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
|
|
c == '-';
|
|
}
|
|
|
|
std::vector<std::string> split_ninja_logical_lines(std::string_view text) {
|
|
std::vector<std::string> lines;
|
|
std::string cur;
|
|
bool continuing = false;
|
|
std::size_t pos = 0;
|
|
while (pos < text.size()) {
|
|
const auto nl = text.find('\n', pos);
|
|
std::string_view phys =
|
|
text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
|
|
if (!phys.empty() && phys.back() == '\r') {
|
|
phys.remove_suffix(1);
|
|
}
|
|
pos = (nl == std::string_view::npos) ? text.size() : (nl + 1);
|
|
|
|
if (continuing) {
|
|
while (!phys.empty() && (phys.front() == ' ' || phys.front() == '\t')) {
|
|
phys.remove_prefix(1);
|
|
}
|
|
}
|
|
cur.append(phys);
|
|
|
|
std::size_t trailing_dollars = 0;
|
|
for (auto it = cur.rbegin(); it != cur.rend() && *it == '$'; ++it) {
|
|
++trailing_dollars;
|
|
}
|
|
if ((trailing_dollars % 2) == 1 && pos <= text.size() && nl != std::string_view::npos) {
|
|
cur.pop_back();
|
|
continuing = true;
|
|
continue;
|
|
}
|
|
continuing = false;
|
|
lines.push_back(std::move(cur));
|
|
cur.clear();
|
|
}
|
|
if (!cur.empty()) {
|
|
lines.push_back(std::move(cur));
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
std::string expand_ninja_vars(std::string_view sv,
|
|
const std::map<std::string, std::string, std::less<>> &vars,
|
|
bool unescape_path_escapes, bool preserve_unknown) {
|
|
std::string out;
|
|
out.reserve(sv.size());
|
|
for (std::size_t i = 0; i < sv.size();) {
|
|
if (sv[i] != '$') {
|
|
out.push_back(sv[i++]);
|
|
continue;
|
|
}
|
|
if (i + 1 >= sv.size()) {
|
|
out.push_back('$');
|
|
break;
|
|
}
|
|
const char next = sv[i + 1];
|
|
if (next == '$') {
|
|
out.push_back('$');
|
|
i += 2;
|
|
} else if (next == ' ' || next == ':') {
|
|
if (unescape_path_escapes) {
|
|
out.push_back(next);
|
|
} else {
|
|
out.push_back('$');
|
|
out.push_back(next);
|
|
}
|
|
i += 2;
|
|
} else if (next == '{') {
|
|
const auto close = sv.find('}', i + 2);
|
|
if (close == std::string_view::npos) {
|
|
out.push_back(sv[i++]);
|
|
continue;
|
|
}
|
|
const auto name = sv.substr(i + 2, close - (i + 2));
|
|
if (const auto vit = vars.find(name); vit != vars.end()) {
|
|
out.append(vit->second);
|
|
} else if (preserve_unknown) {
|
|
out.append(sv.substr(i, close + 1 - i));
|
|
}
|
|
i = close + 1;
|
|
} else if (is_ninja_ident_char(next)) {
|
|
std::size_t end = i + 2;
|
|
while (end < sv.size() && is_ninja_ident_char(sv[end])) {
|
|
++end;
|
|
}
|
|
const auto name = sv.substr(i + 1, end - (i + 1));
|
|
if (const auto vit = vars.find(name); vit != vars.end()) {
|
|
out.append(vit->second);
|
|
} else if (preserve_unknown) {
|
|
out.append(sv.substr(i, end - i));
|
|
}
|
|
i = end;
|
|
} else {
|
|
out.push_back('$');
|
|
++i;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
std::vector<std::string> tokenize_ninja_raw_list(std::string_view sv) {
|
|
std::vector<std::string> tokens;
|
|
std::string cur;
|
|
for (std::size_t i = 0; i < sv.size(); ++i) {
|
|
if (sv[i] == '$' && i + 1 < sv.size() && (sv[i + 1] == ' ' || sv[i + 1] == ':')) {
|
|
cur.push_back(sv[i]);
|
|
cur.push_back(sv[i + 1]);
|
|
++i;
|
|
continue;
|
|
}
|
|
if (sv[i] == ' ' || sv[i] == '\t') {
|
|
if (!cur.empty()) {
|
|
tokens.push_back(std::move(cur));
|
|
cur.clear();
|
|
}
|
|
continue;
|
|
}
|
|
cur.push_back(sv[i]);
|
|
}
|
|
if (!cur.empty()) {
|
|
tokens.push_back(std::move(cur));
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
std::size_t find_unescaped_ninja_colon(std::string_view sv) {
|
|
for (std::size_t i = 0; i < sv.size(); ++i) {
|
|
if (sv[i] == '$' && i + 1 < sv.size()) {
|
|
++i;
|
|
continue;
|
|
}
|
|
if (sv[i] == ':') {
|
|
return i;
|
|
}
|
|
}
|
|
return std::string_view::npos;
|
|
}
|
|
|
|
struct NinjaCustomEdge {
|
|
std::size_t index{0};
|
|
std::vector<std::filesystem::path> all_outputs;
|
|
std::vector<std::filesystem::path> concrete_outputs;
|
|
std::vector<std::filesystem::path> file_inputs;
|
|
std::vector<std::string> raw_all_inputs;
|
|
std::vector<std::string> raw_order_inputs;
|
|
std::string command;
|
|
std::filesystem::path working_directory;
|
|
std::vector<std::string> command_argv;
|
|
std::string pool;
|
|
bool is_noop_util{false};
|
|
bool is_valid{false};
|
|
std::string unsupported_kind;
|
|
std::string unsupported_detail;
|
|
};
|
|
|
|
struct NinjaCustomGraph {
|
|
std::filesystem::path configure_dir;
|
|
std::filesystem::path source_root;
|
|
bool found_build_ninja{false};
|
|
std::vector<NinjaCustomEdge> edges;
|
|
std::map<std::string, std::size_t, std::less<>> edge_by_output;
|
|
std::map<std::string, std::vector<std::string>, std::less<>> phony_by_target;
|
|
// Maps compiler input source file path -> list of extra implicit/order-only dependency paths.
|
|
std::map<std::filesystem::path, std::vector<std::filesystem::path>> compiler_extra_deps_by_src;
|
|
};
|
|
|
|
bool is_cmake_internal_stamp_path(const std::filesystem::path &p,
|
|
const std::filesystem::path &cfg_norm) {
|
|
const auto rel = p.lexically_relative(cfg_norm);
|
|
const auto rel_s = rel.generic_string();
|
|
return rel_s.starts_with("CMakeFiles/") || p.extension() == ".util";
|
|
}
|
|
|
|
bool validate_and_parse_custom_command(NinjaCustomEdge &edge, const std::filesystem::path &cfg_norm,
|
|
const std::filesystem::path &src_norm) {
|
|
if (edge.pool == "console") {
|
|
edge.unsupported_kind = "console_pool";
|
|
edge.unsupported_detail = "custom rule uses console pool (interactive terminal rules are "
|
|
"outside bounded hermetic translation)";
|
|
return false;
|
|
}
|
|
|
|
std::string cmd = trim_copy(edge.command);
|
|
edge.working_directory = cfg_norm;
|
|
|
|
// Strip leading POSIX CMake `cd <dir> && ` wrapper into working_directory.
|
|
if (cmd.starts_with("cd ")) {
|
|
std::size_t p = 3;
|
|
while (p < cmd.size() && (cmd[p] == ' ' || cmd[p] == '\t')) {
|
|
++p;
|
|
}
|
|
std::string dir_tok;
|
|
bool in_single = false;
|
|
bool in_double = false;
|
|
bool esc = false;
|
|
while (p < cmd.size()) {
|
|
const char c = cmd[p];
|
|
if (esc) {
|
|
dir_tok.push_back(c);
|
|
esc = false;
|
|
++p;
|
|
continue;
|
|
}
|
|
if (c == '\\' && !in_single) {
|
|
esc = true;
|
|
++p;
|
|
continue;
|
|
}
|
|
if (c == '\'' && !in_double) {
|
|
in_single = !in_single;
|
|
++p;
|
|
continue;
|
|
}
|
|
if (c == '"' && !in_single) {
|
|
in_double = !in_double;
|
|
++p;
|
|
continue;
|
|
}
|
|
if (!in_single && !in_double && (c == ' ' || c == '\t')) {
|
|
break;
|
|
}
|
|
dir_tok.push_back(c);
|
|
++p;
|
|
}
|
|
while (p < cmd.size() && (cmd[p] == ' ' || cmd[p] == '\t')) {
|
|
++p;
|
|
}
|
|
if (p + 1 < cmd.size() && cmd[p] == '&' && cmd[p + 1] == '&' && !dir_tok.empty()) {
|
|
std::filesystem::path wd{dir_tok};
|
|
wd = (wd.is_absolute() ? wd : (cfg_norm / wd)).lexically_normal();
|
|
if (!Platform::path_is_within(cfg_norm, wd) &&
|
|
(src_norm.empty() || !Platform::path_is_within(src_norm, wd))) {
|
|
edge.unsupported_kind = "out_of_tree_working_directory";
|
|
edge.unsupported_detail = std::format(
|
|
"custom rule sets working directory '{}' outside configure/source root",
|
|
wd.string());
|
|
return false;
|
|
}
|
|
edge.working_directory = wd;
|
|
cmd = trim_copy(std::string_view{cmd}.substr(p + 2));
|
|
}
|
|
}
|
|
|
|
const bool all_internal_stamps =
|
|
!edge.all_outputs.empty() &&
|
|
std::ranges::all_of(edge.all_outputs, [&](const std::filesystem::path &op) {
|
|
return is_cmake_internal_stamp_path(op, cfg_norm);
|
|
});
|
|
|
|
if (cmd.empty() || cmd == ":" || cmd == "true") {
|
|
if (all_internal_stamps) {
|
|
edge.is_noop_util = true;
|
|
edge.is_valid = true;
|
|
return true;
|
|
}
|
|
edge.unsupported_kind = "empty_custom_command";
|
|
edge.unsupported_detail = "custom rule declares outputs without an executable COMMAND";
|
|
return false;
|
|
}
|
|
|
|
if (edge.concrete_outputs.empty()) {
|
|
edge.unsupported_kind = "utility_without_hermetic_outputs";
|
|
edge.unsupported_detail =
|
|
"custom/utility target executes side-effect commands with only stamp/.util outputs";
|
|
return false;
|
|
}
|
|
|
|
for (const auto &out_p : edge.concrete_outputs) {
|
|
if (!Platform::path_is_within(cfg_norm, out_p)) {
|
|
edge.unsupported_kind = "out_of_tree_custom_output";
|
|
edge.unsupported_detail =
|
|
std::format("custom command output '{}' escapes configure_dir '{}'", out_p.string(),
|
|
cfg_norm.string());
|
|
return false;
|
|
}
|
|
if (!src_norm.empty() && cfg_norm == src_norm) {
|
|
edge.unsupported_kind = "out_of_tree_custom_output";
|
|
edge.unsupported_detail = std::format(
|
|
"custom command output '{}' runs in-source build overlapping source_root '{}'",
|
|
out_p.string(), src_norm.string());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (cmd.find("--regenerate-build-system") != std::string::npos ||
|
|
cmd.find("meson --internal regenerate") != std::string::npos) {
|
|
edge.unsupported_kind = "build_system_regeneration";
|
|
edge.unsupported_detail = "custom rule recursively regenerates foreign build system files";
|
|
return false;
|
|
}
|
|
|
|
// Scan unquoted characters for subshells, arbitrary chaining, or out-of-tree redirections.
|
|
bool has_shell_chain = false;
|
|
bool in_single = false;
|
|
bool in_double = false;
|
|
bool esc = false;
|
|
for (std::size_t i = 0; i < cmd.size(); ++i) {
|
|
const char c = cmd[i];
|
|
if (esc) {
|
|
esc = false;
|
|
continue;
|
|
}
|
|
if (c == '\\' && !in_single) {
|
|
esc = true;
|
|
continue;
|
|
}
|
|
if (c == '\'' && !in_double) {
|
|
in_single = !in_single;
|
|
continue;
|
|
}
|
|
if (c == '"' && !in_single) {
|
|
in_double = !in_double;
|
|
continue;
|
|
}
|
|
if (in_single || in_double) {
|
|
continue;
|
|
}
|
|
if (c == '`' || (c == '$' && i + 1 < cmd.size() && cmd[i + 1] == '(')) {
|
|
edge.unsupported_kind = "unbounded_shell_custom_command";
|
|
edge.unsupported_detail =
|
|
"custom command uses unquoted shell command substitution (`...` or $(...))";
|
|
return false;
|
|
}
|
|
if (c == '&' && i + 1 < cmd.size() && cmd[i + 1] == '&') {
|
|
has_shell_chain = true;
|
|
++i;
|
|
continue;
|
|
}
|
|
if (c == '>') {
|
|
has_shell_chain = true;
|
|
std::size_t rp = i + 1;
|
|
if (rp < cmd.size() && cmd[rp] == '>') {
|
|
++rp;
|
|
}
|
|
while (rp < cmd.size() && (cmd[rp] == ' ' || cmd[rp] == '\t')) {
|
|
++rp;
|
|
}
|
|
std::size_t rend = rp;
|
|
while (rend < cmd.size() && cmd[rend] != ' ' && cmd[rend] != '\t') {
|
|
++rend;
|
|
}
|
|
std::string redir = cmd.substr(rp, rend - rp);
|
|
if (!redir.empty() && redir.size() >= 2 &&
|
|
((redir.front() == '"' && redir.back() == '"') ||
|
|
(redir.front() == '\'' && redir.back() == '\''))) {
|
|
redir = redir.substr(1, redir.size() - 2);
|
|
}
|
|
if (redir.empty()) {
|
|
edge.unsupported_kind = "out_of_tree_custom_output";
|
|
edge.unsupported_detail = "custom command has unparsed shell output redirection";
|
|
return false;
|
|
}
|
|
const std::filesystem::path rpath =
|
|
(std::filesystem::path{redir}.is_absolute() ? std::filesystem::path{redir}
|
|
: (edge.working_directory / redir))
|
|
.lexically_normal();
|
|
if (!Platform::path_is_within(cfg_norm, rpath)) {
|
|
edge.unsupported_kind = "out_of_tree_custom_output";
|
|
edge.unsupported_detail = std::format(
|
|
"custom command shell redirection target '{}' escapes configure_dir '{}'",
|
|
rpath.string(), cfg_norm.string());
|
|
return false;
|
|
}
|
|
continue;
|
|
}
|
|
if (c == ';' || c == '|' || c == '<') {
|
|
has_shell_chain = true;
|
|
}
|
|
}
|
|
|
|
if (has_shell_chain) {
|
|
edge.command_argv = {"/bin/sh", "-c", cmd};
|
|
} else {
|
|
edge.command_argv = split_shell_tokens(cmd);
|
|
}
|
|
if (edge.command_argv.empty()) {
|
|
edge.unsupported_kind = "empty_custom_command";
|
|
edge.unsupported_detail = "custom rule produced an empty command argv";
|
|
return false;
|
|
}
|
|
edge.is_valid = true;
|
|
return true;
|
|
}
|
|
|
|
NinjaCustomGraph parse_ninja_custom_graph(const std::filesystem::path &configure_dir,
|
|
const std::filesystem::path &source_root) {
|
|
NinjaCustomGraph ng;
|
|
ng.configure_dir = configure_dir.lexically_normal();
|
|
ng.source_root = source_root.lexically_normal();
|
|
|
|
auto text = Void::FileSystem::read_file(ng.configure_dir / "build.ninja");
|
|
if (!text) {
|
|
return ng;
|
|
}
|
|
ng.found_build_ninja = true;
|
|
|
|
const auto lines = split_ninja_logical_lines(*text);
|
|
std::map<std::string, std::string, std::less<>> ninja_vars;
|
|
std::optional<std::size_t> active_custom_edge;
|
|
|
|
auto index_output_key = [&](const std::string &raw_key, std::size_t edge_idx) {
|
|
if (raw_key.empty()) {
|
|
return;
|
|
}
|
|
ng.edge_by_output.try_emplace(raw_key, edge_idx);
|
|
const std::filesystem::path p{raw_key};
|
|
const auto norm = (p.is_absolute() ? p : (ng.configure_dir / p)).lexically_normal();
|
|
ng.edge_by_output.try_emplace(norm.generic_string(), edge_idx);
|
|
};
|
|
|
|
for (const auto &line : lines) {
|
|
const std::string trimmed = trim_copy(line);
|
|
if (trimmed.empty()) {
|
|
active_custom_edge.reset();
|
|
continue;
|
|
}
|
|
if (trimmed.front() == '#') {
|
|
continue;
|
|
}
|
|
|
|
const bool indented = (line.front() == ' ' || line.front() == '\t');
|
|
if (indented) {
|
|
if (!active_custom_edge) {
|
|
continue;
|
|
}
|
|
const auto eq = trimmed.find('=');
|
|
if (eq == std::string::npos) {
|
|
continue;
|
|
}
|
|
const std::string key = trim_copy(std::string_view{trimmed}.substr(0, eq));
|
|
const std::string val = expand_ninja_vars(
|
|
trim_copy(std::string_view{trimmed}.substr(eq + 1)), ninja_vars, false, true);
|
|
auto &edge = ng.edges[*active_custom_edge];
|
|
if (key == "COMMAND") {
|
|
edge.command = val;
|
|
} else if (key == "pool") {
|
|
edge.pool = val;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
active_custom_edge.reset();
|
|
|
|
if (line.starts_with("build ")) {
|
|
const auto rest = std::string_view{line}.substr(6);
|
|
const auto colon = find_unescaped_ninja_colon(rest);
|
|
if (colon == std::string_view::npos) {
|
|
continue;
|
|
}
|
|
const auto lhs = rest.substr(0, colon);
|
|
const auto rhs = rest.substr(colon + 1);
|
|
|
|
std::vector<std::string> outs;
|
|
bool in_imp_outs = false;
|
|
for (const auto &rtok : tokenize_ninja_raw_list(lhs)) {
|
|
if (rtok == "|") {
|
|
in_imp_outs = true;
|
|
continue;
|
|
}
|
|
(void)in_imp_outs;
|
|
outs.push_back(expand_ninja_vars(rtok, ninja_vars, true, false));
|
|
}
|
|
|
|
const auto rhs_tokens = tokenize_ninja_raw_list(rhs);
|
|
if (rhs_tokens.empty()) {
|
|
continue;
|
|
}
|
|
const std::string rule = expand_ninja_vars(rhs_tokens.front(), ninja_vars, true, false);
|
|
std::vector<std::string> exp_ins;
|
|
std::vector<std::string> imp_ins;
|
|
std::vector<std::string> order_ins;
|
|
int section = 0; // 0: explicit, 1: implicit, 2: order-only
|
|
for (std::size_t i = 1; i < rhs_tokens.size(); ++i) {
|
|
const auto &rtok = rhs_tokens[i];
|
|
if (rtok == "||") {
|
|
section = 2;
|
|
continue;
|
|
}
|
|
if (rtok == "|") {
|
|
section = 1;
|
|
continue;
|
|
}
|
|
const std::string expanded = expand_ninja_vars(rtok, ninja_vars, true, false);
|
|
if (section == 0) {
|
|
exp_ins.push_back(expanded);
|
|
} else if (section == 1) {
|
|
imp_ins.push_back(expanded);
|
|
} else {
|
|
order_ins.push_back(expanded);
|
|
}
|
|
}
|
|
|
|
if (rule == "phony") {
|
|
std::vector<std::string> all_in;
|
|
all_in.insert(all_in.end(), exp_ins.begin(), exp_ins.end());
|
|
all_in.insert(all_in.end(), imp_ins.begin(), imp_ins.end());
|
|
all_in.insert(all_in.end(), order_ins.begin(), order_ins.end());
|
|
for (const auto &o : outs) {
|
|
ng.phony_by_target[o] = all_in;
|
|
const std::filesystem::path p{o};
|
|
const auto norm =
|
|
(p.is_absolute() ? p : (ng.configure_dir / p)).lexically_normal();
|
|
ng.phony_by_target.try_emplace(norm.generic_string(), all_in);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (rule == "CUSTOM_COMMAND" || rule == "CUSTOM_COMMAND_ph") {
|
|
NinjaCustomEdge edge;
|
|
edge.index = ng.edges.size();
|
|
std::set<std::filesystem::path> seen_outs;
|
|
for (const auto &o : outs) {
|
|
const std::filesystem::path p{o};
|
|
const auto norm =
|
|
(p.is_absolute() ? p : (ng.configure_dir / p)).lexically_normal();
|
|
if (seen_outs.insert(norm).second) {
|
|
edge.all_outputs.push_back(norm);
|
|
if (!is_cmake_internal_stamp_path(norm, ng.configure_dir)) {
|
|
edge.concrete_outputs.push_back(norm);
|
|
}
|
|
}
|
|
index_output_key(o, edge.index);
|
|
}
|
|
auto add_in_tokens = [&](const std::vector<std::string> &vec) {
|
|
for (const auto &in : vec) {
|
|
if (!in.empty() && !std::ranges::contains(edge.raw_all_inputs, in)) {
|
|
edge.raw_all_inputs.push_back(in);
|
|
}
|
|
}
|
|
};
|
|
add_in_tokens(exp_ins);
|
|
add_in_tokens(imp_ins);
|
|
add_in_tokens(order_ins);
|
|
edge.raw_order_inputs = std::move(order_ins);
|
|
ng.edges.push_back(std::move(edge));
|
|
active_custom_edge = ng.edges.size() - 1;
|
|
continue;
|
|
}
|
|
|
|
// Record implicit/order-only dependencies on compiler edges (used for Meson generated
|
|
// headers).
|
|
if (rule.ends_with("_COMPILER") && !exp_ins.empty()) {
|
|
const std::filesystem::path src_p{exp_ins.front()};
|
|
const auto src_abs =
|
|
(src_p.is_absolute() ? src_p : (ng.configure_dir / src_p)).lexically_normal();
|
|
auto &extras = ng.compiler_extra_deps_by_src[src_abs];
|
|
auto add_dep_list = [&](const std::vector<std::string> &vec) {
|
|
for (const auto &d : vec) {
|
|
if (d.empty()) {
|
|
continue;
|
|
}
|
|
const std::filesystem::path dp{d};
|
|
const auto d_abs =
|
|
(dp.is_absolute() ? dp : (ng.configure_dir / dp)).lexically_normal();
|
|
if (!std::ranges::contains(extras, d_abs)) {
|
|
extras.push_back(d_abs);
|
|
}
|
|
}
|
|
};
|
|
add_dep_list(imp_ins);
|
|
add_dep_list(order_ins);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (!line.starts_with("rule ") && !line.starts_with("pool ") &&
|
|
!line.starts_with("default ") && !line.starts_with("include ") &&
|
|
!line.starts_with("subninja ")) {
|
|
const auto eq = line.find('=');
|
|
if (eq != std::string::npos) {
|
|
const std::string key = trim_copy(std::string_view{line}.substr(0, eq));
|
|
const std::string val = expand_ninja_vars(
|
|
trim_copy(std::string_view{line}.substr(eq + 1)), ninja_vars, true, false);
|
|
if (!key.empty()) {
|
|
ninja_vars[key] = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (auto &edge : ng.edges) {
|
|
(void)validate_and_parse_custom_command(edge, ng.configure_dir, ng.source_root);
|
|
}
|
|
return ng;
|
|
}
|
|
|
|
class CustomActionMaterializer {
|
|
public:
|
|
CustomActionMaterializer(const NinjaCustomGraph &ng,
|
|
const std::set<std::string> &known_target_artifacts)
|
|
: ng_(ng), known_artifacts_(known_target_artifacts) {}
|
|
|
|
Void::Result::Result<std::vector<std::string>, UnsupportedConstruct>
|
|
materialize_key(std::string_view raw_key, std::string_view owner_target_name) {
|
|
std::vector<std::string> names;
|
|
std::set<std::string> visiting_keys;
|
|
if (!collect_for_key(raw_key, owner_target_name, visiting_keys, names)) {
|
|
return std::unexpected{std::move(*last_error_)};
|
|
}
|
|
return names;
|
|
}
|
|
|
|
std::vector<TargetRecord> targets;
|
|
|
|
private:
|
|
const NinjaCustomGraph &ng_;
|
|
const std::set<std::string> &known_artifacts_;
|
|
std::map<std::size_t, std::string> target_name_by_edge_;
|
|
std::set<std::size_t> active_edges_;
|
|
std::optional<UnsupportedConstruct> last_error_;
|
|
|
|
std::string normalize_lookup_key(std::string_view raw) const {
|
|
const std::filesystem::path p{raw};
|
|
return (p.is_absolute() ? p : (ng_.configure_dir / p)).lexically_normal().generic_string();
|
|
}
|
|
|
|
bool set_err(std::string_view target_name, std::string kind, std::string detail) {
|
|
last_error_ =
|
|
UnsupportedConstruct{std::string{target_name}, std::move(kind), std::move(detail)};
|
|
return false;
|
|
}
|
|
|
|
bool collect_for_key(std::string_view raw_key, std::string_view owner_target_name,
|
|
std::set<std::string> &visiting_keys,
|
|
std::vector<std::string> &out_names) {
|
|
const std::string key{raw_key};
|
|
const std::string norm_key = normalize_lookup_key(key);
|
|
if (!visiting_keys.insert(norm_key).second) {
|
|
return set_err(owner_target_name, "custom_command_cycle",
|
|
std::format("cycle detected while resolving custom rule '{}'", key));
|
|
}
|
|
|
|
bool ok = true;
|
|
if (auto eit = ng_.edge_by_output.find(key); eit != ng_.edge_by_output.end()) {
|
|
ok = materialize_edge(eit->second, owner_target_name, visiting_keys, out_names);
|
|
} else if (auto eit2 = ng_.edge_by_output.find(norm_key);
|
|
eit2 != ng_.edge_by_output.end()) {
|
|
ok = materialize_edge(eit2->second, owner_target_name, visiting_keys, out_names);
|
|
} else {
|
|
const std::vector<std::string> *phony_ins = nullptr;
|
|
if (auto pit = ng_.phony_by_target.find(key); pit != ng_.phony_by_target.end()) {
|
|
phony_ins = &pit->second;
|
|
} else if (auto pit2 = ng_.phony_by_target.find(norm_key);
|
|
pit2 != ng_.phony_by_target.end()) {
|
|
phony_ins = &pit2->second;
|
|
}
|
|
if (phony_ins) {
|
|
for (const auto &in_tok : *phony_ins) {
|
|
if (in_tok == "cmake_force" || in_tok == "always" ||
|
|
in_tok.starts_with("CMakeFiles/cmake_object_order_depends_target_")) {
|
|
continue;
|
|
}
|
|
if (!collect_for_key(in_tok, owner_target_name, visiting_keys, out_names)) {
|
|
ok = false;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
visiting_keys.erase(norm_key);
|
|
return ok;
|
|
}
|
|
|
|
bool materialize_edge(std::size_t edge_idx, std::string_view owner_target_name,
|
|
std::set<std::string> &visiting_keys,
|
|
std::vector<std::string> &out_names) {
|
|
const auto &edge = ng_.edges[edge_idx];
|
|
if (!edge.is_valid) {
|
|
return set_err(owner_target_name, edge.unsupported_kind, edge.unsupported_detail);
|
|
}
|
|
if (edge.is_noop_util) {
|
|
for (const auto &in_tok : edge.raw_all_inputs) {
|
|
if (in_tok == "cmake_force" ||
|
|
in_tok.starts_with("CMakeFiles/cmake_object_order_depends_target_")) {
|
|
continue;
|
|
}
|
|
if (!collect_for_key(in_tok, owner_target_name, visiting_keys, out_names)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (const auto existing = target_name_by_edge_.find(edge_idx);
|
|
existing != target_name_by_edge_.end()) {
|
|
if (!std::ranges::contains(out_names, existing->second)) {
|
|
out_names.push_back(existing->second);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (!active_edges_.insert(edge_idx).second) {
|
|
return set_err(owner_target_name, "custom_command_cycle",
|
|
"cyclic CUSTOM_COMMAND dependency detected in build.ninja");
|
|
}
|
|
|
|
// Reject custom rules invoking/depending on an executable or library compiled in-tree.
|
|
for (const auto &in_tok : edge.raw_all_inputs) {
|
|
const auto norm =
|
|
(std::filesystem::path{in_tok}.is_absolute() ? std::filesystem::path{in_tok}
|
|
: (ng_.configure_dir / in_tok))
|
|
.lexically_normal();
|
|
if (known_artifacts_.contains(in_tok) || known_artifacts_.contains(norm.string()) ||
|
|
known_artifacts_.contains(norm.filename().string())) {
|
|
active_edges_.erase(edge_idx);
|
|
return set_err(
|
|
owner_target_name, "in_tree_tool_custom_command",
|
|
std::format("custom command depends on built in-tree artifact '{}'", in_tok));
|
|
}
|
|
}
|
|
|
|
std::vector<std::string> upstream_prereqs;
|
|
std::vector<std::string> action_inputs;
|
|
for (const auto &in_tok : edge.raw_all_inputs) {
|
|
if (in_tok == "cmake_force" || in_tok == "always" ||
|
|
in_tok.starts_with("CMakeFiles/cmake_object_order_depends_target_")) {
|
|
continue;
|
|
}
|
|
const auto norm_in =
|
|
(std::filesystem::path{in_tok}.is_absolute() ? std::filesystem::path{in_tok}
|
|
: (ng_.configure_dir / in_tok))
|
|
.lexically_normal();
|
|
if (ng_.edge_by_output.contains(in_tok) ||
|
|
ng_.edge_by_output.contains(norm_in.generic_string()) ||
|
|
ng_.phony_by_target.contains(in_tok) ||
|
|
ng_.phony_by_target.contains(norm_in.generic_string())) {
|
|
std::set<std::string> sub_visit;
|
|
if (!collect_for_key(in_tok, owner_target_name, sub_visit, upstream_prereqs)) {
|
|
active_edges_.erase(edge_idx);
|
|
return false;
|
|
}
|
|
}
|
|
if (!is_cmake_internal_stamp_path(norm_in, ng_.configure_dir) &&
|
|
!ng_.phony_by_target.contains(in_tok) &&
|
|
!ng_.phony_by_target.contains(norm_in.generic_string())) {
|
|
if (std::filesystem::exists(norm_in) ||
|
|
ng_.edge_by_output.contains(norm_in.generic_string())) {
|
|
if (!std::ranges::contains(action_inputs, norm_in.string())) {
|
|
action_inputs.push_back(norm_in.string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
TargetRecord tr;
|
|
tr.name = std::format("__vbs_custom_{}_{}", edge_idx,
|
|
edge.concrete_outputs.front().filename().string());
|
|
tr.kind = TargetKind::CustomAction;
|
|
tr.command_argv = edge.command_argv;
|
|
tr.working_directory = edge.working_directory.string();
|
|
tr.action_inputs = std::move(action_inputs);
|
|
for (const auto &out_p : edge.concrete_outputs) {
|
|
tr.action_outputs.push_back(out_p.string());
|
|
}
|
|
tr.prerequisites = std::move(upstream_prereqs);
|
|
|
|
const std::string created_name = tr.name;
|
|
target_name_by_edge_[edge_idx] = created_name;
|
|
targets.push_back(std::move(tr));
|
|
active_edges_.erase(edge_idx);
|
|
|
|
if (!std::ranges::contains(out_names, created_name)) {
|
|
out_names.push_back(created_name);
|
|
}
|
|
return true;
|
|
}
|
|
};
|
|
|
|
struct ParsedCMakeTarget {
|
|
std::string id;
|
|
std::string name;
|
|
std::string type;
|
|
std::vector<SourceRecord> sources;
|
|
std::vector<std::pair<std::filesystem::path, bool>> includes;
|
|
std::vector<std::string> defines;
|
|
std::vector<std::string> compile_options;
|
|
std::vector<PerFileOption> per_file_options;
|
|
std::vector<std::string> link_options;
|
|
CStandard c_standard{CStandard::Default};
|
|
CxxStandard cxx_standard{CxxStandard::Default};
|
|
std::vector<std::string> dep_ids;
|
|
std::vector<std::string> prereq_target_names;
|
|
std::vector<std::string> artifact_rel_paths;
|
|
};
|
|
|
|
struct ParsedCMakeCodemodel {
|
|
std::filesystem::path source_root;
|
|
std::filesystem::path build_root;
|
|
TranslationAuditReport audit;
|
|
std::vector<TargetRecord> synthesized_custom_targets;
|
|
std::map<std::string, std::vector<std::string>, std::less<>> utility_target_prereqs;
|
|
std::map<std::string, ParsedCMakeTarget, std::less<>> targets_by_id;
|
|
std::vector<std::string> target_order;
|
|
};
|
|
|
|
Void::Result::Result<ParsedCMakeCodemodel, Void::Result::Error>
|
|
load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
|
|
const auto reply_dir = configure_dir / ".cmake" / "api" / "v1" / "reply";
|
|
std::error_code ec;
|
|
if (!std::filesystem::is_directory(reply_dir, ec)) {
|
|
return std::unexpected{make_error(
|
|
Void::System::SystemErrorCode::not_found,
|
|
std::format("CMake File API reply directory missing at '{}'", reply_dir.string()))};
|
|
}
|
|
|
|
std::vector<std::filesystem::path> indices;
|
|
for (const auto &entry : std::filesystem::directory_iterator(reply_dir, ec)) {
|
|
const auto name = entry.path().filename().string();
|
|
if (name.starts_with("index-") && name.ends_with(".json")) {
|
|
indices.push_back(entry.path());
|
|
}
|
|
}
|
|
std::ranges::sort(indices);
|
|
if (indices.empty()) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
|
"CMake File API reply contains no index-*.json")};
|
|
}
|
|
|
|
auto index_json = parse_json_file(indices.back());
|
|
if (!index_json) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
|
"failed parsing CMake File API index JSON")};
|
|
}
|
|
const auto *idx_obj = std::get_if<JsonVal::Object>(&index_json->value);
|
|
const auto *reply_v = idx_obj ? find_key(*idx_obj, "reply") : nullptr;
|
|
const auto *reply_obj = reply_v ? std::get_if<JsonVal::Object>(&reply_v->value) : nullptr;
|
|
const auto *cm_v = reply_obj ? find_key(*reply_obj, "codemodel-v2") : nullptr;
|
|
const auto *cm_obj = cm_v ? std::get_if<JsonVal::Object>(&cm_v->value) : nullptr;
|
|
const std::string cm_file = cm_obj ? get_str(*cm_obj, "jsonFile") : std::string{};
|
|
if (cm_file.empty()) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
|
"CMake File API index missing codemodel-v2 entry")};
|
|
}
|
|
|
|
auto cm_json = parse_json_file(reply_dir / cm_file);
|
|
if (!cm_json) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
|
"failed parsing CMake codemodel-v2 JSON")};
|
|
}
|
|
const auto *cm_root = std::get_if<JsonVal::Object>(&cm_json->value);
|
|
if (!cm_root) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
|
"CMake codemodel-v2 root must be a JSON object")};
|
|
}
|
|
|
|
ParsedCMakeCodemodel out;
|
|
if (const auto *paths_v = find_key(*cm_root, "paths")) {
|
|
if (const auto *pobj = std::get_if<JsonVal::Object>(&paths_v->value)) {
|
|
out.source_root = std::filesystem::path{get_str(*pobj, "source")}.lexically_normal();
|
|
out.build_root = std::filesystem::path{get_str(*pobj, "build")}.lexically_normal();
|
|
}
|
|
}
|
|
|
|
auto add_unsupported = [&](std::string target_name, std::string kind, std::string detail) {
|
|
out.audit.status = TranslationStatus::Unsupported;
|
|
out.audit.unsupported.push_back(
|
|
UnsupportedConstruct{std::move(target_name), std::move(kind), std::move(detail)});
|
|
};
|
|
|
|
// First pass: load all target JSON files and collect known artifact basenames/paths.
|
|
std::vector<std::pair<std::string, JsonVal>> raw_target_docs;
|
|
std::set<std::string> known_target_artifacts;
|
|
|
|
if (const auto *cfgs_v = find_key(*cm_root, "configurations")) {
|
|
if (const auto *carr = std::get_if<JsonVal::Array>(&cfgs_v->value)) {
|
|
if (carr->size() > 1) {
|
|
add_unsupported(
|
|
"<codemodel>", "multi_config",
|
|
"multi-configuration generators are outside the bounded single-config "
|
|
"translation subset");
|
|
}
|
|
if (!carr->empty()) {
|
|
if (const auto *cobj = std::get_if<JsonVal::Object>(&carr->front().value)) {
|
|
if (const auto *targets_v = find_key(*cobj, "targets")) {
|
|
if (const auto *tarr = std::get_if<JsonVal::Array>(&targets_v->value)) {
|
|
for (const auto &tv : *tarr) {
|
|
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
|
|
if (!to) {
|
|
continue;
|
|
}
|
|
const auto jf = get_str(*to, "jsonFile");
|
|
if (jf.empty()) {
|
|
continue;
|
|
}
|
|
auto tdoc = parse_json_file(reply_dir / jf);
|
|
if (!tdoc) {
|
|
add_unsupported(get_str(*to, "name"), "missing_target_json",
|
|
"failed reading target JSON '" + jf + "'");
|
|
continue;
|
|
}
|
|
if (const auto *td = std::get_if<JsonVal::Object>(&tdoc->value)) {
|
|
if (const auto *arts = find_key(*td, "artifacts")) {
|
|
if (const auto *aarr =
|
|
std::get_if<JsonVal::Array>(&arts->value)) {
|
|
for (const auto &av : *aarr) {
|
|
if (const auto *ao =
|
|
std::get_if<JsonVal::Object>(&av.value)) {
|
|
const auto p = get_str(*ao, "path");
|
|
if (!p.empty()) {
|
|
known_target_artifacts.insert(p);
|
|
known_target_artifacts.insert(
|
|
std::filesystem::path{p}
|
|
.filename()
|
|
.string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
raw_target_docs.emplace_back(jf, std::move(*tdoc));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Parse Ninja custom commands/utility graph when configured with Ninja (Plan 21 Track B2).
|
|
const NinjaCustomGraph ninja_graph = parse_ninja_custom_graph(configure_dir, out.source_root);
|
|
CustomActionMaterializer custom_mat{ninja_graph, known_target_artifacts};
|
|
|
|
// Second pass: audit every target strictly and build ParsedCMakeTarget records.
|
|
for (const auto &[jf, tdoc] : raw_target_docs) {
|
|
const auto *td = std::get_if<JsonVal::Object>(&tdoc.value);
|
|
if (!td) {
|
|
continue;
|
|
}
|
|
ParsedCMakeTarget pt;
|
|
pt.id = get_str(*td, "id");
|
|
pt.name = get_str(*td, "name");
|
|
pt.type = get_str(*td, "type");
|
|
|
|
if (pt.type == "UTILITY") {
|
|
if (!ninja_graph.found_build_ninja) {
|
|
add_unsupported(
|
|
pt.name, "utility_target",
|
|
std::format("CMake UTILITY target '{}' cannot be translated without "
|
|
"build.ninja (configure with Ninja)",
|
|
pt.name));
|
|
continue;
|
|
}
|
|
const std::string candidates[] = {pt.name, "CMakeFiles/" + pt.name, pt.name + ".util"};
|
|
bool matched = false;
|
|
std::vector<std::string> resolved_names;
|
|
for (const auto &cand : candidates) {
|
|
if (ninja_graph.edge_by_output.contains(cand) ||
|
|
ninja_graph.phony_by_target.contains(cand)) {
|
|
matched = true;
|
|
auto mres = custom_mat.materialize_key(cand, pt.name);
|
|
if (!mres) {
|
|
add_unsupported(pt.name, mres.error().construct_kind, mres.error().detail);
|
|
matched = true;
|
|
resolved_names.clear();
|
|
goto done_utility;
|
|
}
|
|
for (const auto &cn : *mres) {
|
|
if (!std::ranges::contains(resolved_names, cn)) {
|
|
resolved_names.push_back(cn);
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
if (!matched || resolved_names.empty()) {
|
|
add_unsupported(
|
|
pt.name, "utility_without_hermetic_outputs",
|
|
std::format("CMake UTILITY target '{}' does not produce verifiable hermetic "
|
|
"outputs inside configure_dir",
|
|
pt.name));
|
|
continue;
|
|
}
|
|
out.utility_target_prereqs[pt.id] = std::move(resolved_names);
|
|
out.audit.supported_targets.push_back(pt.name);
|
|
done_utility:
|
|
continue;
|
|
}
|
|
// CMake synthesizes @cmake_cxx_std@(synth_N) INTERFACE_LIBRARY carriers for
|
|
// target_compile_features standards. The -std flag is already lowered from each
|
|
// consumer's compile groups, so these feature-only targets have no graph effect.
|
|
if (pt.type == "INTERFACE_LIBRARY" && pt.name.starts_with("@cmake_cxx_std")) {
|
|
continue;
|
|
}
|
|
if (pt.type == "GLOBAL_TARGET") {
|
|
add_unsupported(
|
|
pt.name, "utility_target",
|
|
std::format("CMake target '{}' has type '{}' (global build-system target is "
|
|
"outside native translation subset)",
|
|
pt.name, pt.type));
|
|
continue;
|
|
}
|
|
if (pt.type != "STATIC_LIBRARY" && pt.type != "SHARED_LIBRARY" &&
|
|
pt.type != "OBJECT_LIBRARY" && pt.type != "EXECUTABLE") {
|
|
add_unsupported(
|
|
pt.name, "unsupported_target_type",
|
|
std::format("CMake target '{}' has unsupported type '{}'", pt.name, pt.type));
|
|
continue;
|
|
}
|
|
|
|
// Index C++20 CXX_MODULES fileSets (`SourceKind::ModuleInterface`, Plan 21 Track B3).
|
|
std::set<std::size_t> module_fileset_indexes;
|
|
std::set<std::size_t> module_source_indexes;
|
|
if (const auto *fsets = find_key(*td, "fileSets")) {
|
|
if (const auto *farr = std::get_if<JsonVal::Array>(&fsets->value)) {
|
|
for (std::size_t fs_i = 0; fs_i < farr->size(); ++fs_i) {
|
|
if (const auto *fo = std::get_if<JsonVal::Object>(&(*farr)[fs_i].value)) {
|
|
if (get_str(*fo, "type") == "CXX_MODULES") {
|
|
module_fileset_indexes.insert(fs_i);
|
|
if (const auto *sidxs = find_key(*fo, "sourceIndexes")) {
|
|
if (const auto *sarr = std::get_if<JsonVal::Array>(&sidxs->value)) {
|
|
for (const auto &iv : *sarr) {
|
|
if (const auto *idx =
|
|
std::get_if<std::int64_t>(&iv.value)) {
|
|
module_source_indexes.insert(
|
|
static_cast<std::size_t>(*idx));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Collect sources and translate hermetic generated sources via build.ninja CUSTOM_COMMAND.
|
|
struct RawSource {
|
|
std::filesystem::path abs_path;
|
|
bool is_generated{false};
|
|
bool is_module_interface{false};
|
|
std::optional<std::int64_t> compile_group_index;
|
|
};
|
|
std::vector<RawSource> raw_sources;
|
|
if (const auto *srcs = find_key(*td, "sources")) {
|
|
if (const auto *sarr = std::get_if<JsonVal::Array>(&srcs->value)) {
|
|
for (std::size_t src_i = 0; src_i < sarr->size(); ++src_i) {
|
|
if (const auto *so = std::get_if<JsonVal::Object>(&(*sarr)[src_i].value)) {
|
|
RawSource rs;
|
|
const std::filesystem::path raw_p{get_str(*so, "path")};
|
|
rs.abs_path = (raw_p.is_absolute() ? raw_p : (out.source_root / raw_p))
|
|
.lexically_normal();
|
|
rs.is_generated = get_bool(*so, "isGenerated", false);
|
|
rs.compile_group_index = get_i64(*so, "compileGroupIndex");
|
|
const auto fs_idx = get_i64(*so, "fileSetIndex");
|
|
rs.is_module_interface =
|
|
module_source_indexes.contains(src_i) ||
|
|
(fs_idx.has_value() &&
|
|
module_fileset_indexes.contains(static_cast<std::size_t>(*fs_idx)));
|
|
if (rs.is_generated && rs.abs_path.extension() != ".rule") {
|
|
const auto gen_key = rs.abs_path.generic_string();
|
|
const auto rel_cfg =
|
|
rs.abs_path.lexically_relative(ninja_graph.configure_dir)
|
|
.generic_string();
|
|
if (!ninja_graph.found_build_ninja ||
|
|
(!ninja_graph.edge_by_output.contains(gen_key) &&
|
|
!ninja_graph.edge_by_output.contains(rel_cfg))) {
|
|
add_unsupported(
|
|
pt.name, "generated_source",
|
|
std::format("target '{}' depends on generated source '{}' "
|
|
"(no build.ninja CUSTOM_COMMAND producer found)",
|
|
pt.name, get_str(*so, "path")));
|
|
} else {
|
|
auto mres = custom_mat.materialize_key(gen_key, pt.name);
|
|
if (!mres) {
|
|
add_unsupported(pt.name, mres.error().construct_kind,
|
|
mres.error().detail);
|
|
} else {
|
|
for (const auto &cn : *mres) {
|
|
if (!std::ranges::contains(pt.prereq_target_names, cn)) {
|
|
pt.prereq_target_names.push_back(cn);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
raw_sources.push_back(std::move(rs));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Audit & extract compileGroups (supporting C, CXX, mixed C/C++, and per-group flags).
|
|
struct GroupSpec {
|
|
std::string lang;
|
|
CStandard c_std{CStandard::Default};
|
|
CxxStandard cxx_std{CxxStandard::Default};
|
|
std::vector<std::string> defines;
|
|
std::vector<std::string> compile_options;
|
|
std::vector<std::filesystem::path> source_paths;
|
|
};
|
|
std::vector<GroupSpec> groups;
|
|
|
|
if (const auto *cgs = find_key(*td, "compileGroups")) {
|
|
if (const auto *cgarr = std::get_if<JsonVal::Array>(&cgs->value)) {
|
|
for (const auto &cgv : *cgarr) {
|
|
const auto *cgo = std::get_if<JsonVal::Object>(&cgv.value);
|
|
if (!cgo) {
|
|
continue;
|
|
}
|
|
GroupSpec gs;
|
|
gs.lang = get_str(*cgo, "language");
|
|
if (gs.lang != "CXX" && gs.lang != "C") {
|
|
add_unsupported(
|
|
pt.name, "unsupported_language",
|
|
std::format("target '{}' compiles language '{}' (bounded subset "
|
|
"supports C and CXX)",
|
|
pt.name, gs.lang));
|
|
}
|
|
if (const auto *pchs = find_key(*cgo, "precompileHeaders")) {
|
|
if (const auto *parr = std::get_if<JsonVal::Array>(&pchs->value);
|
|
parr && !parr->empty()) {
|
|
add_unsupported(
|
|
pt.name, "precompiled_header",
|
|
std::format("target '{}' uses CMake precompileHeaders", pt.name));
|
|
}
|
|
}
|
|
if (const auto *lstd = find_key(*cgo, "languageStandard")) {
|
|
if (const auto *lo = std::get_if<JsonVal::Object>(&lstd->value)) {
|
|
const auto std_str = get_str(*lo, "standard");
|
|
if (gs.lang == "C") {
|
|
if (std_str == "11") {
|
|
gs.c_std = CStandard::C11;
|
|
} else if (std_str == "17" || std_str == "18") {
|
|
gs.c_std = CStandard::C17;
|
|
} else if (std_str == "23") {
|
|
gs.c_std = CStandard::C23;
|
|
}
|
|
} else {
|
|
if (std_str == "17") {
|
|
gs.cxx_std = CxxStandard::Cxx17;
|
|
} else if (std_str == "20") {
|
|
gs.cxx_std = CxxStandard::Cxx20;
|
|
} else if (std_str == "23") {
|
|
gs.cxx_std = CxxStandard::Cxx23;
|
|
} else if (std_str == "26") {
|
|
gs.cxx_std = CxxStandard::Cxx26;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (const auto *incs = find_key(*cgo, "includes")) {
|
|
if (const auto *iarr = std::get_if<JsonVal::Array>(&incs->value)) {
|
|
for (const auto &iv : *iarr) {
|
|
if (const auto *io = std::get_if<JsonVal::Object>(&iv.value)) {
|
|
const std::filesystem::path ip{get_str(*io, "path")};
|
|
const bool sys = get_bool(*io, "isSystem", false);
|
|
if (!std::ranges::contains(pt.includes, std::pair{ip, sys})) {
|
|
pt.includes.emplace_back(ip, sys);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (const auto *defs = find_key(*cgo, "defines")) {
|
|
if (const auto *darr = std::get_if<JsonVal::Array>(&defs->value)) {
|
|
for (const auto &dv : *darr) {
|
|
if (const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value)) {
|
|
const auto d = get_str(*do_obj, "define");
|
|
if (!d.empty() && !std::ranges::contains(gs.defines, d)) {
|
|
gs.defines.push_back(d);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (const auto *frags = find_key(*cgo, "compileCommandFragments")) {
|
|
if (const auto *farr = std::get_if<JsonVal::Array>(&frags->value)) {
|
|
for (const auto &fv : *farr) {
|
|
if (const auto *fo = std::get_if<JsonVal::Object>(&fv.value)) {
|
|
for (const auto &tok :
|
|
split_shell_tokens(get_str(*fo, "fragment"))) {
|
|
if (auto cstd = parse_c_std_flag(tok);
|
|
cstd && gs.lang == "C") {
|
|
if (gs.c_std == CStandard::Default) {
|
|
gs.c_std = *cstd;
|
|
}
|
|
continue;
|
|
}
|
|
if (auto xstd = parse_cxx_std_flag(tok);
|
|
xstd && gs.lang == "CXX") {
|
|
if (gs.cxx_std == CxxStandard::Default) {
|
|
gs.cxx_std = *xstd;
|
|
}
|
|
continue;
|
|
}
|
|
if (tok == "-fPIC" || tok == "-fpic" ||
|
|
tok.starts_with("-std=") || tok == "-fmodules" ||
|
|
tok == "-fmodules-ts" ||
|
|
tok.starts_with("-fmodule-mapper=") ||
|
|
tok.starts_with("-fdeps-")) {
|
|
continue;
|
|
}
|
|
if (!std::ranges::contains(gs.compile_options, tok)) {
|
|
gs.compile_options.push_back(tok);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (const auto *sidxs = find_key(*cgo, "sourceIndexes")) {
|
|
if (const auto *siarr = std::get_if<JsonVal::Array>(&sidxs->value)) {
|
|
for (const auto &iv : *siarr) {
|
|
if (const auto *idx = std::get_if<std::int64_t>(&iv.value)) {
|
|
const auto u = static_cast<std::size_t>(*idx);
|
|
if (u < raw_sources.size()) {
|
|
const SourceKind skind = raw_sources[u].is_module_interface
|
|
? SourceKind::ModuleInterface
|
|
: SourceKind::File;
|
|
pt.sources.push_back(
|
|
SourceRecord{skind, raw_sources[u].abs_path.string()});
|
|
gs.source_paths.push_back(raw_sources[u].abs_path);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
groups.push_back(std::move(gs));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Reconcile language standards and common vs per-file options across compileGroups.
|
|
for (const auto &gs : groups) {
|
|
if (gs.lang == "C" && pt.c_standard == CStandard::Default &&
|
|
gs.c_std != CStandard::Default) {
|
|
pt.c_standard = gs.c_std;
|
|
}
|
|
if (gs.lang == "CXX" && pt.cxx_standard == CxxStandard::Default &&
|
|
gs.cxx_std != CxxStandard::Default) {
|
|
pt.cxx_standard = gs.cxx_std;
|
|
}
|
|
}
|
|
if (groups.size() == 1) {
|
|
pt.defines = std::move(groups.front().defines);
|
|
pt.compile_options = std::move(groups.front().compile_options);
|
|
} else if (groups.size() > 1) {
|
|
for (const auto &d : groups.front().defines) {
|
|
const bool in_all = std::ranges::all_of(groups, [&](const GroupSpec &g) {
|
|
return std::ranges::contains(g.defines, d);
|
|
});
|
|
if (in_all && !std::ranges::contains(pt.defines, d)) {
|
|
pt.defines.push_back(d);
|
|
}
|
|
}
|
|
for (const auto &o : groups.front().compile_options) {
|
|
const bool in_all = std::ranges::all_of(groups, [&](const GroupSpec &g) {
|
|
return std::ranges::contains(g.compile_options, o);
|
|
});
|
|
if (in_all && !std::ranges::contains(pt.compile_options, o)) {
|
|
pt.compile_options.push_back(o);
|
|
}
|
|
}
|
|
for (const auto &gs : groups) {
|
|
for (const auto &sp : gs.source_paths) {
|
|
for (const auto &d : gs.defines) {
|
|
if (!std::ranges::contains(pt.defines, d)) {
|
|
pt.per_file_options.push_back(
|
|
PerFileOption{sp.generic_string(), "-D" + d});
|
|
}
|
|
}
|
|
for (const auto &o : gs.compile_options) {
|
|
if (!std::ranges::contains(pt.compile_options, o)) {
|
|
pt.per_file_options.push_back(PerFileOption{sp.generic_string(), o});
|
|
}
|
|
}
|
|
if (gs.lang == "C" && gs.c_std != CStandard::Default &&
|
|
gs.c_std != pt.c_standard) {
|
|
const char *sf = (gs.c_std == CStandard::C11) ? "-std=c11"
|
|
: (gs.c_std == CStandard::C17) ? "-std=c17"
|
|
: "-std=c23";
|
|
pt.per_file_options.push_back(PerFileOption{sp.generic_string(), sf});
|
|
}
|
|
if (gs.lang == "CXX" && gs.cxx_std != CxxStandard::Default &&
|
|
gs.cxx_std != pt.cxx_standard) {
|
|
const char *sf = (gs.cxx_std == CxxStandard::Cxx17) ? "-std=c++17"
|
|
: (gs.cxx_std == CxxStandard::Cxx20) ? "-std=c++20"
|
|
: (gs.cxx_std == CxxStandard::Cxx23) ? "-std=c++23"
|
|
: "-std=c++26";
|
|
pt.per_file_options.push_back(PerFileOption{sp.generic_string(), sf});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Audit link fragments so external/untracked linker inputs are never silently dropped.
|
|
if (const auto *lnk = find_key(*td, "link")) {
|
|
if (const auto *lobj = std::get_if<JsonVal::Object>(&lnk->value)) {
|
|
if (const auto *frags = find_key(*lobj, "commandFragments")) {
|
|
if (const auto *farr = std::get_if<JsonVal::Array>(&frags->value)) {
|
|
for (const auto &fv : *farr) {
|
|
const auto *fo = std::get_if<JsonVal::Object>(&fv.value);
|
|
if (!fo) {
|
|
continue;
|
|
}
|
|
const auto role = get_str(*fo, "role");
|
|
const auto frag = get_str(*fo, "fragment");
|
|
if (role == "flags") {
|
|
for (const auto &tok : split_shell_tokens(frag)) {
|
|
if (is_safe_system_link_flag(tok) &&
|
|
!std::ranges::contains(pt.link_options, tok)) {
|
|
pt.link_options.push_back(tok);
|
|
}
|
|
}
|
|
} else if (role == "libraries") {
|
|
for (const auto &tok : split_shell_tokens(frag)) {
|
|
if (tok.empty()) {
|
|
continue;
|
|
}
|
|
if (is_safe_system_link_flag(tok)) {
|
|
if (!std::ranges::contains(pt.link_options, tok)) {
|
|
pt.link_options.push_back(tok);
|
|
}
|
|
} else if (known_target_artifacts.contains(tok) ||
|
|
known_target_artifacts.contains(
|
|
std::filesystem::path{tok}
|
|
.filename()
|
|
.string())) {
|
|
// Internal translated target dependency (wired via
|
|
// dep_ids).
|
|
} else if (tok.starts_with("-Wl,-rpath")) {
|
|
// Handled natively by VBS RPATH lowering.
|
|
} else {
|
|
add_unsupported(
|
|
pt.name, "unsupported_link_fragment",
|
|
std::format("target '{}' has untranslated library link "
|
|
"fragment '{}'",
|
|
pt.name, tok));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (const auto *deps = find_key(*td, "dependencies")) {
|
|
if (const auto *darr = std::get_if<JsonVal::Array>(&deps->value)) {
|
|
for (const auto &dv : *darr) {
|
|
if (const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value)) {
|
|
const auto dep_id = get_str(*do_obj, "id");
|
|
if (!dep_id.empty()) {
|
|
pt.dep_ids.push_back(dep_id);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (const auto *arts = find_key(*td, "artifacts")) {
|
|
if (const auto *aarr = std::get_if<JsonVal::Array>(&arts->value)) {
|
|
for (const auto &av : *aarr) {
|
|
if (const auto *ao = std::get_if<JsonVal::Object>(&av.value)) {
|
|
const auto rel = get_str(*ao, "path");
|
|
if (!rel.empty()) {
|
|
pt.artifact_rel_paths.push_back(rel);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
out.audit.supported_targets.push_back(pt.name);
|
|
out.target_order.push_back(pt.id);
|
|
out.targets_by_id[pt.id] = std::move(pt);
|
|
}
|
|
|
|
// Wire UTILITY prerequisite targets and verify every dependency edge resolves cleanly.
|
|
for (const auto &tid : out.target_order) {
|
|
auto &pt = out.targets_by_id.at(tid);
|
|
std::vector<std::string> link_deps;
|
|
for (const auto &dep_id : pt.dep_ids) {
|
|
if (const auto uit = out.utility_target_prereqs.find(dep_id);
|
|
uit != out.utility_target_prereqs.end()) {
|
|
for (const auto &cname : uit->second) {
|
|
if (!std::ranges::contains(pt.prereq_target_names, cname)) {
|
|
pt.prereq_target_names.push_back(cname);
|
|
}
|
|
}
|
|
} else if (out.targets_by_id.contains(dep_id)) {
|
|
link_deps.push_back(dep_id);
|
|
} else if (dep_id.starts_with("@cmake_cxx_std")) {
|
|
// Feature-only INTERFACE_LIBRARY carrier skipped above; the standard is
|
|
// already encoded in the consumer's compile options.
|
|
} else {
|
|
add_unsupported(pt.name, "untranslated_dependency_edge",
|
|
std::format("target '{}' depends on untranslated CMake target '{}'",
|
|
pt.name, dep_id));
|
|
}
|
|
}
|
|
pt.dep_ids = std::move(link_deps);
|
|
}
|
|
out.synthesized_custom_targets = std::move(custom_mat.targets);
|
|
|
|
if (out.audit.is_supported()) {
|
|
out.audit.summary = std::format("all {} CMake target(s) fit the bounded native subset",
|
|
out.audit.supported_targets.size());
|
|
} else {
|
|
out.audit.summary =
|
|
std::format("{} unsupported construct(s) detected across CMake codemodel",
|
|
out.audit.unsupported.size());
|
|
}
|
|
|
|
return out;
|
|
}
|
|
|
|
std::string format_unsupported_diagnostics(const TranslationAuditReport &audit) {
|
|
std::string msg = "CMake native graph translation unsupported (" + audit.summary + "):";
|
|
for (const auto &u : audit.unsupported) {
|
|
msg += std::format("\n - [{}] {}: {}", u.construct_kind, u.target_name, u.detail);
|
|
}
|
|
return msg;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
|
configure_cmake_for_translation(const ProviderRequest &request,
|
|
const std::filesystem::path &configure_dir, std::stop_token stop) {
|
|
auto cmake_bin = Platform::resolve_executable("cmake");
|
|
if (!cmake_bin) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
|
"CMake translation requires 'cmake' in PATH")};
|
|
}
|
|
|
|
std::error_code ec;
|
|
std::filesystem::remove_all(configure_dir, ec);
|
|
std::filesystem::create_directories(configure_dir / ".cmake" / "api" / "v1" / "query", ec);
|
|
if (auto w = Platform::atomic_write_file(
|
|
configure_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false);
|
|
!w) {
|
|
return std::unexpected{w.error()};
|
|
}
|
|
|
|
Void::Log::info("Translate", "Configuring CMake dependency '{}' for native graph audit...",
|
|
request.dependency.name);
|
|
|
|
Platform::ProcessRequest req;
|
|
req.executable = *cmake_bin;
|
|
req.arguments = {"-S", request.source.source_dir.string(), "-B", configure_dir.string()};
|
|
if (Platform::resolve_executable("ninja").has_value()) {
|
|
req.arguments.push_back("-G");
|
|
req.arguments.push_back("Ninja");
|
|
}
|
|
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 btype =
|
|
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
|
|
: "Debug";
|
|
req.arguments.push_back("-DCMAKE_BUILD_TYPE=" + btype);
|
|
for (const auto &[k, v] : request.dependency.options) {
|
|
req.arguments.push_back("-D" + k + "=" + cmake_option_value(v));
|
|
}
|
|
req.timeout = std::chrono::seconds{180};
|
|
auto proc = Platform::run_supervised(req, stop);
|
|
if (!proc || !proc->succeeded()) {
|
|
return std::unexpected{make_error(
|
|
Void::System::SystemErrorCode::io_error,
|
|
std::format("CMake configure failed for '{}':\n{}", request.dependency.name,
|
|
proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))};
|
|
}
|
|
return configure_dir / ".cmake" / "api" / "v1" / "reply";
|
|
}
|
|
|
|
Void::Result::Result<TranslationAuditReport, Void::Result::Error>
|
|
audit_cmake_codemodel(const std::filesystem::path &configure_dir) {
|
|
auto loaded = load_and_audit_codemodel(configure_dir);
|
|
if (!loaded) {
|
|
return std::unexpected{loaded.error()};
|
|
}
|
|
return std::move(loaded->audit);
|
|
}
|
|
|
|
Void::Result::Result<TranslatedCMakeGraph, Void::Result::Error> translate_cmake_to_native_graph(
|
|
const ProviderRequest &request, const std::filesystem::path &configure_dir,
|
|
const std::filesystem::path &native_build_root, const Snapshot::InputSnapshot *snapshot) {
|
|
auto loaded = load_and_audit_codemodel(configure_dir);
|
|
if (!loaded) {
|
|
return std::unexpected{loaded.error()};
|
|
}
|
|
if (!loaded->audit.is_supported()) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported,
|
|
format_unsupported_diagnostics(loaded->audit))};
|
|
}
|
|
|
|
Graph::ProjectDescription desc;
|
|
desc.profile = request.profile;
|
|
// Preserve foreign project's exact configured flags instead of injecting parent profile flags
|
|
// twice; keep profile identity/toolchain/reproducibility epoch intact.
|
|
desc.profile.compile_options.clear();
|
|
desc.profile.defines.clear();
|
|
|
|
for (const auto &ca : loaded->synthesized_custom_targets) {
|
|
desc.targets.push_back(ca);
|
|
}
|
|
|
|
for (const auto &tid : loaded->target_order) {
|
|
const auto &pt = loaded->targets_by_id.at(tid);
|
|
TargetRecord tr;
|
|
tr.name = pt.name;
|
|
if (pt.type == "STATIC_LIBRARY") {
|
|
tr.kind = TargetKind::StaticLibrary;
|
|
} else if (pt.type == "SHARED_LIBRARY") {
|
|
tr.kind = TargetKind::SharedLibrary;
|
|
} else if (pt.type == "OBJECT_LIBRARY") {
|
|
tr.kind = TargetKind::ObjectLibrary;
|
|
} else {
|
|
tr.kind = TargetKind::Executable;
|
|
}
|
|
tr.c_standard = pt.c_standard;
|
|
tr.cxx_standard = pt.cxx_standard;
|
|
tr.sources = pt.sources;
|
|
tr.per_file_options = pt.per_file_options;
|
|
tr.prerequisites = pt.prereq_target_names;
|
|
|
|
for (const auto &[inc, is_sys] : pt.includes) {
|
|
tr.include_directories.push_back(
|
|
IncludeDirectory{inc.string(), Visibility::Public, is_sys});
|
|
}
|
|
for (const auto &def : pt.defines) {
|
|
tr.defines.push_back(ScopedOption{def, Visibility::Public});
|
|
}
|
|
for (const auto &opt : pt.compile_options) {
|
|
tr.compile_options.push_back(opt);
|
|
tr.scoped_compile_options.push_back(ScopedOption{opt, Visibility::Private});
|
|
}
|
|
for (const auto &lo : pt.link_options) {
|
|
tr.link_options.push_back(ScopedOption{lo, Visibility::Public});
|
|
}
|
|
for (const auto &dep_id : pt.dep_ids) {
|
|
const auto &dep_target = loaded->targets_by_id.at(dep_id);
|
|
tr.links.push_back(
|
|
LinkRecord{LinkKind::Local, dep_target.name, {}, Visibility::Public});
|
|
}
|
|
desc.targets.push_back(std::move(tr));
|
|
}
|
|
|
|
const auto src_root =
|
|
loaded->source_root.empty() ? request.source.source_dir : loaded->source_root;
|
|
Graph::GraphLowerOptions gopts{src_root, native_build_root, snapshot, {}, 32768};
|
|
auto graph = Graph::lower_project_graph(desc, request.toolchain, gopts);
|
|
if (!graph) {
|
|
return std::unexpected{graph.error()};
|
|
}
|
|
|
|
// Build exported ImportedTargetInterface entries pointing directly at VBS native outputs!
|
|
TranslatedCMakeGraph result;
|
|
result.audit = std::move(loaded->audit);
|
|
|
|
std::map<std::string, const Graph::ResolvedTargetSummary *, std::less<>> summary_by_name;
|
|
for (const auto &s : graph->targets) {
|
|
summary_by_name[s.name] = &s;
|
|
}
|
|
|
|
for (const auto &tid : loaded->target_order) {
|
|
const auto &pt = loaded->targets_by_id.at(tid);
|
|
const auto sit = summary_by_name.find(pt.name);
|
|
if (sit == summary_by_name.end()) {
|
|
continue;
|
|
}
|
|
Graph::ImportedTargetInterface iface;
|
|
iface.dependency_name = request.dependency.name;
|
|
iface.target_name = pt.name;
|
|
iface.include_dirs = pt.includes;
|
|
iface.defines = pt.defines;
|
|
iface.link_options = pt.link_options;
|
|
iface.module_bmis = sit->second->exported_module_bmis;
|
|
|
|
// Collect primary output + transitive static/shared outputs in dependency order.
|
|
if (!sit->second->primary_outputs.empty()) {
|
|
const auto &primary = sit->second->primary_outputs.front();
|
|
if (pt.type == "STATIC_LIBRARY") {
|
|
iface.static_libraries.push_back(primary);
|
|
} else if (pt.type == "SHARED_LIBRARY") {
|
|
iface.shared_libraries.push_back(primary);
|
|
iface.runtime_files.push_back(primary);
|
|
}
|
|
}
|
|
// Append transitive dependency libraries via DFS post-order reversed.
|
|
std::vector<std::string> post_order;
|
|
std::set<std::string> visited;
|
|
auto dfs = [&](auto &&self, const std::string &cur_id) -> void {
|
|
if (!visited.insert(cur_id).second) {
|
|
return;
|
|
}
|
|
const auto it = loaded->targets_by_id.find(cur_id);
|
|
if (it == loaded->targets_by_id.end()) {
|
|
return;
|
|
}
|
|
for (const auto &sub : it->second.dep_ids) {
|
|
self(self, sub);
|
|
}
|
|
post_order.push_back(cur_id);
|
|
};
|
|
for (const auto &dep_id : pt.dep_ids) {
|
|
dfs(dfs, dep_id);
|
|
}
|
|
std::ranges::reverse(post_order);
|
|
for (const auto &dep_id : post_order) {
|
|
const auto &dep_pt = loaded->targets_by_id.at(dep_id);
|
|
const auto dsit = summary_by_name.find(dep_pt.name);
|
|
if (dsit == summary_by_name.end() || dsit->second->primary_outputs.empty()) {
|
|
continue;
|
|
}
|
|
const auto &dep_out = dsit->second->primary_outputs.front();
|
|
if (dep_pt.type == "STATIC_LIBRARY" &&
|
|
!std::ranges::contains(iface.static_libraries, dep_out)) {
|
|
iface.static_libraries.push_back(dep_out);
|
|
} else if (dep_pt.type == "SHARED_LIBRARY" &&
|
|
!std::ranges::contains(iface.shared_libraries, dep_out)) {
|
|
iface.shared_libraries.push_back(dep_out);
|
|
iface.runtime_files.push_back(dep_out);
|
|
}
|
|
for (const auto &[mname, bmi_p] : dsit->second->exported_module_bmis) {
|
|
iface.module_bmis.try_emplace(mname, bmi_p);
|
|
}
|
|
}
|
|
|
|
result.exported_targets[pt.name] = iface;
|
|
result.exported_targets[request.dependency.name + "::" + pt.name] = std::move(iface);
|
|
}
|
|
|
|
result.graph = std::move(*graph);
|
|
return result;
|
|
}
|
|
|
|
Void::Result::Result<TranslationResolution, Void::Result::Error>
|
|
resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore &state,
|
|
TranslationPolicy policy, std::stop_token stop) {
|
|
if (request.dependency.builder != "cmake") {
|
|
return std::unexpected{make_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
std::format("resolve_cmake_with_translation requires builder='cmake', got '{}'",
|
|
request.dependency.builder))};
|
|
}
|
|
|
|
const auto sw = Void::Time::Stopwatch::started();
|
|
const std::string input_hash = compute_provider_input_hash(request);
|
|
const auto slot_dir = request.provider_build_root /
|
|
("translate_" + request.dependency.name + "_" + input_hash.substr(0, 16));
|
|
const auto cfg_dir = slot_dir / "cmake-configure";
|
|
const auto native_build_root = slot_dir / "native-build";
|
|
|
|
auto reply_dir = configure_cmake_for_translation(request, cfg_dir, stop);
|
|
if (!reply_dir) {
|
|
return std::unexpected{reply_dir.error()};
|
|
}
|
|
|
|
auto audit = audit_cmake_codemodel(cfg_dir);
|
|
if (!audit) {
|
|
return std::unexpected{audit.error()};
|
|
}
|
|
|
|
if (!audit->is_supported()) {
|
|
if (policy == TranslationPolicy::RequireNative) {
|
|
return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported,
|
|
format_unsupported_diagnostics(*audit))};
|
|
}
|
|
Void::Log::warn("Translate",
|
|
"CMake dependency '{}' has unsupported constructs ({}); falling back to "
|
|
"foreign CMake provider",
|
|
request.dependency.name, audit->summary);
|
|
auto fallback = resolve_foreign_provider(request, stop);
|
|
if (!fallback) {
|
|
return std::unexpected{fallback.error()};
|
|
}
|
|
TranslationResolution res;
|
|
res.executed_natively = false;
|
|
res.audit = std::move(*audit);
|
|
res.exported = std::move(*fallback);
|
|
return res;
|
|
}
|
|
|
|
auto translated = translate_cmake_to_native_graph(request, cfg_dir, native_build_root, nullptr);
|
|
if (!translated) {
|
|
return std::unexpected{translated.error()};
|
|
}
|
|
|
|
Void::Log::info("Translate",
|
|
"Executing CMake dependency '{}' natively ({} actions, 0 cmake --build)...",
|
|
request.dependency.name, translated->graph.actions.size());
|
|
|
|
auto exec = Execution::execute_graph(translated->graph, state, {}, stop);
|
|
if (!exec) {
|
|
return std::unexpected{exec.error()};
|
|
}
|
|
if (!exec->succeeded) {
|
|
return std::unexpected{make_error(
|
|
Void::System::SystemErrorCode::io_error,
|
|
std::format("native execution of translated CMake dependency '{}' failed: {}",
|
|
request.dependency.name, exec->diagnostic))};
|
|
}
|
|
|
|
Void::Log::info("Translate",
|
|
"Native CMake translation '{}' finished in {}ms ({} executed, {} cached)",
|
|
request.dependency.name, sw.elapsed_as<std::chrono::milliseconds>().count(),
|
|
exec->executed_count, exec->cached_count);
|
|
|
|
ProviderExport exp;
|
|
exp.dependency_name = request.dependency.name;
|
|
exp.builder = "cmake-native-translated";
|
|
exp.input_identity_hash = input_hash;
|
|
exp.from_cache = (exec->executed_count == 0);
|
|
exp.targets = std::move(translated->exported_targets);
|
|
|
|
TranslationResolution res;
|
|
res.executed_natively = true;
|
|
res.audit = std::move(translated->audit);
|
|
res.exported = std::move(exp);
|
|
res.native_execution = std::move(*exec);
|
|
return res;
|
|
}
|
|
|
|
namespace {
|
|
|
|
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<PerFileOption> per_file_options;
|
|
std::vector<std::string> link_options;
|
|
CStandard c_standard{CStandard::Default};
|
|
CxxStandard cxx_standard{CxxStandard::Default};
|
|
std::vector<std::string> dep_ids;
|
|
std::vector<std::string> prereq_target_names;
|
|
};
|
|
|
|
struct ParsedMesonModel {
|
|
TranslationAuditReport audit;
|
|
std::vector<TargetRecord> synthesized_custom_targets;
|
|
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 std::filesystem::path &source_root = {}) {
|
|
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,
|
|
// and parse build.ninja custom rules for hermetic custom_target / generated_sources
|
|
// translation.
|
|
std::set<std::string> compiled_artifacts;
|
|
for (const auto &tv : *arr) {
|
|
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
|
|
if (!to) {
|
|
continue;
|
|
}
|
|
const auto ttype = get_str(*to, "type");
|
|
if (ttype == "static library" || ttype == "shared library" || ttype == "executable") {
|
|
for (const auto &fn : get_str_array(*to, "filename")) {
|
|
const auto p = std::filesystem::path{fn}.lexically_normal();
|
|
compiled_artifacts.insert(p.string());
|
|
compiled_artifacts.insert(p.filename().string());
|
|
}
|
|
}
|
|
}
|
|
const NinjaCustomGraph ninja_graph = parse_ninja_custom_graph(configure_dir, source_root);
|
|
CustomActionMaterializer custom_mat{ninja_graph, compiled_artifacts};
|
|
std::map<std::filesystem::path, std::string> custom_target_by_output;
|
|
|
|
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 == "run") {
|
|
add_unsupported(
|
|
pt.name, "run_target",
|
|
std::format("Meson target '{}' has type 'run' (non-artifact run targets are "
|
|
"outside bounded native translation)",
|
|
pt.name));
|
|
continue;
|
|
}
|
|
if (pt.type == "custom") {
|
|
const auto fns = get_str_array(*to, "filename");
|
|
if (fns.empty() || !ninja_graph.found_build_ninja) {
|
|
add_unsupported(
|
|
pt.name, "custom_target",
|
|
std::format("Meson custom target '{}' lacks verifiable outputs or build.ninja",
|
|
pt.name));
|
|
continue;
|
|
}
|
|
bool ok = true;
|
|
for (const auto &fn : fns) {
|
|
const auto abs_fn = std::filesystem::path{fn}.lexically_normal();
|
|
const auto mres = custom_mat.materialize_key(abs_fn.generic_string(), pt.name);
|
|
if (!mres || mres->empty()) {
|
|
if (!mres) {
|
|
add_unsupported(pt.name, mres.error().construct_kind, mres.error().detail);
|
|
} else {
|
|
add_unsupported(
|
|
pt.name, "custom_target",
|
|
std::format(
|
|
"Meson custom target '{}' output '{}' has no CUSTOM_COMMAND "
|
|
"producer",
|
|
pt.name, fn));
|
|
}
|
|
ok = false;
|
|
break;
|
|
}
|
|
custom_target_by_output[abs_fn] = mres->front();
|
|
}
|
|
if (ok) {
|
|
out.audit.supported_targets.push_back(pt.name);
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
|
|
struct MesonGroupSpec {
|
|
std::string lang;
|
|
CStandard c_std{CStandard::Default};
|
|
CxxStandard cxx_std{CxxStandard::Default};
|
|
std::vector<std::string> defines;
|
|
std::vector<std::string> compile_options;
|
|
std::vector<std::filesystem::path> source_paths;
|
|
};
|
|
std::vector<MesonGroupSpec> groups;
|
|
|
|
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;
|
|
}
|
|
MesonGroupSpec gs;
|
|
gs.lang = get_str(*tso, "language");
|
|
const auto srcs = get_str_array(*tso, "sources");
|
|
const auto gen_srcs = get_str_array(*tso, "generated_sources");
|
|
if ((!srcs.empty() || !gen_srcs.empty()) &&
|
|
(gs.lang != "cpp" && gs.lang != "c")) {
|
|
add_unsupported(
|
|
pt.name, "unsupported_language",
|
|
std::format("Meson target '{}' compiles language '{}' (bounded subset "
|
|
"supports c and cpp)",
|
|
pt.name, gs.lang));
|
|
}
|
|
for (const auto &g : gen_srcs) {
|
|
const auto gp = std::filesystem::path{g};
|
|
const auto g_abs =
|
|
(gp.is_absolute() ? gp : (configure_dir / gp)).lexically_normal();
|
|
auto mres = custom_mat.materialize_key(g_abs.generic_string(), pt.name);
|
|
if (!mres || mres->empty()) {
|
|
if (!mres) {
|
|
add_unsupported(pt.name, mres.error().construct_kind,
|
|
mres.error().detail);
|
|
} else {
|
|
add_unsupported(
|
|
pt.name, "generated_source",
|
|
std::format("Meson target '{}' generated source '{}' has no "
|
|
"hermetic CUSTOM_COMMAND producer",
|
|
pt.name, g));
|
|
}
|
|
} else {
|
|
for (const auto &cn : *mres) {
|
|
if (!std::ranges::contains(pt.prereq_target_names, cn)) {
|
|
pt.prereq_target_names.push_back(cn);
|
|
}
|
|
}
|
|
custom_target_by_output[g_abs] = mres->front();
|
|
}
|
|
pt.sources.push_back(g_abs);
|
|
gs.source_paths.push_back(g_abs);
|
|
}
|
|
for (const auto &s : srcs) {
|
|
const auto sp = std::filesystem::path{s}.lexically_normal();
|
|
pt.sources.push_back(sp);
|
|
gs.source_paths.push_back(sp);
|
|
}
|
|
|
|
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 (def == "_FILE_OFFSET_BITS=64") {
|
|
continue;
|
|
}
|
|
if (!std::ranges::contains(gs.defines, def)) {
|
|
gs.defines.push_back(def);
|
|
}
|
|
} else if (p == "-D" && i + 1 < params.size()) {
|
|
const std::string def = params[++i];
|
|
if (def != "_FILE_OFFSET_BITS=64" &&
|
|
!std::ranges::contains(gs.defines, def)) {
|
|
gs.defines.push_back(def);
|
|
}
|
|
} else if (auto cstd = parse_c_std_flag(p); cstd && gs.lang == "c") {
|
|
gs.c_std = *cstd;
|
|
} else if (auto xstd = parse_cxx_std_flag(p); xstd && gs.lang == "cpp") {
|
|
gs.cxx_std = *xstd;
|
|
} else if (p == "-fPIC" || p == "-fpic" ||
|
|
p == "-fdiagnostics-color=always" || p == "-pipe" ||
|
|
p.starts_with("-std=")) {
|
|
continue;
|
|
} else if (p == "-pthread") {
|
|
if (!std::ranges::contains(gs.compile_options, p)) {
|
|
gs.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(gs.compile_options, p)) {
|
|
gs.compile_options.push_back(p);
|
|
}
|
|
}
|
|
}
|
|
groups.push_back(std::move(gs));
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const auto &gs : groups) {
|
|
if (gs.lang == "c" && pt.c_standard == CStandard::Default &&
|
|
gs.c_std != CStandard::Default) {
|
|
pt.c_standard = gs.c_std;
|
|
}
|
|
if (gs.lang == "cpp" && pt.cxx_standard == CxxStandard::Default &&
|
|
gs.cxx_std != CxxStandard::Default) {
|
|
pt.cxx_standard = gs.cxx_std;
|
|
}
|
|
}
|
|
if (groups.size() == 1) {
|
|
pt.defines = std::move(groups.front().defines);
|
|
pt.compile_options = std::move(groups.front().compile_options);
|
|
} else if (groups.size() > 1) {
|
|
for (const auto &d : groups.front().defines) {
|
|
if (std::ranges::all_of(groups,
|
|
[&](const MesonGroupSpec &g) {
|
|
return std::ranges::contains(g.defines, d);
|
|
}) &&
|
|
!std::ranges::contains(pt.defines, d)) {
|
|
pt.defines.push_back(d);
|
|
}
|
|
}
|
|
for (const auto &o : groups.front().compile_options) {
|
|
if (std::ranges::all_of(groups,
|
|
[&](const MesonGroupSpec &g) {
|
|
return std::ranges::contains(g.compile_options, o);
|
|
}) &&
|
|
!std::ranges::contains(pt.compile_options, o)) {
|
|
pt.compile_options.push_back(o);
|
|
}
|
|
}
|
|
for (const auto &gs : groups) {
|
|
for (const auto &sp : gs.source_paths) {
|
|
for (const auto &d : gs.defines) {
|
|
if (!std::ranges::contains(pt.defines, d)) {
|
|
pt.per_file_options.push_back(
|
|
PerFileOption{sp.generic_string(), "-D" + d});
|
|
}
|
|
}
|
|
for (const auto &o : gs.compile_options) {
|
|
if (!std::ranges::contains(pt.compile_options, o)) {
|
|
pt.per_file_options.push_back(PerFileOption{sp.generic_string(), o});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Attach any custom-target header/source dependencies referenced by this target's compile
|
|
// edges.
|
|
for (const auto &sp : pt.sources) {
|
|
if (const auto cit = ninja_graph.compiler_extra_deps_by_src.find(sp);
|
|
cit != ninja_graph.compiler_extra_deps_by_src.end()) {
|
|
for (const auto &dep_out : cit->second) {
|
|
if (const auto ctit = custom_target_by_output.find(dep_out);
|
|
ctit != custom_target_by_output.end()) {
|
|
if (!std::ranges::contains(pt.prereq_target_names, ctit->second)) {
|
|
pt.prereq_target_names.push_back(ctit->second);
|
|
}
|
|
} else if (ninja_graph.edge_by_output.contains(dep_out.generic_string())) {
|
|
auto mres = custom_mat.materialize_key(dep_out.generic_string(), pt.name);
|
|
if (!mres) {
|
|
add_unsupported(pt.name, mres.error().construct_kind,
|
|
mres.error().detail);
|
|
} else {
|
|
for (const auto &cn : *mres) {
|
|
if (!std::ranges::contains(pt.prereq_target_names, cn)) {
|
|
pt.prereq_target_names.push_back(cn);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
out.audit.supported_targets.push_back(pt.name);
|
|
out.target_order.push_back(pt.id);
|
|
out.targets_by_id[pt.id] = std::move(pt);
|
|
}
|
|
out.synthesized_custom_targets = std::move(custom_mat.targets);
|
|
|
|
// Recover internal target link edges cleanly from Meson's configured `build.ninja`
|
|
// (`build <target_rel>: {c,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;
|
|
for (const auto &line : split_ninja_logical_lines(*ninja_text)) {
|
|
if (line.starts_with("build ")) {
|
|
cur_target_id.clear();
|
|
const auto colon = find_unescaped_ninja_colon(std::string_view{line}.substr(6));
|
|
if (colon != std::string_view::npos) {
|
|
const auto outs_part = std::string_view{line}.substr(6, colon);
|
|
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 = std::string_view{line}.substr(6 + 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 = std::string_view{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));
|
|
}
|
|
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()))};
|
|
}
|
|
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, request.source.source_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 &ca : loaded->synthesized_custom_targets) {
|
|
desc.targets.push_back(ca);
|
|
}
|
|
|
|
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.c_standard = pt.c_standard;
|
|
tr.cxx_standard = pt.cxx_standard;
|
|
tr.per_file_options = pt.per_file_options;
|
|
tr.prerequisites = pt.prereq_target_names;
|
|
|
|
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;
|
|
iface.module_bmis = sit->second->exported_module_bmis;
|
|
|
|
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
|