Files
Library/build.cpp
Void agent 99c91ab5fc
VoidLibrary (VBS) / vbs-build (pull_request) Failing after 1m3s
VoidLibrary (VBS) / vbs-build (push) Failing after 1m8s
build: declare package tests and run them in CI
2026-12-05 11:39:19 +03:00

1057 lines
42 KiB
C++

// First-class VoidBuildSystem description for VoidLibrary.
//
// Mirrors the module graph declared by src/<Module>/module.cmake without CMake:
// every module becomes a target with its own sources, usage requirements and
// external dependencies, and the Void::Testing suites are registered through
// generated units. The CMake build remains the bootstrap path.
//
// External dependencies are detected from the environment and conventional
// prefixes:
// <NAME>_ROOT, <NAME>_INCLUDE_DIR, <NAME>_LIBRARY_DIR
// plus CPATH / LIBRARY_PATH. Optional backends (OpenSSL for Crypto,
// LibArchive for Archive, Lua for Script) are reported through the same
// VOID_*_HAS_* macros the CMake build defines.
#include <Void/Build.hpp>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <map>
#include <optional>
#include <ranges>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace
{
namespace fs = std::filesystem;
using namespace Void::Build;
// ── Module graph (mirrors src/<Module>/module.cmake INTERNAL_DEPS) ──────────
const std::map<std::string, std::vector<std::string>, std::less<>> &module_defs()
{
static const std::map<std::string, std::vector<std::string>, std::less<>> defs{
{"Core", {}},
{"Functional", {}},
{"Math", {}},
{"Algorithms", {"Core", "Math"}},
{"Memory", {"Core"}},
{"Time", {}},
{"Text", {}},
{"Unicode", {"Core", "Text"}},
{"LogState", {}},
{"Data", {"Core", "Math", "Time"}},
{"System", {"Functional", "Time", "LogState"}},
{"Async", {"Functional", "Time", "LogState"}},
{"Crypto", {"Functional"}},
{"Archive", {"Functional", "Time", "System"}},
{"Configuration", {"Core", "Functional", "System", "Data", "Time", "LogState"}},
{"Log", {"Async", "Core", "Data", "Functional", "Memory", "Time", "LogState"}},
{"Testing", {"Core", "Functional", "Time", "LogState"}},
{"Containers", {"Core", "Memory"}},
{"Binary", {"Functional", "Memory"}},
{"ConfigurationAsync",
{"Configuration", "SystemAsync", "Async", "Time", "Functional", "LogState"}},
{"CryptoAsync", {"Crypto", "IO", "Async", "Time", "Functional"}},
{"Discovery", {"Core", "Functional", "Time", "Async"}},
{"DiscoveryRpc", {"Discovery", "RPC"}},
{"Fsm", {"Async", "Core", "Data", "Functional", "Time", "Log", "Service"}},
{"FunctionalCoreFormatting", {"Functional", "Core"}},
{"IO", {"Core", "Functional", "Time", "Memory", "Async"}},
{"IPC", {"Core", "Functional", "Memory", "Time", "Binary", "Async", "IO", "Resilience"}},
{"LogConfig", {"Log", "Configuration", "Functional"}},
{"MCP", {"Functional", "Data"}},
{"Messaging", {"Core", "Functional", "Binary", "Time", "Async"}},
{"MessagingRpc", {"Messaging", "RPC"}},
{"MessagingStorage", {"Messaging", "Storage"}},
{"Net", {"Functional", "Text", "Time"}},
{"Observability", {"ObservabilityHooks", "Core", "Functional", "Time", "Memory"}},
{"ObservabilityHooks", {}},
{"Plugin", {"Core", "Functional", "System", "Data", "Time", "Async", "LogState", "Text",
"Service"}},
{"RPC", {"Core", "Functional", "Binary", "Data", "Time", "Async", "Net"}},
{"Resilience", {"Functional", "Time", "ObservabilityHooks"}},
{"ResilienceAsync",
{"Resilience", "Async", "Functional", "Time", "ObservabilityHooks"}},
{"Runtime", {"Core", "Functional", "Time", "Memory", "Algorithms", "Async", "IO"}},
{"Scheduler", {"Core", "Functional", "Time", "Async"}},
{"SchedulerStorage", {"Scheduler", "Storage"}},
{"Script", {}},
{"Security", {"Functional", "Time"}},
{"SecurityAsync", {"Security", "Async", "Time", "Resilience", "Functional"}},
{"Service", {"Core", "Functional", "Time", "Async", "LogState"}},
{"ServicePlugin", {"Service", "Plugin", "LogState"}},
{"ShortUrl", {"Service", "Time"}},
{"ShortUrlRemote", {"ShortUrl", "Net", "Data"}},
{"ShortUrlStorage", {"ShortUrl", "Storage", "Security"}},
{"Sqlite", {"Functional", "Time"}},
{"SqliteAsync", {"Sqlite", "Async", "Time", "Functional"}},
{"Stacktrace", {"Functional", "Time", "LogState"}},
{"Storage", {"Core", "Functional", "Time", "Memory", "Binary", "IO", "Async"}},
{"SystemAsync", {"System", "Async", "IO", "Time", "Functional", "LogState"}},
{"TestingMock", {"Core", "Testing", "Functional"}},
{"Update", {"Archive", "Crypto", "Data", "Functional", "System", "Text", "Time"}},
};
return defs;
}
// Modules linked (and VOID_HAS_<DEP> defined) when the optional dependency is
// part of the selected module set; mirrors void_add_module(OPTIONAL_DEPS).
const std::map<std::string, std::vector<std::string>, std::less<>> &optional_deps()
{
static const std::map<std::string, std::vector<std::string>, std::less<>> deps{
{"Testing", {"Stacktrace", "Log", "Async", "Configuration", "Text"}},
{"Log", {"Stacktrace"}},
};
return deps;
}
// ── Small helpers ───────────────────────────────────────────────────────────
std::string upper_case(std::string_view text)
{
std::string out{text};
for (char &c : out) {
if (c >= 'a' && c <= 'z') {
c = static_cast<char>(c - 'a' + 'A');
} else if (c == '-' || c == '.') {
c = '_';
}
}
return out;
}
std::optional<std::string> env_value(const std::string &name)
{
const char *value = std::getenv(name.c_str());
if (value == nullptr || *value == '\0') {
return std::nullopt;
}
return std::string{value};
}
std::vector<std::string> split_list(std::string_view text, std::string_view separators)
{
std::vector<std::string> parts;
std::size_t pos = 0;
while (pos <= text.size()) {
std::size_t end = text.find_first_of(separators, pos);
if (end == std::string_view::npos) {
end = text.size();
}
std::string_view token = text.substr(pos, end - pos);
while (!token.empty() && (token.front() == ' ' || token.front() == '\t')) {
token.remove_prefix(1);
}
while (!token.empty() && (token.back() == ' ' || token.back() == '\t')) {
token.remove_suffix(1);
}
if (!token.empty()) {
parts.emplace_back(token);
}
if (end == text.size()) {
break;
}
pos = end + 1;
}
return parts;
}
std::vector<std::string> sorted_cpp_files(const fs::path &directory,
const fs::path &root,
const std::vector<std::string> &excluded_names = {})
{
std::vector<std::string> files;
std::error_code ec;
if (!fs::is_directory(directory, ec)) {
return files;
}
for (auto it = fs::recursive_directory_iterator(directory, ec);
!ec && it != fs::recursive_directory_iterator(); it.increment(ec)) {
if (!it->is_regular_file(ec) || it->path().extension() != ".cpp") {
continue;
}
const std::string name = it->path().filename().string();
if (std::ranges::contains(excluded_names, name)) {
continue;
}
files.push_back(fs::relative(it->path(), root, ec).generic_string());
}
std::sort(files.begin(), files.end());
return files;
}
// ── External dependency detection ──────────────────────────────────────────
// ── Test discovery ────────────────────────────────────────────────────────
// Registration units are generated here rather than by `vbs gen-tests`,
// which does not handle DisabledTest, @tag/@skip comments, wrapped
// declarations, Suite members (which self-register through reflection) or
// Fixture members (which register as `&Fixture::member`).
struct DiscoveredCase
{
std::string function;
std::string owner; // Fixture class, or empty for a free function
std::size_t line{0};
std::vector<std::string> tags;
bool skipped{false};
std::string skip_reason;
};
struct TestToken
{
bool found{false};
bool disabled{false};
bool complete{false};
std::size_t name_begin{0};
std::size_t name_end{0};
};
bool is_identifier_char(char c)
{
return std::isalnum(static_cast<unsigned char>(c)) != 0 || c == '_';
}
TestToken find_test_token(std::string_view line)
{
TestToken token;
for (std::size_t search = 0;;) {
const std::size_t at = line.find("Test", search);
if (at == std::string_view::npos) {
return token;
}
const bool disabled = at >= 8 && line.substr(at - 8, 8) == "Disabled";
const std::size_t start = disabled ? at - 8 : at;
const std::size_t length = disabled ? 12 : 4;
const bool before_ok =
start == 0 || !is_identifier_char(line[start - 1]);
const std::size_t after = start + length;
if (before_ok && after < line.size() &&
(line[after] == ' ' || line[after] == '\t')) {
std::size_t begin = after;
while (begin < line.size() && (line[begin] == ' ' || line[begin] == '\t')) {
++begin;
}
std::size_t end = begin;
while (end < line.size() && is_identifier_char(line[end])) {
++end;
}
if (end > begin) {
std::size_t paren = end;
while (paren < line.size() &&
(line[paren] == ' ' || line[paren] == '\t')) {
++paren;
}
token.found = true;
token.disabled = disabled;
token.name_begin = begin;
token.name_end = end;
if (paren < line.size() && line[paren] == '(') {
std::size_t close = paren + 1;
while (close < line.size() &&
(line[close] == ' ' || line[close] == '\t')) {
++close;
}
token.complete = close < line.size() && line[close] == ')';
}
return token;
}
}
search = at + 1;
}
}
std::string trim_copy(std::string_view text)
{
const std::size_t first = text.find_first_not_of(" \t\r");
if (first == std::string_view::npos) {
return {};
}
const std::size_t last = text.find_last_not_of(" \t\r");
return std::string{text.substr(first, last - first + 1)};
}
std::vector<std::pair<std::size_t, std::string>> logical_lines(const fs::path &file)
{
std::ifstream input{file};
std::vector<std::string> raw;
std::string line;
while (std::getline(input, line)) {
raw.push_back(std::move(line));
}
std::vector<std::pair<std::size_t, std::string>> joined;
for (std::size_t index = 0; index < raw.size(); ++index) {
std::pair<std::size_t, std::string> entry{index + 1, raw[index]};
const std::string_view trimmed = std::string_view{entry.second}.substr(
std::min(entry.second.find_first_not_of(" \t"), entry.second.size()));
if (!trimmed.starts_with("//")) {
TestToken token = find_test_token(entry.second);
std::size_t extra = 0;
while (token.found && !token.complete && extra < 4 &&
index + 1 < raw.size()) {
entry.second += " " + trim_copy(raw[index + 1]);
++index;
++extra;
token = find_test_token(entry.second);
}
}
joined.push_back(std::move(entry));
}
return joined;
}
std::vector<DiscoveredCase> scan_test_file(const fs::path &file)
{
std::vector<DiscoveredCase> cases;
std::string owner;
bool owner_is_fixture = false;
std::string last_class_name;
std::vector<std::string> tags;
std::string skip_reason;
bool skip_set = false;
for (const auto &[number, text] : logical_lines(file)) {
const std::size_t first = text.find_first_not_of(" \t");
if (first == std::string::npos) {
continue;
}
const std::string_view trimmed{text.data() + first, text.size() - first};
if (trimmed.starts_with("//")) {
if (const std::size_t tag = text.find("@tag");
tag != std::string::npos) {
std::string rest = text.substr(tag + 4);
rest.erase(std::remove(rest.begin(), rest.end(), ' '), rest.end());
for (auto &tag_name : split_list(rest, ",")) {
tags.push_back(std::move(tag_name));
}
}
if (const std::size_t skip = text.find("@skip");
skip != std::string::npos) {
std::string rest = trim_copy(text.substr(skip + 5));
if (rest.size() >= 2 && rest.front() == '"' && rest.back() == '"') {
rest = rest.substr(1, rest.size() - 2);
}
skip_reason = std::move(rest);
skip_set = true;
}
continue;
}
// Track the most recent class name and whether it is a Suite/Fixture.
for (const std::string_view keyword : {"class ", "struct "}) {
const std::size_t at = text.find(keyword);
if (at == std::string::npos) {
continue;
}
std::size_t begin = at + keyword.size();
while (begin < text.size() && text[begin] == ' ') {
++begin;
}
std::size_t end = begin;
while (end < text.size() && is_identifier_char(text[end])) {
++end;
}
if (end > begin) {
last_class_name = text.substr(begin, end - begin);
}
break;
}
const bool suite_line = text.find("Suite<") != std::string::npos;
const bool fixture_line = text.find("Fixture") != std::string::npos;
if ((suite_line || fixture_line) && !last_class_name.empty()) {
owner = last_class_name;
owner_is_fixture = fixture_line;
}
const TestToken token = find_test_token(text);
if (token.found && token.complete) {
DiscoveredCase discovered;
discovered.function =
text.substr(token.name_begin, token.name_end - token.name_begin);
discovered.line = number;
discovered.tags = tags;
discovered.skipped = token.disabled || skip_set;
if (skip_set) {
discovered.skip_reason = skip_reason;
} else if (token.disabled) {
discovered.skip_reason = "disabled";
}
if (first > 0 && !owner.empty()) {
// Suite members self-register via reflection.
if (!owner_is_fixture) {
tags.clear();
skip_reason.clear();
skip_set = false;
continue;
}
discovered.owner = owner;
}
cases.push_back(std::move(discovered));
tags.clear();
skip_reason.clear();
skip_set = false;
continue;
}
tags.clear();
skip_reason.clear();
skip_set = false;
}
return cases;
}
bool compiler_has_reflection()
{
#ifdef __cpp_reflection
return true;
#else
return false;
#endif
}
// Skip test files that include headers of modules outside the selected set
// (mirrors the capability gate in tests/CMakeLists.txt).
bool test_file_dependencies_selected(const fs::path &file,
const std::set<std::string> &selected)
{
std::ifstream input{file};
std::string line;
while (std::getline(input, line)) {
const std::size_t include = line.find("#include");
if (include == std::string::npos) {
continue;
}
std::size_t pos = include + 8;
while (pos < line.size() && (line[pos] == ' ' || line[pos] == '\t')) {
++pos;
}
if (pos >= line.size() || (line[pos] != '<' && line[pos] != '"')) {
continue;
}
const char open = line[pos];
const std::size_t close = line.find(open == '<' ? '>' : '"', pos + 1);
if (close == std::string::npos) {
continue;
}
const std::string_view header{line.data() + pos + 1, close - pos - 1};
if (!header.starts_with("Void/")) {
continue;
}
const std::string_view rest = header.substr(5);
const std::size_t slash = rest.find('/');
if (slash == std::string_view::npos) {
continue;
}
if (!selected.contains(std::string{rest.substr(0, slash)})) {
return false;
}
}
return true;
}
std::string escape_cpp_string(std::string_view text)
{
std::string out;
for (const char c : text) {
switch (c) {
case '\\': out += "\\\\"; break;
case '"': out += "\\\""; break;
case '\n': out += "\\n"; break;
default: out += c; break;
}
}
return out;
}
struct ExternalDep
{
bool found{false};
std::vector<std::string> include_dirs;
std::vector<std::string> link_options;
};
ExternalDep detect_dependency(std::string_view label,
std::initializer_list<std::string_view> headers,
std::initializer_list<std::string_view> libraries,
const std::vector<std::string> &fallback_roots = {})
{
ExternalDep dep;
const std::string prefix = upper_case(label);
std::vector<fs::path> include_roots;
std::vector<fs::path> library_roots;
// Explicit include/library directories win over a combined root, so a
// split package (headers in one output, libraries in another) works.
if (auto include = env_value(prefix + "_INCLUDE_DIR")) {
include_roots.emplace_back(*include);
}
if (auto library = env_value(prefix + "_LIBRARY_DIR")) {
library_roots.emplace_back(*library);
}
if (auto root = env_value(prefix + "_ROOT")) {
include_roots.emplace_back(*root);
library_roots.emplace_back(*root);
}
for (const char *variable : {"CPATH", "CPLUS_INCLUDE_PATH", "C_INCLUDE_PATH"}) {
if (auto paths = env_value(variable)) {
for (auto &path : split_list(*paths, ":")) {
include_roots.emplace_back(path);
}
}
}
for (const char *variable : {"LIBRARY_PATH", "LD_LIBRARY_PATH"}) {
if (auto paths = env_value(variable)) {
for (auto &path : split_list(*paths, ":")) {
library_roots.emplace_back(path);
}
}
}
for (const std::string &root : fallback_roots) {
include_roots.emplace_back(root);
library_roots.emplace_back(root);
}
fs::path include;
for (const auto &root : include_roots) {
for (const fs::path &candidate : {root, root / "include"}) {
bool complete = true;
for (const std::string_view header : headers) {
if (!fs::is_regular_file(candidate / std::string{header})) {
complete = false;
break;
}
}
if (complete) {
include = candidate;
break;
}
}
if (!include.empty()) {
break;
}
}
if (include.empty()) {
return dep;
}
dep.found = true;
dep.include_dirs.push_back(include.string());
fs::path library;
for (const auto &root : library_roots) {
for (const fs::path &candidate : {root / "lib", root / "lib64", root}) {
if (fs::is_directory(candidate)) {
library = candidate;
break;
}
}
if (!library.empty()) {
break;
}
}
if (!library.empty()) {
dep.link_options.push_back("-L" + library.string());
}
for (const std::string_view name : libraries) {
dep.link_options.push_back("-l" + std::string{name});
}
return dep;
}
void apply_external(Target &target, const ExternalDep &dep,
Visibility visibility = Visibility::Public)
{
for (const auto &include : dep.include_dirs) {
target.system_include_directory(include, visibility);
}
for (const auto &option : dep.link_options) {
target.link_option(option, visibility);
}
}
// ── Module selection ──────────────────────────────────────────────────────
std::vector<std::string> selected_modules_in_order()
{
const auto &defs = module_defs();
std::vector<std::string> pending;
if (auto requested = env_value("VOID_ENABLED_MODULES")) {
pending = split_list(*requested, ";, ");
} else {
for (const auto &[name, deps] : defs) {
(void)deps;
pending.push_back(name);
}
}
std::set<std::string> selected;
while (!pending.empty()) {
const std::string module = pending.back();
pending.pop_back();
if (!selected.insert(module).second) {
continue;
}
const auto it = defs.find(module);
if (it == defs.end()) {
throw std::runtime_error{"VoidLibrary: unknown module '" + module + "'"};
}
for (const auto &dependency : it->second) {
pending.push_back(dependency);
}
}
// Deterministic post-order over the requested closure.
std::vector<std::string> ordered;
std::set<std::string> visited;
const std::function<void(const std::string &)> visit = [&](const std::string &module) {
if (!visited.insert(module).second) {
return;
}
for (const auto &dependency : defs.at(module)) {
visit(dependency);
}
ordered.push_back(module);
};
for (const auto &module : selected) {
visit(module);
}
return ordered;
}
std::string shell_quote(std::string_view text)
{
std::string out{"'"};
for (const char c : text) {
if (c == '\'') {
out += "'\\''";
} else {
out += c;
}
}
out += '\'';
return out;
}
} // namespace
void build(Void::Build::Project &project)
{
const ProfileContext &context = project.context();
const fs::path root = fs::current_path();
const bool windows = context.os == "windows";
const bool gcc = context.compiler == CompilerFamily::Gcc;
// ── External dependencies ──────────────────────────────────────────────
const std::vector<std::string> conventional_roots{"/usr", "/usr/local",
"/opt/homebrew"};
const auto boost = detect_dependency(
"Boost", {"boost/beast.hpp", "boost/asio.hpp", "boost/url.hpp",
"boost/stacktrace.hpp"},
{}, conventional_roots);
const auto openssl =
detect_dependency("OpenSSL", {"openssl/ssl.h", "openssl/evp.h"},
{"ssl", "crypto"}, conventional_roots);
const auto sqlite3 = detect_dependency("SQLite3", {"sqlite3.h"}, {"sqlite3"},
conventional_roots);
const auto sodium =
detect_dependency("Sodium", {"sodium.h"}, {"sodium"}, conventional_roots);
const auto libarchive = detect_dependency("LibArchive", {"archive.h"},
{"archive"}, conventional_roots);
const auto lua = detect_dependency("Lua", {"lua.h"}, {"lua5.4"},
conventional_roots);
// ── Module targets ─────────────────────────────────────────────────────
const std::vector<std::string> modules = selected_modules_in_order();
const std::set<std::string> selected(modules.begin(), modules.end());
std::map<std::string, Target, std::less<>> targets;
for (const std::string &module : modules) {
const std::vector<std::string> excluded =
windows ? (module == "Net" ? std::vector<std::string>{"HttpServer.cpp"}
: module == "IO" ? std::vector<std::string>{"EpollDriver.cpp"}
: std::vector<std::string>{})
: std::vector<std::string>{};
const std::vector<std::string> sources =
sorted_cpp_files(root / "src" / module, root, excluded);
Target target = sources.empty()
? project.header_only_library("Void_" + module)
: project.static_library("Void_" + module);
target.cxx_standard(CxxStandard::Cxx26)
.include_directory("include", Visibility::Public);
if (gcc) {
target.compile_option("-freflection", Visibility::Public);
}
for (const auto &source : sources) {
target.sources(SourceSet::file(source));
}
for (const auto &dependency : module_defs().at(module)) {
target.link(targets.at(dependency), Visibility::Public);
}
// External dependencies of this module, mirroring module.cmake.
if (module == "Net") {
if (!boost.found || !openssl.found) {
throw std::runtime_error{
"VoidLibrary: Net requires Boost and OpenSSL "
"(set BOOST_ROOT/BOOST_INCLUDE_DIR and OPENSSL_ROOT_DIR)"};
}
apply_external(target, boost);
apply_external(target, openssl);
// Boost.URL ships compiled symbols.
target.link_option("-lboost_url", Visibility::Public);
target.compile_option("-pthread", Visibility::Public);
target.link_option("-pthread", Visibility::Public);
} else if (module == "Stacktrace") {
if (!boost.found) {
throw std::runtime_error{
"VoidLibrary: Stacktrace requires Boost (set BOOST_ROOT)"};
}
apply_external(target, boost);
target.link_option("-lboost_stacktrace_addr2line", Visibility::Public);
target.link_option("-ldl", Visibility::Public);
target.compile_option("-g");
target.compile_option("-fno-omit-frame-pointer");
} else if (module == "Crypto") {
if (openssl.found) {
apply_external(target, openssl);
target.define("VOID_CRYPTO_HAS_OPENSSL=1", Visibility::Public);
} else {
target.define("VOID_CRYPTO_HAS_OPENSSL=0", Visibility::Public);
}
} else if (module == "CryptoAsync" || module == "SecurityAsync" ||
module == "System" || module == "SystemAsync") {
target.compile_option("-pthread", Visibility::Public);
target.link_option("-pthread", Visibility::Public);
} else if (module == "Archive") {
if (libarchive.found) {
apply_external(target, libarchive);
target.define("VOID_ARCHIVE_HAS_LIBARCHIVE=1", Visibility::Public);
} else {
target.define("VOID_ARCHIVE_HAS_LIBARCHIVE=0", Visibility::Public);
}
} else if (module == "Security") {
if (!sodium.found) {
throw std::runtime_error{
"VoidLibrary: Security requires libsodium (set SODIUM_ROOT)"};
}
apply_external(target, sodium);
} else if (module == "Sqlite") {
if (!sqlite3.found) {
throw std::runtime_error{
"VoidLibrary: Sqlite requires SQLite3 (set SQLITE3_ROOT)"};
}
apply_external(target, sqlite3);
} else if (module == "Plugin") {
if (!windows) {
target.link_option("-ldl", Visibility::Public);
}
} else if (module == "IO" && windows) {
target.link_option("ws2_32", Visibility::Public);
} else if (module == "Script") {
// Defined only when the adapter is built (the sources test
// `#if defined(VOID_SCRIPT_HAS_LUA)`), matching module.cmake.
if (lua.found) {
apply_external(target, lua);
target.define("VOID_SCRIPT_HAS_LUA=1", Visibility::Public);
}
}
targets.emplace(module, target);
}
// OPTIONAL_DEPS: link and define VOID_HAS_<DEP> only when the dependency is
// part of the selected module set.
for (const auto &[module, optionals] : optional_deps()) {
const auto owner = targets.find(module);
if (owner == targets.end()) {
continue;
}
for (const auto &optional : optionals) {
const auto dependency = targets.find(optional);
if (dependency == targets.end()) {
continue;
}
owner->second.link(dependency->second, Visibility::Public);
owner->second.define("VOID_HAS_" + upper_case(optional), Visibility::Public);
}
}
// ── Installation ───────────────────────────────────────────────────────
for (auto &[name, target] : targets) {
(void)name;
if (target.record().kind == TargetKind::StaticLibrary ||
target.record().kind == TargetKind::SharedLibrary) {
target.install("lib");
}
}
project.install_directory("include", "include");
// ── Test support ──────────────────────────────────────────────────────
const auto testing_option = env_value("VOID_ENABLE_TESTING");
const bool tests_enabled = !testing_option || *testing_option != "0";
if (!tests_enabled || !selected.contains("Testing")) {
return;
}
// VBS does not propagate link options from linked static libraries, so
// every external library flag the final binaries may need is applied
// directly to each executable/shared target below.
std::vector<std::string> runtime_link_options;
if (!windows) {
runtime_link_options.push_back("-pthread");
runtime_link_options.push_back("-ldl");
}
for (const auto *dep : {&boost, &openssl, &sqlite3, &sodium, &libarchive, &lua}) {
if (dep->found) {
runtime_link_options.insert(runtime_link_options.end(),
dep->link_options.begin(),
dep->link_options.end());
}
}
const auto link_runtime = [&runtime_link_options](Target &target) {
for (const auto &option : runtime_link_options) {
target.link_option(option, Visibility::Private);
}
};
const std::string artifact_root = "$BUILD_DIR/out";
const std::string bin_root = artifact_root + "/bin";
const std::string lib_root = artifact_root;
const auto library_artifact = [&](const std::string &name) {
return windows ? lib_root + "/" + name + ".dll" : lib_root + "/lib" + name + ".so";
};
const auto binary_artifact = [&](const std::string &name) {
return bin_root + "/" + name + (windows ? ".exe" : "");
};
std::string helper_defines;
const auto add_define = [&helper_defines](const std::string &macro,
const std::string &value) {
helper_defines += "#define " + macro + " \"" + value + "\"\n";
};
add_define("VOID_PROCESS_HELPER_PATH", binary_artifact("VoidProcessHelper"));
add_define("VOID_ARCHIVE_WORKER_PATH", binary_artifact("VoidArchiveWorker"));
add_define("VOID_TEST_PLUGIN_PATH", library_artifact("VoidTestPlugin"));
add_define("VOID_CONFIGURABLE_PATH", library_artifact("VoidConfigurablePlugin"));
add_define("VOID_STATEFUL_V1_PATH", library_artifact("VoidStatefulPluginV1"));
add_define("VOID_STATEFUL_V2_PATH", library_artifact("VoidStatefulPluginV2"));
add_define("VOID_SERVICE_V1_PATH", library_artifact("VoidServicePluginV1"));
add_define("VOID_SERVICE_V2_PATH", library_artifact("VoidServicePluginV2"));
add_define("VOID_CABI_V1_PATH", library_artifact("VoidCAbiPluginV1"));
add_define("VOID_CABI_V2_PATH", library_artifact("VoidCAbiPluginV2"));
add_define("VOID_CABI_BAD_TRUNC_PATH", library_artifact("VoidCAbiBadTrunc"));
add_define("VOID_CABI_BAD_MAJOR_PATH", library_artifact("VoidCAbiBadMajor"));
add_define("VOID_CABI_BAD_RESERVED_PATH", library_artifact("VoidCAbiBadReserved"));
add_define("VOID_CABI_DEP_A_PATH", library_artifact("VoidCAbiDepA"));
add_define("VOID_CABI_DEP_B_PATH", library_artifact("VoidCAbiDepB"));
add_define("VOID_CABI_CYC_A_PATH", library_artifact("VoidCAbiCycA"));
add_define("VOID_CABI_CYC_B_PATH", library_artifact("VoidCAbiCycB"));
std::vector<std::string> test_sources;
for (const auto &file : sorted_cpp_files(root / "tests" / "standalone", root)) {
test_sources.push_back(file);
}
for (const auto &file : sorted_cpp_files(root / "tests" / "internal", root)) {
test_sources.push_back(file);
}
std::sort(test_sources.begin(), test_sources.end());
std::vector<std::string> active_test_sources;
for (const auto &file : test_sources) {
const fs::path relative{file};
auto part = relative.begin();
if (part != relative.end() && *part == "tests") {
auto next = std::next(part);
if (next != relative.end() && *next == "standalone") {
auto module = std::next(next);
if (module != relative.end() && !selected.contains(module->string())) {
continue;
}
}
}
if (!test_file_dependencies_selected(root / file, selected)) {
continue;
}
if (!compiler_has_reflection()) {
std::ifstream gate{root / file};
std::string content((std::istreambuf_iterator<char>{gate}),
std::istreambuf_iterator<char>{});
if (content.find("// @requires-reflection") != std::string::npos) {
continue;
}
}
active_test_sources.push_back(file);
}
std::string support_script;
support_script += "set -eu\n";
support_script += "mkdir -p \"$GEN/tests\"\n";
support_script += "cat > \"$GEN/tests/helper_paths.hpp\" <<'VBS_HELPER_EOF'\n";
support_script += "#pragma once\n";
support_script += helper_defines;
support_script += "VBS_HELPER_EOF\n";
Target support = project.custom_action("VoidGenerateTestSupport");
support.command({"/bin/sh", "-c", support_script})
.outputs({"tests/helper_paths.hpp"});
std::vector<std::string> generated_units;
std::vector<Target> generators;
for (std::size_t index = 0; index < active_test_sources.size(); ++index) {
const std::string &source = active_test_sources[index];
const fs::path source_path = root / source;
const std::string suite = source_path.stem().string();
const std::string absolute_path =
fs::weakly_canonical(source_path).generic_string();
std::string unit;
unit += "#include <Void/Testing/Detail/Registrar.hpp>\n";
unit += "#include <vector>\n";
unit += "#include <string>\n\n";
unit += "#include \"" + escape_cpp_string(absolute_path) + "\"\n\n";
unit += "namespace {\n";
for (const auto &discovered : scan_test_file(source_path)) {
const std::string qualified =
discovered.owner.empty()
? discovered.function
: discovered.owner + "::" + discovered.function;
const std::string variable =
"_auto_reg_" + (discovered.owner.empty()
? discovered.function
: discovered.owner + "_" + discovered.function);
std::string tag_list;
for (const auto &tag : discovered.tags) {
if (!tag_list.empty()) {
tag_list += ", ";
}
tag_list += "\"" + escape_cpp_string(tag) + "\"";
}
unit += "static Void::Testing::Detail::test_registrar<&" + qualified +
"> " + variable + "{\"" + escape_cpp_string(suite) + "\", \"" +
escape_cpp_string(absolute_path) + "\", " +
std::to_string(discovered.line) + ", \"" +
escape_cpp_string(discovered.function) +
"\", std::vector<std::string>{" + tag_list + "}, " +
(discovered.skipped ? "true" : "false") + ", \"" +
escape_cpp_string(discovered.skip_reason) + "\"};\n";
}
unit += "} // namespace\n";
const std::string unit_dir = "$GEN/tests/gen/" + std::to_string(index);
std::string script;
script += "set -eu\n";
script += "mkdir -p " + shell_quote(unit_dir) + "\n";
script += "cat > " + shell_quote(unit_dir + "/unit.cpp") +
" <<'VBS_UNIT_EOF'\n";
script += unit;
script += "VBS_UNIT_EOF\n";
Target generator =
project.custom_action("VoidGenerateTest_" + std::to_string(index));
generator.command({"/bin/sh", "-c", script})
.inputs({source})
.outputs({"tests/gen/" + std::to_string(index) + "/unit.cpp"});
generators.push_back(generator);
generated_units.push_back("tests/gen/" + std::to_string(index) + "/unit.cpp");
}
// Helper executables and plugin fixtures.
std::vector<Target> test_dependencies;
if (!windows) {
Target process_helper = project.executable("VoidProcessHelper");
process_helper.cxx_standard(CxxStandard::Cxx26)
.sources({"tests/helpers/ProcessHelper.cpp"});
test_dependencies.push_back(process_helper);
}
Target archive_worker = project.executable("VoidArchiveWorker");
archive_worker.cxx_standard(CxxStandard::Cxx26)
.sources({"tests/helpers/ArchiveWorker.cpp"})
.link(targets.at("Archive"));
link_runtime(archive_worker);
test_dependencies.push_back(archive_worker);
const auto add_plugin = [&](const std::string &name, const std::string &source,
const std::vector<std::string> &links,
const std::vector<std::string> &defines = {}) {
Target plugin = project.shared_library(name);
plugin.cxx_standard(CxxStandard::Cxx26)
.sources({source})
.include_directory("include", Visibility::Public)
.include_directory("tests/plugins", Visibility::Private);
for (const auto &module : links) {
plugin.link(targets.at(module), Visibility::Public);
}
for (const auto &definition : defines) {
plugin.define(definition, Visibility::Private);
}
if (gcc) {
plugin.compile_option("-freflection", Visibility::Public);
}
link_runtime(plugin);
test_dependencies.push_back(plugin);
};
add_plugin("VoidTestPlugin", "tests/plugins/TestPlugin.cpp", {"Plugin"});
add_plugin("VoidConfigurablePlugin", "tests/plugins/ConfigurablePlugin.cpp", {"Plugin"});
add_plugin("VoidStatefulPluginV1", "tests/plugins/StatefulPluginV1.cpp", {"Plugin", "Data"});
add_plugin("VoidStatefulPluginV2", "tests/plugins/StatefulPluginV2.cpp", {"Plugin", "Data"});
add_plugin("VoidServicePluginV1", "tests/plugins/ServicePluginV1.cpp",
{"Plugin", "Service", "Data"});
add_plugin("VoidServicePluginV2", "tests/plugins/ServicePluginV2.cpp",
{"Plugin", "Service", "Data"});
const auto add_cabi = [&](const std::string &name, const std::string &source,
const std::vector<std::string> &defines = {}) {
Target fixture = project.shared_library(name);
fixture.c_standard(CStandard::C11)
.sources({source})
.include_directory("include", Visibility::Public);
for (const auto &definition : defines) {
fixture.define(definition, Visibility::Private);
}
test_dependencies.push_back(fixture);
};
add_cabi("VoidCAbiPluginV1", "tests/plugins/CAbiPluginV1.c");
add_cabi("VoidCAbiPluginV2", "tests/plugins/CAbiPluginV2.c");
add_cabi("VoidCAbiBadTrunc", "tests/plugins/CAbiBadPlugin.c", {"BAD_MODE=1"});
add_cabi("VoidCAbiBadMajor", "tests/plugins/CAbiBadPlugin.c", {"BAD_MODE=2"});
add_cabi("VoidCAbiBadReserved", "tests/plugins/CAbiBadPlugin.c", {"BAD_MODE=3"});
add_cabi("VoidCAbiDepA", "tests/plugins/CAbiDepPlugin.c", {"DEP_MODE=1"});
add_cabi("VoidCAbiDepB", "tests/plugins/CAbiDepPlugin.c", {"DEP_MODE=2"});
add_cabi("VoidCAbiCycA", "tests/plugins/CAbiDepPlugin.c", {"DEP_MODE=3"});
add_cabi("VoidCAbiCycB", "tests/plugins/CAbiDepPlugin.c", {"DEP_MODE=4"});
Target tests = project.test("VoidTests");
tests.cxx_standard(CxxStandard::Cxx26)
.include_directory("include", Visibility::Public)
.include_directory("tests/plugins", Visibility::Private)
.include_directory("$GEN/tests", Visibility::Private)
.compile_option("-includehelper_paths.hpp", Visibility::Private);
if (gcc) {
tests.compile_option("-freflection", Visibility::Public);
}
for (const auto &unit : generated_units) {
tests.sources(SourceSet::file("$GEN/" + unit));
}
for (const auto &[name, target] : targets) {
if (name != "Testing") {
tests.link(target, Visibility::Private);
}
}
tests.link(targets.at("Testing"), Visibility::Private);
link_runtime(tests);
tests.depends_on(support);
for (const auto &generator : generators) {
tests.depends_on(generator);
}
for (const auto &dependency : test_dependencies) {
tests.depends_on(dependency);
}
}