Compare commits

..
64 changed files with 563 additions and 3296 deletions

View file

@ -16,20 +16,20 @@ crafter-build is a C++26 modules build system. A project is described by a `proj
| `examples/` | Standalone user-facing projects, MIT licensed. | | `examples/` | Standalone user-facing projects, MIT licensed. |
| `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. | | `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. |
| `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. | | `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. |
| `lib/` | Vendored third-party headers (glslang's DirStackFileIncluder). Do not edit. | | `lib/` | Vendored third-party headers (nlohmann/json, glslang's DirStackFileIncluder). Do not edit. |
| `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. | | `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. |
| `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. | | `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. |
| `.review-gates/` | The pre-push review's `config.json` and this repository's lens sections (`lenses/`), read by Crafter.Review. Its `push/` and `trees/` are generated and gitignored. | | `.review-gates/` | The pre-push review's `config.json` and this repository's lens sections (`lenses/`), read by Crafter.Review. Its `push/` and `trees/` are generated and gitignored. |
Partitions and what they own: Partitions and what they own:
- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, clang-scan-deps, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. - `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages.
- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. - `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types.
- `:Platform` runs commands, implements `LoadConfigurations` and `LoadProject` (compile and load `project.cpp`), the host PCM cache and `#pragma crafter dependency`. - `:Platform` runs commands, implements `LoadConfigurations` and `LoadProject` (compile and load `project.cpp`), the host PCM cache and `#pragma crafter dependency`.
- `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`. - `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`.
- `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`). - `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`).
- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. - `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`.
- `:Test` holds `AddTest`, `RunTests` and `TestRunner`, and starts the headless compositor of a test that sets `Test::wayland` (`RunSingleTest`), through `:Platform`'s `BackgroundCommand` and `PrivateDirectory`. - `:Test` holds `AddTest`, `RunTests` and `TestRunner`.
- `:Lint` is the lint/format driver plus the libclang token and AST layer. - `:Lint` is the lint/format driver plus the libclang token and AST layer.
- `:Script` is the driver behind `crafter-build run`: it looks a name up in the `scripts` of the configurations it is given, calls the callback and turns what it returns into the exit code. - `:Script` is the driver behind `crafter-build run`: it looks a name up in the `scripts` of the configurations it is given, calls the callback and turns what it returns into the exit code.
- `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configurations returned by a project file that `GitProject` or `LocalProject` loaded have their `path` rebased. - `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configurations returned by a project file that `GitProject` or `LocalProject` loaded have their `path` rebased.
@ -40,7 +40,7 @@ Partitions and what they own:
The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop. The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop.
Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime, and `clang-scan-deps`, which a build reads what each C++ source declares and imports with), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them.
```bash ```bash
./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/ ./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/
@ -90,10 +90,9 @@ Conventions the existing tests follow:
- Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape. - Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape.
- Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it. - Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it.
- Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout. - Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout.
- Fixtures under `tests/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"`, after removing what an earlier run left there, which matters where the test runs by hand: under `crafter-build test` the copy is in the test's own `TMPDIR`, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. The fixed name is safe because `RunTests` gives every test a `TMPDIR` of its own for the run, so two runs at once, natively or in the Flatpak, whose sandboxes all share the app's `/tmp`, stage into different directories. A test that writes to `/tmp` by name, as `HostFlatpak` has to, makes a directory of its own there, a `PrivateDirectory`, which a later run removes, where a killed run left it, once it has not changed for a minute. A test that builds against a sysroot it stages, or has crafter-build fetch a repository it stages, points `XDG_CACHE_HOME` into its scratch directory too, as `SysrootStdModule` and the external-dependency tests do: the cache's key holds that path or URL, which is a new one every run. - Fixtures under `tests/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"` and removes it on the next run. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy.
- Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. - Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`.
- Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. - Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration.
- `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first.
- A test that needs the host's flatpak goes through `RunHostFlatpak`, skips (77) with the reason `HostFlatpakUnavailable` gives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a private `FLATPAK_USER_DIR` under its fixture's `build/`, as `FlatpakInstall` does. It never runs an installed app: `flatpak run` makes `~/.var/app/<app-id>` in the real home. - A test that needs the host's flatpak goes through `RunHostFlatpak`, skips (77) with the reason `HostFlatpakUnavailable` gives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a private `FLATPAK_USER_DIR` under its fixture's `build/`, as `FlatpakInstall` does. It never runs an installed app: `flatpak run` makes `~/.var/app/<app-id>` in the real home.
- A test that packages a Flatpak stages the runtime: it writes a `.flatpak-info` whose `[Application]` group has a `runtime=runtime/org.freedesktop.Sdk/x86_64/26.08` line, as the parser takes only that group's, and points `CRAFTER_BUILD_FLATPAK_INFO` at it with `setenv`, first thing in `main`, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak; `FlatpakNative` stages an empty one for the native case. - A test that packages a Flatpak stages the runtime: it writes a `.flatpak-info` whose `[Application]` group has a `runtime=runtime/org.freedesktop.Sdk/x86_64/26.08` line, as the parser takes only that group's, and points `CRAFTER_BUILD_FLATPAK_INFO` at it with `setenv`, first thing in `main`, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak; `FlatpakNative` stages an empty one for the native case.
@ -162,12 +161,11 @@ These were decided deliberately. Do not undo them without the maintainer's say-s
- `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters. - `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters.
- Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built. - Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built.
- `--runner=cmd:<command>` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests. - `--runner=cmd:<command>` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests.
- `--compositor=` and `CRAFTER_BUILD_COMPOSITOR` name the command that crafter-build runs through `sh` beside every test that sets `Test::wayland`, unless they name `host`; the default is the weston on `PATH`.
- `crafter-build run <name>` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's: `run` leaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (`KeptBy`); keep it that way. - `crafter-build run <name>` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's: `run` leaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (`KeptBy`); keep it that way.
- The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. - The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library.
- crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. - crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs.
- CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. - CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it.
- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make, and a later run removes what a killed one left once that has not changed for a minute (`PrivateDirectory`): `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up; and `tests/HostFlatpak`, which in the Flatpak makes a directory of its own in the sandbox's `/tmp`, the place it asks the host about. - Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`. Keep it that way.
## CI and publishing ## CI and publishing
@ -207,7 +205,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary:
- A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. - A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps.
- The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel <hardware threads>` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. - The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel <hardware threads>` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own.
- An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. - An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure.
- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. A scan is kept in the build directory as an object is, in `scans/` or, for a source outside `cfg.path`, in `scans-outside/`, as JSON holding the compile command it was taken for and what clang-scan-deps wrote, with a dependency file beside it, and taken again when that command differs, when the source or a file the dependency file lists is newer, and when it cannot be read; clang-scan-deps is given that command with its first word made the compiler where clang started with that command takes itself to be: the directory it is installed in, or, for a command whose last of `-canonical-prefixes` and `-no-canonical-prefixes` is `-no-canonical-prefixes`, that of the compiler as written (`ScannedAs`, `Toolchain::InstalledClangxx`). A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build. - The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then.
- Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are.
- A CMake external whose recorded configure inputs (`<build>/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. - A CMake external whose recorded configure inputs (`<build>/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached.
- The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps. - The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps.
@ -215,7 +213,6 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary:
- `RunCommandWithTimeout` runs its command under `timeout`, which can only start programs, so a shell builtin such as `command -v` fails there wherever no program of that name is on PATH, as on Arch and in the Sdk: a probe built on it reports the tool missing, and whatever it guards is skipped without a word. Probe through `RunCommandChecked`, which goes through `sh`, or `std::system` in a test. - `RunCommandWithTimeout` runs its command under `timeout`, which can only start programs, so a shell builtin such as `command -v` fails there wherever no program of that name is on PATH, as on Arch and in the Sdk: a probe built on it reports the tool missing, and whatever it guards is skipped without a word. Probe through `RunCommandChecked`, which goes through `sh`, or `std::system` in a test.
- A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules/<major>/`, one `libcxx-<major>-modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot. - A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules/<major>/`, one `libcxx-<major>-modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot.
- The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`. - The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`.
- The Flatpak carries weston for the tests that set `Test::wayland`: the `libevdev`, `libinput`, `libdisplay-info` and `weston` modules, just before `crafter-build`, so that bumping them rebuilds only them and crafter-build. weston's frontend links the first three whatever the backend, so they ship. weston is configured with its headless backend, its GL renderer and its desktop shell, and with none of its other backends or shells and no Vulkan renderer. libinput is a `git` source pinned by commit, since its 1.32.0 release has no tarball attached. `tests/HeadlessCompositor` stands in a fake compositor, so the suite needs no weston: only a project's own tests that set `Test::wayland` run the real one.
- The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib/<triple>/eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`. - The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib/<triple>/eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`.
- `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`. - `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`.
- `CudaCompile` builds with a real CUDA toolkit whose `lib64` beside `bin/nvcc` holds `libcudart_static.a`, and skips everywhere else, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, or how the CUDA runtime is linked and handed on through `BuildResult::runtimeLibs`, run it in the native loop on a machine with such a toolkit, as Arch's `/opt/cuda` is. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere, and so is whether the `lib64` beside it holds the static runtime. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either. - `CudaCompile` builds with a real CUDA toolkit whose `lib64` beside `bin/nvcc` holds `libcudart_static.a`, and skips everywhere else, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, or how the CUDA runtime is linked and handed on through `BuildResult::runtimeLibs`, run it in the native loop on a machine with such a toolkit, as Arch's `/opt/cuda` is. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere, and so is whether the `lib64` beside it holds the static runtime. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either.

View file

@ -45,9 +45,9 @@ Run `crafter-build` in that directory, outputs land at `bin/myapp-<target>-<marc
A `.cpp`, `.c` or `.cu` of a configuration is compiled into an object named from its path: `a/Thing.cpp` into `objects/a/Thing_impl.o` in that `build/` directory, at the source's path from `cfg.path`, and a source outside `cfg.path` into `objects-outside/` there, at its whole path. Two sources may therefore have the same file name in different directories, and a `.c` may lie beside a `.cpp` or a `.cu` of its name. The progress line of such a source's compile names it by the same path, `Compiling a/Thing.cpp`. The link, and the archive step of a static library, read their objects from a file in that directory, `<outputName>.objects`, so the command is no longer for many sources than for one. A `.cpp`, `.c` or `.cu` of a configuration is compiled into an object named from its path: `a/Thing.cpp` into `objects/a/Thing_impl.o` in that `build/` directory, at the source's path from `cfg.path`, and a source outside `cfg.path` into `objects-outside/` there, at its whole path. Two sources may therefore have the same file name in different directories, and a `.c` may lie beside a `.cpp` or a `.cu` of its name. The progress line of such a source's compile names it by the same path, `Compiling a/Thing.cpp`. The link, and the archive step of a static library, read their objects from a file in that directory, `<outputName>.objects`, so the command is no longer for many sources than for one.
crafter-build orders a configuration's units by what their sources import: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. What a `.cppm` or `.cpp` declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, so it reads them as the compiler does: an import in a comment, in a string literal or in a branch that `#if` leaves out is none, and a define or a header decides one as it does for the compile. It reads them once the configuration's dependencies are built, since the command takes their include paths, and keeps what it found in the `build/` directory, as it keeps objects: in `scans/` at the source's path from `cfg.path`, and in `scans-outside/` at its whole path for a source outside `cfg.path`, until the source, a file it includes or the command changes. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused once its sources are read, before any of its `.cppm` and `.cpp` is compiled, with an error that names the units in the order they wait. crafter-build orders a configuration's units by the `import` lines of its sources: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused before anything of it is built, with an error that names the units in the order they wait. The imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under `#if 0` counts too, and such text can make a round in a project the compiler accepts.
A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the scans and the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts.
### Several configurations ### Several configurations
@ -182,7 +182,7 @@ Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project.
cfg.dependencies = { math }; cfg.dependencies = { math };
``` ```
The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that exports modules and that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths, unless both lists give the project one build directory, as two orders of the same flags of its own can: it is then built once. Releases up to 2.2.0 forward nothing when `.args` is left out. The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths. Releases up to 2.2.0 forward nothing when `.args` is left out.
The default is read when the spec is made, so make it inside the entry point, `CrafterBuildProject` or `CrafterBuildConfigurations`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing. The default is read when the spec is made, so make it inside the entry point, `CrafterBuildProject` or `CrafterBuildConfigurations`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing.
@ -299,9 +299,8 @@ Test conventions:
- **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH"). - **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH").
- Each test runs in its own subprocess — a segfault doesn't take the runner down. - Each test runs in its own subprocess — a segfault doesn't take the runner down.
- Each test runs with `TMPDIR` naming a directory of its own, `<run>/<name>` in a directory made for the run in the temp directory, or, where the run has given that name out already, the first of `<name>-2`, `<name>-3` and on that it has not, so `fs::temp_directory_path()` in a test is the test's alone, even with another run going at the same time. Its path is longer than the temp directory's by 28 bytes and the name of the test's own directory, room a test that binds a Unix socket there has to leave: a socket's path holds 107 bytes. That takes a runner that hands the test `TMPDIR`, as running it directly and qemu-user do: under wine a Windows test does not get `TMPDIR`, and its `TMP`, `TEMP` and temp directory are the Wine prefix's, which every run in that prefix shares; wasmtime gives a test no environment at all. What a test leaves in its `TMPDIR` is removed when it passes or skips. When it fails, crashes or times out, what it left is kept, and its log in `build/test-logs/` says where, as does what is printed of a test that fails or crashes. A later run removes it once the run's directory has gone a minute unchanged: a minute after the run that kept it ended, or, where that run was killed, a minute after it last made or removed a test's directory there. A test that builds against a sysroot or mingw prefix it stages there, or has crafter-build fetch a repository it stages there (an `ExternalDependency` or a `GitProject` of it), keys crafter-build's cache on that path or URL, which is a new one every run: point `XDG_CACHE_HOME` into its `TMPDIR` as well, or every run leaves an entry of its own in the cache.
- Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()` tests (`--jobs=`). The steps of their builds share one limit, a build's: as many at once as there are hardware threads. - Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()` tests (`--jobs=`). The steps of their builds share one limit, a build's: as many at once as there are hardware threads.
- Stdout+stderr is captured and printed atomically on completion. A test that fails, crashes or times out once it is built also writes what it printed, and what crafter-build said of it, to `build/test-logs/<name>.log`, when that is anything, and, where it sets `Test::wayland` and ran, what its compositor printed, if anything, to `<name>.compositor.log` beside it (what a compositor that did not start printed is in `<name>.log`); one that failed to build, or did not get that far, writes neither. `<name>` is the test's name with `-2`, `-3` and on after it where the run has given that name out already, as two configurations or two targets may each declare a test of one name. - Stdout+stderr is captured and printed atomically on completion. Failed/crashed/timed-out tests also write to `build/test-logs/<name>.log`.
- A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run. - A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run.
CLI: CLI:
@ -314,7 +313,6 @@ crafter-build test --target=x86_64-w64-mingw32 # only tests for
crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine
crafter-build test --jobs=1 # one test at a time crafter-build test --jobs=1 # one test at a time
crafter-build test --timeout=5 # override per-test timeout crafter-build test --timeout=5 # override per-test timeout
crafter-build test --compositor=host # Wayland tests on this session's display
``` ```
Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed. Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed.
@ -377,24 +375,6 @@ cmd:<command> # cmd:wine, cmd:qemu-aarch64, cmd:valgrind, ...
Each runner carries a `probe` command (e.g. `which wine`), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (`AllPassed()` returns true on skip-only runs). Each runner carries a `probe` command (e.g. `which wine`), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (`AllPassed()` returns true on skip-only runs).
### Tests that open windows
A test that talks to a Wayland compositor sets `Test::wayland`, and every run of it gets a headless compositor of its own instead of your session's display, so the windows it opens through `WAYLAND_DISPLAY` show up there and not on your desktop:
```cpp
cfg.AddTest("Swapchain").Wayland(); // or, on a Test you build yourself: test.wayland = true;
```
Before the test, crafter-build starts the compositor with `XDG_RUNTIME_DIR` set to a directory made for it (in your `XDG_RUNTIME_DIR`, else in `/tmp`) and without `WAYLAND_DISPLAY`, `WAYLAND_SOCKET` or `DISPLAY`, and waits up to 30 s for a `wayland-<n>` socket to appear there. The test then runs with `WAYLAND_DISPLAY` set to that socket's full path and with `DISPLAY` and `WAYLAND_SOCKET` unset; its `XDG_RUNTIME_DIR` stays yours. Afterwards the compositor's process group is sent SIGTERM, what is left of the group SIGKILL once the compositor has ended or 5 s have passed, and the directory is removed. No two tests share a compositor, so tests that run at once cannot cover each other's windows or take each other's focus.
The compositor is `weston --backend=headless --renderer=gl --no-config --idle-time=0` unless `CRAFTER_BUILD_COMPOSITOR` names another, and `--compositor=` wins over both. The Flatpak ships weston 16.0.2; outside it, install weston 12 or newer, the first release to take `--renderer=`. Its GL renderer takes the GPU buffers (dmabufs) that a GPU's Vulkan driver presents, as Mesa's and NVIDIA's do, and which the headless backend's default, a renderer that draws nothing, and pixman take none of; `--no-config` keeps your `weston.ini` out, and `--idle-time=0` keeps the output from going idle after 5 minutes, which would stop frame callbacks. Another compositor is any command, run through `sh`, that listens on a `wayland-<n>` socket in the `XDG_RUNTIME_DIR` it is given. `host` starts none and gives these tests your own display, to watch what they draw:
```bash
crafter-build test --compositor=host 'Swapchain*'
```
A compositor that ends before it listens, `sh` not finding it included, or does not listen within 30 s fails the test with what it printed. A test that may run where weston is missing declares it with `.Requires("tool:weston")`, and is then skipped there before it is built, as for any tool it declares. When a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to `build/test-logs/<name>.compositor.log`, named as the test's own log is, and the test's output says so, and also when the compositor ended before the test did; what a compositor that did not start printed is in the test's own failure, in `build/test-logs/<name>.log`. A crafter-build that is killed takes its compositors with it; the directories it leaves behind are removed by a test that starts a compositor after they have gone a minute unchanged.
### Linking the parent project's library ### Linking the parent project's library
A test fixture can depend on the project's own library so it can `import` and exercise its API: A test fixture can depend on the project's own library so it can `import` and exercise its API:
@ -562,7 +542,7 @@ This project is licensed under the GNU Lesser General Public License, version 3
The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects. The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects.
The [lib/](lib/) directory contains vendored third-party code (glslang's DirStackFileIncluder) that remains under its own permissive license, see the header of that file. The [lib/](lib/) directory contains vendored third-party code (nlohmann/json, glslang's DirStackFileIncluder) that remains under its own permissive licenses, see the headers of those files.
## Copyright ## Copyright

View file

@ -37,7 +37,6 @@ builder methods overlay overrides:
- `.Dependencies({ &otherCfg, ... })` - `.Dependencies({ &otherCfg, ... })`
- `.Path(p)` &mdash; rebase the test's source-resolution path - `.Path(p)` &mdash; rebase the test's source-resolution path
- `.LinkFlag(s)` / `.CompileFlag(s)` - `.LinkFlag(s)` / `.CompileFlag(s)`
- `.Wayland()` &mdash; a headless Wayland compositor of the test's own, so that the windows it opens stay off your desktop ([Tests that open windows](../../README.md#tests-that-open-windows))
## Test conventions ## Test conventions

File diff suppressed because it is too large Load diff

View file

@ -17,8 +17,8 @@ namespace Crafter {
std::string objPath = object.string(); std::string objPath = object.string();
std::string cppPath = std::format("{}.cpp", path.string()); std::string cppPath = std::format("{}.cpp", path.string());
// The depfile clang wrote beside the object lists the headers this TU // The depfile clang wrote beside the object lists the headers this TU
// included when the object was compiled: inputs of the object as // included; nothing else in the configuration knows about them, since
// much as the source and the BMIs it imports. // the source scanner only reads `import` lines.
if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) { if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) {
return true; return true;
} }

View file

