From ce041ace07ce0f39efa56168a0da858f558b551e Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 13:55:02 +0300 Subject: [PATCH] feat(deps): resolve pkg-config modules --- CMakeLists.txt | 1 + docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/agent-workflow/VERIFICATION.md | 11 + docs/roadmap/22-superiority-and-gaps.md | 20 +- include/Void/Build.hpp | 5 +- include/Void/Build/Provider/PkgConfig.hpp | 24 ++ sdk/Build.cpp | 17 + src/Graph/Graph.cpp | 3 + src/Main.cpp | 19 + src/Package/Resolver.cpp | 13 + src/Provider/PkgConfig.cpp | 430 ++++++++++++++++++++++ tests/FullV1Tests.cpp | 129 +++++++ 13 files changed, 663 insertions(+), 12 deletions(-) create mode 100644 include/Void/Build/Provider/PkgConfig.hpp create mode 100644 src/Provider/PkgConfig.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6dd8585..251370e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,6 +60,7 @@ add_library(VoidBuild_Core STATIC src/Package/Fetch.cpp src/Package/RegistryClient.cpp src/Package/Resolver.cpp + src/Provider/PkgConfig.cpp src/Provider/Provider.cpp src/Provider/Translator.cpp src/Install/Installer.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index bef0d0d..40977fe 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -371,6 +371,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Wave 139 (Installable VSIX for the VS Code Plugin)**: `vbs ide plugin --editor vscode --vsix FILE` now packages the generated extension as a real `.vsix` (ZIP with `extension.vsixmanifest`, `[Content_Types].xml` and the sources under `extension/`), which `code --install-extension` accepts. The stored-ZIP writer moved from the installer into `Package::create_stored_zip` so both share it. The packaged extension's own test passes when extracted, and the C++ test parses the ZIP central directory and verifies every CRC. +- **Wave 140 (pkg-config Discovery)**: `p.dependency("zlib").pkgconfig("zlib >= 1.2")` resolves system libraries from `.pc` files (parsed directly - no `pkg-config` executable needed), honoring `PKG_CONFIG_PATH`/`PKG_CONFIG_LIBDIR` plus conventional prefixes. Variables (`${prefix}`, `${pcfiledir}`, nested) expand, `Requires` chains merge flags, and RPM-style version comparison enforces constraints at the root and in the chain. Cflags become include dirs/defines/compile options and Libs become link options or library paths. The dependency is recorded in `vbs.lock` as `pkgconfig` and never fetched. `FullV1Tests.pkgconfig_dependency_resolves_flags_requires_and_versions` builds and runs a real app against a generated `.pc` + archive, and asserts both version-mismatch errors. + ## Remaining future scope - **Superiority plan ([22-superiority-and-gaps.md](../roadmap/22-superiority-and-gaps.md), 2026-12-05)**: revised platform strategy - **macOS deferred**, **Windows via MinGW-w64 cross-compilation + Wine execution** (`dev cpp-gcc -p pkgsCross.mingwW64.stdenv.cc`, `dev cpp-gcc -p wine64`), native MSVC deferred; plus packaging parity (ZIP/DEB/RPM), IDE ecosystem, migration tooling, test-runner parity, benchmarks, CI runners, and remote execution in prioritized order. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index ea0f39d..d0358c0 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -140,4 +140,5 @@ Base HEAD: `fe0d1a6` | Wave 137 (UDIF/DMG-style packaging) | `--archive-format dmg`: tar payload + koly trailer with CRC-32 | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; trailer parsed and CRC matches zlib, install test passes, full CTest 8/8) | `src/Install/Installer.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 138 (Full CMake File API) | `cmakeFiles-v1`, `toolchains-v1`, `cache-v2` replies | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; IDE E2E passes, full CTest 8/8) | `src/Editor/CompDb.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 139 (VSIX packaging) | `vbs ide plugin --vsix FILE`; shared `Package::create_stored_zip` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Python zipfile validates the VSIX, packaged harness passes under Node, C++ test checks CRCs, full CTest 8/8) | `src/Editor/CompDb.cpp`, `src/Package/Archive.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | +| Wave 140 (pkg-config discovery) | `.pkgconfig(spec)` dependency, `.pc` parser with variables/Requires/version compare, lock entries | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E builds/runs and checks version errors, full CTest 8/8) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `src/Provider/PkgConfig.cpp`, `src/Graph/Graph.cpp`, `src/Package/Resolver.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | | Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions) |"}] Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index b001b85..09523a3 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1825,6 +1825,17 @@ VOID_INCLUDE_DIR=/tmp/opencode/vl-pin/include dev cpp -c bash fuzz/run.sh 30 recomputes each entry's CRC-32 and asserts the layout (**passed**, 34 ms). - Full CTest: **8 / 8 passed** in 305.48 s. +## pkg-config Discovery (GCC 16.2, pin `0002e74`) + +- `p.dependency("mylib").pkgconfig("mylib >= 1.0")`: `.pc` files are located in + `PKG_CONFIG_PATH` then `PKG_CONFIG_LIBDIR` (or conventional prefixes), parsed with variable + expansion, `Requires` recursion and RPM-style version comparison. +- `FullV1Tests.pkgconfig_dependency_resolves_flags_requires_and_versions` **passed** (5.60 s): + a generated `mylib.pc` (with `Requires: child >= 0.5`) and a real `libmylib.a` let an app + including headers from both modules build and run (`app` exit 0); `mylib >= 2.0` fails with + "is required, but version 1.2.3 is installed" and `child >= 0.8` fails through the chain. +- Full CTest: **8 / 8 passed** in 311.96 s. + ## Limits and Unrun Checks 1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). diff --git a/docs/roadmap/22-superiority-and-gaps.md b/docs/roadmap/22-superiority-and-gaps.md index 8064883..4f00dfa 100644 --- a/docs/roadmap/22-superiority-and-gaps.md +++ b/docs/roadmap/22-superiority-and-gaps.md @@ -49,7 +49,7 @@ Concrete work this implies: | Capability | CMake | Meson | build2 *(unverified)* | VBS now | Planned work | | --- | --- | --- | --- | --- | --- | | Platforms | Windows, macOS, Linux, BSD, cross | same | same | Linux | Wine-first Windows (§2); macOS deferred | -| Languages | C, C++, CUDA, Fortran, ObjC, ASM, HIP… | C, C++, Rust, D, Fortran, Java… | C/C++ focused | C, C++ | ASM/CUDA/ObjC or a documented extension API | +| Languages | C, C++, CUDA, Fortran, ObjC, ASM, HIP… | C, C++, Rust, D, Fortran, Java… | C/C++ focused | C, C++ | ASM and shader languages (GLSL/HLSL/Slang) | | Toolchains | MSVC, clang-cl, GCC, Clang, Apple, many | GCC, Clang, MSVC, many | GCC, Clang, MSVC | GCC, Clang (Linux) | MinGW target; MSVC deferred | | Package/registry | External (vcpkg, Conan, FetchContent) | wrapdb, subprojects | cppget.org / brep | **Built-in registry + solver + lock + binary variants + signatures + SBOM** | federation, mirrors, key distribution | | Install/package | `install()`, `install(EXPORT)`, CPack (TGZ/ZIP/DEB/RPM/WIX/DMG/NuGet/APK…) | `install_data`, `install_headers`, dist scripts | install module | prefix staging, components, relocatable CMake + native exports, tar, self-extracting `sh`, **stored ZIP**, **DEB (dpkg-validated)**, SBOM, **Ed25519-signed archives with checksums** | **RPM (rpm 6.1-validated)**, **WiX source for MSI** (candle/light on Windows), **UDIF/DMG container** (koly trailer, CRC-32; HFS+ payload is macOS-only) | @@ -84,6 +84,7 @@ Concrete work this implies: 7. Benchmarks against CMake/Meson/build2 on documented fixtures (including 10k-target scaling). 8. CI on real runners, sanitizer jobs (**sanitizer build run done**), parser fuzzing (**deterministic mutation harness and a Clang/libFuzzer target done**). 9. Remote execution workers (**registry worker/lease/result protocol, queue, remote action execution and parallel workers done**; cross-machine orchestration remains). +10. pkg-config discovery (the top adoption blocker, §8.1) and ASM/shader language support. ## 6. Observed baseline (2026-12-05, x86_64, GCC 16.2, Debug, `benchmarks/compare.sh 20`) @@ -109,21 +110,18 @@ first, then what makes VBS *better* rather than merely equal. ### 8.1 Adoption blockers -1. **pkg-config discovery.** CMake (`FindPkgConfig`/`find_package`) and Meson +1. **pkg-config discovery - done (Wave 140).** `Dependency::pkgconfig(spec)` resolves `.pc` modules into imported targets. Originally: CMake (`FindPkgConfig`/`find_package`) and Meson (`dependency()`, auto method order `pkg-config` → `cmake` → framework) both find system-installed libraries. VBS has registry/git/path/CMake/Meson/Conan providers but no pkg-config lookup, so most existing Linux projects cannot be built as-is. Add `.pkgconfig("libfoo >= 1.2")` plus a `.pc` search path in profiles, resolved into an imported target. -2. **Language breadth.** CMake supports C, C++, CUDA, Fortran, ObjC, ASM, HIP; Meson C, C++, - Rust, D, Fortran, Java. VBS is C/C++ only. Assembly is the cheapest high-value addition - (`.s`, `.S` with the C preprocessor), then CUDA. -3. **Platform breadth.** Native MSVC and Apple Clang/macOS remain deferred by decision; MinGW - cross + Wine is the current Windows story. This stays the biggest "can I use it at work?" - blocker outside Linux. -4. **Credibility evidence.** CI workflows have never run on a real runner, and there is no - 10k-target scaling benchmark yet (CMake/Meson handle very large projects daily). -5. **Package-generator parity.** CPack also ships NuGet, PKG/productbuild, APK and IFW +2. **Language breadth: ASM and shader languages.** VBS is C/C++ only. Add assembly (`.s`, + `.S` with the C preprocessor) and the shader languages used by Void projects (GLSL, HLSL, + Slang) through pluggable shader-compiler toolchains with capability probes. +3. **Platform breadth - deferred.** Native MSVC and Apple Clang/macOS stay deferred by + decision; MinGW cross + Wine is the current Windows story. +4. **Package-generator parity.** CPack also ships NuGet, PKG/productbuild, APK and IFW installers; VBS has tar, `sh`, ZIP, DEB, RPM, WiX and UDIF. NuGet and PKG are the next useful ones. diff --git a/include/Void/Build.hpp b/include/Void/Build.hpp index 6768fc6..a84b75d 100644 --- a/include/Void/Build.hpp +++ b/include/Void/Build.hpp @@ -31,7 +31,7 @@ enum class TargetKind { }; enum class SourceKind { File, Glob, ModuleInterface, ModulePartition, HeaderUnit }; enum class LinkKind { Local, Imported }; -enum class DependencySourceKind { Unspecified, Git, Package, Path, Archive, Conan }; +enum class DependencySourceKind { Unspecified, Git, Package, Path, Archive, Conan, PkgConfig }; enum class CStandard { Default, C11, C17, C23 }; enum class CxxStandard { Default, Cxx17, Cxx20, Cxx23, Cxx26 }; enum class LtoMode { None, Full, Thin }; @@ -314,6 +314,9 @@ class Dependency { Dependency &cmake(OptionMap options = {}); Dependency &meson(OptionMap options = {}); Dependency &conan(std::string reference, OptionMap options = {}); + // A system library discovered through a pkg-config module spec (e.g. "zlib >= 1.2"). + // Search paths come from PKG_CONFIG_PATH / PKG_CONFIG_LIBDIR plus conventional prefixes. + Dependency &pkgconfig(std::string spec); Dependency &native_builder(OptionMap options = {}); Dependency &package(std::string id, std::string range); Dependency ®istry(std::string authority_url); diff --git a/include/Void/Build/Provider/PkgConfig.hpp b/include/Void/Build/Provider/PkgConfig.hpp new file mode 100644 index 0000000..dd978fe --- /dev/null +++ b/include/Void/Build/Provider/PkgConfig.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Void::Build::Provider { + +// Resolves a pkg-config module spec such as "zlib >= 1.2" into an imported target +// interface. `.pc` files are parsed directly (no pkg-config executable needed); search +// paths come from `search_paths` (typically PKG_CONFIG_PATH / PKG_CONFIG_LIBDIR plus +// conventional prefixes). The exported target is keyed by the module name. +[[nodiscard]] Void::Result::Result +resolve_pkgconfig(std::string_view dependency_name, std::string_view spec, + const std::vector &search_paths); + +// Search paths from the environment: PKG_CONFIG_PATH, or PKG_CONFIG_LIBDIR (which +// replaces the defaults) plus conventional system prefixes. +[[nodiscard]] std::vector pkgconfig_search_paths(); + +} // namespace Void::Build::Provider diff --git a/sdk/Build.cpp b/sdk/Build.cpp index 07e8d06..08c9a1b 100644 --- a/sdk/Build.cpp +++ b/sdk/Build.cpp @@ -953,6 +953,20 @@ Dependency &Dependency::archive(std::string url, std::string sha256) { return *this; } +Dependency &Dependency::pkgconfig(std::string spec) { + require_text(spec, "pkg-config module spec"); + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind != DependencySourceKind::Unspecified || !record.builder.empty()) { + throw std::invalid_argument{"dependency '" + record.name + + "' already has a source/provider"}; + } + record.source_kind = DependencySourceKind::PkgConfig; + record.builder = "pkgconfig"; + record.location = std::move(spec); + return *this; +} + Dependency &Dependency::cmake(OptionMap options) { for (const auto &[key, value] : options) { (void)value; @@ -1293,6 +1307,9 @@ std::string Project::to_json() const { case DependencySourceKind::Conan: result += "\"conan\",\"package\":" + json_quote(dependency.package); break; + case DependencySourceKind::PkgConfig: + result += "\"pkgconfig\",\"location\":" + json_quote(dependency.location); + break; case DependencySourceKind::Unspecified: break; } diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp index 5f580df..e037b29 100644 --- a/src/Graph/Graph.cpp +++ b/src/Graph/Graph.cpp @@ -384,6 +384,9 @@ ProjectDescription::from_json(std::string_view json_text) { } else if (kind == "conan") { d.source_kind = DependencySourceKind::Conan; d.package = get_str(*so, "package"); + } else if (kind == "pkgconfig") { + d.source_kind = DependencySourceKind::PkgConfig; + d.location = get_str(*so, "location"); } } } diff --git a/src/Main.cpp b/src/Main.cpp index 6d46479..e1be85f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -680,6 +681,24 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } } + // pkg-config dependencies are resolved from the host environment (PKG_CONFIG_PATH / + // PKG_CONFIG_LIBDIR) instead of being fetched. + for (const auto &dep : *merged_deps) { + if (dep.record.source_kind != DependencySourceKind::PkgConfig) { + continue; + } + auto exported = Provider::resolve_pkgconfig(dep.record.name, dep.record.location, + Provider::pkgconfig_search_paths()); + if (!exported) { + std::cerr << "vbs: " << exported.error().message() << '\n'; + return 1; + } + Void::Log::info("Provider", "[{}] Resolved pkg-config '{}' ({} target(s))", + prof_name, dep.record.location, exported->targets.size()); + for (auto &[k, v] : exported->targets) { + imported_targets[k] = std::move(v); + } + } if (need_lock_publish) { const std::string base_rev = pinned_lock->has_value() ? (*pinned_lock)->revision_hash : std::string{}; diff --git a/src/Package/Resolver.cpp b/src/Package/Resolver.cpp index 0329528..2426db9 100644 --- a/src/Package/Resolver.cpp +++ b/src/Package/Resolver.cpp @@ -160,6 +160,16 @@ resolve_and_materialize_dependencies(const ProfileContext &ctx, const auto pkg_cache_root = options.build_root / ".vbs" / "cache" / "packages"; std::error_code ec; for (const auto &nd : merged_deps) { + if (nd.record.source_kind == DependencySourceKind::PkgConfig) { + // Resolved from the environment by the pkg-config provider; nothing to fetch. + LockedSourceEntry le; + le.alias = nd.record.name; + le.source_kind = "pkgconfig"; + le.location = nd.record.location; + le.builder = nd.record.builder; + out.lock_context.entries.push_back(std::move(le)); + continue; + } if (nd.record.source_kind == DependencySourceKind::Package) { const auto &pid = alias_to_pkg_id.at(nd.record.name); const auto &sp = solved_packages.at(pid); @@ -266,6 +276,9 @@ resolve_and_materialize_dependencies(const ProfileContext &ctx, case DependencySourceKind::Conan: le.source_kind = "conan"; break; + case DependencySourceKind::PkgConfig: + le.source_kind = "pkgconfig"; + break; case DependencySourceKind::Package: le.source_kind = "package"; break; diff --git a/src/Provider/PkgConfig.cpp b/src/Provider/PkgConfig.cpp new file mode 100644 index 0000000..5cff041 --- /dev/null +++ b/src/Provider/PkgConfig.cpp @@ -0,0 +1,430 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Provider { +namespace { + +Void::Result::Error make_error(std::string msg) { + return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, + std::move(msg)); +} + +bool is_space(char c) { return std::isspace(static_cast(c)) != 0; } + +std::string trim(std::string_view text) { return std::string{Void::Str::trim_ascii(text)}; } + +std::vector split_ws(std::string_view text) { + std::vector out; + std::size_t i = 0; + while (i < text.size()) { + while (i < text.size() && is_space(text[i])) { + ++i; + } + const std::size_t start = i; + while (i < text.size() && !is_space(text[i])) { + ++i; + } + if (i > start) { + out.emplace_back(text.substr(start, i - start)); + } + } + return out; +} + +std::vector split_colon_list(std::string_view text) { + std::vector out; + std::size_t start = 0; + while (start <= text.size()) { + const auto end = text.find(':', start); + const auto piece = text.substr(start, end == std::string_view::npos ? std::string_view::npos + : end - start); + if (!piece.empty()) { + out.emplace_back(piece); + } + if (end == std::string_view::npos) { + break; + } + start = end + 1; + } + return out; +} + +struct PcFile { + std::filesystem::path path; + std::map> variables; + std::map> fields; +}; + +std::optional load_pc(const std::filesystem::path &path) { + auto text = Void::FileSystem::read_file(path); + if (!text) { + return std::nullopt; + } + PcFile pc; + pc.path = path; + const std::string_view text_view{*text}; + std::size_t start = 0; + while (start < text_view.size()) { + auto end = text_view.find('\n', start); + if (end == std::string_view::npos) { + end = text_view.size(); + } + const std::string line = trim(text_view.substr(start, end - start)); + start = end + 1; + if (line.empty() || line.starts_with('#')) { + continue; + } + const auto eq = line.find('='); + const auto colon = line.find(':'); + if (eq != std::string::npos && (colon == std::string::npos || eq < colon)) { + pc.variables[trim(std::string_view{line}.substr(0, eq))] = + trim(std::string_view{line}.substr(eq + 1)); + } else if (colon != std::string::npos) { + pc.fields[trim(std::string_view{line}.substr(0, colon))] = + trim(std::string_view{line}.substr(colon + 1)); + } + } + return pc; +} + +// Expands ${var} references using the file's variables (plus the builtin pcfiledir). +std::string expand(const PcFile &pc, std::string_view value, int depth = 0) { + if (depth > 16) { + return std::string{value}; + } + std::string out; + std::size_t i = 0; + while (i < value.size()) { + const auto dollar = value.find("${", i); + if (dollar == std::string_view::npos) { + out += value.substr(i); + break; + } + out += value.substr(i, dollar - i); + const auto close = value.find('}', dollar + 2); + if (close == std::string_view::npos) { + out += value.substr(dollar); + break; + } + const std::string name{value.substr(dollar + 2, close - dollar - 2)}; + if (name == "pcfiledir") { + out += pc.path.parent_path().string(); + } else if (const auto it = pc.variables.find(name); it != pc.variables.end()) { + out += expand(pc, it->second, depth + 1); + } + i = close + 1; + } + return out; +} + +std::string field(const PcFile &pc, std::string_view name) { + const auto it = pc.fields.find(std::string{name}); + return it == pc.fields.end() ? std::string{} : expand(pc, it->second); +} + +struct ModuleReq { + std::string name; + std::string op; + std::string version; +}; + +std::vector parse_module_list(std::string_view text) { + std::vector out; + for (const auto &part : [&] { + std::vector pieces; + std::size_t start = 0; + while (start <= text.size()) { + const auto comma = text.find(',', start); + pieces.emplace_back(text.substr(start, comma == std::string_view::npos + ? std::string_view::npos + : comma - start)); + if (comma == std::string_view::npos) { + break; + } + start = comma + 1; + } + return pieces; + }()) { + const auto tokens = split_ws(part); + if (tokens.empty()) { + continue; + } + ModuleReq req; + req.name = tokens[0]; + if (tokens.size() >= 2) { + req.op = tokens[1]; + if (req.op == "==") { + req.op = "="; + } + if (tokens.size() >= 3) { + req.version = tokens[2]; + } + } + out.push_back(std::move(req)); + } + return out; +} + +int compare_versions(std::string_view a, std::string_view b) { + // rpmvercmp-style comparison: alternating numeric and alphabetic segments. + std::size_t i = 0; + std::size_t j = 0; + const auto is_alnum = [](char c) { return std::isalnum(static_cast(c)) != 0; }; + while (i < a.size() || j < b.size()) { + while (i < a.size() && !is_alnum(a[i])) { + ++i; + } + while (j < b.size() && !is_alnum(b[j])) { + ++j; + } + if (i >= a.size() || j >= b.size()) { + break; + } + const bool a_digit = std::isdigit(static_cast(a[i])) != 0; + const bool b_digit = std::isdigit(static_cast(b[j])) != 0; + std::size_t a_end = i; + std::size_t b_end = j; + if (a_digit) { + while (a_end < a.size() && std::isdigit(static_cast(a[a_end]))) { + ++a_end; + } + } else { + while (a_end < a.size() && std::isalpha(static_cast(a[a_end]))) { + ++a_end; + } + } + if (b_digit) { + while (b_end < b.size() && std::isdigit(static_cast(b[b_end]))) { + ++b_end; + } + } else { + while (b_end < b.size() && std::isalpha(static_cast(b[b_end]))) { + ++b_end; + } + } + if (a_digit != b_digit) { + return a_digit ? 1 : -1; // Numeric segments sort newer than alphabetic ones. + } + auto a_seg = a.substr(i, a_end - i); + auto b_seg = b.substr(j, b_end - j); + if (a_digit) { + while (a_seg.size() > 1 && a_seg.front() == '0') { + a_seg.remove_prefix(1); + } + while (b_seg.size() > 1 && b_seg.front() == '0') { + b_seg.remove_prefix(1); + } + if (a_seg.size() != b_seg.size()) { + return a_seg.size() < b_seg.size() ? -1 : 1; + } + } + if (const int cmp = a_seg.compare(b_seg); cmp != 0) { + return cmp < 0 ? -1 : 1; + } + i = a_end; + j = b_end; + } + if (i < a.size()) { + return 1; + } + if (j < b.size()) { + return -1; + } + return 0; +} + +bool satisfies(std::string_view version, const ModuleReq &req) { + if (req.op.empty() || req.version.empty()) { + return true; + } + const int cmp = compare_versions(version, req.version); + if (req.op == ">=") { + return cmp >= 0; + } + if (req.op == "<=") { + return cmp <= 0; + } + if (req.op == ">") { + return cmp > 0; + } + if (req.op == "<") { + return cmp < 0; + } + if (req.op == "=") { + return cmp == 0; + } + if (req.op == "!=") { + return cmp != 0; + } + return false; +} + +std::optional +find_pc(std::string_view module, const std::vector &search_paths) { + for (const auto &dir : search_paths) { + std::error_code ec; + const auto candidate = dir / (std::string{module} + ".pc"); + if (std::filesystem::is_regular_file(candidate, ec)) { + return candidate; + } + } + return std::nullopt; +} + +struct ResolvedModule { + std::string name; + std::string version; + std::vector cflags; + std::vector libs; +}; + +Void::Result::Result +resolve_module(const ModuleReq &req, const std::vector &search_paths, + std::map> &resolved, + std::set &visiting) { + if (const auto it = resolved.find(req.name); it != resolved.end()) { + if (!satisfies(it->second.version, req)) { + return std::unexpected{make_error( + std::format("pkg-config module '{}' {} {} is required, but version {} was found", + req.name, req.op, req.version, it->second.version))}; + } + return {}; + } + if (!visiting.insert(req.name).second) { + return {}; // Dependency cycle: already being resolved. + } + const auto path = find_pc(req.name, search_paths); + if (!path) { + return std::unexpected{ + make_error(std::format("pkg-config module '{}' was not found in {}", req.name, [&] { + std::string dirs; + for (const auto &dir : search_paths) { + dirs += (dirs.empty() ? "" : ":") + dir.string(); + } + return dirs.empty() ? std::string{"(no search paths)"} : dirs; + }()))}; + } + const auto pc = load_pc(*path); + if (!pc) { + return std::unexpected{ + make_error(std::format("cannot read pkg-config file '{}'", path->string()))}; + } + ResolvedModule module; + module.name = req.name; + module.version = field(*pc, "Version"); + if (!satisfies(module.version, req)) { + return std::unexpected{make_error( + std::format("pkg-config module '{}' {} {} is required, but version {} is installed", + req.name, req.op, req.version, module.version))}; + } + // Required modules first (their flags come before this module's own). + for (const auto &child : parse_module_list(field(*pc, "Requires"))) { + if (auto ok = resolve_module(child, search_paths, resolved, visiting); !ok) { + return ok; + } + const auto &child_module = resolved.at(child.name); + module.cflags.insert(module.cflags.end(), child_module.cflags.begin(), + child_module.cflags.end()); + module.libs.insert(module.libs.end(), child_module.libs.begin(), child_module.libs.end()); + } + const auto cflags = split_ws(field(*pc, "Cflags")); + module.cflags.insert(module.cflags.end(), cflags.begin(), cflags.end()); + const auto libs = split_ws(field(*pc, "Libs")); + module.libs.insert(module.libs.end(), libs.begin(), libs.end()); + visiting.erase(req.name); + resolved[req.name] = std::move(module); + return {}; +} + +} // namespace + +std::vector pkgconfig_search_paths() { + std::vector paths; + const std::string libdir = Void::Configuration::get_env_or("PKG_CONFIG_LIBDIR", ""); + const std::string path_env = Void::Configuration::get_env_or("PKG_CONFIG_PATH", ""); + for (const auto &entry : split_colon_list(path_env)) { + paths.emplace_back(entry); + } + if (!libdir.empty()) { + for (const auto &entry : split_colon_list(libdir)) { + paths.emplace_back(entry); + } + return paths; + } + for (const char *fallback : + {"/usr/local/lib/pkgconfig", "/usr/local/share/pkgconfig", "/usr/lib/pkgconfig", + "/usr/lib/x86_64-linux-gnu/pkgconfig", "/usr/lib64/pkgconfig", "/usr/share/pkgconfig"}) { + paths.emplace_back(fallback); + } + return paths; +} + +Void::Result::Result +resolve_pkgconfig(std::string_view dependency_name, std::string_view spec, + const std::vector &search_paths) { + const auto requirements = parse_module_list(spec); + if (requirements.empty()) { + return std::unexpected{make_error("empty pkg-config module spec")}; + } + std::map> resolved; + std::set visiting; + for (const auto &req : requirements) { + if (auto ok = resolve_module(req, search_paths, resolved, visiting); !ok) { + return std::unexpected{ok.error()}; + } + } + + Graph::ImportedTargetInterface iface; + iface.dependency_name = std::string{dependency_name}; + iface.target_name = requirements.front().name; + for (const auto &[name, module] : resolved) { + (void)name; + for (const auto &flag : module.cflags) { + if (flag.starts_with("-I") && flag.size() > 2) { + iface.include_dirs.emplace_back(flag.substr(2), true); + } else if (flag.starts_with("-isystem") && flag.size() > 8) { + iface.include_dirs.emplace_back(flag.substr(8), true); + } else if (flag.starts_with("-D") && flag.size() > 2) { + iface.defines.push_back(flag.substr(2)); + } else { + iface.compile_options.push_back(flag); + } + } + for (const auto &flag : module.libs) { + if (flag.starts_with("-l") || flag.starts_with("-L") || flag.starts_with("-Wl,") || + flag == "-pthread" || flag == "-ldl") { + iface.link_options.push_back(flag); + if (flag == "-pthread") { + iface.compile_options.push_back(flag); + } + } else if (flag.ends_with(".a")) { + iface.static_libraries.emplace_back(flag); + } else if (flag.ends_with(".so") || flag.contains(".so.") || flag.ends_with(".dylib")) { + iface.shared_libraries.emplace_back(flag); + } else { + iface.link_options.push_back(flag); + } + } + } + + ProviderExport exported; + exported.dependency_name = std::string{dependency_name}; + exported.builder = "pkgconfig"; + exported.targets[iface.target_name] = iface; + exported.targets[std::string{dependency_name} + "::" + iface.target_name] = iface; + return exported; +} + +} // namespace Void::Build::Provider diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index 06f923f..07cb3c2 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -2433,6 +2433,135 @@ void build(Void::Build::Project &p) { } } +// === pkg-config dependency discovery === +VOID_TEST(FullV1Tests, pkgconfig_dependency_resolves_flags_requires_and_versions) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_pkgcfg_"}; + const auto prefix = tmp / "prefix"; + const auto proj = tmp / "proj"; + const auto bdir = tmp / "build"; + const auto pc_dir = prefix / "lib" / "pkgconfig"; + std::filesystem::create_directories(pc_dir); + std::filesystem::create_directories(prefix / "include"); + std::filesystem::create_directories(prefix / "childinclude"); + std::filesystem::create_directories(proj / "src"); + + write_file(prefix / "include" / "mylib.hpp", + "#pragma once\nint mylib_answer_impl();\n" + "inline int mylib_answer() { return mylib_answer_impl(); }\n"); + write_file(prefix / "childinclude" / "child_flag.hpp", + "#pragma once\n#define CHILD_FLAG_PRESENT 1\n"); + write_file(tmp / "lib.cpp", "int mylib_answer_impl() { return 42; }\n"); + write_file(pc_dir / "child.pc", "Name: child\nDescription: child module\nVersion: 0.7.1\n" + "Cflags: -I" + + (prefix / "childinclude").string() + "\n"); + write_file(pc_dir / "mylib.pc", "prefix=" + prefix.string() + + "\nincludedir=${prefix}/include\nlibdir=${prefix}/lib\n\n" + "Name: mylib\nDescription: test library\nVersion: 1.2.3\n" + "Requires: child >= 0.5\n" + "Cflags: -I${includedir} -DMYLIB_ENABLED=1\n" + "Libs: -L${libdir} -lmylib\n"); + + // Build the library the .pc file advertises (needs a real compiler and archiver). + const auto run_tool = [&](const std::string &exe, std::vector args) { + Platform::ProcessRequest req; + req.executable = exe; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{120}; + return Platform::run_supervised(req); + }; + const auto object = tmp / "lib.o"; + auto compiled_lib = run_tool("g++", {"-c", (tmp / "lib.cpp").string(), "-o", object.string()}); + if (!compiled_lib || !compiled_lib->succeeded()) { + return; // No host compiler in PATH: nothing to link against. + } + auto archived = + run_tool("ar", {"rcs", (prefix / "lib" / "libmylib.a").string(), object.string()}); + if (!archived || !archived->succeeded()) { + return; + } + + write_file(proj / "build.cpp", + "#include \n" + "void build(Void::Build::Project &p) {\n" + " auto dep = p.dependency(\"mylib\").pkgconfig(\"mylib >= 1.0\");\n" + " p.executable(\"app\")\n" + " .cxx_standard(Void::Build::CxxStandard::Cxx26)\n" + " .sources({\"src/main.cpp\"})\n" + " .link(dep.target(\"mylib\"));\n" + "}\n"); + write_file(proj / "src" / "main.cpp", "#include \n" + "#include \n" + "#ifndef MYLIB_ENABLED\n" + "#error MYLIB_ENABLED missing\n" + "#endif\n" + "#ifndef CHILD_FLAG_PRESENT\n" + "#error Requires chain not merged\n" + "#endif\n" + "int main() { return mylib_answer() == 42 ? 0 : 1; }\n"); + + const auto run_vbs = [&]() { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = {"build", "--project", proj.string(), "--build-dir", bdir.string()}; + req.environment.set_vars["PKG_CONFIG_PATH"] = pc_dir.string(); + req.timeout = std::chrono::seconds{300}; + return Platform::run_supervised(req); + }; + + auto built = run_vbs(); + Void::Testing::expect(built.has_value() && built->succeeded()); + if (built) { + Void::Testing::expect(built->stderr_data.find("Resolved pkg-config 'mylib >= 1.0'") != + std::string::npos); + } + const auto app = bdir / "profiles" / "debug" / "out" / "bin" / "app"; + if (std::filesystem::exists(app)) { + auto ran = run_tool(app.string(), {}); + Void::Testing::expect(ran.has_value() && ran->succeeded()); + } + + // A version the root module cannot satisfy is a clear configuration error. + write_file(proj / "build.cpp", + "#include \n" + "void build(Void::Build::Project &p) {\n" + " auto dep = p.dependency(\"mylib\").pkgconfig(\"mylib >= 2.0\");\n" + " (void)dep;\n" + "}\n"); + auto too_new = run_vbs(); + Void::Testing::expect(too_new.has_value() && !too_new->succeeded()); + if (too_new) { + Void::Testing::expect( + too_new->stderr_data.find("is required, but version 1.2.3 is installed") != + std::string::npos); + } + + // A version the Requires chain cannot satisfy is reported too. + write_file(proj / "build.cpp", + "#include \n" + "void build(Void::Build::Project &p) {\n" + " auto dep = p.dependency(\"mylib\").pkgconfig(\"mylib >= 1.0\");\n" + " (void)dep;\n" + "}\n"); + write_file(pc_dir / "mylib.pc", "prefix=" + prefix.string() + + "\nincludedir=${prefix}/include\nlibdir=${prefix}/lib\n\n" + "Name: mylib\nDescription: test library\nVersion: 1.2.3\n" + "Requires: child >= 0.8\n" + "Cflags: -I${includedir}\n" + "Libs: -L${libdir} -lmylib\n"); + auto child_too_new = run_vbs(); + Void::Testing::expect(child_too_new.has_value() && !child_too_new->succeeded()); + if (child_too_new) { + Void::Testing::expect( + child_too_new->stderr_data.find("pkg-config module 'child' >= 0.8 is required") != + std::string::npos); + } +} + // === Track A1: Native VBS subproject dependency (builder == "native", zero CMake!) === VOID_TEST(FullV1Tests, native_vbs_subproject_dependency_builds_without_cmake) { const auto vbs_bin = locate_vbs_binary();