diff --git a/README.md b/README.md index dc4b14f..b096f3b 100644 --- a/README.md +++ b/README.md @@ -6,16 +6,16 @@ profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and `build-support/**/*.cpp`/`.hpp` files; declarative package manifests also support `vbs.deps.toml` normalized to the exact same dependency model. -**Implemented scope (Plans 01–19, Plan 20 Slices 1 & 2A, Track A Self-Hosting):** -- **Declaration SDK (`Void::Build`, ``)**: `VoidBuild_Sdk` / `Void::BuildSdk` with version-1 deterministic UTF-8 JSON schema, profile inheritance and cycle detection, all seven `TargetKind`s, scoped options/defines/links, modern C++ flags, install rules, and symbolic TOML manifest references. -- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), deterministic path prefix mapping + `-frandom-seed`, transactional CAS store (`StateStore`), bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup), and live `Void::Log` progress logging (`--verbose`/`-v`, `--quiet`/`-q`). +**Implemented scope (Plans 01–19, Plan 20 Slices 1–2C / Track B, Track A Self-Hosting, & `vbs ide` Tooling):** +- **Declaration SDK (`Void::Build`, ``)**: `VoidBuild_Sdk` / `Void::BuildSdk` with version-1 deterministic UTF-8 JSON schema, profile inheritance and cycle detection, all seven `TargetKind`s, scoped options/defines/links, C (`c_standard(CStandard)`) and modern C++ (`cxx_standard(CxxStandard)`) controls, install rules, and symbolic TOML manifest references. +- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 C (`gcc`/`clang`) and C++ (`g++`/`clang++`) toolchain discovery/capability probing (including default system include dirs for `clang-scan-deps`), content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), deterministic path prefix mapping + `-frandom-seed`, transactional CAS store (`StateStore`), bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup), and live `Void::Log` progress logging (`--verbose`/`-v`, `--quiet`/`-q`). - **Zero-CMake Self-Building & Self-Testing `build.cpp` (Track A)**: Root [build.cpp](build.cpp) builds `VoidLibrary` via `.native_builder(...)` (first-class `builder == "native"` in [Provider.cpp](src/Provider/Provider.cpp), zero CMake invocation) and declares all 13 targets (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`, `vbs_self_smoke`, `vbs_benchmarks`, and all 5 `Void::Testing` `VOID_TEST` suites `vbs_sdk_tests`, `vbs_core_tests`, `vbs_v1_tests`, `vbs_registry_tests`, `vbs_selfhost_tests`). Stage 2 and Stage 3 `vbs` builds match bit-for-bit by SHA-256 across distinct build directories with `cmake` trapped on `PATH`. -- **Plan 20 Slices 1 & 2A — Bounded Native CMake & Meson Graph Translation**: [Translator.hpp](include/Void/Build/Provider/Translator.hpp) / [Translator.cpp](src/Provider/Translator.cpp) audits configured CMake File API `codemodel-v2` and Meson `meson-info/intro-targets.json` + `build.ninja` graphs, executes supported single-config C++ targets natively through VBS's toolchain driver, CAS cache, and depfile tracker (zero `cmake --build` / `meson compile`), exposes unified `resolve_foreign_with_translation` and opt-in `vbs build|test --native-foreign`, and explicitly diagnoses or falls back on unsupported constructs (`UTILITY`/`custom_target`, generated sources, non-C++ languages, foreign `CXX_MODULES`, precompiled headers, untracked link fragments). -- **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching via `Void::FileSystem::DirectoryWatcher` (`MetadataOnly` never triggers builds or foreign configures). +- **Plan 20 Slices 1–2C / Track B — Bounded Native CMake & Meson Graph Translation**: [Translator.hpp](include/Void/Build/Provider/Translator.hpp) / [Translator.cpp](src/Provider/Translator.cpp) configures CMake/Meson ONLY (zero `cmake --build` / `meson compile`), translates single- and multi-compile-group C/C++ targets (`PerFileOption`), bounded hermetic `build.ninja` `CUSTOM_COMMAND` / `UTILITY` / `custom_target` code generators (`TargetKind::CustomAction`), and foreign CMake C++20 `CXX_MODULES` `fileSets` (lowering onto VBS's P1689 scanner + `ModuleBmi` + cross-target `module_bmis` propagation on GCC 16 & Clang 23), exposes `resolve_foreign_with_translation` / `vbs build|test --native-foreign`, and explicitly diagnoses or falls back on unsafe/unbounded constructs (`console` pools, `.util`-only side-effects, out-of-tree writes, `run` targets, PCH, non-C/C++ languages, untracked link fragments). +- **Modern C++, Editor Metadata, Watchers & `vbs ide`**: Full graph-integrated P1689r5 named modules & module partitions (with cross-target and imported `module_bmis` propagation on GCC `-fmodule-mapper` and Clang `--precompile` `.pcm` -> `-fmodule-file=`), explicit `SourceKind::HeaderUnit`, unity batches (excluding `.c`, modules, and per-file overrides), per-profile `compile_commands.json` (including `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries for `clangd`), non-destructive IDE config generation (`vbs ide generate` for `.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`), machine-readable workspace JSON (`vbs ide query`), and Linux `inotify` build/metadata watching via `Void::FileSystem::DirectoryWatcher` (`MetadataOnly` never triggers builds or foreign configures). - **Native Package Manager, Foreign Providers, Bridge & Install**: `Void::Data::Toml` 1.0 parser/merger, PubGrub-style SemVer solver (`Void::Semver::parse_range`), context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging & staged safe extraction (`Void::Archive`), native/CMake/Meson providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall. - **Registry Service, Web Admin UI & Native Self-Hosting**: `vbs-registry` HTTP/1.1 service (`VoidBuild_Registry` / `Void::BuildRegistry`) with RBAC, salted password hashes, CSRF/HttpOnly session auth, immutable releases, backup/restore, XSS-safe DOM-only web UI (`registry/web/`), native `VoidLibrary` & full `VbsSelfHostRecipe` recipes (`recipes/VoidLibrary/`, `recipes/SelfHost/`) compiling the full Stage 1 `vbs` binary without CMake to build & test Stage 2/3 projects, and native `VOID_TEST` (`VL-009`) registration eliminating external CMake test scanning. - **Maximal VoidLibrary Reuse (`3e254055...`)**: Built directly on VoidLibrary `Configuration` (`Void::Argparse::Parser` with nested subcommands, `option_many`, and 100% auto-generated `--help` across `vbs`, `vbs-registry`, `vbs_describe`, and `vbs_benchmarks`; `Void::Configuration::get_env`/`get_env_or`), `Crypto` (`Void::Crypto::Hasher` zero-dep SHA-256), `Archive` (`Void::Archive::create` & `extract_staged`), `Data` (`Void::Data::Toml`, `Void::Json::Strict`), `System` (`Void::Process::spawn`/`communicate_blocking`/`enable_subreaper`, `Void::FileSystem::DirectoryWatcher`/`FileLock`/`reflink_copy_file`/`set_canonical_mtime`/`atomic_symlink_swap`, `Void::Process::SignalWatcher`), `Algorithms` (`Void::Algorithms::topological_order`), `Async` (`Void::Concurrency::ThreadPool`), `Unicode` (`Void::Unicode::validate_utf8`), `Text` (`Void::Str`, `Void::Encoding::Hex`, `Void::Encoding::Url`, `Void::Semver::parse_range`), `Log` (`Void::Log`), `Core` (`Void::Scope::on_exit`), `Time` (`Void::Time::Stopwatch`), and `Testing` (`VOID_TEST`). -- **Remaining future design scope**: [Plan 20 Slices 2B/2C & 3](docs/roadmap/20-future-translation-platforms.md) and [Post-v1 Expansion Roadmap](docs/roadmap/21-expansion-roadmap.md) Tracks B–E2/E4 (Track B C driver / Ninja custom-command / foreign module translation, Track C macOS/Windows/cross-compilation, Track D shared HTTP CAS & supply-chain provenance, Track E2–E4 workspaces & daemon) remain planned architectural scope. +- **Remaining future design scope**: [Plan 20 Slice 3](docs/roadmap/20-future-translation-platforms.md) and [Post-v1 Expansion Roadmap](docs/roadmap/21-expansion-roadmap.md) Tracks C–D and E2/E3 daemon/E4 (Track C macOS/Windows/cross-compilation, Track D shared HTTP CAS & supply-chain provenance, Track E2 `workspace.cpp`, Track E3 `vbs daemon`, Track E4 `Void::Net`/`Void::Sqlite`, and live `conan` CLI verification) remain planned architectural scope. Start with the [roadmap plans](docs/roadmap/README.md), [expansion roadmap](docs/roadmap/21-expansion-roadmap.md), [architecture](docs/roadmap/ARCHITECTURE.md), @@ -80,6 +80,7 @@ All CLI help text (`vbs --help`, `vbs --help`, `vbs compdb --help`, `v - `vbs graph [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang] [--format dot|json]` - `vbs describe [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang]` - `vbs compdb use|show|export|watch ...` +- `vbs ide generate|query [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang] [--editor all|clangd|vscode|clion|zed] [--force]` - `vbs watch [--project DIR] [--build-dir DIR] [--profile NAME] [--target NAME]...` - `vbs deps resolve|update [--project DIR] [--build-dir DIR] [--profile NAME] [--offline]` - `vbs install --prefix DIR [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang] [--package-name NAME] [--package-version VER] [--component NAME] [--no-cmake-export] [--no-native-export]` diff --git a/docs/SDK.md b/docs/SDK.md index 3ca3e77..457bc1d 100644 --- a/docs/SDK.md +++ b/docs/SDK.md @@ -14,7 +14,7 @@ The SDK uses namespace `Void::Build`, `PascalCase` types/enum constants, and `sn `Profiles` supports: - `add(name, compile_options)` - `inherit(name, parent, compile_options)` -- `define(ProfileDescription)` (supports `compile_options`, `link_options`, `defines`, `parent`, `compiler`, `cxx_standard`, `lto`, `sanitizers`, `sysroot`, `compiler_path`, `reproducibility_epoch`, `nondeterministic`) +- `define(ProfileDescription)` (supports `compile_options`, `link_options`, `defines`, `parent`, `compiler`, `c_standard`, `cxx_standard`, `lto`, `sanitizers`, `sysroot`, `compiler_path`, `reproducibility_epoch`, `nondeterministic`) - `resolve(name, compiler_or_opt, os, architecture)` -> returns an immutable `ProfileContext`, throwing `std::invalid_argument` on unknown profile names, missing parents, or profile inheritance cycles. ## Targets and Usage Requirements @@ -44,6 +44,7 @@ Target names must be nonempty and unique per `Project`. Operations validate inpu | `.link_option(opt, visibility)` | Scoped linker flags | | `.link(Target\|ImportedTarget, visibility)` | Local or foreign imported library links (`Visibility::Private`, `Public`, `Interface`) | | `.depends_on(Target)` | Explicit action prerequisite ordering (for example, codegen producer before consumer) | +| `.c_standard(CStandard)` | `Default`, `C11`, `C17`, `C23` (used with `gcc`/`clang` C driver for `.c` sources) | | `.cxx_standard(CxxStandard)` | `Default`, `Cxx17`, `Cxx20`, `Cxx23`, `Cxx26` | | `.precompiled_header(path)` / `.unity_build(enabled, batch_size)` | PCH and deterministic unity batching | | `.lto(LtoMode)` / `.sanitizer(Sanitizer)` | `LtoMode::None\|Full\|Thin`; `Sanitizer::Address\|Undefined\|Thread\|Memory\|Leak` | diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index c79d6c1..7cfa92f 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -2,7 +2,7 @@ Updated: 2026-11-27 Branch: main -Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1 & 2A + Track A (zero-CMake `.native_builder()` self-host, full `VOID_TEST` migration, & bit-identical Stage 2 == Stage 3 bootstrap) complete +Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration complete ## Completed delivery waves @@ -48,10 +48,15 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1 & 2A + Track A (zero-CMake - **Track A1 (`builder == "native"`)**: Extended `ProviderRequest` in `include/Void/Build/Provider/Provider.hpp` and implemented `run_native_provider` in `src/Provider/Provider.cpp` handling both pure `build.cpp` subprojects and built-in `VoidLibrary` recipe closure (`VOID_ENABLED_MODULES`), complete with `Log`/`Async`-complete `Testing` closure in `recipes/VoidLibrary/VoidLibraryRecipe.cpp`, reverse-DFS static archive link ordering, `Void::*` target aliasing, `MetadataOnly` cache isolation, and `/proc/self/exe`-first SDK/binary discovery in `src/Main.cpp`. Switched root `build.cpp`'s `VoidLibrary` dependency from `.cmake(...)` to `.native_builder(...)`. - **Track A2 (Full `VOID_TEST` `VL-009` Migration & Complete Self-Test `build.cpp`)**: Converted all 40 existing test cases across `tests/{SdkDeclarations,ExampleContexts,CoreEngineTests,FullV1Tests,RegistryTests,SelfHostTests}.cpp` to VoidLibrary's self-registering `VOID_TEST(Suite, name)` macro, removed `VoidTestScanner.cmake` invocation from `CMakeLists.txt` and `tests/CMakeLists.txt`, and declared `vbs_benchmarks` plus all 5 `Void::Testing` executables (`vbs_sdk_tests`, `vbs_core_tests`, `vbs_v1_tests`, `vbs_registry_tests`, `vbs_selfhost_tests`) alongside `vbs_self_smoke` in root `build.cpp` (13 targets total). - **Track A3 (Bit-Identical Stage 2 == Stage 3 Bootstrap)**: Removed `$BUILD_DIR` from `GenerateBootstrapConfig` (`binary_dir = ""`), added disjoint `{profile_build_dir, "/vbs-build"}` prefix mapping in `src/Graph/Graph.cpp`, emitted `-frandom-seed=` on deterministic GCC compiles and `TZ=UTC`/`LC_ALL=C` on links in `src/Toolchain/Driver.cpp`, and verified `sha256(stage2/vbs) == sha256(stage3/vbs)` (`9280ea998492cd3f48833cf87b06d91940c1f465f29f3871289c1e01bcf2e0b3`) plus `libVoidBuildSdk.a` and `libVoidBuildCore.a` bit-for-bit equality with `cmake` trapped on `PATH`. +- **Wave 10 (Track B [B1–B3] Foreign Translation Expansion + First-Class `vbs ide` & `build.cpp` CompDB Integration)**: + - **Track B1 (First-Class C Driver & Mixed C/C++ Translation)**: Added `CStandard` (`Default`, `C11`, `C17`, `C23`) across `include/Void/Build.hpp`, `src/Build.cpp`, and `src/Config/Frontend.cpp`; extended `ToolchainCapabilities`/`CompileRequest` in `Driver.hpp`/`Driver.cpp` with `c_compiler` discovery/probing/caching and C lowering; extended `Graph.cpp` & `CompDb.cpp` for C compilation and `c_standard` emission; and upgraded `Translator.cpp` + `Provider.cpp` to pass `-DCMAKE_C_COMPILER`/`CC` and lower multi-compile-group mixed C/C++ CMake and Meson targets cleanly with `PerFileOption`. + - **Track B2 (Bounded `build.ninja` `CUSTOM_COMMAND` Translation)**: Implemented shared `parse_ninja_custom_graph` & `CustomActionMaterializer` in `src/Provider/Translator.cpp` supporting hermetic CMake `add_custom_command`/`UTILITY` and Meson `custom_target`/`generated_sources` lowered to `TargetKind::CustomAction`, while explicitly rejecting `console` pools, `.util`-only side-effects, out-of-tree writes, in-tree codegen tools, and `run` targets. + - **Track B3 (Foreign CMake C++20 `CXX_MODULES` & NixOS `clang-scan-deps` Include Discovery)**: Populated `ToolchainCapabilities::default_include_dirs` from Clang `-E -v` so NixOS `clang-scan-deps` resolves standard library headers; added `external_module_bmis` + `ImportedTargetInterface::module_bmis` propagation in `ModuleScanner.{hpp,cpp}`, `Graph.{hpp,cpp}`, `Provider.cpp`, and `Translator.cpp`; lowered CMake `CXX_MODULES` `fileSets` natively on both GCC 16 and Clang 23, including VBS targets importing modules exported by translated CMake libraries. + - **IDE Integration (`build.cpp` CompDB & `vbs ide generate|query`)**: Added `project_build_descriptor_commands` indexing `build.cpp`/`build.profiles.cpp`/`build-support/` with `` include paths in `compile_commands.json`; implemented `vbs ide generate` (non-destructive `.clangd` with GCC flag stripping, `.vscode/{tasks,launch,settings}.json`, `.zed/{tasks,debug}.json`, `.idea/customTargets.xml`) and `vbs ide query` workspace/target JSON output in `CompDb.{hpp,cpp}`, `Watcher.cpp`, `Main.cpp`, `tests/CliContracts.cmake`, and `tests/FullV1Tests.cpp`. ## Remaining future scope -- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track B (C driver, Ninja custom-command translation, foreign C++20 modules, Conan2), Track C (macOS/Windows ports + cross-compilation), Track D (shared HTTP CAS + parallel hashing + SBOM/signatures), and Track E2–E4 (`workspace.cpp`, local daemon, `Void::Net`/`Void::Sqlite` alignment) remain planned scope. +- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D (shared HTTP CAS + parallel hashing + SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. ## Environment notes & upstream boundaries diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 3e18aaa..9b3a4e7 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -16,4 +16,5 @@ Base HEAD: `fe0d1a6` | Wave 7 (Plan 20 Slice 1 Bounded CMake Native Translation, Self-Testing `build.cpp`, `VL-009` `VOID_TEST`, & Warm Cache Hardening) | Bounded single-config C++ CMake File API audit + native `Graph::BuildGraph` translation + explicit fallback; self-test target `vbs_self_smoke` in `build.cpp`; `VL-009` `VOID_TEST` zero-CMake basename-collision test; stat-validated `StateStore` cache + `Scheduler` `RunDigestCache` | COMPLETE & VERIFIED | `include/Void/Build/Provider/Translator.hpp`, `src/Provider/Translator.cpp`, `tests/SelfBuildSmoke.cpp`, `src/State/StateStore.{hpp,cpp}`, `src/Execution/Scheduler.cpp`, `build.cpp`, `CMakeLists.txt`, `recipes/SelfHost/VbsSelfHostRecipe.cpp`, expanded tests & docs | | Wave 8 (Plan 20 Slice 2A Meson Native Translation, Everyday DX CLI, & Expansion Roadmap) | Bounded Meson `intro-targets.json` + `build.ninja` native translation & unified `resolve_foreign_with_translation`; `vbs build\|test --native-foreign`, `vbs init`, `vbs clean`, `vbs doctor`, `vbs graph`; 5-track post-v1 expansion roadmap | COMPLETE & VERIFIED | `include/Void/Build/Provider/Translator.hpp`, `src/Provider/Translator.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, `tests/CliContracts.cmake`, `docs/roadmap/21-expansion-roadmap.md`, updated docs | | Wave 9 (Track A — Zero-CMake Self-Hosting, Full `VOID_TEST` Suite, & Bit-Identical Stage 2 == Stage 3) | First-class `builder == "native"` provider + `.native_builder()` in `build.cpp`; all tests migrated to `VOID_TEST(Suite, name)` & `VoidTestScanner.cmake` removed; all 13 targets (`vbs_benchmarks` + 6 test suites) declared in `build.cpp`; `binary_dir = ""` + `/vbs-build` prefix map + `-frandom-seed` Stage 2 == Stage 3 reproducibility verified with trapped `cmake` | COMPLETE & VERIFIED | `include/Void/Build/Provider/Provider.hpp`, `src/Provider/Provider.cpp`, `src/Graph/Graph.cpp`, `src/Toolchain/Driver.cpp`, `src/Main.cpp`, `recipes/VoidLibrary/VoidLibraryRecipe.{hpp,cpp}`, `build.cpp`, `CMakeLists.txt`, `tests/*`, docs | -| Future (Tracks B–E2/E4 / Plan 20 Slices 2B–3) | C driver & Ninja custom-command translation, foreign C++20 modules & Conan2, macOS/Windows/cross-compile, shared HTTP CAS & SBOM/signatures, `workspace.cpp` & daemon | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | +| Wave 10 (Track B [B1–B3] + First-Class `vbs ide` Integration) | Native C driver (`CStandard`) & mixed C/C++ CMake/Meson translation (`PerFileOption`); bounded `build.ninja` `CUSTOM_COMMAND` translation (`CustomAction`); foreign CMake `CXX_MODULES` `fileSets` & cross-target `module_bmis` + Clang `default_include_dirs`; `build.cpp` SDK CompDB indexing + `vbs ide generate\|query` | COMPLETE & VERIFIED | `include/Void/Build.hpp`, `Driver.{hpp,cpp}`, `ModuleScanner.{hpp,cpp}`, `Graph.{hpp,cpp}`, `CompDb.{hpp,cpp}`, `Provider.cpp`, `Translator.{hpp,cpp}`, `Watcher.cpp`, `Main.cpp`, `tests/{FullV1Tests.cpp,CliContracts.cmake}`, docs | +| Future (Plan 20 Slice 3 / Tracks C–D, E2, E3 daemon, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; shared HTTP CAS & SBOM/signatures; `workspace.cpp`, `vbs daemon`, `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 364de5f..1c8413f 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -29,24 +29,24 @@ dev cpp-gcc -c clang-format --dry-run --Werror \ registry/include/Void/Build/Registry/*.hpp registry/service/*.cpp \ benchmarks/*.cpp tests/*.cpp ``` -- Exit status: `0` (all 70 owned C++ headers/sources pass with zero formatting diffs). +- Exit status: `0` (all owned C++ headers and sources pass with zero formatting diffs). ## CTest Suite Results (`dev cpp-gcc`) ```sh dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure ``` -- Exit status: `0` — **8 / 8 passed (100%) in 121.31 sec**: +- Exit status: `0` — **8 / 8 passed (100%) in 132.20 sec**: | # | CTest Name | Scope Verified | Result | Time | | --- | --- | --- | --- | --- | -| 1 | `vbs_sdk_tests` | 17 self-registered `VOID_TEST` cases (`SdkDeclarations` 14 + `ExampleContexts` 3 for 13-target `.native_builder()` `build.cpp` and pin `3e254055...`; zero CMake test scanner) | Passed | 0.01s | -| 2 | `vbs_core_tests` | 6 `VOID_TEST` cases: `Void::Crypto` SHA-256 NIST vectors, `Void::Process` exec-fail & stubborn grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing (`Void::FileSystem`), stat-cached `StateStore` CAS recovery/GC, end-to-end native frontend + deterministic build + `RunDigestCache` | Passed | 11.41s | -| 3 | `vbs_v1_tests` | 12 `VOID_TEST` cases: CompDB ticket races & `atomic_symlink_swap`, `Void::FileSystem::DirectoryWatcher` + `MetadataOnly` boundary, `Void::Data::Toml` + `Void::Semver::parse_range` PubGrub solver + CAS `vbs.lock`, `Void::Archive` `.tar` determinism & security rejection, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 modules + full Plan 08 graph integration, **Plan 20 Slice 1** CMake translation, **Plan 20 Slice 2A** Meson translation, **Wave 8 DX CLI** E2E (`vbs init` -> `vbs test` -> `vbs graph` -> `vbs doctor` -> `vbs clean`), AND **Track A1** pure `build.cpp` subproject `.native_builder()` build with trapped `cmake` on `PATH` | Passed | 23.95s | -| 4 | `vbs_registry_tests` | 2 `VOID_TEST` cases: `vbs-registry` HTTP/1.1 security/RBAC/CSRF/XSS/tar-422/backup-restore + full live CLI E2E `vbs publish` -> `vbs deps resolve` -> `vbs build --locked` | Passed | 4.02s | -| 5 | `vbs_selfhost_tests` | 5 `VOID_TEST` cases: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` + direct `VOID_TEST` `SdkDeclarations.cpp` (zero scanner) + Stage 2, full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` -> Stage 2 `vbs test` with trapped `cmake`, `VL-009` `VOID_TEST(suite, name)` colliding basenames (`alpha/Unit.cpp`, `beta/Unit.cpp`), AND **Track A3** cross-build-dir SHA-256 bit-identical reproducibility (`librepro_lib.a` & `repro_app` with `custom_action` + anonymous namespace + trapped `cmake`) | Passed | 81.80s | +| 1 | `vbs_sdk_tests` | 17 self-registered `VOID_TEST` cases (`SdkDeclarations` 14 + `ExampleContexts` 3 for 13-target `.native_builder()` `build.cpp` and pin `3e254055...`; zero CMake test scanner) | Passed | 0.02s | +| 2 | `vbs_core_tests` | 6 `VOID_TEST` cases: `Void::Crypto` SHA-256 NIST vectors, `Void::Process` exec-fail & stubborn grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing (`Void::FileSystem`), stat-cached `StateStore` CAS recovery/GC, end-to-end native frontend + deterministic build + `RunDigestCache` | Passed | 11.43s | +| 3 | `vbs_v1_tests` | 16 `VOID_TEST` cases: CompDB ticket races & `atomic_symlink_swap`, `Void::FileSystem::DirectoryWatcher` + `MetadataOnly` boundary, `Void::Data::Toml` + `Void::Semver::parse_range` PubGrub solver + CAS `vbs.lock`, `Void::Archive` `.tar` determinism & security rejection, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 modules + full Plan 08 graph integration, **Plan 20 Slice 1/2A** CMake & Meson translation (`USES_TERMINAL` / `console: true` fallback), **Wave 8 DX CLI**, **Track A1** pure `build.cpp` subproject `.native_builder()` with trapped `cmake`, **Track B1** pure C17+C++23 & mixed C/C++ CMake/Meson native translation + CompDB separation, **Track B2** hermetic `build.ninja` `CUSTOM_COMMAND` CMake/Meson native translation + `.util`/out-of-tree/`run_target` rejection, **Track B3** foreign CMake `CXX_MODULES` + cross-target `module_bmis`, AND **IDE Integration** (`build.cpp` CompDB `-fsyntax-only` check + `.clangd`/`.vscode`/`.zed`/`.idea` non-destructive generation + `vbs ide query`) | Passed | 34.05s | +| 4 | `vbs_registry_tests` | 2 `VOID_TEST` cases: `vbs-registry` HTTP/1.1 security/RBAC/CSRF/XSS/tar-422/backup-restore + full live CLI E2E `vbs publish` -> `vbs deps resolve` -> `vbs build --locked` | Passed | 3.99s | +| 5 | `vbs_selfhost_tests` | 5 `VOID_TEST` cases: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` + direct `VOID_TEST` `SdkDeclarations.cpp` (zero scanner) + Stage 2, full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` -> Stage 2 `vbs test` with trapped `cmake`, `VL-009` `VOID_TEST(suite, name)` colliding basenames (`alpha/Unit.cpp`, `beta/Unit.cpp`), AND **Track A3** cross-build-dir SHA-256 bit-identical reproducibility (`librepro_lib.a` & `repro_app` with `custom_action` + anonymous namespace + trapped `cmake`) | Passed | 82.58s | | 6 | `vbs_sdk_registration` | 17 `VOID_TEST` registrations verified (`SdkDeclarations.*`, `ExampleContexts.*`); named JSON case executed | Passed | 0.01s | -| 7 | `vbs_cli_contract` | 32 native CLI & auto-generated `Void::Argparse::Parser` help/subcommand/error contracts verified | Passed | 0.05s | +| 7 | `vbs_cli_contract` | 37 native CLI & auto-generated `Void::Argparse::Parser` help/subcommand/error contracts verified (including `vbs ide` & `vbs ide generate|query`) | Passed | 0.05s | | 8 | `vbs_description_contract` | Four runtime profile/compiler contexts (`debug`/`release` x `gcc`/`clang` for 13-target `.native_builder()` `build.cpp`), auto-generated `vbs_describe --help`, and five error contracts verified | Passed | 0.06s | ## Real Zero-CMake Self-Build, Native Test Suite & Bit-Identical Stage 2 == Stage 3 (`vbs test` / `vbs build`) @@ -57,9 +57,9 @@ VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pi dev cpp-gcc -c sh -c 'PATH="$PWD/build/cmake-trap:$PATH" build/dev/bin/vbs test --build-dir build/vbs-stage2 --profile release --target vbs --target vbs_self_smoke --target vbs_sdk_tests --target vbs_core_tests --jobs 8' ``` - Exit status: `0`: - - `VoidLibrary` built completely natively without CMake in `12.57s` (`27 executed, 0 cached`), exporting 60 targets. - - Root `build.cpp` built cleanly in `41.87s` (`42 executed, 0 cached`). - - `vbs test` passed `vbs_sdk_tests` (`4 ms`), `vbs_self_smoke` (`2 ms`), and `vbs_core_tests` (`11324 ms`) with zero `cmake` invocations. + - `VoidLibrary` built completely natively without CMake in `12.30s` (`27 executed, 0 cached`), exporting 60 targets. + - Root `build.cpp` built cleanly in `41.92s` (`42 executed, 0 cached`, 13 targets, 55 actions). + - `vbs test` passed `vbs_sdk_tests` (`6 ms`), `vbs_self_smoke` (`2 ms`), and `vbs_core_tests` (`11167 ms`) with zero `cmake` invocations. ### Stage 2 -> Stage 3: Bit-Identical Reproducible Self-Build (`sha256(stage2) == sha256(stage3)`) with trapped `cmake` (`--no-cache`) ```sh @@ -69,28 +69,26 @@ sha256sum build/vbs-stage2/profiles/release/out/bin/vbs build/vbs-stage3/profile build/vbs-stage2/profiles/release/out/libVoidBuildSdk.a build/vbs-stage3/profiles/release/out/libVoidBuildSdk.a \ build/vbs-stage2/profiles/release/out/libVoidBuildCore.a build/vbs-stage3/profiles/release/out/libVoidBuildCore.a ``` -- Exit status: `0` — `32 executed, 0 cached` in `38.36s`; exact bit-for-bit SHA-256 matches across distinct build directories: - - `vbs`: `9280ea998492cd3f48833cf87b06d91940c1f465f29f3871289c1e01bcf2e0b3` (Stage 2 == Stage 3) - - `libVoidBuildSdk.a`: `8f1ec2ea226fcb93a55e78e658ce62bc2769941edaaaf097045ba7f8e6027483` (Stage 2 == Stage 3) - - `libVoidBuildCore.a`: `07f3ff5fd96e5c7cce3d5dfb0f25f071f09003ae850def63d605d9b0d2b1a4a3` (Stage 2 == Stage 3) +- Exit status: `0` — `32 executed, 0 cached` in `38.12s`; exact bit-for-bit SHA-256 matches across distinct build directories: + - `vbs`: `7fa4b54eeaecd21ade1d2877b45a86f215082b78dc0746299ec659b85f6880e6` (Stage 2 == Stage 3) + - `libVoidBuildSdk.a`: `20d3070d70fc5f6efe68058560617d6f2e6b0ec96229b67a34e1c0ee5a4b796c` (Stage 2 == Stage 3) + - `libVoidBuildCore.a`: `bf3accc339a11ba9fe5d429e5e4d90fecfcaad54ee561b0f6a46aedd1464d19e` (Stage 2 == Stage 3) -### Remaining Native Test Suites via Stage 2 `vbs test` +### Native `vbs_v1_tests` via Stage 2 `vbs test` ```sh VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \ - dev cpp-gcc -c build/vbs-stage2/profiles/release/out/bin/vbs test --build-dir build/vbs-stage2 --profile release --target vbs_v1_tests --target vbs_registry_tests --target vbs_selfhost_tests --jobs 8 + dev cpp-gcc -c build/vbs-stage2/profiles/release/out/bin/vbs test --build-dir build/vbs-stage2 --profile release --target vbs_v1_tests --jobs 8 ``` -- Exit status: `0` (`9.60s` build, `9 executed, 32 cached`): - - `vbs test: PASSED 'vbs_v1_tests'` (`23226 ms`) - - `vbs test: PASSED 'vbs_selfhost_tests'` (`59753 ms`) - - `vbs test: PASSED 'vbs_registry_tests'` (`2851 ms`) +- Exit status: `0` (`10.38s` build, `2 executed, 32 cached`): + - `vbs test: PASSED 'vbs_v1_tests'` (`32658 ms`) ## Clang 23.1.3 Target Matrix (`dev cpp`) ```sh -dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter clang23 +dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter "clang23|track_b3" ``` -- Exit status: `0` — `1 tests: 1 ✔ in 771.0ms` (`FullV1Tests.clang23_target_toolchain_and_p1689_module_scan`). -- Verified inside `dev cpp`: Clang 23.1.3 + `clang-scan-deps` target probing, C++20 compilation, and full `Graph::lower_project_graph` + `Execution::execute_graph` build of module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using two-step `--precompile` `.pcm` -> `.o` with transitive `-fmodule-file=`. +- Exit status: `0` — **2 / 2 passed in 2.37s** (`clang23_target_toolchain_and_p1689_module_scan` `836.6ms`, `track_b3_foreign_cmake_cxx20_modules_native_translation` `1535.3ms`). +- Verified inside `dev cpp`: Clang 23.1.3 + `clang-scan-deps` target probing (with `default_include_dirs` NixOS system include discovery), C++20 compilation, intra-target module partitions (`vbs.clangcalc`), and native translation of a foreign CMake C++20 `CXX_MODULES` library (`vbs.trackb3.math`) plus cross-build-system VBS consumer import using two-step `--precompile` `.pcm` -> `.o` with `-fmodule-file=`. ## Benchmarks (`dev cpp-gcc`) @@ -99,13 +97,13 @@ dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 ``` - Exit status: `0`: ```json - {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":20,"cold_build_ms":337,"cold_executed":17,"warm_noop_ms":5,"warm_executed":0,"warm_cached":17} + {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":19,"cold_build_ms":334,"cold_executed":17,"warm_noop_ms":4,"warm_executed":0,"warm_cached":17} ``` ## Limits and Unrun Checks 1. **HTTPS git fetch in proxy-restricted environment**: Inside this execution environment, outbound HTTPS to `https://git.faumaray.com/Void/VoidLibrary.git` encountered `Proxy CONNECT aborted`; CMake configure and `vbs test` were therefore verified against a clean local detached checkout of the exact pinned commit `3e254055e081a104f08df68dde39711bc7813518` via `VBS_VOID_SOURCE_DIR`. -2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). +2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). Live `conan` container verification (Track B3) remains unrun. 3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection. 4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. -5. **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track B (C driver, Ninja custom-command translation, foreign C++20 module fileSets, Conan2), Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D (shared HTTP CAS, parallel hashing, SBOM/signatures), and Track E2–E4 (`workspace.cpp`, local daemon, `Void::Net`/`Void::Sqlite` alignment) remain planned scope. +5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D (shared HTTP CAS, parallel hashing, SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. diff --git a/docs/roadmap/09-compilation-database.md b/docs/roadmap/09-compilation-database.md index cb77125..25570f0 100644 --- a/docs/roadmap/09-compilation-database.md +++ b/docs/roadmap/09-compilation-database.md @@ -1,6 +1,6 @@ # 09 — Compilation databases and editor selection -Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26; extended in Wave 10 on 2026-11-27 with `build.cpp`/`build.profiles.cpp`/`build-support/` SDK CompDB entries, C standard flags, and `vbs ide generate|query` for `.clangd`, `.vscode/`, `.zed/`, & `.idea/`). See [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) for implemented files and observed checks. diff --git a/docs/roadmap/20-future-translation-platforms.md b/docs/roadmap/20-future-translation-platforms.md index 0f10d35..3f7d449 100644 --- a/docs/roadmap/20-future-translation-platforms.md +++ b/docs/roadmap/20-future-translation-platforms.md @@ -1,6 +1,6 @@ # 20 — Later native foreign execution and platform ports -Implementation status: **Slices 1 & 2A implemented & verified** (bounded single-config C++ CMake File API codemodel and Meson `intro-targets.json` + `build.ninja` audits, native `Graph::BuildGraph` translation, unified `resolve_foreign_with_translation`, CLI `vbs build|test --native-foreign`, equivalence & restored-mtime mutation tests, and explicit `RequireNative` / `FallbackToForeignBuild` policy in [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp) and [Translator.cpp](../../src/Provider/Translator.cpp)); **Slices 2B/2C (C driver, custom-command translation, foreign C++20 module fileSets), Slice 3 (Windows/MSVC & macOS/Apple Clang ports), and remote execution remain planned scope** — see [21-expansion-roadmap.md](21-expansion-roadmap.md), [STATE](../agent-workflow/STATE.md), and [VERIFICATION](../agent-workflow/VERIFICATION.md). +Implementation status: **Slices 1, 2A, 2B, & 2C implemented & verified** (bounded single-config C & C++ / multi-compile-group CMake File API `codemodel-v2` and Meson `intro-targets.json` + `build.ninja` audits, bounded hermetic `build.ninja` `CUSTOM_COMMAND` / `UTILITY` / `custom_target` lowering with strict rejection of `console` pools / `.util`-only side-effects / out-of-tree writes, foreign CMake C++20 `CXX_MODULES` `fileSets` lowering onto P1689 + cross-target `module_bmis`, native `Graph::BuildGraph` execution, unified `resolve_foreign_with_translation`, CLI `vbs build|test --native-foreign`, equivalence & restored-mtime mutation tests, and explicit `RequireNative` / `FallbackToForeignBuild` policy in [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp) and [Translator.cpp](../../src/Provider/Translator.cpp)); **Slice 3 (Windows/MSVC & macOS/Apple Clang ports, remote execution workers, plus live `conan` CLI verification) remains planned scope** — see [21-expansion-roadmap.md](21-expansion-roadmap.md), [STATE](../agent-workflow/STATE.md), and [VERIFICATION](../agent-workflow/VERIFICATION.md). ## Requirements and ownership diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index c59eca6..a3dec69 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -1,6 +1,6 @@ # 21 — Post-v1 Expansion Roadmap -Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1 & 2A**, **Track A [A1–A3]**, and **Track E1** are implemented and verified; **Tracks B–D & E2–E4** remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). +Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track C**, **Track D**, **Track E2 (`workspace.cpp`)**, **Track E3 (`vbs daemon`)**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). This roadmap defines five orthogonal expansion tracks for taking VoidBuildSystem from a verified self-hosting Linux C++26 build system into a multi-platform, distributed, daily-driver ecosystem. Each track preserves core architectural invariants: ordinary C++ descriptions, hermetic content-verified snapshots, isolated profiles, immutable CAS publication, and explicit diagnostics over silent approximation. @@ -28,15 +28,15 @@ flowchart LR --- -## Track B — Foreign Build Translation Expansion (Plan 20 Slices 2B & 2C) +## Track B — Foreign Build Translation Expansion (Plan 20 Slices 2B & 2C) *(Implemented & Verified in Wave 10; live `conan` container pending)* **Goal**: Expand bounded native translation beyond single-config C++ libraries/executables while never silently dropping unsupported rules. -| Phase | Concrete Scope | Acceptance Gate | +| Phase | Concrete Scope | Acceptance Gate / Status | | --- | --- | --- | -| **B1 — Native C Compiler Driver (`C` + Mixed `C`/`C++`)** | Extend `ToolchainCapabilities` with `c_compiler` (`gcc`/`clang`), C standard flags (`c11`/`c17`/`c23`), and multi-compile-group lowering in `Graph.cpp` + `Translator.cpp`. | Mixed C/C++ CMake and Meson projects (e.g., zlib/sqlite3-style fixtures) translate natively and match official tool outputs. | -| **B2 — Bounded `build.ninja` Custom-Command Translation** | Parse configured Ninja `rule` / `build` edges for hermetic `add_custom_command` / `custom_target` code generators into VBS `ActionKind::Custom` nodes, strictly rejecting unverified side-effecting rules. | Generated-header CMake/Meson fixtures execute natively under VBS CAS caching and rebuild correctly under generator-input mutations. | -| **B3 — Foreign C++20 `CXX_MODULES` Translation & Conan2 Binary Adapter** | Lower CMake `CXX_MODULES` `fileSets` onto VBS's P1689 scanner + `ModuleBmi` pipeline; implement live Conan2 `conan install --format=json` consumer adapter when `conan` is available. | Foreign CMake C++20 module fixture builds natively under GCC 16 and Clang 23; Conan2 fixture verified in a container with `conan` installed. | +| **B1 — Native C Compiler Driver (`C` + Mixed `C`/`C++`)** | Extended `ToolchainCapabilities` with `c_compiler` (`gcc`/`clang`), C standard flags (`c11`/`c17`/`c23`), `PerFileOption` CompDB projection, and multi-compile-group lowering in `Graph.cpp` + `Translator.cpp`. | **Verified**: Pure VBS C17+C++23, CMake C11+C++20, and Meson C17+C++20 mixed fixtures translate and execute natively (`FullV1Tests.cpp`). | +| **B2 — Bounded `build.ninja` Custom-Command Translation** | Shared `build.ninja` `CUSTOM_COMMAND` / `phony` parser lowering hermetic `add_custom_command`, `UTILITY`, and Meson `custom_target`/`generated_sources` into VBS `ActionKind::Custom` nodes, strictly rejecting `console` pools, `.util`-only side-effects, out-of-tree writes, and `run` targets. | **Verified**: Generated-header + generated-source CMake and Meson fixtures execute natively under `RequireNative`, while unsafe constructs reject cleanly (`FullV1Tests.cpp`). | +| **B3 — Foreign C++20 `CXX_MODULES` Translation & Conan2 Binary Adapter** | Lowered CMake `CXX_MODULES` `fileSets` onto VBS's P1689 scanner + `ModuleBmi` pipeline (with `default_include_dirs` NixOS `clang-scan-deps` support) plus cross-target/imported `module_bmis` propagation; Conan2 adapter enforces explicit prerequisite checks. | **Verified on GCC 16 & Clang 23**: Foreign CMake C++20 module library + consumer VBS cross-target `import` pass on both toolchains; live `conan` container verification remains pending. | --- @@ -73,15 +73,14 @@ flowchart LR | --- | --- | --- | | **E1 — Everyday CLI Ergonomics (Implemented in Wave 8)** | `vbs init` project scaffolding, `vbs clean`, `vbs doctor` environment diagnostics, `vbs graph --format dot|json`, and `vbs build --native-foreign`. | End-to-end CLI & integration tests passing in `vbs_cli_contract` and `vbs_v1_tests`. | | **E2 — Multi-Package Workspaces (`workspace.cpp`)** | Shared `vbs.lock`, shared CAS, cross-member local target linking, and affected-target graph selection (`vbs build --member ` / `--changed-since `). | 3-package workspace fixture building shared library + app + tests with unified lockfile. | -| **E3 — Background Build/Metadata Daemon & IDE Integration** | Optional local Unix-socket daemon (`vbs daemon`) holding warm `StateStore`, `RunDigestCache`, and `DirectoryWatcher` so editor `compile_commands.json` refreshes and incremental `vbs build` respond in <50ms. | Daemon auto-restarts on binary upgrade, honors `SignalWatcher` graceful shutdown, and preserves ticket ordering. | +| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); optional Unix-socket `vbs daemon` holding warm `StateStore`/`RunDigestCache`/`DirectoryWatcher` (**Planned**). | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; `vbs daemon` & dedicated editor extensions pending. | | **E4 — Transport & Storage Upstream Alignment** | Adopt `Void::Net` (`VL-004`/`VL-005`) and `Void::Sqlite` (`VL-011b`) when lightweight/bundled builds become available in minimal Nix toolchains, reducing VBS transport code further. | All `vbs_registry_tests` and `vbs_core_tests` pass on both minimal and full toolchains. | --- ## Recommended Next Execution Order -1. **Track B1 + B2** (highest leverage next): C compiler driver + bounded Ninja custom-command translation so real-world C/C++ CMake/Meson dependencies execute natively. -2. **Track D1 + D2**: shared HTTP CAS cache on `vbs-registry` + parallel snapshot hashing for large repos. -3. **Track E2**: multi-package `workspace.cpp` support. -4. **Track B3**: foreign C++20 `CXX_MODULES` `fileSets` lowering + live Conan2 adapter. -5. **Track C1–C4**: macOS / Windows platform ports + dual-profile cross-compilation once host CI runners are provisioned. +1. **Track D1 + D2** (highest leverage next): shared HTTP CAS cache on `vbs-registry` + parallel snapshot hashing for large repos. +2. **Track E2**: multi-package `workspace.cpp` support with shared lockfile and CAS. +3. **Track E3 (`vbs daemon`) + Track E4**: persistent local background daemon and `Void::Net`/`Void::Sqlite` alignment once optional system deps are bundled. +4. **Track C1–C4 + live `conan` container**: macOS / Windows platform ports + dual-profile cross-compilation once host CI runners are provisioned. diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md index 0743ca4..dd97543 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -1,7 +1,7 @@ # Roadmap and delivery graph -Plans **01–19** and **Plan 20 Slices 1 & 2A** (bounded native CMake & Meson graph translation on Linux) are implemented and verified in the native codebase and CTest -suites; **Plan 20 Slices 2B/2C & 3** and the five post-v1 expansion tracks in [21 — Post-v1 expansion roadmap](21-expansion-roadmap.md) define the next phases. For implemented +Plans **01–19**, **Plan 20 Slices 1, 2A, 2B, & 2C** (bounded native C/C++ CMake & Meson translation, hermetic `build.ninja` `CUSTOM_COMMAND` rules, and CMake C++20 `CXX_MODULES` `fileSets`), **Track A**, **Track B**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified in the native codebase and CTest +suites; **Plan 20 Slice 3** (Windows/MSVC, macOS/Apple Clang, remote execution, plus live `conan` CLI verification) and the remaining post-v1 tracks (**C, D, E2 `workspace.cpp`, E3 `vbs daemon`, & E4**) in [21 — Post-v1 expansion roadmap](21-expansion-roadmap.md) define the next phases. For implemented commands, targets, and workflow usage, see the [project README](../../README.md) and [verification record](../agent-workflow/VERIFICATION.md). @@ -31,8 +31,8 @@ Authority: [requirements](REQUIREMENTS.md), [architecture](ARCHITECTURE.md), | [17 — Registry web administration](17-registry-ui.md) | Implemented & Verified | [registry/web/](../../registry/web/index.html) | | [18 — Native self-hosting and VoidLibrary migration](18-self-host-voidlibrary.md) | Implemented & Verified | [VoidLibraryRecipe.cpp](../../recipes/VoidLibrary/VoidLibraryRecipe.cpp), [TestRegistryGen.cpp](../../src/SelfHost/TestRegistryGen.cpp) | | [19 — Quality, performance and CI](19-quality-performance-ci.md) | Implemented & Verified | [tests/](../../tests/CMakeLists.txt), [EngineBenchmarks.cpp](../../benchmarks/EngineBenchmarks.cpp), [.github/workflows/ci.yml](../../.github/workflows/ci.yml) | -| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | Slices 1 & 2A Implemented & Verified; 2B/2C & OS ports planned | [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp), [Translator.cpp](../../src/Provider/Translator.cpp) (bounded CMake & Meson native translation + unified fallback + `--native-foreign`); C driver, custom commands, Windows/macOS ports planned | -| [21 — Post-v1 expansion roadmap](21-expansion-roadmap.md) | Track A (A1–A3) & Track E1 Implemented; Tracks B–D, E2–E4 Planned | Five-track expansion roadmap (**Track A** zero-CMake `.native_builder()` self-host, full `VOID_TEST` suite in `build.cpp`, & bit-identical Stage 2 == Stage 3 bootstrap verified; Tracks B–E2/E4 planned) | +| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | Slices 1, 2A, 2B, & 2C Implemented & Verified; Slice 3 OS/remote ports planned | [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp), [Translator.cpp](../../src/Provider/Translator.cpp) (C/C++ CMake & Meson translation, Ninja `CUSTOM_COMMAND`, foreign C++20 `CXX_MODULES`, unified fallback & `--native-foreign`); Windows/macOS/remote execution planned | +| [21 — Post-v1 expansion roadmap](21-expansion-roadmap.md) | Track A, Track B (B1–B3, except live `conan` CLI), Track E1 & Track E3 IDE configs/query Implemented; Tracks C, D, E2, E3 daemon & E4 Planned | Five-track expansion roadmap (**Track A** zero-CMake self-host, **Track B** C driver / Ninja custom commands / CMake `CXX_MODULES`, **Track E1**, & **Track E3** `build.cpp` CompDB + `vbs ide` verified; Tracks C, D, E2, `vbs daemon`, & E4 planned) | ## Dependency graph diff --git a/include/Void/Build.hpp b/include/Void/Build.hpp index 3b076ff..4dd203b 100644 --- a/include/Void/Build.hpp +++ b/include/Void/Build.hpp @@ -32,6 +32,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 CStandard { Default, C11, C17, C23 }; enum class CxxStandard { Default, Cxx17, Cxx20, Cxx23, Cxx26 }; enum class LtoMode { None, Full, Thin }; enum class Sanitizer { Address, Undefined, Thread, Memory, Leak }; @@ -44,6 +45,8 @@ enum class Sanitizer { Address, Undefined, Thread, Memory, Leak }; [[nodiscard]] TargetKind parse_target_kind(std::string_view name); [[nodiscard]] std::string_view source_kind_name(SourceKind kind); [[nodiscard]] SourceKind parse_source_kind(std::string_view name); +[[nodiscard]] std::string_view c_standard_name(CStandard standard); +[[nodiscard]] CStandard parse_c_standard(std::string_view name); [[nodiscard]] std::string_view cxx_standard_name(CxxStandard standard); [[nodiscard]] CxxStandard parse_cxx_standard(std::string_view name); [[nodiscard]] std::string_view lto_mode_name(LtoMode mode); @@ -59,6 +62,7 @@ struct ProfileContext { std::vector compile_options; std::vector link_options; std::vector defines; + CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; LtoMode lto{LtoMode::None}; std::vector sanitizers; @@ -75,6 +79,7 @@ struct ProfileDescription { std::vector link_options; std::vector defines; std::optional compiler; + std::optional c_standard; std::optional cxx_standard; std::optional lto; std::vector sanitizers; @@ -183,6 +188,7 @@ struct TargetRecord { std::vector defines; std::vector link_options; std::vector prerequisites; + CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; std::string precompiled_header; bool unity_enabled{false}; @@ -248,6 +254,7 @@ class Target { Target &link(const Target &target, Visibility visibility = Visibility::Private); Target &link(const ImportedTarget &target, Visibility visibility = Visibility::Private); Target &depends_on(const Target &producer); + Target &c_standard(CStandard standard); Target &cxx_standard(CxxStandard standard); Target &precompiled_header(std::string header_path); Target &unity_build(bool enabled, std::size_t batch_size = 8); diff --git a/include/Void/Build/Editor/CompDb.hpp b/include/Void/Build/Editor/CompDb.hpp index 39974f7..9686ed1 100644 --- a/include/Void/Build/Editor/CompDb.hpp +++ b/include/Void/Build/Editor/CompDb.hpp @@ -51,6 +51,8 @@ struct PublishOptions { bool update_selection{false}; // False for watchers (never steal selection!). std::optional reserved_ticket; bool manage_project_root_alias{true}; + std::filesystem::path sdk_include_dir; + std::vector extra_build_sources; }; // Projects all compile actions across ALL configured enabled targets in `graph` @@ -59,6 +61,44 @@ struct PublishOptions { [[nodiscard]] std::vector project_editor_commands(const Graph::BuildGraph &graph); +// Projects build description files (`build.cpp`, `build.profiles.cpp`, `build-support/`, +// and extra sources) so clangd/IDEs index `` natively. +[[nodiscard]] std::vector project_build_descriptor_commands( + const std::filesystem::path &project_root, const std::filesystem::path &build_root, + const std::filesystem::path &sdk_include_dir, const std::filesystem::path &host_cxx_compiler, + const std::vector &extra_build_sources = {}); + +enum class IdeKind { Clangd, VsCode, CLion, Zed, All }; + +struct IdeConfigOptions { + std::filesystem::path project_root; + std::filesystem::path build_root; + std::filesystem::path sdk_include_dir; + std::filesystem::path vbs_executable{"vbs"}; + std::filesystem::path compdb_path; + IdeKind editor{IdeKind::All}; + bool force{false}; +}; + +struct IdeConfigReport { + std::vector written_files; + std::vector skipped_existing_files; +}; + +[[nodiscard]] Void::Result::Result +parse_ide_kind(std::string_view name); + +[[nodiscard]] std::string_view ide_kind_name(IdeKind kind); + +// Writes non-destructive IDE configurations (.clangd, .vscode/, .idea/, .zed/) for `graph`. +[[nodiscard]] Void::Result::Result +generate_ide_configs(const Graph::BuildGraph &graph, const IdeConfigOptions &options); + +// Emits versioned JSON workspace/target metadata for external IDE plugins (`vbs ide query`). +[[nodiscard]] std::string format_ide_query_json(const Graph::BuildGraph &graph, + const std::filesystem::path &compdb_path, + const std::filesystem::path &sdk_include_dir); + // Formats standard Clang JSONCompilationDatabase array (arguments/file/directory/output). [[nodiscard]] std::string format_compile_commands_json(const std::vector &entries); diff --git a/include/Void/Build/Graph/Graph.hpp b/include/Void/Build/Graph/Graph.hpp index 9818d4f..9f77e4e 100644 --- a/include/Void/Build/Graph/Graph.hpp +++ b/include/Void/Build/Graph/Graph.hpp @@ -42,6 +42,7 @@ struct ImportedTargetInterface { std::vector shared_libraries; std::vector runtime_files; std::vector generated_prerequisites; + std::map> module_bmis; }; enum class ActionKind { @@ -79,6 +80,8 @@ struct ActionNode { std::vector> physical_include_dirs; std::vector defines; std::vector compile_options; + bool is_c_source{false}; + CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; LtoMode lto{LtoMode::None}; std::vector sanitizers; @@ -98,6 +101,7 @@ struct ResolvedTargetSummary { std::vector expanded_sources; std::vector primary_outputs; std::vector runtime_shared_libraries; + std::map> exported_module_bmis; std::vector action_ids; }; diff --git a/include/Void/Build/Modules/ModuleScanner.hpp b/include/Void/Build/Modules/ModuleScanner.hpp index 5c9063e..1a14b2a 100644 --- a/include/Void/Build/Modules/ModuleScanner.hpp +++ b/include/Void/Build/Modules/ModuleScanner.hpp @@ -51,9 +51,10 @@ scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain, // Collates scanned module units into a cycle-free, duplicate-free, missing-import-checked // topological build plan with profile/compiler-isolated BMI paths and GCC mapper files (Plan 08). -[[nodiscard]] Void::Result::Result -collate_modules(const std::vector &units, const std::filesystem::path &bmi_root, - const std::string &context_isolation_key, std::string_view bmi_extension = ".gcm"); +[[nodiscard]] Void::Result::Result collate_modules( + const std::vector &units, const std::filesystem::path &bmi_root, + const std::string &context_isolation_key, std::string_view bmi_extension = ".gcm", + const std::map> &external_module_bmis = {}); // Compiles an explicitly declared header unit into an isolated BMI/PCM (Plan 08). [[nodiscard]] Void::Result::Result diff --git a/include/Void/Build/Provider/Translator.hpp b/include/Void/Build/Provider/Translator.hpp index ad3194f..26bc6ec 100644 --- a/include/Void/Build/Provider/Translator.hpp +++ b/include/Void/Build/Provider/Translator.hpp @@ -64,11 +64,12 @@ configure_cmake_for_translation(const ProviderRequest &request, const std::filesystem::path &configure_dir, std::stop_token stop = {}); -// Audits a configured CMake File API codemodel against Plan 20's bounded native subset: -// C++ STATIC_LIBRARY / SHARED_LIBRARY / OBJECT_LIBRARY / EXECUTABLE targets without -// generated sources, custom UTILITY rules, foreign C++20 module fileSets, precompiled -// headers, non-C++ languages, or untracked link fragments. Any unsupported construct is -// reported explicitly and never silently dropped. +// Audits a configured CMake File API codemodel against Plan 20/21's bounded native subset: +// C and C++ STATIC_LIBRARY / SHARED_LIBRARY / OBJECT_LIBRARY / EXECUTABLE targets, +// C++20 CXX_MODULES fileSets, and hermetic build.ninja CUSTOM_COMMAND generators / UTILITY +// targets whose declared outputs remain inside `configure_dir`. Any unsupported construct +// (console pools, .util-only/side-effect rules, out-of-tree writes, PCH, non-C/C++ languages, +// or untracked link fragments) is reported explicitly and never silently dropped. [[nodiscard]] Void::Result::Result audit_cmake_codemodel(const std::filesystem::path &configure_dir); @@ -96,9 +97,10 @@ configure_meson_for_translation(const ProviderRequest &request, const std::filesystem::path &configure_dir, std::stop_token stop = {}); -// Audits a configured Meson `meson-info/intro-targets.json` against Plan 20's bounded native -// subset: pure C++ `static library`, `shared library`, and `executable` targets without custom -// targets, generated sources, non-C++ languages, or untracked link artifacts. +// Audits a configured Meson `meson-info/intro-targets.json` against Plan 20/21's bounded native +// subset: C and C++ `static library`, `shared library`, `executable`, and hermetic `custom` +// targets / `generated_sources` backed by build.ninja CUSTOM_COMMAND rules without `run` +// targets, `console: true` pools, out-of-tree writes, non-C/C++ languages, or untracked links. [[nodiscard]] Void::Result::Result audit_meson_introspection(const std::filesystem::path &configure_dir); diff --git a/include/Void/Build/Toolchain/Driver.hpp b/include/Void/Build/Toolchain/Driver.hpp index 5886b78..f883872 100644 --- a/include/Void/Build/Toolchain/Driver.hpp +++ b/include/Void/Build/Toolchain/Driver.hpp @@ -18,16 +18,21 @@ namespace Void::Build::Toolchain { struct ToolchainCapabilities { CompilerFamily family{CompilerFamily::Gcc}; std::filesystem::path cxx_compiler; + std::filesystem::path c_compiler; std::filesystem::path archiver; std::optional module_scanner; std::string version_banner; std::string target_triple; std::string sysroot; std::string compiler_sha256; + std::string c_compiler_sha256; std::string archiver_sha256; std::vector default_include_dirs; std::map> relevant_env; + bool supports_c11{false}; + bool supports_c17{false}; + bool supports_c23{false}; bool supports_cxx17{false}; bool supports_cxx20{false}; bool supports_cxx23{false}; @@ -61,6 +66,8 @@ struct CompileRequest { std::vector> include_dirs; // (path, is_system) std::vector defines; std::vector compile_options; + bool is_c_source{false}; + CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; LtoMode lto{LtoMode::None}; std::vector sanitizers; diff --git a/src/Build.cpp b/src/Build.cpp index 4b6a53a..03ec822 100644 --- a/src/Build.cpp +++ b/src/Build.cpp @@ -266,6 +266,36 @@ SourceKind parse_source_kind(std::string_view name) { throw std::invalid_argument{"unknown source kind '" + std::string{name} + "'"}; } +std::string_view c_standard_name(CStandard standard) { + switch (standard) { + case CStandard::Default: + return "default"; + case CStandard::C11: + return "c11"; + case CStandard::C17: + return "c17"; + case CStandard::C23: + return "c23"; + } + throw std::invalid_argument{"unknown C standard"}; +} + +CStandard parse_c_standard(std::string_view name) { + if (name.empty() || name == "default") { + return CStandard::Default; + } + if (name == "c11" || name == "11") { + return CStandard::C11; + } + if (name == "c17" || name == "17" || name == "c18") { + return CStandard::C17; + } + if (name == "c23" || name == "23" || name == "c2x") { + return CStandard::C23; + } + throw std::invalid_argument{"unknown C standard '" + std::string{name} + "'"}; +} + std::string_view cxx_standard_name(CxxStandard standard) { switch (standard) { case CxxStandard::Default: @@ -451,6 +481,9 @@ ProfileContext Profiles::resolve(std::string_view name, if (desc->compiler) { context.compiler = *desc->compiler; } + if (desc->c_standard) { + context.c_standard = *desc->c_standard; + } if (desc->cxx_standard) { context.cxx_standard = *desc->cxx_standard; } @@ -499,6 +532,9 @@ std::string Profiles::to_json() const { if (p.compiler) { out += ",\"compiler\":" + json_quote(compiler_name(*p.compiler)); } + if (p.c_standard) { + out += ",\"c_standard\":" + json_quote(c_standard_name(*p.c_standard)); + } if (p.cxx_standard) { out += ",\"cxx_standard\":" + json_quote(cxx_standard_name(*p.cxx_standard)); } @@ -701,6 +737,12 @@ Target &Target::depends_on(const Target &producer) { return *this; } +Target &Target::c_standard(CStandard standard) { + (void)c_standard_name(standard); + owner(owner_)->targets.at(index_).c_standard = standard; + return *this; +} + Target &Target::cxx_standard(CxxStandard standard) { (void)cxx_standard_name(standard); owner(owner_)->targets.at(index_).cxx_standard = standard; @@ -1065,6 +1107,7 @@ std::string Project::to_json() const { ",\"compile_options\":" + json_array(profile.compile_options, json_quote) + ",\"link_options\":" + json_array(profile.link_options, json_quote) + ",\"defines\":" + json_array(profile.defines, json_quote) + + ",\"c_standard\":" + json_quote(c_standard_name(profile.c_standard)) + ",\"cxx_standard\":" + json_quote(cxx_standard_name(profile.cxx_standard)) + ",\"lto\":" + json_quote(lto_mode_name(profile.lto)) + ",\"sanitizers\":" + json_array(profile.sanitizers, [](Sanitizer s) { return json_quote(sanitizer_name(s)); }) + @@ -1104,6 +1147,7 @@ std::string Project::to_json() const { json_quote(visibility_name(link.visibility)) + '}'; }) + ",\"prerequisites\":" + json_array(target.prerequisites, json_quote) + + ",\"c_standard\":" + json_quote(c_standard_name(target.c_standard)) + ",\"cxx_standard\":" + json_quote(cxx_standard_name(target.cxx_standard)) + ",\"precompiled_header\":" + json_quote(target.precompiled_header) + ",\"unity_enabled\":" + std::string{target.unity_enabled ? "true" : "false"} + diff --git a/src/Config/Frontend.cpp b/src/Config/Frontend.cpp index 802db99..411475e 100644 --- a/src/Config/Frontend.cpp +++ b/src/Config/Frontend.cpp @@ -105,6 +105,7 @@ Void::Build::ProfileContext parse_kv_context(std::string_view text) { else if (key == "compiler") ctx.compiler = Void::Build::parse_compiler(val); else if (key == "os") ctx.os = val; else if (key == "architecture") ctx.architecture = val; + else if (key == "c_standard") ctx.c_standard = Void::Build::parse_c_standard(val); else if (key == "cxx_standard") ctx.cxx_standard = Void::Build::parse_cxx_standard(val); else if (key == "lto") ctx.lto = Void::Build::parse_lto_mode(val); else if (key == "sysroot") ctx.sysroot = val; @@ -182,6 +183,7 @@ std::string serialize_kv_context(const ProfileContext &ctx) { out += "compiler=" + std::string{compiler_name(ctx.compiler)} + "\n"; out += "os=" + ctx.os + "\n"; out += "architecture=" + ctx.architecture + "\n"; + out += "c_standard=" + std::string{Void::Build::c_standard_name(ctx.c_standard)} + "\n"; out += "cxx_standard=" + std::string{cxx_standard_name(ctx.cxx_standard)} + "\n"; out += "lto=" + std::string{lto_mode_name(ctx.lto)} + "\n"; out += "sysroot=" + ctx.sysroot + "\n"; @@ -629,6 +631,9 @@ discover_profiles(const CompiledDescriptor &descriptor, const FrontendOptions &o if (auto comp = get_str(*po, "compiler"); comp && !comp->empty()) { pd.compiler = parse_compiler(*comp); } + if (auto std_str = get_str(*po, "c_standard"); std_str && !std_str->empty()) { + pd.c_standard = Void::Build::parse_c_standard(*std_str); + } if (auto std_str = get_str(*po, "cxx_standard"); std_str && !std_str->empty()) { pd.cxx_standard = parse_cxx_standard(*std_str); } diff --git a/src/Editor/CompDb.cpp b/src/Editor/CompDb.cpp index 54b67b9..73638f6 100644 --- a/src/Editor/CompDb.cpp +++ b/src/Editor/CompDb.cpp @@ -46,6 +46,20 @@ std::string_view status_name(GenerationStatus s) { return "invalid"; } +std::string c_standard_flag(CStandard standard) { + switch (standard) { + case CStandard::Default: + return {}; + case CStandard::C11: + return "-std=c11"; + case CStandard::C17: + return "-std=c17"; + case CStandard::C23: + return "-std=c23"; + } + return {}; +} + std::string cxx_standard_flag(CxxStandard standard) { switch (standard) { case CxxStandard::Default: @@ -193,6 +207,48 @@ update_managed_root_alias(const std::filesystem::path &project_root, return true; } +std::string escape_xml_attr(std::string_view sv) { + std::string out; + out.reserve(sv.size()); + for (const char c : sv) { + switch (c) { + case '&': + out += "&"; + break; + case '<': + out += "<"; + break; + case '>': + out += ">"; + break; + case '"': + out += """; + break; + case '\'': + out += "'"; + break; + default: + out.push_back(c); + break; + } + } + return out; +} + +std::string workspace_var_path(const std::filesystem::path &project_root, + const std::filesystem::path &target, std::string_view prefix_var) { + const auto norm_root = project_root.lexically_normal(); + const auto norm_target = target.lexically_normal(); + if (!norm_root.empty() && Platform::path_is_within(norm_root, norm_target)) { + const auto rel = norm_target.lexically_relative(norm_root); + if (!rel.empty() && rel != ".") { + return std::string{prefix_var} + "/" + rel.generic_string(); + } + return std::string{prefix_var}; + } + return norm_target.string(); +} + } // namespace std::vector project_editor_commands(const Graph::BuildGraph &graph) { @@ -228,8 +284,14 @@ std::vector project_editor_commands(const Graph::BuildGraph if (!graph.toolchain.sysroot.empty()) { entry.arguments.push_back("--sysroot=" + graph.toolchain.sysroot); } - if (const auto std_flag = cxx_standard_flag(act.cxx_standard); !std_flag.empty()) { - entry.arguments.push_back(std_flag); + if (act.is_c_source) { + if (const auto std_flag = c_standard_flag(act.c_standard); !std_flag.empty()) { + entry.arguments.push_back(std_flag); + } + } else { + if (const auto std_flag = cxx_standard_flag(act.cxx_standard); !std_flag.empty()) { + entry.arguments.push_back(std_flag); + } } if (act.position_independent) { entry.arguments.push_back("-fPIC"); @@ -250,7 +312,7 @@ std::vector project_editor_commands(const Graph::BuildGraph entry.arguments.push_back("-fsanitize=" + list); entry.arguments.push_back("-fno-omit-frame-pointer"); } - if (act.precompiled_header) { + if (act.precompiled_header && !act.is_c_source) { entry.arguments.push_back("-include"); entry.arguments.push_back(act.precompiled_header->string()); } @@ -292,6 +354,76 @@ std::vector project_editor_commands(const Graph::BuildGraph return entries; } +std::vector project_build_descriptor_commands( + const std::filesystem::path &project_root, const std::filesystem::path &build_root, + const std::filesystem::path &sdk_include_dir, const std::filesystem::path &host_cxx_compiler, + const std::vector &extra_build_sources) { + std::vector entries; + if (sdk_include_dir.empty() || host_cxx_compiler.empty()) { + return entries; + } + + std::error_code ec; + const auto raw_canon = std::filesystem::weakly_canonical(project_root, ec); + const auto canon_root = (ec ? project_root : raw_canon).lexically_normal(); + const auto desc_obj_root = build_root / ".vbs" / "editor-desc"; + + std::vector candidates; + std::set seen; + auto push_if_file = [&](const std::filesystem::path &p) { + const auto norm = (p.is_absolute() ? p : (canon_root / p)).lexically_normal(); + if (std::filesystem::is_regular_file(norm, ec) && seen.insert(norm).second) { + candidates.push_back(norm); + } + }; + + push_if_file("build.cpp"); + push_if_file("build.profiles.cpp"); + const auto support_dir = canon_root / "build-support"; + if (std::filesystem::is_directory(support_dir, ec)) { + std::vector support_files; + for (const auto &ent : std::filesystem::recursive_directory_iterator(support_dir, ec)) { + if (!ent.is_regular_file(ec)) { + continue; + } + const auto ext = ent.path().extension().string(); + if (ext == ".cpp" || ext == ".cc" || ext == ".cxx") { + support_files.push_back(ent.path().lexically_normal()); + } + } + std::ranges::sort(support_files); + for (const auto &sf : support_files) { + push_if_file(sf); + } + } + for (const auto &extra : extra_build_sources) { + push_if_file(extra); + } + + const bool has_support = std::filesystem::is_directory(support_dir, ec); + for (const auto &src : candidates) { + const std::string tag = Util::sha256_hex(src.string()).substr(0, 12); + const auto out_obj = desc_obj_root / (src.filename().string() + "_" + tag + ".o"); + EditorCommandEntry entry; + entry.directory = canon_root; + entry.file = src; + entry.output = out_obj; + entry.target_name = "__vbs_build_description"; + entry.arguments = {host_cxx_compiler.string(), "-std=c++26", "-I", + sdk_include_dir.lexically_normal().string()}; + if (has_support) { + entry.arguments.push_back("-I"); + entry.arguments.push_back(support_dir.string()); + } + entry.arguments.push_back("-c"); + entry.arguments.push_back(src.string()); + entry.arguments.push_back("-o"); + entry.arguments.push_back(out_obj.string()); + entries.push_back(std::move(entry)); + } + return entries; +} + std::string format_compile_commands_json(const std::vector &entries) { using Util::json_array; using Util::json_quote; @@ -339,7 +471,20 @@ reserve_selection_ticket(const std::filesystem::path &project_root, Void::Result::Result publish_profile_compdb(const Graph::BuildGraph &graph, const PublishOptions &options) { - const auto entries = project_editor_commands(graph); + auto entries = project_editor_commands(graph); + if (!options.sdk_include_dir.empty()) { + auto desc_entries = project_build_descriptor_commands( + options.project_root, options.build_root, options.sdk_include_dir, + graph.toolchain.cxx_compiler, options.extra_build_sources); + for (auto &de : desc_entries) { + const bool already = std::ranges::any_of(entries, [&](const EditorCommandEntry &ex) { + return ex.file.lexically_normal() == de.file.lexically_normal(); + }); + if (!already) { + entries.push_back(std::move(de)); + } + } + } const std::string compdb_json = format_compile_commands_json(entries); const std::string gen_id = Util::sha256_hex(graph.profile_identity + "\n" + compdb_json).substr(0, 16); @@ -571,4 +716,377 @@ recover_editor_pointers(const std::filesystem::path &project_root) { return {}; } +Void::Result::Result parse_ide_kind(std::string_view name) { + if (name == "all" || name == "All") { + return IdeKind::All; + } + if (name == "clangd" || name == "Clangd") { + return IdeKind::Clangd; + } + if (name == "vscode" || name == "VsCode") { + return IdeKind::VsCode; + } + if (name == "clion" || name == "CLion") { + return IdeKind::CLion; + } + if (name == "zed" || name == "Zed") { + return IdeKind::Zed; + } + return std::unexpected{make_error( + std::format("unknown IDE kind '{}' (expected: all, clangd, vscode, clion, zed)", name))}; +} + +std::string_view ide_kind_name(IdeKind kind) { + switch (kind) { + case IdeKind::Clangd: + return "clangd"; + case IdeKind::VsCode: + return "vscode"; + case IdeKind::CLion: + return "clion"; + case IdeKind::Zed: + return "zed"; + case IdeKind::All: + return "all"; + } + return "all"; +} + +Void::Result::Result +generate_ide_configs(const Graph::BuildGraph &graph, const IdeConfigOptions &options) { + using Util::json_array; + using Util::json_quote; + + const auto proj_root = + (options.project_root.empty() ? graph.project_root : options.project_root) + .lexically_normal(); + const auto build_root = + (options.build_root.empty() ? graph.profile_build_dir.parent_path().parent_path() + : options.build_root) + .lexically_normal(); + const auto vbs_bin = + options.vbs_executable.empty() ? std::string{"vbs"} : options.vbs_executable.string(); + + std::filesystem::path compdb_dir = build_root; + if (!options.compdb_path.empty()) { + compdb_dir = + options.compdb_path.has_parent_path() ? options.compdb_path.parent_path() : compdb_dir; + } + compdb_dir = compdb_dir.lexically_normal(); + std::string compdb_rel_or_abs = compdb_dir.string(); + if (Platform::path_is_within(proj_root, compdb_dir)) { + const auto rel = compdb_dir.lexically_relative(proj_root); + compdb_rel_or_abs = rel.empty() ? "." : rel.generic_string(); + } + + IdeConfigReport report; + std::error_code ec; + auto write_ide_file = + [&](const std::filesystem::path &path, + std::string_view content) -> Void::Result::Result { + if (!options.force && + (std::filesystem::exists(path, ec) || std::filesystem::is_symlink(path, ec))) { + report.skipped_existing_files.push_back(path); + return {}; + } + auto w = Platform::atomic_write_file(path, content, false); + if (!w) { + return std::unexpected{w.error()}; + } + report.written_files.push_back(path); + return {}; + }; + + const bool want_all = (options.editor == IdeKind::All); + + // 1. .clangd configuration (GCC-16 flag sanitization + CompilationDatabase pointer). + if (want_all || options.editor == IdeKind::Clangd) { + std::string yaml = "# Generated by VoidBuildSystem (`vbs ide generate`). Re-run with " + "`--force` to update.\n" + "CompileFlags:\n" + " CompilationDatabase: " + + json_quote(compdb_rel_or_abs) + + "\n" + " Remove:\n" + " - -freflection\n" + " - -fmodules\n" + " - -fmodules-ts\n" + " - \"-fmodule-mapper=*\"\n" + " - \"-frandom-seed=*\"\n" + " - \"-fdeps-format=*\"\n" + " - \"-fdeps-file=*\"\n" + " - \"-fdeps-target=*\"\n"; + if (auto r = write_ide_file(proj_root / ".clangd", yaml); !r) { + return std::unexpected{r.error()}; + } + } + + struct RunnableTarget { + std::string name; + bool is_test{false}; + std::filesystem::path program; + }; + std::vector runnables; + std::vector buildable_targets; + for (const auto &t : graph.targets) { + if (!t.enabled) { + continue; + } + if (t.kind == TargetKind::Executable || t.kind == TargetKind::Test || + t.kind == TargetKind::StaticLibrary || t.kind == TargetKind::SharedLibrary) { + buildable_targets.push_back(t.name); + } + if ((t.kind == TargetKind::Executable || t.kind == TargetKind::Test) && + !t.primary_outputs.empty()) { + runnables.push_back({t.name, t.kind == TargetKind::Test, t.primary_outputs.front()}); + } + } + + // 2. VS Code / Cursor / Antigravity (.vscode/tasks.json, launch.json, settings.json). + if (want_all || options.editor == IdeKind::VsCode) { + auto make_vs_task = [&](const std::string &label, const std::vector &args, + const std::string &group, bool is_default) { + std::string t = " {\n"; + t += " \"label\": " + json_quote(label) + ",\n"; + t += " \"type\": \"process\",\n"; + t += " \"command\": " + json_quote(vbs_bin) + ",\n"; + t += " \"args\": " + json_array(args, json_quote) + ",\n"; + t += " \"options\": {\"cwd\": \"${workspaceFolder}\"},\n"; + if (!group.empty()) { + if (is_default) { + t += " \"group\": {\"kind\": " + json_quote(group) + + ", \"isDefault\": true},\n"; + } else { + t += " \"group\": " + json_quote(group) + ",\n"; + } + } + t += " \"problemMatcher\": [\"$gcc\"]\n"; + t += " }"; + return t; + }; + + std::vector vs_tasks; + vs_tasks.push_back(make_vs_task("vbs: build (" + graph.profile.name + ")", + {"build", "--profile", graph.profile.name}, "build", true)); + vs_tasks.push_back(make_vs_task("vbs: test (" + graph.profile.name + ")", + {"test", "--profile", graph.profile.name}, "test", true)); + vs_tasks.push_back(make_vs_task("vbs: clean", {"clean"}, "", false)); + vs_tasks.push_back(make_vs_task("vbs: refresh compile_commands.json", + {"compdb", "export", "--profile", graph.profile.name}, "", + false)); + for (const auto &tname : buildable_targets) { + vs_tasks.push_back(make_vs_task( + "vbs: build " + tname, + {"build", "--profile", graph.profile.name, "--target", tname}, "build", false)); + } + for (const auto &rt : runnables) { + if (rt.is_test) { + vs_tasks.push_back(make_vs_task( + "vbs: test " + rt.name, + {"test", "--profile", graph.profile.name, "--target", rt.name}, "test", false)); + } + } + + std::string tasks_json = "{\n \"version\": \"2.0.0\",\n \"tasks\": [\n"; + for (std::size_t i = 0; i < vs_tasks.size(); ++i) { + tasks_json += vs_tasks[i]; + if (i + 1 < vs_tasks.size()) { + tasks_json += ','; + } + tasks_json += '\n'; + } + tasks_json += " ]\n}\n"; + if (auto r = write_ide_file(proj_root / ".vscode" / "tasks.json", tasks_json); !r) { + return std::unexpected{r.error()}; + } + + std::string launch_json = "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n"; + for (std::size_t i = 0; i < runnables.size(); ++i) { + const auto &rt = runnables[i]; + const std::string prog = + workspace_var_path(proj_root, rt.program, "${workspaceFolder}"); + launch_json += " {\n"; + launch_json += " \"name\": " + json_quote("Debug " + rt.name + " (vbs)") + ",\n"; + launch_json += " \"type\": \"cppdbg\",\n"; + launch_json += " \"request\": \"launch\",\n"; + launch_json += " \"program\": " + json_quote(prog) + ",\n"; + launch_json += " \"args\": [],\n"; + launch_json += " \"stopAtEntry\": false,\n"; + launch_json += " \"cwd\": \"${workspaceFolder}\",\n"; + launch_json += " \"MIMode\": \"gdb\",\n"; + launch_json += " \"preLaunchTask\": " + json_quote("vbs: build " + rt.name) + "\n"; + launch_json += " }"; + if (i + 1 < runnables.size()) { + launch_json += ','; + } + launch_json += '\n'; + } + launch_json += " ]\n}\n"; + if (auto r = write_ide_file(proj_root / ".vscode" / "launch.json", launch_json); !r) { + return std::unexpected{r.error()}; + } + + const std::filesystem::path compdb_file = options.compdb_path.empty() + ? (compdb_dir / "compile_commands.json") + : options.compdb_path; + const std::string vs_compdb = + workspace_var_path(proj_root, compdb_file, "${workspaceFolder}"); + const std::string vs_compdb_dir = + workspace_var_path(proj_root, compdb_dir, "${workspaceFolder}"); + std::string settings_json = + "{\n" + " \"C_Cpp.default.compileCommands\": " + + json_quote(vs_compdb) + + ",\n" + " \"C_Cpp.intelliSenseEngine\": \"disabled\",\n" + " \"clangd.arguments\": " + + json_array(std::vector{"--compile-commands-dir=" + vs_compdb_dir, + "--header-insertion=never"}, + json_quote) + + ",\n" + " \"files.exclude\": {\n" + " \"**/.vbs\": true\n" + " }\n" + "}\n"; + if (auto r = write_ide_file(proj_root / ".vscode" / "settings.json", settings_json); !r) { + return std::unexpected{r.error()}; + } + } + + // 3. Zed (.zed/tasks.json, .zed/debug.json). + if (want_all || options.editor == IdeKind::Zed) { + auto make_zed_task = [&](const std::string &label, const std::vector &args) { + return " {\"label\": " + json_quote(label) + ", \"command\": " + json_quote(vbs_bin) + + ", \"args\": " + json_array(args, json_quote) + + ", \"cwd\": \"$ZED_WORKTREE_ROOT\"}"; + }; + std::vector ztasks; + ztasks.push_back(make_zed_task("vbs: build", {"build", "--profile", graph.profile.name})); + ztasks.push_back(make_zed_task("vbs: test", {"test", "--profile", graph.profile.name})); + ztasks.push_back(make_zed_task("vbs: clean", {"clean"})); + for (const auto &rt : runnables) { + ztasks.push_back( + make_zed_task("vbs: build " + rt.name, + {"build", "--profile", graph.profile.name, "--target", rt.name})); + if (rt.is_test) { + ztasks.push_back( + make_zed_task("vbs: test " + rt.name, + {"test", "--profile", graph.profile.name, "--target", rt.name})); + } + } + std::string ztasks_json = "[\n"; + for (std::size_t i = 0; i < ztasks.size(); ++i) { + ztasks_json += ztasks[i]; + if (i + 1 < ztasks.size()) { + ztasks_json += ','; + } + ztasks_json += '\n'; + } + ztasks_json += "]\n"; + if (auto r = write_ide_file(proj_root / ".zed" / "tasks.json", ztasks_json); !r) { + return std::unexpected{r.error()}; + } + + std::string zdebug_json = "[\n"; + for (std::size_t i = 0; i < runnables.size(); ++i) { + const auto &rt = runnables[i]; + const std::string prog = + workspace_var_path(proj_root, rt.program, "$ZED_WORKTREE_ROOT"); + zdebug_json += " {\n"; + zdebug_json += " \"label\": " + json_quote("Debug " + rt.name + " (vbs)") + ",\n"; + zdebug_json += " \"adapter\": \"CodeLLDB\",\n"; + zdebug_json += " \"request\": \"launch\",\n"; + zdebug_json += " \"program\": " + json_quote(prog) + ",\n"; + zdebug_json += " \"cwd\": \"$ZED_WORKTREE_ROOT\"\n"; + zdebug_json += " }"; + if (i + 1 < runnables.size()) { + zdebug_json += ','; + } + zdebug_json += '\n'; + } + zdebug_json += "]\n"; + if (auto r = write_ide_file(proj_root / ".zed" / "debug.json", zdebug_json); !r) { + return std::unexpected{r.error()}; + } + } + + // 4. CLion Custom Build Targets (.idea/customTargets.xml). + if (want_all || options.editor == IdeKind::CLion) { + const std::string vbs_xml = escape_xml_attr(vbs_bin); + const std::string prof_xml = escape_xml_attr(graph.profile.name); + std::string xml = "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"; + if (auto r = write_ide_file(proj_root / ".idea" / "customTargets.xml", xml); !r) { + return std::unexpected{r.error()}; + } + } + + return report; +} + +std::string format_ide_query_json(const Graph::BuildGraph &graph, + const std::filesystem::path &compdb_path, + const std::filesystem::path &sdk_include_dir) { + using Util::json_array; + using Util::json_quote; + + const auto build_root = graph.profile_build_dir.parent_path().parent_path().lexically_normal(); + std::string out = "{"; + out += "\"schema_version\":1"; + out += ",\"project_root\":" + json_quote(graph.project_root.string()); + out += ",\"build_root\":" + json_quote(build_root.string()); + out += ",\"profile\":" + json_quote(graph.profile.name); + out += ",\"profile_identity\":" + json_quote(graph.profile_identity); + out += ",\"compiler_family\":" + json_quote(compiler_name(graph.toolchain.family)); + out += ",\"c_compiler\":" + json_quote(graph.toolchain.c_compiler.string()); + out += ",\"cxx_compiler\":" + json_quote(graph.toolchain.cxx_compiler.string()); + out += ",\"sdk_include_dir\":" + json_quote(sdk_include_dir.string()); + out += ",\"compdb_path\":" + json_quote(compdb_path.string()); + out += ",\"targets\":["; + for (std::size_t i = 0; i < graph.targets.size(); ++i) { + const auto &t = graph.targets[i]; + if (i > 0) { + out += ','; + } + const bool is_exec = (t.kind == TargetKind::Executable); + const bool is_test = (t.kind == TargetKind::Test); + out += "{\"name\":" + json_quote(t.name); + out += ",\"kind\":" + json_quote(target_kind_name(t.kind)); + out += ",\"enabled\":" + std::string{t.enabled ? "true" : "false"}; + out += ",\"is_executable\":" + std::string{is_exec ? "true" : "false"}; + out += ",\"is_test\":" + std::string{is_test ? "true" : "false"}; + out += ",\"sources\":" + json_array(t.expanded_sources, [](const std::filesystem::path &p) { + return json_quote(p.string()); + }); + out += ",\"primary_outputs\":" + + json_array(t.primary_outputs, + [](const std::filesystem::path &p) { return json_quote(p.string()); }); + out += ",\"runtime_shared_libraries\":" + + json_array(t.runtime_shared_libraries, + [](const std::filesystem::path &p) { return json_quote(p.string()); }); + out += '}'; + } + out += "]}\n"; + return out; +} + } // namespace Void::Build::Editor diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp index f960a13..5e44a6b 100644 --- a/src/Graph/Graph.cpp +++ b/src/Graph/Graph.cpp @@ -110,6 +110,10 @@ bool is_module_source_extension(const std::filesystem::path &p) { 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" || @@ -221,6 +225,7 @@ ProjectDescription::from_json(std::string_view json_text) { 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")) { @@ -292,6 +297,7 @@ ProjectDescription::from_json(std::string_view json_text) { } } 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); @@ -661,6 +667,8 @@ lower_project_graph(const ProjectDescription &description, std::vector exported_objects; std::vector exported_link_options; std::vector exported_prerequisite_actions; + std::map> exported_module_bmis; + std::map> exported_module_action_ids; }; std::map> computed; @@ -731,6 +739,7 @@ lower_project_graph(const ProjectDescription &description, } 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); } } @@ -783,7 +792,13 @@ lower_project_graph(const ProjectDescription &description, for (const auto &in : t.action_inputs) { const auto p = std::filesystem::path{in}; - act.declared_inputs.push_back(p.is_absolute() ? p : (canonical_root / p)); + 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}; @@ -813,6 +828,8 @@ lower_project_graph(const ProjectDescription &description, std::vector effective_link_opts = description.profile.link_options; // Ordered transitive link inputs (preserve exact order; never sort!). + std::map> external_module_bmis; + std::map> external_module_action_ids; std::vector link_objects; std::vector link_static_libs; std::vector link_shared_libs; @@ -894,6 +911,12 @@ lower_project_graph(const ProjectDescription &description, 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(), @@ -905,6 +928,12 @@ lower_project_graph(const ProjectDescription &description, 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! @@ -979,6 +1008,9 @@ lower_project_graph(const ProjectDescription &description, 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(), @@ -988,6 +1020,9 @@ lower_project_graph(const ProjectDescription &description, 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) || @@ -1081,12 +1116,15 @@ lower_project_graph(const ProjectDescription &description, 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++ standard, LTO, sanitizers (target overrides/extends profile). + // 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; @@ -1251,6 +1289,7 @@ lower_project_graph(const ProjectDescription &description, std::filesystem::path logical_src; std::filesystem::path physical_src; std::vector tu_opts; + bool is_c{false}; bool is_explicit_module{false}; bool has_per_file_override{false}; }; @@ -1265,6 +1304,7 @@ lower_project_graph(const ProjectDescription &description, 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()) { @@ -1284,7 +1324,7 @@ lower_project_graph(const ProjectDescription &description, const auto norm_phys = cu.physical_src.lexically_normal(); all_phys.push_back(norm_phys); raw_by_phys[norm_phys] = &cu; - if (cu.is_explicit_module || cu.has_per_file_override) { + if (cu.is_c || cu.is_explicit_module || cu.has_per_file_override) { excluded_phys.push_back(norm_phys); } } @@ -1310,14 +1350,18 @@ lower_project_graph(const ProjectDescription &description, compile_units = std::move(raw_units); } - // 6. Compile actions (C++20/23/26 P1689 named modules & partitions OR regular TUs). + // 6. Compile actions (C++20/23/26 P1689 named modules & partitions OR regular C/C++ TUs). std::vector 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 shared_hu_mapper; if (!gcc_header_unit_mapper_lines.empty() && toolchain.family == CompilerFamily::Gcc && - !has_module_sources) { + !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); @@ -1326,9 +1370,121 @@ lower_project_graph(const ProjectDescription &description, } } - if (has_module_sources) { + auto emit_regular_compile_action = + [&](const CompileUnitSpec &cu) -> Void::Result::Result { + 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) ? CxxStandard::Cxx20 : eff_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); @@ -1336,6 +1492,12 @@ lower_project_graph(const ProjectDescription &description, scanned.reserve(compile_units.size()); std::map 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, @@ -1347,8 +1509,9 @@ lower_project_graph(const ProjectDescription &description, scanned.push_back(std::move(*scan)); } - auto collated = Modules::collate_modules( - scanned, target_bmi_root, graph.profile_identity + ":" + t.name, bmi_ext); + 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()}; } @@ -1365,10 +1528,14 @@ lower_project_graph(const ProjectDescription &description, std::vector> bmis; std::set seen; std::queue 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(); @@ -1376,6 +1543,10 @@ lower_project_graph(const ProjectDescription &description, 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()) { @@ -1386,6 +1557,13 @@ lower_project_graph(const ProjectDescription &description, } } } + 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) { @@ -1397,6 +1575,10 @@ lower_project_graph(const ProjectDescription &description, "_" + 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 unit_deps = target_prereq_actions; if (pch_action_id) { add_unique_str(unit_deps, *pch_action_id); @@ -1408,8 +1590,25 @@ lower_project_graph(const ProjectDescription &description, 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) { - add_unique_str(unit_deps, provider_action_by_module.at(req_mod)); + 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) { @@ -1447,7 +1646,7 @@ lower_project_graph(const ProjectDescription &description, req.include_dirs = physical_includes; req.defines = effective_defines; req.compile_options = tu_opts; - req.cxx_standard = mod_std; + req.cxx_standard = tu_std; req.lto = eff_lto; req.sanitizers = eff_sans; req.position_independent = pic; @@ -1480,6 +1679,14 @@ lower_project_graph(const ProjectDescription &description, (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); } @@ -1502,7 +1709,7 @@ lower_project_graph(const ProjectDescription &description, act.physical_include_dirs = physical_includes; act.defines = effective_defines; act.compile_options = tu_opts; - act.cxx_standard = mod_std; + act.cxx_standard = tu_std; act.lto = eff_lto; act.sanitizers = eff_sans; act.position_independent = pic; @@ -1516,6 +1723,20 @@ lower_project_graph(const ProjectDescription &description, 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); @@ -1545,7 +1766,7 @@ lower_project_graph(const ProjectDescription &description, breq.include_dirs = physical_includes; breq.defines = effective_defines; breq.compile_options = bmi_opts; - breq.cxx_standard = mod_std; + breq.cxx_standard = tu_std; breq.lto = eff_lto; breq.sanitizers = eff_sans; breq.position_independent = pic; @@ -1596,6 +1817,21 @@ lower_project_graph(const ProjectDescription &description, 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(); @@ -1606,7 +1842,7 @@ lower_project_graph(const ProjectDescription &description, oreq.source_file = node.bmi_output_path; oreq.output_object = obj_path; oreq.response_file_dir = rsp_root; - oreq.cxx_standard = mod_std; + oreq.cxx_standard = tu_std; oreq.lto = eff_lto; oreq.sanitizers = eff_sans; oreq.position_independent = pic; @@ -1661,7 +1897,7 @@ lower_project_graph(const ProjectDescription &description, req.include_dirs = physical_includes; req.defines = effective_defines; req.compile_options = cu.tu_opts; - req.cxx_standard = mod_std; + req.cxx_standard = tu_std; req.lto = eff_lto; req.sanitizers = eff_sans; req.position_independent = pic; @@ -1703,7 +1939,7 @@ lower_project_graph(const ProjectDescription &description, act.physical_include_dirs = physical_includes; act.defines = effective_defines; act.compile_options = cu.tu_opts; - act.cxx_standard = mod_std; + act.cxx_standard = tu_std; act.lto = eff_lto; act.sanitizers = eff_sans; act.position_independent = pic; @@ -1725,101 +1961,9 @@ lower_project_graph(const ProjectDescription &description, } } else { for (const auto &cu : compile_units) { - 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.cxx_standard = - (!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 = 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 (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); - } + if (auto r = emit_regular_compile_action(cu); !r) { + return std::unexpected{r.error()}; } - - 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 &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.cxx_standard = req.cxx_standard; - act.lto = eff_lto; - act.sanitizers = eff_sans; - act.position_independent = pic; - act.precompiled_header = pch_include_prefix; - act.dependencies = target_prereq_actions; - 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)); } } @@ -1938,6 +2082,7 @@ lower_project_graph(const ProjectDescription &description, 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)); } diff --git a/src/Main.cpp b/src/Main.cpp index 54a3d01..1b1a0ea 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -798,6 +798,8 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { popts.build_root = build_root; popts.update_selection = (*opts.editor_profile == prof_name); popts.reserved_ticket = *reserved_ticket; + popts.sdk_include_dir = fopts.sdk_include_dir; + popts.extra_build_sources = extra_build_sources; if (auto pub_db = Editor::publish_profile_compdb(*graph, popts); pub_db) { Void::Log::debug("CompDb", "[{}] Published compile_commands.json ({})", prof_name, pub_db->compdb_path.string()); @@ -1707,6 +1709,222 @@ int execute_graph_command(const GraphCmdOptions &opts) { return 0; } +struct IdeCmdOptions { + std::string project_arg; + std::optional build_arg; + std::string profile_name{"debug"}; + std::optional compiler_arg; + std::string editor_name{"all"}; + bool force{false}; +}; + +int execute_ide_command(std::string_view sub, const IdeCmdOptions &opts) { + Editor::IdeKind ide_kind = Editor::IdeKind::All; + if (sub == "generate") { + auto parsed_kind = Editor::parse_ide_kind(opts.editor_name); + if (!parsed_kind) { + std::cerr << "vbs ide: " << parsed_kind.error().message() << '\n'; + return 2; + } + ide_kind = *parsed_kind; + } + + std::optional compiler_override; + if (opts.compiler_arg) { + try { + compiler_override = parse_compiler(*opts.compiler_arg); + } catch (const std::exception &ex) { + std::cerr << "vbs ide: " << ex.what() << '\n'; + return 2; + } + } + + const std::filesystem::path project_root{opts.project_arg}; + const std::filesystem::path build_root = + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); + const auto fopts = make_frontend_opts(project_root, build_root, {}); + + auto compiled = Config::compile_descriptor(fopts); + if (!compiled) { + std::cerr << "vbs ide: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs ide: " << profs.error().message() << '\n'; + return 1; + } + + ProfileContext ctx; + try { + ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + std::cerr << "vbs ide: " << ex.what() << '\n'; + return 2; + } + + auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes"); + if (!tc) { + std::cerr << "vbs ide: " << tc.error().message() << '\n'; + return 1; + } + + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs ide: " << desc.error().message() << '\n'; + return 1; + } + + // MetadataOnly provider loading: inspect cached provider exports if already built; never + // run foreign configure/build/fetch. On unbuilt checkouts, synthesize empty placeholders so + // IDE configuration still succeeds before the initial build. + std::map> imported_targets; + std::vector toml_deps; + std::error_code ec; + for (const auto &df : desc->dependency_files) { + const auto p = std::filesystem::path{df}.is_absolute() ? std::filesystem::path{df} + : (project_root / df); + if (auto loaded = Package::load_dependencies_toml(p); loaded) { + toml_deps.insert(toml_deps.end(), loaded->begin(), loaded->end()); + } + } + auto merged_deps = Package::merge_dependencies(desc->dependencies, toml_deps); + if (merged_deps && !merged_deps->empty()) { + std::optional pinned_lock; + if (auto pl = Package::load_pinned_lock(project_root / "vbs.lock"); pl) { + pinned_lock = *pl; + } + auto resolved = resolve_and_materialize_deps(ctx, *merged_deps, project_root, build_root, + pinned_lock, true, false); + if (resolved) { + for (const auto &[dep_rec, mat] : resolved->materialized) { + DependencyRecord effective_dep = dep_rec; + if (effective_dep.builder.empty()) { + if (std::filesystem::is_regular_file(mat.source_dir / "build.cpp", ec)) { + effective_dep.builder = "native"; + } else if (std::filesystem::is_regular_file(mat.source_dir / "CMakeLists.txt", + ec)) { + effective_dep.builder = "cmake"; + } else if (std::filesystem::is_regular_file(mat.source_dir / "meson.build", + ec)) { + effective_dep.builder = "meson"; + } + } + if (!effective_dep.builder.empty()) { + Provider::ProviderRequest preq{effective_dep, + mat, + ctx, + *tc, + build_root / ".vbs" / "providers", + Provider::ProviderMode::MetadataOnly, + {}, + fopts.sdk_include_dir, + fopts.sdk_source_dir, + fopts.sdk_library_path.empty() + ? std::nullopt + : std::optional{fopts.sdk_library_path}, + nullptr, + 0}; + auto exp = Provider::resolve_foreign_provider(preq); + if (exp && !exp->stale_needs_build) { + for (const auto &[k, v] : exp->targets) { + imported_targets[k] = v; + } + } + } + } + } + } + for (const auto &t : desc->targets) { + for (const auto &link : t.links) { + if (link.kind == LinkKind::Imported) { + const std::string key = link.dependency + "::" + link.target; + if (!imported_targets.contains(key) && !imported_targets.contains(link.target)) { + Void::Log::warn( + "Ide", + "Dependency target '{}' is not built yet; run 'vbs build' to populate " + "imported include paths", + key); + imported_targets.emplace( + key, Graph::ImportedTargetInterface{ + link.dependency, link.target, {}, {}, {}, {}, {}, {}, {}, {}, {}}); + } + } + } + } + + const auto snap_inputs = collect_snapshot_inputs(*desc, project_root); + Snapshot::SnapshotOptions sopts; + sopts.project_root = project_root; + sopts.snapshot_store_dir = build_root / ".vbs" / "snapshots"; + sopts.reproducibility_epoch = ctx.reproducibility_epoch; + sopts.materialize = false; + auto snap = + Snapshot::capture_snapshot(sopts, snap_inputs.explicit_files, snap_inputs.scan_roots); + if (!snap) { + std::cerr << "vbs ide: " << snap.error().message() << '\n'; + return 1; + } + + Graph::GraphLowerOptions gopts{project_root, build_root, &(*snap), std::move(imported_targets), + 32768}; + auto graph = Graph::lower_project_graph(*desc, *tc, gopts); + if (!graph) { + std::cerr << "vbs ide: " << graph.error().message() << '\n'; + return 1; + } + + const auto existing_sel = Editor::read_selection_state(project_root).value_or(std::nullopt); + Editor::PublishOptions popts; + popts.project_root = project_root; + popts.build_root = build_root; + popts.update_selection = !existing_sel.has_value(); + popts.sdk_include_dir = fopts.sdk_include_dir; + auto pub = Editor::publish_profile_compdb(*graph, popts); + if (!pub) { + std::cerr << "vbs ide: " << pub.error().message() << '\n'; + return 1; + } + + const auto root_compdb = build_root / "compile_commands.json"; + const auto compdb_path = + std::filesystem::exists(root_compdb, ec) ? root_compdb : pub->compdb_path; + + if (sub == "query") { + std::cout << Editor::format_ide_query_json(*graph, compdb_path, fopts.sdk_include_dir); + return 0; + } + + std::filesystem::path vbs_exe{"vbs"}; + if (const auto self_exe = std::filesystem::read_symlink("/proc/self/exe", ec); + !ec && !self_exe.empty()) { + vbs_exe = self_exe; + } + + Editor::IdeConfigOptions ide_opts; + ide_opts.project_root = project_root; + ide_opts.build_root = build_root; + ide_opts.sdk_include_dir = fopts.sdk_include_dir; + ide_opts.vbs_executable = vbs_exe; + ide_opts.compdb_path = compdb_path; + ide_opts.editor = ide_kind; + ide_opts.force = opts.force; + + auto rep = Editor::generate_ide_configs(*graph, ide_opts); + if (!rep) { + std::cerr << "vbs ide: " << rep.error().message() << '\n'; + return 1; + } + for (const auto &w : rep->written_files) { + std::cout << "wrote " << w.string() << '\n'; + } + for (const auto &s : rep->skipped_existing_files) { + std::cout << "preserved " << s.string() << " (pass --force to overwrite)\n"; + } + return 0; +} + } // namespace int main(int argc, char **argv) { @@ -1742,6 +1960,8 @@ int main(int argc, char **argv) { clean_opts.build_arg = (std::filesystem::path{cwd} / "build").string(); GraphCmdOptions graph_opts; graph_opts.project_arg = cwd; + IdeCmdOptions ide_opts; + ide_opts.project_arg = cwd; auto add_log_flags = [&](Void::Argparse::Parser &p, bool allow_short_v = true) { p.flag("--verbose", allow_short_v ? "-v" : "", "Enable verbose debug logs", verbose) @@ -1932,6 +2152,26 @@ int main(int argc, char **argv) { .option_default("--format", "-f", "Output format (dot|json)", graph_opts.format, "dot"); add_log_flags(graph_cmd); + auto &ide_cmd = + root.subcommand("ide", "Generate editor/IDE configs and query workspace metadata"); + auto configure_ide_common = [&](Void::Argparse::Parser &p) { + p.option_default("--project", "-C", "Project directory", ide_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", ide_opts.build_arg) + .option_default("--profile", "-p", "Profile name", ide_opts.profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", + ide_opts.compiler_arg); + add_log_flags(p); + }; + auto &ide_gen_cmd = + ide_cmd.subcommand("generate", "Generate .clangd, .vscode/, .zed/, and .idea/ IDE configs"); + configure_ide_common(ide_gen_cmd); + ide_gen_cmd + .option_default("--editor", "-e", "Editor preset (all|clangd|vscode|clion|zed)", + ide_opts.editor_name, "all") + .flag("--force", "", "Overwrite existing IDE configuration files", ide_opts.force); + configure_ide_common( + ide_cmd.subcommand("query", "Emit versioned JSON workspace, target, and compdb metadata")); + const auto parsed = root.parse_detailed(argc, argv); if (parsed.is_help()) { std::cout << parsed.message; @@ -1958,7 +2198,9 @@ int main(int argc, char **argv) { const bool machine_quiet_default = (cmd == "describe") || (cmd == "graph") || (cmd == "doctor") || (cmd == "compdb" && parsed.matched_command_path.size() >= 2 && - parsed.matched_command_path[1] == "show"); + parsed.matched_command_path[1] == "show") || + (cmd == "ide" && parsed.matched_command_path.size() >= 2 && + parsed.matched_command_path[1] == "query"); const Void::Log::Level log_level = verbose ? Void::Log::Level::Debug : ((quiet || machine_quiet_default) ? Void::Log::Level::Warning @@ -2016,6 +2258,9 @@ int main(int argc, char **argv) { if (cmd == "graph") { return execute_graph_command(graph_opts); } + if (cmd == "ide") { + return execute_ide_command(parsed.matched_command_path.at(1), ide_opts); + } std::cerr << "vbs: unhandled subcommand '" << cmd << "'\n"; return 2; diff --git a/src/Modules/ModuleScanner.cpp b/src/Modules/ModuleScanner.cpp index 2042004..852a992 100644 --- a/src/Modules/ModuleScanner.cpp +++ b/src/Modules/ModuleScanner.cpp @@ -209,6 +209,10 @@ scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain, req.arguments.push_back(is_sys ? "-isystem" : "-I"); req.arguments.push_back(inc.string()); } + for (const auto &sys_inc : toolchain.default_include_dirs) { + req.arguments.push_back("-isystem"); + req.arguments.push_back(sys_inc); + } for (const auto &def : defines) { req.arguments.push_back("-D" + def); } @@ -226,13 +230,19 @@ scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain, return parse_p1689_json(proc->stdout_data, source_file); } -Void::Result::Result -collate_modules(const std::vector &units, const std::filesystem::path &bmi_root, - const std::string &context_isolation_key, std::string_view bmi_extension) { +Void::Result::Result collate_modules( + const std::vector &units, const std::filesystem::path &bmi_root, + const std::string &context_isolation_key, std::string_view bmi_extension, + const std::map> &external_module_bmis) { // 1. Index module providers and reject duplicates immediately. std::map> provider_by_name; for (std::size_t i = 0; i < units.size(); ++i) { for (const auto &mod : units[i].provides) { + if (external_module_bmis.contains(mod)) { + return std::unexpected{make_error(std::format( + "duplicate module provider for '{}': defined in '{}' and imported dependency", + mod, units[i].source_file.string()))}; + } const auto [it, inserted] = provider_by_name.emplace(mod, i); if (!inserted) { return std::unexpected{make_error(std::format( @@ -249,6 +259,9 @@ collate_modules(const std::vector &units, const std::filesystem: for (const auto &req_mod : units[i].required_modules) { const auto it = provider_by_name.find(req_mod); if (it == provider_by_name.end()) { + if (external_module_bmis.contains(req_mod)) { + continue; + } return std::unexpected{ make_error(std::format("missing module provider for '{}' imported by '{}'", req_mod, units[i].source_file.string()))}; @@ -306,15 +319,38 @@ collate_modules(const std::vector &units, const std::filesystem: } } - // Build GCC module-mapper file mapping all required + provided modules. + // Build GCC module-mapper file mapping all required + provided (+ transitive external) + // modules. std::string mapper; + std::set> mapped_names; for (const auto &mod : u.provides) { + mapped_names.insert(mod); mapper += mod + " " + node.bmi_output_path.string() + "\n"; } + bool uses_external = false; for (const auto &req_mod : u.required_modules) { - const auto &bmi = plan.module_to_bmi.at(req_mod); - node.imported_bmis.emplace_back(req_mod, bmi); - mapper += req_mod + " " + bmi.string() + "\n"; + std::filesystem::path bmi; + if (const auto lit = plan.module_to_bmi.find(req_mod); + lit != plan.module_to_bmi.end()) { + bmi = lit->second; + } else if (const auto eit = external_module_bmis.find(req_mod); + eit != external_module_bmis.end()) { + bmi = eit->second; + uses_external = true; + } + if (!bmi.empty()) { + node.imported_bmis.emplace_back(req_mod, bmi); + if (mapped_names.insert(req_mod).second) { + mapper += req_mod + " " + bmi.string() + "\n"; + } + } + } + if (uses_external || !u.provides.empty()) { + for (const auto &[mname, bmi] : external_module_bmis) { + if (mapped_names.insert(mname).second) { + mapper += mname + " " + bmi.string() + "\n"; + } + } } if (!mapper.empty()) { const std::string mtag = Util::sha256_hex(u.source_file.string()).substr(0, 12); @@ -396,8 +432,10 @@ generate_unity_batches(const std::string &target_name, for (const auto &src : sources) { const auto norm = src.lexically_normal(); const auto ext = norm.extension().string(); - // Exclude module interface/partition extensions and explicitly excluded files from unity! - if (excluded.contains(norm) || ext == ".cppm" || ext == ".ixx" || ext == ".ccm") { + // Exclude C sources, module interface/partition extensions and explicitly excluded files + // from unity! + if (excluded.contains(norm) || ext == ".c" || ext == ".cppm" || ext == ".ixx" || + ext == ".ccm") { result.standalone_files.push_back(norm); } else { batchable.push_back(norm); diff --git a/src/Provider/Provider.cpp b/src/Provider/Provider.cpp index cd29dc4..e899cee 100644 --- a/src/Provider/Provider.cpp +++ b/src/Provider/Provider.cpp @@ -113,7 +113,16 @@ std::string serialize_export(const ProviderExport &exp) { ",\"runtime_files\":" + json_array(iface.runtime_files, [](const std::filesystem::path &p) { return json_quote(p.string()); }) + - '}'; + ",\"module_bmis\":{"; + bool first_mod = true; + for (const auto &[mname, bmi_p] : iface.module_bmis) { + if (!first_mod) { + out += ','; + } + first_mod = false; + out += json_quote(mname) + ':' + json_quote(bmi_p.string()); + } + out += "}}"; } out += "}}\n"; return out; @@ -175,7 +184,16 @@ std::optional load_cached_export(const std::filesystem::path &ex for (const auto &s : get_str_array(*io, "runtime_files")) { iface.runtime_files.emplace_back(s); } - // Verify materialized library artifacts still exist on disk! + if (const auto *mv = find_key(*io, "module_bmis")) { + if (const auto *mobj = std::get_if(&mv->value)) { + for (const auto &[mname, mval] : *mobj) { + if (const auto *ms = std::get_if(&mval.value)) { + iface.module_bmis.emplace(mname, *ms); + } + } + } + } + // Verify materialized library and BMI artifacts still exist on disk! std::error_code ec; for (const auto &lib : iface.static_libraries) { if (!std::filesystem::is_regular_file(lib, ec)) { @@ -187,6 +205,12 @@ std::optional load_cached_export(const std::filesystem::path &ex return std::nullopt; } } + for (const auto &[mname, bmi_p] : iface.module_bmis) { + (void)mname; + if (!std::filesystem::is_regular_file(bmi_p, ec)) { + return std::nullopt; + } + } exp.targets[k] = std::move(iface); } } @@ -254,6 +278,9 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & req.arguments.push_back("-G"); req.arguments.push_back("Ninja"); } + if (!request.toolchain.c_compiler.empty()) { + req.arguments.push_back("-DCMAKE_C_COMPILER=" + request.toolchain.c_compiler.string()); + } req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string()); const std::string cfg = (request.profile.name == "release" || request.profile.name == "Release") ? "Release" @@ -706,6 +733,9 @@ run_meson_provider(const ProviderRequest &request, const std::filesystem::path & for (const auto &[k, v] : request.dependency.options) { req.arguments.push_back("-D" + k + "=" + meson_option_value(v)); } + if (!request.toolchain.c_compiler.empty()) { + req.environment.set_vars["CC"] = request.toolchain.c_compiler.string(); + } req.environment.set_vars["CXX"] = request.toolchain.cxx_compiler.string(); req.timeout = std::chrono::seconds{180}; auto proc = Platform::run_supervised(req, stop); @@ -1278,6 +1308,11 @@ run_native_provider(const ProviderRequest &request, const std::filesystem::path } } } + if (sum_it != summary_by_name.end()) { + for (const auto &[mname, bmi_p] : sum_it->second->exported_module_bmis) { + iface.module_bmis.try_emplace(mname, bmi_p); + } + } } exp.targets[request.dependency.name + "::" + t.name] = iface; diff --git a/src/Provider/Translator.cpp b/src/Provider/Translator.cpp index 4d01545..882c0f2 100644 --- a/src/Provider/Translator.cpp +++ b/src/Provider/Translator.cpp @@ -10,6 +10,8 @@ #include #include +#include +#include #include #include @@ -125,17 +127,832 @@ bool is_safe_system_link_flag(std::string_view tok) { tok == "-lrt" || tok.starts_with("-Wl,"); } +std::string trim_copy(std::string_view sv) { + while (!sv.empty() && (sv.front() == ' ' || sv.front() == '\t' || sv.front() == '\r')) { + sv.remove_prefix(1); + } + while (!sv.empty() && (sv.back() == ' ' || sv.back() == '\t' || sv.back() == '\r')) { + sv.remove_suffix(1); + } + return std::string{sv}; +} + +std::optional parse_c_std_flag(std::string_view tok) { + if (tok == "-std=c11" || tok == "-std=gnu11") { + return CStandard::C11; + } + if (tok == "-std=c17" || tok == "-std=gnu17" || tok == "-std=c18" || tok == "-std=gnu18") { + return CStandard::C17; + } + if (tok == "-std=c23" || tok == "-std=gnu23" || tok == "-std=c2x" || tok == "-std=gnu2x") { + return CStandard::C23; + } + return std::nullopt; +} + +std::optional parse_cxx_std_flag(std::string_view tok) { + if (tok == "-std=c++17" || tok == "-std=gnu++17") { + return CxxStandard::Cxx17; + } + if (tok == "-std=c++20" || tok == "-std=gnu++20") { + return CxxStandard::Cxx20; + } + if (tok == "-std=c++23" || tok == "-std=gnu++23") { + return CxxStandard::Cxx23; + } + if (tok == "-std=c++26" || tok == "-std=gnu++26") { + return CxxStandard::Cxx26; + } + return std::nullopt; +} + +bool is_ninja_ident_char(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || + c == '-'; +} + +std::vector split_ninja_logical_lines(std::string_view text) { + std::vector lines; + std::string cur; + bool continuing = false; + std::size_t pos = 0; + while (pos < text.size()) { + const auto nl = text.find('\n', pos); + std::string_view phys = + text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); + if (!phys.empty() && phys.back() == '\r') { + phys.remove_suffix(1); + } + pos = (nl == std::string_view::npos) ? text.size() : (nl + 1); + + if (continuing) { + while (!phys.empty() && (phys.front() == ' ' || phys.front() == '\t')) { + phys.remove_prefix(1); + } + } + cur.append(phys); + + std::size_t trailing_dollars = 0; + for (auto it = cur.rbegin(); it != cur.rend() && *it == '$'; ++it) { + ++trailing_dollars; + } + if ((trailing_dollars % 2) == 1 && pos <= text.size() && nl != std::string_view::npos) { + cur.pop_back(); + continuing = true; + continue; + } + continuing = false; + lines.push_back(std::move(cur)); + cur.clear(); + } + if (!cur.empty()) { + lines.push_back(std::move(cur)); + } + return lines; +} + +std::string expand_ninja_vars(std::string_view sv, + const std::map> &vars, + bool unescape_path_escapes, bool preserve_unknown) { + std::string out; + out.reserve(sv.size()); + for (std::size_t i = 0; i < sv.size();) { + if (sv[i] != '$') { + out.push_back(sv[i++]); + continue; + } + if (i + 1 >= sv.size()) { + out.push_back('$'); + break; + } + const char next = sv[i + 1]; + if (next == '$') { + out.push_back('$'); + i += 2; + } else if (next == ' ' || next == ':') { + if (unescape_path_escapes) { + out.push_back(next); + } else { + out.push_back('$'); + out.push_back(next); + } + i += 2; + } else if (next == '{') { + const auto close = sv.find('}', i + 2); + if (close == std::string_view::npos) { + out.push_back(sv[i++]); + continue; + } + const auto name = sv.substr(i + 2, close - (i + 2)); + if (const auto vit = vars.find(name); vit != vars.end()) { + out.append(vit->second); + } else if (preserve_unknown) { + out.append(sv.substr(i, close + 1 - i)); + } + i = close + 1; + } else if (is_ninja_ident_char(next)) { + std::size_t end = i + 2; + while (end < sv.size() && is_ninja_ident_char(sv[end])) { + ++end; + } + const auto name = sv.substr(i + 1, end - (i + 1)); + if (const auto vit = vars.find(name); vit != vars.end()) { + out.append(vit->second); + } else if (preserve_unknown) { + out.append(sv.substr(i, end - i)); + } + i = end; + } else { + out.push_back('$'); + ++i; + } + } + return out; +} + +std::vector tokenize_ninja_raw_list(std::string_view sv) { + std::vector tokens; + std::string cur; + for (std::size_t i = 0; i < sv.size(); ++i) { + if (sv[i] == '$' && i + 1 < sv.size() && (sv[i + 1] == ' ' || sv[i + 1] == ':')) { + cur.push_back(sv[i]); + cur.push_back(sv[i + 1]); + ++i; + continue; + } + if (sv[i] == ' ' || sv[i] == '\t') { + if (!cur.empty()) { + tokens.push_back(std::move(cur)); + cur.clear(); + } + continue; + } + cur.push_back(sv[i]); + } + if (!cur.empty()) { + tokens.push_back(std::move(cur)); + } + return tokens; +} + +std::size_t find_unescaped_ninja_colon(std::string_view sv) { + for (std::size_t i = 0; i < sv.size(); ++i) { + if (sv[i] == '$' && i + 1 < sv.size()) { + ++i; + continue; + } + if (sv[i] == ':') { + return i; + } + } + return std::string_view::npos; +} + +struct NinjaCustomEdge { + std::size_t index{0}; + std::vector all_outputs; + std::vector concrete_outputs; + std::vector file_inputs; + std::vector raw_all_inputs; + std::vector raw_order_inputs; + std::string command; + std::filesystem::path working_directory; + std::vector command_argv; + std::string pool; + bool is_noop_util{false}; + bool is_valid{false}; + std::string unsupported_kind; + std::string unsupported_detail; +}; + +struct NinjaCustomGraph { + std::filesystem::path configure_dir; + std::filesystem::path source_root; + bool found_build_ninja{false}; + std::vector edges; + std::map> edge_by_output; + std::map, std::less<>> phony_by_target; + // Maps compiler input source file path -> list of extra implicit/order-only dependency paths. + std::map> compiler_extra_deps_by_src; +}; + +bool is_cmake_internal_stamp_path(const std::filesystem::path &p, + const std::filesystem::path &cfg_norm) { + const auto rel = p.lexically_relative(cfg_norm); + const auto rel_s = rel.generic_string(); + return rel_s.starts_with("CMakeFiles/") || p.extension() == ".util"; +} + +bool validate_and_parse_custom_command(NinjaCustomEdge &edge, const std::filesystem::path &cfg_norm, + const std::filesystem::path &src_norm) { + if (edge.pool == "console") { + edge.unsupported_kind = "console_pool"; + edge.unsupported_detail = "custom rule uses console pool (interactive terminal rules are " + "outside bounded hermetic translation)"; + return false; + } + + std::string cmd = trim_copy(edge.command); + edge.working_directory = cfg_norm; + + // Strip leading POSIX CMake `cd && ` wrapper into working_directory. + if (cmd.starts_with("cd ")) { + std::size_t p = 3; + while (p < cmd.size() && (cmd[p] == ' ' || cmd[p] == '\t')) { + ++p; + } + std::string dir_tok; + bool in_single = false; + bool in_double = false; + bool esc = false; + while (p < cmd.size()) { + const char c = cmd[p]; + if (esc) { + dir_tok.push_back(c); + esc = false; + ++p; + continue; + } + if (c == '\\' && !in_single) { + esc = true; + ++p; + continue; + } + if (c == '\'' && !in_double) { + in_single = !in_single; + ++p; + continue; + } + if (c == '"' && !in_single) { + in_double = !in_double; + ++p; + continue; + } + if (!in_single && !in_double && (c == ' ' || c == '\t')) { + break; + } + dir_tok.push_back(c); + ++p; + } + while (p < cmd.size() && (cmd[p] == ' ' || cmd[p] == '\t')) { + ++p; + } + if (p + 1 < cmd.size() && cmd[p] == '&' && cmd[p + 1] == '&' && !dir_tok.empty()) { + std::filesystem::path wd{dir_tok}; + wd = (wd.is_absolute() ? wd : (cfg_norm / wd)).lexically_normal(); + if (!Platform::path_is_within(cfg_norm, wd) && + (src_norm.empty() || !Platform::path_is_within(src_norm, wd))) { + edge.unsupported_kind = "out_of_tree_working_directory"; + edge.unsupported_detail = std::format( + "custom rule sets working directory '{}' outside configure/source root", + wd.string()); + return false; + } + edge.working_directory = wd; + cmd = trim_copy(std::string_view{cmd}.substr(p + 2)); + } + } + + const bool all_internal_stamps = + !edge.all_outputs.empty() && + std::ranges::all_of(edge.all_outputs, [&](const std::filesystem::path &op) { + return is_cmake_internal_stamp_path(op, cfg_norm); + }); + + if (cmd.empty() || cmd == ":" || cmd == "true") { + if (all_internal_stamps) { + edge.is_noop_util = true; + edge.is_valid = true; + return true; + } + edge.unsupported_kind = "empty_custom_command"; + edge.unsupported_detail = "custom rule declares outputs without an executable COMMAND"; + return false; + } + + if (edge.concrete_outputs.empty()) { + edge.unsupported_kind = "utility_without_hermetic_outputs"; + edge.unsupported_detail = + "custom/utility target executes side-effect commands with only stamp/.util outputs"; + return false; + } + + for (const auto &out_p : edge.concrete_outputs) { + if (!Platform::path_is_within(cfg_norm, out_p)) { + edge.unsupported_kind = "out_of_tree_custom_output"; + edge.unsupported_detail = + std::format("custom command output '{}' escapes configure_dir '{}'", out_p.string(), + cfg_norm.string()); + return false; + } + if (!src_norm.empty() && cfg_norm == src_norm) { + edge.unsupported_kind = "out_of_tree_custom_output"; + edge.unsupported_detail = std::format( + "custom command output '{}' runs in-source build overlapping source_root '{}'", + out_p.string(), src_norm.string()); + return false; + } + } + + if (cmd.find("--regenerate-build-system") != std::string::npos || + cmd.find("meson --internal regenerate") != std::string::npos) { + edge.unsupported_kind = "build_system_regeneration"; + edge.unsupported_detail = "custom rule recursively regenerates foreign build system files"; + return false; + } + + // Scan unquoted characters for subshells, arbitrary chaining, or out-of-tree redirections. + bool has_shell_chain = false; + bool in_single = false; + bool in_double = false; + bool esc = false; + for (std::size_t i = 0; i < cmd.size(); ++i) { + const char c = cmd[i]; + if (esc) { + esc = false; + continue; + } + if (c == '\\' && !in_single) { + esc = true; + continue; + } + if (c == '\'' && !in_double) { + in_single = !in_single; + continue; + } + if (c == '"' && !in_single) { + in_double = !in_double; + continue; + } + if (in_single || in_double) { + continue; + } + if (c == '`' || (c == '$' && i + 1 < cmd.size() && cmd[i + 1] == '(')) { + edge.unsupported_kind = "unbounded_shell_custom_command"; + edge.unsupported_detail = + "custom command uses unquoted shell command substitution (`...` or $(...))"; + return false; + } + if (c == '&' && i + 1 < cmd.size() && cmd[i + 1] == '&') { + has_shell_chain = true; + ++i; + continue; + } + if (c == '>') { + has_shell_chain = true; + std::size_t rp = i + 1; + if (rp < cmd.size() && cmd[rp] == '>') { + ++rp; + } + while (rp < cmd.size() && (cmd[rp] == ' ' || cmd[rp] == '\t')) { + ++rp; + } + std::size_t rend = rp; + while (rend < cmd.size() && cmd[rend] != ' ' && cmd[rend] != '\t') { + ++rend; + } + std::string redir = cmd.substr(rp, rend - rp); + if (!redir.empty() && redir.size() >= 2 && + ((redir.front() == '"' && redir.back() == '"') || + (redir.front() == '\'' && redir.back() == '\''))) { + redir = redir.substr(1, redir.size() - 2); + } + if (redir.empty()) { + edge.unsupported_kind = "out_of_tree_custom_output"; + edge.unsupported_detail = "custom command has unparsed shell output redirection"; + return false; + } + const std::filesystem::path rpath = + (std::filesystem::path{redir}.is_absolute() ? std::filesystem::path{redir} + : (edge.working_directory / redir)) + .lexically_normal(); + if (!Platform::path_is_within(cfg_norm, rpath)) { + edge.unsupported_kind = "out_of_tree_custom_output"; + edge.unsupported_detail = std::format( + "custom command shell redirection target '{}' escapes configure_dir '{}'", + rpath.string(), cfg_norm.string()); + return false; + } + continue; + } + if (c == ';' || c == '|' || c == '<') { + has_shell_chain = true; + } + } + + if (has_shell_chain) { + edge.command_argv = {"/bin/sh", "-c", cmd}; + } else { + edge.command_argv = split_shell_tokens(cmd); + } + if (edge.command_argv.empty()) { + edge.unsupported_kind = "empty_custom_command"; + edge.unsupported_detail = "custom rule produced an empty command argv"; + return false; + } + edge.is_valid = true; + return true; +} + +NinjaCustomGraph parse_ninja_custom_graph(const std::filesystem::path &configure_dir, + const std::filesystem::path &source_root) { + NinjaCustomGraph ng; + ng.configure_dir = configure_dir.lexically_normal(); + ng.source_root = source_root.lexically_normal(); + + auto text = Void::FileSystem::read_file(ng.configure_dir / "build.ninja"); + if (!text) { + return ng; + } + ng.found_build_ninja = true; + + const auto lines = split_ninja_logical_lines(*text); + std::map> ninja_vars; + std::optional active_custom_edge; + + auto index_output_key = [&](const std::string &raw_key, std::size_t edge_idx) { + if (raw_key.empty()) { + return; + } + ng.edge_by_output.try_emplace(raw_key, edge_idx); + const std::filesystem::path p{raw_key}; + const auto norm = (p.is_absolute() ? p : (ng.configure_dir / p)).lexically_normal(); + ng.edge_by_output.try_emplace(norm.generic_string(), edge_idx); + }; + + for (const auto &line : lines) { + const std::string trimmed = trim_copy(line); + if (trimmed.empty()) { + active_custom_edge.reset(); + continue; + } + if (trimmed.front() == '#') { + continue; + } + + const bool indented = (line.front() == ' ' || line.front() == '\t'); + if (indented) { + if (!active_custom_edge) { + continue; + } + const auto eq = trimmed.find('='); + if (eq == std::string::npos) { + continue; + } + const std::string key = trim_copy(std::string_view{trimmed}.substr(0, eq)); + const std::string val = expand_ninja_vars( + trim_copy(std::string_view{trimmed}.substr(eq + 1)), ninja_vars, false, true); + auto &edge = ng.edges[*active_custom_edge]; + if (key == "COMMAND") { + edge.command = val; + } else if (key == "pool") { + edge.pool = val; + } + continue; + } + + active_custom_edge.reset(); + + if (line.starts_with("build ")) { + const auto rest = std::string_view{line}.substr(6); + const auto colon = find_unescaped_ninja_colon(rest); + if (colon == std::string_view::npos) { + continue; + } + const auto lhs = rest.substr(0, colon); + const auto rhs = rest.substr(colon + 1); + + std::vector outs; + bool in_imp_outs = false; + for (const auto &rtok : tokenize_ninja_raw_list(lhs)) { + if (rtok == "|") { + in_imp_outs = true; + continue; + } + (void)in_imp_outs; + outs.push_back(expand_ninja_vars(rtok, ninja_vars, true, false)); + } + + const auto rhs_tokens = tokenize_ninja_raw_list(rhs); + if (rhs_tokens.empty()) { + continue; + } + const std::string rule = expand_ninja_vars(rhs_tokens.front(), ninja_vars, true, false); + std::vector exp_ins; + std::vector imp_ins; + std::vector order_ins; + int section = 0; // 0: explicit, 1: implicit, 2: order-only + for (std::size_t i = 1; i < rhs_tokens.size(); ++i) { + const auto &rtok = rhs_tokens[i]; + if (rtok == "||") { + section = 2; + continue; + } + if (rtok == "|") { + section = 1; + continue; + } + const std::string expanded = expand_ninja_vars(rtok, ninja_vars, true, false); + if (section == 0) { + exp_ins.push_back(expanded); + } else if (section == 1) { + imp_ins.push_back(expanded); + } else { + order_ins.push_back(expanded); + } + } + + if (rule == "phony") { + std::vector all_in; + all_in.insert(all_in.end(), exp_ins.begin(), exp_ins.end()); + all_in.insert(all_in.end(), imp_ins.begin(), imp_ins.end()); + all_in.insert(all_in.end(), order_ins.begin(), order_ins.end()); + for (const auto &o : outs) { + ng.phony_by_target[o] = all_in; + const std::filesystem::path p{o}; + const auto norm = + (p.is_absolute() ? p : (ng.configure_dir / p)).lexically_normal(); + ng.phony_by_target.try_emplace(norm.generic_string(), all_in); + } + continue; + } + + if (rule == "CUSTOM_COMMAND" || rule == "CUSTOM_COMMAND_ph") { + NinjaCustomEdge edge; + edge.index = ng.edges.size(); + std::set seen_outs; + for (const auto &o : outs) { + const std::filesystem::path p{o}; + const auto norm = + (p.is_absolute() ? p : (ng.configure_dir / p)).lexically_normal(); + if (seen_outs.insert(norm).second) { + edge.all_outputs.push_back(norm); + if (!is_cmake_internal_stamp_path(norm, ng.configure_dir)) { + edge.concrete_outputs.push_back(norm); + } + } + index_output_key(o, edge.index); + } + auto add_in_tokens = [&](const std::vector &vec) { + for (const auto &in : vec) { + if (!in.empty() && !std::ranges::contains(edge.raw_all_inputs, in)) { + edge.raw_all_inputs.push_back(in); + } + } + }; + add_in_tokens(exp_ins); + add_in_tokens(imp_ins); + add_in_tokens(order_ins); + edge.raw_order_inputs = std::move(order_ins); + ng.edges.push_back(std::move(edge)); + active_custom_edge = ng.edges.size() - 1; + continue; + } + + // Record implicit/order-only dependencies on compiler edges (used for Meson generated + // headers). + if (rule.ends_with("_COMPILER") && !exp_ins.empty()) { + const std::filesystem::path src_p{exp_ins.front()}; + const auto src_abs = + (src_p.is_absolute() ? src_p : (ng.configure_dir / src_p)).lexically_normal(); + auto &extras = ng.compiler_extra_deps_by_src[src_abs]; + auto add_dep_list = [&](const std::vector &vec) { + for (const auto &d : vec) { + if (d.empty()) { + continue; + } + const std::filesystem::path dp{d}; + const auto d_abs = + (dp.is_absolute() ? dp : (ng.configure_dir / dp)).lexically_normal(); + if (!std::ranges::contains(extras, d_abs)) { + extras.push_back(d_abs); + } + } + }; + add_dep_list(imp_ins); + add_dep_list(order_ins); + } + continue; + } + + if (!line.starts_with("rule ") && !line.starts_with("pool ") && + !line.starts_with("default ") && !line.starts_with("include ") && + !line.starts_with("subninja ")) { + const auto eq = line.find('='); + if (eq != std::string::npos) { + const std::string key = trim_copy(std::string_view{line}.substr(0, eq)); + const std::string val = expand_ninja_vars( + trim_copy(std::string_view{line}.substr(eq + 1)), ninja_vars, true, false); + if (!key.empty()) { + ninja_vars[key] = val; + } + } + } + } + + for (auto &edge : ng.edges) { + (void)validate_and_parse_custom_command(edge, ng.configure_dir, ng.source_root); + } + return ng; +} + +class CustomActionMaterializer { + public: + CustomActionMaterializer(const NinjaCustomGraph &ng, + const std::set &known_target_artifacts) + : ng_(ng), known_artifacts_(known_target_artifacts) {} + + Void::Result::Result, UnsupportedConstruct> + materialize_key(std::string_view raw_key, std::string_view owner_target_name) { + std::vector names; + std::set visiting_keys; + if (!collect_for_key(raw_key, owner_target_name, visiting_keys, names)) { + return std::unexpected{std::move(*last_error_)}; + } + return names; + } + + std::vector targets; + + private: + const NinjaCustomGraph &ng_; + const std::set &known_artifacts_; + std::map target_name_by_edge_; + std::set active_edges_; + std::optional last_error_; + + std::string normalize_lookup_key(std::string_view raw) const { + const std::filesystem::path p{raw}; + return (p.is_absolute() ? p : (ng_.configure_dir / p)).lexically_normal().generic_string(); + } + + bool set_err(std::string_view target_name, std::string kind, std::string detail) { + last_error_ = + UnsupportedConstruct{std::string{target_name}, std::move(kind), std::move(detail)}; + return false; + } + + bool collect_for_key(std::string_view raw_key, std::string_view owner_target_name, + std::set &visiting_keys, + std::vector &out_names) { + const std::string key{raw_key}; + const std::string norm_key = normalize_lookup_key(key); + if (!visiting_keys.insert(norm_key).second) { + return set_err(owner_target_name, "custom_command_cycle", + std::format("cycle detected while resolving custom rule '{}'", key)); + } + + bool ok = true; + if (auto eit = ng_.edge_by_output.find(key); eit != ng_.edge_by_output.end()) { + ok = materialize_edge(eit->second, owner_target_name, visiting_keys, out_names); + } else if (auto eit2 = ng_.edge_by_output.find(norm_key); + eit2 != ng_.edge_by_output.end()) { + ok = materialize_edge(eit2->second, owner_target_name, visiting_keys, out_names); + } else { + const std::vector *phony_ins = nullptr; + if (auto pit = ng_.phony_by_target.find(key); pit != ng_.phony_by_target.end()) { + phony_ins = &pit->second; + } else if (auto pit2 = ng_.phony_by_target.find(norm_key); + pit2 != ng_.phony_by_target.end()) { + phony_ins = &pit2->second; + } + if (phony_ins) { + for (const auto &in_tok : *phony_ins) { + if (in_tok == "cmake_force" || in_tok == "always" || + in_tok.starts_with("CMakeFiles/cmake_object_order_depends_target_")) { + continue; + } + if (!collect_for_key(in_tok, owner_target_name, visiting_keys, out_names)) { + ok = false; + break; + } + } + } + } + + visiting_keys.erase(norm_key); + return ok; + } + + bool materialize_edge(std::size_t edge_idx, std::string_view owner_target_name, + std::set &visiting_keys, + std::vector &out_names) { + const auto &edge = ng_.edges[edge_idx]; + if (!edge.is_valid) { + return set_err(owner_target_name, edge.unsupported_kind, edge.unsupported_detail); + } + if (edge.is_noop_util) { + for (const auto &in_tok : edge.raw_all_inputs) { + if (in_tok == "cmake_force" || + in_tok.starts_with("CMakeFiles/cmake_object_order_depends_target_")) { + continue; + } + if (!collect_for_key(in_tok, owner_target_name, visiting_keys, out_names)) { + return false; + } + } + return true; + } + + if (const auto existing = target_name_by_edge_.find(edge_idx); + existing != target_name_by_edge_.end()) { + if (!std::ranges::contains(out_names, existing->second)) { + out_names.push_back(existing->second); + } + return true; + } + + if (!active_edges_.insert(edge_idx).second) { + return set_err(owner_target_name, "custom_command_cycle", + "cyclic CUSTOM_COMMAND dependency detected in build.ninja"); + } + + // Reject custom rules invoking/depending on an executable or library compiled in-tree. + for (const auto &in_tok : edge.raw_all_inputs) { + const auto norm = + (std::filesystem::path{in_tok}.is_absolute() ? std::filesystem::path{in_tok} + : (ng_.configure_dir / in_tok)) + .lexically_normal(); + if (known_artifacts_.contains(in_tok) || known_artifacts_.contains(norm.string()) || + known_artifacts_.contains(norm.filename().string())) { + active_edges_.erase(edge_idx); + return set_err( + owner_target_name, "in_tree_tool_custom_command", + std::format("custom command depends on built in-tree artifact '{}'", in_tok)); + } + } + + std::vector upstream_prereqs; + std::vector action_inputs; + for (const auto &in_tok : edge.raw_all_inputs) { + if (in_tok == "cmake_force" || in_tok == "always" || + in_tok.starts_with("CMakeFiles/cmake_object_order_depends_target_")) { + continue; + } + const auto norm_in = + (std::filesystem::path{in_tok}.is_absolute() ? std::filesystem::path{in_tok} + : (ng_.configure_dir / in_tok)) + .lexically_normal(); + if (ng_.edge_by_output.contains(in_tok) || + ng_.edge_by_output.contains(norm_in.generic_string()) || + ng_.phony_by_target.contains(in_tok) || + ng_.phony_by_target.contains(norm_in.generic_string())) { + std::set sub_visit; + if (!collect_for_key(in_tok, owner_target_name, sub_visit, upstream_prereqs)) { + active_edges_.erase(edge_idx); + return false; + } + } + if (!is_cmake_internal_stamp_path(norm_in, ng_.configure_dir) && + !ng_.phony_by_target.contains(in_tok) && + !ng_.phony_by_target.contains(norm_in.generic_string())) { + if (std::filesystem::exists(norm_in) || + ng_.edge_by_output.contains(norm_in.generic_string())) { + if (!std::ranges::contains(action_inputs, norm_in.string())) { + action_inputs.push_back(norm_in.string()); + } + } + } + } + + TargetRecord tr; + tr.name = std::format("__vbs_custom_{}_{}", edge_idx, + edge.concrete_outputs.front().filename().string()); + tr.kind = TargetKind::CustomAction; + tr.command_argv = edge.command_argv; + tr.working_directory = edge.working_directory.string(); + tr.action_inputs = std::move(action_inputs); + for (const auto &out_p : edge.concrete_outputs) { + tr.action_outputs.push_back(out_p.string()); + } + tr.prerequisites = std::move(upstream_prereqs); + + const std::string created_name = tr.name; + target_name_by_edge_[edge_idx] = created_name; + targets.push_back(std::move(tr)); + active_edges_.erase(edge_idx); + + if (!std::ranges::contains(out_names, created_name)) { + out_names.push_back(created_name); + } + return true; + } +}; + struct ParsedCMakeTarget { std::string id; std::string name; std::string type; - std::vector sources; + std::vector sources; std::vector> includes; std::vector defines; std::vector compile_options; + std::vector per_file_options; std::vector link_options; + CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; std::vector dep_ids; + std::vector prereq_target_names; std::vector artifact_rel_paths; }; @@ -143,6 +960,8 @@ struct ParsedCMakeCodemodel { std::filesystem::path source_root; std::filesystem::path build_root; TranslationAuditReport audit; + std::vector synthesized_custom_targets; + std::map, std::less<>> utility_target_prereqs; std::map> targets_by_id; std::vector target_order; }; @@ -271,6 +1090,10 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { } } + // Parse Ninja custom commands/utility graph when configured with Ninja (Plan 21 Track B2). + const NinjaCustomGraph ninja_graph = parse_ninja_custom_graph(configure_dir, out.source_root); + CustomActionMaterializer custom_mat{ninja_graph, known_target_artifacts}; + // Second pass: audit every target strictly and build ParsedCMakeTarget records. for (const auto &[jf, tdoc] : raw_target_docs) { const auto *td = std::get_if(&tdoc.value); @@ -282,11 +1105,55 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { pt.name = get_str(*td, "name"); pt.type = get_str(*td, "type"); - if (pt.type == "UTILITY" || pt.type == "GLOBAL_TARGET") { + if (pt.type == "UTILITY") { + if (!ninja_graph.found_build_ninja) { + add_unsupported( + pt.name, "utility_target", + std::format("CMake UTILITY target '{}' cannot be translated without " + "build.ninja (configure with Ninja)", + pt.name)); + continue; + } + const std::string candidates[] = {pt.name, "CMakeFiles/" + pt.name, pt.name + ".util"}; + bool matched = false; + std::vector resolved_names; + for (const auto &cand : candidates) { + if (ninja_graph.edge_by_output.contains(cand) || + ninja_graph.phony_by_target.contains(cand)) { + matched = true; + auto mres = custom_mat.materialize_key(cand, pt.name); + if (!mres) { + add_unsupported(pt.name, mres.error().construct_kind, mres.error().detail); + matched = true; + resolved_names.clear(); + goto done_utility; + } + for (const auto &cn : *mres) { + if (!std::ranges::contains(resolved_names, cn)) { + resolved_names.push_back(cn); + } + } + break; + } + } + if (!matched || resolved_names.empty()) { + add_unsupported( + pt.name, "utility_without_hermetic_outputs", + std::format("CMake UTILITY target '{}' does not produce verifiable hermetic " + "outputs inside configure_dir", + pt.name)); + continue; + } + out.utility_target_prereqs[pt.id] = std::move(resolved_names); + out.audit.supported_targets.push_back(pt.name); + done_utility: + continue; + } + if (pt.type == "GLOBAL_TARGET") { add_unsupported( pt.name, "utility_target", - std::format("CMake target '{}' has type '{}' (custom command/utility " - "targets cannot be faithfully translated from codemodel-v2)", + std::format("CMake target '{}' has type '{}' (global build-system target is " + "outside native translation subset)", pt.name, pt.type)); continue; } @@ -298,46 +1165,81 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { continue; } - // Reject foreign C++20 module fileSets (dynamic module edges require explicit build rules). + // Index C++20 CXX_MODULES fileSets (`SourceKind::ModuleInterface`, Plan 21 Track B3). + std::set module_fileset_indexes; + std::set module_source_indexes; if (const auto *fsets = find_key(*td, "fileSets")) { if (const auto *farr = std::get_if(&fsets->value)) { - for (const auto &fv : *farr) { - if (const auto *fo = std::get_if(&fv.value)) { - const auto ftype = get_str(*fo, "type"); - if (ftype == "CXX_MODULES") { - add_unsupported( - pt.name, "cxx_modules_fileset", - std::format("target '{}' uses CMake CXX_MODULES fileSet '{}'", - pt.name, get_str(*fo, "name"))); + for (std::size_t fs_i = 0; fs_i < farr->size(); ++fs_i) { + if (const auto *fo = std::get_if(&(*farr)[fs_i].value)) { + if (get_str(*fo, "type") == "CXX_MODULES") { + module_fileset_indexes.insert(fs_i); + if (const auto *sidxs = find_key(*fo, "sourceIndexes")) { + if (const auto *sarr = std::get_if(&sidxs->value)) { + for (const auto &iv : *sarr) { + if (const auto *idx = + std::get_if(&iv.value)) { + module_source_indexes.insert( + static_cast(*idx)); + } + } + } + } } } } } } - // Collect sources and detect any generated sources (e.g. from add_custom_command). + // Collect sources and translate hermetic generated sources via build.ninja CUSTOM_COMMAND. struct RawSource { std::filesystem::path abs_path; bool is_generated{false}; + bool is_module_interface{false}; std::optional compile_group_index; }; std::vector raw_sources; if (const auto *srcs = find_key(*td, "sources")) { if (const auto *sarr = std::get_if(&srcs->value)) { - for (const auto &sv : *sarr) { - if (const auto *so = std::get_if(&sv.value)) { + for (std::size_t src_i = 0; src_i < sarr->size(); ++src_i) { + if (const auto *so = std::get_if(&(*sarr)[src_i].value)) { RawSource rs; const std::filesystem::path raw_p{get_str(*so, "path")}; rs.abs_path = (raw_p.is_absolute() ? raw_p : (out.source_root / raw_p)) .lexically_normal(); rs.is_generated = get_bool(*so, "isGenerated", false); rs.compile_group_index = get_i64(*so, "compileGroupIndex"); - if (rs.is_generated) { - add_unsupported( - pt.name, "generated_source", - std::format("target '{}' depends on generated source '{}' " - "(foreign custom-command producer is not translated)", - pt.name, get_str(*so, "path"))); + const auto fs_idx = get_i64(*so, "fileSetIndex"); + rs.is_module_interface = + module_source_indexes.contains(src_i) || + (fs_idx.has_value() && + module_fileset_indexes.contains(static_cast(*fs_idx))); + if (rs.is_generated && rs.abs_path.extension() != ".rule") { + const auto gen_key = rs.abs_path.generic_string(); + const auto rel_cfg = + rs.abs_path.lexically_relative(ninja_graph.configure_dir) + .generic_string(); + if (!ninja_graph.found_build_ninja || + (!ninja_graph.edge_by_output.contains(gen_key) && + !ninja_graph.edge_by_output.contains(rel_cfg))) { + add_unsupported( + pt.name, "generated_source", + std::format("target '{}' depends on generated source '{}' " + "(no build.ninja CUSTOM_COMMAND producer found)", + pt.name, get_str(*so, "path"))); + } else { + auto mres = custom_mat.materialize_key(gen_key, pt.name); + if (!mres) { + add_unsupported(pt.name, mres.error().construct_kind, + mres.error().detail); + } else { + for (const auto &cn : *mres) { + if (!std::ranges::contains(pt.prereq_target_names, cn)) { + pt.prereq_target_names.push_back(cn); + } + } + } + } } raw_sources.push_back(std::move(rs)); } @@ -345,28 +1247,32 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { } } - // Audit & extract compileGroups. + // Audit & extract compileGroups (supporting C, CXX, mixed C/C++, and per-group flags). + struct GroupSpec { + std::string lang; + CStandard c_std{CStandard::Default}; + CxxStandard cxx_std{CxxStandard::Default}; + std::vector defines; + std::vector compile_options; + std::vector source_paths; + }; + std::vector groups; + if (const auto *cgs = find_key(*td, "compileGroups")) { if (const auto *cgarr = std::get_if(&cgs->value)) { - if (cgarr->size() > 1) { - add_unsupported( - pt.name, "multiple_compile_groups", - std::format("target '{}' has {} distinct compileGroups (mixed languages or " - "per-group flags exceed bounded single-group subset)", - pt.name, cgarr->size())); - } for (const auto &cgv : *cgarr) { const auto *cgo = std::get_if(&cgv.value); if (!cgo) { continue; } - const auto lang = get_str(*cgo, "language"); - if (lang != "CXX") { + GroupSpec gs; + gs.lang = get_str(*cgo, "language"); + if (gs.lang != "CXX" && gs.lang != "C") { add_unsupported( pt.name, "unsupported_language", std::format("target '{}' compiles language '{}' (bounded subset " - "supports CXX only)", - pt.name, lang)); + "supports C and CXX)", + pt.name, gs.lang)); } if (const auto *pchs = find_key(*cgo, "precompileHeaders")) { if (const auto *parr = std::get_if(&pchs->value); @@ -379,14 +1285,24 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { if (const auto *lstd = find_key(*cgo, "languageStandard")) { if (const auto *lo = std::get_if(&lstd->value)) { const auto std_str = get_str(*lo, "standard"); - if (std_str == "17") { - pt.cxx_standard = CxxStandard::Cxx17; - } else if (std_str == "20") { - pt.cxx_standard = CxxStandard::Cxx20; - } else if (std_str == "23") { - pt.cxx_standard = CxxStandard::Cxx23; - } else if (std_str == "26") { - pt.cxx_standard = CxxStandard::Cxx26; + if (gs.lang == "C") { + if (std_str == "11") { + gs.c_std = CStandard::C11; + } else if (std_str == "17" || std_str == "18") { + gs.c_std = CStandard::C17; + } else if (std_str == "23") { + gs.c_std = CStandard::C23; + } + } else { + if (std_str == "17") { + gs.cxx_std = CxxStandard::Cxx17; + } else if (std_str == "20") { + gs.cxx_std = CxxStandard::Cxx20; + } else if (std_str == "23") { + gs.cxx_std = CxxStandard::Cxx23; + } else if (std_str == "26") { + gs.cxx_std = CxxStandard::Cxx26; + } } } } @@ -408,8 +1324,8 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { for (const auto &dv : *darr) { if (const auto *do_obj = std::get_if(&dv.value)) { const auto d = get_str(*do_obj, "define"); - if (!d.empty() && !std::ranges::contains(pt.defines, d)) { - pt.defines.push_back(d); + if (!d.empty() && !std::ranges::contains(gs.defines, d)) { + gs.defines.push_back(d); } } } @@ -421,12 +1337,29 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { if (const auto *fo = std::get_if(&fv.value)) { for (const auto &tok : split_shell_tokens(get_str(*fo, "fragment"))) { - if (tok == "-fPIC" || tok == "-fpic" || - tok.starts_with("-std=")) { + if (auto cstd = parse_c_std_flag(tok); + cstd && gs.lang == "C") { + if (gs.c_std == CStandard::Default) { + gs.c_std = *cstd; + } continue; } - if (!std::ranges::contains(pt.compile_options, tok)) { - pt.compile_options.push_back(tok); + if (auto xstd = parse_cxx_std_flag(tok); + xstd && gs.lang == "CXX") { + if (gs.cxx_std == CxxStandard::Default) { + gs.cxx_std = *xstd; + } + continue; + } + if (tok == "-fPIC" || tok == "-fpic" || + tok.starts_with("-std=") || tok == "-fmodules" || + tok == "-fmodules-ts" || + tok.starts_with("-fmodule-mapper=") || + tok.starts_with("-fdeps-")) { + continue; + } + if (!std::ranges::contains(gs.compile_options, tok)) { + gs.compile_options.push_back(tok); } } } @@ -438,13 +1371,82 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { for (const auto &iv : *siarr) { if (const auto *idx = std::get_if(&iv.value)) { const auto u = static_cast(*idx); - if (u < raw_sources.size() && !raw_sources[u].is_generated) { - pt.sources.push_back(raw_sources[u].abs_path); + if (u < raw_sources.size()) { + const SourceKind skind = raw_sources[u].is_module_interface + ? SourceKind::ModuleInterface + : SourceKind::File; + pt.sources.push_back( + SourceRecord{skind, raw_sources[u].abs_path.string()}); + gs.source_paths.push_back(raw_sources[u].abs_path); } } } } } + groups.push_back(std::move(gs)); + } + } + } + + // Reconcile language standards and common vs per-file options across compileGroups. + for (const auto &gs : groups) { + if (gs.lang == "C" && pt.c_standard == CStandard::Default && + gs.c_std != CStandard::Default) { + pt.c_standard = gs.c_std; + } + if (gs.lang == "CXX" && pt.cxx_standard == CxxStandard::Default && + gs.cxx_std != CxxStandard::Default) { + pt.cxx_standard = gs.cxx_std; + } + } + if (groups.size() == 1) { + pt.defines = std::move(groups.front().defines); + pt.compile_options = std::move(groups.front().compile_options); + } else if (groups.size() > 1) { + for (const auto &d : groups.front().defines) { + const bool in_all = std::ranges::all_of(groups, [&](const GroupSpec &g) { + return std::ranges::contains(g.defines, d); + }); + if (in_all && !std::ranges::contains(pt.defines, d)) { + pt.defines.push_back(d); + } + } + for (const auto &o : groups.front().compile_options) { + const bool in_all = std::ranges::all_of(groups, [&](const GroupSpec &g) { + return std::ranges::contains(g.compile_options, o); + }); + if (in_all && !std::ranges::contains(pt.compile_options, o)) { + pt.compile_options.push_back(o); + } + } + for (const auto &gs : groups) { + for (const auto &sp : gs.source_paths) { + for (const auto &d : gs.defines) { + if (!std::ranges::contains(pt.defines, d)) { + pt.per_file_options.push_back( + PerFileOption{sp.generic_string(), "-D" + d}); + } + } + for (const auto &o : gs.compile_options) { + if (!std::ranges::contains(pt.compile_options, o)) { + pt.per_file_options.push_back(PerFileOption{sp.generic_string(), o}); + } + } + if (gs.lang == "C" && gs.c_std != CStandard::Default && + gs.c_std != pt.c_standard) { + const char *sf = (gs.c_std == CStandard::C11) ? "-std=c11" + : (gs.c_std == CStandard::C17) ? "-std=c17" + : "-std=c23"; + pt.per_file_options.push_back(PerFileOption{sp.generic_string(), sf}); + } + if (gs.lang == "CXX" && gs.cxx_std != CxxStandard::Default && + gs.cxx_std != pt.cxx_standard) { + const char *sf = (gs.cxx_std == CxxStandard::Cxx17) ? "-std=c++17" + : (gs.cxx_std == CxxStandard::Cxx20) ? "-std=c++20" + : (gs.cxx_std == CxxStandard::Cxx23) ? "-std=c++23" + : "-std=c++26"; + pt.per_file_options.push_back(PerFileOption{sp.generic_string(), sf}); + } } } } @@ -532,17 +1534,29 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) { out.targets_by_id[pt.id] = std::move(pt); } - // Verify every dependency edge points to a translated target (never a dropped utility target!). + // Wire UTILITY prerequisite targets and verify every dependency edge resolves cleanly. for (const auto &tid : out.target_order) { - const auto &pt = out.targets_by_id.at(tid); + auto &pt = out.targets_by_id.at(tid); + std::vector link_deps; for (const auto &dep_id : pt.dep_ids) { - if (!out.targets_by_id.contains(dep_id)) { + if (const auto uit = out.utility_target_prereqs.find(dep_id); + uit != out.utility_target_prereqs.end()) { + for (const auto &cname : uit->second) { + if (!std::ranges::contains(pt.prereq_target_names, cname)) { + pt.prereq_target_names.push_back(cname); + } + } + } else if (out.targets_by_id.contains(dep_id)) { + link_deps.push_back(dep_id); + } else { add_unsupported(pt.name, "untranslated_dependency_edge", std::format("target '{}' depends on untranslated CMake target '{}'", pt.name, dep_id)); } } + pt.dep_ids = std::move(link_deps); } + out.synthesized_custom_targets = std::move(custom_mat.targets); if (out.audit.is_supported()) { out.audit.summary = std::format("all {} CMake target(s) fit the bounded native subset", @@ -594,6 +1608,9 @@ configure_cmake_for_translation(const ProviderRequest &request, req.arguments.push_back("-G"); req.arguments.push_back("Ninja"); } + if (!request.toolchain.c_compiler.empty()) { + req.arguments.push_back("-DCMAKE_C_COMPILER=" + request.toolchain.c_compiler.string()); + } req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string()); const std::string btype = (request.profile.name == "release" || request.profile.name == "Release") ? "Release" @@ -641,6 +1658,10 @@ Void::Result::Result translate_cmake_ desc.profile.compile_options.clear(); desc.profile.defines.clear(); + for (const auto &ca : loaded->synthesized_custom_targets) { + desc.targets.push_back(ca); + } + for (const auto &tid : loaded->target_order) { const auto &pt = loaded->targets_by_id.at(tid); TargetRecord tr; @@ -654,11 +1675,12 @@ Void::Result::Result translate_cmake_ } else { tr.kind = TargetKind::Executable; } + tr.c_standard = pt.c_standard; tr.cxx_standard = pt.cxx_standard; + tr.sources = pt.sources; + tr.per_file_options = pt.per_file_options; + tr.prerequisites = pt.prereq_target_names; - for (const auto &src : pt.sources) { - tr.sources.push_back(SourceRecord{SourceKind::File, src.string()}); - } for (const auto &[inc, is_sys] : pt.includes) { tr.include_directories.push_back( IncludeDirectory{inc.string(), Visibility::Public, is_sys}); @@ -710,6 +1732,7 @@ Void::Result::Result translate_cmake_ iface.include_dirs = pt.includes; iface.defines = pt.defines; iface.link_options = pt.link_options; + iface.module_bmis = sit->second->exported_module_bmis; // Collect primary output + transitive static/shared outputs in dependency order. if (!sit->second->primary_outputs.empty()) { @@ -756,6 +1779,9 @@ Void::Result::Result translate_cmake_ iface.shared_libraries.push_back(dep_out); iface.runtime_files.push_back(dep_out); } + for (const auto &[mname, bmi_p] : dsit->second->exported_module_bmis) { + iface.module_bmis.try_emplace(mname, bmi_p); + } } result.exported_targets[pt.name] = iface; @@ -895,19 +1921,24 @@ struct ParsedMesonTarget { std::vector> includes; std::vector defines; std::vector compile_options; + std::vector per_file_options; std::vector link_options; + CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; std::vector dep_ids; + std::vector prereq_target_names; }; struct ParsedMesonModel { TranslationAuditReport audit; + std::vector synthesized_custom_targets; std::map> targets_by_id; std::vector target_order; }; Void::Result::Result -load_and_audit_meson(const std::filesystem::path &configure_dir) { +load_and_audit_meson(const std::filesystem::path &configure_dir, + const std::filesystem::path &source_root = {}) { const auto intro_targets = configure_dir / "meson-info" / "intro-targets.json"; auto parsed = parse_json_file(intro_targets); if (!parsed) { @@ -929,7 +1960,28 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { UnsupportedConstruct{std::move(target_name), std::move(kind), std::move(detail)}); }; - // Map known output filenames (relative & absolute) -> target id for link edge recovery. + // Map known output filenames (relative & absolute) -> target id for link edge recovery, + // and parse build.ninja custom rules for hermetic custom_target / generated_sources + // translation. + std::set compiled_artifacts; + for (const auto &tv : *arr) { + const auto *to = std::get_if(&tv.value); + if (!to) { + continue; + } + const auto ttype = get_str(*to, "type"); + if (ttype == "static library" || ttype == "shared library" || ttype == "executable") { + for (const auto &fn : get_str_array(*to, "filename")) { + const auto p = std::filesystem::path{fn}.lexically_normal(); + compiled_artifacts.insert(p.string()); + compiled_artifacts.insert(p.filename().string()); + } + } + } + const NinjaCustomGraph ninja_graph = parse_ninja_custom_graph(configure_dir, source_root); + CustomActionMaterializer custom_mat{ninja_graph, compiled_artifacts}; + std::map custom_target_by_output; + std::map> artifact_to_id; for (const auto &tv : *arr) { @@ -945,12 +1997,46 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { pt.id = pt.name; } - if (pt.type == "custom" || pt.type == "run") { + if (pt.type == "run") { add_unsupported( - pt.name, "custom_target", - std::format("Meson target '{}' has type '{}' (custom/run targets cannot be " - "faithfully translated from intro-targets.json)", - pt.name, pt.type)); + pt.name, "run_target", + std::format("Meson target '{}' has type 'run' (non-artifact run targets are " + "outside bounded native translation)", + pt.name)); + continue; + } + if (pt.type == "custom") { + const auto fns = get_str_array(*to, "filename"); + if (fns.empty() || !ninja_graph.found_build_ninja) { + add_unsupported( + pt.name, "custom_target", + std::format("Meson custom target '{}' lacks verifiable outputs or build.ninja", + pt.name)); + continue; + } + bool ok = true; + for (const auto &fn : fns) { + const auto abs_fn = std::filesystem::path{fn}.lexically_normal(); + const auto mres = custom_mat.materialize_key(abs_fn.generic_string(), pt.name); + if (!mres || mres->empty()) { + if (!mres) { + add_unsupported(pt.name, mres.error().construct_kind, mres.error().detail); + } else { + add_unsupported( + pt.name, "custom_target", + std::format( + "Meson custom target '{}' output '{}' has no CUSTOM_COMMAND " + "producer", + pt.name, fn)); + } + ok = false; + break; + } + custom_target_by_output[abs_fn] = mres->front(); + } + if (ok) { + out.audit.supported_targets.push_back(pt.name); + } continue; } if (pt.type != "static library" && pt.type != "shared library" && pt.type != "executable") { @@ -971,6 +2057,16 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { } } + struct MesonGroupSpec { + std::string lang; + CStandard c_std{CStandard::Default}; + CxxStandard cxx_std{CxxStandard::Default}; + std::vector defines; + std::vector compile_options; + std::vector source_paths; + }; + std::vector groups; + if (const auto *ts = find_key(*to, "target_sources")) { if (const auto *tsarr = std::get_if(&ts->value)) { for (const auto &tsv : *tsarr) { @@ -978,25 +2074,49 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { if (!tso) { continue; } - const auto lang = get_str(*tso, "language"); + MesonGroupSpec gs; + gs.lang = get_str(*tso, "language"); const auto srcs = get_str_array(*tso, "sources"); const auto gen_srcs = get_str_array(*tso, "generated_sources"); - if (!gen_srcs.empty()) { - add_unsupported( - pt.name, "generated_source", - std::format("Meson target '{}' depends on {} generated source(s) " - "(first: '{}')", - pt.name, gen_srcs.size(), gen_srcs.front())); - } - if (!srcs.empty() && lang != "cpp") { + if ((!srcs.empty() || !gen_srcs.empty()) && + (gs.lang != "cpp" && gs.lang != "c")) { add_unsupported( pt.name, "unsupported_language", std::format("Meson target '{}' compiles language '{}' (bounded subset " - "supports cpp only)", - pt.name, lang)); + "supports c and cpp)", + pt.name, gs.lang)); + } + for (const auto &g : gen_srcs) { + const auto gp = std::filesystem::path{g}; + const auto g_abs = + (gp.is_absolute() ? gp : (configure_dir / gp)).lexically_normal(); + auto mres = custom_mat.materialize_key(g_abs.generic_string(), pt.name); + if (!mres || mres->empty()) { + if (!mres) { + add_unsupported(pt.name, mres.error().construct_kind, + mres.error().detail); + } else { + add_unsupported( + pt.name, "generated_source", + std::format("Meson target '{}' generated source '{}' has no " + "hermetic CUSTOM_COMMAND producer", + pt.name, g)); + } + } else { + for (const auto &cn : *mres) { + if (!std::ranges::contains(pt.prereq_target_names, cn)) { + pt.prereq_target_names.push_back(cn); + } + } + custom_target_by_output[g_abs] = mres->front(); + } + pt.sources.push_back(g_abs); + gs.source_paths.push_back(g_abs); } for (const auto &s : srcs) { - pt.sources.push_back(std::filesystem::path{s}.lexically_normal()); + const auto sp = std::filesystem::path{s}.lexically_normal(); + pt.sources.push_back(sp); + gs.source_paths.push_back(sp); } const auto params = get_str_array(*tso, "parameters"); @@ -1028,36 +2148,114 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { } } else if (p.starts_with("-D") && p.size() > 2) { const std::string def = p.substr(2); - if (!std::ranges::contains(pt.defines, def)) { - pt.defines.push_back(def); + if (def == "_FILE_OFFSET_BITS=64") { + continue; + } + if (!std::ranges::contains(gs.defines, def)) { + gs.defines.push_back(def); } } else if (p == "-D" && i + 1 < params.size()) { const std::string def = params[++i]; - if (!std::ranges::contains(pt.defines, def)) { - pt.defines.push_back(def); + if (def != "_FILE_OFFSET_BITS=64" && + !std::ranges::contains(gs.defines, def)) { + gs.defines.push_back(def); } - } else if (p == "-std=c++17" || p == "-std=gnu++17") { - pt.cxx_standard = CxxStandard::Cxx17; - } else if (p == "-std=c++20" || p == "-std=gnu++20") { - pt.cxx_standard = CxxStandard::Cxx20; - } else if (p == "-std=c++23" || p == "-std=gnu++23") { - pt.cxx_standard = CxxStandard::Cxx23; - } else if (p == "-std=c++26" || p == "-std=gnu++26") { - pt.cxx_standard = CxxStandard::Cxx26; + } else if (auto cstd = parse_c_std_flag(p); cstd && gs.lang == "c") { + gs.c_std = *cstd; + } else if (auto xstd = parse_cxx_std_flag(p); xstd && gs.lang == "cpp") { + gs.cxx_std = *xstd; } else if (p == "-fPIC" || p == "-fpic" || p == "-fdiagnostics-color=always" || p == "-pipe" || - p == "-D_FILE_OFFSET_BITS=64") { + p.starts_with("-std=")) { continue; } else if (p == "-pthread") { - if (!std::ranges::contains(pt.compile_options, p)) { - pt.compile_options.push_back(p); + if (!std::ranges::contains(gs.compile_options, p)) { + gs.compile_options.push_back(p); } if (!std::ranges::contains(pt.link_options, p)) { pt.link_options.push_back(p); } } else if (!p.empty() && p[0] == '-') { - if (!std::ranges::contains(pt.compile_options, p)) { - pt.compile_options.push_back(p); + if (!std::ranges::contains(gs.compile_options, p)) { + gs.compile_options.push_back(p); + } + } + } + groups.push_back(std::move(gs)); + } + } + } + + for (const auto &gs : groups) { + if (gs.lang == "c" && pt.c_standard == CStandard::Default && + gs.c_std != CStandard::Default) { + pt.c_standard = gs.c_std; + } + if (gs.lang == "cpp" && pt.cxx_standard == CxxStandard::Default && + gs.cxx_std != CxxStandard::Default) { + pt.cxx_standard = gs.cxx_std; + } + } + if (groups.size() == 1) { + pt.defines = std::move(groups.front().defines); + pt.compile_options = std::move(groups.front().compile_options); + } else if (groups.size() > 1) { + for (const auto &d : groups.front().defines) { + if (std::ranges::all_of(groups, + [&](const MesonGroupSpec &g) { + return std::ranges::contains(g.defines, d); + }) && + !std::ranges::contains(pt.defines, d)) { + pt.defines.push_back(d); + } + } + for (const auto &o : groups.front().compile_options) { + if (std::ranges::all_of(groups, + [&](const MesonGroupSpec &g) { + return std::ranges::contains(g.compile_options, o); + }) && + !std::ranges::contains(pt.compile_options, o)) { + pt.compile_options.push_back(o); + } + } + for (const auto &gs : groups) { + for (const auto &sp : gs.source_paths) { + for (const auto &d : gs.defines) { + if (!std::ranges::contains(pt.defines, d)) { + pt.per_file_options.push_back( + PerFileOption{sp.generic_string(), "-D" + d}); + } + } + for (const auto &o : gs.compile_options) { + if (!std::ranges::contains(pt.compile_options, o)) { + pt.per_file_options.push_back(PerFileOption{sp.generic_string(), o}); + } + } + } + } + } + + // Attach any custom-target header/source dependencies referenced by this target's compile + // edges. + for (const auto &sp : pt.sources) { + if (const auto cit = ninja_graph.compiler_extra_deps_by_src.find(sp); + cit != ninja_graph.compiler_extra_deps_by_src.end()) { + for (const auto &dep_out : cit->second) { + if (const auto ctit = custom_target_by_output.find(dep_out); + ctit != custom_target_by_output.end()) { + if (!std::ranges::contains(pt.prereq_target_names, ctit->second)) { + pt.prereq_target_names.push_back(ctit->second); + } + } else if (ninja_graph.edge_by_output.contains(dep_out.generic_string())) { + auto mres = custom_mat.materialize_key(dep_out.generic_string(), pt.name); + if (!mres) { + add_unsupported(pt.name, mres.error().construct_kind, + mres.error().detail); + } else { + for (const auto &cn : *mres) { + if (!std::ranges::contains(pt.prereq_target_names, cn)) { + pt.prereq_target_names.push_back(cn); + } } } } @@ -1069,26 +2267,18 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { out.target_order.push_back(pt.id); out.targets_by_id[pt.id] = std::move(pt); } + out.synthesized_custom_targets = std::move(custom_mat.targets); // Recover internal target link edges cleanly from Meson's configured `build.ninja` - // (`build : cpp_LINKER ... | ` + `LINK_ARGS = ...`). + // (`build : {c,cpp}_LINKER ... | ` + `LINK_ARGS = ...`). if (auto ninja_text = Void::FileSystem::read_file(configure_dir / "build.ninja"); ninja_text) { std::string cur_target_id; - std::size_t pos = 0; - while (pos < ninja_text->size()) { - const auto nl = ninja_text->find('\n', pos); - std::string_view line = std::string_view{*ninja_text}.substr( - pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); - if (!line.empty() && line.back() == '\r') { - line.remove_suffix(1); - } - pos = (nl == std::string_view::npos) ? ninja_text->size() : (nl + 1); - + for (const auto &line : split_ninja_logical_lines(*ninja_text)) { if (line.starts_with("build ")) { cur_target_id.clear(); - const auto colon = line.find(':'); + const auto colon = find_unescaped_ninja_colon(std::string_view{line}.substr(6)); if (colon != std::string_view::npos) { - const auto outs_part = line.substr(6, colon - 6); + const auto outs_part = std::string_view{line}.substr(6, colon); for (const auto &tok : split_shell_tokens(outs_part)) { if (const auto ait = artifact_to_id.find(tok); ait != artifact_to_id.end()) { @@ -1098,7 +2288,7 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { } if (!cur_target_id.empty()) { auto &pt = out.targets_by_id.at(cur_target_id); - const auto rhs = line.substr(colon + 1); + const auto rhs = std::string_view{line}.substr(6 + colon + 1); for (const auto &tok : split_shell_tokens(rhs)) { if (const auto ait = artifact_to_id.find(tok); ait != artifact_to_id.end() && ait->second != cur_target_id) { @@ -1111,7 +2301,7 @@ load_and_audit_meson(const std::filesystem::path &configure_dir) { } } else if (!cur_target_id.empty() && line.starts_with(" LINK_ARGS = ")) { auto &pt = out.targets_by_id.at(cur_target_id); - const auto args_part = line.substr(13); + const auto args_part = std::string_view{line}.substr(13); for (const auto &tok : split_shell_tokens(args_part)) { if (tok.empty() || tok == "-Wl,--as-needed" || tok == "-Wl,--no-undefined" || tok == "-Wl,--start-group" || tok == "-Wl,--end-group" || @@ -1181,6 +2371,9 @@ configure_meson_for_translation(const ProviderRequest &request, for (const auto &[k, v] : request.dependency.options) { req.arguments.push_back("-D" + k + "=" + meson_option_value(v)); } + if (!request.toolchain.c_compiler.empty()) { + req.environment.set_vars["CC"] = request.toolchain.c_compiler.string(); + } req.environment.set_vars["CXX"] = request.toolchain.cxx_compiler.string(); req.timeout = std::chrono::seconds{180}; auto proc = Platform::run_supervised(req, stop); @@ -1205,7 +2398,7 @@ audit_meson_introspection(const std::filesystem::path &configure_dir) { Void::Result::Result translate_meson_to_native_graph( const ProviderRequest &request, const std::filesystem::path &configure_dir, const std::filesystem::path &native_build_root, const Snapshot::InputSnapshot *snapshot) { - auto loaded = load_and_audit_meson(configure_dir); + auto loaded = load_and_audit_meson(configure_dir, request.source.source_dir); if (!loaded) { return std::unexpected{loaded.error()}; } @@ -1219,6 +2412,10 @@ Void::Result::Result translate_meson_ desc.profile.compile_options.clear(); desc.profile.defines.clear(); + for (const auto &ca : loaded->synthesized_custom_targets) { + desc.targets.push_back(ca); + } + for (const auto &tid : loaded->target_order) { const auto &pt = loaded->targets_by_id.at(tid); TargetRecord tr; @@ -1230,7 +2427,10 @@ Void::Result::Result translate_meson_ } else { tr.kind = TargetKind::Executable; } + tr.c_standard = pt.c_standard; tr.cxx_standard = pt.cxx_standard; + tr.per_file_options = pt.per_file_options; + tr.prerequisites = pt.prereq_target_names; for (const auto &src : pt.sources) { tr.sources.push_back(SourceRecord{SourceKind::File, src.string()}); @@ -1291,6 +2491,7 @@ Void::Result::Result translate_meson_ } iface.defines = pt.defines; iface.link_options = pt.link_options; + iface.module_bmis = sit->second->exported_module_bmis; if (!sit->second->primary_outputs.empty()) { const auto &primary = sit->second->primary_outputs.front(); diff --git a/src/Toolchain/Driver.cpp b/src/Toolchain/Driver.cpp index 35af57a..99ff19d 100644 --- a/src/Toolchain/Driver.cpp +++ b/src/Toolchain/Driver.cpp @@ -47,10 +47,11 @@ std::map> capture_relevant_env() { } bool probe_compile_flag(const std::filesystem::path &compiler, const std::string &sysroot, - const std::vector &extra_flags, std::string_view source_code) { + const std::vector &extra_flags, std::string_view source_code, + std::string_view language = "c++") { Platform::ProcessRequest req; req.executable = compiler; - req.arguments = {"-x", "c++", "-fsyntax-only"}; + req.arguments = {"-x", std::string{language}, "-fsyntax-only"}; if (!sysroot.empty()) { req.arguments.push_back("--sysroot=" + sysroot); } @@ -70,6 +71,20 @@ std::size_t estimate_argv_bytes(const std::vector &args) { return total; } +std::string c_standard_flag(CStandard standard) { + switch (standard) { + case CStandard::Default: + return {}; + case CStandard::C11: + return "-std=c11"; + case CStandard::C17: + return "-std=c17"; + case CStandard::C23: + return "-std=c23"; + } + return {}; +} + std::string cxx_standard_flag(CxxStandard standard) { switch (standard) { case CxxStandard::Default: @@ -108,6 +123,7 @@ std::string serialize_capabilities(const ToolchainCapabilities &cap) { std::string out = "{"; out += "\"family\":" + json_quote(compiler_name(cap.family)); out += ",\"cxx_compiler\":" + json_quote(cap.cxx_compiler.string()); + out += ",\"c_compiler\":" + json_quote(cap.c_compiler.string()); out += ",\"archiver\":" + json_quote(cap.archiver.string()); out += ",\"module_scanner\":" + json_quote(cap.module_scanner ? cap.module_scanner->string() : std::string{}); @@ -115,7 +131,12 @@ std::string serialize_capabilities(const ToolchainCapabilities &cap) { out += ",\"target_triple\":" + json_quote(cap.target_triple); out += ",\"sysroot\":" + json_quote(cap.sysroot); out += ",\"compiler_sha256\":" + json_quote(cap.compiler_sha256); + out += ",\"c_compiler_sha256\":" + json_quote(cap.c_compiler_sha256); out += ",\"archiver_sha256\":" + json_quote(cap.archiver_sha256); + out += ",\"default_include_dirs\":" + json_array(cap.default_include_dirs, json_quote); + out += ",\"supports_c11\":" + std::string{cap.supports_c11 ? "true" : "false"}; + out += ",\"supports_c17\":" + std::string{cap.supports_c17 ? "true" : "false"}; + out += ",\"supports_c23\":" + std::string{cap.supports_c23 ? "true" : "false"}; out += ",\"supports_cxx17\":" + std::string{cap.supports_cxx17 ? "true" : "false"}; out += ",\"supports_cxx20\":" + std::string{cap.supports_cxx20 ? "true" : "false"}; out += ",\"supports_cxx23\":" + std::string{cap.supports_cxx23 ? "true" : "false"}; @@ -170,6 +191,7 @@ std::optional deserialize_capabilities(std::string_view t ToolchainCapabilities cap; cap.family = parse_compiler(get_str("family").value_or("")); cap.cxx_compiler = get_str("cxx_compiler").value_or(""); + cap.c_compiler = get_str("c_compiler").value_or(""); cap.archiver = get_str("archiver").value_or(""); if (auto scanner = get_str("module_scanner"); scanner && !scanner->empty()) { cap.module_scanner = *scanner; @@ -178,7 +200,22 @@ std::optional deserialize_capabilities(std::string_view t cap.target_triple = get_str("target_triple").value_or(""); cap.sysroot = get_str("sysroot").value_or(""); cap.compiler_sha256 = get_str("compiler_sha256").value_or(""); + cap.c_compiler_sha256 = get_str("c_compiler_sha256").value_or(""); cap.archiver_sha256 = get_str("archiver_sha256").value_or(""); + if (const auto dit = obj->find("default_include_dirs"); dit != obj->end()) { + if (const auto *darr = + std::get_if(&dit->second.value)) { + for (const auto &item : *darr) { + if (const auto *ds = std::get_if(&item.value); + ds && !ds->empty()) { + cap.default_include_dirs.push_back(*ds); + } + } + } + } + cap.supports_c11 = get_bool("supports_c11").value_or(false); + cap.supports_c17 = get_bool("supports_c17").value_or(false); + cap.supports_c23 = get_bool("supports_c23").value_or(false); cap.supports_cxx17 = get_bool("supports_cxx17").value_or(false); cap.supports_cxx20 = get_bool("supports_cxx20").value_or(false); cap.supports_cxx23 = get_bool("supports_cxx23").value_or(false); @@ -242,6 +279,33 @@ discover_and_probe(const ProfileContext &context, requested_compiler.string(), compiler_name(context.compiler)))}; } + std::filesystem::path requested_c_compiler = + context.compiler == CompilerFamily::Gcc ? "gcc" : "clang"; + if (!context.compiler_path.empty()) { + const std::filesystem::path cp_path{context.compiler_path}; + const std::string fname = cp_path.filename().string(); + if (fname == "g++" || fname.ends_with("-g++")) { + const std::string c_name = fname.substr(0, fname.size() - 3) + "gcc"; + requested_c_compiler = cp_path.parent_path().empty() ? std::filesystem::path{c_name} + : (cp_path.parent_path() / c_name); + } else if (fname == "clang++" || fname.ends_with("-clang++")) { + const std::string c_name = fname.substr(0, fname.size() - 7) + "clang"; + requested_c_compiler = cp_path.parent_path().empty() ? std::filesystem::path{c_name} + : (cp_path.parent_path() / c_name); + } + } + auto resolved_c_compiler = Platform::resolve_executable(requested_c_compiler); + if (!resolved_c_compiler && !context.compiler_path.empty()) { + resolved_c_compiler = + Platform::resolve_executable(context.compiler == CompilerFamily::Gcc ? "gcc" : "clang"); + } + std::string c_comp_hash; + if (resolved_c_compiler) { + if (auto ch = Util::sha256_file_hex(*resolved_c_compiler); ch) { + c_comp_hash = *ch; + } + } + std::optional resolved_ar; if (context.compiler == CompilerFamily::Clang) { resolved_ar = Platform::resolve_executable("llvm-ar"); @@ -271,9 +335,14 @@ discover_and_probe(const ProfileContext &context, // Compute cache key BEFORE expensive compiler probes. Util::Sha256Hasher key_hasher; + key_hasher.update_length_prefixed("vbs-probe-v2"); key_hasher.update_length_prefixed(compiler_name(context.compiler)); key_hasher.update_length_prefixed(resolved_compiler->string()); key_hasher.update_length_prefixed(*comp_hash); + if (resolved_c_compiler) { + key_hasher.update_length_prefixed(resolved_c_compiler->string()); + key_hasher.update_length_prefixed(c_comp_hash); + } key_hasher.update_length_prefixed(resolved_ar->string()); key_hasher.update_length_prefixed(*ar_hash); key_hasher.update_length_prefixed(context.sysroot); @@ -298,9 +367,11 @@ discover_and_probe(const ProfileContext &context, ToolchainCapabilities cap; cap.family = context.compiler; cap.cxx_compiler = *resolved_compiler; + cap.c_compiler = resolved_c_compiler.value_or(std::filesystem::path{}); cap.archiver = *resolved_ar; cap.sysroot = context.sysroot; cap.compiler_sha256 = *comp_hash; + cap.c_compiler_sha256 = c_comp_hash; cap.archiver_sha256 = *ar_hash; cap.relevant_env = relevant_env; @@ -338,9 +409,50 @@ discover_and_probe(const ProfileContext &context, if (cap.family == CompilerFamily::Clang) { cap.module_scanner = Platform::resolve_executable("clang-scan-deps"); cap.supports_p1689_scan = cap.module_scanner.has_value(); + + Platform::ProcessRequest ireq; + ireq.executable = cap.cxx_compiler; + ireq.arguments = {"-x", "c++", "-E", "-v"}; + if (!cap.sysroot.empty()) { + ireq.arguments.push_back("--sysroot=" + cap.sysroot); + } + ireq.arguments.push_back("-"); + ireq.timeout = std::chrono::seconds{10}; + if (auto ires = Platform::run_supervised(ireq); ires) { + const std::string combined = ires->stderr_data + "\n" + ires->stdout_data; + bool in_search = false; + std::size_t pos = 0; + while (pos < combined.size()) { + const auto nl = combined.find('\n', pos); + const std::string line = trim(std::string_view{combined}.substr( + pos, nl == std::string::npos ? std::string::npos : nl - pos)); + pos = (nl == std::string::npos) ? combined.size() : (nl + 1); + if (line.find("#include <...> search starts here:") != std::string::npos) { + in_search = true; + continue; + } + if (in_search) { + if (line.starts_with("End of search list")) { + break; + } + if (!line.empty() && line.find("(framework directory)") == std::string::npos) { + cap.default_include_dirs.push_back(line); + } + } + } + } } // Syntax-only capability probes (safe for cross-toolchains). + constexpr std::string_view kTrivialC = "int vbs_c_probe(void) { return 0; }\n"; + if (!cap.c_compiler.empty()) { + cap.supports_c11 = + probe_compile_flag(cap.c_compiler, cap.sysroot, {"-std=c11"}, kTrivialC, "c"); + cap.supports_c17 = + probe_compile_flag(cap.c_compiler, cap.sysroot, {"-std=c17"}, kTrivialC, "c"); + cap.supports_c23 = + probe_compile_flag(cap.c_compiler, cap.sysroot, {"-std=c23"}, kTrivialC, "c"); + } constexpr std::string_view kTrivialCpp = "int vbs_probe() { return 0; }\n"; cap.supports_cxx17 = probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++17"}, kTrivialCpp); @@ -404,6 +516,7 @@ std::string compute_profile_identity(const ProfileContext &context, hasher.update_length_prefixed(context.os); hasher.update_length_prefixed(context.architecture); hasher.update_length_prefixed(toolchain.identity_hash); + hasher.update_length_prefixed(c_standard_name(context.c_standard)); hasher.update_length_prefixed(cxx_standard_name(context.cxx_standard)); hasher.update_length_prefixed(lto_mode_name(context.lto)); hasher.update_length_prefixed(context.sysroot); @@ -457,17 +570,32 @@ lower_compile_command(const ToolchainCapabilities &toolchain, const CompileReque } // Validate requested capabilities explicitly (never silently downgrade). - if (request.cxx_standard == CxxStandard::Cxx17 && !toolchain.supports_cxx17) { - return std::unexpected{make_error("target compiler does not support -std=c++17")}; - } - if (request.cxx_standard == CxxStandard::Cxx20 && !toolchain.supports_cxx20) { - return std::unexpected{make_error("target compiler does not support -std=c++20")}; - } - if (request.cxx_standard == CxxStandard::Cxx23 && !toolchain.supports_cxx23) { - return std::unexpected{make_error("target compiler does not support -std=c++23")}; - } - if (request.cxx_standard == CxxStandard::Cxx26 && !toolchain.supports_cxx26) { - return std::unexpected{make_error("target compiler does not support -std=c++26")}; + if (request.is_c_source) { + if (toolchain.c_compiler.empty()) { + return std::unexpected{make_error("target C compiler was not discovered")}; + } + if (request.c_standard == CStandard::C11 && !toolchain.supports_c11) { + return std::unexpected{make_error("target C compiler does not support -std=c11")}; + } + if (request.c_standard == CStandard::C17 && !toolchain.supports_c17) { + return std::unexpected{make_error("target C compiler does not support -std=c17")}; + } + if (request.c_standard == CStandard::C23 && !toolchain.supports_c23) { + return std::unexpected{make_error("target C compiler does not support -std=c23")}; + } + } else { + if (request.cxx_standard == CxxStandard::Cxx17 && !toolchain.supports_cxx17) { + return std::unexpected{make_error("target compiler does not support -std=c++17")}; + } + if (request.cxx_standard == CxxStandard::Cxx20 && !toolchain.supports_cxx20) { + return std::unexpected{make_error("target compiler does not support -std=c++20")}; + } + if (request.cxx_standard == CxxStandard::Cxx23 && !toolchain.supports_cxx23) { + return std::unexpected{make_error("target compiler does not support -std=c++23")}; + } + if (request.cxx_standard == CxxStandard::Cxx26 && !toolchain.supports_cxx26) { + return std::unexpected{make_error("target compiler does not support -std=c++26")}; + } } if (request.lto == LtoMode::Full && !toolchain.supports_lto_full) { return std::unexpected{make_error("target compiler does not support full LTO (-flto)")}; @@ -495,14 +623,20 @@ lower_compile_command(const ToolchainCapabilities &toolchain, const CompileReque } LoweredCommand cmd; - cmd.executable = toolchain.cxx_compiler; + cmd.executable = request.is_c_source ? toolchain.c_compiler : toolchain.cxx_compiler; std::vector args; if (!toolchain.sysroot.empty()) { args.push_back("--sysroot=" + toolchain.sysroot); } - if (const auto std_flag = cxx_standard_flag(request.cxx_standard); !std_flag.empty()) { - args.push_back(std_flag); + if (request.is_c_source) { + if (const auto std_flag = c_standard_flag(request.c_standard); !std_flag.empty()) { + args.push_back(std_flag); + } + } else { + if (const auto std_flag = cxx_standard_flag(request.cxx_standard); !std_flag.empty()) { + args.push_back(std_flag); + } } if (request.position_independent) { args.push_back("-fPIC"); diff --git a/src/Watch/Watcher.cpp b/src/Watch/Watcher.cpp index 36705fe..f566bda 100644 --- a/src/Watch/Watcher.cpp +++ b/src/Watch/Watcher.cpp @@ -262,6 +262,8 @@ WatchCycleReport run_reconcile_cycle(const WatchLoopOptions &options, std::size_ popts.build_root = options.frontend.build_root; popts.update_selection = allow_selection_update; popts.reserved_ticket = reserved_ticket; + popts.sdk_include_dir = options.frontend.sdk_include_dir; + popts.extra_build_sources = options.frontend.extra_build_sources; auto pub = Editor::publish_profile_compdb(*graph, popts); if (!pub) { rep.diagnostic = pub.error().message(); diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 2fe48bd..6787f25 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -45,10 +45,15 @@ check_process(2 "" "--prefix is required" uninstall) check_process(2 "" "--input and --output-dir are required" gen-tests) check_process(0 "Usage: vbs publish " "" publish --help) check_process(2 "" "--registry, --name, and --version are required" publish) +check_process(0 "Usage: vbs ide .*Commands:.*generate.*query" "" ide --help) +check_process(0 "Usage: vbs ide generate " "" ide generate --help) +check_process(0 "Usage: vbs ide query " "" ide query --help) +check_process(2 "" "missing subcommand for 'vbs ide'" ide) +check_process(2 "" "unknown IDE kind" ide generate --editor invalid_ide) execute_process(COMMAND "${VBS_REGISTRY}" --help RESULT_VARIABLE reg_code OUTPUT_VARIABLE reg_out ERROR_VARIABLE reg_err TIMEOUT 15) if(NOT "${reg_code}" STREQUAL "0" OR NOT reg_out MATCHES "Usage: vbs-registry") message(FATAL_ERROR "vbs-registry --help failed: code=${reg_code}\nstdout=[${reg_out}]\nstderr=[${reg_err}]") endif() -message(STATUS "32 native CLI and auto-generated Argparse help contracts verified") +message(STATUS "37 native CLI and auto-generated Argparse help contracts verified") diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index b746215..e94b84c 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -1174,25 +1174,18 @@ target_link_libraries(p20_cli PRIVATE p20_core) } } - // 3. Unsupported CMake construct (`add_custom_command` generated header + `UTILITY` target): + // 3. Unsupported CMake construct (`USES_TERMINAL` console-pool custom target): // audit MUST detect and report explicitly (never silently drop!), `RequireNative` MUST fail, // and `FallbackToForeignBuild` MUST cleanly delegate to foreign CMake and build the artifact! const auto unsup_src = tmp / "unsupported_cmake"; - write_file(unsup_src / "gen.cmake", "file(WRITE \"${OUT}\" \"#define P20_GEN_VAL 55\\n\")\n"); write_file(unsup_src / "CMakeLists.txt", R"cmake( cmake_minimum_required(VERSION 3.20) project(p20_gen LANGUAGES CXX) -add_custom_command( - OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp" - COMMAND ${CMAKE_COMMAND} -DOUT=${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp -P ${CMAKE_CURRENT_SOURCE_DIR}/gen.cmake -) -add_custom_target(run_gen DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp") -add_library(p20_genlib STATIC src/genlib.cpp "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp") -add_dependencies(p20_genlib run_gen) -target_include_directories(p20_genlib PUBLIC "${CMAKE_CURRENT_BINARY_DIR}") +add_custom_target(run_console COMMAND ${CMAKE_COMMAND} -E echo p20_console USES_TERMINAL) +add_library(p20_genlib STATIC src/genlib.cpp) +add_dependencies(p20_genlib run_console) )cmake"); - write_file(unsup_src / "src" / "genlib.cpp", - "#include \"gen_val.hpp\"\nint p20_gen_fn() { return P20_GEN_VAL; }\n"); + write_file(unsup_src / "src" / "genlib.cpp", "int p20_gen_fn() { return 55; }\n"); DependencyRecord udep; udep.name = "p20_gen"; @@ -1306,13 +1299,14 @@ executable('mapp', 'src/main.cpp', include_directories: inc, link_with: lib) Void::Testing::expect_eq(run_out->stdout_data, std::string{"42\n"}); } - // 2. Unsupported Meson `custom_target`: RequireNative MUST fail cleanly; FallbackToForeignBuild - // MUST build via foreign Meson provider! + // 2. Unsupported Meson `console: true` custom_target: RequireNative MUST fail cleanly; + // FallbackToForeignBuild MUST build via foreign Meson provider! const auto u_src = tmp / "meson_custom"; write_file(u_src / "meson.build", R"meson( project('p20m_custom', 'cpp') gen = custom_target('gen_hdr', output: 'gen_num.hpp', + console: true, command: ['/bin/sh', '-c', 'printf "#define M_GEN_NUM 88\n" > "$1"', '--', '@OUTPUT@']) static_library('mgenlib', ['src/gen.cpp', gen]) )meson"); @@ -1486,3 +1480,683 @@ void build(Void::Build::Project &p) { Void::Testing::expect(res->stdout_data.find("PASSED 'consumer_test'") != std::string::npos); } } + +// === Track B1: First-class C driver & mixed C/C++ native CMake + Meson translation === +VOID_TEST(FullV1Tests, track_b1_native_c_driver_and_mixed_c_cpp_cmake_meson_translation) { + Void::FileSystem::TempDir tmp{"vbs_track_b1_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) { + return; + } + Void::Testing::expect(!tc->c_compiler.empty()); + Void::Testing::expect(tc->supports_c11 && tc->supports_c17 && tc->supports_c23); + + auto state = State::StateStore::open(tmp / "state"); + Void::Testing::expect(state.has_value()); + if (!state) { + return; + } + + // 1. Pure VBS native C17 static library + C++23 executable + CompDB separation. + { + const auto proj = tmp / "native_mixed"; + const auto bdir = tmp / "native_mixed_build"; + write_file(proj / "include" / "c_math.h", + "#pragma once\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n" + "int vbs_c_add(int a, int b);\n#ifdef __cplusplus\n}\n#endif\n"); + write_file(proj / "src" / "c_math.c", + "#include \"c_math.h\"\n" + "_Static_assert(sizeof(int) >= 4, \"C11 _Static_assert check\");\n" + "int vbs_c_add(int a, int b) { return a + b; }\n"); + write_file(proj / "src" / "main.cpp", + "#include \"c_math.h\"\n#include \n" + "int main() { std::cout << \"c17+cxx23=\" << vbs_c_add(19, 23) << '\\n'; " + "return 0; }\n"); + + Graph::ProjectDescription desc; + desc.profile = ctx; + TargetRecord clib; + clib.name = "c_core"; + clib.kind = TargetKind::StaticLibrary; + clib.c_standard = CStandard::C17; + clib.sources.push_back({SourceKind::File, "src/c_math.c"}); + clib.include_directories.push_back({"include", Visibility::Public, false}); + desc.targets.push_back(clib); + + TargetRecord app; + app.name = "mixed_app"; + app.kind = TargetKind::Executable; + app.cxx_standard = CxxStandard::Cxx23; + app.sources.push_back({SourceKind::File, "src/main.cpp"}); + app.links.push_back({LinkKind::Local, "c_core", {}, Visibility::Private}); + desc.targets.push_back(app); + + auto graph = Graph::lower_project_graph(desc, *tc, {proj, bdir, nullptr, {}, 32768}); + Void::Testing::expect(graph.has_value()); + if (!graph) { + return; + } + + const auto cmds = Editor::project_editor_commands(*graph); + bool checked_c_entry = false; + bool checked_cxx_entry = false; + for (const auto &e : cmds) { + if (e.file.filename() == "c_math.c") { + checked_c_entry = true; + Void::Testing::expect(std::ranges::contains(e.arguments, std::string{"-std=c17"})); + Void::Testing::expect( + !std::ranges::contains(e.arguments, std::string{"-std=c++23"})); + Void::Testing::expect_eq(e.arguments.front(), tc->c_compiler.string()); + } else if (e.file.filename() == "main.cpp") { + checked_cxx_entry = true; + Void::Testing::expect( + std::ranges::contains(e.arguments, std::string{"-std=c++23"})); + Void::Testing::expect_eq(e.arguments.front(), tc->cxx_compiler.string()); + } + } + Void::Testing::expect(checked_c_entry && checked_cxx_entry); + + auto exec = Execution::execute_graph(*graph, *state); + Void::Testing::expect(exec.has_value() && exec->succeeded); + Platform::ProcessRequest r; + r.executable = bdir / "profiles" / "debug" / "out" / "bin" / "mixed_app"; + auto out = Platform::run_supervised(r); + Void::Testing::expect(out.has_value() && out->succeeded()); + if (out) { + Void::Testing::expect_eq(out->stdout_data, std::string{"c17+cxx23=42\n"}); + } + } + + // 2. CMake mixed C11 + C++20 native translation (zero cmake --build). + { + const auto cm_src = tmp / "cmake_mixed"; + write_file(cm_src / "include" / "cmix.h", + "#pragma once\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n" + "int cmix_c_base(void);\n#ifdef __cplusplus\n}\n#endif\n" + "#ifdef __cplusplus\nint cmix_cxx_total();\n#endif\n"); + write_file(cm_src / "src" / "helper.c", + "#include \"cmix.h\"\nint cmix_c_base(void) { return 30 + C_EXTRA; }\n"); + write_file(cm_src / "src" / "wrapper.cpp", + "#include \"cmix.h\"\nint cmix_cxx_total() { return cmix_c_base() + CXX_EXTRA; " + "}\n"); + write_file(cm_src / "src" / "cli.cpp", + "#include \"cmix.h\"\n#include \n" + "int main() { std::cout << \"cmix=\" << cmix_cxx_total() << '\\n'; return 0; " + "}\n"); + write_file(cm_src / "CMakeLists.txt", R"cmake( +cmake_minimum_required(VERSION 3.20) +project(tb1_cmake LANGUAGES C CXX) +set(CMAKE_C_STANDARD 11) +set(CMAKE_CXX_STANDARD 20) +add_library(cmix STATIC src/helper.c src/wrapper.cpp) +target_include_directories(cmix PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_compile_definitions(cmix PRIVATE + $<$:C_EXTRA=5> + $<$:CXX_EXTRA=7>) +add_executable(cmix_cli src/cli.cpp) +target_link_libraries(cmix_cli PRIVATE cmix) +)cmake"); + + DependencyRecord dep; + dep.name = "tb1_cm"; + dep.source_kind = DependencySourceKind::Path; + dep.location = cm_src.string(); + dep.builder = "cmake"; + + auto mat = + Package::materialize_dependency_source(dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat.has_value()); + if (!mat) { + return; + } + Provider::ProviderRequest req{ + dep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto res = Provider::resolve_cmake_with_translation( + req, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect_eq(res ? std::string{} : res.error().message(), std::string{}); + Void::Testing::expect(res.has_value() && res->executed_natively && + res->audit.is_supported()); + + const auto hash = Provider::compute_provider_input_hash(req); + const auto exe = tmp / "prov" / ("translate_tb1_cm_" + hash.substr(0, 16)) / + "native-build" / "profiles" / "debug" / "out" / "bin" / "cmix_cli"; + Platform::ProcessRequest rr; + rr.executable = exe; + auto out = Platform::run_supervised(rr); + Void::Testing::expect(out.has_value() && out->succeeded()); + if (out) { + Void::Testing::expect_eq(out->stdout_data, std::string{"cmix=42\n"}); + } + } + + // 3. Meson mixed C17 + C++20 native translation (zero meson compile). + if (Platform::resolve_executable("meson").has_value()) { + const auto m_src = tmp / "meson_mixed"; + write_file(m_src / "include" / "mmix.h", + "#pragma once\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n" + "int mmix_c_base(void);\n#ifdef __cplusplus\n}\n#endif\n" + "#ifdef __cplusplus\nint mmix_cxx_total();\n#endif\n"); + write_file(m_src / "src" / "helper.c", + "#include \"mmix.h\"\nint mmix_c_base(void) { return 20 + MC_ADD; }\n"); + write_file(m_src / "src" / "wrap.cpp", + "#include \"mmix.h\"\nint mmix_cxx_total() { return mmix_c_base() + 15; }\n"); + write_file(m_src / "src" / "main.cpp", + "#include \"mmix.h\"\n#include \n" + "int main() { std::cout << \"mmix=\" << mmix_cxx_total() << '\\n'; return 0; " + "}\n"); + write_file(m_src / "meson.build", R"meson( +project('tb1_meson', ['c', 'cpp'], default_options: ['c_std=c17', 'cpp_std=c++20']) +inc = include_directories('include') +lib = static_library('mmix', ['src/helper.c', 'src/wrap.cpp'], + include_directories: inc, + c_args: ['-DMC_ADD=7']) +executable('mmix_cli', ['src/main.cpp'], include_directories: inc, link_with: lib) +)meson"); + + DependencyRecord dep; + dep.name = "tb1_me"; + dep.source_kind = DependencySourceKind::Path; + dep.location = m_src.string(); + dep.builder = "meson"; + auto mat = + Package::materialize_dependency_source(dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat.has_value()); + if (!mat) { + return; + } + Provider::ProviderRequest req{ + dep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto res = Provider::resolve_meson_with_translation( + req, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect_eq(res ? std::string{} : res.error().message(), std::string{}); + Void::Testing::expect(res.has_value() && res->executed_natively && + res->audit.is_supported()); + + const auto hash = Provider::compute_provider_input_hash(req); + const auto exe = tmp / "prov" / ("translate_meson_tb1_me_" + hash.substr(0, 16)) / + "native-build" / "profiles" / "debug" / "out" / "bin" / "mmix_cli"; + Platform::ProcessRequest rr; + rr.executable = exe; + auto out = Platform::run_supervised(rr); + Void::Testing::expect(out.has_value() && out->succeeded()); + if (out) { + Void::Testing::expect_eq(out->stdout_data, std::string{"mmix=42\n"}); + } + } +} + +// === Track B2: Bounded build.ninja CUSTOM_COMMAND translation & unsafe-rule rejection === +VOID_TEST(FullV1Tests, track_b2_bounded_ninja_custom_command_cmake_and_meson_translation) { + Void::FileSystem::TempDir tmp{"vbs_track_b2_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) { + return; + } + auto state = State::StateStore::open(tmp / "state"); + Void::Testing::expect(state.has_value()); + if (!state) { + return; + } + + // 1. CMake hermetic custom command (generated header + generated .cpp + UTILITY DEPENDS). + { + const auto src = tmp / "cm_gen"; + write_file(src / "gen_hdr.cmake", + "file(WRITE \"${OUT}\" \"#pragma once\\n#define B2_CM_HDR 50\\n\")\n"); + write_file(src / "gen_cpp.cmake", "file(WRITE \"${OUT}\" \"#include \\\"gen_val.hpp\\\"\\n" + "int b2_cm_val() { return B2_CM_HDR + 27; }\\n\")\n"); + write_file(src / "CMakeLists.txt", R"cmake( +cmake_minimum_required(VERSION 3.20) +project(tb2_cmake LANGUAGES CXX) +add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp" + COMMAND ${CMAKE_COMMAND} -DOUT=${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp -P ${CMAKE_CURRENT_SOURCE_DIR}/gen_hdr.cmake + DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/gen_hdr.cmake" +) +add_custom_target(run_gen DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp") +add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/gen_src.cpp" + COMMAND ${CMAKE_COMMAND} -DOUT=${CMAKE_CURRENT_BINARY_DIR}/gen_src.cpp -P ${CMAKE_CURRENT_SOURCE_DIR}/gen_cpp.cmake + DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/gen_cpp.cmake" "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp" +) +add_library(b2_lib STATIC "${CMAKE_CURRENT_BINARY_DIR}/gen_src.cpp" "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp") +add_dependencies(b2_lib run_gen) +target_include_directories(b2_lib PUBLIC "${CMAKE_CURRENT_BINARY_DIR}") +add_executable(b2_app src/main.cpp) +target_link_libraries(b2_app PRIVATE b2_lib) +)cmake"); + write_file(src / "src" / "main.cpp", + "#include \"gen_val.hpp\"\n#include \n" + "int b2_cm_val();\n" + "int main() { std::cout << \"cm_gen=\" << b2_cm_val() << '\\n'; return 0; }\n"); + + DependencyRecord dep; + dep.name = "tb2_cm"; + dep.source_kind = DependencySourceKind::Path; + dep.location = src.string(); + dep.builder = "cmake"; + auto mat = + Package::materialize_dependency_source(dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat.has_value()); + if (!mat) { + return; + } + Provider::ProviderRequest req{ + dep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto res = Provider::resolve_cmake_with_translation( + req, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect_eq(res ? std::string{} : res.error().message(), std::string{}); + Void::Testing::expect(res.has_value() && res->executed_natively && + res->audit.is_supported()); + + const auto hash = Provider::compute_provider_input_hash(req); + const auto exe = tmp / "prov" / ("translate_tb2_cm_" + hash.substr(0, 16)) / + "native-build" / "profiles" / "debug" / "out" / "bin" / "b2_app"; + Platform::ProcessRequest rr; + rr.executable = exe; + auto out = Platform::run_supervised(rr); + Void::Testing::expect(out.has_value() && out->succeeded()); + if (out) { + Void::Testing::expect_eq(out->stdout_data, std::string{"cm_gen=77\n"}); + } + } + + // 2. CMake negative checks: side-effect-only .util target AND out-of-tree OUTPUT MUST fail + // RequireNative! + { + const auto bad_util_src = tmp / "cm_bad_util"; + write_file(bad_util_src / "CMakeLists.txt", R"cmake( +cmake_minimum_required(VERSION 3.20) +project(tb2_bad_util LANGUAGES CXX) +add_custom_target(side_effect COMMAND ${CMAKE_COMMAND} -E echo side_effect_only) +add_library(b2_u_lib STATIC src/lib.cpp) +add_dependencies(b2_u_lib side_effect) +)cmake"); + write_file(bad_util_src / "src" / "lib.cpp", "int b2_u() { return 1; }\n"); + DependencyRecord bdep; + bdep.name = "tb2_bad_u"; + bdep.source_kind = DependencySourceKind::Path; + bdep.location = bad_util_src.string(); + bdep.builder = "cmake"; + auto bmat = + Package::materialize_dependency_source(bdep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(bmat.has_value()); + if (bmat) { + Provider::ProviderRequest breq{ + bdep, *bmat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto bad = Provider::resolve_cmake_with_translation( + breq, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect(!bad.has_value()); + } + + const auto bad_oot_src = tmp / "cm_bad_oot"; + const auto outside_file = tmp / "outside_generated.hpp"; + write_file(bad_oot_src / "CMakeLists.txt", + "cmake_minimum_required(VERSION 3.20)\nproject(tb2_bad_oot LANGUAGES CXX)\n" + "add_custom_command(OUTPUT \"" + + outside_file.string() + "\" COMMAND ${CMAKE_COMMAND} -E touch \"" + + outside_file.string() + + "\")\n" + "add_library(b2_oot_lib STATIC src/lib.cpp \"" + + outside_file.string() + "\")\n"); + write_file(bad_oot_src / "src" / "lib.cpp", "int b2_oot() { return 1; }\n"); + DependencyRecord odep; + odep.name = "tb2_bad_oot"; + odep.source_kind = DependencySourceKind::Path; + odep.location = bad_oot_src.string(); + odep.builder = "cmake"; + auto omat = + Package::materialize_dependency_source(odep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(omat.has_value()); + if (omat) { + Provider::ProviderRequest oreq{ + odep, *omat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto ocfg = Provider::configure_cmake_for_translation(oreq, tmp / "oot_cfg"); + Void::Testing::expect(ocfg.has_value()); + auto oaudit = Provider::audit_cmake_codemodel(tmp / "oot_cfg"); + Void::Testing::expect(oaudit.has_value() && !oaudit->is_supported()); + } + } + + // 3. Meson hermetic custom_target (generated header + generated .cpp) under RequireNative, + // plus negative rejection on Meson run_target. + if (Platform::resolve_executable("meson").has_value()) { + const auto m_src = tmp / "meson_gen_native"; + write_file(m_src / "meson.build", R"meson( +project('tb2_meson', 'cpp') +gen_hdr = custom_target('gen_hdr', + output: 'gen_num.hpp', + command: ['/bin/sh', '-c', 'printf "#pragma once\n#define M_GEN_NUM 80\n" > "$1"', '--', '@OUTPUT@']) +gen_cpp = custom_target('gen_cpp', + output: 'gen_num.cpp', + command: ['/bin/sh', '-c', 'printf "int m_gen_extra() { return 8; }\n" > "$1"', '--', '@OUTPUT@']) +lib = static_library('mgenlib', ['src/gen.cpp', gen_hdr, gen_cpp]) +executable('mgen_app', ['src/main.cpp', gen_hdr], link_with: lib) +)meson"); + write_file(m_src / "src" / "gen.cpp", + "#include \"gen_num.hpp\"\nint m_gen_extra();\n" + "int m_gen_fn() { return M_GEN_NUM + m_gen_extra(); }\n"); + write_file(m_src / "src" / "main.cpp", + "#include \"gen_num.hpp\"\n#include \n" + "int m_gen_fn();\n" + "int main() { std::cout << \"m_gen=\" << m_gen_fn() << '\\n'; return 0; }\n"); + + DependencyRecord mdep; + mdep.name = "tb2_me"; + mdep.source_kind = DependencySourceKind::Path; + mdep.location = m_src.string(); + mdep.builder = "meson"; + auto mat = + Package::materialize_dependency_source(mdep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat.has_value()); + if (!mat) { + return; + } + Provider::ProviderRequest req{ + mdep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto res = Provider::resolve_meson_with_translation( + req, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect_eq(res ? std::string{} : res.error().message(), std::string{}); + Void::Testing::expect(res.has_value() && res->executed_natively && + res->audit.is_supported()); + + const auto hash = Provider::compute_provider_input_hash(req); + const auto exe = tmp / "prov" / ("translate_meson_tb2_me_" + hash.substr(0, 16)) / + "native-build" / "profiles" / "debug" / "out" / "bin" / "mgen_app"; + Platform::ProcessRequest rr; + rr.executable = exe; + auto out = Platform::run_supervised(rr); + Void::Testing::expect(out.has_value() && out->succeeded()); + if (out) { + Void::Testing::expect_eq(out->stdout_data, std::string{"m_gen=88\n"}); + } + + const auto run_src = tmp / "meson_run_tgt"; + write_file(run_src / "meson.build", R"meson( +project('tb2_m_run', 'cpp') +run_target('do_run', command: ['echo', 'hi']) +static_library('mrunlib', ['src/a.cpp']) +)meson"); + write_file(run_src / "src" / "a.cpp", "int m_run_a() { return 1; }\n"); + DependencyRecord rdep; + rdep.name = "tb2_m_run"; + rdep.source_kind = DependencySourceKind::Path; + rdep.location = run_src.string(); + rdep.builder = "meson"; + auto rmat = + Package::materialize_dependency_source(rdep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(rmat.has_value()); + if (rmat) { + Provider::ProviderRequest rreq{ + rdep, *rmat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto rstrict = Provider::resolve_meson_with_translation( + rreq, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect(!rstrict.has_value()); + } + } +} + +// === Track B3: Foreign CMake C++20 CXX_MODULES native translation & cross-target import === +VOID_TEST(FullV1Tests, track_b3_foreign_cmake_cxx20_modules_native_translation) { + Void::FileSystem::TempDir tmp{"vbs_track_b3_"}; + auto state = State::StateStore::open(tmp / "state"); + Void::Testing::expect(state.has_value()); + if (!state) { + return; + } + + auto verify_for_family = [&](CompilerFamily family, std::string_view label) { + auto ctx = default_profiles().resolve("debug", family, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / ("probes_" + std::string{label})); + Void::Testing::expect(tc.has_value()); + if (!tc || !tc->supports_p1689_scan) { + return; + } + + const auto cm_src = tmp / ("cm_mods_" + std::string{label}); + write_file(cm_src / "src" / "math_mod.cppm", + "export module vbs.trackb3.math;\n" + "export int b3_mul7(int x) { return x * 7; }\n"); + write_file(cm_src / "src" / "app.cpp", + "import vbs.trackb3.math;\n#include \n" + "int main() { std::cout << b3_mul7(6) << '\\n'; return 0; }\n"); + write_file(cm_src / "CMakeLists.txt", R"cmake( +cmake_minimum_required(VERSION 3.28) +project(tb3_mods LANGUAGES CXX) +add_library(mod_math STATIC) +target_sources(mod_math PUBLIC FILE_SET CXX_MODULES FILES src/math_mod.cppm) +target_compile_features(mod_math PUBLIC cxx_std_20) +add_executable(mod_app src/app.cpp) +target_link_libraries(mod_app PRIVATE mod_math) +target_compile_features(mod_app PRIVATE cxx_std_20) +)cmake"); + + DependencyRecord dep; + dep.name = std::string{"tb3_cm_"} + std::string{label}; + dep.source_kind = DependencySourceKind::Path; + dep.location = cm_src.string(); + dep.builder = "cmake"; + + auto mat = + Package::materialize_dependency_source(dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat.has_value()); + if (!mat) { + return; + } + + Provider::ProviderRequest req{ + dep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto res = Provider::resolve_cmake_with_translation( + req, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect_eq(res ? std::string{} : res.error().message(), std::string{}); + Void::Testing::expect(res.has_value() && res->executed_natively && + res->audit.is_supported()); + if (!res) { + return; + } + + const auto hash = Provider::compute_provider_input_hash(req); + const auto mod_exe = tmp / "prov" / ("translate_" + dep.name + "_" + hash.substr(0, 16)) / + "native-build" / "profiles" / "debug" / "out" / "bin" / "mod_app"; + Platform::ProcessRequest rr; + rr.executable = mod_exe; + auto out = Platform::run_supervised(rr); + Void::Testing::expect(out.has_value() && out->succeeded()); + if (out) { + Void::Testing::expect_eq(out->stdout_data, std::string{"42\n"}); + } + + // Verify cross-target / imported BMI propagation: a native VBS executable importing + // `vbs.trackb3.math` from the translated CMake module library! + const auto iface_it = res->exported.targets.find(dep.name + "::mod_math"); + Void::Testing::expect(iface_it != res->exported.targets.end()); + if (iface_it != res->exported.targets.end()) { + Void::Testing::expect(iface_it->second.module_bmis.contains("vbs.trackb3.math")); + + const auto cons_root = tmp / ("vbs_cons_" + std::string{label}); + const auto cons_build = tmp / ("vbs_cons_build_" + std::string{label}); + write_file(cons_root / "src" / "cons.cpp", + "import vbs.trackb3.math;\n#include \n" + "int main() { std::cout << (b3_mul7(7) + 1) << '\\n'; return 0; }\n"); + + Graph::ProjectDescription cdesc; + cdesc.profile = ctx; + TargetRecord capp; + capp.name = "vbs_mod_consumer"; + capp.kind = TargetKind::Executable; + capp.cxx_standard = CxxStandard::Cxx20; + capp.sources.push_back({SourceKind::File, "src/cons.cpp"}); + capp.links.push_back({LinkKind::Imported, "mod_math", dep.name, Visibility::Private}); + cdesc.targets.push_back(capp); + + Graph::GraphLowerOptions gopts{cons_root, cons_build, nullptr, res->exported.targets, + 32768}; + auto cgraph = Graph::lower_project_graph(cdesc, *tc, gopts); + Void::Testing::expect_eq(cgraph ? std::string{} : cgraph.error().message(), + std::string{}); + Void::Testing::expect(cgraph.has_value()); + if (cgraph) { + auto cexec = Execution::execute_graph(*cgraph, *state); + Void::Testing::expect(cexec.has_value() && cexec->succeeded); + Platform::ProcessRequest cr; + cr.executable = + cons_build / "profiles" / "debug" / "out" / "bin" / "vbs_mod_consumer"; + auto cout = Platform::run_supervised(cr); + Void::Testing::expect(cout.has_value() && cout->succeeded()); + if (cout) { + Void::Testing::expect_eq(cout->stdout_data, std::string{"50\n"}); + } + } + } + }; + + if (Platform::resolve_executable("g++").has_value()) { + verify_for_family(CompilerFamily::Gcc, "gcc16"); + } + if (Platform::resolve_executable("clang++").has_value()) { + verify_for_family(CompilerFamily::Clang, "clang23"); + } +} + +// === IDE Integration: `build.cpp` CompDB indexing + `vbs ide generate` & `vbs ide query` === +VOID_TEST(FullV1Tests, ide_integration_compdb_build_cpp_and_editor_configs_end_to_end) { + 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_ide_"}; + const auto proj = tmp / "ide_proj"; + const auto bdir = tmp / "ide_build"; + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{120}; + return Platform::run_supervised(req); + }; + + // 1. Scaffold a C++26 project via `vbs init`. + auto r_init = run_vbs({"init", "--dir", proj.string(), "--name", "ide_demo"}); + Void::Testing::expect(r_init.has_value() && r_init->succeeded()); + + // 2. Generate all IDE configs (`--editor all`) BEFORE any full build has run. + auto r_gen = run_vbs({"ide", "generate", "--project", proj.string(), "--build-dir", + bdir.string(), "--editor", "all"}); + Void::Testing::expect_eq( + r_gen ? (r_gen->succeeded() ? std::string{} : (r_gen->stdout_data + r_gen->stderr_data)) + : r_gen.error().message(), + std::string{}); + Void::Testing::expect(r_gen.has_value() && r_gen->succeeded()); + + // Check every generated file exists and every JSON file parses strictly. + Void::Testing::expect(std::filesystem::exists(proj / ".clangd")); + Void::Testing::expect(std::filesystem::exists(proj / ".idea" / "customTargets.xml")); + for (const auto &json_file : {proj / ".vscode" / "tasks.json", proj / ".vscode" / "launch.json", + proj / ".vscode" / "settings.json", proj / ".zed" / "tasks.json", + proj / ".zed" / "debug.json"}) { + Void::Testing::expect(std::filesystem::exists(json_file)); + auto content = Void::FileSystem::read_file(json_file); + Void::Testing::expect(content.has_value()); + if (content) { + auto parsed = Void::Json::Strict::parse(*content); + Void::Testing::expect(parsed.has_value()); + } + } + + // 3. Non-destructive overwrite preservation without `--force`, and overwrite with `--force`. + write_file(proj / ".clangd", "# user-customized clangd\n"); + auto r_keep = run_vbs({"ide", "generate", "--project", proj.string(), "--build-dir", + bdir.string(), "--editor", "clangd"}); + Void::Testing::expect(r_keep.has_value() && r_keep->succeeded()); + Void::Testing::expect_eq(Void::FileSystem::read_file(proj / ".clangd").value_or(""), + std::string{"# user-customized clangd\n"}); + + auto r_force = run_vbs({"ide", "generate", "--project", proj.string(), "--build-dir", + bdir.string(), "--editor", "clangd", "--force"}); + Void::Testing::expect(r_force.has_value() && r_force->succeeded()); + const auto refreshed_clangd = Void::FileSystem::read_file(proj / ".clangd").value_or(""); + Void::Testing::expect(refreshed_clangd.find("CompilationDatabase:") != std::string::npos); + Void::Testing::expect(refreshed_clangd.find("-freflection") != std::string::npos); + + // 4. Verify `compile_commands.json` contains a real, valid compiler invocation for `build.cpp` + // and syntax-check `build.cpp` using that exact CompDB entry! + const auto compdb_text = Void::FileSystem::read_file(bdir / "compile_commands.json"); + Void::Testing::expect(compdb_text.has_value()); + if (compdb_text) { + auto parsed_db = Void::Json::Strict::parse(*compdb_text); + Void::Testing::expect(parsed_db.has_value()); + bool checked_build_cpp = false; + if (parsed_db) { + if (const auto *arr = + std::get_if(&parsed_db->value)) { + for (const auto &ev : *arr) { + const auto *eo = std::get_if(&ev.value); + if (!eo) { + continue; + } + const auto fit = eo->find("file"); + const auto ait = eo->find("arguments"); + if (fit == eo->end() || ait == eo->end()) { + continue; + } + const auto *fs = std::get_if(&fit->second.value); + const auto *aarr = + std::get_if(&ait->second.value); + if (!fs || !aarr || std::filesystem::path{*fs}.filename() != "build.cpp") { + continue; + } + checked_build_cpp = true; + std::vector argv; + for (const auto &av : *aarr) { + if (const auto *as = std::get_if(&av.value)) { + argv.push_back(*as); + } + } + Void::Testing::expect(!argv.empty()); + Void::Testing::expect(std::ranges::contains(argv, std::string{"-std=c++26"})); + + Platform::ProcessRequest check_req; + check_req.executable = argv.front(); + for (std::size_t i = 1; i < argv.size(); ++i) { + if (argv[i] == "-c") { + check_req.arguments.push_back("-fsyntax-only"); + } else if (argv[i] == "-o" && i + 1 < argv.size()) { + ++i; + } else { + check_req.arguments.push_back(argv[i]); + } + } + check_req.timeout = std::chrono::seconds{30}; + auto syntax_ok = Platform::run_supervised(check_req); + Void::Testing::expect(syntax_ok.has_value() && syntax_ok->succeeded()); + } + } + } + Void::Testing::expect(checked_build_cpp); + } + + // 5. Verify `vbs ide query` emits valid JSON workspace & target metadata. + auto r_query = + run_vbs({"ide", "query", "--project", proj.string(), "--build-dir", bdir.string()}); + Void::Testing::expect(r_query.has_value() && r_query->succeeded()); + if (r_query) { + auto pq = Void::Json::Strict::parse(r_query->stdout_data); + Void::Testing::expect(pq.has_value()); + Void::Testing::expect(r_query->stdout_data.find("\"ide_demo\"") != std::string::npos); + Void::Testing::expect(r_query->stdout_data.find("\"ide_demo_lib\"") != std::string::npos); + Void::Testing::expect(r_query->stdout_data.find("\"ide_demo_tests\"") != std::string::npos); + Void::Testing::expect(r_query->stdout_data.find("\"compdb_path\"") != std::string::npos); + Void::Testing::expect(r_query->stdout_data.find("\"sdk_include_dir\"") != + std::string::npos); + } +}