@ -185,10 +185,10 @@ namespace Crafter {
if (scheduled) return precompileJob; if (scheduled) return precompileJob;
std::vector<JobGroup::Job> after; std::vector<JobGroup::Job> after;
// All of the module's partitions, not the ones the primary interface // All of the module's partitions, not the ones the primary interface
// names: Build() records no edge for its `import :Part;` lines (see // names: the scanner records no edge for its `import :Part;` lines
// Module::moduleDependencies). And of a module that is up to date as // (see GetInterfacesAndImplementations). And of a module that is up
// well: this is where its partitions are scheduled, and one of them // to date as well: this is where its partitions are scheduled, and
// may be without its object. // one of them may be without its object.
for (const std::unique_ptr<ModulePartition>& partition : partitions) { for (const std::unique_ptr<ModulePartition>& partition : partitions) {
if (const std::optional<JobGroup::Job> job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); if (const std::optional<JobGroup::Job> job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
} }

View file

@ -43,7 +43,6 @@ namespace {
decltype(&clang_createIndex) createIndex = nullptr; decltype(&clang_createIndex) createIndex = nullptr;
decltype(&clang_disposeIndex) disposeIndex = nullptr; decltype(&clang_disposeIndex) disposeIndex = nullptr;
decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr; decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr;
decltype(&clang_parseTranslationUnit2FullArgv) parseTranslationUnit2FullArgv = nullptr;
decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr; decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr;
decltype(&clang_getFile) getFile = nullptr; decltype(&clang_getFile) getFile = nullptr;
decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr; decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr;
@ -134,7 +133,6 @@ namespace {
bind(lib.createIndex, "clang_createIndex"); bind(lib.createIndex, "clang_createIndex");
bind(lib.disposeIndex, "clang_disposeIndex"); bind(lib.disposeIndex, "clang_disposeIndex");
bind(lib.parseTranslationUnit, "clang_parseTranslationUnit"); bind(lib.parseTranslationUnit, "clang_parseTranslationUnit");
bind(lib.parseTranslationUnit2FullArgv, "clang_parseTranslationUnit2FullArgv");
bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit"); bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit");
bind(lib.getFile, "clang_getFile"); bind(lib.getFile, "clang_getFile");
bind(lib.getLocationForOffset, "clang_getLocationForOffset"); bind(lib.getLocationForOffset, "clang_getLocationForOffset");
@ -707,12 +705,11 @@ namespace {
return decls; return decls;
} }
// The resource directory, which holds clang's own headers such as // libclang locates its builtin headers relative to its own install path,
// stddef.h, as the compiler names it. libclang's driver would otherwise // which need not agree with the clang++ on PATH that produced the PCMs.
// derive one from argv[0] for libclang's own release, so with a libclang // When it disagrees the failure is total and unhelpful — every parse dies
// of another release than the compiler, a file that includes a header of // on "'stddef.h' file not found" — so ask the driver and pass it
// the C++ standard library would fail on "'stddef.h' file not found". // explicitly. Cached like HostTarget, and for the same reason.
// Cached like HostTarget, and for the same reason.
const std::string& ClangResourceDir() { const std::string& ClangResourceDir() {
static const std::string Cached = []() -> std::string { static const std::string Cached = []() -> std::string {
CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string())); CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string()));
@ -755,26 +752,7 @@ namespace {
// Byte-length preserving, so cursor line/column land on the original. // Byte-length preserving, so cursor line/column land on the original.
std::string buffer = BlankExportKeywords(content, tokens); std::string buffer = BlankExportKeywords(content, tokens);
std::string path = file.string(); std::string path = file.string();
// In a build for the host whose compile command names no libc++ std::vector<std::string> args = CommandToArgs(compileCommand);
// directory (a sysroot or CRAFTER_BUILD_LIBCXX_DIR names one), the
// driver inside libclang looks for libc++'s headers in ../include from
// the directory of argv[0], as the compiler's driver does from its
// own, and then in /usr/local/include and in /usr/include. Left to
// name argv[0] itself, libclang names it plain "clang", in no
// directory, so the first of those was ../include from the working
// directory, and where none of them had a libc++, as in the Flatpak,
// whose compiler keeps its own in /app, no file of such a build that
// includes a header of the C++ standard library could be parsed
// (issue #46). The compile command's own argv[0] would not do either:
// a clang++ from PATH is a bare name, and one reached through a link
// into another directory takes itself to be where the link leads,
// unless the command's last prefix flag is -no-canonical-prefixes. So
// argv[0] is the compiler where clang started with this command takes
// itself to be, in the directory it says it is installed in when run
// with the command's last prefix flag, or, where it names none,
// clangxx as the command has it (Toolchain::InstalledClangxx).
std::vector<std::string> args = { GetToolchain().InstalledClangxx(compileCommand).string() };
std::ranges::move(CommandToArgs(compileCommand), std::back_inserter(args));
// Required: libclang will not infer a module interface unit from the // Required: libclang will not infer a module interface unit from the
// .cppm extension, and silently treats every flag as a linker input if // .cppm extension, and silently treats every flag as a linker input if
// left to guess. // left to guess.
@ -794,8 +772,8 @@ namespace {
result.error = "clang_createIndex failed"; result.error = "clang_createIndex failed";
return result; return result;
} }
CXTranslationUnit tu = nullptr; CXTranslationUnit tu = lc.parseTranslationUnit(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None);
if (lc.parseTranslationUnit2FullArgv(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None, &tu) != CXError_Success || !tu) { if (!tu) {
lc.disposeIndex(index); lc.disposeIndex(index);
result.error = "clang could not create a translation unit"; result.error = "clang could not create a translation unit";
return result; return result;
@ -925,10 +903,15 @@ namespace {
// First owner wins, matching the root-first rule dedup: a source // First owner wins, matching the root-first rule dedup: a source
// reachable through two configurations parses with the nearer one. // reachable through two configurations parses with the nearer one.
auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); }; auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); };
// The sources as they are listed: which module each one is a unit for (const std::unique_ptr<Module>& mod : c.interfaces) {
// of, only a build reads. own(fs::path(std::format("{}.cppm", mod->path.string())));
for (const fs::path& source : c.interfaceSources) own(source); for (const std::unique_ptr<ModulePartition>& part : mod->partitions) {
for (const fs::path& source : c.implementationSources) own(source); own(fs::path(std::format("{}.cppm", part->path.string())));
}
}
for (const Implementation& impl : c.implementations) {
own(fs::path(std::format("{}.cpp", impl.path.string())));
}
// cFiles/cuda resolve against cwd at build time (see Build's compile // cFiles/cuda resolve against cwd at build time (see Build's compile
// loops); mirror that here. // loops); mirror that here.
for (const fs::path& cf : c.cFiles) { for (const fs::path& cf : c.cFiles) {
@ -1223,7 +1206,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
for (const auto& [file, owner] : files) { for (const auto& [file, owner] : files) {
std::ifstream in(file, std::ios::binary); std::ifstream in(file, std::ios::binary);
if (!in) continue; // a listed file that is not there is the build's to report if (!in) continue; // config parse already read it; a vanished file fails the build first
std::stringstream buffer; std::stringstream buffer;
buffer << in.rdbuf(); buffer << in.rdbuf();
LintContext ctx; LintContext ctx;

View file

@ -9,8 +9,6 @@ module;
#include <dlfcn.h> #include <dlfcn.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <sys/file.h> #include <sys/file.h>
#include <sys/prctl.h>
#include <signal.h>
#include <fcntl.h> #include <fcntl.h>
#include <errno.h> #include <errno.h>
module Crafter.Build:Platform_impl; module Crafter.Build:Platform_impl;
@ -876,168 +874,6 @@ CommandResult Crafter::RunCommandWithTimeout(std::string_view cmd, std::chrono::
return result; return result;
} }
namespace {
// How a child that waitid saw end ended, read as DecodeWaitStatus reads
// a pclose: the exit code, or 128+signal when a signal ended it.
std::int32_t ChildExitCode(const siginfo_t& info) {
return info.si_code == CLD_EXITED ? info.si_status : 128 + info.si_status;
}
}
Crafter::BackgroundCommand::BackgroundCommand(std::string_view command, std::span<const EnvironmentChange> environment, const fs::path& log, std::chrono::seconds lifetime) {
// The death signal goes to the process this forks, so that has to be
// the timeout process: `exec` makes the sh it starts as become it.
// timeout passes a SIGTERM on to its whole group and ends what is still
// running 2 s later.
std::string script = std::format("exec timeout -k 2 {} sh -c {}", lifetime.count(), ShellQuote(command));
std::string shell = "sh";
std::string flag = "-c";
std::array<char*, 4> argv = { shell.data(), flag.data(), script.data(), nullptr };
std::vector<std::string> variables;
for (char** entry = environ; *entry != nullptr; ++entry) {
const std::string_view variable(*entry);
const std::string_view name = variable.substr(0, variable.find('='));
if (std::ranges::none_of(environment, [&](const EnvironmentChange& change) { return change.name == name; })) {
variables.emplace_back(variable);
}
}
for (const EnvironmentChange& change : environment) {
if (change.value) variables.push_back(std::format("{}={}", change.name, *change.value));
}
std::vector<char*> envp;
for (std::string& variable : variables) envp.push_back(variable.data());
envp.push_back(nullptr);
// Both close-on-exec: the child keeps them only as its 0, 1 and 2.
const std::int32_t output = ::open(log.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (output < 0) throw std::runtime_error(std::format("cannot write {}: {}", log.string(), std::strerror(errno)));
const std::int32_t input = ::open("/dev/null", O_RDONLY | O_CLOEXEC);
if (input < 0) {
const std::int32_t openError = errno;
::close(output);
throw std::runtime_error(std::format("cannot open /dev/null: {}", std::strerror(openError)));
}
const pid_t parent = ::getpid();
// Everything the child uses was made above: between fork and exec it
// makes async-signal-safe calls only, since another thread of this
// process may hold the allocator's lock at the moment of the fork.
pid = ::fork();
if (pid == 0) {
// The signal is sent when the thread that forked ends, not the
// process; the parent may also have ended before this line.
if (::prctl(PR_SET_PDEATHSIG, SIGTERM) != 0 || ::getppid() != parent) ::_exit(126);
// A signal mask outlives exec, and a SIGTERM blocked in it would
// keep both the death signal and Stop() from reaching timeout.
sigset_t none;
::sigemptyset(&none);
::sigprocmask(SIG_SETMASK, &none, nullptr);
::setpgid(0, 0);
::dup2(input, STDIN_FILENO);
::dup2(output, STDOUT_FILENO);
::dup2(output, STDERR_FILENO);
::execve("/bin/sh", argv.data(), envp.data());
::_exit(127);
}
const std::int32_t forkError = errno;
::close(input);
::close(output);
if (pid < 0) throw std::runtime_error(std::format("cannot start {}: {}", command, std::strerror(forkError)));
// From this side as well, so that the group exists before Stop() can
// signal it, whichever of the two runs first. Once the child has
// exec'd this fails, after the child's own call has made the group.
::setpgid(pid, pid);
}
Crafter::BackgroundCommand::~BackgroundCommand() {
Stop(std::chrono::seconds(5));
}
std::optional<std::int32_t> Crafter::BackgroundCommand::Exited() {
if (exitCode || pid < 0) return exitCode;
siginfo_t info{};
// WNOWAIT leaves an ended command unreaped: its pid, and with it the
// number of its process group, which Stop() signals, cannot be handed
// to another process before Stop() reaps it.
if (::waitid(P_PID, static_cast<id_t>(pid), &info, WEXITED | WNOHANG | WNOWAIT) == 0 && info.si_pid == pid) {
exitCode = ChildExitCode(info);
}
return exitCode;
}
void Crafter::BackgroundCommand::Stop(std::chrono::milliseconds grace) {
if (pid < 0 || reaped) return;
::kill(-pid, SIGTERM);
const auto deadline = std::chrono::steady_clock::now() + grace;
while (!Exited() && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// What is left of the group: anything the command started that outlived
// it, and the command itself when it did not end within `grace`.
::kill(-pid, SIGKILL);
std::int32_t status = 0;
while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
reaped = true;
}
namespace {
// Removes what PrivateDirectory's destructor would have, for the
// processes that never ran it.
void RemoveAbandonedDirectories(const fs::path& parent, std::string_view prefix) {
std::error_code ec;
const auto now = fs::file_time_type::clock::now();
for (const fs::directory_entry& entry : fs::directory_iterator(parent, ec)) {
std::error_code entryError;
if (!entry.path().filename().string().starts_with(prefix) || !entry.is_directory(entryError) || entry.is_symlink(entryError)) continue;
// Another user's directory does not open: mkdtemp made it 0700.
const std::int32_t held = ::open(entry.path().c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (held < 0) continue;
// Dated only once it is held: a directory that is kept is dated
// by its holder just before it lets go of it, so a date read
// before the lock can be one the holder has replaced since.
if (::flock(held, LOCK_EX | LOCK_NB) == 0) {
const auto changed = fs::last_write_time(entry.path(), entryError);
if (!entryError && now - changed >= std::chrono::minutes(1)) fs::remove_all(entry.path(), entryError);
}
::close(held);
}
}
fs::path MakeDirectory(const fs::path& parent, std::string_view prefix) {
RemoveAbandonedDirectories(parent, prefix);
std::string pattern = (parent / std::format("{}XXXXXX", prefix)).string();
if (::mkdtemp(pattern.data()) == nullptr) {
throw std::runtime_error(std::format("cannot make a directory in {}: {}", parent.string(), std::strerror(errno)));
}
return fs::path(pattern);
}
}
Crafter::PrivateDirectory::PrivateDirectory(const fs::path& parent, std::string_view prefix) : path(MakeDirectory(parent, prefix)) {
// Close-on-exec, so that the lock is this process's alone: a command it
// starts that outlives it does not keep the directory from being
// removed.
fd = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd >= 0) {
while (::flock(fd, LOCK_EX) != 0 && errno == EINTR) {}
}
}
Crafter::PrivateDirectory::~PrivateDirectory() {
std::error_code ec;
if (kept) {
// Dated now, while it is still held: its date is that of what was
// last made or removed in it, which may be long before, as for the
// run of a test that failed after minutes, and a directory nobody
// holds is removed a minute after its date.
fs::last_write_time(path, fs::file_time_type::clock::now(), ec);
} else {
fs::remove_all(path, ec);
}
if (fd >= 0) ::close(fd);
}
std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
CacheLock lock(stdPcm.parent_path()); CacheLock lock(stdPcm.parent_path());
if(config.target == "x86_64-w64-mingw32") { if(config.target == "x86_64-w64-mingw32") {

View file

@ -64,78 +64,12 @@ namespace {
} }
} }
// Writes build/test-logs/<name>.log and returns its path, or nothing void WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) {
// when the directory cannot be made.
std::optional<fs::path> WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) {
fs::path logDir = projectPath / "build" / "test-logs"; fs::path logDir = projectPath / "build" / "test-logs";
std::error_code ec; std::error_code ec;
fs::create_directories(logDir, ec); fs::create_directories(logDir, ec);
if (ec) return std::nullopt; if (ec) return;
const fs::path log = logDir / std::format("{}.log", name); std::ofstream(logDir / (std::format("{}.log", name))) << output;
std::ofstream(log) << output;
return log;
}
// weston on its headless backend: the compositor a test that sets
// Test::wayland runs with unless --compositor= or CRAFTER_BUILD_COMPOSITOR
// names another. Its GL renderer takes the dmabufs that hardware Vulkan
// and EGL drivers present, which the headless backend's default, a
// renderer that draws nothing, and pixman do not. --no-config keeps the
// user's weston.ini out of the test, and --idle-time=0 keeps the output
// from going idle after the default 300 s, which would stop frame
// callbacks.
constexpr std::string_view DefaultCompositor = "weston --backend=headless --renderer=gl --no-config --idle-time=0";
// The compositor named for none of the test's own: the test gets the
// display crafter-build has, to watch its windows, and the TMPDIR it is
// given, as any test does.
constexpr std::string_view HostDisplay = "host";
// How long a compositor may take to listen. weston needs a fraction of a
// second; this is for a machine running a test on every hardware thread.
constexpr std::chrono::seconds CompositorStartup{30};
std::string CompositorCommand(const std::optional<std::string>& compositorOverride) {
if (compositorOverride && !compositorOverride->empty()) return *compositorOverride;
const char* named = std::getenv("CRAFTER_BUILD_COMPOSITOR");
if (named != nullptr && *named != '\0') return named;
return std::string(DefaultCompositor);
}
// The wayland-<n> socket a compositor made in `directory`. Any number:
// libwayland's wl_display_add_socket_auto starts at 0 and weston at 1.
std::optional<fs::path> WaylandSocket(const fs::path& directory) {
constexpr std::string_view prefix = "wayland-";
std::error_code ec;
for (const fs::directory_entry& entry : fs::directory_iterator(directory, ec)) {
const std::string name = entry.path().filename().string();
if (!name.starts_with(prefix) || name.size() == prefix.size()) continue;
if (!std::ranges::all_of(name.substr(prefix.size()), [](char c) { return c >= '0' && c <= '9'; })) continue;
std::error_code statError;
if (fs::is_socket(entry.symlink_status(statError))) return entry.path();
}
return std::nullopt;
}
// Where the directory one test's compositor gets as its XDG_RUNTIME_DIR
// is made: in $XDG_RUNTIME_DIR, where a session's sockets live, when
// that is a directory, else in /tmp. A socket's path holds at most 107
// bytes, so the directory needs a short path, which a project's, a
// scratch directory's or the temp directory TMPDIR names need not be.
fs::path CompositorParent() {
const char* runtime = std::getenv("XDG_RUNTIME_DIR");
std::error_code ec;
if (runtime != nullptr && *runtime != '\0' && fs::is_directory(runtime, ec)) return runtime;
return "/tmp";
}
// That directory, which also holds the compositor's log.
struct CompositorDirectory : PrivateDirectory {
CompositorDirectory() : PrivateDirectory(CompositorParent(), "crafter-build-wayland-") {}
fs::path Log() const { return path / "compositor.log"; }
};
std::string ReadWhole(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
} }
void PrintResult(const TestResult& r, std::string_view runnerName) { void PrintResult(const TestResult& r, std::string_view runnerName) {
@ -325,91 +259,27 @@ TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) {
return fallback; return fallback;
} }
TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional<std::string>& compositorOverride, const fs::path& temporaryDirectory) { TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout) {
TestResult result; TestResult result;
result.name = test.config.name; result.name = test.config.name;
std::map<std::string, std::string> ph; std::map<std::string, std::string> ph;
ph["{args}"] = JoinAndQuoteArgs(test.args); ph["{args}"] = JoinAndQuoteArgs(test.args);
std::string cmd; auto start = std::chrono::steady_clock::now();
CommandResult r;
if (test.runner.exec.empty()) { if (test.runner.exec.empty()) {
// Local runner: spawn the binary directly through the host shell. // Local runner: spawn the binary directly through the host shell.
cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]); std::string cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]);
r = RunCommandWithTimeout(cmd, timeout);
} else { } else {
// Prefix runner (qemu-user, wasmtime, wine, ...): templated exec // Prefix runner (qemu-user, wasmtime, wine, ...): templated exec
// wraps the local binary. // wraps the local binary.
ph["{bin}"] = binary.string(); ph["{bin}"] = binary.string();
cmd = Substitute(test.runner.exec, ph); r = RunCommandWithTimeout(Substitute(test.runner.exec, ph), timeout);
} }
// What `env` changes for the test, its -u options and its assignments,
// which it takes in that order.
std::string unset;
std::string set;
if (!temporaryDirectory.empty()) set += std::format(" TMPDIR={}", ShellQuote(temporaryDirectory.string()));
// The test's own compositor, which no other test shares, so that no
// two tests cover each other's windows or take each other's focus. Its
// directory goes after it: declared first, it is destroyed last.
const std::string compositor = test.wayland ? CompositorCommand(compositorOverride) : std::string();
std::optional<CompositorDirectory> directory;
std::optional<BackgroundCommand> process;
if (test.wayland && compositor != HostDisplay) {
directory.emplace();
// Without a WAYLAND_DISPLAY, which the compositor would take for a
// session to open a window in (wlroots does), or a DISPLAY.
const std::array<EnvironmentChange, 4> environment = {{
{"XDG_RUNTIME_DIR", directory->path.string()},
{"WAYLAND_DISPLAY", std::nullopt},
{"WAYLAND_SOCKET", std::nullopt},
{"DISPLAY", std::nullopt},
}};
// As long as the test may run, the wait for its socket and 30 s
// more; none for a test with none, a timeout of 0, which timeout(1)
// takes for no limit, the test's as the compositor's.
const std::chrono::seconds lifetime = timeout.count() > 0 ? timeout + CompositorStartup + std::chrono::seconds(30) : std::chrono::seconds(0);
process.emplace(compositor, environment, directory->Log(), lifetime);
// weston makes its socket once its backend and renderer are up, so a
// socket means a compositor that takes clients.
const auto deadline = std::chrono::steady_clock::now() + CompositorStartup;
std::optional<fs::path> socket = WaylandSocket(directory->path);
std::optional<std::int32_t> ended;
while (!socket && !(ended = process->Exited()) && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
socket = WaylandSocket(directory->path);
}
if (!socket) {
process->Stop(std::chrono::seconds(5));
std::string printed = ReadWhole(directory->Log());
if (!printed.empty() && !printed.ends_with('\n')) printed.push_back('\n');
// A compositor that is missing fails the test as any other that
// does not start does. The one skip is the test's own requires_,
// tool:weston for the default, which RunTests checks before the
// build; a probe of the command here would not do, since it is any
// sh command, whose first word need not be the compositor.
result.outcome = TestOutcome::Fail;
result.exitCode = -1;
result.output = ended
? std::format("the headless compositor ({}) ended with status {} before it listened for clients; it printed:\n{}", compositor, *ended, printed)
: std::format("the headless compositor ({}) made no wayland-<n> socket in {} within {} s; it printed:\n{}", compositor, directory->path.string(), CompositorStartup.count(), printed);
// sh's status for a command it cannot find.
if (ended == 127) result.output += "install weston, name another compositor with CRAFTER_BUILD_COMPOSITOR or --compositor=, or skip a test that may run without it with requires_, tool:weston for weston\n";
return result;
}
unset += " -u DISPLAY -u WAYLAND_SOCKET";
set += std::format(" WAYLAND_DISPLAY={}", ShellQuote(socket->string()));
}
// env's command is sh, which execs the test's words as they are: env
// takes every word with an '=' in it ahead of its command for an
// assignment, the binary's path among them where it has one (a test
// named a=b), and with no command left it printed its environment and
// exited 0, a pass for a test that never ran.
if (!unset.empty() || !set.empty()) cmd = std::format("env{}{} sh -c 'exec \"$@\"' sh {}", unset, set, cmd);
auto start = std::chrono::steady_clock::now();
CommandResult r = RunCommandWithTimeout(cmd, timeout);
auto end = std::chrono::steady_clock::now(); auto end = std::chrono::steady_clock::now();
result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
result.output = std::move(r.output); result.output = std::move(r.output);
@ -422,19 +292,6 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std:
else if (r.exitCode != 0) result.outcome = TestOutcome::Fail; else if (r.exitCode != 0) result.outcome = TestOutcome::Fail;
else result.outcome = TestOutcome::Pass; else result.outcome = TestOutcome::Pass;
if (process) {
// Asked before Stop() ends it, which would make every compositor one
// that ended.
const std::optional<std::int32_t> ended = process->Exited();
process->Stop(std::chrono::seconds(5));
if (result.outcome != TestOutcome::Pass && result.outcome != TestOutcome::Skipped) {
if (ended) {
if (!result.output.empty() && !result.output.ends_with('\n')) result.output.push_back('\n');
result.output += std::format("the headless compositor ({}) ended with status {} while the test ran\n", compositor, *ended);
}
result.compositorLog = ReadWhole(directory->Log());
}
}
return result; return result;
} }
@ -587,10 +444,20 @@ TestBuilder& TestBuilder::Define(std::string n, std::string v) {
TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; } TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; }
TestBuilder& TestBuilder::Args(std::vector<std::string> a) { Ref().args = std::move(a); return *this; } TestBuilder& TestBuilder::Args(std::vector<std::string> a) { Ref().args = std::move(a); return *this; }
TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; } TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; }
TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> d) { Ref().config.dependencies = std::move(d); return *this; } TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> d) {
Ref().config.dependencies = std::move(d);
// AddTest already scanned tests/<name>/main.cpp, at which point this test
// had no dependencies, so every `import <DepModule>;` in it came back
// unresolved. Place them now that the libraries are known — without this
// the test's object carries no staleness edge to the interfaces it consumes
// and survives a layout change to them (issue #27). Build() re-runs the
// same sweep as a backstop; doing it here keeps the Configuration coherent
// for anyone inspecting it before the build.
Ref().config.ResolvePendingImports();
return *this;
}
TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; }
TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; }
TestBuilder& TestBuilder::Wayland(bool w) { Ref().wayland = w; return *this; }
void Crafter::UnpackageTests(Configuration& cfg) { void Crafter::UnpackageTests(Configuration& cfg) {
for (Test& test : cfg.tests) test.config.packaging = Packaging::None; for (Test& test : cfg.tests) test.config.packaging = Packaging::None;
@ -601,30 +468,14 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
return RunTests(std::span<Configuration* const>(one), opts, projectArgs); return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
} }
namespace { TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
// The directory of one run of `crafter-build test`, in the temp
// directory, which each test's TMPDIR is made in, and the names given
// out in it. Every pass of a sweep over targets shares it: the first
// that runs a test makes it, and RunTests lets go of it once the last
// pass is done. A pass that made one of its own made it once the
// passes before had let go of theirs, and making it removed any of
// those that had not changed for a minute: a kept one after a pass
// that long, while its test's output said where it was kept.
struct RunTemporaries {
std::optional<PrivateDirectory> directory;
std::set<std::string> used;
};
}
// RunTests, with the run's temporaries.
static TestSummary RunTestsWith(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs, RunTemporaries& run) {
// Each of them once, however often the list names it: named twice, a // Each of them once, however often the list names it: named twice, a
// configuration would have each of its tests built twice at once. // configuration would have each of its tests built twice at once.
std::vector<Configuration*> distinct; std::vector<Configuration*> distinct;
for (Configuration* cfg : configurations) { for (Configuration* cfg : configurations) {
if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg); if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg);
} }
if (distinct.size() != configurations.size()) return RunTestsWith(distinct, opts, projectArgs, run); if (distinct.size() != configurations.size()) return RunTests(distinct, opts, projectArgs);
for (Configuration* cfg : configurations) UnpackageTests(*cfg); for (Configuration* cfg : configurations) UnpackageTests(*cfg);
// Multi-target sweep: when no --target= was given, the run covers every // Multi-target sweep: when no --target= was given, the run covers every
@ -651,7 +502,7 @@ static TestSummary RunTestsWith(std::span<Configuration* const> configurations,
Progress::Clear(); Progress::Clear();
std::println("\n=== target: {} ===", target); std::println("\n=== target: {} ===", target);
} }
TestSummary s = RunTestsWith(configurations, perTarget, projectArgs, run); TestSummary s = RunTests(configurations, perTarget, projectArgs);
aggregate.passed += s.passed; aggregate.passed += s.passed;
aggregate.failed += s.failed; aggregate.failed += s.failed;
aggregate.crashed += s.crashed; aggregate.crashed += s.crashed;
@ -731,28 +582,6 @@ static TestSummary RunTestsWith(std::span<Configuration* const> configurations,
} }
} }
// Each test runs with TMPDIR naming a directory of its own, <run>/<name>,
// in the run's directory in the temp directory (RunTemporaries), so that
// fs::temp_directory_path() in the test names it, where its runner hands
// it TMPDIR (RunSingleTest). Tests stage their fixtures under
// fixed names in it (crafter-build-<name>), and two runs at once staged
// into the same ones: natively every process shares the machine's
// /tmp, and every sandbox of crafter-build's Flatpak shares the one the
// app has. A second test of one name in the run, as two configurations
// or two targets may each have one, gets <name>-2. What a test that
// passes or skips leaves there is removed when it ends; what one that
// fails, crashes or times out leaves is kept, its output says where, and
// so is the run's directory, for a later run to remove a minute after
// this one ends, or after its last change to it where this one is
// killed (PrivateDirectory::Keep).
if (!run.directory) run.directory.emplace(fs::temp_directory_path(), "crafter-build-tests-");
std::vector<fs::path> temporary(filtered.size());
for (std::size_t i = 0; i < filtered.size(); ++i) {
std::string name = filtered[i]->config.name;
for (std::int32_t n = 2; !run.used.insert(name).second; ++n) name = std::format("{}-{}", filtered[i]->config.name, n);
temporary[i] = run.directory->path / name;
}
std::int32_t jobs = opts.jobs > 0 std::int32_t jobs = opts.jobs > 0
? opts.jobs ? opts.jobs
: std::max(1u, std::thread::hardware_concurrency()); : std::max(1u, std::thread::hardware_concurrency());
@ -873,47 +702,16 @@ static TestSummary RunTestsWith(std::span<Configuration* const> configurations,
// triple and nothing for wasm, so every wasm test was handed to // triple and nothing for wasm, so every wasm test was handed to
// wasmtime without the .wasm it was linked as. // wasmtime without the .wasm it was linked as.
fs::path binary = ExpectedOutput(t.config); fs::path binary = ExpectedOutput(t.config);
std::error_code temporaryError;
fs::create_directories(temporary[i], temporaryError);
try { try {
if (temporaryError) throw std::runtime_error(std::format("cannot make the test's TMPDIR {}: {}", temporary[i].string(), temporaryError.message())); r = RunSingleTest(t, binary, timeout);
r = RunSingleTest(t, binary, timeout, opts.compositorOverride, temporary[i]);
} catch (const std::exception& e) { } catch (const std::exception& e) {
r.outcome = TestOutcome::Fail; r.outcome = TestOutcome::Fail;
r.output = std::format("runner threw: {}", e.what()); r.output = std::format("runner threw: {}", e.what());
r.exitCode = -1; r.exitCode = -1;
} }
// The logs are named as the test's TMPDIR is, <name>-2 for a later
// test of one name in the run, so that each has its own: with one
// for both, the second's was written over the first's, and with it
// where what the first left is kept.
const std::string logName = temporary[i].filename().string();
// Beside the test's own log rather than in it: weston prints some
// 70 lines starting up, which would bury what the test said.
if (!r.compositorLog.empty()) {
if (const std::optional<fs::path> log = WriteLog(owners[i]->path, std::format("{}.compositor", logName), r.compositorLog)) {
if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n');
r.output += std::format("the headless compositor's output is in {}\n", log->string());
}
}
if (!temporaryError) {
std::error_code ec;
const bool failed = r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped;
if (failed && !fs::is_empty(temporary[i], ec) && !ec) {
// Kept at once, so that it stays whatever ends the run:
// a later pass that throws, as one does for a target whose
// runner CRAFTER_BUILD_RUNNER_ gives wrong, or a worker
// that cannot be started unwinds past the end of RunTests.
run.directory->Keep();
if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n');
r.output += std::format("what it left in its TMPDIR is kept in {}\n", temporary[i].string());
} else {
fs::remove_all(temporary[i], ec);
}
}
if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) { if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) {
WriteLog(owners[i]->path, logName, r.output); WriteLog(owners[i]->path, r.name, r.output);
} }
{ {
@ -959,8 +757,3 @@ static TestSummary RunTestsWith(std::span<Configuration* const> configurations,
return summary; return summary;
} }
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
RunTemporaries run;
return RunTestsWith(configurations, opts, projectArgs, run);
}

