Files
Build-System/src/Graph/Graph.cpp
T
2026-11-27 07:50:54 +03:00

2094 lines
104 KiB
C++

#include <Void/Build/Graph/Graph.hpp>
#include <Void/Algorithms/Graph.hpp>
#include <Void/Build/Modules/ModuleScanner.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <format>
#include <queue>
#include <set>
namespace Void::Build::Graph {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(std::string msg) {
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
std::move(msg));
}
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &key) {
const auto it = obj.find(key);
return it == obj.end() ? nullptr : &it->second;
}
std::string get_str(const JsonVal::Object &obj, const std::string &key, std::string fallback = {}) {
const auto *v = find_key(obj, key);
if (!v) {
return fallback;
}
const auto *s = std::get_if<std::string>(&v->value);
return s ? *s : fallback;
}
bool get_bool(const JsonVal::Object &obj, const std::string &key, bool fallback = false) {
const auto *v = find_key(obj, key);
if (!v) {
return fallback;
}
const auto *b = std::get_if<bool>(&v->value);
return b ? *b : fallback;
}
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &key,
std::int64_t fallback = 0) {
const auto *v = find_key(obj, key);
if (!v) {
return fallback;
}
const auto *i = std::get_if<std::int64_t>(&v->value);
return i ? *i : fallback;
}
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &key) {
std::vector<std::string> out;
const auto *v = find_key(obj, key);
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;
}
std::vector<ScopedOption> get_scoped_options(const JsonVal::Object &obj, const std::string &key) {
std::vector<ScopedOption> out;
const auto *v = find_key(obj, key);
if (!v) {
return out;
}
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
for (const auto &item : *arr) {
if (const auto *o = std::get_if<JsonVal::Object>(&item.value)) {
out.push_back(
{get_str(*o, "value"), parse_visibility(get_str(*o, "visibility", "private"))});
}
}
}
return out;
}
bool is_excluded_discovery_path(const std::filesystem::path &rel) {
const std::string gen = rel.lexically_normal().generic_string();
if (gen == "build.cpp" || gen == "build.profiles.cpp") {
return true;
}
for (const auto &part : rel) {
const auto s = part.string();
if (s == ".git" || s == ".vbs" || s == "build" || s == "build-support" || s == ".serena" ||
s == ".cache" || s == "keys" || s == ".env") {
return true;
}
}
return false;
}
bool is_module_source_extension(const std::filesystem::path &p) {
const auto ext = p.extension().string();
return ext == ".cppm" || ext == ".ixx" || ext == ".ccm";
}
bool is_c_source_extension(const std::filesystem::path &p) {
return p.extension().string() == ".c";
}
bool is_cpp_source_extension(const std::filesystem::path &p) {
const auto ext = p.extension().string();
return ext == ".cpp" || ext == ".cc" || ext == ".cxx" || ext == ".c" ||
is_module_source_extension(p);
}
Void::Result::Result<void, Void::Result::Error>
validate_sanitizers(std::string_view target_name, const std::vector<Sanitizer> &sans) {
auto has = [&](Sanitizer s) { return std::ranges::contains(sans, s); };
if (has(Sanitizer::Address) && has(Sanitizer::Thread)) {
return std::unexpected{
make_error(std::format("target '{}': incompatible sanitizers requested (address and "
"thread cannot be combined)",
target_name))};
}
if (has(Sanitizer::Memory) &&
(has(Sanitizer::Address) || has(Sanitizer::Thread) || has(Sanitizer::Leak))) {
return std::unexpected{make_error(std::format(
"target '{}': incompatible sanitizers requested (memory cannot be combined with "
"address, thread, or leak)",
target_name))};
}
if (has(Sanitizer::Thread) && has(Sanitizer::Leak)) {
return std::unexpected{make_error(std::format(
"target '{}': incompatible sanitizers requested (thread and leak cannot be combined)",
target_name))};
}
return {};
}
std::string sanitize_id_component(std::string_view text) {
std::string out;
out.reserve(text.size());
for (const char c : text) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '-' || c == '.') {
out.push_back(c);
} else {
out.push_back('_');
}
}
return out;
}
std::string compute_action_key(const ActionNode &action, const BuildGraph &graph) {
Util::Sha256Hasher hasher;
hasher.update_length_prefixed("vbs-action-v1");
hasher.update_length_prefixed(graph.profile_identity);
hasher.update_length_prefixed(graph.toolchain.identity_hash);
hasher.update_u64(static_cast<std::uint64_t>(action.kind));
hasher.update_length_prefixed(action.target_name);
hasher.update_length_prefixed(action.executable.string());
hasher.update_u64(action.arguments.size());
for (const auto &arg : action.arguments) {
hasher.update_length_prefixed(arg);
}
hasher.update_length_prefixed(action.response_file_content);
hasher.update_u64(action.environment.size());
for (const auto &[k, v] : action.environment) {
hasher.update_length_prefixed(k);
hasher.update_length_prefixed(v);
}
hasher.update_u64(action.declared_inputs.size());
for (const auto &in : action.declared_inputs) {
hasher.update_length_prefixed(in.string());
}
hasher.update_u64(action.declared_outputs.size());
for (const auto &out : action.declared_outputs) {
hasher.update_length_prefixed(out.string());
}
hasher.update_length_prefixed(graph.snapshot_id);
hasher.update_u64(action.nondeterministic ? 1u : 0u);
return hasher.finalize_hex();
}
} // namespace
Void::Result::Result<ProjectDescription, Void::Result::Error>
ProjectDescription::from_json(std::string_view json_text) {
if (!Util::is_valid_utf8(json_text)) {
return std::unexpected{make_error("ProjectDescription JSON contains invalid UTF-8")};
}
auto parsed = Void::Json::Strict::parse(json_text);
if (!parsed) {
return std::unexpected{make_error("failed parsing ProjectDescription JSON")};
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error("ProjectDescription JSON root must be an object")};
}
try {
ProjectDescription desc;
desc.schema_version = static_cast<int>(get_i64(*root, "schema_version", 0));
if (desc.schema_version != Void::Build::schema_version) {
return std::unexpected{make_error(
std::format("unsupported ProjectDescription schema_version {} (expected {})",
desc.schema_version, Void::Build::schema_version))};
}
const auto *prof_v = find_key(*root, "profile");
const auto *prof = prof_v ? std::get_if<JsonVal::Object>(&prof_v->value) : nullptr;
if (!prof) {
return std::unexpected{make_error("ProjectDescription missing profile object")};
}
desc.profile.name = get_str(*prof, "name");
desc.profile.compiler = parse_compiler(get_str(*prof, "compiler", "gcc"));
desc.profile.os = get_str(*prof, "os");
desc.profile.architecture = get_str(*prof, "architecture");
desc.profile.compile_options = get_str_array(*prof, "compile_options");
desc.profile.link_options = get_str_array(*prof, "link_options");
desc.profile.defines = get_str_array(*prof, "defines");
desc.profile.c_standard = parse_c_standard(get_str(*prof, "c_standard", "default"));
desc.profile.cxx_standard = parse_cxx_standard(get_str(*prof, "cxx_standard", "default"));
desc.profile.lto = parse_lto_mode(get_str(*prof, "lto", "none"));
for (const auto &s : get_str_array(*prof, "sanitizers")) {
desc.profile.sanitizers.push_back(parse_sanitizer(s));
}
desc.profile.sysroot = get_str(*prof, "sysroot");
desc.profile.compiler_path = get_str(*prof, "compiler_path");
desc.profile.reproducibility_epoch = get_i64(*prof, "reproducibility_epoch", 0);
desc.profile.nondeterministic = get_bool(*prof, "nondeterministic", false);
if (const auto *targets_v = find_key(*root, "targets")) {
const auto *arr = std::get_if<JsonVal::Array>(&targets_v->value);
if (!arr) {
return std::unexpected{make_error("targets must be an array")};
}
for (const auto &tv : *arr) {
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
if (!to) {
continue;
}
TargetRecord t;
t.name = get_str(*to, "name");
t.kind = parse_target_kind(get_str(*to, "kind"));
if (const auto *sv = find_key(*to, "sources")) {
if (const auto *sarr = std::get_if<JsonVal::Array>(&sv->value)) {
for (const auto &item : *sarr) {
if (const auto *so = std::get_if<JsonVal::Object>(&item.value)) {
t.sources.push_back({parse_source_kind(get_str(*so, "kind")),
get_str(*so, "path")});
}
}
}
}
if (const auto *iv = find_key(*to, "include_directories")) {
if (const auto *iarr = std::get_if<JsonVal::Array>(&iv->value)) {
for (const auto &item : *iarr) {
if (const auto *io = std::get_if<JsonVal::Object>(&item.value)) {
t.include_directories.push_back(
{get_str(*io, "path"),
parse_visibility(get_str(*io, "visibility", "private")),
get_bool(*io, "is_system", false)});
}
}
}
}
t.compile_options = get_str_array(*to, "compile_options");
t.scoped_compile_options = get_scoped_options(*to, "scoped_compile_options");
if (t.scoped_compile_options.empty() && !t.compile_options.empty()) {
for (const auto &opt : t.compile_options) {
t.scoped_compile_options.push_back({opt, Visibility::Private});
}
}
t.defines = get_scoped_options(*to, "defines");
t.link_options = get_scoped_options(*to, "link_options");
if (const auto *lv = find_key(*to, "links")) {
if (const auto *larr = std::get_if<JsonVal::Array>(&lv->value)) {
for (const auto &item : *larr) {
if (const auto *lo = std::get_if<JsonVal::Object>(&item.value)) {
LinkRecord lr;
lr.kind = get_str(*lo, "kind") == "imported" ? LinkKind::Imported
: LinkKind::Local;
lr.target = get_str(*lo, "target");
lr.dependency = get_str(*lo, "dependency");
lr.visibility =
parse_visibility(get_str(*lo, "visibility", "private"));
t.links.push_back(std::move(lr));
}
}
}
}
t.prerequisites = get_str_array(*to, "prerequisites");
t.c_standard = parse_c_standard(get_str(*to, "c_standard", "default"));
t.cxx_standard = parse_cxx_standard(get_str(*to, "cxx_standard", "default"));
t.precompiled_header = get_str(*to, "precompiled_header");
t.unity_enabled = get_bool(*to, "unity_enabled", false);
t.unity_batch_size = static_cast<std::size_t>(get_i64(*to, "unity_batch_size", 8));
t.lto = parse_lto_mode(get_str(*to, "lto", "none"));
for (const auto &s : get_str_array(*to, "sanitizers")) {
t.sanitizers.push_back(parse_sanitizer(s));
}
if (const auto *pfv = find_key(*to, "per_file_options")) {
if (const auto *pfarr = std::get_if<JsonVal::Array>(&pfv->value)) {
for (const auto &item : *pfarr) {
if (const auto *po = std::get_if<JsonVal::Object>(&item.value)) {
t.per_file_options.push_back(
{get_str(*po, "source_path"), get_str(*po, "option")});
}
}
}
}
t.command_argv = get_str_array(*to, "command_argv");
t.action_inputs = get_str_array(*to, "action_inputs");
t.action_outputs = get_str_array(*to, "action_outputs");
t.working_directory = get_str(*to, "working_directory");
if (const auto *ev = find_key(*to, "environment")) {
if (const auto *eo = std::get_if<JsonVal::Object>(&ev->value)) {
for (const auto &[k, val] : *eo) {
if (const auto *vs = std::get_if<std::string>(&val.value)) {
t.environment[k] = *vs;
}
}
}
}
t.nondeterministic = get_bool(*to, "nondeterministic", false);
t.enabled = get_bool(*to, "enabled", true);
t.use_conventional_sources = get_bool(*to, "use_conventional_sources", false);
if (const auto *irv = find_key(*to, "install_rule")) {
if (const auto *iro = std::get_if<JsonVal::Object>(&irv->value)) {
t.install_rule = InstallRule{
get_str(*iro, "target_name"), get_str(*iro, "source_path"),
get_str(*iro, "destination"), get_str(*iro, "component", "default"),
get_bool(*iro, "is_directory", false)};
}
}
desc.targets.push_back(std::move(t));
}
}
if (const auto *deps_v = find_key(*root, "dependencies")) {
if (const auto *darr = std::get_if<JsonVal::Array>(&deps_v->value)) {
for (const auto &dv : *darr) {
const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value);
if (!do_obj) {
continue;
}
DependencyRecord d;
d.name = get_str(*do_obj, "name");
d.builder = get_str(*do_obj, "builder");
d.registry_authority = get_str(*do_obj, "registry_authority");
d.features = get_str_array(*do_obj, "features");
d.build_dependency = get_bool(*do_obj, "build_dependency", false);
if (const auto *src_v = find_key(*do_obj, "source")) {
if (const auto *so = std::get_if<JsonVal::Object>(&src_v->value)) {
const auto kind = get_str(*so, "kind");
if (kind == "git") {
d.source_kind = DependencySourceKind::Git;
d.location = get_str(*so, "location");
d.revision = get_str(*so, "revision");
} else if (kind == "package") {
d.source_kind = DependencySourceKind::Package;
d.package = get_str(*so, "package");
d.version = get_str(*so, "version");
} else if (kind == "path") {
d.source_kind = DependencySourceKind::Path;
d.location = get_str(*so, "location");
} else if (kind == "archive") {
d.source_kind = DependencySourceKind::Archive;
d.location = get_str(*so, "location");
d.sha256 = get_str(*so, "sha256");
} else if (kind == "conan") {
d.source_kind = DependencySourceKind::Conan;
d.package = get_str(*so, "package");
}
}
}
if (const auto *opt_v = find_key(*do_obj, "options")) {
if (const auto *oo = std::get_if<JsonVal::Object>(&opt_v->value)) {
for (const auto &[k, val] : *oo) {
if (const auto *s = std::get_if<std::string>(&val.value)) {
d.options.emplace(k, OptionValue{*s});
} else if (const auto *b = std::get_if<bool>(&val.value)) {
d.options.emplace(k, OptionValue{*b});
} else if (const auto *i = std::get_if<std::int64_t>(&val.value)) {
d.options.emplace(k, OptionValue{*i});
}
}
}
}
desc.dependencies.push_back(std::move(d));
}
}
}
desc.dependency_files = get_str_array(*root, "dependency_files");
if (const auto *rules_v = find_key(*root, "install_rules")) {
if (const auto *rarr = std::get_if<JsonVal::Array>(&rules_v->value)) {
for (const auto &rv : *rarr) {
if (const auto *ro = std::get_if<JsonVal::Object>(&rv.value)) {
desc.install_rules.push_back(InstallRule{
get_str(*ro, "target_name"), get_str(*ro, "source_path"),
get_str(*ro, "destination"), get_str(*ro, "component", "default"),
get_bool(*ro, "is_directory", false)});
}
}
}
}
return desc;
} catch (const std::exception &ex) {
return std::unexpected{make_error(ex.what())};
}
}
bool match_glob(std::string_view pattern, std::string_view path) noexcept {
// Recursive glob supporting '*', '?', and '**' across path separators.
std::size_t pi = 0;
std::size_t si = 0;
while (pi < pattern.size()) {
if (pi + 1 < pattern.size() && pattern[pi] == '*' && pattern[pi + 1] == '*') {
pi += 2;
if (pi < pattern.size() && pattern[pi] == '/') {
++pi;
}
if (pi == pattern.size()) {
return true;
}
for (std::size_t k = si; k <= path.size(); ++k) {
if (k == si || path[k - 1] == '/') {
if (match_glob(pattern.substr(pi), path.substr(k))) {
return true;
}
}
}
return false;
}
if (pattern[pi] == '*') {
++pi;
for (std::size_t k = si; k <= path.size(); ++k) {
if (k > si && path[k - 1] == '/') {
break;
}
if (match_glob(pattern.substr(pi), path.substr(k))) {
return true;
}
}
return false;
}
if (si == path.size()) {
return false;
}
if (pattern[pi] == '?') {
if (path[si] == '/') {
return false;
}
++pi;
++si;
} else if (pattern[pi] == path[si]) {
++pi;
++si;
} else {
return false;
}
}
return si == path.size();
}
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
expand_glob(const std::filesystem::path &project_root, std::string_view pattern) {
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(project_root, ec);
if (ec || !std::filesystem::is_directory(canonical_root)) {
return std::unexpected{make_error(std::format(
"expand_glob: project root '{}' is not a directory", project_root.string()))};
}
std::vector<std::filesystem::path> matches;
std::filesystem::recursive_directory_iterator it{
canonical_root, std::filesystem::directory_options::skip_permission_denied, ec};
for (; !ec && it != std::filesystem::recursive_directory_iterator{}; it.increment(ec)) {
const auto rel = it->path().lexically_relative(canonical_root);
if (is_excluded_discovery_path(rel)) {
if (it->is_directory(ec)) {
it.disable_recursion_pending();
}
continue;
}
if (it->is_regular_file(ec)) {
const std::string gen = rel.lexically_normal().generic_string();
if (match_glob(pattern, gen)) {
matches.push_back(rel.lexically_normal());
}
}
}
std::ranges::sort(matches);
return matches;
}
Void::Result::Result<std::vector<std::size_t>, Void::Result::Error>
BuildGraph::select_action_closure(const std::vector<std::string> &selected_targets) const {
std::set<std::string> wanted_targets;
if (selected_targets.empty()) {
for (const auto &t : targets) {
if (t.enabled) {
wanted_targets.insert(t.name);
}
}
} else {
for (const auto &name : selected_targets) {
const auto found = std::ranges::find(targets, name, &ResolvedTargetSummary::name);
if (found == targets.end()) {
return std::unexpected{
make_error(std::format("unknown requested target '{}'", name))};
}
wanted_targets.insert(name);
}
}
std::set<std::string> needed_ids;
std::queue<std::string> work;
for (const auto &t : targets) {
if (wanted_targets.contains(t.name)) {
for (const auto &aid : t.action_ids) {
if (needed_ids.insert(aid).second) {
work.push(aid);
}
}
}
}
while (!work.empty()) {
const auto id = work.front();
work.pop();
const auto idx_it = action_index_by_id.find(id);
if (idx_it == action_index_by_id.end()) {
continue;
}
for (const auto &dep_id : actions[idx_it->second].dependencies) {
if (needed_ids.insert(dep_id).second) {
work.push(dep_id);
}
}
}
std::vector<std::size_t> ordered;
for (std::size_t i = 0; i < actions.size(); ++i) {
if (needed_ids.contains(actions[i].id)) {
ordered.push_back(i);
}
}
return ordered;
}
Void::Result::Result<BuildGraph, Void::Result::Error>
lower_project_graph(const ProjectDescription &description,
const Toolchain::ToolchainCapabilities &toolchain,
const GraphLowerOptions &options) {
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec);
if (ec) {
return std::unexpected{make_error("cannot canonicalize project root")};
}
BuildGraph graph;
graph.profile = description.profile;
graph.toolchain = toolchain;
graph.profile_identity = Toolchain::compute_profile_identity(description.profile, toolchain);
graph.project_root = canonical_root;
const auto canonical_build_root = std::filesystem::weakly_canonical(options.build_root, ec);
graph.profile_build_dir =
canonical_build_root / "profiles" / sanitize_id_component(description.profile.name);
if (options.snapshot) {
graph.snapshot_id = options.snapshot->snapshot_id;
graph.snapshot_materialized_root = options.snapshot->materialized_root;
}
// Index targets by name and detect target-level cycles upfront via Void::Algorithms.
std::map<std::string, const TargetRecord *, std::less<>> target_by_name;
std::map<std::string, std::size_t, std::less<>> target_index_by_name;
for (std::size_t i = 0; i < description.targets.size(); ++i) {
const auto &t = description.targets[i];
if (!target_by_name.emplace(t.name, &t).second) {
return std::unexpected{make_error(std::format("duplicate target '{}'", t.name))};
}
target_index_by_name.emplace(t.name, i);
}
// Validate references and build directed graph (edge dep -> dependent).
std::vector<std::vector<std::size_t>> target_adj(description.targets.size());
for (std::size_t i = 0; i < description.targets.size(); ++i) {
const auto &t = description.targets[i];
auto add_edge =
[&](const std::string &dep_name,
std::string_view kind_label) -> Void::Result::Result<void, Void::Result::Error> {
const auto it = target_index_by_name.find(dep_name);
if (it == target_index_by_name.end()) {
return std::unexpected{
make_error(std::format("target '{}' references unknown {} target '{}'", t.name,
kind_label, dep_name))};
}
const std::size_t dep_idx = it->second;
if (dep_idx == i) {
return std::unexpected{
make_error(std::format("dependency cycle detected: {} -> {}", t.name, t.name))};
}
if (!std::ranges::contains(target_adj[dep_idx], i)) {
target_adj[dep_idx].push_back(i);
}
return {};
};
for (const auto &pre : t.prerequisites) {
if (auto r = add_edge(pre, "prerequisite"); !r) {
return std::unexpected{r.error()};
}
}
for (const auto &link : t.links) {
if (link.kind == LinkKind::Local) {
if (auto r = add_edge(link.target, "linked"); !r) {
return std::unexpected{r.error()};
}
}
}
}
const Void::Algorithms::AdjacencyView target_view{target_adj};
auto topo = Void::Algorithms::topological_order(target_view);
if (!topo) {
std::string chain;
const auto &cycle = topo.error().cycle;
for (auto it = cycle.rbegin(); it != cycle.rend(); ++it) {
if (!chain.empty()) {
chain += " -> ";
}
chain += description.targets[*it].name;
}
return std::unexpected{make_error(
chain.empty() ? std::format("dependency cycle detected: {}", topo.error().message)
: std::format("dependency cycle detected: {}", chain))};
}
std::vector<std::string> topo_targets;
topo_targets.reserve(topo->order.size());
for (const std::size_t idx : topo->order) {
topo_targets.push_back(description.targets[idx].name);
}
// Track per-target primary outputs, exported compile requirements, and ordered link closures.
struct TargetComputed {
std::vector<std::filesystem::path> object_files;
std::optional<std::filesystem::path> primary_artifact;
std::vector<std::string> producer_action_ids;
// Public/Interface compile usage exposed to consumers.
std::vector<std::pair<std::filesystem::path, bool>> exported_includes;
std::vector<std::string> exported_defines;
std::vector<std::string> exported_compile_options;
// Transitive ordered link libraries and options exposed to final linkers.
std::vector<std::filesystem::path> exported_static_libs;
std::vector<std::filesystem::path> exported_shared_libs;
std::vector<std::filesystem::path> exported_objects;
std::vector<std::string> exported_link_options;
std::vector<std::string> exported_prerequisite_actions;
std::map<std::string, std::filesystem::path, std::less<>> exported_module_bmis;
std::map<std::string, std::string, std::less<>> exported_module_action_ids;
};
std::map<std::string, TargetComputed, std::less<>> computed;
// Track output producers to reject collisions and source/output overlap.
std::map<std::filesystem::path, std::string> output_owner;
auto register_output =
[&](const std::filesystem::path &out_path,
const std::string &action_id) -> Void::Result::Result<void, Void::Result::Error> {
const auto norm = out_path.lexically_normal();
// Reject writing generated outputs directly onto editable source root paths outside build
// dir.
if (Platform::path_is_within(canonical_root, norm) &&
!Platform::path_is_within(graph.profile_build_dir, norm)) {
return std::unexpected{make_error(std::format(
"action '{}' output '{}' overlaps project source tree outside build dir", action_id,
norm.string()))};
}
const auto [it, inserted] = output_owner.emplace(norm, action_id);
if (!inserted) {
return std::unexpected{make_error(
std::format("output path collision on '{}': produced by both '{}' and '{}'",
norm.string(), it->second, action_id))};
}
return {};
};
auto map_logical_to_physical = [&](const std::filesystem::path &logical_abs) {
if (graph.snapshot_materialized_root.empty()) {
return logical_abs;
}
if (Platform::path_is_within(canonical_root, logical_abs) &&
!Platform::path_is_within(canonical_build_root, logical_abs) &&
!Platform::path_is_within(graph.profile_build_dir, logical_abs)) {
const auto rel = logical_abs.lexically_relative(canonical_root);
const auto candidate = graph.snapshot_materialized_root / rel;
std::error_code mec;
if (std::filesystem::exists(candidate, mec)) {
return candidate;
}
}
return logical_abs;
};
const auto generated_root = graph.profile_build_dir / "gen";
const auto objects_root = graph.profile_build_dir / "obj";
const auto artifacts_root = graph.profile_build_dir / "out";
const auto rsp_root = graph.profile_build_dir / "rsp";
for (const auto &target_name : topo_targets) {
const TargetRecord &t = *target_by_name.at(target_name);
TargetComputed tc;
ResolvedTargetSummary summary;
summary.name = t.name;
summary.kind = t.kind;
summary.enabled = t.enabled;
// 1. Collect prerequisite action IDs (explicit depends_on + linked target producers).
std::vector<std::string> target_prereq_actions;
auto add_unique_str = [](std::vector<std::string> &vec, const std::string &val) {
if (!std::ranges::contains(vec, val)) {
vec.push_back(val);
}
};
for (const auto &pre_name : t.prerequisites) {
for (const auto &aid : computed.at(pre_name).producer_action_ids) {
add_unique_str(target_prereq_actions, aid);
}
for (const auto &aid : computed.at(pre_name).exported_prerequisite_actions) {
add_unique_str(target_prereq_actions, aid);
add_unique_str(tc.exported_prerequisite_actions, aid);
}
}
// 2. CustomAction lowering.
if (t.kind == TargetKind::CustomAction) {
if (t.command_argv.empty()) {
return std::unexpected{
make_error(std::format("custom_action '{}' must declare command()", t.name))};
}
if (t.action_outputs.empty()) {
return std::unexpected{make_error(
std::format("custom_action '{}' must declare at least one output", t.name))};
}
ActionNode act;
act.id = "custom:" + sanitize_id_component(t.name);
act.kind = ActionKind::Custom;
act.target_name = t.name;
auto expand_vars = [&](std::string text) {
auto replace_all = [&](std::string_view token, const std::string &val) {
std::size_t pos = 0;
while ((pos = text.find(token, pos)) != std::string::npos) {
text.replace(pos, token.size(), val);
pos += val.size();
}
};
replace_all("$GEN", generated_root.string());
replace_all("$PROJECT_ROOT", canonical_root.string());
replace_all("$BUILD_DIR", graph.profile_build_dir.string());
return text;
};
act.executable = expand_vars(t.command_argv.front());
for (std::size_t i = 1; i < t.command_argv.size(); ++i) {
act.arguments.push_back(expand_vars(t.command_argv[i]));
}
act.environment = t.environment;
if (!t.nondeterministic && !description.profile.nondeterministic) {
act.environment.emplace("SOURCE_DATE_EPOCH",
std::to_string(description.profile.reproducibility_epoch));
act.environment.emplace("TZ", "UTC");
act.environment.emplace("LC_ALL", "C");
}
act.working_directory = t.working_directory.empty()
? canonical_root
: (std::filesystem::path{t.working_directory}.is_absolute()
? std::filesystem::path{t.working_directory}
: (canonical_root / t.working_directory));
act.dependencies = target_prereq_actions;
act.nondeterministic = t.nondeterministic || description.profile.nondeterministic;
act.cacheable = !act.nondeterministic;
for (const auto &in : t.action_inputs) {
const auto p = std::filesystem::path{in};
const auto resolved_in =
(p.is_absolute() ? p : (canonical_root / p)).lexically_normal();
if (const auto prod_it = output_owner.find(resolved_in);
prod_it != output_owner.end()) {
add_unique_str(act.dependencies, prod_it->second);
}
act.declared_inputs.push_back(resolved_in);
}
for (const auto &out : t.action_outputs) {
const auto p = std::filesystem::path{out};
const auto resolved_out = p.is_absolute() ? p : (generated_root / p);
if (auto reg = register_output(resolved_out, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.declared_outputs.push_back(resolved_out);
summary.primary_outputs.push_back(resolved_out);
}
act.action_key = compute_action_key(act, graph);
tc.producer_action_ids.push_back(act.id);
tc.exported_prerequisite_actions.push_back(act.id);
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
computed[t.name] = std::move(tc);
graph.targets.push_back(std::move(summary));
continue;
}
// 3. Gather effective compile & link requirements from own declarations and linked deps.
std::vector<std::pair<std::filesystem::path, bool>> effective_includes;
std::vector<std::string> effective_defines = description.profile.defines;
std::vector<std::string> effective_compile_opts = description.profile.compile_options;
std::vector<std::string> effective_link_opts = description.profile.link_options;
// Ordered transitive link inputs (preserve exact order; never sort!).
std::map<std::string, std::filesystem::path, std::less<>> external_module_bmis;
std::map<std::string, std::string, std::less<>> external_module_action_ids;
std::vector<std::filesystem::path> link_objects;
std::vector<std::filesystem::path> link_static_libs;
std::vector<std::filesystem::path> link_shared_libs;
auto resolve_include = [&](const std::string &raw) -> std::filesystem::path {
const std::filesystem::path p{raw};
if (p.is_absolute()) {
return p.lexically_normal();
}
if (raw.starts_with("$GEN/") || raw.starts_with("gen/")) {
const auto suffix = raw.starts_with("$GEN/") ? raw.substr(5) : raw.substr(4);
return (generated_root / suffix).lexically_normal();
}
return (canonical_root / p).lexically_normal();
};
// Own include directories, defines, compile options, link options.
if (t.use_conventional_sources &&
std::filesystem::is_directory(canonical_root / "include")) {
const auto inc = (canonical_root / "include").lexically_normal();
effective_includes.emplace_back(inc, false);
tc.exported_includes.emplace_back(inc, false);
}
for (const auto &inc : t.include_directories) {
const auto abs = resolve_include(inc.path);
if (inc.visibility != Visibility::Interface) {
effective_includes.emplace_back(abs, inc.is_system);
}
if (inc.visibility != Visibility::Private) {
tc.exported_includes.emplace_back(abs, inc.is_system);
}
}
for (const auto &def : t.defines) {
if (def.visibility != Visibility::Interface) {
effective_defines.push_back(def.value);
}
if (def.visibility != Visibility::Private) {
tc.exported_defines.push_back(def.value);
}
}
for (const auto &opt : t.scoped_compile_options) {
if (opt.visibility != Visibility::Interface) {
effective_compile_opts.push_back(opt.value);
}
if (opt.visibility != Visibility::Private) {
tc.exported_compile_options.push_back(opt.value);
}
}
for (const auto &opt : t.link_options) {
if (opt.visibility != Visibility::Interface) {
effective_link_opts.push_back(opt.value);
}
if (opt.visibility != Visibility::Private) {
tc.exported_link_options.push_back(opt.value);
}
}
// Propagate from linked targets (local and imported).
for (const auto &link : t.links) {
if (link.kind == LinkKind::Local) {
const auto &dep_rec = *target_by_name.at(link.target);
const auto &dep = computed.at(link.target);
// Generated prerequisites from dependencies must precede our compilation.
for (const auto &aid : dep.exported_prerequisite_actions) {
add_unique_str(target_prereq_actions, aid);
if (link.visibility != Visibility::Private) {
add_unique_str(tc.exported_prerequisite_actions, aid);
}
}
// Compile usage (Public & Interface propagate to consumers).
if (link.visibility != Visibility::Interface) {
effective_includes.insert(effective_includes.end(),
dep.exported_includes.begin(),
dep.exported_includes.end());
effective_defines.insert(effective_defines.end(), dep.exported_defines.begin(),
dep.exported_defines.end());
effective_compile_opts.insert(effective_compile_opts.end(),
dep.exported_compile_options.begin(),
dep.exported_compile_options.end());
for (const auto &[mname, bmi_p] : dep.exported_module_bmis) {
external_module_bmis.try_emplace(mname, bmi_p);
}
for (const auto &[mname, aid] : dep.exported_module_action_ids) {
external_module_action_ids.try_emplace(mname, aid);
}
}
if (link.visibility != Visibility::Private) {
tc.exported_includes.insert(tc.exported_includes.end(),
dep.exported_includes.begin(),
dep.exported_includes.end());
tc.exported_defines.insert(tc.exported_defines.end(),
dep.exported_defines.begin(),
dep.exported_defines.end());
tc.exported_compile_options.insert(tc.exported_compile_options.end(),
dep.exported_compile_options.begin(),
dep.exported_compile_options.end());
for (const auto &[mname, bmi_p] : dep.exported_module_bmis) {
tc.exported_module_bmis.try_emplace(mname, bmi_p);
}
for (const auto &[mname, aid] : dep.exported_module_action_ids) {
tc.exported_module_action_ids.try_emplace(mname, aid);
}
}
// Link usage: static private dependencies STILL propagate to final linkers!
const bool propagate_to_consumers = (link.visibility != Visibility::Private) ||
(t.kind == TargetKind::StaticLibrary) ||
(t.kind == TargetKind::HeaderOnly) ||
(t.kind == TargetKind::ObjectLibrary);
if (dep_rec.kind == TargetKind::ObjectLibrary) {
link_objects.insert(link_objects.end(), dep.object_files.begin(),
dep.object_files.end());
if (propagate_to_consumers) {
tc.exported_objects.insert(tc.exported_objects.end(),
dep.object_files.begin(),
dep.object_files.end());
}
} else if (dep_rec.kind == TargetKind::StaticLibrary && dep.primary_artifact) {
link_static_libs.push_back(*dep.primary_artifact);
if (propagate_to_consumers) {
tc.exported_static_libs.push_back(*dep.primary_artifact);
}
} else if (dep_rec.kind == TargetKind::SharedLibrary && dep.primary_artifact) {
link_shared_libs.push_back(*dep.primary_artifact);
summary.runtime_shared_libraries.push_back(*dep.primary_artifact);
if (propagate_to_consumers) {
tc.exported_shared_libs.push_back(*dep.primary_artifact);
}
}
// Preserve exact order: dependency's transitive libs come AFTER dependency itself.
link_objects.insert(link_objects.end(), dep.exported_objects.begin(),
dep.exported_objects.end());
link_static_libs.insert(link_static_libs.end(), dep.exported_static_libs.begin(),
dep.exported_static_libs.end());
link_shared_libs.insert(link_shared_libs.end(), dep.exported_shared_libs.begin(),
dep.exported_shared_libs.end());
effective_link_opts.insert(effective_link_opts.end(),
dep.exported_link_options.begin(),
dep.exported_link_options.end());
if (propagate_to_consumers) {
tc.exported_objects.insert(tc.exported_objects.end(),
dep.exported_objects.begin(),
dep.exported_objects.end());
tc.exported_static_libs.insert(tc.exported_static_libs.end(),
dep.exported_static_libs.begin(),
dep.exported_static_libs.end());
tc.exported_shared_libs.insert(tc.exported_shared_libs.end(),
dep.exported_shared_libs.begin(),
dep.exported_shared_libs.end());
tc.exported_link_options.insert(tc.exported_link_options.end(),
dep.exported_link_options.begin(),
dep.exported_link_options.end());
}
} else {
// Imported target from foreign/native package provider.
const std::string key = link.dependency + "::" + link.target;
auto it = options.imported_targets.find(key);
if (it == options.imported_targets.end()) {
it = options.imported_targets.find(link.target);
}
if (it == options.imported_targets.end()) {
return std::unexpected{make_error(std::format(
"target '{}' links unresolved imported target '{}' from dependency '{}'",
t.name, link.target, link.dependency))};
}
const auto &imp = it->second;
if (link.visibility != Visibility::Interface) {
effective_includes.insert(effective_includes.end(), imp.include_dirs.begin(),
imp.include_dirs.end());
effective_defines.insert(effective_defines.end(), imp.defines.begin(),
imp.defines.end());
effective_compile_opts.insert(effective_compile_opts.end(),
imp.compile_options.begin(),
imp.compile_options.end());
for (const auto &[mname, bmi_p] : imp.module_bmis) {
external_module_bmis.try_emplace(mname, bmi_p);
}
}
if (link.visibility != Visibility::Private) {
tc.exported_includes.insert(tc.exported_includes.end(),
imp.include_dirs.begin(), imp.include_dirs.end());
tc.exported_defines.insert(tc.exported_defines.end(), imp.defines.begin(),
imp.defines.end());
tc.exported_compile_options.insert(tc.exported_compile_options.end(),
imp.compile_options.begin(),
imp.compile_options.end());
for (const auto &[mname, bmi_p] : imp.module_bmis) {
tc.exported_module_bmis.try_emplace(mname, bmi_p);
}
}
const bool propagate_to_consumers = (link.visibility != Visibility::Private) ||
(t.kind == TargetKind::StaticLibrary) ||
(t.kind == TargetKind::HeaderOnly);
link_static_libs.insert(link_static_libs.end(), imp.static_libraries.begin(),
imp.static_libraries.end());
link_shared_libs.insert(link_shared_libs.end(), imp.shared_libraries.begin(),
imp.shared_libraries.end());
effective_link_opts.insert(effective_link_opts.end(), imp.link_options.begin(),
imp.link_options.end());
if (propagate_to_consumers) {
tc.exported_static_libs.insert(tc.exported_static_libs.end(),
imp.static_libraries.begin(),
imp.static_libraries.end());
tc.exported_shared_libs.insert(tc.exported_shared_libs.end(),
imp.shared_libraries.begin(),
imp.shared_libraries.end());
tc.exported_link_options.insert(tc.exported_link_options.end(),
imp.link_options.begin(),
imp.link_options.end());
}
}
}
// 4. Expand sources (explicit files, globs, conventional src/source, modules, header
// units).
std::vector<std::filesystem::path> expanded_sources;
std::vector<std::filesystem::path> header_unit_sources;
std::set<std::filesystem::path> explicit_module_sources;
std::set<std::filesystem::path> seen_sources;
auto add_source = [&](const std::filesystem::path &rel_or_abs, bool is_mod = false) {
const auto norm = rel_or_abs.lexically_normal();
if (seen_sources.insert(norm).second) {
expanded_sources.push_back(norm);
}
if (is_mod || is_module_source_extension(norm)) {
explicit_module_sources.insert(norm);
}
};
if (t.use_conventional_sources) {
for (const char *dir : {"src", "source"}) {
if (std::filesystem::is_directory(canonical_root / dir)) {
auto found = expand_glob(canonical_root, std::string{dir} + "/**/*");
if (!found) {
return std::unexpected{found.error()};
}
for (const auto &f : *found) {
if (is_cpp_source_extension(f)) {
add_source(f);
}
}
}
}
}
for (const auto &src : t.sources) {
if (src.kind == SourceKind::Glob) {
auto found = expand_glob(canonical_root, src.path);
if (!found) {
return std::unexpected{found.error()};
}
for (const auto &f : *found) {
add_source(f);
}
} else if (src.kind == SourceKind::HeaderUnit) {
const std::filesystem::path p{src.path};
const auto abs = p.is_absolute() ? p : (canonical_root / p);
if (!std::filesystem::exists(abs)) {
return std::unexpected{make_error(std::format(
"target '{}' explicit header unit '{}' does not exist", t.name, src.path))};
}
header_unit_sources.push_back(p.lexically_normal());
} else if (src.kind == SourceKind::File || src.kind == SourceKind::ModuleInterface ||
src.kind == SourceKind::ModulePartition) {
const std::filesystem::path p{src.path};
const auto abs = p.is_absolute() ? p : (canonical_root / p);
const auto gen_candidate =
src.path.starts_with("$GEN/") ? (generated_root / src.path.substr(5)) : abs;
const bool produced_by_action =
output_owner.contains(gen_candidate.lexically_normal());
if (!produced_by_action && !std::filesystem::exists(abs)) {
return std::unexpected{make_error(std::format(
"target '{}' explicit source '{}' does not exist", t.name, src.path))};
}
const bool is_mod = (src.kind == SourceKind::ModuleInterface ||
src.kind == SourceKind::ModulePartition);
add_source(produced_by_action ? gen_candidate : p, is_mod);
}
}
summary.expanded_sources = expanded_sources;
if (t.kind == TargetKind::HeaderOnly) {
summary.exported_module_bmis = tc.exported_module_bmis;
computed[t.name] = std::move(tc);
graph.targets.push_back(std::move(summary));
continue;
}
// Effective C & C++ standards, LTO, sanitizers (target overrides/extends profile).
const CStandard eff_c_std =
t.c_standard != CStandard::Default ? t.c_standard : description.profile.c_standard;
const CxxStandard eff_std = t.cxx_standard != CxxStandard::Default
? t.cxx_standard
: description.profile.cxx_standard;
const LtoMode eff_lto = t.lto != LtoMode::None ? t.lto : description.profile.lto;
std::vector<Sanitizer> eff_sans = description.profile.sanitizers;
for (const auto s : t.sanitizers) {
if (!std::ranges::contains(eff_sans, s)) {
eff_sans.push_back(s);
}
}
if (auto sv = validate_sanitizers(t.name, eff_sans); !sv) {
return std::unexpected{sv.error()};
}
const bool pic = (t.kind == TargetKind::SharedLibrary);
// Map include dirs to physical snapshot paths when snapshot is active.
std::vector<std::pair<std::filesystem::path, bool>> physical_includes;
physical_includes.reserve(effective_includes.size());
for (const auto &[inc_path, is_sys] : effective_includes) {
physical_includes.emplace_back(map_logical_to_physical(inc_path), is_sys);
}
// Path prefix maps remap physical snapshot and build roots to canonical logical paths
// so __FILE__, __BASE_FILE__, std::source_location, and debug paths remain deterministic
// across isolated snapshots and build directories!
std::vector<Toolchain::PathPrefixMap> prefix_maps;
if (!graph.snapshot_materialized_root.empty()) {
prefix_maps.push_back({graph.snapshot_materialized_root, canonical_root});
}
if (!t.nondeterministic && !description.profile.nondeterministic &&
!graph.profile_build_dir.empty()) {
prefix_maps.push_back({graph.profile_build_dir, "/vbs-build"});
}
// 5. Optional PCH compilation action (Plan 08 foundation).
std::optional<std::filesystem::path> pch_include_prefix;
std::optional<std::string> pch_action_id;
if (!t.precompiled_header.empty()) {
const std::filesystem::path pch_rel{t.precompiled_header};
const auto pch_logical =
pch_rel.is_absolute() ? pch_rel : (canonical_root / pch_rel).lexically_normal();
const auto pch_physical = map_logical_to_physical(pch_logical);
const auto pch_out_base =
objects_root / sanitize_id_component(t.name) / "pch" / pch_logical.filename();
const auto pch_gch = std::filesystem::path{pch_out_base.string() + ".gch"};
Toolchain::CompileRequest req;
req.source_file = pch_physical;
req.output_object = pch_gch;
req.depfile = std::filesystem::path{pch_gch.string() + ".d"};
req.response_file_dir = rsp_root;
req.include_dirs = physical_includes;
req.defines = effective_defines;
req.compile_options = effective_compile_opts;
req.compile_options.push_back("-x");
req.compile_options.push_back("c++-header");
req.cxx_standard = eff_std;
req.lto = eff_lto;
req.sanitizers = eff_sans;
req.position_independent = pic;
req.prefix_maps = prefix_maps;
req.reproducibility_epoch = description.profile.reproducibility_epoch;
req.nondeterministic = t.nondeterministic || description.profile.nondeterministic;
req.response_file_threshold = options.response_file_threshold;
auto lowered = Toolchain::lower_compile_command(toolchain, req);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "pch:" + sanitize_id_component(t.name);
act.kind = ActionKind::PrecompiledHeader;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.response_file = lowered->response_file;
act.response_file_content = std::move(lowered->response_file_content);
act.declared_inputs = {pch_physical};
act.declared_outputs = {pch_gch};
act.depfile = req.depfile;
act.logical_source_file = pch_logical;
act.physical_source_file = pch_physical;
act.logical_output_file = pch_gch;
act.physical_output_file = pch_gch;
act.dependencies = target_prereq_actions;
act.nondeterministic = req.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(pch_gch, act.id); !reg) {
return std::unexpected{reg.error()};
}
// Include physical path & toolchain identity in PCH action key (Plan 07/08).
act.action_key = compute_action_key(act, graph);
pch_action_id = act.id;
pch_include_prefix = pch_out_base;
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
}
// 5b. Explicit Header Units lowering (Plan 08).
const std::string_view bmi_ext =
(toolchain.family == CompilerFamily::Clang) ? ".pcm" : ".gcm";
const auto target_bmi_root =
graph.profile_build_dir / "bmi" / sanitize_id_component(t.name);
std::vector<std::string> header_unit_action_ids;
std::vector<std::filesystem::path> header_unit_bmi_paths;
std::string gcc_header_unit_mapper_lines;
for (const auto &hu_path : header_unit_sources) {
const auto logical_hu =
hu_path.is_absolute() ? hu_path : (canonical_root / hu_path).lexically_normal();
const auto physical_hu = map_logical_to_physical(logical_hu);
const std::string hu_hash = Util::sha256_hex(logical_hu.string()).substr(0, 12);
const auto hu_bmi =
target_bmi_root / ("hu_" + sanitize_id_component(logical_hu.filename().string()) +
"_" + hu_hash + std::string{bmi_ext});
const CxxStandard hu_std =
(eff_std == CxxStandard::Default) ? CxxStandard::Cxx20 : eff_std;
auto lowered = Modules::lower_header_unit_command(toolchain, physical_hu, hu_bmi,
physical_includes, effective_defines,
effective_compile_opts, hu_std);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "headerunit:" + sanitize_id_component(t.name) + ":" + hu_hash;
act.kind = ActionKind::HeaderUnit;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.declared_inputs = {physical_hu};
act.declared_outputs = {hu_bmi};
act.logical_source_file = logical_hu;
act.physical_source_file = physical_hu;
act.logical_output_file = hu_bmi;
act.physical_output_file = hu_bmi;
act.dependencies = target_prereq_actions;
act.nondeterministic = t.nondeterministic || description.profile.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(hu_bmi, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.action_key = compute_action_key(act, graph);
header_unit_action_ids.push_back(act.id);
header_unit_bmi_paths.push_back(hu_bmi);
gcc_header_unit_mapper_lines += physical_hu.string() + " " + hu_bmi.string() + "\n";
if (logical_hu != physical_hu) {
gcc_header_unit_mapper_lines += logical_hu.string() + " " + hu_bmi.string() + "\n";
}
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
}
// 5c. Build effective compile unit list (with optional deterministic unity batching
// excluding module sources and per-file-option sources — Plan 08).
struct CompileUnitSpec {
std::filesystem::path logical_src;
std::filesystem::path physical_src;
std::vector<std::string> tu_opts;
bool is_c{false};
bool is_explicit_module{false};
bool has_per_file_override{false};
};
std::vector<CompileUnitSpec> raw_units;
raw_units.reserve(expanded_sources.size());
for (const auto &src_path : expanded_sources) {
CompileUnitSpec cu;
cu.logical_src =
src_path.is_absolute() ? src_path : (canonical_root / src_path).lexically_normal();
cu.physical_src = map_logical_to_physical(cu.logical_src);
cu.tu_opts = effective_compile_opts;
cu.is_explicit_module =
explicit_module_sources.contains(src_path) || is_module_source_extension(src_path);
cu.is_c = !cu.is_explicit_module && is_c_source_extension(src_path);
for (const auto &pfo : t.per_file_options) {
if (pfo.source_path == src_path.generic_string() ||
pfo.source_path == cu.logical_src.generic_string()) {
cu.tu_opts.push_back(pfo.option);
cu.has_per_file_override = true;
}
}
raw_units.push_back(std::move(cu));
}
std::vector<CompileUnitSpec> compile_units;
if (t.unity_enabled && !raw_units.empty()) {
std::vector<std::filesystem::path> all_phys;
std::vector<std::filesystem::path> excluded_phys;
std::map<std::filesystem::path, const CompileUnitSpec *> raw_by_phys;
for (const auto &cu : raw_units) {
const auto norm_phys = cu.physical_src.lexically_normal();
all_phys.push_back(norm_phys);
raw_by_phys[norm_phys] = &cu;
if (cu.is_c || cu.is_explicit_module || cu.has_per_file_override) {
excluded_phys.push_back(norm_phys);
}
}
const auto unity_dir =
graph.profile_build_dir / "unity" / sanitize_id_component(t.name);
auto unity =
Modules::generate_unity_batches(sanitize_id_component(t.name), all_phys,
excluded_phys, t.unity_batch_size, unity_dir);
if (!unity) {
return std::unexpected{unity.error()};
}
for (const auto &uf : unity->generated_unity_files) {
CompileUnitSpec cu;
cu.logical_src = uf;
cu.physical_src = uf;
cu.tu_opts = effective_compile_opts;
compile_units.push_back(std::move(cu));
}
for (const auto &sf : unity->standalone_files) {
compile_units.push_back(*raw_by_phys.at(sf.lexically_normal()));
}
} else {
compile_units = std::move(raw_units);
}
// 6. Compile actions (C++20/23/26 P1689 named modules & partitions OR regular C/C++ TUs).
std::vector<std::string> compile_action_ids;
const bool has_module_sources = std::ranges::any_of(
compile_units, [](const CompileUnitSpec &u) { return u.is_explicit_module; });
const bool has_cpp_sources =
std::ranges::any_of(compile_units, [](const CompileUnitSpec &u) { return !u.is_c; });
const bool run_module_pipeline =
has_module_sources || (has_cpp_sources && !external_module_bmis.empty());
std::optional<std::filesystem::path> shared_hu_mapper;
if (!gcc_header_unit_mapper_lines.empty() && toolchain.family == CompilerFamily::Gcc &&
!run_module_pipeline) {
shared_hu_mapper = target_bmi_root / "header_units.modmap";
if (auto w = Platform::atomic_write_file(*shared_hu_mapper,
gcc_header_unit_mapper_lines, false);
!w) {
return std::unexpected{w.error()};
}
}
auto emit_regular_compile_action =
[&](const CompileUnitSpec &cu) -> Void::Result::Result<void, Void::Result::Error> {
const std::string src_hash = Util::sha256_hex(cu.logical_src.string()).substr(0, 12);
const auto obj_path =
objects_root / sanitize_id_component(t.name) /
(sanitize_id_component(cu.logical_src.filename().string()) + "_" + src_hash + ".o");
const auto dep_path = std::filesystem::path{obj_path.string() + ".d"};
Toolchain::CompileRequest req;
req.source_file = cu.physical_src;
req.output_object = obj_path;
req.depfile = dep_path;
req.response_file_dir = rsp_root;
req.include_dirs = physical_includes;
req.defines = effective_defines;
req.compile_options = cu.tu_opts;
req.is_c_source = cu.is_c;
req.c_standard = cu.is_c ? eff_c_std : CStandard::Default;
req.cxx_standard =
cu.is_c ? CxxStandard::Default
: ((!header_unit_bmi_paths.empty() && eff_std == CxxStandard::Default)
? CxxStandard::Cxx20
: eff_std);
req.lto = eff_lto;
req.sanitizers = eff_sans;
req.position_independent = pic;
req.precompiled_header = cu.is_c ? std::nullopt : pch_include_prefix;
req.prefix_maps = prefix_maps;
req.reproducibility_epoch = description.profile.reproducibility_epoch;
req.nondeterministic = t.nondeterministic || description.profile.nondeterministic;
req.response_file_threshold = options.response_file_threshold;
if (!cu.is_c) {
if (shared_hu_mapper) {
req.module_mapper_file = shared_hu_mapper;
} else if (!header_unit_bmi_paths.empty() &&
toolchain.family == CompilerFamily::Clang) {
for (const auto &hb : header_unit_bmi_paths) {
req.module_bmi_imports.emplace_back(std::string{}, hb);
}
}
}
auto lowered = Toolchain::lower_compile_command(toolchain, req);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash;
act.kind = ActionKind::Compile;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.response_file = lowered->response_file;
act.response_file_content = std::move(lowered->response_file_content);
act.declared_inputs = {cu.physical_src};
if (!cu.is_c) {
for (const auto &hb : header_unit_bmi_paths) {
act.declared_inputs.push_back(hb);
}
if (shared_hu_mapper) {
act.declared_inputs.push_back(*shared_hu_mapper);
}
}
act.declared_outputs = {obj_path};
act.depfile = dep_path;
act.logical_source_file = cu.logical_src;
act.physical_source_file = cu.physical_src;
act.logical_output_file = obj_path;
act.physical_output_file = obj_path;
act.logical_include_dirs = effective_includes;
act.physical_include_dirs = physical_includes;
act.defines = effective_defines;
act.compile_options = cu.tu_opts;
act.is_c_source = req.is_c_source;
act.c_standard = req.c_standard;
act.cxx_standard = req.cxx_standard;
act.lto = eff_lto;
act.sanitizers = eff_sans;
act.position_independent = pic;
act.precompiled_header = req.precompiled_header;
act.dependencies = target_prereq_actions;
if (!cu.is_c) {
if (pch_action_id) {
add_unique_str(act.dependencies, *pch_action_id);
}
for (const auto &huid : header_unit_action_ids) {
add_unique_str(act.dependencies, huid);
}
}
if (const auto prod_it = output_owner.find(cu.logical_src);
prod_it != output_owner.end()) {
add_unique_str(act.dependencies, prod_it->second);
}
act.nondeterministic = req.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(obj_path, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.action_key = compute_action_key(act, graph);
compile_action_ids.push_back(act.id);
tc.object_files.push_back(obj_path);
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
return {};
};
if (run_module_pipeline) {
const CxxStandard mod_std =
(eff_std == CxxStandard::Default || eff_std == CxxStandard::Cxx17)
? CxxStandard::Cxx20
: eff_std;
const auto scan_dir =
graph.profile_build_dir / "modscan" / sanitize_id_component(t.name);
std::vector<Modules::ModuleScanUnit> scanned;
scanned.reserve(compile_units.size());
std::map<std::filesystem::path, const CompileUnitSpec *> cu_by_phys;
for (const auto &cu : compile_units) {
if (cu.is_c) {
if (auto r = emit_regular_compile_action(cu); !r) {
return std::unexpected{r.error()};
}
continue;
}
const auto norm_phys = cu.physical_src.lexically_normal();
cu_by_phys[norm_phys] = &cu;
auto scan = Modules::scan_translation_unit(toolchain, norm_phys, scan_dir,
physical_includes, effective_defines,
cu.tu_opts, mod_std);
if (!scan) {
return std::unexpected{scan.error()};
}
scanned.push_back(std::move(*scan));
}
auto collated = Modules::collate_modules(scanned, target_bmi_root,
graph.profile_identity + ":" + t.name, bmi_ext,
external_module_bmis);
if (!collated) {
return std::unexpected{collated.error()};
}
std::map<std::string, std::string, std::less<>> provider_action_by_module;
std::map<std::string, std::vector<std::string>, std::less<>> module_deps_by_name;
for (const auto &n : collated->ordered_units) {
for (const auto &prov : n.provides) {
module_deps_by_name[prov] = n.required_modules;
}
}
auto collect_transitive_bmis = [&](const std::vector<std::string> &direct_reqs)
-> std::vector<std::pair<std::string, std::filesystem::path>> {
std::vector<std::pair<std::string, std::filesystem::path>> bmis;
std::set<std::string> seen;
std::queue<std::string> q;
bool uses_external = false;
for (const auto &r : direct_reqs) {
if (seen.insert(r).second) {
q.push(r);
}
if (external_module_bmis.contains(r)) {
uses_external = true;
}
}
while (!q.empty()) {
const auto cur = q.front();
q.pop();
if (const auto bit = collated->module_to_bmi.find(cur);
bit != collated->module_to_bmi.end()) {
bmis.emplace_back(cur, bit->second);
} else if (const auto ebit = external_module_bmis.find(cur);
ebit != external_module_bmis.end()) {
bmis.emplace_back(cur, ebit->second);
uses_external = true;
}
if (const auto dit = module_deps_by_name.find(cur);
dit != module_deps_by_name.end()) {
for (const auto &sub : dit->second) {
if (seen.insert(sub).second) {
q.push(sub);
}
}
}
}
if (uses_external) {
for (const auto &[mname, bmi_p] : external_module_bmis) {
if (seen.insert(mname).second) {
bmis.emplace_back(mname, bmi_p);
}
}
}
return bmis;
};
for (const auto &node : collated->ordered_units) {
const auto &cu = *cu_by_phys.at(node.source_file.lexically_normal());
const std::string src_hash =
Util::sha256_hex(cu.logical_src.string()).substr(0, 12);
const auto obj_path = objects_root / sanitize_id_component(t.name) /
(sanitize_id_component(cu.logical_src.filename().string()) +
"_" + src_hash + ".o");
const auto dep_path = std::filesystem::path{obj_path.string() + ".d"};
const bool tu_uses_modules =
!node.provides.empty() || !node.required_modules.empty();
const CxxStandard tu_std = tu_uses_modules ? mod_std : eff_std;
std::vector<std::string> unit_deps = target_prereq_actions;
if (pch_action_id) {
add_unique_str(unit_deps, *pch_action_id);
}
for (const auto &huid : header_unit_action_ids) {
add_unique_str(unit_deps, huid);
}
if (const auto prod_it = output_owner.find(cu.logical_src);
prod_it != output_owner.end()) {
add_unique_str(unit_deps, prod_it->second);
}
bool tu_uses_external_mod = false;
for (const auto &req_mod : node.required_modules) {
if (const auto pit = provider_action_by_module.find(req_mod);
pit != provider_action_by_module.end()) {
add_unique_str(unit_deps, pit->second);
} else {
tu_uses_external_mod = true;
if (const auto epit = external_module_action_ids.find(req_mod);
epit != external_module_action_ids.end()) {
add_unique_str(unit_deps, epit->second);
}
}
}
if (tu_uses_external_mod ||
(!node.provides.empty() && !external_module_action_ids.empty())) {
for (const auto &[mname, aid] : external_module_action_ids) {
(void)mname;
add_unique_str(unit_deps, aid);
}
}
if (toolchain.family == CompilerFamily::Gcc) {
std::optional<std::filesystem::path> mapper_to_use;
if (!node.module_mapper_path.empty()) {
mapper_to_use = node.module_mapper_path;
if (!gcc_header_unit_mapper_lines.empty()) {
auto prev = Void::FileSystem::read_file(*mapper_to_use).value_or("");
auto w = Platform::atomic_write_file(
*mapper_to_use, prev + gcc_header_unit_mapper_lines, false);
if (!w) {
return std::unexpected{w.error()};
}
}
} else if (!gcc_header_unit_mapper_lines.empty()) {
mapper_to_use = target_bmi_root / (src_hash + ".hu.modmap");
auto w = Platform::atomic_write_file(*mapper_to_use,
gcc_header_unit_mapper_lines, false);
if (!w) {
return std::unexpected{w.error()};
}
}
std::vector<std::string> tu_opts = cu.tu_opts;
if (cu.is_explicit_module || is_module_source_extension(cu.physical_src)) {
tu_opts.push_back("-x");
tu_opts.push_back("c++");
}
Toolchain::CompileRequest req;
req.source_file = cu.physical_src;
req.output_object = obj_path;
req.depfile = dep_path;
req.response_file_dir = rsp_root;
req.include_dirs = physical_includes;
req.defines = effective_defines;
req.compile_options = tu_opts;
req.cxx_standard = tu_std;
req.lto = eff_lto;
req.sanitizers = eff_sans;
req.position_independent = pic;
req.precompiled_header = pch_include_prefix;
req.prefix_maps = prefix_maps;
req.reproducibility_epoch = description.profile.reproducibility_epoch;
req.nondeterministic =
t.nondeterministic || description.profile.nondeterministic;
req.response_file_threshold = options.response_file_threshold;
req.is_module_interface = !node.provides.empty();
req.module_mapper_file = mapper_to_use;
auto lowered = Toolchain::lower_compile_command(toolchain, req);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash;
act.kind = ActionKind::Compile;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.response_file = lowered->response_file;
act.response_file_content = std::move(lowered->response_file_content);
act.declared_inputs = {cu.physical_src};
for (const auto &[mname, bmi_p] : node.imported_bmis) {
(void)mname;
act.declared_inputs.push_back(bmi_p);
}
if (tu_uses_external_mod || !node.provides.empty()) {
for (const auto &[mname, bmi_p] : external_module_bmis) {
(void)mname;
if (!std::ranges::contains(act.declared_inputs, bmi_p)) {
act.declared_inputs.push_back(bmi_p);
}
}
}
for (const auto &hb : header_unit_bmi_paths) {
act.declared_inputs.push_back(hb);
}
if (mapper_to_use) {
act.declared_inputs.push_back(*mapper_to_use);
}
act.declared_outputs = {obj_path};
if (!node.bmi_output_path.empty()) {
act.declared_outputs.push_back(node.bmi_output_path);
if (auto reg = register_output(node.bmi_output_path, act.id); !reg) {
return std::unexpected{reg.error()};
}
}
act.depfile = dep_path;
act.logical_source_file = cu.logical_src;
act.physical_source_file = cu.physical_src;
act.logical_output_file = obj_path;
act.physical_output_file = obj_path;
act.logical_include_dirs = effective_includes;
act.physical_include_dirs = physical_includes;
act.defines = effective_defines;
act.compile_options = tu_opts;
act.cxx_standard = tu_std;
act.lto = eff_lto;
act.sanitizers = eff_sans;
act.position_independent = pic;
act.precompiled_header = pch_include_prefix;
act.dependencies = std::move(unit_deps);
act.nondeterministic = req.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(obj_path, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.action_key = compute_action_key(act, graph);
for (const auto &prov : node.provides) {
provider_action_by_module[prov] = act.id;
tc.exported_module_bmis[prov] = node.bmi_output_path;
tc.exported_module_action_ids[prov] = act.id;
}
if (!node.provides.empty()) {
for (const auto &[imp_m, imp_bmi] : node.imported_bmis) {
tc.exported_module_bmis.try_emplace(imp_m, imp_bmi);
if (const auto pit = provider_action_by_module.find(imp_m);
pit != provider_action_by_module.end()) {
tc.exported_module_action_ids.try_emplace(imp_m, pit->second);
} else if (const auto epit = external_module_action_ids.find(imp_m);
epit != external_module_action_ids.end()) {
tc.exported_module_action_ids.try_emplace(imp_m, epit->second);
}
}
}
compile_action_ids.push_back(act.id);
tc.object_files.push_back(obj_path);
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
} else {
// Clang two-step module compilation:
// Providers: (1) --precompile source -> .pcm (ModuleBmi), (2) -c .pcm -> .o.
// Importers: -c source -fmodule-file=... -> .o.
std::vector<std::pair<std::string, std::filesystem::path>> clang_imports =
collect_transitive_bmis(node.required_modules);
for (const auto &hb : header_unit_bmi_paths) {
clang_imports.emplace_back(std::string{}, hb);
}
if (!node.provides.empty()) {
std::vector<std::string> bmi_opts = cu.tu_opts;
bmi_opts.push_back("-x");
bmi_opts.push_back("c++-module");
Toolchain::CompileRequest breq;
breq.source_file = cu.physical_src;
breq.output_object = obj_path;
breq.depfile = std::filesystem::path{node.bmi_output_path.string() + ".d"};
breq.response_file_dir = rsp_root;
breq.include_dirs = physical_includes;
breq.defines = effective_defines;
breq.compile_options = bmi_opts;
breq.cxx_standard = tu_std;
breq.lto = eff_lto;
breq.sanitizers = eff_sans;
breq.position_independent = pic;
breq.precompiled_header = pch_include_prefix;
breq.prefix_maps = prefix_maps;
breq.reproducibility_epoch = description.profile.reproducibility_epoch;
breq.nondeterministic =
t.nondeterministic || description.profile.nondeterministic;
breq.response_file_threshold = options.response_file_threshold;
breq.is_module_interface = true;
breq.bmi_output = node.bmi_output_path;
breq.module_bmi_imports = clang_imports;
auto lowered_bmi = Toolchain::lower_compile_command(toolchain, breq);
if (!lowered_bmi) {
return std::unexpected{lowered_bmi.error()};
}
ActionNode bmi_act;
bmi_act.id = "bmi:" + sanitize_id_component(t.name) + ":" + src_hash;
bmi_act.kind = ActionKind::ModuleBmi;
bmi_act.target_name = t.name;
bmi_act.executable = lowered_bmi->executable;
bmi_act.arguments = std::move(lowered_bmi->arguments);
bmi_act.environment = std::move(lowered_bmi->environment);
bmi_act.working_directory = canonical_root;
bmi_act.response_file = lowered_bmi->response_file;
bmi_act.response_file_content =
std::move(lowered_bmi->response_file_content);
bmi_act.declared_inputs = {cu.physical_src};
for (const auto &[mname, bmi_p] : clang_imports) {
(void)mname;
bmi_act.declared_inputs.push_back(bmi_p);
}
bmi_act.declared_outputs = {node.bmi_output_path};
bmi_act.depfile = breq.depfile;
bmi_act.logical_source_file = cu.logical_src;
bmi_act.physical_source_file = cu.physical_src;
bmi_act.logical_output_file = node.bmi_output_path;
bmi_act.physical_output_file = node.bmi_output_path;
bmi_act.dependencies = std::move(unit_deps);
bmi_act.nondeterministic = breq.nondeterministic;
bmi_act.cacheable = !bmi_act.nondeterministic;
if (auto reg = register_output(node.bmi_output_path, bmi_act.id); !reg) {
return std::unexpected{reg.error()};
}
bmi_act.action_key = compute_action_key(bmi_act, graph);
const std::string bmi_act_id = bmi_act.id;
for (const auto &prov : node.provides) {
provider_action_by_module[prov] = bmi_act_id;
tc.exported_module_bmis[prov] = node.bmi_output_path;
tc.exported_module_action_ids[prov] = bmi_act_id;
}
for (const auto &[imp_m, imp_bmi] : clang_imports) {
if (imp_m.empty()) {
continue;
}
tc.exported_module_bmis.try_emplace(imp_m, imp_bmi);
if (const auto pit = provider_action_by_module.find(imp_m);
pit != provider_action_by_module.end()) {
tc.exported_module_action_ids.try_emplace(imp_m, pit->second);
} else if (const auto epit = external_module_action_ids.find(imp_m);
epit != external_module_action_ids.end()) {
tc.exported_module_action_ids.try_emplace(imp_m, epit->second);
}
}
summary.action_ids.push_back(bmi_act_id);
graph.action_index_by_id[bmi_act_id] = graph.actions.size();
graph.actions.push_back(std::move(bmi_act));
// Step 2: compile .pcm -> .o.
Toolchain::CompileRequest oreq;
oreq.source_file = node.bmi_output_path;
oreq.output_object = obj_path;
oreq.response_file_dir = rsp_root;
oreq.cxx_standard = tu_std;
oreq.lto = eff_lto;
oreq.sanitizers = eff_sans;
oreq.position_independent = pic;
oreq.reproducibility_epoch = description.profile.reproducibility_epoch;
oreq.nondeterministic = breq.nondeterministic;
oreq.response_file_threshold = options.response_file_threshold;
oreq.compile_only = true;
oreq.module_bmi_imports = clang_imports;
auto lowered_obj = Toolchain::lower_compile_command(toolchain, oreq);
if (!lowered_obj) {
return std::unexpected{lowered_obj.error()};
}
ActionNode obj_act;
obj_act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash;
obj_act.kind = ActionKind::Compile;
obj_act.target_name = t.name;
obj_act.executable = lowered_obj->executable;
obj_act.arguments = std::move(lowered_obj->arguments);
obj_act.environment = std::move(lowered_obj->environment);
obj_act.working_directory = canonical_root;
obj_act.response_file = lowered_obj->response_file;
obj_act.response_file_content =
std::move(lowered_obj->response_file_content);
obj_act.declared_inputs = {node.bmi_output_path};
for (const auto &[mname, bmi_p] : clang_imports) {
(void)mname;
obj_act.declared_inputs.push_back(bmi_p);
}
obj_act.declared_outputs = {obj_path};
obj_act.logical_output_file = obj_path;
obj_act.physical_output_file = obj_path;
obj_act.dependencies = {bmi_act_id};
obj_act.nondeterministic = oreq.nondeterministic;
obj_act.cacheable = !obj_act.nondeterministic;
if (auto reg = register_output(obj_path, obj_act.id); !reg) {
return std::unexpected{reg.error()};
}
obj_act.action_key = compute_action_key(obj_act, graph);
compile_action_ids.push_back(obj_act.id);
tc.object_files.push_back(obj_path);
summary.action_ids.push_back(obj_act.id);
graph.action_index_by_id[obj_act.id] = graph.actions.size();
graph.actions.push_back(std::move(obj_act));
} else {
Toolchain::CompileRequest req;
req.source_file = cu.physical_src;
req.output_object = obj_path;
req.depfile = dep_path;
req.response_file_dir = rsp_root;
req.include_dirs = physical_includes;
req.defines = effective_defines;
req.compile_options = cu.tu_opts;
req.cxx_standard = tu_std;
req.lto = eff_lto;
req.sanitizers = eff_sans;
req.position_independent = pic;
req.precompiled_header = pch_include_prefix;
req.prefix_maps = prefix_maps;
req.reproducibility_epoch = description.profile.reproducibility_epoch;
req.nondeterministic =
t.nondeterministic || description.profile.nondeterministic;
req.response_file_threshold = options.response_file_threshold;
req.module_bmi_imports = clang_imports;
auto lowered = Toolchain::lower_compile_command(toolchain, req);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash;
act.kind = ActionKind::Compile;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.response_file = lowered->response_file;
act.response_file_content = std::move(lowered->response_file_content);
act.declared_inputs = {cu.physical_src};
for (const auto &[mname, bmi_p] : clang_imports) {
(void)mname;
act.declared_inputs.push_back(bmi_p);
}
act.declared_outputs = {obj_path};
act.depfile = dep_path;
act.logical_source_file = cu.logical_src;
act.physical_source_file = cu.physical_src;
act.logical_output_file = obj_path;
act.physical_output_file = obj_path;
act.logical_include_dirs = effective_includes;
act.physical_include_dirs = physical_includes;
act.defines = effective_defines;
act.compile_options = cu.tu_opts;
act.cxx_standard = tu_std;
act.lto = eff_lto;
act.sanitizers = eff_sans;
act.position_independent = pic;
act.precompiled_header = pch_include_prefix;
act.dependencies = std::move(unit_deps);
act.nondeterministic = req.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(obj_path, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.action_key = compute_action_key(act, graph);
compile_action_ids.push_back(act.id);
tc.object_files.push_back(obj_path);
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
}
}
}
} else {
for (const auto &cu : compile_units) {
if (auto r = emit_regular_compile_action(cu); !r) {
return std::unexpected{r.error()};
}
}
}
// 7. Archive or Link action for concrete product targets.
if (t.kind == TargetKind::ObjectLibrary) {
tc.producer_action_ids = compile_action_ids;
summary.primary_outputs = tc.object_files;
} else if (t.kind == TargetKind::StaticLibrary) {
const auto archive_path = artifacts_root / ("lib" + t.name + ".a");
auto lowered =
Toolchain::lower_archive_command(toolchain, archive_path, tc.object_files, rsp_root,
options.response_file_threshold);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "archive:" + sanitize_id_component(t.name);
act.kind = ActionKind::Archive;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.response_file = lowered->response_file;
act.response_file_content = std::move(lowered->response_file_content);
act.declared_inputs = tc.object_files;
act.declared_outputs = {archive_path};
act.logical_output_file = archive_path;
act.physical_output_file = archive_path;
act.dependencies = compile_action_ids;
act.nondeterministic = t.nondeterministic || description.profile.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(archive_path, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.action_key = compute_action_key(act, graph);
tc.primary_artifact = archive_path;
tc.producer_action_ids = {act.id};
summary.primary_outputs = {archive_path};
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
} else if (t.kind == TargetKind::Executable || t.kind == TargetKind::SharedLibrary ||
t.kind == TargetKind::Test) {
const auto out_name =
(t.kind == TargetKind::SharedLibrary) ? ("lib" + t.name + ".so") : t.name;
const auto bin_path =
(t.kind == TargetKind::SharedLibrary ? artifacts_root : (artifacts_root / "bin")) /
out_name;
std::vector<std::filesystem::path> all_objects = tc.object_files;
all_objects.insert(all_objects.end(), link_objects.begin(), link_objects.end());
std::vector<std::filesystem::path> rpaths;
for (const auto &sh : link_shared_libs) {
const auto dir = sh.parent_path();
if (!dir.empty() && !std::ranges::contains(rpaths, dir)) {
rpaths.push_back(dir);
}
}
Toolchain::LinkRequest lreq;
lreq.kind = t.kind;
lreq.output_file = bin_path;
lreq.response_file_dir = rsp_root;
lreq.object_files = all_objects;
lreq.static_libraries = link_static_libs;
lreq.shared_libraries = link_shared_libs;
lreq.rpaths = rpaths;
lreq.link_options = effective_link_opts;
lreq.lto = eff_lto;
lreq.sanitizers = eff_sans;
lreq.response_file_threshold = options.response_file_threshold;
auto lowered = Toolchain::lower_link_command(toolchain, lreq);
if (!lowered) {
return std::unexpected{lowered.error()};
}
ActionNode act;
act.id = "link:" + sanitize_id_component(t.name);
act.kind = ActionKind::Link;
act.target_name = t.name;
act.executable = lowered->executable;
act.arguments = std::move(lowered->arguments);
act.environment = std::move(lowered->environment);
act.working_directory = canonical_root;
act.response_file = lowered->response_file;
act.response_file_content = std::move(lowered->response_file_content);
act.declared_inputs = all_objects;
act.declared_inputs.insert(act.declared_inputs.end(), link_static_libs.begin(),
link_static_libs.end());
act.declared_inputs.insert(act.declared_inputs.end(), link_shared_libs.begin(),
link_shared_libs.end());
act.declared_outputs = {bin_path};
act.logical_output_file = bin_path;
act.physical_output_file = bin_path;
act.dependencies = compile_action_ids;
for (const auto &dep_in : act.declared_inputs) {
if (const auto prod_it = output_owner.find(dep_in.lexically_normal());
prod_it != output_owner.end()) {
add_unique_str(act.dependencies, prod_it->second);
}
}
act.nondeterministic = t.nondeterministic || description.profile.nondeterministic;
act.cacheable = !act.nondeterministic;
if (auto reg = register_output(bin_path, act.id); !reg) {
return std::unexpected{reg.error()};
}
act.action_key = compute_action_key(act, graph);
tc.primary_artifact = bin_path;
tc.producer_action_ids = {act.id};
summary.primary_outputs = {bin_path};
summary.action_ids.push_back(act.id);
graph.action_index_by_id[act.id] = graph.actions.size();
graph.actions.push_back(std::move(act));
}
summary.exported_module_bmis = tc.exported_module_bmis;
computed[t.name] = std::move(tc);
graph.targets.push_back(std::move(summary));
}
return graph;
}
} // namespace Void::Build::Graph