View file

@ -151,24 +151,6 @@ namespace {
std::atomic<bool> ViewMade = false; std::atomic<bool> ViewMade = false;
} }
fs::path Toolchain::InstalledClangxx(std::string_view command) const {
// Every word of the command, as clang's driver.cpp reads its arguments
// before it names its own path; the build quotes neither flag.
bool canonical = true;
for (std::size_t at = 0; at < command.size();) {
const std::size_t end = std::min(command.find(' ', at), command.size());
const std::string_view word = command.substr(at, end - at);
if (word == "-canonical-prefixes") {
canonical = true;
} else if (word == "-no-canonical-prefixes") {
canonical = false;
}
at = end + 1;
}
const fs::path& dir = canonical ? installedDir : installedDirAsWritten;
return dir.empty() ? clangxx : dir / clangxx.filename();
}
std::string Toolchain::LibcxxCompileFlags() const { std::string Toolchain::LibcxxCompileFlags() const {
if (libcxxDir.empty()) return {}; if (libcxxDir.empty()) return {};
return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string()); return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string());
@ -225,13 +207,11 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.clang = "clang"; tc.clang = "clang";
tc.llvmAr = "llvm-ar"; tc.llvmAr = "llvm-ar";
tc.llvmReadelf = "llvm-readelf"; tc.llvmReadelf = "llvm-readelf";
tc.clangScanDeps = "clang-scan-deps";
} else { } else {
tc.clangxx = tc.prefix / "bin" / "clang++"; tc.clangxx = tc.prefix / "bin" / "clang++";
tc.clang = tc.prefix / "bin" / "clang"; tc.clang = tc.prefix / "bin" / "clang";
tc.llvmAr = tc.prefix / "bin" / "llvm-ar"; tc.llvmAr = tc.prefix / "bin" / "llvm-ar";
tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf"; tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf";
tc.clangScanDeps = tc.prefix / "bin" / "clang-scan-deps";
if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) { if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) {
tc.llvmIncludeDir = tc.prefix / "include"; tc.llvmIncludeDir = tc.prefix / "include";
} }
@ -416,22 +396,11 @@ const Toolchain& Crafter::GetToolchain() {
return tc; return tc;
} }
tc.hostTriple = Trimmed(std::move(triple.output)); tc.hostTriple = Trimmed(std::move(triple.output));
// The InstalledDir line of a `--version` run; empty where the run
// failed or printed none.
const auto installedDirOf = [](const CommandResult& run) {
constexpr std::string_view InstalledDirLine = "\nInstalledDir: ";
const std::size_t at = run.output.find(InstalledDirLine);
if (run.exitCode != 0 || at == std::string::npos) return fs::path();
const std::size_t begin = at + InstalledDirLine.size();
return fs::path(Trimmed(run.output.substr(begin, run.output.find('\n', begin) - begin)));
};
CommandResult version = RunCommandChecked(std::format("{} --version", tc.clangxx.string())); CommandResult version = RunCommandChecked(std::format("{} --version", tc.clangxx.string()));
if (version.exitCode == 0) { if (version.exitCode == 0) {
std::string first = version.output.substr(0, version.output.find('\n')); std::string first = version.output.substr(0, version.output.find('\n'));
tc.clangVersion = Trimmed(std::move(first)); tc.clangVersion = Trimmed(std::move(first));
} }
tc.installedDir = installedDirOf(version);
tc.installedDirAsWritten = installedDirOf(RunCommandChecked(std::format("{} -no-canonical-prefixes --version", tc.clangxx.string())));
return tc; return tc;
}(); }();
return Resolved; return Resolved;

View file

@ -69,15 +69,6 @@ export namespace Crafter {
// path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from // path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from
// these directories into files/lib. // these directories into files/lib.
std::set<std::string> runPaths; std::set<std::string> runPaths;
// The configuration this is the build of: the one whose Build() ran.
// A build pass builds a directory once, so of two configurations
// that would be built into one, as the same project loaded along two
// paths with its args in two orders is, only one is built, and only
// that one has the modules the build read in the sources
// (Configuration::interfaces). What is built on the other finds them
// through this. Null where Build() stopped before it read the
// sources.
const struct Configuration* built = nullptr;
}; };
struct Define { struct Define {
@ -176,11 +167,6 @@ export namespace Crafter {
std::int32_t signal = 0; std::int32_t signal = 0;
std::chrono::milliseconds duration{0}; std::chrono::milliseconds duration{0};
std::string output; std::string output;
// What the headless compositor of a test that sets Test::wayland
// printed, kept when the test ran and failed, crashed or timed out,
// for RunTests to write beside the test's own log. A compositor that
// did not start has what it printed in `output`.
std::string compositorLog;
}; };
// One lint diagnostic. Produced by LintContext::Report — or derived by // One lint diagnostic. Produced by LintContext::Report — or derived by
@ -523,26 +509,6 @@ export namespace Crafter {
// sandbox permissions any configuration may declare for the // sandbox permissions any configuration may declare for the
// executables built on it. // executables built on it.
FlatpakApp flatpak; FlatpakApp flatpak;
// The module interface units (.cppm) and the implementation units
// (.cpp) of the configuration, as GetInterfacesAndImplementations
// lists them: absolute, with their extensions.
std::vector<fs::path> interfaceSources;
std::vector<fs::path> implementationSources;
// What those sources are, as Build() found them the last time it read
// all of them without an error: each module whose primary interface
// unit is among interfaceSources, with its partitions, and a unit for
// each of implementationSources, with what each of them imports.
// Build() takes what a source declares and imports from
// clang-scan-deps, which preprocesses the source with the command it
// is compiled with, so it reads them as the compiler does: one in a
// string literal, in a comment or in a branch that #if leaves out is
// not there. It reads them once the configuration's dependencies and
// external dependencies are built, since the command takes their
// include paths and a source may include their headers. Empty until a
// Build() has read the sources. A pass builds a directory once, so a
// configuration whose directory it built for another keeps what it
// had, and what is built on it finds the modules of that build
// through BuildResult::built.
std::vector<std::unique_ptr<Module>> interfaces; std::vector<std::unique_ptr<Module>> interfaces;
std::vector<Implementation> implementations; std::vector<Implementation> implementations;
std::vector<fs::path> cFiles; std::vector<fs::path> cFiles;
@ -636,14 +602,16 @@ export namespace Crafter {
// read, for what that one is built against (see UpdateAgentsMd). Not // read, for what that one is built against (see UpdateAgentsMd). Not
// part of VariantId: the notes change nothing that is compiled. // part of VariantId: the notes change nothing that is compiled.
DependencyNotes dependencyNotes = DependencyNotes::Transitive; DependencyNotes dependencyNotes = DependencyNotes::Transitive;
// Adds the units `interfaces` and `implementations` name to
// interfaceSources and implementationSources. Each is named without
// its extension, .cppm for an interface unit and .cpp for an
// implementation unit, and resolved against `path` and the working
// directory as they are at the call. Reads none of them: Build()
// does, with the command the configuration has by then, its defines,
// flags and dependencies set after this call included.
void GetInterfacesAndImplementations(std::span<fs::path> interfaces, std::span<fs::path> implementations); void GetInterfacesAndImplementations(std::span<fs::path> interfaces, std::span<fs::path> implementations);
// Retry the `import X;` names GetInterfacesAndImplementations could not
// place, against the dependency DAG as it stands now. Sources are
// scanned when they're declared, but `dependencies` is often assigned
// afterwards (AddTest does exactly this), and an import that resolved to
// nothing leaves no staleness edge — so a dependency's interface could
// change and this Configuration's objects would be silently reused
// against the new layout. Build() calls this before checking mtimes;
// calling it again is harmless.
void ResolvePendingImports();
// Declare a test. Sources default to `tests/<name>/main.cpp` resolved // Declare a test. Sources default to `tests/<name>/main.cpp` resolved
// against this Configuration's path; target/march/mtune/sysroot/debug // against this Configuration's path; target/march/mtune/sysroot/debug
// and cudaArch are inherited from this Configuration so cross-arch // and cudaArch are inherited from this Configuration so cross-arch
@ -822,19 +790,6 @@ export namespace Crafter {
// unavailable runner becomes a Fail instead of a silent Skip — the // unavailable runner becomes a Fail instead of a silent Skip — the
// dependency has to be declared to be allowed to be missing. // dependency has to be declared to be allowed to be missing.
std::vector<std::string> requires_; std::vector<std::string> requires_;
// The test talks to a Wayland compositor, so every run of it gets one
// of its own: a headless compositor started for it alone and stopped
// when it ends. The test finds it through WAYLAND_DISPLAY, the full
// path of its socket, and runs with DISPLAY unset, so the windows it
// opens through WAYLAND_DISPLAY do not reach the session's display.
// The compositor is weston on
// its headless backend unless --compositor= or CRAFTER_BUILD_COMPOSITOR
// names another, or names `host` to give the test the session's own
// display. A test whose compositor cannot be started fails, unless it
// declares the compositor in requires_ (tool:weston for the default),
// which skips it where that is missing. README, "Tests that open
// windows".
bool wayland = false;
}; };
// Directory holding the std module PCM for this Configuration, // Directory holding the std module PCM for this Configuration,

View file

@ -11,11 +11,12 @@ namespace Crafter {
export class ModulePartition; export class ModulePartition;
export class Implementation { export class Implementation {
public: public:
// What this unit imports, as in ModulePartition: for a unit of a
// module (`module X;`), the module's primary interface among them.
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<ModulePartition*> partitionDependencies; std::vector<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
// See ModulePartition::pendingImports — imports this TU declared that
// no reachable Configuration provided when the source was scanned.
std::vector<std::string> pendingImports;
fs::path path; fs::path path;
Implementation(fs::path&& path); Implementation(fs::path&& path);
// Whether `object`, the object Build() keeps for this unit // Whether `object`, the object Build() keeps for this unit

View file

@ -10,19 +10,20 @@ namespace Crafter {
export class Module; export class Module;
export class ModulePartition { export class ModulePartition {
public: public:
// What this unit imports, as the Build() that made it read the
// source: modules of its own configuration, partitions of its own
// module, and modules of the configurations it is built on, each of
// those with the BMI that configuration's build writes. An import of
// anything else, `std` or a module from outside the build, has no
// entry.
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<ModulePartition*> partitionDependencies; std::vector<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
// The state of the Build() that made this unit: whether Check has // Names from `import X;` that matched neither a module in this
// run, what it found, whether Schedule has added this unit's jobs, // Configuration nor one reachable through its dependencies at the time
// and the one among them that writes its BMI, which is the job the // the source was scanned. Retried by ResolvePendingImports (see
// units importing it come after. // Crafter.Build:Clang) so a dependency wired up after
// GetInterfacesAndImplementations still produces a staleness edge.
// Names that never resolve (`std`, module-mapped externals) stay here.
std::vector<std::string> pendingImports;
// The state of one Build(), which clears it before it checks: whether
// Check has run, what it found, whether Schedule has added this
// unit's jobs, and the one among them that writes its BMI, which is
// the job the units importing it come after.
bool needsRecompiling = false; bool needsRecompiling = false;
bool checked = false; bool checked = false;
bool scheduled = false; bool scheduled = false;
@ -57,14 +58,13 @@ namespace Crafter {
public: public:
// A primary module interface unit imports things too — `import Base;` // A primary module interface unit imports things too — `import Base;`
// in `export module Widget;` is as much a layout dependency as the // in `export module Widget;` is as much a layout dependency as the
// same line in a partition. Recorded as a partition records the // same line in a partition. Recorded on the same three vectors, with
// modules it imports, with the same meanings, so Check() can see // the same meanings, so Check() can see through them and Schedule()
// through them and Schedule() can order itself behind a sibling // can order itself behind a sibling module in the same Configuration
// module in the same Configuration (issue #26). The partitions it // (issue #26).
// imports need no entry: it is checked and built after all of its
// module's partitions.
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
std::vector<std::string> pendingImports;
// As in ModulePartition. // As in ModulePartition.
bool needsRecompiling = false; bool needsRecompiling = false;
bool checked = false; bool checked = false;

View file

@ -58,67 +58,6 @@ namespace Crafter {
// and not to crafter-build, which then sees it as exit code 130. // and not to crafter-build, which then sees it as exit code 130.
// Project scripts reach this through ScriptContext::Run. // Project scripts reach this through ScriptContext::Run.
std::int32_t RunCommandAttached(std::string_view command); std::int32_t RunCommandAttached(std::string_view command);
// One change to the environment a command inherits from this process:
// the variable set to `value`, or taken out when there is none.
struct EnvironmentChange {
std::string name;
std::optional<std::string> value;
};
// A command that runs beside its caller, through sh, until Stop() or the
// destructor ends it: the compositor of a test that sets Test::wayland.
// Its stdin is /dev/null and its stdout and stderr go to `log`. It is
// the leader of a process group of its own, so that Stop() reaches what
// it starts in turn, as long as that stays in the group, and runs under `timeout`, which ends that group
// after `lifetime` if nothing else has, a `lifetime` of 0 being none,
// as for timeout(1). The timeout process is also sent
// SIGTERM, which it passes on to the group, when the thread that
// constructed this ends, so a crafter-build that is killed, by Ctrl-C
// or otherwise, leaves no command of this kind running. That is why the
// object has to stay on the thread that made it. Throws when the command
// cannot be started.
class BackgroundCommand {
std::int32_t pid = -1;
std::optional<std::int32_t> exitCode;
bool reaped = false;
public:
BackgroundCommand(std::string_view command, std::span<const EnvironmentChange> environment, const fs::path& log, std::chrono::seconds lifetime);
~BackgroundCommand();
BackgroundCommand(const BackgroundCommand&) = delete;
BackgroundCommand& operator=(const BackgroundCommand&) = delete;
// The command's exit code once it has ended on its own, 128+signal
// when a signal ended it; nullopt while it runs. Does not wait.
std::optional<std::int32_t> Exited();
// Sends the group SIGTERM, then SIGKILL to whatever of it is left
// once the command has ended or `grace` has passed, and waits for the
// command. Further calls do nothing.
void Stop(std::chrono::milliseconds grace);
};
// A new directory in `parent`, named `prefix` and six random characters,
// that only this user may enter (mkdtemp), removed with everything in it
// when this ends, unless it is kept. A process that is killed runs no
// destructor, so this also holds an flock on the directory, which the OS
// drops with the process, and making one removes the directories of
// `prefix` in `parent` that nobody holds and that have not changed for a
// minute: left behind by a process that is gone, or kept. The minute
// covers one that is being made at that moment, between mkdtemp and its
// lock. Throws when the directory cannot be made.
// Exported for the tests that make a directory of their own outside the
// temp directory.
export class PrivateDirectory {
std::int32_t fd = -1;
std::atomic<bool> kept{false};
public:
const fs::path path;
PrivateDirectory(const fs::path& parent, std::string_view prefix);
~PrivateDirectory();
PrivateDirectory(const PrivateDirectory&) = delete;
PrivateDirectory& operator=(const PrivateDirectory&) = delete;
// The destructor leaves the directory where it is, unlocked and
// dated as it lets go of it, so that what is in it can be looked at
// for a minute at least, until it is removed as one that nobody
// holds. Several threads may call it at once.
void Keep() { kept = true; }
};
// The link flags that record `dir` as a run path, with -Xlinker rather // The link flags that record `dir` as a run path, with -Xlinker rather
// than -Wl,: clang splits a -Wl, value at every comma, and `dir` may be a // than -Wl,: clang splits a -Wl, value at every comma, and `dir` may be a
// project's own directory, named whatever its owner chose. Quoted for // project's own directory, named whatever its owner chose. Quoted for
@ -225,10 +164,10 @@ namespace Crafter {
// derives <prefix>/share/crafter-build from the running executable's path. // derives <prefix>/share/crafter-build from the running executable's path.
export fs::path GetCrafterBuildHome(); export fs::path GetCrafterBuildHome();
// Newest mtime among the prerequisites a compiler recorded in `depFile` // Newest mtime among the prerequisites a compiler recorded in `depFile`
// (clang's `-MD -MF <artifact>.d`), or clang-scan-deps for the scan of // (clang's `-MD -MF <artifact>.d`). This is how a build step learns which
// a C++ source. This is how a build step learns which headers its // headers its source pulled in: the module scanner only reads `import`
// source pulled in: only the tool that preprocessed the source knows // lines, so an `#include`d file is invisible to it until the compiler
// which files its #includes opened. // reports what it actually opened.
// //
// Returns file_time_type::max() when freshness cannot be proven — no // Returns file_time_type::max() when freshness cannot be proven — no
// depfile (nothing has compiled this artifact since depfiles were emitted, // depfile (nothing has compiled this artifact since depfiles were emitted,

View file

@ -24,8 +24,8 @@ export namespace Crafter {
// interfaces. The builder only mutates compile state, deps, runtime // interfaces. The builder only mutates compile state, deps, runtime
// args, and requires; it deliberately does NOT expose Sources() to // args, and requires; it deliberately does NOT expose Sources() to
// avoid the double-`GetInterfacesAndImplementations` footgun (calling // avoid the double-`GetInterfacesAndImplementations` footgun (calling
// it twice would list the same .cppm files twice, and the build would // it twice would re-parse the same .cppm files into duplicate Module
// make a Module entry of each listing). // entries).
struct TestBuilder { struct TestBuilder {
Configuration* parent; Configuration* parent;
std::size_t index; std::size_t index;
@ -53,9 +53,6 @@ export namespace Crafter {
TestBuilder& LinkFlag(std::string f); TestBuilder& LinkFlag(std::string f);
// Append a single compile flag. // Append a single compile flag.
TestBuilder& CompileFlag(std::string f); TestBuilder& CompileFlag(std::string f);
// Sets Test::wayland: the test runs with a headless Wayland
// compositor of its own.
TestBuilder& Wayland(bool w = true);
}; };
struct RunTestsOptions { struct RunTestsOptions {
@ -78,10 +75,6 @@ export namespace Crafter {
// Target scoping is unnecessary because targetFilter ensures the run // Target scoping is unnecessary because targetFilter ensures the run
// contains only one target's tests. // contains only one target's tests.
std::optional<std::string> runnerOverride; std::optional<std::string> runnerOverride;
// From --compositor=: the compositor every test of the run that sets
// Test::wayland runs with, in place of CRAFTER_BUILD_COMPOSITOR and
// the default. See RunSingleTest.
std::optional<std::string> compositorOverride;
}; };
struct TestSummary { struct TestSummary {
@ -105,34 +98,7 @@ export namespace Crafter {
// compiled alike are, both fail without being built and name the // compiled alike are, both fail without being built and name the
// configurations. A configuration the list names twice counts once. // configurations. A configuration the list names twice counts once.
TestSummary RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs = {}); TestSummary RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs = {});
// Runs `binary` as `test` with its runner, its arguments and `timeout`, TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout);
// and reads the outcome from how it ended (exit 0 passes, 77 skips).
// With a `temporaryDirectory` the test's command runs with TMPDIR naming
// it; RunTests gives each test a directory of its own, made for the run.
// fs::temp_directory_path() in the test names it where the runner hands
// the test TMPDIR, as running it directly and qemu-user do. Under wine a
// Windows test does not get TMPDIR, and takes the Wine prefix's TMP, TEMP
// and temp directory; wasmtime gives a test no environment at all.
//
// When the test sets Test::wayland, a compositor is started for it
// first: `compositorOverride` when it holds a command, else the one
// CRAFTER_BUILD_COMPOSITOR names, else weston on its headless backend.
// The command runs through sh in a process group of its own, with
// XDG_RUNTIME_DIR naming a directory made for it alone and without
// WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, and is waited for until
// a wayland-<n> socket appears in that directory, with a limit of the
// test's, the wait and 30 s more, or none when `timeout` is 0, which is
// no limit for the test either (timeout(1)). The test then runs
// with WAYLAND_DISPLAY set to the socket's path and DISPLAY and
// WAYLAND_SOCKET unset; afterwards the compositor's group is stopped and
// the directory removed. A compositor that ends before it listens, sh
// not finding it included, or does not listen within 30 s fails the
// test, with what it printed; a test that may run where its compositor
// is missing declares it in requires_ (tool:weston), which RunTests
// checks before the build. `host` starts nothing and leaves the test the
// display this process has, its WAYLAND_DISPLAY, WAYLAND_SOCKET, DISPLAY
// and XDG_RUNTIME_DIR; a `temporaryDirectory` is its TMPDIR all the same.
TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout, const std::optional<std::string>& compositorOverride = std::nullopt, const std::filesystem::path& temporaryDirectory = {});
// The configurations of the project crafter-build was pointed at, by // The configurations of the project crafter-build was pointed at, by
// name. Run() hands SetParentProject what the project file returned, // name. Run() hands SetParentProject what the project file returned,

View file

@ -7,11 +7,11 @@ namespace fs = std::filesystem;
export namespace Crafter { export namespace Crafter {
// The compiler crafter-build drives and what sits next to it, resolved // The compiler crafter-build drives and what sits next to it, resolved
// once per process by GetToolchain(). Every clang++, clang, llvm-ar and // once per process by GetToolchain(). Every clang++, clang and llvm-ar
// clang-scan-deps the tool spawns, the libclang the linter dlopens, the // the tool spawns, the libclang the linter dlopens, the std module
// std module source and the default sysroots come from here, so a // source and the default sysroots come from here, so a toolchain
// toolchain installed anywhere other than /usr (the Flatpak carries its // installed anywhere other than /usr (the Flatpak carries its own under
// own under /app) needs no per-call-site knowledge. // /app) needs no per-call-site knowledge.
struct Toolchain { struct Toolchain {
// LLVM install prefix. Empty when the tools are bare names on PATH. // LLVM install prefix. Empty when the tools are bare names on PATH.
fs::path prefix; fs::path prefix;
@ -20,9 +20,6 @@ export namespace Crafter {
fs::path llvmAr; fs::path llvmAr;
// What a packaged program's shared libraries are read with. // What a packaged program's shared libraries are read with.
fs::path llvmReadelf; fs::path llvmReadelf;
// What reads the module a C++ source declares and the modules it
// imports, by preprocessing it with its compile command (Build).
fs::path clangScanDeps;
// Where clang-c/Index.h lives when it is not on the default include // Where clang-c/Index.h lives when it is not on the default include
// path; empty otherwise. // path; empty otherwise.
fs::path llvmIncludeDir; fs::path llvmIncludeDir;
@ -100,37 +97,9 @@ export namespace Crafter {
// `clang++ --version`; both empty when clang++ could not be run. // `clang++ --version`; both empty when clang++ could not be run.
std::string hostTriple; std::string hostTriple;
std::string clangVersion; std::string clangVersion;
// The directory clang++ is installed in, from the InstalledDir line
// of that `clang++ --version`. clang names the directory of the file
// it runs from, so for a clang++ found on PATH, or reached through a
// link into another directory, it is where the compiler really is,
// the directory its driver looks for headers and configuration files
// from (InstalledClangxx). Empty when clang++ could not be run or
// named no directory.
fs::path installedDir;
// The same line of `clang++ -no-canonical-prefixes --version`. With
// that flag clang names the directory of clang++ as written, or, where
// no file is there, as is usual for a bare name, of the one PATH
// gives, a link not followed, and a compile whose last prefix flag is
// that one looks from there. Empty as installedDir is.
fs::path installedDirAsWritten;
// Why clang++ could not be resolved or run; empty when it could. // Why clang++ could not be resolved or run; empty when it could.
std::string error; std::string error;
// clangxx as a program that runs a clang driver of its own over
// `command`, a compile command that starts with clangxx, has to be
// given it: the same file name in the directory clang started with
// that command takes itself to be in, installedDirAsWritten where the
// last of -canonical-prefixes and -no-canonical-prefixes in the
// command is -no-canonical-prefixes, as clang's own driver decides it,
// and installedDir otherwise. That driver takes the directory of the
// compiler it is given as written, without following a link to where
// the compiler is, and looks from there for what the compiler's own
// driver looks for from its directory: clang's own headers where it is
// not told where they are, libc++'s in a build for the host whose
// command names no libc++ directory, and its default configuration
// files. clangxx itself where that directory is empty.
fs::path InstalledClangxx(std::string_view command) const;
// Flags for compiling against libcxxDir; empty without one. // Flags for compiling against libcxxDir; empty without one.
std::string LibcxxCompileFlags() const; std::string LibcxxCompileFlags() const;
// Where libc++.so.1 is when clang would not find it itself: an // Where libc++.so.1 is when clang would not find it itself: an

View file

@ -26,37 +26,6 @@
</provides> </provides>
<content_rating type="oars-1.1"/> <content_rating type="oars-1.1"/>
<releases> <releases>
<release version="6.5.0" date="2026-11-28">
<description>
<p>New</p>
<ul>
<li>A test that sets <code>Test::wayland</code>, or <code>.Wayland()</code> on what <code>AddTest</code> returns, runs with a headless Wayland compositor of its own instead of your session's display, so the windows it opens through <code>WAYLAND_DISPLAY</code> no longer show up on your desktop. The compositor is started for that test alone and stopped when it ends; the test finds it through <code>WAYLAND_DISPLAY</code>, the full path of its socket, and runs without <code>DISPLAY</code>. It is weston on its headless backend with its GL renderer, unless <code>CRAFTER_BUILD_COMPOSITOR</code> or the new <code>--compositor=</code> names another command, and <code>host</code> gives such tests your own display, to watch what they draw. A test whose compositor cannot be started fails, saying why, unless it declares <code>.Requires("tool:weston")</code>, which skips it where weston is missing, and when a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to <code>build/test-logs/&lt;name&gt;.compositor.log</code>, named as the test's own log is. The README's new "Tests that open windows" section has the details.</li>
<li>The Flatpak ships weston 16.0.2, with its headless backend, its GL renderer and its desktop shell: the compositor those tests get.</li>
</ul>
<p>Fixes</p>
<ul>
<li>Two runs of <code>crafter-build test</code> at once no longer write into each other's temporary files. Each test now runs with <code>TMPDIR</code> naming a directory of its own, made for the run, so <code>fs::temp_directory_path()</code> in a test is the test's alone. Tests that staged files under fixed names there collided with another run doing the same: natively every process shares <code>/tmp</code>, and in the Flatpak every instance of the app shares one. What a test leaves there is removed when it passes or skips, and kept when it fails, crashes or times out, with its place in the test's log, until a later run removes it, a minute after the run that kept it ended, or after its last change to it where that run was killed. This takes a runner that passes the test <code>TMPDIR</code>, as running it directly and qemu-user do; under wine, which does not pass it on, and wasmtime, which passes on no environment at all, a test's temporary directory is what it was. A test that builds against a sysroot it stages there, or has crafter-build fetch a repository it stages there, keys crafter-build's cache on a path that is now a new one every run: point <code>XDG_CACHE_HOME</code> into its temporary directory as well.</li>
</ul>
</description>
</release>
<release version="6.4.3" date="2026-11-27">
<description>
<p>Fixes</p>
<ul>
<li>In crafter-build's Flatpak, <code>crafter-build lint</code> runs the rules that read a file's AST on a source that includes a header of the C++ standard library, such as <code>&lt;algorithm&gt;</code>, in a build for the host that names no libc++ directory of its own through a sysroot, <code>CRAFTER_BUILD_LIBCXX_DIR</code> or its flags (#46). There such a source built, and lint then ran none of those rules on it, printed <code>'algorithm' file not found</code> and exited 1. The parse of such a build took the first libc++ it found under <code>../include</code> from the working directory, <code>/usr/local/include</code> and <code>/usr/include</code>, wherever the build's compiler keeps its own (<code>/app</code> in the Flatpak, whose <code>/usr</code> has none). It now looks for libc++ where the compiler does, and reads the default configuration files beside the compiler that the compile reads, such as <code>clang++.cfg</code>.</li>
<li>A build no longer fails to scan its sources where its compiler is reached through a link from another directory, as a <code>bin/clang++</code> under <code>CRAFTER_BUILD_LLVM_DIR</code> may be. clang-scan-deps, which reads what a source declares and imports since 6.4.2, looked for clang's own headers from the directory of the link, and for libc++'s too in a build for the host that names no libc++ directory of its own, and where they were not to be found from there, the scan of a source that includes a header of the C++ standard library failed, and the build with it, though its compile found the header. It is now given the compiler in the directory the compiler says it is installed in, as lint's parse is, and reads the default configuration files beside the compiler that the compile reads.</li>
</ul>
</description>
</release>
<release version="6.4.2" date="2026-11-27">
<description>
<p>Fixes</p>
<ul>
<li>What a <code>.cppm</code> or <code>.cpp</code> declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, where crafter-build searched its text (#45). An import in a comment that spans lines, in a string literal or in a branch that <code>#if</code> leaves out no longer counts; one written with two spaces after <code>import</code>, or with a space before its semicolon, is no longer missed, which let a unit be compiled before the module it imports; and a define or a header decides an import as it does for the compile. A string literal that holds <code>export module std;</code> no longer stops the build. What was read is kept in the build directory, and read again when the source, a file it includes or its compile command changes. The refusal of interface units that import each other, and of a module built twice for one program, comes once the configuration's dependencies are built, before any of its own <code>.cppm</code> and <code>.cpp</code> is compiled, where it came before the configuration built anything.</li>
<li>A project that exports modules and that two paths load with the same flags of its own in two orders is built once where the two orders give it one build directory. The build stopped, taking it for two builds of the project's modules.</li>
</ul>
</description>
</release>
<release version="6.4.1" date="2026-11-19"> <release version="6.4.1" date="2026-11-19">
<description> <description>
<p>Fixes</p> <p>Fixes</p>

View file

@ -378,114 +378,6 @@ modules:
url: https://github.com/KhronosGroup/Vulkan-ValidationLayers/archive/refs/tags/vulkan-sdk-1.4.357.0.tar.gz url: https://github.com/KhronosGroup/Vulkan-ValidationLayers/archive/refs/tags/vulkan-sdk-1.4.357.0.tar.gz
sha256: 73180b11992a3554e97ebc18e6bf2b45ff9790ded9d87fc526c7bab865d1303f sha256: 73180b11992a3554e97ebc18e6bf2b45ff9790ded9d87fc526c7bab865d1303f
# weston on its headless backend, the compositor `crafter-build test` starts
# for each test that sets Test::wayland (README, "Tests that open windows"):
# built with the headless backend, the GL renderer, which imports the
# dmabufs a GPU's Vulkan driver presents, and the desktop shell, and with
# none of its other backends or shells and no Vulkan renderer. weston's frontend
# links libinput, libevdev and libdisplay-info whatever the backend, and the
# Sdk has none of them, so they come first; the headless backend never opens
# an input device, so libinput ships without its quirks, udev helpers and
# tools.
- name: libevdev
buildsystem: meson
config-opts:
- -Dtests=disabled
- -Dtools=disabled
- -Ddocumentation=disabled
cleanup:
- /include
- /lib/pkgconfig
sources:
- type: archive
url: https://www.freedesktop.org/software/libevdev/libevdev-1.14.0.tar.xz
sha256: 5a0966c7110648665983848bad696c7acba614a2160d2865d535397101007332
- name: libinput
buildsystem: meson
config-opts:
- -Dlibwacom=false
- -Dmtdev=false
- -Ddebug-gui=false
- -Dtests=false
- -Ddocumentation=false
- -Dlua-plugins=disabled
- -Dudev-dir=/app/lib/udev
- -Dzshcompletiondir=no
cleanup:
- /bin
- /include
- /lib/pkgconfig
- /lib/udev
- /libexec
- /share/libinput
sources:
# libinput publishes no release tarball, only the tag.
- type: git
url: https://gitlab.freedesktop.org/libinput/libinput.git
tag: 1.32.0
commit: 5cf833b572f5a33663888da321dce0ba1abd82a2
- name: libdisplay-info
buildsystem: meson
cleanup:
- /bin
- /include
- /lib/pkgconfig
sources:
- type: archive
url: https://gitlab.freedesktop.org/emersion/libdisplay-info/-/releases/0.4.0/downloads/libdisplay-info-0.4.0.tar.xz
sha256: 43b180baa143e2035654759d84e2b2f5ee77d5fe817c423838c7fe59c0d68459
- name: weston
buildsystem: meson
config-opts:
# The modules above, never a subproject meson would download.
- --wrap-mode=nodownload
- -Dbackend-drm=false
- -Dbackend-headless=true
- -Dbackend-pipewire=false
- -Dbackend-rdp=false
- -Dbackend-vnc=false
- -Dbackend-wayland=false
- -Dbackend-x11=false
- -Dbackend-default=headless
- -Drenderer-gl=true
- -Drenderer-vulkan=false
- -Dxwayland=false
- -Dsystemd=false
- -Ddeprecated-remoting=false
- -Ddeprecated-pipewire=false
- -Dshell-desktop=true
- -Dshell-ivi=false
- -Dshell-kiosk=false
- -Dshell-lua=false
- -Dcolor-management-lcms=false
- -Dimage-jpeg=false
- -Dimage-webp=false
- -Dtools=[]
- -Ddemo-clients=false
- -Dsimple-clients=[]
- -Dtests=false
- -Ddoc=false
- -Dperfetto=false
cleanup:
- /bin/weston-screenshooter
- /include
- /lib/pkgconfig
- /share/libweston-16
- /share/man
- /share/pkgconfig
- /share/wayland-sessions
post-install:
- weston --version
- test -f /app/lib/libweston-16/headless-backend.so
- test -f /app/lib/libweston-16/gl-renderer.so
sources:
- type: archive
url: https://gitlab.freedesktop.org/wayland/weston/-/releases/16.0.2/downloads/weston-16.0.2.tar.xz
sha256: 49dd87d18cb229384264d2f69cb5a51f14f61a111e9227bfedb91b3ca8c39643
- name: crafter-build - name: crafter-build
buildsystem: simple buildsystem: simple
build-options: build-options:

View file

@ -314,8 +314,6 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("TestTemporaryDirectory").Dependencies({ CrafterBuildLib.get() });
// Loading a project file dlopens the project.so compiled from it, // Loading a project file dlopens the project.so compiled from it,
// which references Crafter:: symbols (HostTarget, Configuration // which references Crafter:: symbols (HostTarget, Configuration
// ctors) that have to be visible from the test exe — same wiring // ctors) that have to be visible from the test exe — same wiring
@ -351,10 +349,8 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("LintCompilerHeaders").Dependencies({ CrafterBuildLib.get() });
} }
// Dogfood: the lite house rules, imported from their own repo through // Dogfood: the lite house rules, imported from their own repo through

View file

@ -8,12 +8,10 @@ using namespace Crafter;
// Regression for the concurrent dependency-reset deadlock (issue #16). // Regression for the concurrent dependency-reset deadlock (issue #16).
// //
// Each Module/ModulePartition holds the state of one build (`checked`, // Build() resets each Module/ModulePartition's per-build state (`checked`,
// `scheduled` and the job that precompiles the unit). Build() used to reset // `scheduled` and the job that precompiles the unit) so a reused Configuration
// it so a reused Configuration re-evaluates mtimes, and now makes the units // re-evaluates mtimes. That reset MUST stay scoped to the configuration being
// anew from what it reads in the sources. Either way that MUST stay scoped // built. It used to recurse into cfg.dependencies — but dependency
// to the configuration being built. The reset used to recurse into
// cfg.dependencies — but dependency
// Configurations are shared across the build DAG and each is built // Configurations are shared across the build DAG and each is built
// concurrently by its own Build() call. Every unit then had a thread of its // concurrently by its own Build() call. Every unit then had a thread of its
// own and a `compiled` flag that the units importing it waited on, and a // own and a `compiled` flag that the units importing it waited on, and a
@ -32,11 +30,11 @@ using namespace Crafter;
// timing: build a static-lib dependency fully (its module ends up checked and // timing: build a static-lib dependency fully (its module ends up checked and
// scheduled), then build a consumer that depends on it while the dependency is // scheduled), then build a consumer that depends on it while the dependency is
// already cached in depResults (so it is NOT rebuilt). A consumer that reset // already cached in depResults (so it is NOT rebuilt). A consumer that reset
// its dependencies, or made their units anew, would leave the dependency's // its dependencies would flip the dependency's module `checked` and
// module with `checked` and `scheduled` false and, because the dependency // `scheduled` flags back to false and, because the dependency never rebuilds,
// never rebuilds, they would stay false. The consumer makes only its own // they would stay false. The consumer resets only its own modules, so the
// units, so the dependency's flags are left intact. We assert both are still // dependency's flags are left intact. We assert both are still set once the
// set once the consumer build completes. // consumer build completes.
int main() { int main() {
fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture"; fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture";
@ -60,6 +58,11 @@ int main() {
dep.GetInterfacesAndImplementations(ifaces, impls); dep.GetInterfacesAndImplementations(ifaces, impls);
} }
if (dep.interfaces.size() != 1) {
std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size());
return 1;
}
{ {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults; std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex; std::mutex depMutex;
@ -68,10 +71,6 @@ int main() {
std::println(std::cerr, "dependency build failed: {}", r.result); std::println(std::cerr, "dependency build failed: {}", r.result);
return 1; return 1;
} }
if (dep.interfaces.size() != 1) {
std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size());
return 1;
}
if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) { if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
std::println(std::cerr, "dependency module not marked checked and scheduled after its own build"); std::println(std::cerr, "dependency module not marked checked and scheduled after its own build");
return 1; return 1;

View file

@ -38,15 +38,6 @@ int main() {
app.GetInterfacesAndImplementations(ifaces, impls); app.GetInterfacesAndImplementations(ifaces, impls);
} }
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(app, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
// What the build read in the sources.
if (app.implementations.size() != 1) { if (app.implementations.size() != 1) {
std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size()); std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size());
return 1; return 1;
@ -65,6 +56,14 @@ int main() {
return 1; return 1;
} }
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(app, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
fs::path libArchive = lib->BinDir() / "libcalc.a"; fs::path libArchive = lib->BinDir() / "libcalc.a";
if (!fs::exists(libArchive)) { if (!fs::exists(libArchive)) {
std::println(std::cerr, "dep archive not produced at {}", libArchive.string()); std::println(std::cerr, "dep archive not produced at {}", libArchive.string());

View file

@ -8,16 +8,13 @@ using namespace Crafter;
// Loads M itself and through A, which passes on all of its args. With // Loads M itself and through A, which passes on all of its args. With
// --split, the list P gives M leaves --wide out, as a filter meant for one // --split, the list P gives M leaves --wide out, as a filter meant for one
// sibling would, and the two paths load M with two different lists. With // sibling would, and the two paths load M with two different lists.
// --reorder, P gives M its args in the other order: the same list, which
// the loader still takes for another.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) { extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
const bool split = std::ranges::contains(args, std::string_view("--split")); const bool split = std::ranges::contains(args, std::string_view("--split"));
std::vector<std::string> mArgs; std::vector<std::string> mArgs;
for (std::string_view arg : args) { for (std::string_view arg : args) {
if (!split || arg != "--wide") mArgs.emplace_back(arg); if (!split || arg != "--wide") mArgs.emplace_back(arg);
} }
if (std::ranges::contains(args, std::string_view("--reorder"))) std::ranges::reverse(mArgs);
Configuration* m = LocalProject({ .projectFile = "../m/project.cpp", .args = mArgs }); Configuration* m = LocalProject({ .projectFile = "../m/project.cpp", .args = mArgs });
Configuration* a = LocalProject({ .projectFile = "../a/project.cpp" }); Configuration* a = LocalProject({ .projectFile = "../a/project.cpp" });

View file

@ -8,14 +8,13 @@ using namespace Crafter;
// A program can hold one module of each name, so Build() refuses a graph in // A program can hold one module of each name, so Build() refuses a graph in
// which two configurations export the same module: the same project loaded // which two configurations export the same module: the same project loaded
// along two paths with two arg lists, say. It used to build both and compile // along two paths with two arg lists, say. It used to build both and put
// the consumer with both on its module path. Clang took the first for every // both on the consumer's module path. Clang took the first for every import
// import of the module, the ones inside the other build's consumers // of the module, the ones inside the other build's consumers included, and
// included, and the program linked code compiled against two layouts of one // the program linked code compiled against two layouts of one struct: it
// struct: it built cleanly, then read garbage or crashed (issue #41). The // built cleanly, then read garbage or crashed (issue #41). The fixture is
// fixture is P -> M and P -> A -> M. With --split, P gives M its args // P -> M and P -> A -> M. With --split, P gives M its args without --wide,
// without --wide, which changes what M declares, while A passes them on // which changes what M declares, while A passes them on whole.
// whole.
namespace { namespace {
std::int32_t Failures = 0; std::int32_t Failures = 0;
@ -54,9 +53,7 @@ int main() {
const fs::path cwd = fs::current_path(); const fs::path cwd = fs::current_path();
fs::current_path(scratch / "p"); fs::current_path(scratch / "p");
try { try {
// Two lists for M: refused before P compiles anything of its own. // Two lists for M: refused before anything is built.
// The modules of a configuration are known once it is built, so M is
// built twice, and A on one of the two, before P can tell.
{ {
std::array<std::string_view, 2> args = { "--wide", "--split" }; std::array<std::string_view, 2> args = { "--wide", "--split" };
Configuration cfg = LoadProject("project.cpp", args); Configuration cfg = LoadProject("project.cpp", args);
@ -64,73 +61,7 @@ int main() {
Check(!built.result.empty(), "a graph with two builds of one module fails to build"); Check(!built.result.empty(), "a graph with two builds of one module fails to build");
Check(built.result.contains("module M is built twice for P"), std::format("the error names the module and the program (got: {})", built.result)); Check(built.result.contains("module M is built twice for P"), std::format("the error names the module and the program (got: {})", built.result));
Check(built.result.contains("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result)); Check(built.result.contains("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result));
Check(!fs::exists(ObjectPath(cfg, scratch / "p" / "main.cpp")) && !fs::exists(ExpectedOutput(cfg)), "P compiled and linked nothing"); Check(!fs::exists(scratch / "m" / "bin") && !fs::exists(scratch / "a" / "bin") && !fs::exists(scratch / "p" / "bin"), "nothing was built");
}
// The same list for M along both paths, in two orders. The loader
// makes a configuration of M for each order, and VariantId, which
// takes the args sorted, gives both one directory, which a pass
// builds once, on whichever of the two asks first. That build's
// modules stand for both: P's import of M and A's have their edge to
// the module it read, and the graph is not taken for one with two
// builds of M. A second pass builds the other configuration on
// purpose, while the first still holds the modules it read: then
// both have modules, and they are still one build.
{
std::array<std::string_view, 2> args = { "--wide", "--reorder" };
Configuration cfg = LoadProject("project.cpp", args);
const bool twoM = cfg.dependencies.size() == 2 && cfg.dependencies[1]->dependencies.size() == 1 && cfg.dependencies[0] != cfg.dependencies[1]->dependencies[0];
Check(twoM, "the two orders load two configurations of M");
if (twoM) {
Configuration& a = *cfg.dependencies[1];
Configuration& mOfP = *cfg.dependencies[0];
Configuration& mOfA = *a.dependencies[0];
Check(mOfP.PcmDir() == mOfA.PcmDir(), "which are built into one directory");
// The module M as a build of `m` read it; nullptr where no
// build of `m` has.
const auto moduleOf = [](const Configuration& m) -> const Module* {
return m.interfaces.size() == 1 ? m.interfaces[0].get() : nullptr;
};
// The module a unit's edge to M leads to; nullptr without one.
const auto edgeToM = [](const auto& unit) -> const Module* {
for (const auto& [imported, bmi] : unit.externalModuleDependencies) {
if (imported->name == "M") return imported;
}
return nullptr;
};
// P's main.cpp and A's interface lead to the module of `built`.
const auto checkEdges = [&](const Configuration& built, std::string_view pass) {
const Module* m = moduleOf(built);
Check(m != nullptr, std::format("{}: the configuration of M built has its module", pass));
Check(cfg.implementations.size() == 1 && edgeToM(cfg.implementations[0]) == m, std::format("{}: P's main.cpp has its edge to that module", pass));
Check(a.interfaces.size() == 1 && edgeToM(*a.interfaces[0]) == m, std::format("{}: A's interface has its edge to that module", pass));
};
// Pass 1, with a record of its own.
BuildResult built = BuildPass(cfg);
Check(built.result.empty(), std::format("pass 1: the graph with one M in two configurations builds (got: {})", built.result));
if (built.result.empty()) {
Configuration& first = moduleOf(mOfP) != nullptr ? mOfP : mOfA;
Configuration& other = &first == &mOfP ? mOfA : mOfP;
Check(moduleOf(other) == nullptr, "pass 1: one of the two is built, and the other has no modules");
checkEdges(first, "pass 1");
// Pass 2: the other one is built first and recorded for
// the directory, as BuildAll records a configuration it
// builds, and the graph after it, which finds that build.
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
std::promise<BuildResult> otherBuilt;
otherBuilt.set_value(Build(other, depResults, depMutex));
depResults.insert_or_assign(other.PcmDir(), otherBuilt.get_future().share());
built = Build(cfg, depResults, depMutex);
Check(built.result.empty(), std::format("pass 2: the graph builds with the other configuration of M built, and the first one holding the module it read in pass 1 (got: {})", built.result));
if (built.result.empty()) {
Check(moduleOf(first) != nullptr, "pass 2: the first one still holds the module it read in pass 1");
checkEdges(other, "pass 2");
}
}
}
} }
// One list along both paths: one M, and the build goes through. // One list along both paths: one M, and the build goes through.

View file

@ -1,517 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
using namespace std::chrono_literals;
// A test that sets Test::wayland runs with a headless compositor of its own,
// so that `test` opens no window on the desktop of whoever runs it, as
// Crafter.Graphics's window tests did. RunSingleTest starts the compositor
// with XDG_RUNTIME_DIR naming a directory made for it, in the session's
// XDG_RUNTIME_DIR or in /tmp where there is none, and without the session's
// WAYLAND_DISPLAY and DISPLAY, waits for a wayland-<n> socket there, runs
// the test with WAYLAND_DISPLAY naming that socket and no DISPLAY, and stops
// the compositor and removes the directory afterwards; also when
// crafter-build is killed while the test runs, which would otherwise leave a
// compositor running for good, and the directory that such a crafter-build
// leaves goes the next time one is made. A test that does not set it, or a
// run that names `host`, keeps the session's display. A test with no time
// limit gives its compositor none, and one whose binary's path holds an '='
// runs as any other. One that is given a TMPDIR as well, as RunTests gives
// every test one, runs with both.
//
// This binary plays every part. Without arguments it is the driver; the
// harness starts it again as the compositor, which listens on a wayland-7
// socket and records what it was given, and as the test, which records its
// environment and connects. No real compositor is needed.
//
// The compositors' directories are made in an XDG_RUNTIME_DIR the driver
// makes in the session's own, or in /tmp where there is none, not in the
// temp directory: a socket's path holds 107 bytes, which a temp directory's
// path can use up by itself. The driver removes it, and its state under
// the temp directory, at the end, and it is a PrivateDirectory, so that one
// a killed driver left goes when a later one is made, once it has not
// changed for a minute. The check without an XDG_RUNTIME_DIR has the
// harness make its compositor's directory in /tmp itself, as crafter-build
// does where there is none.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
constexpr std::string_view Unset = "<unset>";
std::string Variable(std::string_view name) {
const char* value = std::getenv(std::string(name).c_str());
return value != nullptr ? std::string(value) : std::string(Unset);
}
// The variables of a Wayland session, and the TMPDIR a test is given.
constexpr std::array<std::string_view, 5> SessionVariables = { "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY", "XDG_RUNTIME_DIR", "TMPDIR" };
void WriteFile(const fs::path& file, std::string_view content) {
std::ofstream(file, std::ios::binary) << content;
}
std::string ReadFile(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// SessionVariables as this process has them, one NAME=value line each.
void RecordEnvironment(const fs::path& file) {
std::string lines;
for (const std::string_view name : SessionVariables) {
lines += std::format("{}={}\n", name, Variable(name));
}
WriteFile(file, lines);
}
std::map<std::string, std::string> ReadEnvironment(const fs::path& file) {
std::map<std::string, std::string> variables;
std::istringstream in(ReadFile(file));
for (std::string line; std::getline(in, line);) {
const std::size_t equals = line.find('=');
if (equals != std::string::npos) variables[line.substr(0, equals)] = line.substr(equals + 1);
}
return variables;
}
bool SocketAddress(std::string_view path, sockaddr_un& address) {
address = {};
address.sun_family = AF_UNIX;
if (path.size() >= sizeof(address.sun_path)) return false;
std::ranges::copy(path, address.sun_path);
return true;
}
// A descriptor connected to the socket at `path`, or -1.
std::int32_t Connect(std::string_view path) {
sockaddr_un address;
if (!SocketAddress(path, address)) return -1;
const std::int32_t fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) return -1;
if (::connect(fd, reinterpret_cast<const sockaddr*>(&address), sizeof(address)) != 0) {
::close(fd);
return -1;
}
return fd;
}
bool Gone(pid_t pid) {
return ::kill(pid, 0) != 0 && errno == ESRCH;
}
pid_t ReadPid(const fs::path& file) {
pid_t pid = 0;
std::istringstream(ReadFile(file)) >> pid;
return pid;
}
bool WaitFor(const std::function<bool()>& done, std::chrono::milliseconds limit) {
const auto deadline = std::chrono::steady_clock::now() + limit;
while (!done()) {
if (std::chrono::steady_clock::now() > deadline) return false;
std::this_thread::sleep_for(10ms);
}
return true;
}
// The parent of `pid`, from /proc/<pid>/stat, "<pid> (<comm>) <state>
// <ppid> ...", whose comm may hold spaces and parentheses.
pid_t ParentOf(pid_t pid) {
const std::string stat = ReadFile(std::format("/proc/{}/stat", pid));
const std::size_t close = stat.rfind(')');
if (close == std::string::npos) return 0;
std::istringstream rest(stat.substr(close + 1));
std::string state;
pid_t parent = 0;
rest >> state >> parent;
return parent;
}
// The command line of the timeout(1) this process runs under, the
// nearest of its ancestors that is one, its words joined by spaces.
std::string TimeoutAbove() {
for (pid_t pid = ::getppid(); pid > 1; pid = ParentOf(pid)) {
std::string words = ReadFile(std::format("/proc/{}/cmdline", pid));
std::ranges::replace(words, '\0', ' ');
if (words.starts_with("timeout ")) return words;
}
return std::string();
}
// The compositor: listens until SIGTERM, which it records, and records
// the timeout(1) it runs under.
std::int32_t FakeCompositor(const fs::path& state) {
RecordEnvironment(state / "compositor.env");
WriteFile(state / "compositor.timeout", TimeoutAbove());
WriteFile(state / "compositor.pid", std::format("{}", ::getpid()));
// Blocked before the socket appears, so that sigwait takes the
// SIGTERM of a Stop() that comes the moment the harness sees it.
sigset_t term;
::sigemptyset(&term);
::sigaddset(&term, SIGTERM);
::sigprocmask(SIG_BLOCK, &term, nullptr);
const fs::path socketPath = fs::path(Variable("XDG_RUNTIME_DIR")) / "wayland-7";
sockaddr_un address;
const std::int32_t fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0 || !SocketAddress(socketPath.string(), address)
|| ::bind(fd, reinterpret_cast<const sockaddr*>(&address), sizeof(address)) != 0 || ::listen(fd, 8) != 0) {
std::println(std::cerr, "fake compositor: cannot listen on {}: {}", socketPath.string(), std::strerror(errno));
return 2;
}
std::println(std::cerr, "fake compositor listening on {}", socketPath.string());
WriteFile(state / "compositor.listening", socketPath.string());
std::int32_t signal = 0;
::sigwait(&term, &signal);
WriteFile(state / "compositor.terminated", "");
return 0;
}
// The test: records its environment and connects to WAYLAND_DISPLAY.
// With `hold` it stays connected until the compositor goes away.
std::int32_t Client(const fs::path& state, bool hold) {
RecordEnvironment(state / "client.env");
const std::string display = Variable("WAYLAND_DISPLAY");
const std::int32_t fd = Connect(display);
if (fd < 0) {
std::println(std::cerr, "cannot connect to {}: {}", display, std::strerror(errno));
return 1;
}
WriteFile(state / "client.connected", "");
if (hold) {
// Never written to: read returns once the listening socket is
// gone, with 0 or ECONNRESET.
char byte = 0;
while (::read(fd, &byte, 1) > 0) {}
}
::close(fd);
return 0;
}
// The test, failing after it has ended its compositor: the harness has
// to say that the compositor ended while the test ran.
std::int32_t KillCompositor(const fs::path& state) {
const pid_t compositor = ReadPid(state / "compositor.pid");
if (compositor <= 0 || ::kill(compositor, SIGKILL) != 0) return 2;
WaitFor([&] { return Gone(compositor); }, 5s);
// Time for timeout, which ends when its child has, to have ended.
std::this_thread::sleep_for(300ms);
return 1;
}
std::string FakeCompositorCommand(const fs::path& self, const fs::path& state) {
return std::format("{} --compositor {}", ShellQuote(self.string()), ShellQuote(state.string()));
}
Test MakeTest(bool wayland, std::string_view mode, const fs::path& state) {
Test test;
test.runner = TestRunner::Local();
test.config.name = std::format("HeadlessCompositor{}", mode);
test.wayland = wayland;
test.args = { std::string(mode), state.string() };
return test;
}
// crafter-build in the middle of a test, for the driver to kill.
std::int32_t Orphan(const fs::path& self, const fs::path& state) {
RunSingleTest(MakeTest(true, "--hold", state), self, 30s, FakeCompositorCommand(self, state));
return 0;
}
}
int main(int argc, char* argv[]) {
const fs::path self = fs::read_symlink("/proc/self/exe");
if (argc == 3) {
const std::string_view mode = argv[1];
const fs::path state = argv[2];
if (mode == "--compositor") return FakeCompositor(state);
if (mode == "--client") return Client(state, false);
if (mode == "--hold") return Client(state, true);
if (mode == "--env") {
RecordEnvironment(state / "client.env");
return 0;
}
if (mode == "--fail") {
RecordEnvironment(state / "client.env");
std::println(std::cerr, "the test failed");
return 1;
}
if (mode == "--kill-compositor") return KillCompositor(state);
if (mode == "--orphan") return Orphan(self, state);
return 2;
}
const fs::path root = fs::temp_directory_path() / "crafter-build-headless-compositor";
std::error_code ec;
fs::remove_all(root, ec);
const auto stateDir = [&](std::string_view name) {
const fs::path dir = root / name;
fs::create_directories(dir);
return dir;
};
// The directory the harness makes the compositors' in, as it would in
// the session's XDG_RUNTIME_DIR: one of the driver's own, so that
// nothing here removes or keeps the directories of a real run. Where
// the session has none, it is made in /tmp, by name, whose path leaves
// a socket's room, as a temp directory's need not (above).
const std::string sessionRuntime = Variable("XDG_RUNTIME_DIR");
const fs::path base = sessionRuntime != Unset && fs::is_directory(sessionRuntime, ec) ? fs::path(sessionRuntime) : fs::path("/tmp");
std::optional<PrivateDirectory> own;
try {
own.emplace(base, "crafter-build-headless-compositor-");
} catch (const std::exception& e) {
std::println(std::cerr, "FAIL: {}", e.what());
return 1;
}
const fs::path parent = own->path;
const std::string runtime = parent.string();
::setenv("XDG_RUNTIME_DIR", runtime.c_str(), 1);
// The session's display, which a test that sets Test::wayland must not
// see and one that does not must.
::setenv("WAYLAND_DISPLAY", "crafter-build-session-display", 1);
::setenv("DISPLAY", ":4242", 1);
// An fd number nothing has open: nothing here connects through
// libwayland, which would take it for its connection to a compositor.
::setenv("WAYLAND_SOCKET", "4243", 1);
::unsetenv("CRAFTER_BUILD_COMPOSITOR");
{
const fs::path state = stateDir("wayland");
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state));
Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland passes against its compositor: {}", r.output));
std::map<std::string, std::string> server = ReadEnvironment(state / "compositor.env");
std::map<std::string, std::string> client = ReadEnvironment(state / "client.env");
const fs::path directory = server["XDG_RUNTIME_DIR"];
Check(directory.parent_path() == parent && directory.filename().string().starts_with("crafter-build-wayland-"),
std::format("the compositor's XDG_RUNTIME_DIR is a directory of its own in {}: {}", parent.string(), directory.string()));
Check(server["WAYLAND_DISPLAY"] == Unset && server["WAYLAND_SOCKET"] == Unset && server["DISPLAY"] == Unset,
"the compositor gets none of the session's WAYLAND_DISPLAY, WAYLAND_SOCKET and DISPLAY");
Check(client["WAYLAND_DISPLAY"] == ReadFile(state / "compositor.listening"),
std::format("the test's WAYLAND_DISPLAY is the path of the compositor's socket: {}", client["WAYLAND_DISPLAY"]));
Check(client["DISPLAY"] == Unset && client["WAYLAND_SOCKET"] == Unset, "the test runs without DISPLAY and WAYLAND_SOCKET");
Check(client["XDG_RUNTIME_DIR"] == runtime, "the test keeps the session's XDG_RUNTIME_DIR");
Check(fs::exists(state / "client.connected"), "the test connected to the compositor");
Check(fs::exists(state / "compositor.terminated"), "the compositor is sent SIGTERM once the test has ended");
Check(!directory.empty() && !fs::exists(directory), "the compositor's directory is removed afterwards");
const pid_t compositor = ReadPid(state / "compositor.pid");
Check(compositor > 0 && Gone(compositor), "the compositor is not running after the test");
Check(r.compositorLog.empty(), "a test that passes keeps no compositor log");
const std::string limit = ReadFile(state / "compositor.timeout");
Check(limit.starts_with("timeout -k 2 70 "), std::format("the compositor's limit is the test's, the wait for its socket and 30 s more: {}", limit));
}
// A test with no time limit, a timeout of 0, which timeout(1) takes for
// none, gives its compositor none either: a limit of its own would end
// the compositor under a test that runs on.
{
const fs::path state = stateDir("unlimited");
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 0s, FakeCompositorCommand(self, state));
Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland and has no time limit passes: {}", r.output));
const std::string limit = ReadFile(state / "compositor.timeout");
Check(limit.starts_with("timeout -k 2 0 "), std::format("and its compositor has no limit either: {}", limit));
}
// A test whose binary's path has an '=' in it: env, which unsets and
// sets the display's variables, would take that path for an
// assignment of its own.
{
const fs::path state = stateDir("equals");
const fs::path linked = stateDir("a=b") / "HeadlessCompositor";
fs::create_symlink(self, linked, ec);
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), linked, 10s, FakeCompositorCommand(self, state));
Check(r.outcome == TestOutcome::Pass && fs::exists(state / "client.connected"),
std::format("a test whose binary's path has an '=' in it runs against its compositor: {}", r.output));
}
// Where the session has no XDG_RUNTIME_DIR, the compositor's directory
// is made in /tmp, by name: the temp directory's path may leave a
// socket's path no room.
{
const fs::path state = stateDir("no-runtime");
::unsetenv("XDG_RUNTIME_DIR");
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state));
::setenv("XDG_RUNTIME_DIR", runtime.c_str(), 1);
Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland passes where the session has no XDG_RUNTIME_DIR: {}", r.output));
std::map<std::string, std::string> server = ReadEnvironment(state / "compositor.env");
const fs::path directory = server["XDG_RUNTIME_DIR"];
Check(directory.parent_path() == "/tmp" && directory.filename().string().starts_with("crafter-build-wayland-"),
std::format("and its compositor's XDG_RUNTIME_DIR is then a directory of its own in /tmp: {}", directory.string()));
Check(!directory.empty() && !fs::exists(directory), "which is removed afterwards");
}
// A test that sets wayland and is given a TMPDIR: the env prefix takes
// the TMPDIR beside what it unsets and sets for the display.
{
const fs::path state = stateDir("tmpdir");
const fs::path given = stateDir("tmpdir-given");
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state), given);
Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland and is given a TMPDIR passes: {}", r.output));
std::map<std::string, std::string> client = ReadEnvironment(state / "client.env");
Check(client["TMPDIR"] == given.string(), std::format("and runs with that TMPDIR: {}", client["TMPDIR"]));
Check(client["WAYLAND_DISPLAY"] == ReadFile(state / "compositor.listening") && client["DISPLAY"] == Unset && client["WAYLAND_SOCKET"] == Unset,
std::format("and with its compositor's display alone: {}", client["WAYLAND_DISPLAY"]));
}
// Under `host`, a test given a TMPDIR runs with it, beside the
// session's display.
{
const fs::path state = stateDir("host-tmpdir");
const fs::path given = stateDir("host-tmpdir-given");
const TestResult r = RunSingleTest(MakeTest(true, "--env", state), self, 10s, "host", given);
std::map<std::string, std::string> client = ReadEnvironment(state / "client.env");
Check(r.outcome == TestOutcome::Pass && client["TMPDIR"] == given.string(), std::format("under `host` a test given a TMPDIR runs with it: {}", client["TMPDIR"]));
Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243",
"and with the session's display");
}
{
const fs::path state = stateDir("without");
const TestResult r = RunSingleTest(MakeTest(false, "--env", state), self, 10s, FakeCompositorCommand(self, state));
std::map<std::string, std::string> client = ReadEnvironment(state / "client.env");
Check(r.outcome == TestOutcome::Pass, std::format("a test that does not set wayland passes: {}", r.output));
Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243",
"a test that does not set wayland keeps the session's display");
Check(!fs::exists(state / "compositor.pid"), "no compositor is started for a test that does not set wayland");
}
{
const fs::path state = stateDir("host");
const TestResult r = RunSingleTest(MakeTest(true, "--env", state), self, 10s, "host");
std::map<std::string, std::string> client = ReadEnvironment(state / "client.env");
Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland passes under `host`: {}", r.output));
Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243",
"under `host` the test keeps the session's display");
}
{
const fs::path state = stateDir("variable");
::setenv("CRAFTER_BUILD_COMPOSITOR", FakeCompositorCommand(self, state).c_str(), 1);
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s);
Check(r.outcome == TestOutcome::Pass && fs::exists(state / "client.connected"),
std::format("without an override the compositor CRAFTER_BUILD_COMPOSITOR names is started: {}", r.output));
}
{
const fs::path state = stateDir("override");
::setenv("CRAFTER_BUILD_COMPOSITOR", "crafter-build-no-such-compositor", 1);
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state));
Check(r.outcome == TestOutcome::Pass && fs::exists(state / "client.connected"),
std::format("--compositor= wins over CRAFTER_BUILD_COMPOSITOR: {}", r.output));
::unsetenv("CRAFTER_BUILD_COMPOSITOR");
}
{
const fs::path state = stateDir("missing");
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, "crafter-build-no-such-compositor --headless");
Check(r.outcome == TestOutcome::Fail, std::format("a compositor sh cannot find fails the test: {}", r.output));
// The command in the harness's words: sh's own error names its first
// word and never the rest.
Check(r.output.contains("(crafter-build-no-such-compositor --headless)") && r.output.contains("status 127") && r.output.contains("tool:weston"),
std::format("the failure names the compositor and says how a test is skipped without it: {}", r.output));
Check(!fs::exists(state / "client.env"), "the test does not run without its compositor");
}
{
const fs::path state = stateDir("broken");
// Printed in two halves, so that what the failure quotes of the
// command does not hold what the compositor printed.
const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, "printf '%s-%s\\n' compositor start-failure >&2; exit 3");
Check(r.outcome == TestOutcome::Fail, std::format("a compositor that ends before it listens fails the test: {}", r.output));
Check(r.output.contains("status 3") && r.output.contains("it printed:\ncompositor-start-failure"),
std::format("the failure gives the compositor's status and what it printed: {}", r.output));
Check(!fs::exists(state / "client.env"), "the test does not run when its compositor did not start");
}
{
const fs::path state = stateDir("failing");
const TestResult r = RunSingleTest(MakeTest(true, "--fail", state), self, 10s, FakeCompositorCommand(self, state));
Check(r.outcome == TestOutcome::Fail, std::format("a failing test fails: {}", r.output));
Check(r.compositorLog.contains("fake compositor listening"), std::format("a failing test keeps what its compositor printed: {}", r.compositorLog));
Check(!r.output.contains("while the test ran"), std::format("a compositor that ran until the end is not reported as ended: {}", r.output));
}
{
const fs::path state = stateDir("ended");
const TestResult r = RunSingleTest(MakeTest(true, "--kill-compositor", state), self, 10s, FakeCompositorCommand(self, state));
Check(r.outcome == TestOutcome::Fail && r.output.contains("ended with status 137 while the test ran"),
std::format("a compositor killed while the test ran is reported: {}", r.output));
}
{
// crafter-build killed in the middle of a test, as Ctrl-C would.
const fs::path state = stateDir("orphan");
std::fflush(nullptr);
const pid_t orphan = ::fork();
if (orphan == 0) {
const std::string path = self.string();
const std::string mode = "--orphan";
const std::string dir = state.string();
::execl(path.c_str(), path.c_str(), mode.c_str(), dir.c_str(), nullptr);
::_exit(127);
}
const bool connected = orphan > 0 && WaitFor([&] { return fs::exists(state / "client.connected"); }, 10s);
Check(connected, "the test of the crafter-build to be killed connected to its compositor");
if (orphan > 0) {
::kill(orphan, SIGKILL);
std::int32_t status = 0;
::waitpid(orphan, &status, 0);
}
if (connected) {
const pid_t compositor = ReadPid(state / "compositor.pid");
Check(WaitFor([&] { return fs::exists(state / "compositor.terminated"); }, 5s),
"the compositor of a crafter-build that is killed is sent SIGTERM");
Check(compositor > 0 && WaitFor([&] { return Gone(compositor); }, 5s), "and is not left running");
}
// Its directory is left, unlocked, and goes when the next is made
// once it has not changed for a minute; one made a moment ago, or one
// that is held (here by the driver), stays.
const fs::path abandoned = ReadEnvironment(state / "compositor.env")["XDG_RUNTIME_DIR"];
Check(connected && fs::is_directory(abandoned, ec), std::format("a crafter-build that is killed leaves its directory: {}", abandoned.string()));
const auto old = fs::file_time_type::clock::now() - std::chrono::minutes(2);
fs::last_write_time(abandoned, old, ec);
const fs::path young = parent / "crafter-build-wayland-young";
const fs::path held = parent / "crafter-build-wayland-held";
fs::create_directories(young, ec);
fs::create_directories(held, ec);
fs::last_write_time(held, old, ec);
const std::int32_t lock = ::open(held.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Check(lock >= 0 && ::flock(lock, LOCK_EX) == 0, "the driver holds a directory");
const fs::path next = stateDir("after-orphan");
const TestResult r = RunSingleTest(MakeTest(true, "--client", next), self, 10s, FakeCompositorCommand(self, next));
Check(r.outcome == TestOutcome::Pass, std::format("the next test that sets wayland passes: {}", r.output));
Check(!fs::exists(abandoned), "an abandoned directory that has not changed for a minute is removed");
Check(fs::is_directory(young, ec), "one that changed a moment ago is kept");
Check(fs::is_directory(held, ec), "and so is one that is held");
if (lock >= 0) ::close(lock);
}
fs::remove_all(root, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -79,18 +79,11 @@ int main() {
} }
at = info.find("filesystems=", at + 1); at = info.find("filesystems=", at + 1);
} }
// Both in a directory of this run's own there, a PrivateDirectory,
// removed at the end of this block: every sandbox of the app has the
// same /tmp, so two runs at once would ask about, and remove, the
// same projects, and what a run that is killed leaves goes when a
// later one is made, once it has not changed for a minute.
const PrivateDirectory own("/tmp", "crafter-build-host-flatpak-");
const fs::path& scratch = own.path;
const fs::path link = fixture / "build" / "to-tmp"; const fs::path link = fixture / "build" / "to-tmp";
fs::create_directories(link.parent_path(), ec); fs::create_directories(link.parent_path(), ec);
fs::remove(link, ec); fs::remove(link, ec);
fs::create_directory_symlink(scratch, link, ec); fs::create_directory_symlink("/tmp", link, ec);
const std::array<fs::path, 2> unseen = {scratch / "project", link / "linked"}; const std::array<fs::path, 2> unseen = {"/tmp/crafter-build-host-flatpak", link / "crafter-build-host-flatpak-linked"};
for (const fs::path& project : unseen) { for (const fs::path& project : unseen) {
if (tmpShared) { if (tmpShared) {
std::println("an override shares the host's /tmp with the sandbox, so the host sees {}: left out", project.string()); std::println("an override shares the host's /tmp with the sandbox, so the host sees {}: left out", project.string());
@ -107,8 +100,6 @@ int main() {
Check(fs::is_empty(project, ec), std::format("and asking leaves nothing in {}", project.string())); Check(fs::is_empty(project, ec), std::format("and asking leaves nothing in {}", project.string()));
fs::remove_all(fs::weakly_canonical(project, ec), ec); fs::remove_all(fs::weakly_canonical(project, ec), ec);
} }
// The link goes with the directory it leads to.
fs::remove(link, ec);
// From a working directory only the sandbox has, the host is reached // From a working directory only the sandbox has, the host is reached
// all the same, and sees the fixture. // all the same, and sees the fixture.
if (permitted) { if (permitted) {

View file

@ -6,11 +6,11 @@ import Crafter.Build;
namespace fs = std::filesystem; namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
// Interface units that import each other are refused before any .cppm or // Interface units that import each other are refused before their
// .cpp of their configuration is compiled, with an error naming them. No // configuration builds anything, with an error naming them. No order builds
// order builds them. Before the refusal such a build hung with no compiler // them. Before the refusal such a build hung with no compiler running, each
// running, each unit waiting for the units it imports, which is how this // unit waiting for the units it imports, which is how this test failed then:
// test failed then: by running into its timeout. // by running into its timeout.
// //
// Three ways round: two partitions that import each other, a partition that // Three ways round: two partitions that import each other, a partition that
// imports its own module, whose primary interface is built after all of its // imports its own module, whose primary interface is built after all of its
@ -28,9 +28,9 @@ namespace {
// Builds the interfaces of the fixture in `dir` as a library and returns // Builds the interfaces of the fixture in `dir` as a library and returns
// Build()'s error. On a copy outside the checkout, made anew each run: a // Build()'s error. On a copy outside the checkout, made anew each run: a
// build that gets past the refusal can compile units before it fails, and // build that gets past the refusal has made its directories before it
// in the checkout the next run would find them there and report them // fails, and in the checkout the next run would find them there and
// against a refusal that works. // report them against a refusal that works.
std::string BuildError(std::string_view dir, std::span<fs::path> interfaces) { std::string BuildError(std::string_view dir, std::span<fs::path> interfaces) {
const fs::path staged = fs::temp_directory_path() / "crafter-build-import-cycle" / dir; const fs::path staged = fs::temp_directory_path() / "crafter-build-import-cycle" / dir;
fs::remove_all(staged); fs::remove_all(staged);
@ -49,13 +49,9 @@ namespace {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults; std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex; std::mutex depMutex;
const BuildResult built = Build(cfg, depResults, depMutex); const BuildResult built = Build(cfg, depResults, depMutex);
// Refused once the build has read what the units import, which is // Refused like a graph with a module built twice: before a directory
// before it compiles any of them: no unit has a BMI or an object. // is made for it.
for (const fs::path& interface : interfaces) { Check(!fs::exists(cfg.BuildDir()) && !fs::exists(cfg.BinDir()), std::format("{}: the refused build left {} or {} behind", dir, cfg.BuildDir().string(), cfg.BinDir().string()));
const fs::path bmi = cfg.PcmDir() / std::format("{}.pcm", interface.string());
const fs::path object = cfg.BuildDir() / std::format("{}.o", interface.string());
Check(!fs::exists(bmi) && !fs::exists(object), std::format("{}: the refused build compiled {}", dir, interface.string()));
}
return built.result; return built.result;
} }
} }
@ -65,6 +61,9 @@ int main() {
std::array<fs::path, 3> interfaces = { "Ring", "Ring-First", "Ring-Second" }; std::array<fs::path, 3> interfaces = { "Ring", "Ring-First", "Ring-Second" };
const std::string error = BuildError("partitions", interfaces); const std::string error = BuildError("partitions", interfaces);
Check(error.contains("Ring:First -> Ring:Second -> Ring:First"), std::format("partitions that import each other are named in the order they wait in, got: '{}'", error)); Check(error.contains("Ring:First -> Ring:Second -> Ring:First"), std::format("partitions that import each other are named in the order they wait in, got: '{}'", error));
// The scanner reads imports the compiler does not see, so the error
// has to say where a round nobody wrote can come from.
Check(error.contains("string literal") && error.contains("#if 0"), std::format("the error says which text the scanner reads as an import, got: '{}'", error));
} }
{ {
std::array<fs::path, 2> interfaces = { "Own", "Own-Part" }; std::array<fs::path, 2> interfaces = { "Own", "Own-Part" };

View file

@ -2,9 +2,9 @@
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module; module;
// The whole point of the fixture: an input to this interface unit that is // The whole point of the fixture: an input to this interface unit that the
// not its own source. WIDGET_SLOTS comes from a header, so the class layout // module scanner cannot see. WIDGET_SLOTS comes from a header, so the class
// below changes without Widget.cppm being touched. // layout below changes without Widget.cppm being touched.
#include "widget-layout.h" #include "widget-layout.h"
export module Widget; export module Widget;
import std; import std;

View file

@ -8,7 +8,7 @@ using namespace Crafter;
// Editing a header must rebuild everything that #includes it. The staleness // Editing a header must rebuild everything that #includes it. The staleness
// check used to compare an artifact against its own source and its module // check used to compare an artifact against its own source and its module
// imports only — and the module scanner read `import` lines, so a header was // imports only — and the module scanner reads `import` lines, so a header was
// invisible to it. A build after a header-only edit reported nothing to do and // invisible to it. A build after a header-only edit reported nothing to do and
// left objects compiled against the previous contents: the same silent // left objects compiled against the previous contents: the same silent
// mixed-layout binary as issue #27, reached through #include instead. // mixed-layout binary as issue #27, reached through #include instead.

View file

@ -3,7 +3,10 @@
// Copied over lib/Widget.cppm mid-test to stand in for the interface edit from // Copied over lib/Widget.cppm mid-test to stand in for the interface edit from
// issue #27: one extra data member, every signature and mangled name unchanged. // issue #27: one extra data member, every signature and mangled name unchanged.
// Kept as a .cppm.in so that no build takes it for a source of its own. // Kept as a .cppm.in so the module scanner never treats it as a source of its
// own — and so the text does not have to live in a string literal inside the
// test, where `export module Widget;` would make the test itself look like an
// implementation unit of Widget.
export module Widget; export module Widget;
import std; import std;

View file

@ -7,17 +7,15 @@ namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
// Adding a data member to a class in a module interface must rebuild every // Adding a data member to a class in a module interface must rebuild every
// object compiled against the old layout. The dangerous shape (issue #27) was a // object compiled against the old layout. The dangerous shape (issue #27) is a
// consumer whose sources were scanned *before* its `dependencies` were assigned: // consumer whose sources were scanned *before* its `dependencies` were assigned:
// its `import <DepModule>;` matched nothing, so its object carried no staleness // its `import <DepModule>;` matched nothing, so its object carried no staleness
// edge to the interface, and a layout change rebuilt the library, relinked the // edge to the interface, and a layout change rebuilt the library, relinked the
// consumer, and produced a binary mixing both layouts with no error or warning. // consumer, and produced a binary mixing both layouts with no error or warning.
// //
// `AddTest` is exactly that shape — it lists tests/<name>/main.cpp and only then // `AddTest` is exactly that shape — it scans tests/<name>/main.cpp and only then
// returns a builder whose .Dependencies() supplies the library — which is why // returns a builder whose .Dependencies() supplies the library — which is why
// the original report saw the corruption in test executables specifically. // the original report saw the corruption in test executables specifically.
// A build reads the sources now, once the dependencies are built, so the order
// they were declared in no longer matters; the cases below hold it to that.
namespace { namespace {
std::int32_t Failures = 0; std::int32_t Failures = 0;
@ -38,7 +36,10 @@ namespace {
return staged; return staged;
} }
// Swap in the variant carrying the extra member, kept beside the original. // Swap in the variant carrying the extra member. Comes from a file rather
// than a string literal here: the module scanner reads raw source, so an
// `export module Widget;` spelled inside this test would make the test look
// like an implementation unit of Widget.
void GrowWidget(const fs::path& staged) { void GrowWidget(const fs::path& staged) {
fs::copy_file(staged / "lib" / "Widget-grown.cppm.in", staged / "lib" / "Widget.cppm", fs::copy_options::overwrite_existing); fs::copy_file(staged / "lib" / "Widget-grown.cppm.in", staged / "lib" / "Widget.cppm", fs::copy_options::overwrite_existing);
// copy_file carries the source's mtime across, which would leave the // copy_file carries the source's mtime across, which would leave the
@ -59,9 +60,9 @@ namespace {
return lib; return lib;
} }
// Sources first, the dependency wired up afterwards — the ordering that // Scan first, wire the dependency up afterwards — the ordering that used to
// used to silently drop the staleness edge. // silently drop the staleness edge.
Configuration MakeConsumerListedBeforeDependencies(const fs::path& staged, Configuration* lib) { Configuration MakeConsumerScannedBeforeDependencies(const fs::path& staged, Configuration* lib) {
Configuration app; Configuration app;
app.path = staged; app.path = staged;
app.name = "widget-app"; app.name = "widget-app";
@ -93,31 +94,45 @@ namespace {
int main() { int main() {
{ {
// The build places the consumer's import on the library's module, // The scan leaves the unmatched import recorded rather than forgotten,
// although the library became a dependency after the consumer's // and ResolvePendingImports places it once the library is reachable.
// sources were listed.
fs::path staged = StageFixture(); fs::path staged = StageFixture();
std::unique_ptr<Configuration> lib = MakeLib(staged); std::unique_ptr<Configuration> lib = MakeLib(staged);
Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get()); Configuration app;
if (BuildOk(app, "consumer with the dependency wired up last")) { app.path = staged;
Check(app.implementations.size() == 1, "consumer has one implementation"); app.name = "widget-app";
if (app.implementations.size() == 1) { app.outputName = "widget-app";
const Implementation& impl = app.implementations[0]; app.target = HostTarget();
Check(impl.externalModuleDependencies.size() == 1, "the import of the library's module is one external module dep"); app.type = ConfigurationType::Executable;
if (impl.externalModuleDependencies.size() == 1) { std::array<fs::path, 0> ifaces = {};
Check(impl.externalModuleDependencies[0].first->name == "Widget", "external dep is the Widget module"); std::array<fs::path, 1> impls = { "main" };
Check(impl.externalModuleDependencies[0].second == lib->PcmDir() / "Widget.pcm", "external dep points at the library's BMI"); app.GetInterfacesAndImplementations(ifaces, impls);
}
} Check(app.implementations.size() == 1, "consumer has one implementation");
// A second build makes the units anew: the edge is there once. if (app.implementations.size() == 1) {
if (BuildOk(app, "consumer built again")) { const Implementation& impl = app.implementations[0];
Check(app.implementations.size() == 1 && app.implementations[0].externalModuleDependencies.size() == 1, "a second build has the one edge again"); Check(impl.externalModuleDependencies.empty(), "no external dep resolvable before dependencies are assigned");
Check(std::ranges::find(impl.pendingImports, "Widget") != impl.pendingImports.end(), "unresolved 'import Widget;' is recorded as pending");
app.dependencies = { lib.get() };
app.ResolvePendingImports();
Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports adds the external module dep");
if (impl.externalModuleDependencies.size() == 1) {
Check(impl.externalModuleDependencies[0].first->name == "Widget", "external dep is the Widget module");
Check(impl.externalModuleDependencies[0].second == lib->PcmDir() / "Widget.pcm", "external dep points at the library's BMI");
} }
Check(std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "resolved import is no longer pending");
// Idempotent: a second sweep must not duplicate the edge (Build
// runs one unconditionally, on top of whatever callers already did).
app.ResolvePendingImports();
Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent");
} }
} }
{ {
// AddTest is the reported path: it lists the test source, then hands // AddTest is the reported path: it scans the test source, then hands
// back a builder whose .Dependencies() names the library. // back a builder whose .Dependencies() names the library.
fs::path staged = StageFixture(); fs::path staged = StageFixture();
fs::create_directories(staged / "tests" / "Consumer"); fs::create_directories(staged / "tests" / "Consumer");
@ -131,31 +146,28 @@ int main() {
app.target = HostTarget(); app.target = HostTarget();
app.type = ConfigurationType::Executable; app.type = ConfigurationType::Executable;
// AddTest resolves tests/<name>/main against the cwd, which for a real // AddTest resolves tests/<name>/main against the cwd, which for a real
// run is the directory holding project.cpp, and the test's "./" path // run is the directory holding project.cpp. Stand in the staged project
// is read against it when the test is built. Stand in the staged // for the declaration so the fixture's test source is the one scanned.
// project for both, so the fixture's test source is the one listed
// and the test builds beside it.
fs::path restore = fs::current_path(); fs::path restore = fs::current_path();
fs::current_path(staged); fs::current_path(staged);
app.AddTest("Consumer").Dependencies({ lib.get() }); app.AddTest("Consumer").Dependencies({ lib.get() });
Check(app.tests.size() == 1, "one test declared");
if (app.tests.size() == 1 && BuildOk(app.tests[0].config, "test declared with AddTest")) {
Check(app.tests[0].config.implementations.size() == 1, "the test has one implementation");
if (app.tests[0].config.implementations.size() == 1) {
const Implementation& impl = app.tests[0].config.implementations[0];
Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() gives the test's import of the library module its edge");
}
}
fs::current_path(restore); fs::current_path(restore);
Check(app.tests.size() == 1, "one test declared");
if (app.tests.size() == 1 && app.tests[0].config.implementations.size() == 1) {
const Implementation& impl = app.tests[0].config.implementations[0];
Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() resolves the test's import of the library module");
Check(impl.pendingImports.empty() || std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "test's 'import Widget;' is no longer pending");
}
} }
{ {
// End to end: the guarantee under test is that a build of a consumer // End to end, and deliberately without calling ResolvePendingImports:
// declared in that order recompiles it, for consumers that never knew // the guarantee under test is that Build() closes the window on its own,
// the order mattered. // for consumers that never knew they had to ask.
fs::path staged = StageFixture(); fs::path staged = StageFixture();
std::unique_ptr<Configuration> lib = MakeLib(staged); std::unique_ptr<Configuration> lib = MakeLib(staged);
Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get()); Configuration app = MakeConsumerScannedBeforeDependencies(staged, lib.get());
fs::path binary = app.BinDir() / "widget-app"; fs::path binary = app.BinDir() / "widget-app";
fs::path consumerObject = ObjectPath(app, staged / "main.cpp"); fs::path consumerObject = ObjectPath(app, staged / "main.cpp");

View file

@ -54,6 +54,13 @@ namespace {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text; std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
} }
// One module or import declaration of a generated source. Put together
// here because the source scanner reads one spelled out in a string
// literal as a declaration of this file's own (issue #45).
std::string Declare(std::string_view keywords, std::string_view name) {
return std::format("{} {};\n", keywords, name);
}
// The C sources of one project, and as many C++ ones. // The C sources of one project, and as many C++ ones.
constexpr std::int32_t PerKind = 32; constexpr std::int32_t PerKind = 32;
// The units of one project: those sources, the module's primary // The units of one project: those sources, the module's primary
@ -76,10 +83,10 @@ namespace {
// Limit:High imports Limit:Low, the primary interface both, the // Limit:High imports Limit:Low, the primary interface both, the
// module's implementation unit the primary interface, and main.cpp // module's implementation unit the primary interface, and main.cpp
// the module. // the module.
Write(root / "Limit-Low.cppm", "export module Limit:Low;\nexport int Low() { return 1; }\n"); Write(root / "Limit-Low.cppm", std::format("{}export int Low() {{ return 1; }}\n", Declare("export module", "Limit:Low")));
Write(root / "Limit-High.cppm", "export module Limit:High;\nimport :Low;\nexport int High() { return Low() + 1; }\n"); Write(root / "Limit-High.cppm", std::format("{}{}export int High() {{ return Low() + 1; }}\n", Declare("export module", "Limit:High"), Declare("import", ":Low")));
Write(root / "Limit.cppm", "export module Limit;\nexport import :Low;\nexport import :High;\nexport int Top();\n"); Write(root / "Limit.cppm", std::format("{}{}{}export int Top();\n", Declare("export module", "Limit"), Declare("export import", ":Low"), Declare("export import", ":High")));
Write(root / "Limit-impl.cpp", "module Limit;\nint Top() { return High() + 1; }\n"); Write(root / "Limit-impl.cpp", std::format("{}int Top() {{ return High() + 1; }}\n", Declare("module", "Limit")));
std::string declarations; std::string declarations;
std::string sum; std::string sum;
@ -94,7 +101,7 @@ namespace {
declarations += std::format("extern \"C\" int c_unit_{0}(void);\nint cpp_unit_{0}();\n", i); declarations += std::format("extern \"C\" int c_unit_{0}(void);\nint cpp_unit_{0}();\n", i);
sum += std::format(" + c_unit_{0}() + cpp_unit_{0}()", i); sum += std::format(" + c_unit_{0}() + cpp_unit_{0}()", i);
} }
Write(root / "main.cpp", std::format("import std;\nimport Limit;\n{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", declarations, sum)); Write(root / "main.cpp", std::format("{}{}{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", Declare("import", "std"), Declare("import", "Limit"), declarations, sum));
std::array<fs::path, 3> interfaces = { "Limit", "Limit-Low", "Limit-High" }; std::array<fs::path, 3> interfaces = { "Limit", "Limit-Low", "Limit-High" };
cfg->GetInterfacesAndImplementations(interfaces, implementations); cfg->GetInterfacesAndImplementations(interfaces, implementations);

View file

@ -629,9 +629,7 @@ int main() {
Scratch s("ast"); Scratch s("ast");
s.Write("f", Source); s.Write("f", Source);
Configuration cfg = s.Config({"f"}); Configuration cfg = s.Config({"f"});
bool ran = false; cfg.AddAstLintRule("ast", [](LintContext& ctx) {
cfg.AddAstLintRule("ast", [&ran](LintContext& ctx) {
ran = true;
Check(ctx.AstAvailable(), std::format("ast: parse succeeded ({})", ctx.AstUnavailableReason())); Check(ctx.AstAvailable(), std::format("ast: parse succeeded ({})", ctx.AstUnavailableReason()));
std::span<const LintDecl> decls = ctx.Decls(); std::span<const LintDecl> decls = ctx.Decls();
Check(!decls.empty(), "ast: declarations found"); Check(!decls.empty(), "ast: declarations found");
@ -690,13 +688,7 @@ int main() {
Check(std::string_view(ctx.content).substr(count->begin, count->end - count->begin) == "int count", "ast: extent brackets exactly the declaration"); Check(std::string_view(ctx.content).substr(count->begin, count->end - count->begin) == "int count", "ast: extent brackets exactly the declaration");
} }
}); });
const LintSummary summary = RunLint(cfg, Mode(LintMode::Report)); RunLint(cfg, Mode(LintMode::Report));
// The driver runs a rule that reads the AST only on a file it could
// parse, so when the parse fails every check above goes untried and
// the run's error is all that is left to see. In crafter-build's
// Flatpak this file's <string> was not found, and the case passed
// (issue #46).
Check(ran && summary.errors == 0, "ast: the rule ran on the parsed file (why not is on stderr)");
} }
// A module interface unit. libclang reports `export namespace X { … }` as a // A module interface unit. libclang reports `export namespace X { … }` as a
@ -705,8 +697,9 @@ int main() {
// is five of this repo's own interfaces, 677 lines. Blanking the keyword is // is five of this repo's own interfaces, 677 lines. Blanking the keyword is
// byte-length preserving, so the lines reported here must match the file. // byte-length preserving, so the lines reported here must match the file.
// //
// The source lives in fixture/ExportNamespace.cppm.in, copied into the // The source lives in fixture/ExportNamespace.cppm.in rather than inline:
// scratch directory as Demo.cppm. // an `export module` spelled in this file's own text would be picked up by
// the build's module scanner as a real interface of this project.
{ {
Scratch s("ast-module"); Scratch s("ast-module");
fs::copy_file(fs::current_path() / "tests" / "Lint" / "fixture" / "ExportNamespace.cppm.in", s.dir / "Demo.cppm", fs::copy_options::overwrite_existing); fs::copy_file(fs::current_path() / "tests" / "Lint" / "fixture" / "ExportNamespace.cppm.in", s.dir / "Demo.cppm", fs::copy_options::overwrite_existing);
@ -718,9 +711,7 @@ int main() {
std::array<fs::path, 1> ifaces = { "Demo" }; std::array<fs::path, 1> ifaces = { "Demo" };
std::array<fs::path, 0> impls = {}; std::array<fs::path, 0> impls = {};
cfg.GetInterfacesAndImplementations(ifaces, impls); cfg.GetInterfacesAndImplementations(ifaces, impls);
bool ran = false; cfg.AddAstLintRule("ast-module", [](LintContext& ctx) {
cfg.AddAstLintRule("ast-module", [&ran](LintContext& ctx) {
ran = true;
Check(ctx.AstAvailable(), std::format("ast-module: parse succeeded ({})", ctx.AstUnavailableReason())); Check(ctx.AstAvailable(), std::format("ast-module: parse succeeded ({})", ctx.AstUnavailableReason()));
std::span<const LintDecl> decls = ctx.Decls(); std::span<const LintDecl> decls = ctx.Decls();
auto find = [&](LintDeclKind kind, std::string_view name) -> const LintDecl* { auto find = [&](LintDeclKind kind, std::string_view name) -> const LintDecl* {
@ -742,9 +733,7 @@ int main() {
Check(count != nullptr && count->line == 18, "ast-module: field line matches"); Check(count != nullptr && count->line == 18, "ast-module: field line matches");
Check(exported != nullptr && exported->line == 20, "ast-module: exported variable line matches"); Check(exported != nullptr && exported->line == 20, "ast-module: exported variable line matches");
}); });
const LintSummary summary = RunLint(cfg, Mode(LintMode::Report)); RunLint(cfg, Mode(LintMode::Report));
// As in the case above: the checks only count if the rule ran.
Check(ran && summary.errors == 0, "ast-module: the rule ran on the parsed file (why not is on stderr)");
} }
// An unavailable AST must fail the run, never look like a clean file. A // An unavailable AST must fail the run, never look like a clean file. A

View file

@ -1,235 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
extern "C" int setenv(const char* name, const char* value, int overwrite);
extern "C" int unsetenv(const char* name);
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
void Write(const fs::path& path, std::string_view content) {
std::ofstream file(path, std::ios::binary | std::ios::trunc);
file.write(content.data(), static_cast<std::streamsize>(content.size()));
}
// The file the toolchain's clang++ runs as when no other toolchain is
// staged: CRAFTER_BUILD_LLVM_DIR's, else the one on PATH, found in the
// directory the compiler itself names, so that a wrapper on PATH that
// runs the compiler is not taken for it. Empty when there is none.
fs::path RealCompiler() {
const char* llvm = std::getenv("CRAFTER_BUILD_LLVM_DIR");
const std::string compiler = llvm != nullptr && *llvm != '\0' ? (fs::path(llvm) / "bin" / "clang++").string() : std::string("clang++");
const auto version = RunCommandWithTimeout(std::format("{} --version", ShellQuote(compiler)), std::chrono::seconds(30));
constexpr std::string_view InstalledDirLine = "\nInstalledDir: ";
const std::size_t at = version.output.find(InstalledDirLine);
if (version.exitCode != 0 || at == std::string::npos) return {};
const std::size_t begin = at + InstalledDirLine.size();
std::string dir = version.output.substr(begin, version.output.find('\n', begin) - begin);
while (!dir.empty() && (dir.back() == '\r' || dir.back() == ' ')) dir.pop_back();
std::error_code ec;
const fs::path real = fs::canonical(fs::path(dir) / "clang++", ec);
return ec ? fs::path() : real;
}
// A link in `to` to every entry of `from` but the ones `except` names.
void LinkEntries(const fs::path& from, const fs::path& to, std::initializer_list<std::string_view> except) {
for (const fs::directory_entry& entry : fs::directory_iterator(from)) {
const std::string name = entry.path().filename().string();
if (!std::ranges::contains(except, name)) fs::create_symlink(entry.path(), to / name);
}
}
}
// lint parses a file with the headers of the compiler that builds it,
// wherever that compiler is installed. libclang was given the compile
// command without its compiler and named the driver it runs plain "clang",
// and in a build for the host whose compile command names no libc++
// directory, such as this test's, that driver, in no directory, looked for
// libc++ only in ../include from the working directory, in
// /usr/local/include and in /usr/include. Where none of them had one, as in
// the Flatpak, whose compiler keeps its libc++ in /app, a file of such a
// build that includes <algorithm> built, and every rule that reads its AST
// then failed on "'algorithm' file not found" (issue #46).
//
// Staged so that it fails without the fix on any host it can be staged on:
// an installation of the test's own, the toolchain's compiler copied into
// install/bin beside links to the rest of the real installation, with one
// header more in its c++/v1, crafter_issue46.h; and the toolchain the build
// is pointed at, whose bin/clang++ is a link to that copy and which has no
// include directory. The compiler runs from install/bin, so its compile finds
// both headers. A parse that looks for libc++ under /usr finds no
// crafter_issue46.h, and one that takes the compile command's own argv[0],
// llvm/bin/clang++, finds none either. The build's scan of the file, which
// clang-scan-deps makes with a driver of its own, is in the same place: given
// llvm/bin/clang++, it failed the build on crafter_issue46.h. A host whose
// compiler the copy cannot stand in for skips.
//
// A compile command whose last prefix flag is -no-canonical-prefixes has the
// compiler take itself to be where clangxx is as written, in llvm/bin, and
// read the clang++.cfg there, which adds a directory only it names. The second
// configuration's file includes a header from that directory, and the scan and
// the parse have to look from llvm/bin as the compile does: given
// install/bin/clang++, both failed on that header. Where the compile itself
// does not read that file, as where a user or system configuration directory
// hides it, the second configuration is left out, and the test skips unless
// the first failed.
int main() {
const fs::path root = fs::temp_directory_path() / "crafter-build-lint-compiler-headers";
std::error_code ec;
fs::remove_all(root, ec);
const fs::path compiler = RealCompiler();
if (compiler.empty()) {
std::println(std::cerr, "SKIP: no clang++ found to stage an installation from");
return 77;
}
const fs::path real = compiler.parent_path().parent_path();
if (!fs::is_directory(real / "include" / "c++" / "v1")) {
std::println(std::cerr, "SKIP: {} has no libc++ headers of its own in {}", compiler.string(), (real / "include" / "c++" / "v1").string());
return 77;
}
for (const std::string_view tool : { "llvm-ar", "clang-scan-deps" }) {
if (!fs::exists(compiler.parent_path() / tool)) {
std::println(std::cerr, "SKIP: no {} beside {} for the staged toolchain", tool, compiler.string());
return 77;
}
}
const fs::path install = root / "install";
const fs::path llvm = root / "llvm";
fs::create_directories(install / "bin");
fs::create_directories(install / "include" / "c++" / "v1");
fs::create_directories(llvm / "bin");
fs::create_directories(root / "project");
fs::create_directories(root / "cache");
// A copy, not a link: clang finds its installation from the file it runs
// as, and a link would lead it back to the real one. The rest is the real
// installation's, linked: the programs and configuration files beside the
// compiler, its shared libraries and its own headers wherever its build
// put them, lib/ or lib64/, and every header, with one more in c++/v1.
fs::copy_file(compiler, install / "bin" / "clang++");
fs::permissions(install / "bin" / "clang++", fs::perms::owner_all, fs::perm_options::add);
LinkEntries(compiler.parent_path(), install / "bin", {"clang++"});
LinkEntries(real, install, {"bin", "include"});
LinkEntries(real / "include", install / "include", {"c++"});
LinkEntries(real / "include" / "c++", install / "include" / "c++", {"v1"});
LinkEntries(real / "include" / "c++" / "v1", install / "include" / "c++" / "v1", {});
Write(install / "include" / "c++" / "v1" / "crafter_issue46.h", "#pragma once\ninline constexpr int CrafterIssue46 = 46;\n");
// The resource directory the copy works out from where it runs holds
// clang's own headers, stddef.h among them. A clang built to look for it
// somewhere those links do not reach, or a copy that does not start here,
// cannot stand in for the compiler.
const auto resource = RunCommandWithTimeout(std::format("{} -print-resource-dir", ShellQuote((install / "bin" / "clang++").string())), std::chrono::seconds(30));
std::string resourceDir = resource.output;
while (!resourceDir.empty() && (resourceDir.back() == '\n' || resourceDir.back() == '\r')) resourceDir.pop_back();
if (resource.exitCode != 0 || !fs::is_directory(fs::path(resourceDir) / "include")) {
std::println(std::cerr, "SKIP: the copy of {} in {} has no resource directory it can use: {}", compiler.string(), (install / "bin").string(), resourceDir);
return 77;
}
fs::create_symlink(install / "bin" / "clang++", llvm / "bin" / "clang++");
fs::create_symlink(compiler.parent_path() / "llvm-ar", llvm / "bin" / "llvm-ar");
fs::create_symlink(compiler.parent_path() / "clang-scan-deps", llvm / "bin" / "clang-scan-deps");
LinkEntries(real, llvm, {"bin", "include"});
// The toolchain is resolved once per process, so before anything asks
// for it; and the std module it builds goes to a cache of this run's own.
// A CRAFTER_BUILD_LIBCXX_DIR the suite runs with would have every compile
// take that libc++ in place of the staged one, and a
// CLANG_NO_DEFAULT_CONFIG would have clang read no configuration file,
// the one the second configuration rests on among them.
setenv("CRAFTER_BUILD_LLVM_DIR", llvm.c_str(), 1);
unsetenv("CRAFTER_BUILD_LIBCXX_DIR");
unsetenv("CLANG_NO_DEFAULT_CONFIG");
setenv("XDG_CACHE_HOME", (root / "cache").c_str(), 1);
Write(root / "project" / "unit.cpp", "#include <algorithm>\n#include <crafter_issue46.h>\n\nint Largest(int a, int b) {\n return std::max(a, b) + CrafterIssue46;\n}\n");
Configuration cfg;
cfg.path = root / "project";
cfg.name = "compiler-headers";
cfg.outputName = "compiler-headers";
cfg.target = HostTarget();
cfg.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 0> interfaces = {};
std::array<fs::path, 1> implementations = { "unit" };
cfg.GetInterfacesAndImplementations(interfaces, implementations);
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult result = Build(cfg, depResults, depMutex);
Check(result.result.empty(), std::format("the staged toolchain builds the file: {}", result.result));
}
std::vector<std::string> declared;
cfg.AddAstLintRule("reads-ast", [&declared](LintContext& ctx) {
for (const LintDecl& decl : ctx.Decls()) declared.push_back(decl.name);
});
const LintSummary summary = RunLint(cfg, {});
Check(summary.errors == 0, "lint parses the file the build compiled (why not is on stderr)");
Check(std::ranges::contains(declared, std::string("Largest")), "the rule that reads the AST sees the file's function");
// The same toolchain, with -no-canonical-prefixes in the command. The
// configuration file beside the link is written only now, once the first
// configuration is done with. The file includes no header of the C++
// standard library, as llvm/ has no include directory, only the one that
// configuration file's directory holds.
fs::create_directories(root / "cfg-include");
Write(root / "cfg-include" / "crafter_issue46_cfg.h", "#pragma once\ninline constexpr int CrafterIssue46Cfg = 46;\n");
Write(llvm / "bin" / "clang++.cfg", std::format("-isystem {}\n", (root / "cfg-include").string()));
Write(root / "project" / "written.cpp", "#include <crafter_issue46_cfg.h>\n\nint Written() {\n return CrafterIssue46Cfg;\n}\n");
// clang reads the first clang++.cfg it finds, looking in its user and
// system configuration directories before its own, and none where it
// finds a <triple>-clang++.cfg first, so the file beside the link can be
// hidden. The compile the case rests on, tried first, says whether it is.
const auto reads = RunCommandWithTimeout(std::format("{} -no-canonical-prefixes -fsyntax-only -x c++ {}", ShellQuote((llvm / "bin" / "clang++").string()), ShellQuote((root / "project" / "written.cpp").string())), std::chrono::seconds(30));
if (reads.exitCode != 0) {
std::println(std::cerr, "SKIP: the staged clang++ started with -no-canonical-prefixes does not read {}, which a user or system configuration directory can hide: {}", (llvm / "bin" / "clang++.cfg").string(), reads.output.substr(0, reads.output.find('\n')));
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 77;
}
Configuration written;
written.path = root / "project";
written.name = "compiler-headers-as-written";
written.outputName = "compiler-headers-as-written";
written.target = HostTarget();
written.type = ConfigurationType::LibraryStatic;
written.compileFlags.push_back("-no-canonical-prefixes");
std::array<fs::path, 1> writtenImplementations = { "written" };
written.GetInterfacesAndImplementations(interfaces, writtenImplementations);
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult result = Build(written, depResults, depMutex);
Check(result.result.empty(), std::format("with -no-canonical-prefixes, the staged toolchain builds the file: {}", result.result));
}
std::vector<std::string> writtenDeclared;
written.AddAstLintRule("reads-ast", [&writtenDeclared](LintContext& ctx) {
for (const LintDecl& decl : ctx.Decls()) writtenDeclared.push_back(decl.name);
});
const LintSummary writtenSummary = RunLint(written, {});
Check(writtenSummary.errors == 0, "with -no-canonical-prefixes, lint parses the file the build compiled (why not is on stderr)");
Check(std::ranges::contains(writtenDeclared, std::string("Written")), "with -no-canonical-prefixes, the rule that reads the AST sees the file's function");
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -83,7 +83,10 @@ int main() {
Write(mingw / "include" / "_mingw.h", ""); Write(mingw / "include" / "_mingw.h", "");
Write(mingw / "include" / "crafter_probe_error.h", "#error stopped in a mingw-w64 header\n"); Write(mingw / "include" / "crafter_probe_error.h", "#error stopped in a mingw-w64 header\n");
Write(mingw / "include" / "c++" / "15.1.0" / "memory", ""); Write(mingw / "include" / "c++" / "15.1.0" / "memory", "");
Write(mingw / "include" / "c++" / "15.1.0" / "bits" / "std.cc", "export module std;\n"); // Through std::format because the build's import scanner reads string
// literals as code: one holding "module std;" made this file a unit of a
// module std, and the test did not build.
Write(mingw / "include" / "c++" / "15.1.0" / "bits" / "std.cc", std::format("export module {};\n", "std"));
Write(mingw / "lib" / "libstdc++.modules.json", R"({"version": 1, "modules": [{"logical-name": "std", "source-path": "../include/c++/15.1.0/bits/std.cc", "is-std-library": true}]})"); Write(mingw / "lib" / "libstdc++.modules.json", R"({"version": 1, "modules": [{"logical-name": "std", "source-path": "../include/c++/15.1.0/bits/std.cc", "is-std-library": true}]})");
{ {

View file

@ -21,16 +21,8 @@ int main() {
std::array<fs::path, 1> impls = { "main" }; std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls); cfg.GetInterfacesAndImplementations(ifaces, impls);
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults; // Implementation should have picked up the import Greeter; through the
std::mutex depMutex; // interface list resolution in GetInterfacesAndImplementations.
BuildResult r = Build(cfg, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
// The build read main.cpp's import of Greeter and placed it on the
// module among the configuration's own interfaces.
if (cfg.implementations.size() != 1) { if (cfg.implementations.size() != 1) {
std::println(std::cerr, "expected 1 implementation, got {}", cfg.implementations.size()); std::println(std::cerr, "expected 1 implementation, got {}", cfg.implementations.size());
return 1; return 1;
@ -44,6 +36,14 @@ int main() {
return 1; return 1;
} }
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(cfg, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
fs::path bin = cfg.BinDir() / "greeter-app"; fs::path bin = cfg.BinDir() / "greeter-app";
if (!fs::exists(bin)) { if (!fs::exists(bin)) {
std::println(std::cerr, "binary not produced at {}", bin.string()); std::println(std::cerr, "binary not produced at {}", bin.string());

View file

@ -34,8 +34,6 @@ namespace {
// 0 -> Pass // 0 -> Pass
// 77 -> Skipped (autoconf convention) // 77 -> Skipped (autoconf convention)
// anything else -> Fail // anything else -> Fail
// and that a binary whose path has an '=' in it runs, with a TMPDIR as
// RunTests gives it.
int main() { int main() {
fs::path dir = fs::temp_directory_path() / "crafter-build-run-single-test"; fs::path dir = fs::temp_directory_path() / "crafter-build-run-single-test";
std::error_code ec; std::error_code ec;
@ -78,23 +76,6 @@ int main() {
Check(r.outcome == TestOutcome::Pass, "Cmd-prefixed exit 0 -> Pass"); Check(r.outcome == TestOutcome::Pass, "Cmd-prefixed exit 0 -> Pass");
} }
// A test whose binary's path has an '=' in it, given a TMPDIR, as
// RunTests gives every test one: env, which sets the TMPDIR, took that
// path for an assignment and, with no command left, exited 0, a pass
// for a test that never ran.
{
const fs::path equals = dir / "a=b";
fs::create_directories(equals);
fs::create_directories(dir / "tmpdir");
const fs::path marker = dir / "a=b-ran";
const fs::path script = equals / "marker.sh";
std::ofstream(script) << std::format("#!/bin/sh\necho ran > '{}'\nexit 3\n", marker.string());
fs::permissions(script, fs::perms::owner_all, fs::perm_options::replace);
TestResult r = RunSingleTest(t, script, std::chrono::seconds(5), std::nullopt, dir / "tmpdir");
Check(fs::exists(marker), "a test whose binary's path has an '=' in it runs");
Check(r.outcome == TestOutcome::Fail && r.exitCode == 3, std::format("and its exit decides the outcome, got {}", r.exitCode));
}
fs::remove_all(dir, ec); fs::remove_all(dir, ec);
if (Failures > 0) { if (Failures > 0) {

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Extra;
export int ExtraValue() {
return 40;
}

View file

@ -1,17 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Imports Extra when the build defines CRAFTER_TEST_EXTRA, which the test
// does after it lists this source.
#ifdef CRAFTER_TEST_EXTRA
import Extra;
#endif
// Exits with 40 when CRAFTER_TEST_EXTRA is defined, 2 when it is not.
int main() {
#ifdef CRAFTER_TEST_EXTRA
return ExtraValue();
#else
return 2;
#endif
}

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include "not-there.h"
int main() {
return 0;
}

View file

@ -1,10 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// An implementation partition, listed as an interface unit of the
// configuration, as a partition another unit of the module imports has to be.
module X:Impl;
int G() {
return 7;
}

View file

@ -1,9 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module X;
import :Impl;
int F() {
return G();
}

View file

@ -1,6 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module X;
export int F();

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import X;
int main() {
return F() == 7 ? 0 : 1;
}

View file

@ -1,9 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// No unit of any module: what reads as a module declaration below is the
// text of a string literal.
int QuotedLength() {
constexpr char text[] = "export module std;";
return static_cast<int>(sizeof(text)) - 1;
}

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
int QuotedLength();
int main() {
return QuotedLength() == 18 ? 0 : 1;
}

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Extra;
export int ExtraValue() {
return 40;
}

View file

@ -1,19 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// WITH_EXTRA comes from the switch.h of the library the app is built on:
// found through its directory, which is on the include path of what is
// built on it.
#include <switch.h>
#if WITH_EXTRA
import Extra;
#endif
// Exits with 40 when WITH_EXTRA is 1, 2 when it is 0.
int main() {
#if WITH_EXTRA
return ExtraValue();
#else
return 2;
#endif
}

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Off;
export int OffValue() {
return 0;
}

View file

@ -1,5 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#pragma once
#define WITH_EXTRA 0

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module On;
export int OnValue() {
return 1;
}

View file

@ -1,6 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Copied over switch.h by the test, mid-run.
#pragma once
#define WITH_EXTRA 0

View file

@ -1,5 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#pragma once
#define WITH_EXTRA 1

View file

@ -1,8 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Base;
export int BaseValue() {
return 1;
}

View file

@ -1,11 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Commented;
/*
import Spaced;
*/
export int CommentedValue() {
return 3;
}

View file

@ -1,11 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Disabled;
#if 0
import Spaced;
#endif
export int DisabledValue() {
return 4;
}

View file

@ -1,10 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Spaced;
// Two spaces after `import`, as a formatter that lines up columns writes it.
import Base;
export int SpacedValue() {
return BaseValue() + 1;
}

View file

@ -1,12 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// A space before the semicolon.
import Spaced ;
import Commented;
import Disabled;
// Exits 0 when each module gives what it should.
int main() {
return SpacedValue() + CommentedValue() + DisabledValue() == 9 ? 0 : 1;
}

View file

@ -1,288 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// A build reads what a source declares and imports as the compiler reads
// it: clang-scan-deps preprocesses the source with the command it is
// compiled with. The build used to search the text with regular
// expressions after deleting the comments that fit on one line (issue #45),
// so it took a module declaration in a string literal for a real one,
// followed an import in a comment that spans lines or under `#if 0`, missed
// `import X;` and `import X ;`, and read every #if as true. A source that
// held "export module std;" in a string became a unit of a module std and
// stopped the build; an import it missed was an edge missing, so a unit
// could be compiled before the BMI it imports, or kept when that changed.
//
// Each case builds a copy of a fixture and checks what the build read, by
// the modules and units it gave the configuration, and runs the program
// where what it does depends on that:
// text an import in a comment that spans lines, under #if 0, after
// two spaces and before a space, three of the issue's four
// inputs; a build with nothing changed; a kept scan that cannot
// be read
// quoted a module declaration in a string literal, the fourth
// partition
// a .cppm that declares an implementation partition, which
// the build refused as declaring no module
// define an #ifdef on a define set after the source is listed
// switch an #if on a header of a dependency: the header edited, and the
// dependency swapped for another
// missing an #include of a header that is not there
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
const fs::path Scratch = fs::temp_directory_path() / "crafter-build-source-scan";
// A copy of the fixture `name`, made anew: the switch case edits it.
fs::path Stage(std::string_view name) {
const fs::path staged = Scratch / name;
fs::remove_all(staged);
fs::create_directories(Scratch);
fs::copy(fs::current_path() / "tests" / "SourceScan" / "fixture" / name, staged, fs::copy_options::recursive);
return staged;
}
Configuration Make(const fs::path& dir, std::string_view name, ConfigurationType type, std::vector<fs::path> interfaces, std::vector<fs::path> implementations) {
Configuration cfg;
cfg.path = dir;
cfg.name = std::string(name);
cfg.outputName = std::string(name);
cfg.target = HostTarget();
cfg.type = type;
cfg.GetInterfacesAndImplementations(interfaces, implementations);
return cfg;
}
// Build()'s error, in a pass of its own.
std::string BuildError(Configuration& cfg) {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(cfg, depResults, depMutex).result;
}
// The exit code of the program `cfg` built.
std::int32_t Run(const Configuration& cfg) {
const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30));
return run.crashed || run.timedOut ? -1 : run.exitCode;
}
const Module* Named(const Configuration& cfg, std::string_view name) {
for (const std::unique_ptr<Module>& module : cfg.interfaces) {
if (module->name == name) return module.get();
}
return nullptr;
}
// The names of the modules a unit's import edges lead to, local and
// external alike, in order.
template <typename Unit>
std::vector<std::string> Imports(const Unit& unit) {
std::vector<std::string> names;
for (const Module* imported : unit.moduleDependencies) names.push_back(imported->name);
for (const auto& [imported, bmi] : unit.externalModuleDependencies) names.push_back(imported->name);
return names;
}
std::string Listed(const std::vector<std::string>& names) {
return names.empty() ? "nothing" : std::format("{}", names);
}
// The implementation unit of `cfg` whose source is `source`.
const Implementation* UnitOf(const Configuration& cfg, const fs::path& source) {
fs::path stem = source;
stem.replace_extension();
for (const Implementation& unit : cfg.implementations) {
if (unit.path == stem) return &unit;
}
return nullptr;
}
// When the scan the build keeps of `source` was written.
std::optional<fs::file_time_type> ScanTime(const Configuration& cfg, const fs::path& source) {
std::error_code ec;
const fs::file_time_type written = fs::last_write_time(cfg.BuildDir() / "scans" / std::format("{}.json", source.string()), ec);
if (ec) return std::nullopt;
return written;
}
// Copies `from` over `to` and dates it now: copy_file keeps the time of
// `from`, which would leave the edit older than what was built before.
void Replace(const fs::path& from, const fs::path& to) {
fs::copy_file(from, to, fs::copy_options::overwrite_existing);
fs::last_write_time(to, fs::file_time_type::clock::now());
}
void TextCase() {
const fs::path dir = Stage("text");
Configuration cfg = Make(dir, "scan-text", ConfigurationType::Executable, { "Base", "Spaced", "Commented", "Disabled" }, { "main" });
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("text: the build succeeds: {}", error));
if (!error.empty()) return;
Check(Run(cfg) == 0, "text: the program gets what each module gives");
const Module* spaced = Named(cfg, "Spaced");
const Module* commented = Named(cfg, "Commented");
const Module* disabled = Named(cfg, "Disabled");
Check(spaced != nullptr && commented != nullptr && disabled != nullptr && Named(cfg, "Base") != nullptr, "text: the four interface units are four modules");
if (spaced == nullptr || commented == nullptr || disabled == nullptr) return;
Check(Imports(*spaced) == std::vector<std::string>{ "Base" }, std::format("text: `import Base;` is an import of Base, got {}", Listed(Imports(*spaced))));
Check(Imports(*commented).empty(), std::format("text: an import in a comment that spans lines is none, got {}", Listed(Imports(*commented))));
Check(Imports(*disabled).empty(), std::format("text: an import under #if 0 is none, got {}", Listed(Imports(*disabled))));
const Implementation* main = UnitOf(cfg, dir / "main.cpp");
Check(main != nullptr && Imports(*main) == std::vector<std::string>{ "Spaced", "Commented", "Disabled" }, std::format("text: `import Spaced ;` is an import of Spaced, beside the two others, got {}", main == nullptr ? "no unit" : Listed(Imports(*main))));
// Built again with nothing changed: every scan is read as it was
// kept, and none is taken again.
const std::vector<fs::path> sources = { "Base.cppm", "Spaced.cppm", "Commented.cppm", "Disabled.cppm", "main.cpp" };
std::vector<std::optional<fs::file_time_type>> before;
for (const fs::path& source : sources) before.push_back(ScanTime(cfg, source));
Check(std::ranges::none_of(before, [](const std::optional<fs::file_time_type>& t) { return !t; }), "text: every source has its scan in the build directory");
const std::string again = BuildError(cfg);
Check(again.empty(), std::format("text: the build with nothing changed succeeds: {}", again));
for (std::size_t i = 0; i < sources.size(); ++i) {
Check(ScanTime(cfg, sources[i]) == before[i], std::format("text: {} is not scanned again when nothing changed", sources[i].string()));
}
// The build made the modules anew, from the scans it kept.
const Module* kept = Named(cfg, "Spaced");
Check(kept != nullptr && Imports(*kept) == std::vector<std::string>{ "Base" }, "text: the kept scan gives the import of Base again");
// A kept scan that cannot be read is taken again.
std::ofstream(cfg.BuildDir() / "scans" / "Spaced.cppm.json", std::ios::binary | std::ios::trunc) << "not what a build writes";
const std::string unreadable = BuildError(cfg);
Check(unreadable.empty(), std::format("text: a scan that cannot be read is taken again, and the build succeeds: {}", unreadable));
if (const Module* rescanned = Named(cfg, "Spaced")) Check(Imports(*rescanned) == std::vector<std::string>{ "Base" }, "text: the scan taken again gives the import of Base");
}
void QuotedCase() {
const fs::path dir = Stage("quoted");
Configuration cfg = Make(dir, "scan-quoted", ConfigurationType::Executable, {}, { "Quoted", "main" });
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("quoted: a module declaration in a string literal is none, and the build succeeds: {}", error));
if (!error.empty()) return;
Check(cfg.interfaces.empty(), "quoted: the configuration has no module");
const Implementation* quoted = UnitOf(cfg, dir / "Quoted.cpp");
Check(quoted != nullptr && Imports(*quoted).empty(), "quoted: Quoted.cpp imports nothing, a module std least of all");
Check(Run(cfg) == 0, "quoted: the program holds the string");
}
void PartitionCase() {
const fs::path dir = Stage("partition");
Configuration cfg = Make(dir, "scan-partition", ConfigurationType::Executable, { "X", "X-Impl" }, { "X", "main" });
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("partition: an implementation partition listed as an interface unit builds: {}", error));
if (!error.empty()) return;
const Module* x = Named(cfg, "X");
Check(x != nullptr && x->partitions.size() == 1 && x->partitions[0]->name == "Impl", "partition: it is the partition Impl of module X");
const Implementation* unit = UnitOf(cfg, dir / "X.cpp");
Check(unit != nullptr && unit->partitionDependencies.size() == 1 && unit->partitionDependencies[0]->name == "Impl", "partition: X.cpp, which imports :Impl, has its edge to it");
Check(Run(cfg) == 0, "partition: the program gets G() through F()");
}
void DefineCase() {
const fs::path dir = Stage("define");
for (const bool defined : { false, true }) {
Configuration cfg = Make(dir, "scan-define", ConfigurationType::Executable, { "Extra" }, { "main" });
// After the source is listed: the build reads it with the
// command the configuration has by then.
if (defined) cfg.defines.push_back({ "CRAFTER_TEST_EXTRA", "" });
const std::string label = defined ? "with CRAFTER_TEST_EXTRA" : "without CRAFTER_TEST_EXTRA";
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("define, {}: the build succeeds: {}", label, error));
if (!error.empty()) continue;
const Implementation* main = UnitOf(cfg, dir / "main.cpp");
const std::vector<std::string> expected = defined ? std::vector<std::string>{ "Extra" } : std::vector<std::string>{};
Check(main != nullptr && Imports(*main) == expected, std::format("define, {}: main.cpp imports {}, got {}", label, Listed(expected), main == nullptr ? "no unit" : Listed(Imports(*main))));
Check(Run(cfg) == (defined ? 40 : 2), std::format("define, {}: the program is built as the define says", label));
}
}
void SwitchCase() {
const fs::path dir = Stage("switch");
Configuration on = Make(dir / "on", "scan-on", ConfigurationType::LibraryStatic, { "On" }, {});
Configuration off = Make(dir / "off", "scan-off", ConfigurationType::LibraryStatic, { "Off" }, {});
Configuration app = Make(dir / "app", "scan-switch", ConfigurationType::Executable, { "Extra" }, { "main" });
app.dependencies = { &on };
const fs::path source = dir / "app" / "main.cpp";
const auto imports = [&] {
const Implementation* main = UnitOf(app, source);
return main == nullptr ? std::vector<std::string>{ "no unit" } : Imports(*main);
};
std::string error = BuildError(app);
Check(error.empty(), std::format("switch, on: the build succeeds: {}", error));
if (!error.empty()) return;
Check(imports() == std::vector<std::string>{ "Extra" }, std::format("switch, on: WITH_EXTRA 1 imports Extra, got {}", Listed(imports())));
Check(Run(app) == 40, "switch, on: the program imports Extra");
// The header is edited: the scan that read it is taken again.
Replace(dir / "on" / "switch-off.h.in", dir / "on" / "switch.h");
const std::optional<fs::file_time_type> scannedOn = ScanTime(app, "main.cpp");
error = BuildError(app);
Check(error.empty(), std::format("switch, header edited: the build succeeds: {}", error));
if (!error.empty()) return;
Check(ScanTime(app, "main.cpp") != scannedOn, "switch, header edited: main.cpp is scanned again");
Check(imports().empty(), std::format("switch, header edited: WITH_EXTRA 0 imports nothing, got {}", Listed(imports())));
Check(Run(app) == 2, "switch, header edited: the program is compiled again without Extra");
// Back to 1, then built on the other library, whose switch.h has 0.
// Nothing the scan read has changed, but the command it read them
// with has: its include path names the other library. Checked by
// what the build read alone: this is about the scan.
Replace(fs::current_path() / "tests" / "SourceScan" / "fixture" / "switch" / "on" / "switch.h", dir / "on" / "switch.h");
error = BuildError(app);
Check(error.empty() && imports() == std::vector<std::string>{ "Extra" }, std::format("switch, header back to 1: main.cpp imports Extra again, got {} ({})", Listed(imports()), error));
app.dependencies = { &off };
const std::optional<fs::file_time_type> scannedWithOn = ScanTime(app, "main.cpp");
error = BuildError(app);
Check(error.empty(), std::format("switch, off: the build succeeds: {}", error));
if (!error.empty()) return;
Check(ScanTime(app, "main.cpp") != scannedWithOn, "switch, off: main.cpp is scanned again for the command that changed");
Check(imports().empty(), std::format("switch, off: the other library's WITH_EXTRA 0 imports nothing, got {}", Listed(imports())));
}
void MissingCase() {
const fs::path dir = Stage("missing");
Configuration cfg = Make(dir, "scan-missing", ConfigurationType::Executable, {}, { "main" });
const std::string error = BuildError(cfg);
Check(error.contains("not-there.h"), std::format("missing: the build fails naming the header it cannot find, got: {}", error));
Check(!fs::exists(ObjectPath(cfg, dir / "main.cpp")), "missing: nothing is compiled of a source that cannot be read");
}
// Runs one case: an exception it lets out fails that case, and the
// others still run.
void RunCase(std::string_view name, const std::function<void()>& run) {
try {
run();
} catch (const std::exception& e) {
Check(false, std::format("{}: threw {}", name, e.what()));
}
}
}
int main() {
RunCase("text", TextCase);
RunCase("quoted", QuotedCase);
RunCase("partition", PartitionCase);
RunCase("define", DefineCase);
RunCase("switch", SwitchCase);
RunCase("missing", MissingCase);
std::error_code ec;
fs::remove_all(Scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -7,9 +7,9 @@ namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
// Build a tiny module-only static library and confirm libgreet.a lands in // Build a tiny module-only static library and confirm libgreet.a lands in
// BinDir(). Exercises ConfigurationType::LibraryStatic, the module a build // BinDir(). Exercises ConfigurationType::LibraryStatic, interface module
// reads in a source GetInterfacesAndImplementations lists, and the // parsing via GetInterfacesAndImplementations, and the ar/llvm-lib archive
// ar/llvm-lib archive step in Crafter.Build-Clang.cpp. // step in Crafter.Build-Clang.cpp.
int main() { int main() {
Configuration cfg; Configuration cfg;
cfg.path = fs::current_path() / "tests" / "StaticLib" / "fixture"; cfg.path = fs::current_path() / "tests" / "StaticLib" / "fixture";
@ -22,14 +22,6 @@ int main() {
std::array<fs::path, 0> impls = {}; std::array<fs::path, 0> impls = {};
cfg.GetInterfacesAndImplementations(ifaces, impls); cfg.GetInterfacesAndImplementations(ifaces, impls);
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(cfg, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
if (cfg.interfaces.size() != 1) { if (cfg.interfaces.size() != 1) {
std::println(std::cerr, "expected 1 interface, got {}", cfg.interfaces.size()); std::println(std::cerr, "expected 1 interface, got {}", cfg.interfaces.size());
return 1; return 1;
@ -39,6 +31,14 @@ int main() {
return 1; return 1;
} }
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(cfg, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
fs::path archive = cfg.BinDir() / "libgreet.a"; fs::path archive = cfg.BinDir() / "libgreet.a";
if (!fs::exists(archive)) { if (!fs::exists(archive)) {
std::println(std::cerr, "archive not produced at {}", archive.string()); std::println(std::cerr, "archive not produced at {}", archive.string());

View file

@ -1,7 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only // SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std; import std;
import Crafter.Build; import Crafter.Build;
namespace fs = std::filesystem; namespace fs = std::filesystem;
@ -53,11 +52,6 @@ int main() {
std::error_code ec; std::error_code ec;
fs::remove_all(scratch, ec); fs::remove_all(scratch, ec);
fs::create_directories(scratch); fs::create_directories(scratch);
// The cache the build below makes its std module's directory in, which
// is keyed on the sysroot's path: one under the temp directory, which
// is a new one every run of the suite, so the real cache would keep one
// more directory each run. Set while this is the only thread.
setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1);
{ {
StageHeaders(scratch / "headers", 230102); StageHeaders(scratch / "headers", 230102);
@ -132,8 +126,8 @@ int main() {
{ {
// End to end with the real toolchain: a sysroot on a libc++ release // End to end with the real toolchain: a sysroot on a libc++ release
// that does not exist fails the build with the one-line explanation // that does not exist fails the build with the one-line explanation
// before clang is run, for the host's target. The std module's cache // before clang is run. The target is the host's so the std PCM cache
// directory is made in the scratch cache (above). // directory is the one every other test already uses.
const Toolchain& real = GetToolchain(); const Toolchain& real = GetToolchain();
Check(real.libcxxVersion != 0, "the running toolchain's libc++ release is read from its headers"); Check(real.libcxxVersion != 0, "the running toolchain's libc++ release is read from its headers");

View file

@ -1,30 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
namespace fs = std::filesystem;
// Writes the TMPDIR it was given and the directory fs::temp_directory_path()
// names to the file its first argument names, leaves a file in that
// directory, and exits with the status its second argument gives. With a
// third, `ran-long`, it first dates the run's directory, which holds its own,
// and every other crafter-build-tests-* directory beside that one two minutes
// back, as a test that ran that long leaves them; only when its own is in a
// run's directory.
int main(int argc, char* argv[]) {
if (argc != 3 && argc != 4) return 2;
const bool ranLong = argc == 4;
if (ranLong && std::string_view(argv[3]) != "ran-long") return 2;
const char* given = std::getenv("TMPDIR");
const fs::path temporary = fs::temp_directory_path();
std::ofstream(fs::path(argv[1])) << std::format("{}\n{}\n", given != nullptr ? given : "<unset>", temporary.string());
std::ofstream(temporary / "left-behind") << "staged\n";
if (ranLong && temporary.parent_path().filename().string().starts_with("crafter-build-tests-")) {
const auto then = fs::file_time_type::clock::now() - std::chrono::minutes(2);
std::error_code ec;
for (const fs::directory_entry& entry : fs::directory_iterator(temporary.parent_path().parent_path(), ec)) {
if (entry.path().filename().string().starts_with("crafter-build-tests-")) fs::last_write_time(entry.path(), then, ec);
}
}
return std::stoi(argv[2]);
}

View file

@ -1,247 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// Each test runs with TMPDIR naming a directory of its own, <run>/<name>, in
// a directory RunTests makes for the run in the temp directory. Tests stage
// their fixtures under fixed names in fs::temp_directory_path(), and two runs
// at once used to share them, as every run does the machine's /tmp, and in
// crafter-build's Flatpak every sandbox the app's: one run's staged copy was
// written over or removed by the other's, and its test failed. The second
// test of one name in a run, from another configuration, gets <name>-2. What
// a passing test leaves is removed when it ends, and so is the run's
// directory once every test passed; what a failing test leaves is kept, its
// output says where, and the run's directory with it, which a later run
// removes once a minute has passed since the run ended, and one that comes
// sooner leaves alone. That holds when the failing test ran for minutes, so
// that the run's directory had last changed long before the run ended:
// going by that change alone, the next run removed it at once. And one
// directory serves the run, every pass of its sweep over targets: a pass
// that made one of its own made it once the passes before had let go of
// theirs, and making it removed any of those that had not changed for a
// minute, a kept one after a pass that long among them. It is kept the
// moment a test keeps something in it, so that a later pass that throws, as
// one for a target whose runner is given wrong does, does not take it with
// it. Two failing tests of one name each have a log of their own, named as
// their TMPDIRs are, which says where what each left is kept.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The two lines the probe recorded: the TMPDIR it was given, and the
// directory fs::temp_directory_path() named in it.
std::pair<std::string, std::string> Recorded(const fs::path& file) {
std::ifstream in(file);
std::pair<std::string, std::string> lines;
std::getline(in, lines.first);
std::getline(in, lines.second);
return lines;
}
// A test of tests/probe/main.cpp, by the name given, with the arguments
// given, which that file describes.
Test& AddProbe(Configuration& owner, std::string_view name, std::vector<std::string> args, bool second = false) {
Test test;
Configuration& c = test.config;
c.path = "./";
c.name = name;
c.outputName = name;
c.target = HostTarget();
c.type = ConfigurationType::Executable;
// Compiled otherwise than the first configuration's test of the same
// name, so that the two are not built into one directory, which the
// run refuses.
if (second) c.defines.push_back({"SECOND_PROBE", ""});
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "tests/probe/main" };
c.GetInterfacesAndImplementations(ifaces, impls);
test.args = std::move(args);
owner.tests.push_back(std::move(test));
return owner.tests.back();
}
const TestResult* Find(const TestSummary& summary, std::string_view name) {
for (const TestResult& result : summary.results) {
if (result.name == name) return &result;
}
return nullptr;
}
}
int main() {
// The runs below make their directories in a temp directory of this
// test's own, which TMPDIR names from here on, set while this is the
// only thread. What the test dates and removes is then in a directory it
// made, even where RunTests gives a probe no TMPDIR and the probe
// reports this test's own.
const fs::path staged = fs::temp_directory_path() / "crafter-build-test-temporary-directory";
std::error_code ec;
fs::remove_all(staged, ec);
const fs::path records = staged / "records";
const fs::path temp = staged / "runs";
fs::create_directories(records);
fs::create_directories(temp);
setenv("TMPDIR", temp.c_str(), 1);
// As a directory a run let go of looks, made a moment ago, so that the
// run's first look at the temp directory leaves it, and dated two
// minutes back by the failing probe during the first pass: one more pass
// that made a directory of its own would remove it, as it would a kept
// one after a pass of a minute.
const fs::path planted = temp / "crafter-build-tests-planted";
fs::create_directories(planted);
// AddProbe resolves tests/probe/main.cpp against the working directory,
// and the tests' outputs land in the fixture's own bin/ and build/.
fs::current_path(fs::current_path() / "tests" / "TestTemporaryDirectory" / "fixture");
fs::remove_all("bin", ec);
fs::remove_all("build", ec);
// One test at a time, in the order declared, so that the failing test
// is the last of the host's pass to make or remove anything in the run's
// directory: its own directory there, just before it starts. It then
// dates the run's directory two minutes back before it fails, as a test
// that ran that long leaves it. A test for another target makes a second
// pass, after the host's: the host's own triple, without its vendor,
// with x32 after it, x86_64-linux-gnux32 on an x86_64 glibc host, which
// is never the host's and sorts right after it. It is skipped before it
// is built.
const std::string otherTarget = std::format("{}x32", NormalizeTarget(HostTarget()));
Configuration first;
first.path = "./";
first.name = "first";
first.outputName = "first";
first.target = HostTarget();
AddProbe(first, "probe", { (records / "first-probe").string(), "0" });
Configuration second;
second.path = "./";
second.name = "second";
second.outputName = "second";
second.target = HostTarget();
AddProbe(second, "probe", { (records / "second-probe").string(), "0" }, true);
AddProbe(second, "failing", { (records / "failing").string(), "1", "ran-long" });
Test& elsewhere = AddProbe(second, "elsewhere", { (records / "elsewhere").string(), "0" });
elsewhere.config.target = otherTarget;
elsewhere.requires_ = { "tool:crafter-build-no-such-tool" };
std::array<Configuration*, 2> both = { &first, &second };
RunTestsOptions serial;
serial.jobs = 1;
const TestSummary run = RunTests(both, serial);
Check(run.passed == 2 && run.failed == 1 && run.skipped == 1, std::format("the run has two passes, one failure and one skip, got {}, {} and {}", run.passed, run.failed, run.skipped));
Check(fs::is_directory(planted, ec), "the pass for the other target makes no directory of its own, which would have removed what the first pass left a minute old");
const auto [firstGiven, firstSeen] = Recorded(records / "first-probe");
const auto [secondGiven, secondSeen] = Recorded(records / "second-probe");
const auto [failingGiven, failingSeen] = Recorded(records / "failing");
const fs::path directory = fs::path(firstGiven).parent_path();
Check(firstGiven == firstSeen && secondGiven == secondSeen && failingGiven == failingSeen,
std::format("each test's fs::temp_directory_path() is the TMPDIR it was given: {} {} {}", firstSeen, secondSeen, failingSeen));
const bool madeForRun = fs::equivalent(directory.parent_path(), temp, ec) && directory.filename().string().starts_with("crafter-build-tests-");
Check(madeForRun, std::format("the run's directory is one made for it in the temp directory: {}", directory.string()));
Check(fs::path(firstGiven) == directory / "probe", std::format("a test's TMPDIR is named after it: {}", firstGiven));
Check(fs::path(secondGiven) == directory / "probe-2", std::format("the second test of that name gets probe-2: {}", secondGiven));
Check(fs::path(failingGiven) == directory / "failing", std::format("and every test of the run gets one in the same run directory: {}", failingGiven));
Check(!fs::exists(directory / "probe") && !fs::exists(directory / "probe-2"), "what a passing test left is removed");
Check(fs::exists(directory / "failing" / "left-behind"), "what a failing test left is kept");
const TestResult* failed = Find(run, "failing");
Check(failed != nullptr && failed->output.contains((directory / "failing").string()), "and the failing test's output says where");
const std::string log = [] {
std::ifstream in(fs::path("build") / "test-logs" / "failing.log");
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}();
Check(log.contains((directory / "failing").string()), "and so does its log");
// A run straight after leaves the failed run's directory alone, though
// the failing test dated it two minutes back; one that comes when it has
// not changed for a minute removes it.
RunTestsOptions passing;
passing.globs = { "probe" };
std::array<Configuration*, 1> justFirst = { &first };
const TestSummary again = RunTests(justFirst, passing);
Check(again.passed == 1 && again.failed == 0, std::format("the probe passes again, got {} passed, {} failed", again.passed, again.failed));
const fs::path againDirectory = fs::path(Recorded(records / "first-probe").first).parent_path();
Check(againDirectory != directory && fs::equivalent(againDirectory.parent_path(), temp, ec), std::format("a second run gets a directory of its own: {}", againDirectory.string()));
Check(!fs::exists(againDirectory), "and removes it when every test passed");
Check(fs::exists(directory / "failing" / "left-behind"), "the failed run's directory outlives a run that comes at once, though its last test ran long");
// Only the failed run's directory is dated, and not a directory a probe
// reported that is not one: that check has failed already.
if (madeForRun) {
fs::last_write_time(directory, fs::file_time_type::clock::now() - std::chrono::minutes(2), ec);
const TestSummary later = RunTests(justFirst, passing);
Check(later.passed == 1, "the probe passes a third time");
Check(!fs::exists(directory), "a later run removes the failed run's directory once it has not changed for a minute");
}
// A run whose later pass throws, as one does where
// CRAFTER_BUILD_RUNNER_<triple> gives the other target's runner wrong,
// keeps what its first pass kept all the same: the failing test's output
// has said where it is. Set while this is the only thread, under the
// name FromEnv reads, '-' and '.' made '_'.
std::string runnerVariable = std::format("CRAFTER_BUILD_RUNNER_{}", otherTarget);
std::ranges::replace(runnerVariable, '-', '_');
std::ranges::replace(runnerVariable, '.', '_');
setenv(runnerVariable.c_str(), "no-such-runner", 1);
bool threw = false;
try {
RunTests(both, serial);
} catch (const std::exception&) {
threw = true;
}
unsetenv(runnerVariable.c_str());
Check(threw, "a run whose runner for the other target is given wrong throws");
const fs::path thrownDirectory = fs::path(Recorded(records / "failing").first).parent_path();
Check(thrownDirectory != directory && fs::exists(thrownDirectory / "failing" / "left-behind"),
std::format("and keeps what its first pass kept: {}", thrownDirectory.string()));
// Two failing tests of one name in a run, as two configurations may
// each declare one: each one's log is its own, named as its TMPDIR is,
// twin-2 for the second, and says where what it left is kept. With one
// log for both, the second's was written over the first's. Each check
// reads to the end of the line: twin's path is the start of twin-2's.
Configuration one;
one.path = "./";
one.name = "one";
one.outputName = "one";
one.target = HostTarget();
AddProbe(one, "twin", { (records / "twin").string(), "1" });
Configuration other;
other.path = "./";
other.name = "other";
other.outputName = "other";
other.target = HostTarget();
AddProbe(other, "twin", { (records / "twin-2").string(), "1" }, true);
std::array<Configuration*, 2> twins = { &one, &other };
RunTests(twins, serial);
const auto logOf = [](std::string_view name) {
std::ifstream in(fs::path("build") / "test-logs" / std::format("{}.log", name));
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
};
const std::string firstTwin = Recorded(records / "twin").first;
const std::string secondTwin = Recorded(records / "twin-2").first;
Check(!firstTwin.empty() && logOf("twin").contains(std::format("kept in {}\n", firstTwin)),
std::format("the first of two failing tests of one name has a log of its own, which says where it kept what it left: {}", firstTwin));
Check(!secondTwin.empty() && logOf("twin-2").contains(std::format("kept in {}\n", secondTwin)),
std::format("and so has the second, twin-2.log: {}", secondTwin));
fs::remove_all(staged, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -436,10 +436,6 @@ int main() {
prefixed.env.emplace("CRAFTER_BUILD_LLVM_DIR", full.string()); prefixed.env.emplace("CRAFTER_BUILD_LLVM_DIR", full.string());
const Toolchain withPrefix = ResolveToolchain(prefixed); const Toolchain withPrefix = ResolveToolchain(prefixed);
Check(withPrefix.llvmReadelf == full / "bin" / "llvm-readelf", "llvm-readelf comes from the prefix"); Check(withPrefix.llvmReadelf == full / "bin" / "llvm-readelf", "llvm-readelf comes from the prefix");
// So does clang-scan-deps, which reads what a source declares and
// imports.
Check(ResolveToolchain({}).clangScanDeps == "clang-scan-deps", "the PATH fallback names clang-scan-deps bare");
Check(withPrefix.clangScanDeps == full / "bin" / "clang-scan-deps", "clang-scan-deps comes from the prefix");
Check(withPrefix.LibcxxSearchFlags() == std::format(" -L{}", (full / "lib").string()), std::format("the search flags are -L alone (got '{}')", withPrefix.LibcxxSearchFlags())); Check(withPrefix.LibcxxSearchFlags() == std::format(" -L{}", (full / "lib").string()), std::format("the search flags are -L alone (got '{}')", withPrefix.LibcxxSearchFlags()));
} }

View file

@ -45,8 +45,10 @@ namespace {
return staged; return staged;
} }
// Swap in the Base variant carrying the extra member, kept beside the // Swap in the Base variant carrying the extra member. From a file rather
// original. // than a string literal: the module scanner reads raw source, so a module
// declaration spelled inside this test would make the test itself look like
// an implementation unit of Base.
void GrowBase(const fs::path& staged) { void GrowBase(const fs::path& staged) {
fs::copy_file(staged / "base" / "Base-grown.cppm.in", staged / "base" / "Base.cppm", fs::copy_options::overwrite_existing); fs::copy_file(staged / "base" / "Base-grown.cppm.in", staged / "base" / "Base.cppm", fs::copy_options::overwrite_existing);
// copy_file carries the source's mtime across, which would leave the // copy_file carries the source's mtime across, which would leave the
@ -113,24 +115,36 @@ namespace {
int main() { int main() {
return 0; return 0;
{ {
// The build records a primary interface unit's imports, and places // The scan records a primary interface unit's imports, and the
// them on a dependency's module the same way it places a partition's. // pending/resolve machinery reaches them the same way it reaches a
// partition's.
fs::path staged = StageFixture(); fs::path staged = StageFixture();
std::unique_ptr<Configuration> base = MakeBaseLib(staged); std::unique_ptr<Configuration> base = MakeBaseLib(staged);
std::unique_ptr<Configuration> widget = MakeWidgetLib(staged); std::unique_ptr<Configuration> widget = MakeWidgetLib(staged);
widget->dependencies = { base.get() };
if (BuildOk(*widget, "widget on base")) { Module* mod = FindModule(*widget, "Widget");
Module* mod = FindModule(*widget, "Widget"); Check(mod != nullptr, "the primary interface unit registered a module named Widget");
Check(mod != nullptr, "the primary interface unit registered a module named Widget"); if (mod != nullptr) {
if (mod != nullptr) { Check(mod->partitions.empty(), "Widget has no partitions, so nothing else could carry the edge");
Check(mod->partitions.empty(), "Widget has no partitions, so nothing else could carry the edge"); Check(mod->externalModuleDependencies.empty(), "nothing resolvable before dependencies are assigned");
Check(mod->externalModuleDependencies.size() == 1, "the import of Base is one external module edge; std, supplied from outside the graph, has none"); Check(std::ranges::find(mod->pendingImports, "Base") != mod->pendingImports.end(), "the unresolved import of Base is remembered as pending");
if (mod->externalModuleDependencies.size() == 1) { Check(std::ranges::find(mod->pendingImports, "std") != mod->pendingImports.end(), "std stays pending — it is supplied from outside the graph");
Check(mod->externalModuleDependencies[0].first->name == "Base", "the edge names the Base module");
Check(mod->externalModuleDependencies[0].second == base->PcmDir() / "Base.pcm", "the edge points at the dependency's BMI"); widget->dependencies = { base.get() };
} widget->ResolvePendingImports();
Check(mod->externalModuleDependencies.size() == 1, "ResolvePendingImports places the external module edge");
if (mod->externalModuleDependencies.size() == 1) {
Check(mod->externalModuleDependencies[0].first->name == "Base", "the edge names the Base module");
Check(mod->externalModuleDependencies[0].second == base->PcmDir() / "Base.pcm", "the edge points at the dependency's BMI");
} }
Check(std::ranges::find(mod->pendingImports, "Base") == mod->pendingImports.end(), "the resolved name is no longer pending");
Check(std::ranges::find(mod->pendingImports, "std") != mod->pendingImports.end(), "std is still pending after the sweep");
// Build() runs a sweep unconditionally on top of whatever callers
// already did, so a repeat must not duplicate the edge.
widget->ResolvePendingImports();
Check(mod->externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent");
} }
} }
@ -150,18 +164,6 @@ int main() {
std::array<fs::path, 3> impls = { "widget/Widget", "base/Base", "main" }; std::array<fs::path, 3> impls = { "widget/Widget", "base/Base", "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls); cfg.GetInterfacesAndImplementations(ifaces, impls);
// Widget's import of its sibling is also the compile-ordering
// guarantee: Widget's precompile needs Base.pcm on disk. Repeated from
// scratch because the failure was a thread race, and one lucky pass
// proves nothing.
for (std::int32_t attempt = 0; attempt < 4; ++attempt) {
fs::remove_all(cfg.BuildDir());
fs::remove_all(cfg.BinDir());
if (!BuildOk(cfg, std::format("sibling pass {}", attempt))) break;
CheckAgrees(cfg.BinDir() / "sibling", std::format("sibling pass {}", attempt));
}
// The edge itself, as the last pass read it.
Module* widgetMod = FindModule(cfg, "Widget"); Module* widgetMod = FindModule(cfg, "Widget");
Module* baseMod = FindModule(cfg, "Base"); Module* baseMod = FindModule(cfg, "Base");
Check(widgetMod != nullptr && baseMod != nullptr, "both sibling modules registered"); Check(widgetMod != nullptr && baseMod != nullptr, "both sibling modules registered");
@ -170,6 +172,16 @@ int main() {
Check(widgetMod->externalModuleDependencies.empty(), "a sibling in the same Configuration is not an external edge"); Check(widgetMod->externalModuleDependencies.empty(), "a sibling in the same Configuration is not an external edge");
Check(baseMod->moduleDependencies.empty(), "Base imports no sibling"); Check(baseMod->moduleDependencies.empty(), "Base imports no sibling");
} }
// That edge is also the compile-ordering guarantee: Widget's precompile
// needs Base.pcm on disk. Repeated from scratch because the failure was
// a thread race, and one lucky pass proves nothing.
for (std::int32_t attempt = 0; attempt < 4; ++attempt) {
fs::remove_all(cfg.BuildDir());
fs::remove_all(cfg.BinDir());
if (!BuildOk(cfg, std::format("sibling pass {}", attempt))) break;
CheckAgrees(cfg.BinDir() / "sibling", std::format("sibling pass {}", attempt));
}
} }
{ {