Compare commits

...
Author SHA1 Message Date
c144528481
docs(packaging): add the 6.5.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m55s
6.5.0 gives a test that sets Test::wayland a headless compositor of its
own, so that the windows a test opens through WAYLAND_DISPLAY no longer
show up on the desktop of whoever runs the suite, ships weston in the
Flatpak for it, and runs every test's command with a TMPDIR of its own,
so that two runs of `crafter-build test` at once no longer write into
each other's temporary files where the test's runner hands it TMPDIR,
as running it directly and qemu-user do, and wine and wasmtime do not.

A minor release, by the version rule: the notes have New and Fixes and
nothing Breaking. The range adds Test::wayland, TestBuilder::Wayland,
TestResult::compositorLog, RunTestsOptions::compositorOverride and the
export of PrivateDirectory, and two parameters at the end of
RunSingleTest, both with defaults, so that the calls to it that
compiled before compile unchanged.
2026-11-28 11:05:51 +01:00
e643f83c00
docs: the TMPDIR each test's command runs with
The README's test conventions say that each test runs with TMPDIR
naming a directory of its own, made for the run, so that
fs::temp_directory_path() in it is the test's alone while another run
goes on, where its runner hands it TMPDIR, which wine does not, a
Windows test's TMP, TEMP and temp directory being the Wine prefix's
whatever the environment gives, and wasmtime, which hands a test no
environment, does not either; how much longer its path is, which a test
that binds a socket there has to leave room for; that what it leaves
there is removed when it passes or skips and kept, with its place in
its log, when it does not; that a later run removes what was kept once
the run's directory has gone a minute unchanged, a minute after that
run ended or, where it was killed, after its last change to it; and
that a test that builds against a sysroot it stages there, or has
crafter-build fetch a repository it stages there, whose path keys
crafter-build's cache and is a new one every run, points XDG_CACHE_HOME
into its TMPDIR as well.

AGENTS.template.md's testing conventions say why the fixed staging
name is safe now, that a test that writes to /tmp by name makes a
directory of its own there, a PrivateDirectory, and that a test that
builds against what it stages keeps its cache in its scratch directory.
2026-11-28 11:05:51 +01:00
0602e282b2
test: HostFlatpak asks about projects in a directory of its own
In the Flatpak, HostFlatpak makes two projects in the sandbox's /tmp,
one there and one through a link in the fixture's build/ that leads
there, and asks whether the host sees them. They had fixed names,
/tmp/crafter-build-host-flatpak and crafter-build-host-flatpak-linked
beside it, and every sandbox of the app has the same /tmp, so two runs
at once asked about, and removed, the same projects. Both are now in a
directory the test makes there, a PrivateDirectory, which the link
leads to, and which goes afterwards with the link, or, when the test is
killed, when a later one is made, once it has not changed for a minute.
The test still names /tmp rather than the TMPDIR it is given, since the
sandbox's /tmp is what it asks the host about, and AGENTS.template.md's
entry for it says it makes a directory of its own there now.
2026-11-28 11:05:51 +01:00
ab8935826d
test: what a test leaves in its TMPDIR, kept when it fails, else gone
TestTemporaryDirectory runs a probe through RunTests that records the
TMPDIR it was given and the directory fs::temp_directory_path() names,
leaves a file there and exits as it is told. Two configurations each
declare a passing test named probe, built differently so that the run
does not refuse them, and the second also a failing one and one for
another target, the host's own triple without its vendor and with x32
after it, which is never the host's and makes a second pass after the
host's, and is skipped before it is built. The run takes one test at a
time, so the failing one comes last in the host's pass, and it dates
the run's directory, and a directory beside it that looks like one a
run let go of, two minutes back before it fails, as a test that ran
that long leaves them. Each test's fs::temp_directory_path() is the
TMPDIR it was given: <run>/<name>, in a directory made for the run in
the temp directory, and probe-2 for the second probe. What the passing
tests left is removed; what the failing one left is kept, named in its
output and its log, and so is the run's directory. A second run gets a
directory of its own, removes it since every test passed, and leaves
the first run's alone; a third, once that one is dated past the minute,
removes it. The other target's pass makes no directory of its own: the
one dated back beside the run's is still there when the run ends. A
fourth run, whose pass for the other target throws, as one does where
CRAFTER_BUILD_RUNNER_ names that target's runner wrong, keeps what its
first pass kept.

The runs make their directories in a temp directory the test makes for
them and names with TMPDIR. The test removes only its own scratch
directory, which holds that one, and the fixture's bin/ and build/, and
dates a directory a probe reports only when it is a run's directory in
that temp directory.

HeadlessCompositor checks that a test that sets wayland and is given a
TMPDIR runs with both: the TMPDIR it is given and its compositor's
display alone, and that one under `host` and given a TMPDIR has it
beside the session's display. Two failing tests of one name each have a
log of their own, twin.log and twin-2.log, that says where what each
left is kept. RunSingleTestExit runs a script whose path has an '=' in
it, given a TMPDIR, which has to run and whose exit decides the
outcome.

Without TMPDIR on the test's command, 13 of TestTemporaryDirectory's
checks fail; with a test's log named after the test alone, the two on
the logs of the tests of one name do; without the date a kept directory
gets as it is let go of, the one on the second run leaving the first
run's alone does; with a directory of its own for a later pass, beside
the run's, the one on the other target's pass does; and with the
directory kept only once RunTests returns, the one on the fourth run
does. With the test's own words as env's command, the two of
RunSingleTestExit on the script whose path has an '=' fail.
2026-11-28 11:05:51 +01:00
93f1c8d9b9
fix(test): run each test's command with a TMPDIR of its own
Tests stage their fixtures under fixed names in the temp directory,
fs::temp_directory_path() / "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, whatever checkout it runs in. A test of one run could
find what it had staged removed or written over by the same test of the
other run, which removes the directory as it starts and stages its copy
anew.

RunTests now makes a directory for the run in the temp directory, a
PrivateDirectory, and runs each test with TMPDIR naming <run>/<name>,
so that fs::temp_directory_path() in the test names it and the fixed
names are the run's alone. The second test of one name in a run, as two
configurations or two targets may each have one, gets <name>-2, so that
removing one's directory does not take the other's. RunSingleTest takes
the directory as a new last parameter and puts TMPDIR into the env
prefix of the test's command, beside a Wayland test's WAYLAND_DISPLAY.
env's command is sh, which execs the test's words, as for a Wayland
test's: env takes a word with an '=' in it ahead of its command for an
assignment, a binary's path among them, and with no command left it
printed its environment and exited 0, a pass for a test that never ran.

What a test that passes or skips leaves is removed when it ends. What
one that fails, crashes or times out leaves is kept for a look, its log
says where, as does what is printed of a test that fails or crashes,
and the run's directory then outlives the run, unlocked, for a later
run to remove a minute after, or, where the run was killed, a minute
after its last change to it; PrivateDirectory gains Keep() for that. A
test's logs, build/test-logs/<name>.log and <name>.compositor.log, are
named as its TMPDIR is, <name>-2 for a later test of one name, so that
two failing tests of one name each keep their own, and with it where
what each left is kept: with one log for both, the second's was written
over the first's. The README's line on the logs says so. The directory
is dated as it is let go of, since the removal of abandoned directories
goes by its date, which is that of what was last made or removed in it:
for the run of a test that fails after a minute, as one that times out
at the default 60 s does, a minute old already, and the next run would
remove it at once. The removal now reads a directory's date only once
it holds the directory's lock: a date read before could be one the
holder replaced as it let go.

The directory is the run's, not a pass's: every pass of a sweep over
targets shares it, so it is made and its surroundings swept once, and
let go of once the last pass is done. A pass that made one of its own
would have made it once the passes before had let go of theirs, and
making it would have removed any of those that had not changed for a
minute: a kept one, after a pass of that long, while its test's output
said where it was. RunTests becomes the wrapper that holds the run's
directory around RunTestsWith, the passes it recurses into, and the
directory is kept the moment a test keeps something in it, by the
worker that ran the test, so that 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 does not take it with it; Keep() may be
called from several workers at once.

TMPDIR reaches the test where its runner hands it on, 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, and
wasmtime gives a test no environment at all; RunSingleTest's comment
says so. A test under `host` gets its TMPDIR as any test does, so that
comment and HostDisplay's now say that `host` leaves the test the
display, not the whole environment, as it is.

In the runner rather than in each of the 74 tests whose main.cpp uses
the temp directory at this commit: a project's own tests are covered
the same way, where their runner hands them TMPDIR. Of the 74 only
SysrootStdModule has to change. It builds against a sysroot it stages
there, and the std module's cache directory is keyed on the sysroot's
path, which is a new one every run now, so every run left one more
directory, with its lock, in the real cache; it keeps its cache in its
scratch directory now, as the tests that have crafter-build fetch a
repository they stage do. AGENTS.template.md says what changes for the
tests: HostFlatpak, whose /tmp is no longer the temp directory a test
is given, is a second test that writes elsewhere, and under
`crafter-build test` a staged copy goes with the test's TMPDIR rather
than at the test's next run.
2026-11-28 11:05:51 +01:00
fcfac0d9cf
docs: tests that open windows, and the compositor each one gets
The README's Tests section gains "Tests that open windows": a test that
sets Test::wayland, or .Wayland() on what AddTest returns, runs with a
headless compositor of its own instead of the session's display. It
says what crafter-build gives the compositor and the test and what it
does afterwards; the default weston command, weston 12 as the first
release that takes its --renderer=, and what its renderer and two
options are for; how CRAFTER_BUILD_COMPOSITOR, --compositor= and
`host` choose another; when the compositor fails the test, how a test
that may run without weston is skipped, and where the compositor's
output goes; and what a crafter-build that is killed leaves.
The CLI examples gain --compositor=host, and examples/tests/README.md's
list of the builder's methods gains .Wayland().
2026-11-28 11:05:51 +01:00
0a91b128cf
feat(packaging): ship a headless weston for tests that set wayland
A test that sets Test::wayland runs with the weston on PATH unless
another compositor is named, and the Sdk has none, so the Flatpak
builds one: weston 16.0.2 with its headless backend, its GL renderer
and its desktop shell, and with none of its other backends or shells
and no Vulkan renderer. Its frontend links libinput, libevdev and
libdisplay-info whatever the backend, and the Sdk has none of those
either, so three modules come before it: libevdev 1.14.0; libinput
1.32.0 without mtdev, libwacom or Lua plugins, of which only the
library and its licence ship, since the headless backend opens no
input device; and libdisplay-info 0.4.0, which weston would otherwise
fetch as a subproject. libinput is a git source pinned by commit, since
its 1.32.0 release has no tarball of its own.

The four sit just before the crafter-build module, so bumping them
rebuilds only them and crafter-build. weston's post-install runs
`weston --version` and checks that the backend and the renderer the
default command names are installed.
2026-11-28 11:05:51 +01:00
67e97d0a2a
test: a test's headless compositor, from its start to its cleanup
HeadlessCompositor drives RunSingleTest with itself in every part. The
harness starts it again as the compositor, which listens on a
wayland-7 socket in the XDG_RUNTIME_DIR it is given and records its
environment, and as the test, which records its own and connects.

A test that sets wayland passes against its compositor and runs with
WAYLAND_DISPLAY naming the compositor's socket, without DISPLAY and
WAYLAND_SOCKET, and with the XDG_RUNTIME_DIR of the process that runs
it. The compositor gets a directory of its own in that one, or in /tmp
where that process has none, and none of the WAYLAND_DISPLAY,
WAYLAND_SOCKET and DISPLAY that process has, each given a value of the
session's in the driver, and afterwards it has been sent SIGTERM, is
gone and so is its directory. The compositor's timeout(1) is the
test's, the wait for its socket and 30 s more, and none for a test with
no time limit; and a test whose binary's path has an '=' in it runs as
any other. A test that does not set wayland, and one run under `host`,
keep that display. Without an override CRAFTER_BUILD_COMPOSITOR names
the compositor, and an override wins over it. A compositor sh cannot
find fails the test with status 127, named, and a line on how a test
that may run without it is skipped; one that ends before it listens
fails it with its status and what it printed, checked on a word the
command does not hold, without running the test; a failing test keeps
what its compositor printed; a compositor killed while the test runs is
reported as ended. A stand-in crafter-build killed in the middle of a
test has its compositor sent SIGTERM and gone, and the directory it
leaves is removed when the next is made, once dated past the minute,
while one changed a moment ago and one that is held stay.

Without PR_SET_PDEATHSIG the two checks on the killed crafter-build
fail, and without the removal of abandoned directories the one on its
directory does; with the test's own words as env's command, the check
on the binary whose path has an '=' fails, with a limit of its own for
the compositor of a test with none the one on that limit does, without
what the compositor printed in the failure the one on that, with
WAYLAND_SOCKET left to the compositor and the test the ones on it, and
without the command in the failure of a compositor sh cannot find the
one on that, which looks for the harness's words, not sh's. No weston
is needed, so the suite runs it in the native loop and in the Flatpak's
build sandbox alike. The driver makes its compositors' directories in a
directory of its own in $XDG_RUNTIME_DIR, or in /tmp where that is not
a directory, rather than in the temp directory, since a socket's path
holds 107 bytes and a temp directory's path can use them up; its check
without an XDG_RUNTIME_DIR has the harness make that compositor's
directory in /tmp itself, as crafter-build does where there is none.
The driver's directory is a PrivateDirectory, now exported for it, so
that one a killed driver left goes when a later one is made, once it
has not changed for a minute, and AGENTS.template.md's line on where
tests write now says that what a test runs writes caches of its own,
crafter-build's builds and wasmtime the modules the wasm tests run, and
names this test as the one that writes anywhere else.
2026-11-28 11:05:51 +01:00
dc8e9e6f9e
feat(test): give a test that sets Test::wayland a compositor of its own
A test that opens a window opened it on the display of whoever ran the
suite: every `crafter-build test` of Crafter.Graphics put the windows
of its window tests on the desktop, and its other GPU tests connect to
the session's compositor too, since Device::Initialize calls
wl_display_connect whether a window follows or not.

A test that sets the new Test::wayland (TestBuilder::Wayland) now runs
with a headless compositor started for it alone. RunSingleTest starts
the compositor through sh, with XDG_RUNTIME_DIR naming a directory made
for it and without WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, waits up
to 30 s for a wayland-<n> socket in that directory, runs the test with
WAYLAND_DISPLAY set to the socket's path and with DISPLAY and
WAYLAND_SOCKET unset, then stops the compositor's process group and
removes the directory. The test's command is env with those changes,
and env's command is sh, which execs the test's words: env takes every
word with an '=' in it ahead of its command for an assignment, a
binary's path among them. The compositor runs under timeout(1) as long
as the test may, the wait and 30 s more, and with no limit for a test
that has none, a timeout of 0. It is weston on its headless backend
with its GL renderer, unless CRAFTER_BUILD_COMPOSITOR or the new
--compositor= names another command; `host` gives the tests the
session's own display instead, to watch them. A compositor that ends
before it listens, sh not finding it included, or does not listen in
time fails the test with what it printed. A test that may run where its
compositor is missing declares it in requires_ (tool:weston for the
default), the check RunTests makes before the build, so no skip of its
own is added, and no probe of the command: the command is any sh
command, whose first word need not be the compositor. A test that
fails, crashes or times out keeps what its compositor printed
(TestResult::compositorLog), which RunTests writes to
build/test-logs/<name>.compositor.log, and says when the compositor
ended while it ran.

One compositor per test rather than one per run: no two tests share
one, so tests that run at once cannot cover each other's windows or
take each other's focus, for weston's start-up on every test. weston's
GL renderer, because it imports the dmabufs that a GPU's Vulkan driver
presents, as Mesa's and NVIDIA's do, and the headless backend's default
renderer and pixman import none: against pixman, the NVIDIA driver
reports no format for a window's surface, and Crafter.Graphics's
FrameLoopSync stops at its formatCount > 0 assertion. weston cannot
run the test itself, as `weston -- <test>` exits 0 whatever the test
returned, so crafter-build runs the compositor beside it.

:Platform gains BackgroundCommand, the compositor's process, and
PrivateDirectory, its directory. The process is forked with
PR_SET_PDEATHSIG and runs under `timeout`, which passes the SIGTERM it
gets when crafter-build dies on to the compositor's group, so a
crafter-build killed by Ctrl-C leaves no compositor running. The
directory is made in $XDG_RUNTIME_DIR, or in /tmp where that is not a
directory, rather than in the temp directory, since a socket's path
holds 107 bytes, and is flocked while in use; one that a killed
crafter-build left is removed when the next is made beside it, once it
has not changed for a minute.

New members and a parameter with a default, nothing removed: a minor
release.
2026-11-28 11:05:51 +01:00
cb8914d387
docs(packaging): add the 6.4.3 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 13m58s
6.4.3 has lint parse a file for the rules that read its AST with the
libc++ of the compiler that builds it, so that in the Flatpak those
rules run on a file that includes a header of the C++ standard library
(#46), and gives the scan of a build's sources the compiler where it is
installed, so that a build whose compiler is reached through a link
from another directory scans them.

A patch, by the version rule: the notes have Fixes and nothing New or
Breaking. The range adds Toolchain::installedDir,
Toolchain::installedDirAsWritten and
Toolchain::InstalledClangxx(command), which interfaces/ exports, for the
linter and the scan to read. They are not under New, as ObjectPath,
which 6.4.1 exported for the tests, was not.
2026-11-27 16:16:38 +01:00
fe25d7aeff
test(lint): the ast and ast-module cases pass only when their rule ran
RunLint calls a rule that reads the AST only on a file it could parse,
so when the parse failed, the checks inside the "ast" and "ast-module"
rules went untried, and the test, which read nothing of the run but
those checks, passed. That is how the "ast" case, whose file includes
<string>, passed in crafter-build's Flatpak with #46 open: lint printed
"'string' file not found" for that file, and the test exited 0. Both
cases now also check that their rule ran and that the run had no error.
2026-11-27 16:16:38 +01:00
043b1a3015
test(lint): a compiler installed in a directory of its own
LintCompilerHeaders stages an installation of its own: the toolchain's
compiler copied into install/bin, beside links to the rest of the real
installation, and one header more in its c++/v1, crafter_issue46.h.
The toolchain it points the build at with CRAFTER_BUILD_LLVM_DIR has a
bin/clang++ that links to that copy, and no include directory. The
compiler runs from install/bin, so the compile of a file that includes
<algorithm> and crafter_issue46.h finds both, and the build's scan of
the file and lint's parse of it have to as well.

Without the lint fix the parse fails on crafter_issue46.h on a host
whose /usr has a libc++, and on <algorithm> in crafter-build's Flatpak,
whose /usr has none. It fails in the same two ways with argv[0] taken
from the compile command, llvm/bin/clang++. Without the scan fix the
scan, given llvm/bin/clang++ as well, fails the same two ways, and the
build with it, which the test's first check reports. The compiler is
copied because a link would lead clang back to the real installation,
and the copy is of the clang++ in the directory `clang++ --version`
names, so that a wrapper on PATH that runs the compiler is not copied
in its place. The test takes CRAFTER_BUILD_LIBCXX_DIR out of its
environment, which would have every compile take that libc++ in place
of the staged one, and the std module the staged toolchain builds goes
to a cache of its own. It skips where it cannot stage the compiler:
where no clang++ is found, the compiler's installation has no libc++
headers of its own, no llvm-ar or clang-scan-deps is beside the
compiler, or the copy names no resource directory it has.

A second configuration on the same toolchain passes
-no-canonical-prefixes, with which the compiler takes itself to be in
llvm/bin, as written, and reads the clang++.cfg the test writes there,
which adds a directory only it names; its file includes the one header
that directory holds, and none of the C++ standard library, which llvm/
has no include directory for. Given install/bin/clang++ whatever the
command's prefix flags, the scan fails on that header, and the build
with it, and so does the parse. The test takes CLANG_NO_DEFAULT_CONFIG
out of its environment as well, which would have clang read no
configuration file, and where the compile with the flag still does not
read the file beside the link, as where a user or system configuration
directory holds a clang++.cfg, or a <triple>-clang++.cfg, that clang
finds first, it leaves the second configuration out and skips, unless
the first configuration failed.
2026-11-27 16:16:38 +01:00
090d8f6363
fix(build): scan sources with the compiler where it is installed
clang-scan-deps, which reads what a .cppm or .cpp declares and imports
since 6.4.2, builds a clang driver of its own from the compile command
it is given, and that driver looks for clang's own headers, and in a
build for the host whose command names no libc++ directory for libc++'s
too, from the directory of the command's first word: the toolchain's
clangxx, looked up on PATH where it is a bare name, and taken as it
stands where it is a link, whatever the command says of canonical
prefixes. Where clangxx is a link from another directory, as a
CRAFTER_BUILD_LLVM_DIR whose bin/clang++ links into another installation
makes it, and the command's last prefix flag is not
-no-canonical-prefixes, that directory need not lead to either, and the
scan of a source that includes a header of the C++ standard library then
failed, and the build with it, on "'stddef.h' file not found" or on the
header it included, though the compile, which takes itself to be where
the link leads, found them. It is the parse of issue #46 over again, in
the scan.

The scan is now given the compile command with
Toolchain::InstalledClangxx(command) as its first word, the compiler
where clang started with that command takes itself to be, as lint's
parse is given it: in the directory its --version names, or, for a
command whose last prefix flag is -no-canonical-prefixes, in the
directory of clangxx as written, from which such a compile looks and
from which the scan of it looked before. That directory is also where
the driver looks for its default configuration files, clang++.cfg among
them, so for any other command the scan now reads the ones beside the
compiler, which the compile reads, where it read any beside a link. What
is kept of a scan still records the compile command itself, which
decides when a source is scanned again: what the source is compiled with
has not changed. AGENTS.template.md now says which of the two commands
is which.
2026-11-27 16:16:38 +01:00
8019f9d44f
fix(lint): look for libc++ where the compiler does
In crafter-build's Flatpak, whose compiler keeps libc++ in /app and
whose /usr has none, a file that includes a header of the C++ standard
library could not be parsed for the lint rules that read its AST in a
build like that of #46: the file built, and `crafter-build lint` then
ran none of those rules on it, printed "'algorithm' file not found"
and exited 1.

libclang parses through a clang driver of its own. In a build for the
host whose compile command names no libc++ directory, as #46's names
none, where a sysroot or CRAFTER_BUILD_LIBCXX_DIR would name one, that
driver looks for libc++'s headers under ../include from the directory
of its argv[0], then under /usr/local/include and /usr/include.
ParseAst gave libclang the compile command without its compiler, and
clang_parseTranslationUnit names argv[0] plain "clang", in no
directory. So the parse of such a build, natively as in the Flatpak,
took the first libc++ it found under ../include from the working
directory, /usr/local/include and /usr/include, whichever compiler the
build used. The -resource-dir ParseAst passes is for clang's own
headers and changes nothing for libc++.

The compile command's argv[0] would not do on its own: a clang++ from
PATH is the bare name clang++, in no directory either, and a clang++
reached through a link into another directory takes itself to be where
the link leads, as clang finds its installation from the file it runs
as. The compiler says where that is, on the InstalledDir line of
`clang++ --version`, which GetToolchain() already runs for clangVersion.
Toolchain::installedDir keeps it, InstalledClangxx(command) names the
compiler in it, and ParseAst passes that as argv[0], through
clang_parseTranslationUnit2FullArgv, which takes argv[0] from its
caller. With argv[0] there, the parse finds libc++ where the compile
does, whatever the working directory.

A compile command can have the compiler look from elsewhere: with
-no-canonical-prefixes, where the last of it and -canonical-prefixes is
that one, clang takes itself to be at clangxx as written, or, where no
file is there, as is usual for a bare name, at the one PATH gives, a
link not followed, and `clang++ -no-canonical-prefixes --version` names
that directory. GetToolchain() runs that too,
Toolchain::installedDirAsWritten keeps what it names, and
InstalledClangxx(command) names the compiler there for a command whose
last prefix flag is -no-canonical-prefixes, as clang's own driver reads
them.

argv[0] also gives libclang's driver its mode, by its file name, and
the configuration files it reads by default, from its directory. The
parse now runs in the g++ mode the compile runs in, where it ran in
clang's gcc mode, and reads the default configuration files beside the
compiler that the compile reads, clang++.cfg among them; before, it read
none from there, as the driver skips the directory of an argv[0] that
has none.

-resource-dir stays, for a libclang of another release than the
compiler, whose driver would derive the directory from argv[0] for its
own release. The comment on it said libclang found clang's own headers
relative to its own install path; its driver derived them from argv[0],
as it does libc++'s.

Fixes #46
2026-11-27 16:16:38 +01:00
578a1da600
docs(packaging): add the 6.4.2 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m6s
6.4.2 reads what each .cppm and .cpp declares and imports with
clang-scan-deps, which preprocesses the source with its compile command,
where it searched the source's text with regular expressions (#45), and
so refuses a module built twice for one program, and interface units
that import each other, once the dependencies are built.

A patch, by the version rule: the notes have Fixes and nothing New or
Breaking. The range takes ResolvePendingImports off Configuration, and
the pendingImports members off Module, ModulePartition and
Implementation, all of which interfaces/ exports, and leaves a
configuration's interfaces and implementations empty until a build has
read its sources. All of it is the build's own bookkeeping of a
configuration's units, as Compile() and `compiled` were, which 6.3.0
took off the same unit classes as "internal and not user facing"
(12e8b90), and no project.cpp of this checkout or of the Catcrafts
checkouts beside it names any of it (callers.txt in the review's
evidence).
2026-11-27 09:25:54 +01:00
efb8fcc8b2
docs: what a source imports is read as its compile reads it
The README said that crafter-build reads the imports of a
configuration's sources from their text without compiling them, so that
one in a string literal, in a comment that spans lines or under #if 0
counted, and that a configuration whose interface units import each
other is refused before anything of it is built. It now says that
clang-scan-deps reads what a .cppm or .cpp declares and imports, with
the command the source is compiled with, as the compiler reads it, once
the configuration's dependencies are built; where the build keeps what
it read, as it keeps objects; that such a configuration is refused once
its sources are read, before any of its .cppm and .cpp is compiled; and
that the scans are among the steps a build runs at most as many of at
once as the machine has hardware threads.

The README's sentence on a project that two paths load with different
lists now names the projects the build stops for, those that export
modules, since DuplicateModuleError refuses a module built twice and
nothing else, and says that such a project is built once where both
lists give it one build directory, as two orders of the same flags of
its own can. The README and the contributor guide also stop naming
nlohmann/json among the vendored headers in lib/, which it left in
4af9280.
2026-11-27 09:25:53 +01:00
15e9831203
test(build): one project loaded with its flags in two orders is built once
DuplicateModule builds its project once more with --wide --reorder, with
which P gives M the list that A passes on, in the other order. The
loader takes the two orders for two lists and makes two configurations
of M, which VariantId, taking the project's own flags sorted, builds
into one directory, and a pass builds that directory once. The case
checks that the two are two configurations with one directory, and then,
in two passes, that the graph builds and that P's main.cpp and A's
interface have their edges to the module of the configuration of M that
the pass built. The first pass builds whichever asks first, and the
other has no modules. The second builds the other one first and records
it for the directory, as BuildAll records a configuration it builds,
before it builds the graph, so that both configurations of M then have
modules, the first still those it read in the first pass.

On the engine of the range's base the graph is refused as "module M is
built twice for P": every configuration had its modules from the
listing, and the refusal told the builds apart by their configurations.
On an engine that reads a dependency's modules off the configuration it
is listed as, the range's fix without BuildResult::built, the first pass
builds and A's interface has no edge to M, P's M being the one built and
A's having no modules, and the second pass is refused as a graph with
two builds of M.
2026-11-27 09:25:53 +01:00
08a506d34b
test(build): a source's declaration and imports, as its compile reads them
SourceScan builds copies of six fixtures and checks what the build read
in their sources, by the modules and units it gives each configuration,
and runs the program where what it does depends on that:

- text, three of the four inputs of #45: `import  Base;` and
  `import Spaced ;` are imports, and an import in a comment that spans
  lines or under #if 0 is none. A build with nothing changed then
  rewrites none of the scans, and one that cannot be read is taken
  again.
- quoted, the fourth: an implementation source whose string literal
  holds "export module std;" is a unit of no module, and the build
  succeeds.
- partition: a .cppm that declares an implementation partition
  (`module X:Impl;`) is the partition Impl of X, and the implementation
  unit that imports it has its edge to it.
- define: an #ifdef on a define that the test sets after listing the
  source decides whether the source imports a module.
- switch: an #if on a header of the library the app is built on decides
  it. The header is edited, and the source is scanned again; then the
  app is built on another library, whose header of that name says the
  other thing, so that only the command the scan was taken with has
  changed.
- missing: an #include of a header that is not there fails the build
  with a message naming the header, and nothing is compiled of the
  source.

On the engine of the range's base, with only this test added, every case
but missing fails. Each of the three inputs of the text case is read the
old way, and its first build fails outright whenever Spaced.cppm, whose
import of Base was missed, is compiled before Base's BMI is there; the
string literal makes the listing throw "Module std not found not found",
and the implementation partition the listing of the partition case, "No
module declaration found"; the import under the #ifdef counts without
the define, and the one under the #if after the edit and after the swap;
and there is no scan to look at. The missing case passes there too, the
compile reporting the header as the scan now does.
2026-11-27 09:25:53 +01:00
3c8f4ddb54
fix(build): read what a source declares and imports with clang-scan-deps
GetInterfacesAndImplementations found the module declarations and the
imports of a configuration's sources by searching their text with
regular expressions, after deleting the comments that fit on one line.
The expressions skipped neither string literals nor comments that span
lines, knew nothing of the preprocessor, and wanted one space after
`import` and none before its semicolon (#45). An implementation source
that held "export module std;" in a string literal was taken for a unit
of a module std, and listing it threw "Module std not found not found".
An import in a comment that spans lines or under #if 0 was followed.
`import  X;` and `import X ;` were missed, so their unit had no edge to
the module it imports and could be compiled before that module's BMI was
written.

What a .cppm or .cpp declares and imports now comes from clang-scan-deps
-format=p1689, which preprocesses the source with the configuration's
C++ compile command, the one Build() compiles every unit of it with:
strings, comments, spacing, macros and #if come out as they do for the
compiler. GetInterfacesAndImplementations only lists the sources, in the
new interfaceSources and implementationSources. Build() reads them
(ReadSources) once the configuration's dependencies and external
dependencies are built: the command takes their include paths, and a
source may include headers of an external dependency, which are not
there before it is fetched. From what it read, Build() makes the
configuration's modules and units, its `interfaces` and
`implementations`, and places each import on a module of the
configuration or of what it is built on, whose own Build() has read its
sources by then. It makes those of its own configuration alone, as the
reset of the units' state did before it.

A build pass builds a directory once, for whichever configuration of it
asks first, and the loader can make two configurations of one directory:
one project loaded along two paths with its args in two orders, which it
keeps apart and VariantId, sorting the args, does not. Only the one that
was built has the modules that build read, so the result of a build now
names the configuration it ran on (BuildResult::built), and a
dependency's modules are looked up through the pass's record of its
directory. 6.4.1 had every configuration's modules from the listing and
took such a graph for one with two builds of a module, which it refused;
it is now built, once, and the units of both sides have their edges.

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 of the command it
was taken with and of what clang-scan-deps wrote, with the dependency
file clang-scan-deps wrote beside it, which lists the source and every
file it included. A build scans a source again unless its scan is newer
than every file that dependency file lists, was taken with the same
command and can be read, so a build with nothing changed runs no
clang-scan-deps. Both files are written beside their places and renamed
into them, as the archive and the list of objects are, for another
crafter-build that may be building the same clone.

A configuration's modules are known only once its build has read its
sources, so the refusals of a module that two configurations of the
graph build (DuplicateModuleError, #41) and of interface units that
import each other (ImportCycleError) now come there: once the
dependencies are built, before any .cppm or .cpp of the configuration is
compiled. They came before the configuration made a directory or built a
dependency. The contributor guide names clang-scan-deps among the
prerequisites and among what :Toolchain resolves, has a test look at the
modules of a configuration only after building it, and has the gotcha
for the new order.

ResolvePendingImports and the pendingImports of the unit classes go.
They placed the imports that a scan at listing time could not, once the
dependencies were wired up, and with the imports placed when the
dependencies are built there is nothing pending. The tests that looked
at a configuration's modules and units before building now look after it
(DependencyLink, ModuleInterface, StaticLib, ConcurrentDependencyReset
and the disabled TransitiveInterfaceChange), IncrementalInterfaceChange
checks the edge that the build of a consumer gives it when its
dependency was assigned after its sources were listed, and ImportCycle
and DuplicateModule check that the refused configuration compiled
nothing of its own. The workarounds for the old scanner are not needed:
MingwSysroot writes its stand-in std module as a plain literal again,
JobLimit writes the declarations of the sources it generates as plain
literals, and Lint's comment on its fixture file no longer gives the
scanner as the reason for it.

The messages of the regex code stay where they still apply. The one for
a source that declares a unit of a module the configuration does not
have loses its doubled "not found", and applies to an implementation
source that declares one, such as an implementation partition
(`module X:P;`). An implementation unit written `module X;` declares no
unit for clang-scan-deps but imports X, and an import needs no module of
the configuration: the compile reports a module no one builds. A .cppm
that declares an implementation partition is built as a partition of its
module, where it was refused as declaring no module.

The Toolchain gains clangScanDeps, resolved as llvm-ar is: in the bin/
of the LLVM prefix, else by name on PATH. The Flatpak has
/app/bin/clang-scan-deps.

Fixes #45
2026-11-27 09:25:53 +01:00
a99647ecff
docs(packaging): add the 6.4.1 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 17m51s
6.4.1 gives each .cpp, .c and .cu of a configuration an object named
from its path, so that two sources no longer share one for having the
same file name (#50), writes a static library's archive anew, so that
it does not keep the object of a source that left the project, and has
the link and the archive step read their objects from a file, so that
their paths no longer make the command too long to run.

A patch, by the version rule: the notes have Fixes and nothing New or
Breaking. The range changes what Implementation::Check and Schedule
take, which interfaces/ exports, and adds ObjectPath beside
ExpectedOutput, for the tests that look at an object. Check and
Schedule are what Build() itself checks and compiles an implementation
unit with, as Compile() was, which 6.3.0 took off the same class as
"internal and not user facing" (12e8b90), and no project.cpp of this
checkout or of the ones beside it calls either.
2026-11-19 11:02:39 +01:00
9df82bc272
docs: where a source's object goes, and what a link reads
The README's "Writing a project.cpp" says that a .cpp, .c or .cu of a
configuration is compiled into an object named from its path, under
objects/ in the build directory at the source's path from cfg.path, or
under objects-outside/ at its whole path for a source outside
cfg.path; that two sources may therefore have the same file name in
different directories, and a .c lie beside a .cpp or a .cu of its
name; that the progress line of such a source's compile names it by
that path; and that the link and a static library's archive step read
their objects from <outputName>.objects in the build directory.

The contributor guide gains two rules beside the one on output paths.
ObjectPath() names an object, which is not to be named from its
source's file name, and a step that takes every object of a
configuration reads them from a response file. And a static library's
archive and the list of a step's objects are written under another
name beside them and renamed into place, as anything else that a link
or archive step of another crafter-build may be reading is to be: two
crafter-builds can build a project loaded with GitProject at once, in
the clone the cache keeps for its source.
2026-11-19 11:02:39 +01:00
f9bd5333da
test(build): sources of one file name, and where their objects go
SameNamedSources builds configurations whose sources share file names,
on a fresh copy of its fixture outside the checkout, and runs what they
link. `names` is an executable of an a/Thing.cpp and a b/Thing.cpp, the
C sources a/unit.c and b/unit.c, a b/Thing.c beside the b/Thing.cpp and
a Thing.cpp in a directory beside the configuration's own; its program
prints what each returns, the first time and again after a header that
only a/Thing.cpp includes has changed and after b/Thing.cpp and
b/unit.c have. `registry` is a debug executable of an a/Self.cpp and a
b/Self.cpp that register themselves when the program starts, which
prints that each did so once. `things` is a static library of
a/Thing.cpp, b/Thing.cpp, b/Thing.c and the two unit.c, and
`things-app` a program of main.cpp and ../shared/Thing.cpp built on
it, which prints what `names` does. `outside` is a static library of
one C source that lies outside its configuration's directory and is
listed relative to the working directory, built from a working
directory with a space in its name; `llvm-ar t` lists its object.

ObjectPath asks the rule for the objects of sources without building
anything: in the configuration's directory and in directories of it,
of one file name in two directories, a .cpp, a .c and a .cu of one
name in one directory, outside the directory, and under a directory of
the configuration's own that is named objects-outside and holds the
whole path of the source outside. No two of them get one object. A
path spelled with . and .., a relative source, and a source of a
configuration whose path ends in a separator or is ./ are each given
the object of the file they lead to, and a .cppm, a .h and a file
without an extension are refused.

CudaCompile gains a static library of its kernel.cu and a kernel.c
beside it, whose archive lists kernel_source.o and kernel_cuda.o.

Before the fix SameNamedSources failed at the link of `names`, with
duplicate symbols, and of `things-app`, with undefined ones, and its
`registry` printed that one of the two sources had registered twice
and the other not at all. `outside` built before the fix as well, its
object lying in the build directory then: it is there for the path
the fix gives that object.
2026-11-19 11:02:39 +01:00
7f8089474b
fix(build): name a source's object from its path
The object of an implementation unit was named from its file's name
alone, <build dir>/<name>_impl.o, and that of a C or CUDA source
likewise, <name>_source.o. Two sources of one configuration with the
same file name in different directories were therefore compiled into
one object, each over the other, with one dependency file between
them, and the link was given that object twice (issue #50). A build of
an a/Thing.cpp and a b/Thing.cpp that each define a function failed at
the link, with duplicate symbols of one of the two and no word of the
other. A debug build of two such files that define nothing another
file names succeeded, and its program had one file's code twice and
the other's not at all. A .c and a .cu of one name shared an object in
one directory as well.

An object, with its dependency file beside it, is now named from where
its source lies: under <build dir>/objects by the source's path from
the configuration's directory, objects/a/Thing_impl.o for a/Thing.cpp,
or, for a source outside that directory, under
<build dir>/objects-outside by its whole path. A .cu's object ends in
_cuda.o; a .cpp's still ends in _impl.o and a .c's in _source.o. Two
sources then have one object only when their paths are one once . and
.. are taken out of them: any other two differ by path or by ending in
one of the two directories, and the two directories share nothing,
whatever a project calls its own directories. They are directories of
their own, and not the build directory itself, because that one holds
files named after other things: an interface unit's object, the record
of the link and the list of its objects and, for an executable, the
BMIs.

ObjectPath gives that name, exported beside ExpectedOutput for what
looks at an object from outside Build(). Build() names each object by
the same rule, once, as it goes over the sources, and the list it
keeps of them for the link is what the check whether an object is
newer than the output reads as well. Before, each put the name
together for itself: Implementation::Check, Implementation::Schedule,
and Build() where it compiles C and CUDA sources, lists the link's
objects and checks whether to link again. Implementation::Check and
Schedule are given the object, where they put its name together from
the build directory. The job that compiles a source makes the
directory of its object first, since the compiler makes none. The C
compile quotes its source, dependency file and object for the shell,
as the CUDA compile does: the object of a source outside the
configuration's directory holds that source's whole path, and so
directories the command did not name before, the working directory's
among them where the source is listed relative to it.

The progress line of the compile of a .cpp, .c or .cu names the source
by the path its object is named from, "Compiling a/Thing.cpp" where it
was "Compiling Thing.cpp" for both, and so does the error for a .cu
without an nvcc.

What else changes: every implementation unit and every C and CUDA
source has its object in a new place, so an existing build directory
compiles them once more. The objects under the old names stay where
they are, unused; a static library's archive does not keep them, being
written anew. Interface units are as they were: a BMI is found by its
module's name, so two interface files of one name would have to be one
module. A source that a configuration lists twice is also as it was,
compiled twice into its one object, which the link is given twice.

In IncrementalHeaderChange, IncrementalInterfaceChange, StdPcmRebuild
and TransitiveInterfaceChange, the lines that spelled out an object's
old name take it from ObjectPath.

Fixes #50
2026-11-19 11:02:39 +01:00
0d81aca13f
test(build): a link of more objects than one argument holds
LinkManyObjects makes a project six directories deep, each with a name
of 200 characters, with 120 C sources and a main.cpp that adds up what
each of them returns. Every object lies in the project's build
directory, so the test first checks that 120 times the length of that
directory's path is more than 131,072 bytes. It then builds the
sources three ways: as one executable, as a static library and as a
shared library, the libraries each with an executable of main.cpp
built on it. Each of the three programs prints the sum.

It then opens the list the static library's archive step read, builds
the library again with one source fewer, and reads what it had opened:
the 120 lines of the first build, while the list in its place has the
119 of the second.

Before the fix each of the three builds ended with "popen() failed!":
the executable's at its link, the other two at the archive step and
the link of the library. No list was written, so the test found none
to open.
2026-11-19 10:33:33 +01:00
93eca17e57
fix(build): give a link its objects in a response file
Build() wrote the path of every object of a configuration into its
link or archive command. A command is run by a shell, which is given
it as one argument, and Linux holds one argument to 32 pages: 131,072
bytes with pages of 4 KiB, the terminating byte included. Once the
objects' paths left the command longer than that, popen started no
shell and the build ended with "popen() failed!". Issue #50 notes the
limit, and that a response file for the objects would take it away.

The step now reads its objects from a file that the command names with
@, <output name>.objects in the build directory, one object to a line.
clang and llvm-ar both take arguments from such a response file, so
the link of an executable or a shared library and the archive step of
a static library are handed their objects the same way, and the
command is as long for a thousand sources as for one. Build() keeps
the objects as a list for that, where it joined their paths into the
command as it went over the sources. Each line is quoted for the
reader of a response file, which differs from the shell's: it takes a
backslash inside quotes to quote the character after it.

The file is written before every run of the step, and one that cannot
be written fails the build: the list of an earlier build would
otherwise stay in its place and the step would read its objects. It is
written under a name of its own beside its place and moved there, as
the archive of a static library is, so that a step of another
crafter-build which reads the list at that moment reads the list it
opened, whole, or the new one.

The record that decides whether an unchanged build links again held
the command, which held the objects. It now holds the command and,
under it, the list. The command only names the file, so taking a
source out of a configuration can leave the command as it was, with no
object newer than the output, as the second build of
StaticLibSourceRemoved does: the list is then all that says the step
has to run again.
2026-11-19 10:33:33 +01:00
c82b2bb18c
test(build): a source that leaves a static library leaves its archive
StaticLibSourceRemoved builds a static library and a program on it, on
a fresh copy of its fixture outside the checkout. The library has three
sources: lib/first.cpp and lib/second.cpp each define Value(), returning
1 and 2, and lib/extra.cpp defines a function nothing calls. It is
built three times, by configurations of one name and directory: from
the first and the extra source, from the first alone, and from the
second in the first's place, as the project of a renamed source lists
it. The program prints 1, 1 and 2, and `llvm-ar t` lists the archive's
members as first_impl.o and extra_impl.o, then first_impl.o, then
second_impl.o.

While the second and the third build run, a thread of the test looks
for the archive again and again and has to find it every time: the new
archive is moved into the place of the old one, where a build that
removed the old one first would leave whatever links the library at
that moment without it.

Before the fix the second build's archive listed first_impl.o and
extra_impl.o, and the third's those two and second_impl.o, with a
program that printed 1.
2026-11-19 09:20:32 +01:00
2138015178
fix(build): write a static library's archive anew
The archive step of a static library ran `llvm-ar rcs` on the archive
the build before had left. `r` adds to an archive that is there: it
replaces the members it is given and keeps every other member as it is.
The object of a source that had left the configuration therefore stayed
in the library, ahead of the members added after it.

The link takes a symbol from the first archive member that defines it.
So after a source of a static library had been renamed, the library
held the object of the file under its old name and, after it, the one
of the file under its new name, and whatever was built on the library
went on linking the first. The object of a source taken out of the
project stayed in the library the same way.

The step now writes its archive under a name of its own, beside the
archive's place, and Build() moves it there once the step has
succeeded, so the archive holds the objects that step lists and no
others. It is moved into place, and the old archive not removed first,
because another crafter-build may be linking against the library at
that moment: a project loaded with GitProject is built in its clone in
the cache, which every project that names the same source shares, and
nothing keeps two crafter-builds from building it at once. llvm-ar put
the new archive in the place of the old one in one step, so such a
link found one of the two, and with the move it still does. A step
that fails leaves the archive of the build before, as it did, and the
next build runs the step again.

build.sh has written the bootstrap's archive anew since 046609f, for
the same reason, by removing it first.
2026-11-19 09:20:32 +01:00
c929dce8e4
docs(packaging): add the 6.4.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m4s
6.4.0 lets a project.cpp return several configurations from
CrafterBuildConfigurations, which are all built, lets a GitProject or
LocalProject spec pick one of a sibling's configurations by name, keeps
the Configuration of a project loaded through either of them where its
project file built it, and builds a wasm32 library that two
configurations of one build share once when its project file sets the
target itself.

A minor, by the version rule: the notes have New and Fixes and nothing
Breaking.
2026-11-15 02:16:07 +01:00
53485c160b
docs: a project file can return several configurations
The README's opening and the start of "Writing a project.cpp" say that a
project file returns one configuration or several, and so does the
description in the Flatpak's metainfo. The README has a "Several
configurations" section in "Writing a project.cpp":
CrafterBuildConfigurations with an example, how the configurations it
returns have to be kept, and what a build, test, run, lint, format, -r,
install and bundle do with several. "Dependencies" says how a GitProject
or LocalProject spec picks one of a sibling's configurations, and that a
`#pragma crafter dependency` gets the first; its sentences on the args a
sibling gets, on where to make a spec and on IsTopLevelProject() speak
of a project file's entry point, where they named CrafterBuildProject.
"Dependency notes for agents" says how the dependencyNotes of several
configurations combine, and which runs leave AGENTS.md alone now that a
list of configurations can be refused before a build starts: its
sentence on that said that a build that fails still has the notes, and
named an `install` or `bundle` refused before building as the one
refusal that writes none. The table of ScriptContext says that a
script's `project` is the configuration it is declared on.
2026-11-15 02:16:07 +01:00
5795b666f5
test: several configurations from one project file
BuildAll builds configurations the test makes itself, on a fresh copy of
its fixture outside the checkout. A library, a program built on it and
an unrelated program all come out built, each in the record of the pass
under its PcmDir, and a list that names one configuration twice builds
it from nothing, what the build before left of it being removed first,
and leaves it in the record of the pass once. A library built on another
library of its own name, path and type, so that the two are built into
one directory, builds, with both archives in that directory; returned
beside a program that is built on it, the pair is refused, both by name,
before the program is built or anything is recorded. Two libraries that
are each built on a configuration of the other's directory are refused
by name, and nothing of them is built or recorded. A wasm32 library that
names no sysroot and a program for the host built on it leave the
library in the record once, under the directory it has after the pass,
and its refusal comes back once; it is refused for its -fno-exceptions,
so the case needs no WASI sysroot. Of two programs built on a library
that does not compile and a third that has nothing to do with it, the
third is built, the two are not, and the library's error comes back
once. Two configurations that would be built into one directory are
refused, and neither is built. With a wasm executable that declares a
variant among them, a program of one source is linked no earlier than
the program and library given before it; the wasm one is refused for its
-fno-exceptions before it builds anything, so the case needs no WASI
sysroot.

ProjectConfigurations loads fixture project files staged outside the
checkout. A file with CrafterBuildConfigurations comes back as the three
configurations it returns, with the pointer the file took from the
second to the first intact, and as two when its args say so; LoadProject
refuses it. A file with CrafterBuildProject comes back as a list of one
whose test still depends on that Configuration, and that test builds and
passes. A file with both entry points, one with neither, and ones whose
CrafterBuildConfigurations returns nothing, a null pointer or one
configuration twice are refused, each with a message that says which.
Then crafter-build's verbs, through Run() and RunTests, on the file of
three: a build builds all three; -r refuses to pick between its two
executables, and runs the one executable there is when the file returns
two configurations; RunTests runs the tests of the first and the third
configuration in one run, and when the first declares the third's test
as well, that test fails for both, naming the two, and is not built,
while the first's own test passes, and a list that names the first
configuration twice runs its test once; with a fourth configuration of
the third's name and path, a test run and a build are each refused for
the two that would be built into one directory, and neither writes the
AGENTS.md that a build which is not refused writes from the template the
test puts beside the project file; `run` reaches a script of the first
and of the third configuration and hands each the configuration that
declares it; install refuses the project while none of the three is
packaged, bundle refuses it when two are, and with one packaged
executable beside the library bundle does not take the library for the
app.

SiblingConfigurations loads such a file as another project's sibling. A
spec without `configuration` gets the first, a spec that names one gets
that one, and the three specs share one load: the dependency of the
second is the first as LocalProject returned it. All three are rebased
onto the sibling's directory. A name the sibling does not have throws
with the names it has, and a name that two configurations of another
fixture share throws too, while a spec without a name still gets the
first of those two. Building the second builds the first with it and
leaves the third unbuilt. A file that returns something a sibling keeps
to itself is refused when it is loaded, the configuration and the
sibling named: the library the sibling's program is built on, the
configuration of that program's test, and a helper only that test is
built on, none of which the sibling's file returns. A project that
returns the sibling's third configuration beside one of its own builds
both, cannot run the sibling's script and runs its own, and its test run
leaves the sibling's test alone.

DependencyNotes gains a project of two configurations and a fixture,
outer, that builds against lib: two Direct configurations give what each
of them names; a project a Direct one names is followed when a
Transitive one leads to it; a configuration under None keeps out what
only it is built against; with both under None, AGENTS.md is the
template's text; and a returned configuration of another project is one
of the projects the notes come from, followed further only under
Transitive, which is also what a file that made no configuration gets.
For outer's own AGENTS.md, written from the Configuration LocalProject
returned and outer's project file, outer's own setting selects: lib
under Direct, lib and base under Transitive, nothing under None.
Script runs a script of each of two configurations, each handed the
configuration that declares it, refuses a name both declare without
running anything, and, given a list that names one configuration twice,
runs the script asked for, which a name declared twice would have kept
it from. Lint formats the sources of two configurations in one run,
counts a rule both register as one, and runs a rule only one of them
registers over the sources of both. Of two returned configurations that
register a rule under one name the earlier one's runs, over the sources
of all three, though the configuration returned ahead of both depends
on the later one.
2026-11-15 02:16:07 +01:00
4283a3ecd2
feat: let a project file return several configurations
A project.cpp described one configuration: CrafterBuildProject returns a
Configuration by value, and anything else the project wanted built had
to be among that one's dependencies. There it was built as part of that
configuration's graph: under the check that a graph builds each module
once, with its libraries handed up to whatever links that configuration,
and with its tests and scripts out of reach of `test` and `run`. Jorijn
asked for a project.cpp that can return several unrelated configurations
which all get built, and suggested a separate entry point, so that no
existing project file breaks.

A project file now defines one of two functions. CrafterBuildProject is
as it was. CrafterBuildConfigurations returns
std::vector<Configuration*>: pointers to configurations the file keeps
alive itself, or that GitProject and LocalProject gave it. The two have
different names because the loader finds the entry point by its C
symbol, which carries no return type, so one name with two return types
would be called as whichever the loader guessed. They are pointers
because a project file takes pointers between its configurations, for
`dependencies` and for a test's, before it returns them, and a vector of
values would move them.

LoadConfigurations loads a project file with either entry point and
returns the list. A CrafterBuildProject's Configuration comes back as a
list of one, constructed by the call where the loader keeps it for the
rest of the process; LoadProjectFromRoot, which did that for a
sibling's, leaves it to LoadConfigurations, and the project cache holds
the lists without owning a Configuration. The Configuration of the
project crafter-build is pointed at is kept that long as well, where it
was a local of Run(). LoadConfigurations throws for a file that defines
both functions or neither, and for a CrafterBuildConfigurations that
returns nothing, a null pointer or one configuration twice. It also
throws for one that returns a configuration a project loaded through
GitProject or LocalProject keeps to itself, which the loader now takes
down when it loads that project's file: what the configurations the file
returned led to through `dependencies` or through their tests, as far as
the first configuration on each way that a loaded project's file had
returned or another loaded project keeps. Returned from here, such a
configuration would count as this file's own to `test` and `run`, and
only the configurations a project file returns are rebased onto its
directory. LoadProject stays, for a caller that wants a
CrafterBuildProject's Configuration by value, and throws for a file with
the other entry point.

GitProject and LocalProject keep, per spec and args, the list a
sibling's file returned, and return the first one unless the spec's new
`configuration` names another by Configuration::name. Every
configuration of the list is rebased onto the sibling's directory,
except one that another project's file had returned before, which was
rebased onto that project's. Specs that differ only in the name they
pick share one load. A name the sibling does not have throws, listing
the names it has, and a name two of its configurations share throws
too. A `#pragma crafter dependency` gets the first.

BuildAll builds the returned configurations in one pass. Each is built
by Build(), as a project's one configuration is, the first on the
calling thread and each other one on a thread of its own, and its result
then goes into the record of the pass under its PcmDir, where Build()
looks for a dependency. One that another of them is built on is built
before that other starts, which then finds it in the record: started
beside it, the other would not find it there yet and would build it a
second time. A configuration is not put into the record before it is
built, because a dependency of its own that is built into the same
directory would be handed its unfinished build and wait for it, while it
waits for the dependency. All of them are built to the end, and the
errors come back in the order given, each message once; an exception a
build throws comes back as an error that names the configuration, where
Run() printed the exception's own text for a project's one
configuration. Refused before anything is built: two that would be built
into one directory, which would be two builds writing the same files at
once; several that are each built on something of another's directory,
so that none could be built first; and one that is built on something of
its own directory when another is built on that directory as well, since
the record holds one result for a directory and the other could be given
either.

One shortcut is in it. A wasm executable that declares wasmVariants
builds what it is built on once more per variant, and says which
variant by rewriting those configurations in place, at the end of its
Build(). A library that two returned configurations share would change
under the one still building its baseline, so with such an executable
anywhere in the graph BuildAll builds the configurations one after the
other, on the calling thread. Keeping them side by side takes a variant
driver that does not rewrite configurations other builds read, which
this commit does not attempt.

Run() works on the list. A build builds all of it. `test` runs the
tests, and `run` offers the scripts, of the ones in it that the project
file made itself. One that another project's file returned to GitProject
or LocalProject, and that this file returns in turn, is built with the
rest, but its tests and scripts stay that project's, so `run` still
reaches only the scripts of the project crafter-build was pointed at.
What the list itself rules out Run() refuses once the project file has
loaded, before any of the list is built and before AGENTS.md is written:
for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a
list for, and for `test`, which builds its tests with Build() and never
comes to BuildAll, two returned configurations of one directory.
BuildAll makes its refusals again for whoever calls it. A script is
handed the configuration it is declared on. `lint` and `format` walk
from every returned configuration and keep, as before, the
configurations in the project's directory: the returned ones first, in
the order the file returned them, then what they depend on, so that of
two returned ones that register a rule under one name the earlier one's
runs. `-r` runs the executable when exactly one of them is one, and
`install` and `bundle` export the one that is packaged as a Flatpak;
with more than one candidate each refuses and names them, `-r` once
everything is built and `install` and `bundle` before anything is.
AGENTS.md takes the notes that the dependencyNotes of each returned
configuration the file made itself selects among what that one is built
against, and the file's pragma tooling and a returned configuration of
another project go by the widest of those settings. There, a
configuration is another project's when GitProject or LocalProject
loaded it from another project file than the one whose AGENTS.md is
written, two files being one when they resolve to one path, so
UpdateAgentsMd still reads the setting of a Configuration one of the two
returned when it is given that Configuration's own project file.

For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an
overload that takes the list, and the one that takes a single
Configuration calls it with a list of one. SetParentProject gained one
too, and ParentLib searches the graph of every configuration it was
given. BuildAll, RunTests and RunScript count a configuration the list
names twice once.

The tests of several configurations share what one configuration's had
to itself: AddTest names a test's sources, tests/<name>, and its build
directory after the test and its compile state, not after the
configuration that declares it. Two configurations that each declare a
test of one name, compiled alike, would have RunTests build both in that
one directory, each with the dependencies of its own declaration.
RunTests fails both without building either, and each failure names the
configurations. It compares tests of different configurations only, so
a project of one configuration is treated as it was.

The --help text names the second entry point, says what -r, install and
bundle do with several configurations, and speaks of the project file's
entry point as what gets the project args, where it named
CrafterBuildProject. AGENTS.template.md says that a project.cpp returns
one configuration or several, that Run() works on the list and what a
new verb has to decide about it, which configurations have their path
rebased, and that the scripts of a returned configuration of another
project cannot be run. Two of its notes named LoadProject as what loads
a project.cpp for crafter-build, which Run(), GitProject and
LocalProject no longer call, and speak of the load now. Its rule for the
link flags of a test that loads a project file names the ways a test
loads one, where it named LoadProject, and its entry for `:Script`
speaks of the `scripts` of the configurations the driver is given, where
it named `cfg.scripts`. Its entry for `:Platform` names
LoadConfigurations beside LoadProject. That entry also said that
`:Platform` holds all OS-specific code, which it did not before this
range either, :Agents, :Progress, :Lint and :Clang including POSIX
headers of their own, and no longer says so. The bug-prover lens's
section names BuildAll's threads and LoadConfigurations.

Not in this commit: a way to say which executable -r runs or which app
install and bundle export when there are several, and a keyword that
lets a `#pragma crafter dependency` name a configuration.
2026-11-15 02:16:06 +01:00
a7aa22220b
test(wasm): a configuration is the same with its WASI sysroot named or not
WasmSysrootKey makes two wasm32 configurations that differ in one thing:
one names no sysroot and the other names the toolchain's WASI sysroot.
They have to be one configuration: the same VariantId, PcmDir and
BuildDir, the same std module key, and the same compile command, which
names the WASI sysroot. A third, with a sysroot of its own, has another
VariantId.

It then builds two programs for the host in one pass, each on the same
wasm32 library, which names no sysroot. The library carries
-fno-exceptions, which a wasm build is refused for before it makes a
directory, so the case does not depend on the machine having a WASI
sysroot. The library's PcmDir has to be the same after the first
program's build as before it, and the pass has to hold the library
once.

Against the engine as it was before the fix the test fails on each of
the three: the two configurations have different VariantIds, the
library's PcmDir changes with the first build, and the pass holds the
library twice.
2026-11-14 23:42:47 +01:00
1ddba745cf
fix(wasm): resolve the WASI sysroot where it is read, not in Build()
A wasm32 configuration that names no sysroot is built against the
toolchain's WASI sysroot. ApplyStandardArgs stores that sysroot in
cfg.sysroot, for a project file that calls it. For a configuration
whose project file sets the target itself, Build() stored it on its way
in. VariantId hashes the sysroot, so such a configuration had one
BuildDir, BinDir and PcmDir until its build started and others from
then on.

A build pass records each dependency's build under its PcmDir, and a
configuration asks for a dependency by the PcmDir it has at that moment.
A wasm32 library that two configurations of one pass are built on was
recorded under the first directory for the one that asked first. One
that asked after the library's build had started asked under the second
directory, found nothing there, and built the library again.

Configuration::ResolvedSysroot now gives what cfg.sysroot comes to: the
toolchain's WASI sysroot for a wasm32 configuration that names none,
cfg.sysroot as it stands for every other, as ResolvedPackaging gives
what `packaging` comes to. VariantId, the std module's flags, key and
source, the compile and link commands and the check that refuses a wasm
build without a usable sysroot read it, and Build() no longer stores the
sysroot in the configuration. ApplyStandardArgs still does: what a
project file reads in cfg.sysroot after the call stays what it was.

The directories a build writes keep their names: a configuration that
named no sysroot was built into the ones its VariantId named once
Build() had stored it, which are the ones it names now.

StdPcmFlags takes the toolchain, as StdPcmKey does, so that a VariantId
asked for under a toolchain resolves the sysroot under that one.
2026-11-14 23:42:47 +01:00
1440e20231
test(external): a sibling's pointers to its own Configuration hold
SiblingOwnPointers loads a fixture through LocalProject, on a fresh copy
outside the checkout: a library whose project file declares a test with
cfg.AddTest("OwnTest").Dependencies({ &cfg }). The one dependency of
that test has to be the Configuration LocalProject returns. The test
reads the dependency out of that Configuration and compares the two
addresses, without following the dependency.

Against the loader as it was before the fix the test fails: the
dependency is not that Configuration.
2026-11-14 23:42:47 +01:00
8baf14068e
fix(external): keep a sibling project's Configuration where it was built
A project file may take pointers to the Configuration it returns. The
usual one belongs to a test that links the library the file describes,
cfg.AddTest("T").Dependencies({ &cfg }): where the compiler constructs
the local the file returns in place of the return value, &cfg is the
address of what CrafterBuildProject returns.

For the project crafter-build is pointed at, that address stays good:
Run() initialises its Configuration with the call. For a project loaded
through GitProject or LocalProject it did not. LoadProjectFromRoot
assigned the call's result to a local, and from there the Configuration
was moved into the project cache, so what a consumer got was not the
object the project file had built, and every pointer the file had taken
to that one pointed at an object that no longer existed. RunLint follows
such a pointer: for a sibling whose path lies inside the project's
directory it works out the compile command of each of the sibling's
tests when a rule needs an AST, and GetCompileCommand walks the
dependencies of the configuration it is given.

LoadProjectFromRoot now makes the Configuration on the heap with the
call as its initialiser, and StoreProject takes the unique_ptr, so the
Configuration is constructed where the cache keeps it and is never
moved.
2026-11-14 20:19:19 +01:00
12e8b908f6
docs(packaging): add the 6.3.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 15m13s
6.3.0 holds a build to as many steps at once as the machine has
hardware threads, where every stale shader, asset to compress, C, CUDA
and C++ unit got a thread of its own and nothing bounded how many ran
at once. It makes the object of a module interface unit that an earlier
build left with its BMI alone, or with the object of before an edit,
and it refuses interface units of one configuration that import each
other, whose first build hung.

A minor, by the version rule: the notes have New and Fixes and nothing
Breaking, and Jorijn's "6.3.0, that's internal and not user facing"
settled it. What he was asked about: the range takes Compile() off
Module, ModulePartition and Implementation, and the `compiled` flag off
the first two, all of which interfaces/ exports. They are what Build()
itself compiled a unit with, and none of the 35 project.cpp files of
this checkout and the ones beside it reads the flag or calls Compile().
2026-11-13 17:59:56 +01:00
621438de5f
docs: say how many steps a build runs at once
The README says in "Writing a project.cpp" that a build runs at most as
many of its steps at once as the machine has hardware threads, which
steps those are, and that an ExternalDependency's CMake build and the
tests are not among them. Under Tests, --jobs= is named as what counts
the tests, and --jobs=1 as one test at a time where it said "serial
mode": the steps of that one test's build still run side by side.
2026-11-13 17:59:56 +01:00
f9d0ec24fe
test(incremental): an interface unit without its object is built again
IncrementalInterfaceObject builds a module with a partition and a
program that prints what the module's function returns, without
optimisation, so that what it prints says which object was linked. It
edits the primary interface, builds, and puts the object of before the
edit back dated two seconds before the new BMI. A build with the
program still there has to make the object again and link the program
again; after the old object is put back once more and the program
deleted, a build has to make the object again and the program print the
edited value. Then it deletes both objects and the program and builds:
both objects have to be back. A last build of the intact tree has to
leave the objects as they are.

On 5b75df3 the old object is never made again, and the build without
the program links it: the program prints 11 where the source says 12.
The build without the objects fails at the link with "no such file or
directory" for each of the two.
2026-11-13 17:59:56 +01:00
6087ce81db
test(build): build many units at once and count the threads it takes
JobLimit makes two projects and one more for every 32 hardware threads
and builds them from nothing at once, each from a thread of its own, as
RunTests builds its tests, while it counts the threads of its own
process. A project is 69 sources: 64 that import nothing, half C and
half C++, then a module of two partitions, one importing the other,
with its implementation unit, and a main.cpp that imports the module.
It is the same size on every machine, so that no command of its build
grows with the machine. The builds together may add as many threads as
the machine has hardware threads, and have to add at least two where
there are two; every program is then run and has to print 995: what
its 64 C and C++ functions return and the module's Top(), which is
built on the two partitions' functions. On 5b75df3 it fails: on a
machine with 56 hardware threads, "3 builds of 207 sources in all ran
on 205 threads at once". The count sees the steps that are jobs. A link
is none: its Build() runs it through RunBuildCommand from a thread that
was there before the count, which does not tell whether the link waited
for a worker.

JobGroup drives pools of its own, of one to four workers. Twelve jobs on
three workers run three at once and no more; a job starts after the
ones it was added after, in a graph of four jobs and in one of 300; the
first error keeps a job that comes after it and the jobs added later
from starting, and so does Fail(); what a job throws is its error; a
chain gets through one worker; Run() runs its work on a worker, on the
calling thread when that is one, where a JobGroup is refused; and
leaving a group's scope waits for the job that runs and starts no
other. It also holds the process's pool to a worker per hardware thread.
2026-11-13 17:59:55 +01:00
913310da86
feat(build): run a build's steps on one worker per hardware thread
Build() started a thread for every stale shader, asset, C, CUDA and C++
unit, and Module::Compile one more for every stale partition, and
nothing bounded how many of them ran their step at once. Jorijn asked
for the amount of parallelism to be limited by the amount of threads
instead of just starting one per file; the threads are taken here to be
the machine's hardware threads.

The new :Jobs partition holds the two pieces. JobPool is worker threads
behind one queue, started as jobs need them up to a fixed number, and
JobPool::Process() is the pool of the process: at most a worker per
hardware thread, one where std:🧵:hardware_concurrency does not
know. JobGroup is the jobs of one build on a pool. A job starts once
the jobs it was added after have finished; the first job to fail keeps
the ones that have not started from starting, and Wait() returns its
error. No job waits for another job, and a JobGroup made on a worker of
its own pool throws: a worker that waited for a job still in the queue
would hold the thread that job needs.

Build() adds what it did on those threads to a JobGroup instead, and
the group's first error replaces the buildCancelled and buildError pair
the threads set. The module units no longer block on the `compiled`
flag of the units they import: Schedule() replaces Compile() on Module,
ModulePartition and Implementation and adds a unit's jobs after the jobs
that write the BMIs it imports. An interface unit is two jobs, its BMI
and then its object from the BMI, so the units importing it start when
the first is done, as they did when one thread ran both commands and
raised the flag in between. A primary interface now waits for the BMIs
of its partitions and no longer for their objects. Each of the two jobs
has a progress line, "Precompiling X.cppm" and "Compiling X.cppm" for
every interface unit, where a module and its partitions shared one
"Compiling interface X".

RunBuildCommand runs its command on a worker of the process's pool: on
the calling thread when that is one, otherwise it waits for one. A link,
an archive, the std module's precompile and project.cpp's compile are
steps under the limit that way. The threads Build() starts per
dependency and per external dependency stay: one of the first runs the
dependency's own Build(), or waits for the thread that does, and one of
the second runs git and cmake.

With the BMI and the object as two jobs, a build that fails between them
has written the BMI and skips the object, and Check, which reads
staleness off the BMI, would call the unit built from then on.
Schedule() therefore 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
interrupted between the two commands, or one whose second command
failed, left the same behind before, and it stayed: the link took the
object of the source before the edit, or failed on the missing one.

ImportCycleError is now what keeps Schedule() from following a round of
imports without end.

The limit is on steps. Outside it, as AGENTS.template.md lists: an
ExternalDependency's cmake --build, which keeps its own --parallel of
as many jobs as there are hardware threads; the tests RunTests runs,
--jobs= of them at once as before; the Crafter.Build modules
EnsureCrafterBuildPcms precompiles one after another; and the threads a
step starts for itself, which lld does for a link and Crafter.Asset's
GDeflate compressor for an asset. The pool is one process's. The --help
text says what a build runs at once and that test --jobs= counts tests.

ConcurrentDependencyReset read the `compiled` flag, which is gone. It
asserts on `checked` and `scheduled` instead, the state a reset from
another build's thread would clear now, with a unit scheduled twice as
the result, and the comment in its fixture says what the implementation
unit comes after now. TransitiveInterfaceChange's comment names
Schedule() where it named Compile() as what honours a partition's
imports. Two comments in :Platform that spoke of worker threads, a word
that now means the pool's, name the threads they mean. The bug-prover
lens's section said shaders compile on a thread of their own each, and
describes the pool now.
2026-11-13 17:59:55 +01:00
eff9868b68
docs: interface units that import each other stop the build
The README says in "Writing a project.cpp" that a unit is built after
the modules and partitions it imports, that interface units of one
configuration that import each other are refused with an error naming
them, and that 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 can make such a round in a project the
compiler accepts.
2026-11-13 17:59:55 +01:00
ee331377a4
test(build): interface units that import each other are refused
ImportCycle builds three fixtures as static libraries, each on a fresh
copy outside the checkout: two partitions that import each other, a
partition that imports its own module, and two modules that import each
other. Each build has to return an error that holds its round,
"Ring:First -> Ring:Second -> Ring:First", "Own -> Own:Part -> Own" and
"East -> West -> East", and leave neither a build nor a bin directory.

Before the refusal the test ran into its timeout: the first of those
builds never returned.
2026-11-13 17:59:55 +01:00
e87dc4f015
fix(build): refuse interface units that import each other
Two partitions that import each other, a partition that imports its own
module, and two modules of one configuration that import each other
cannot be built in any order. Build() compiles each stale unit on a
thread that first waits for the units its unit imports, and a primary
interface waits for every stale partition of its module as well, so a
build that found every unit of such a round stale, as a first build of
them does, hung: every thread waiting, no compiler running, no error.

ImportCycleError follows the imports of a configuration's interface
units at the top of that configuration's Build(), before it makes a
directory or builds a dependency, and Build() returns an error naming
the units of the first round it finds in the order they wait in,
"Ring:First -> Ring:Second -> Ring:First". A primary interface counts
as coming after each partition of its module, whether it imports that
one or not, since that is how it is built. A configuration built on the
one refused has started its own build by then: the check reads the
imports ResolvePendingImports has just placed, which are that Build()'s
to read while it runs.

The imports are the ones the source scanner reads, and it reads one in a
string literal, in a comment that spans lines or under #if 0 as it
reads any other (issue #45), so the units the error names are where to
look for one of those too. The error says so, since the compiler sees
no round in such a project, and AGENTS.template.md has it under Gotchas.
2026-11-13 17:59:55 +01:00
160 changed files with 8668 additions and 1217 deletions

View file

@ -13,9 +13,26 @@ The execution contexts to enumerate, beside the charter's:
Running a test or a built artifact is a shell command too (`:Test`,
`:Clang`). A path, file name or flag that reaches one with a space or a
shell metacharacter in it is an input to attack. Other steps run inside
the process, among them glslang's shader compiles, on a thread of their
own per stale shader (`:Shader`), and lint's parse through the libclang
the linter dlopens (`:Lint`).
the process, among them glslang's shader compiles (`:Shader`), the
compression of an asset in Crafter.Asset, which starts threads of its own
(`:Asset`), and lint's parse through the libclang the linter dlopens
(`:Lint`).
- A build's steps run as jobs on the workers of `JobPool::Process()`
(`:Jobs`): up to as many threads as the machine has hardware threads, one
where that is one or unknown. The compiles of a configuration's stale
shaders, C, CUDA and C++ units, the compression of its stale assets, and
its copies of `cfg.files` and of the other files of an asset directory
go through the `JobGroup` of its `Build()`, which starts a job once the
jobs it was added after have finished; a `RunBuildCommand` waits for a
worker when its caller is not one. Jobs are waited for by threads that
are not workers, among them one that runs a `Build()` (its caller's, one
of `RunTests`', one of `BuildAll`'s, one a `Build()` starts per
dependency) and the one that loads a project file (`LoadConfigurations`,
`LoadProject`), for the compiles of the std module and of
`project.cpp`. The threads a `Build()` starts per external dependency are
not workers either and wait for no job: they run git and cmake. An
executable's copies of what its dependencies forward run on the thread of
its `Build()`.
- Several crafter-build processes share `~/.cache/crafter.build/` at once:
the std and Crafter.Build PCMs per target and march (the
`ConcurrentCacheRace` test), and the external clones with their `.lock`

View file

@ -4,7 +4,7 @@ Guidance for coding agents and contributors working on crafter-build itself. The
## Project overview
crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process.
crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`, or several of them; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process.
| Path | What lives there |
|---|---|
@ -16,22 +16,23 @@ crafter-build is a C++26 modules build system. A project is described by a `proj
| `examples/` | Standalone user-facing projects, MIT licensed. |
| `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. |
| `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. |
| `lib/` | Vendored third-party headers (nlohmann/json, glslang's DirStackFileIncluder). Do not edit. |
| `lib/` | Vendored third-party headers (glslang's DirStackFileIncluder). Do not edit. |
| `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. |
| `.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:
- `: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.
- `: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.
- `: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 `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code.
- `:Interface` and `:Implementation` model module units, their staleness checks and their compiles.
- `: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()`.
- `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`).
- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`.
- `:Test` holds `AddTest`, `RunTests` and `TestRunner`.
- `: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`.
- `: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 `cfg.scripts`, 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 Configuration `GitProject` and `LocalProject` return has its `path` rebased.
- `: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.
- `:Progress` is console output. `:Shader` compiles shaders through glslang. `:Asset` is the hook into Crafter.Asset.
- `:Flatpak` is an executable packaged as a Flatpak: `FlatpakApp` (app-id, runtime, permissions, desktop file, metainfo, icons, share entries, modules), the writer of its `files/`, which becomes `/app` in the app's sandbox, and what makes the app of that for `install` and `bundle`: the host's `flatpak build-finish`, which writes the metadata and `export/` by flatpak's own rules, then `flatpak build-export` into a repo, or flatpak-builder from a generated manifest when there are modules. It works on plain data; `Build()` and the `InstallFlatpakApp` and `BundleFlatpakApp` of `:Clang` gather it from the Configuration. The host's flatpak and flatpak-builder are reached through `RunHostFlatpak` and `RunHostFlatpakBuilder` in `:Platform`.
@ -39,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.
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.
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.
```bash
./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/
@ -50,7 +51,7 @@ Three things to know about this loop:
- `bin/crafter-build` is the bootstrap binary and the harness for every command below. The self-host build writes to `bin/crafter.build-exe-<variant>/crafter-build` and does not replace it.
- Changes under `implementations/` are picked up by the self-host build and by the tests, which link the local library. Changes under `interfaces/` are not: the harness compiles against the copies in `share/crafter-build/` and the PCM cache built from them, so a new or changed declaration is invisible until you run `./build.sh` again. The symptom is `use of undeclared identifier` for the symbol you just added. A changed default member initialiser has no symptom at all: `project.cpp` compiles against the old one and quietly gets the old default, as `project.cpp`'s sibling loads do with a harness that predates `GitProjectSpec::args = ProjectArgs()`.
- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and `LoadProject` fails with an undefined symbol.
- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and loading `project.cpp` fails with an undefined symbol.
`./build.sh` clones and builds glslang on first run and takes several minutes; later runs are faster. `./bin/crafter-build clean` deletes `bin/` and `build/` without loading `project.cpp`. That takes `bin/crafter-build` itself with it, and `build/flatpak`, the state of the local Flatpak build (see "CI and publishing"): about 4 GB after a first run, and the next `run flatpak` rebuilds LLVM. Set `CRAFTER_BUILD_HOME` only when running a binary from outside this tree; `CRAFTER_BUILD_MARCH` and `CRAFTER_BUILD_MTUNE` default to `native`.
@ -80,7 +81,7 @@ Tests are declared, not discovered. Each one is a line in `project.cpp`:
cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() });
```
The source is `tests/<Name>/main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so `import Crafter.Build;` resolves to the code in this checkout. A test that calls `LoadProject` also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today.
The source is `tests/<Name>/main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so the engine it calls is the one built from this checkout. A test that loads a project file, through `LoadConfigurations`, `LoadProject`, `LocalProject`, `GitProject` or `Run()`, also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today.
A test is an ordinary `int main()`. Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout.
@ -89,9 +90,10 @@ 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.
- 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.
- 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.
- 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.
- 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.
- `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 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.
@ -121,7 +123,10 @@ Beyond the rules:
- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule.
- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests.
- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`.
- Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its `JobGroup` in `Build()`, after the jobs whose output it reads; run a step that stands by itself, as a link does, through `RunBuildCommand`, which runs on a worker of `JobPool::Process()` whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: a `JobGroup` made on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group.
- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`.
- `ObjectPath()` names the object of a `.cpp`, `.c` or `.cu`, from where its source lies: `objects/a/Thing_impl.o` in the build directory for `a/Thing.cpp`. Do not name one from its source's file name: two sources of one name in different directories then share an object, each compiled over the other (issue #50). A step that takes every object of a configuration reads them from a response file, as the link does, and not from its command, which the system holds to a length.
- A static library's archive and the list of objects a step reads are written under another name beside them and renamed into place (`WrittenBeside` and `MoveIntoPlace` in `Crafter.Build-Clang.cpp`), not removed first or written over where they lie: a link or archive step of another crafter-build may be reading them. Two crafter-builds can build a project loaded with `GitProject` at once, in the clone the cache keeps for its source, and one then links against the library, or reads that list, while the other writes it. Write anything else such a step reads the same way.
- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory.
## Design rules
@ -157,11 +162,12 @@ 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.
- 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.
- `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; keep it that way.
- `--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.
- 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.
- 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/`. Keep it that way.
- 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.
## CI and publishing
@ -196,8 +202,12 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary:
- A new partition is listed in four places, in import order: `PARTITIONS` in `build.sh`, `CrafterBuildModules` in `Crafter.Build-Platform.cpp`, both arrays in `project.cpp`, and the umbrella `Crafter.Build.cppm`. Then `./build.sh`.
- A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away.
- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard.
- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because loading a project file fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard.
- `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache.
- 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.
- 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.
- 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.
- 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.
@ -205,6 +215,7 @@ 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.
- 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 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`.
- `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.

104
README.md
View file

@ -1,6 +1,6 @@
# Crafter Build
A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a `project.cpp` that constructs a `Configuration` and returns it. Crafter Build compiles, loads, and executes it.
A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a `project.cpp` that constructs a `Configuration`, or several, and returns them. Crafter Build compiles, loads, and executes it.
## Install
@ -18,7 +18,7 @@ Releases are published to the `stable` branch that the commands above install, a
## Writing a project.cpp
Crafter Build loads a `project.cpp` from the current directory. The file exports one function that returns a populated `Configuration`:
Crafter Build loads a `project.cpp` from the current directory. The file exports one function: `CrafterBuildProject`, which returns a populated `Configuration`, or `CrafterBuildConfigurations` for [several](#several-configurations):
```cpp
import std;
@ -43,6 +43,56 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
Run `crafter-build` in that directory, outputs land at `bin/myapp-<target>-<march>-<mtune>-<hash>/myapp` and intermediates at `build/myapp-<target>-<march>-<mtune>-<hash>/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build, in its own directory, where its shaders, `cfg.files` and assets are; a wasm32 one runs under wasmtime, or wasmer where there is no wasmtime, with no directory given to it, and one built for the browser (`EnableWasiBrowserRuntime`) is served over HTTP from that directory instead.
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.
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.
### Several configurations
A project that builds more than one thing, such as a library and the tool that comes with it or the programs of one repository, returns all of them from `CrafterBuildConfigurations` instead. They need not have anything to do with each other, and `crafter-build` builds every one of them:
```cpp
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view> args) {
static std::deque<Configuration> owned;
Configuration& lib = owned.emplace_back();
lib.path = "./";
lib.name = "mylib";
lib.outputName = "mylib";
lib.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 1> libIfaces = { "interfaces/MyLib" };
std::array<fs::path, 1> libImpls = { "implementations/MyLib" };
lib.GetInterfacesAndImplementations(libIfaces, libImpls);
Configuration& tool = owned.emplace_back();
tool.path = "./";
tool.name = "mytool";
tool.outputName = "mytool";
tool.type = ConfigurationType::Executable;
tool.dependencies = { &lib };
std::array<fs::path, 0> toolIfaces = {};
std::array<fs::path, 1> toolImpls = { "implementations/main" };
tool.GetInterfacesAndImplementations(toolIfaces, toolImpls);
return { &lib, &tool };
}
```
A project file has one of the two functions, never both. `CrafterBuildConfigurations` gets the same args as `CrafterBuildProject`, and `ProjectArgs()` and `IsTopLevelProject()` answer the same inside it. It returns pointers, so the configurations have to stay where they are for as long as crafter-build runs. A `std::deque` that the file only adds to keeps them there, with a new set for every call; a `std::vector` would move them when it grows, and a single static `Configuration` would be filled in again by every load of the file. A pointer that `GitProject` or `LocalProject` returned can be in the list as well, which is how one file builds a set of sibling projects.
With several configurations:
- **A build** builds all of them in one pass, so what two of them depend on is built once. One that fails does not stop the others, and the build then fails with the errors of the ones that failed.
- **`test`** runs the tests of every one the file made itself, in one run. By default a test is built from `tests/<Name>/` into `build/<Name>-<variant>/` and `bin/<Name>-<variant>/`, whichever configuration declares it, so a test belongs to one of them: where two each declare a test that would be built into the same directories, both tests fail without being built and name the two configurations. Give each test a name of its own.
- **`run`** offers the scripts of every one the file made itself: a script gets the configuration it is declared on as `ctx.project`, and a name two of them declare is an error.
- **`lint`** and **`format`** take the rules and the sources of every one that lies in the project's directory, and a rule two of them register under one name runs once.
- **`-r`** runs the executable when exactly one of them is one, and **`install`** and **`bundle`** export the one that is packaged as a Flatpak. With more than one to choose from they stop and name them, as `install` and `bundle` do when none is packaged: `-r` once everything is built, `install` and `bundle` before anything is.
- **A configuration of another project**, which the file got from `GitProject` or `LocalProject` and returns, is built with the rest and counts for `-r`, `install` and `bundle`. Its tests and its scripts stay that project's.
- **Two that would be built into the same directory**, as two with the same `path` and `name` and no other difference are, are refused by a build, `test`, `-r`, `install` and `bundle`, before anything is built. Give each a `name` of its own. A build, `-r`, `install` and `bundle` refuse two more sets before they build anything: configurations that are each built on something of another's directory, so that none could be built first, and one that is built on something of its own directory when another is built on that directory as well.
- **`cfg.dependencyNotes`** is read on every one the file made itself (see [Dependency notes for agents](#dependency-notes-for-agents)).
## Flatpak output
A program crafter-build's Flatpak links for Linux without a sysroot takes the libc++, libc++abi and libunwind of its LLVM and the glibc of its runtime, so outside the Flatpak it starts only on a host that has those libraries and a glibc with every symbol version they and the program reference, 2.38 or newer for the bundled libc++. A build lays the program out as a Flatpak of its own when it is packaged:
@ -132,13 +182,21 @@ Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project.
cfg.dependencies = { math };
```
The sibling's `CrafterBuildProject` 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 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 default is read when the spec is made, so make it inside `CrafterBuildProject`, 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.
Clones share the external cache and identical specs share one `Configuration`. An unpinned source is `git pull`ed on every invocation, set `.commit` for reproducible, offline-after-first-fetch builds.
A project loaded this way runs its `CrafterBuildProject` as a dependency, and `IsTopLevelProject()` is `false` while it does (`true` in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's `project.cpp` from inside crafter-build and recurse.
A sibling whose project file returns [several configurations](#several-configurations) gives its first one, or the one `.configuration` names by its `name`:
```cpp
Configuration* packer = LocalProject({ .projectFile = "../tools/project.cpp", .configuration = "packer" });
```
Only the configuration a consumer names is built for it, with what that one depends on, and specs that differ only in `.configuration` share one load of the sibling. A name the sibling does not have is an error that lists the ones it has, and a name two of its configurations share is an error too. A library that comes to return a second configuration puts it after the first, so that a consumer that names none keeps getting the one it had. Its consumers then need a crafter-build that has `CrafterBuildConfigurations`: an older one loads only a `CrafterBuildProject`.
A project loaded this way runs its entry point as a dependency, and `IsTopLevelProject()` is `false` while it does (`true` in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's `project.cpp` from inside crafter-build and recurse.
### Dependencies of project.cpp itself
@ -155,7 +213,7 @@ import Crafter.LintRules;
#pragma crafter dependency "<source>" [branch "<name>" | commit "<sha>"] [project "<file>"]
```
Such a dependency is built for the host, whatever the project targets, and its `project.cpp` gets none of the project's args.
Such a dependency is built for the host, whatever the project targets, and its `project.cpp` gets none of the project's args. Of a project that returns [several configurations](#several-configurations), the dependency is the first.
### Dependency notes for agents
@ -191,7 +249,7 @@ What a build then writes:
- The section goes after the template's text and a blank line. To have it elsewhere, put the begin and end marker lines in the template where it should go: whatever they enclose is replaced. A template moved over from a committed `AGENTS.md` has them where its section was, around notes that can be deleted.
- `AGENTS.md` is written only when its text changes, in place, so a `CLAUDE.md` linked to it, its ownership and a read-only `AGENTS.md` are respected. An edit made in it is gone after the next build, and a fresh clone has none until its first build. The template is never written.
- An `AGENTS.md` that no build wrote, such as a committed one still next to a new template, is never replaced: each build warns instead, until it is deleted. Without a template, `AGENTS.md` is never touched. One that still holds a section from crafter-build 3.0.0, which kept the notes in a committed `AGENTS.md`, gets a warning: move it over as above, or delete the section.
- The update runs once `project.cpp` has loaded and before the project compiles, so a build that fails still has the notes. A `project.cpp` that fails to load gets no update. `test --list`, `lint`, `format`, `run` and `clean` leave the file alone, and so does an `install` or `bundle` refused before building.
- In a build or a test run that is not refused before it starts, the update runs once `project.cpp` has loaded and before the project compiles, so a build that fails while it compiles still has the notes. It does not run for a `project.cpp` that fails to load, for `test --list`, `lint`, `format`, `run` and `clean`, or for a verb that is refused before it starts a build: an `install` or `bundle` of a project that is not packaged as a Flatpak, or for which crafter-build cannot run the host's flatpak, and a build, `test`, `install` or `bundle` of [several configurations](#several-configurations) that are refused as a set.
- The section follows what the build loaded: a dependency that only some flags pull in (a `--target=`, a flag of the project's own) comes and goes with them. An unpinned dependency's notes follow its default branch, as its code does, so the section can change on any build. Pin a `commit` to decide when.
- A library reached through two specs, pinned at one revision here and another further down, is described once, as the nearer one has it.
- When there are notes to write, unbalanced markers in the template leave `AGENTS.md` as it is, with a warning. A notes file that would break the section (a code block it never closes, a marker line of its own) is left out, also with a warning. Markers quoted inside a fenced code block don't count.
@ -206,6 +264,8 @@ What a build then writes:
Three things never count: the project's own `AGENTS.consumer.md`; its tests' dependencies, since a plain build never looks at the tests; and a dependency's `#pragma crafter dependency` tooling, which is about how the dependency is built, not how it is used.
In a project of [several configurations](#several-configurations), the `dependencyNotes` of each one the file made itself selects among what that one is built against, and a dependency's notes are in when a configuration that asks for them leads to it: what a `Direct` configuration names is followed further when a `Transitive` one reaches it too. The project's own `#pragma crafter dependency` tooling, and a configuration of another project that the file returns, which counts as a dependency here, go by the widest setting among the configurations the file made itself.
## CUDA
`cfg.cuda` lists CUDA sources, named without `.cu`. A relative name is read from the directory crafter-build runs in, except in a project loaded through `GitProject` or `LocalProject`, whose relative names crafter-build rebases onto that project's directory:
@ -239,8 +299,9 @@ Test conventions:
- **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.
- Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()`.
- Stdout+stderr is captured and printed atomically on completion. Failed/crashed/timed-out tests also write to `build/test-logs/<name>.log`.
- 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.
- 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.
- A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run.
CLI:
@ -251,8 +312,9 @@ crafter-build test 'Unit*' # glob-filter te
crafter-build test --list # enumerate without running
crafter-build test --target=x86_64-w64-mingw32 # only tests for this target
crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine
crafter-build test --jobs=1 # serial mode
crafter-build test --jobs=1 # one test at a time
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.
@ -315,6 +377,24 @@ 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).
### 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
A test fixture can depend on the project's own library so it can `import` and exercise its API:
@ -423,7 +503,7 @@ cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) {
| Member | Meaning |
|---|---|
| `project` | the `Configuration` that `project.cpp` returned. Read the project through this; a `cfg` captured by reference is gone by the time a script runs |
| `project` | the `Configuration` the script is declared on: the one `project.cpp` returned, or of several the one whose `scripts` holds it. Read the project through this rather than through a `cfg` captured by reference |
| `projectDir` | absolute directory of the project file |
| `args` | everything typed after the script's name, untouched |
| `Run(command)` | run a shell command with the terminal attached and return its exit code |
@ -482,7 +562,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 [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.
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.
## Copyright

View file

@ -47,7 +47,7 @@ cp wasi-runtime/index.html.in share/crafter-build/wasi-runtime/
# Partition order is the import order: every unit is listed before the
# units that import it, and the umbrella last.
PARTITIONS="Toolchain Shader Platform Flatpak Interface Implementation External Agents Clang Test Lint Script Progress Asset"
PARTITIONS="Toolchain Shader Platform Flatpak Jobs Interface Implementation External Agents Clang Test Lint Script Progress Asset"
cp interfaces/Crafter.Build.cppm share/crafter-build/
for p in $PARTITIONS; do

View file

@ -37,6 +37,7 @@ builder methods overlay overrides:
- `.Dependencies({ &otherCfg, ... })`
- `.Path(p)` &mdash; rebase the test's source-resolution path
- `.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

View file

@ -345,18 +345,60 @@ namespace {
return DependencyNote{ .name = name, .text = std::move(note.text) };
}
// The loaded projects `configs` lead to without passing through another
// loaded project, in the order the configurations name them: one ring
// further out. `walked` spans the whole collection, so each
// Configuration is looked at once however many paths reach it.
std::vector<const Configuration*> NextRing(std::span<const Configuration* const> configs, std::unordered_set<const Configuration*>& walked) {
// Tells a configuration of another project from one of the project
// whose AGENTS.md is written, the one of the project file it is made
// with. GitProject and LocalProject hold the configurations of a project
// file they loaded, so held or not does not tell the two apart: the
// project whose notes are written may itself have been loaded through
// one of them, by a program that then writes its AGENTS.md for it. Two
// files are one project file when they resolve to one path, which is
// how the loader tells project files apart: a hard link to the project
// file in another directory is another project's. Each loaded project's
// file is compared with the project file once and the answer kept, so a
// configuration is the same thing every time one collection asks,
// whatever happens to the files meanwhile.
class OtherProjects {
public:
explicit OtherProjects(const fs::path& projectFile) {
// Left empty when the file cannot be resolved, and then no
// loaded project's file is it.
std::error_code ec;
projectFile_ = fs::canonical(projectFile, ec);
if (ec) projectFile_.clear();
}
// The project `cfg` was loaded from when that is another one;
// nullopt for a configuration the project's own file made.
std::optional<LoadedProject> Of(const Configuration& cfg) {
std::optional<LoadedProject> loaded = LoadedProjectOf(cfg);
if (!loaded) return loaded;
const auto [known, added] = same_.try_emplace(loaded->projectFile, false);
if (added && !projectFile_.empty()) {
std::error_code ec;
const fs::path file = fs::canonical(loaded->projectFile, ec);
known->second = !ec && file == projectFile_;
}
if (known->second) loaded.reset();
return loaded;
}
private:
// The project file, resolved.
fs::path projectFile_;
// By a loaded project's file: whether it is projectFile_.
std::unordered_map<fs::path, bool> same_;
};
// The other projects `configs` lead to without passing through another
// of them, in the order the configurations name them: one ring further
// out. `walked` spans the whole collection, so each Configuration is
// looked at once however many paths reach it.
std::vector<const Configuration*> NextRing(std::span<const Configuration* const> configs, std::unordered_set<const Configuration*>& walked, OtherProjects& others) {
std::vector<const Configuration*> ring;
std::vector<const Configuration*> pending(configs.rbegin(), configs.rend());
while (!pending.empty()) {
const Configuration* cfg = pending.back();
pending.pop_back();
if (!cfg || !walked.insert(cfg).second) continue;
if (LoadedProjectOf(*cfg)) {
if (others.Of(*cfg)) {
ring.push_back(cfg);
continue;
}
@ -365,21 +407,72 @@ namespace {
return ring;
}
// The AGENTS.consumer.md of every project `project` depends on, as
// project.dependencyNotes selects them, ring by ring: first the loaded
// projects (the ones GitProject and LocalProject returned) that its
// `#pragma crafter dependency` lines and its configurations name, in
// that order, then the ones those depend on. Its own configurations, and
// a dependency's internal ones, are only walked through. Direct stops
// after the first ring.
// The AGENTS.consumer.md of every project the project is built against,
// as the dependencyNotes of `configurations`, the configurations its
// project file returns, select them, ring by ring: first the other
// projects (the ones GitProject and LocalProject loaded from another
// project file) that its `#pragma crafter dependency` lines and its
// configurations name, in that order, then the ones those depend on.
// Its own configurations, and a dependency's internal ones, are only
// walked through.
//
// Each configuration the file made itself selects for what it is built
// against: None nothing, Direct the first ring from it, Transitive every
// ring. Another project therefore has its own dependencies followed
// when a Transitive configuration leads to it, at whatever depth, and
// not when only Direct ones do. The pragma lines belong to the file and
// not to one configuration, and a configuration the file loaded from
// another project and returns is a project of the first ring itself,
// with a setting that is that project's own: both go by the widest
// setting among the configurations the file made, and by Transitive
// when it made none.
//
// Never walked: the project's tests, since a plain build never touches
// them and a test's dependency can point at the Configuration the project
// file returned by value, which has since moved; and a dependency's own
// pragma tooling, which is about how the dependency is built, not how it
// is used, and is no `dependencies` edge to begin with.
std::vector<DependencyNote> CollectNotes(const Configuration& project, const fs::path& projectFile, const fs::path& projectDir) {
std::unordered_set<const Configuration*> walked = { &project };
// them and a test's dependency can point at the Configuration a
// CrafterBuildProject returned by value, which a caller of LoadProject
// may have moved since; and a dependency's own pragma tooling, which is
// about how the dependency is built, not how it is used, and is no
// `dependencies` edge to begin with.
std::vector<DependencyNote> CollectNotes(std::span<const Configuration* const> configurations, const fs::path& projectFile, const fs::path& projectDir) {
OtherProjects others(projectFile);
const auto made = [&](const Configuration* cfg) { return !others.Of(*cfg); };
const auto asks = [&](DependencyNotes setting) {
return std::ranges::any_of(configurations, [&](const Configuration* cfg) { return made(cfg) && cfg->dependencyNotes == setting; });
};
const bool transitive = asks(DependencyNotes::Transitive) || std::ranges::none_of(configurations, made);
if (!transitive && !asks(DependencyNotes::Direct)) return {};
// Where the walk starts, and the starts that ask for every ring.
std::vector<const Configuration*> start;
std::vector<const Configuration*> deep;
for (const Configuration* dep : PragmaDependencies(projectFile)) {
start.push_back(dep);
if (transitive) deep.push_back(dep);
}
for (const Configuration* cfg : configurations) {
const DependencyNotes setting = made(cfg) ? cfg->dependencyNotes : transitive ? DependencyNotes::Transitive : DependencyNotes::Direct;
if (setting == DependencyNotes::None) continue;
start.push_back(cfg);
if (setting == DependencyNotes::Transitive) deep.push_back(cfg);
}
// Every other project those lead to: the ones whose own
// dependencies are followed. Worked out ahead of the walk below,
// which meets each project once, at its nearest ring, and that can
// be a ring a Direct configuration put it in.
std::unordered_set<const Configuration*> followed;
{
std::unordered_set<const Configuration*> reached;
for (std::vector<const Configuration*> ring = NextRing(deep, reached, others); !ring.empty();) {
std::vector<const Configuration*> next;
for (const Configuration* cfg : ring) {
followed.insert(cfg);
next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end());
}
ring = NextRing(next, reached, others);
}
}
std::unordered_set<const Configuration*> walked;
// The project's own notes are for its consumers, so they never go
// into its own AGENTS.md, whatever dependency they sit beside. Both
// places count for a symlinked project file.
@ -389,13 +482,11 @@ namespace {
std::unordered_set<std::string> identities;
std::vector<DependencyNote> notes;
std::vector<const Configuration*> start;
for (const Configuration* dep : PragmaDependencies(projectFile)) start.push_back(dep);
start.insert(start.end(), project.dependencies.begin(), project.dependencies.end());
for (std::vector<const Configuration*> ring = NextRing(start, walked); !ring.empty();) {
for (std::vector<const Configuration*> ring = NextRing(start, walked, others); !ring.empty();) {
std::vector<const Configuration*> next;
for (const Configuration* cfg : ring) {
const std::optional<LoadedProject> loaded = LoadedProjectOf(*cfg);
// Another project's, or NextRing had walked through it.
const std::optional<LoadedProject> loaded = others.Of(*cfg);
const fs::path file = loaded->projectFile.parent_path() / NotesFileName;
// One library under two specs (a pin here, another revision
// further down) is described once, as the ring nearest the
@ -403,10 +494,9 @@ namespace {
if (identities.insert(loaded->identity).second && files.insert(file).second) {
if (std::optional<DependencyNote> note = ReadNote(file, loaded->name)) notes.push_back(std::move(*note));
}
next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end());
if (followed.contains(cfg)) next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end());
}
if (project.dependencyNotes == DependencyNotes::Direct) break;
ring = NextRing(next, walked);
ring = NextRing(next, walked, others);
}
return notes;
}
@ -504,6 +594,11 @@ std::string Crafter::MergeDependencyNotes(std::string_view templateMd, std::span
}
bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& projectFile) {
std::array<const Configuration*, 1> one = { &project };
return UpdateAgentsMd(std::span<const Configuration* const>(one), projectFile);
}
bool Crafter::UpdateAgentsMd(std::span<const Configuration* const> configurations, const fs::path& projectFile) {
std::error_code ec;
// Beside the project file as it was named, so a symlinked project.cpp
// keeps the AGENTS.md beside the link.
@ -527,7 +622,7 @@ bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& proje
return false;
}
const std::vector<DependencyNote> notes = project.dependencyNotes == DependencyNotes::None ? std::vector<DependencyNote>() : CollectNotes(project, projectFile, projectDir);
const std::vector<DependencyNote> notes = CollectNotes(configurations, projectFile, projectDir);
std::string wanted;
try {
wanted = std::format("{}{}{}", GeneratedLine, LineEnd(templateMd), MergeDependencyNotes(templateMd, notes));

File diff suppressed because it is too large Load diff

View file

@ -336,29 +336,33 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std:
namespace {
std::mutex ProjectCacheMutex;
std::unordered_map<std::string, std::unique_ptr<Configuration>> ProjectCache;
// Keyed by the Configurations ProjectCache owns, which live as long as
// the process does, so the pointers never dangle. Guarded by
// ProjectCacheMutex as well.
// What each project file loaded here returned, in the file's order, by
// spec and args. An entry is never changed or removed once it is in.
std::unordered_map<std::string, std::vector<Configuration*>> ProjectCache;
// Keyed by the Configurations ProjectCache holds, which live as long as
// the process does (see LoadConfigurations), so the pointers never
// dangle. Guarded by ProjectCacheMutex as well.
std::unordered_map<const Configuration*, LoadedProject> LoadedProjects;
// The configurations a loaded project keeps to itself, with the project:
// what the configurations its file returned led to when the file was
// loaded and the file did not return. A configuration leads to what it
// is built on and to the configurations of its tests, and each of those
// leads on in the same way. Taken down at that moment, since a consumer
// may add to the `dependencies` of a configuration it was given, and
// what it adds is its own. Guarded by ProjectCacheMutex as well.
std::unordered_map<const Configuration*, LoadedProject> KeptConfigurations;
// Run the dep's project.cpp from its own directory so its relative paths
// (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep
// root, then rebase cfg.path and all other relative path collections to
// absolute so Build() can run from any cwd without misresolving them.
// The mutex is NOT held across LoadProject — the dep may itself call
// GitProject/LocalProject, and a non-recursive lock would deadlock.
Configuration LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span<const std::string_view> args) {
fs::path savedCwd = fs::current_path();
Configuration cfg;
fs::current_path(depRoot);
try {
cfg = LoadProject(projectPath, args);
} catch (...) {
fs::current_path(savedCwd);
throw;
// What the cache holds under `fullHash`, or nullptr.
const std::vector<Configuration*>* CachedProject(const std::string& fullHash) {
const std::lock_guard lock(ProjectCacheMutex);
const auto it = ProjectCache.find(fullHash);
return it == ProjectCache.end() ? nullptr : &it->second;
}
fs::current_path(savedCwd);
// cfg.path and every other relative path collection of `cfg`, made
// absolute against `depRoot`, so Build() can run from any cwd without
// misresolving them.
void RebaseOnto(Configuration& cfg, const fs::path& depRoot) {
cfg.path = fs::absolute(depRoot / cfg.path).lexically_normal();
auto abs = [&](const fs::path& p) -> fs::path {
return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal();
@ -378,22 +382,81 @@ namespace {
for (auto& entry : cfg.flatpak.share) {
if (!entry.source.empty()) entry.source = abs(entry.source);
}
return cfg;
}
// Into ProjectCache under `fullHash`, with `loaded` recorded beside it.
// When another thread stored the same spec first, its Configuration
// wins and `cfg` is dropped.
Configuration* StoreProject(std::string fullHash, Configuration cfg, LoadedProject loaded) {
std::lock_guard lock(ProjectCacheMutex);
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
return it->second.get();
// Run the dep's project.cpp from its own directory so its relative paths
// (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep
// root, then rebase every configuration it returns onto that root.
// The mutex is NOT held across the load — the dep may itself call
// GitProject/LocalProject, and a non-recursive lock would deadlock.
std::vector<Configuration*> LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span<const std::string_view> args) {
fs::path savedCwd = fs::current_path();
std::vector<Configuration*> configurations;
fs::current_path(depRoot);
try {
configurations = LoadConfigurations(projectPath, args);
} catch (...) {
fs::current_path(savedCwd);
throw;
}
auto stored = std::make_unique<Configuration>(std::move(cfg));
Configuration* ptr = stored.get();
ProjectCache.emplace(std::move(fullHash), std::move(stored));
LoadedProjects.emplace(ptr, std::move(loaded));
return ptr;
fs::current_path(savedCwd);
for (Configuration* cfg : configurations) {
// One the file loaded from another project file and returns
// itself was rebased onto that project's root when it was
// loaded, and other consumers may be reading it by now.
if (!LoadedProjectOf(*cfg)) RebaseOnto(*cfg, depRoot);
}
return configurations;
}
// Into ProjectCache under `fullHash`, with `loaded` recorded beside each
// configuration that is not another project's already, and beside what
// those are built on and the file kept to itself. When another thread
// stored the same spec first, what it stored wins.
const std::vector<Configuration*>& StoreProject(std::string fullHash, std::vector<Configuration*> configurations, const LoadedProject& loaded) {
const std::lock_guard lock(ProjectCacheMutex);
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
return it->second;
}
// What this file returned, and then what each of those leads to:
// what it is built on and the configurations of its tests. One that
// another project's file returned is that project's, and so is what
// is found from there.
std::vector<const Configuration*> pending;
const auto leadsTo = [&pending](const Configuration& cfg) {
pending.insert(pending.end(), cfg.dependencies.begin(), cfg.dependencies.end());
for (const Test& test : cfg.tests) pending.push_back(&test.config);
};
for (const Configuration* cfg : configurations) {
if (LoadedProjects.try_emplace(cfg, loaded).second) leadsTo(*cfg);
}
while (!pending.empty()) {
const Configuration* kept = pending.back();
pending.pop_back();
if (!kept || LoadedProjects.contains(kept) || !KeptConfigurations.try_emplace(kept, loaded).second) continue;
leadsTo(*kept);
}
return ProjectCache.emplace(std::move(fullHash), std::move(configurations)).first->second;
}
// The one of `configurations` a spec asks for by `name`: the first for
// an empty name. `what` names the spec in the error for a name that none
// has, or that two have.
Configuration* PickConfiguration(std::span<Configuration* const> configurations, std::string_view name, std::string_view what) {
if (name.empty()) return configurations.front();
Configuration* picked = nullptr;
for (Configuration* cfg : configurations) {
if (cfg->name != name) continue;
if (picked) throw std::runtime_error(std::format("{}: two of its configurations are named '{}', so the name picks neither", what, name));
picked = cfg;
}
if (picked) return picked;
std::string names;
for (const Configuration* cfg : configurations) {
if (!names.empty()) names += ", ";
names += cfg->name;
}
throw std::runtime_error(std::format("{}: no configuration named '{}' (it has: {})", what, name, names));
}
// `url` as it names a repository: without user info, which is where a
@ -415,10 +478,11 @@ namespace {
Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
// Two hashes: the clone is shared across specs that point at the same
// source revision (forwarded args don't change what gets cloned, just
// how the dep's project.cpp interprets them at runtime), while the
// in-memory Configuration is keyed by the full spec so each (args)
// permutation gets its own Configuration object, and host tooling one
// apart from the target's even for the same args.
// how the dep's project.cpp interprets them at runtime), while what the
// file returned is keyed by the args as well, so each (args)
// permutation gets its own Configuration objects, and host tooling ones
// apart from the target's even for the same args. Which configuration
// the spec picks is in neither: it chooses among what one load returned.
std::string srcKey = std::format("git|{}|{}|{}|{}", spec.source.url, spec.source.branch, spec.source.commit, spec.projectFile.string());
std::string srcHash = std::format("{:016x}", std::hash<std::string>{}(srcKey));
@ -428,12 +492,10 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
fullKey += a;
}
std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey));
const std::string what = std::format("GitProject({})", spec.source.url);
{
std::lock_guard lock(ProjectCacheMutex);
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
return it->second.get();
}
if (const std::vector<Configuration*>* cached = CachedProject(fullHash)) {
return PickConfiguration(*cached, spec.configuration, what);
}
std::string name = DeriveName(spec.source);
@ -461,15 +523,15 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
}
std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end());
Configuration cfg = LoadProjectFromRoot(projectPath, cloneDir, argViews);
std::vector<Configuration*> configurations = LoadProjectFromRoot(projectPath, cloneDir, argViews);
const fs::path projectInRepo = spec.projectFile.lexically_normal();
const fs::path below = projectInRepo.parent_path();
return StoreProject(std::move(fullHash), std::move(cfg), {
return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), {
.projectFile = projectPath.lexically_normal(),
.name = below.empty() ? name : std::format("{}/{}", name, below.generic_string()),
.identity = std::format("git|{}|{}", RepositoryKey(spec.source.url), projectInRepo.generic_string()),
});
}), spec.configuration, what);
}
fs::path Crafter::GitFetch(const GitSource& source) {
@ -512,23 +574,21 @@ Configuration* Crafter::LocalProject(const LocalProjectSpec& spec) {
fullKey += a;
}
std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey));
const std::string what = std::format("LocalProject({})", canonical.string());
{
std::lock_guard lock(ProjectCacheMutex);
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
return it->second.get();
}
if (const std::vector<Configuration*>* cached = CachedProject(fullHash)) {
return PickConfiguration(*cached, spec.configuration, what);
}
fs::path depRoot = canonical.parent_path();
std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end());
Configuration cfg = LoadProjectFromRoot(canonical, depRoot, argViews);
std::vector<Configuration*> configurations = LoadProjectFromRoot(canonical, depRoot, argViews);
return StoreProject(std::move(fullHash), std::move(cfg), {
return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), {
.projectFile = canonical,
.name = depRoot.filename().string(),
.identity = std::format("local|{}", canonical.string()),
});
}), spec.configuration, what);
}
std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg) {
@ -536,3 +596,9 @@ std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg)
if (auto it = LoadedProjects.find(&cfg); it != LoadedProjects.end()) return it->second;
return std::nullopt;
}
std::optional<LoadedProject> Crafter::KeptBy(const Configuration& cfg) {
const std::lock_guard lock(ProjectCacheMutex);
if (const auto it = KeptConfigurations.find(&cfg); it != KeptConfigurations.end()) return it->second;
return std::nullopt;
}

View file

@ -5,6 +5,7 @@ module Crafter.Build:Implementation_impl;
import std;
import :Implementation;
import :Interface;
import :Jobs;
import :Platform;
namespace fs = std::filesystem;
@ -12,12 +13,12 @@ namespace Crafter {
Implementation::Implementation(fs::path&& path) : path(std::move(path)) {
}
bool Implementation::Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor) const {
std::string objPath = std::format("{}_impl.o", (buildDir/path.filename()).string());
bool Implementation::Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor) const {
std::string objPath = object.string();
std::string cppPath = std::format("{}.cpp", path.string());
// The depfile clang wrote beside the object lists the headers this TU
// included; nothing else in the configuration knows about them, since
// the source scanner only reads `import` lines.
// included when the object was compiled: inputs of the object as
// much as the source and the BMIs it imports.
if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) {
return true;
}
@ -35,33 +36,26 @@ namespace Crafter {
}
return false;
}
void Implementation::Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const {
void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const {
std::vector<JobGroup::Job> after;
for(ModulePartition* dependency : partitionDependencies) {
if(!dependency->compiled.load()) {
dependency->compiled.wait(false);
}
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
for(Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) {
dependency->compiled.wait(false);
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
}
if (buildCancelled.load(std::memory_order_relaxed)) {
return;
}
// -MD leaves <name>_impl.o.d beside the object for Check to read, and
// -fmodule-file-deps puts the BMIs the unit imported in it with the
// headers. The driver adds that for --precompile only, so a std
// module rebuilt in place, for a mingw-w64 or libc++ update under
// the same compiler, left the objects importing it as they were, and
// the next build only relinked them.
std::string result = RunBuildCommand(std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string()));
bool expected = false;
if(!result.empty() && buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
//
// The job makes the directory of its object, which is one for the
// source's own directory (ObjectPath): the compiler makes none.
jobs.Add(std::format("Compiling {}", shown), [directory = object.parent_path(), command = std::format("{0} {1}.cpp -c -MD -MF {2}.d -fmodule-file-deps -o {2}", clang, path.string(), object.string())] {
fs::create_directories(directory);
return RunBuildCommand(command);
}, after);
}
}

View file

@ -4,11 +4,55 @@
module Crafter.Build:Interface_impl;
import std;
import :Interface;
import :Jobs;
import :Platform;
namespace fs = std::filesystem;
namespace {
// The job that makes an interface unit's object from its BMI, once the
// jobs in `after` have finished. The command is put together here, as in
// the functions below, so the job owns the one it runs.
void AddObjectJob(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
jobs.Add(std::format("Compiling {}.cppm", path.filename().string()), [command = std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())] {
return Crafter::RunBuildCommand(command);
}, after);
}
// The two compiler runs of a stale interface unit, as jobs of `jobs`: its
// BMI once the jobs in `after` have finished, then its object from that
// BMI. Returns the first, the one the units importing this one come
// after: the object is the link's alone to wait for.
Crafter::JobGroup::Job AddInterfaceJobs(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
const Crafter::JobGroup::Job precompile = jobs.Add(std::format("Precompiling {}.cppm", path.filename().string()), [command = std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())] {
return Crafter::RunBuildCommand(command);
}, after);
const std::array<Crafter::JobGroup::Job, 1> precompiled = {precompile};
AddObjectJob(jobs, clang, path, pcmDir, buildDir, precompiled);
return precompile;
}
// For a unit whose BMI is up to date: the object job alone, when the
// object is missing or older than the BMI it is made from. The two are
// written by two commands, and a build can end between them: by an error
// elsewhere, which keeps the second from starting, by the second failing,
// or by being interrupted. An object written in the same tick of the
// file system's clock as its BMI is taken to be the later of the two,
// which it is whenever the command that writes it ran.
void AddObjectJobIfStale(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir) {
std::error_code ec;
const fs::file_time_type pcmTime = fs::last_write_time(std::format("{}.pcm", (pcmDir/path.filename()).string()), ec);
// No BMI to make it from; Check does not call such a unit up to date.
if (ec) return;
const fs::file_time_type objectTime = fs::last_write_time(std::format("{}.o", (buildDir/path.filename()).string()), ec);
if (!ec && objectTime >= pcmTime) return;
AddObjectJob(jobs, clang, path, pcmDir, buildDir, {});
}
}
namespace Crafter {
ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {}
ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
if(!checked) {
@ -44,11 +88,6 @@ namespace Crafter {
}
}
needsRecompiling = false;
compiled.store(true);
// Nothing waits on `compiled` until the compile threads start,
// which is after every Check has run — but notify anyway so the
// flag is never left set without a wake-up behind it.
compiled.notify_all();
return false;
} else {
needsRecompiling = true;
@ -59,52 +98,25 @@ namespace Crafter {
}
}
void ModulePartition::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) {
for(ModulePartition* dependency : partitionDependencies) {
if(!dependency->compiled.load()) {
dependency->compiled.wait(false);
std::optional<JobGroup::Job> ModulePartition::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
if (scheduled) return precompileJob;
if (needsRecompiling) {
std::vector<JobGroup::Job> after;
for (ModulePartition* dependency : partitionDependencies) {
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
for (Module* dependency : moduleDependencies) {
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
for(Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) {
dependency->compiled.wait(false);
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
} else {
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
}
scheduled = true;
return precompileJob;
}
if (buildCancelled.load(std::memory_order_relaxed)) {
compiled.store(true);
compiled.notify_all();
return;
}
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
compiled.store(true);
compiled.notify_all();
return;
}
}
compiled.store(true);
compiled.notify_all();
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}
}
Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {}
Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
if(!checked) {
@ -116,7 +128,7 @@ namespace Crafter {
if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) {
fs::file_time_type pcmTime = fs::last_write_time(pcmPath);
// Every partition gets Check()ed even once one is known stale:
// Compile() drives partition rebuilds off their own
// Schedule() drives partition rebuilds off their own
// needsRecompiling flags, so short-circuiting here would leave
// the later ones unevaluated and silently unbuilt.
bool depCheck = false;
@ -149,14 +161,12 @@ namespace Crafter {
return true;
} else {
needsRecompiling = false;
compiled.store(true);
compiled.notify_all();
return false;
}
} else {
// Already known stale, but the dependencies still need
// evaluating: an unchecked local module would never get built,
// and Compile() below waits on its `compiled` flag.
// evaluating: Schedule() below reads their needsRecompiling,
// and an unchecked local module would never get built.
for(std::unique_ptr<ModulePartition>& partition : partitions) {
partition->Check(pcmDir, sourceFloor);
}
@ -171,60 +181,29 @@ namespace Crafter {
}
}
void Module::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) {
// A sibling module in the same Configuration that this interface unit
// imports has to have its PCM on disk before we precompile against it.
// Safe to block here: Build() Checks every interface before it spawns
// any compile thread, so a dependency that needs no rebuild already has
// `compiled` set and this returns immediately.
for(Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) {
dependency->compiled.wait(false);
std::optional<JobGroup::Job> Module::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
if (scheduled) return precompileJob;
std::vector<JobGroup::Job> after;
// All of the module's partitions, not the ones the primary interface
// names: Build() records no edge for its `import :Part;` lines (see
// Module::moduleDependencies). And of a module that is up to date as
// well: this is where its partitions are scheduled, and one of them
// may be without its object.
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 (needsRecompiling) {
// A sibling module in the same Configuration that this interface
// unit imports has to have its PCM on disk before we precompile
// against it.
for (Module* dependency : moduleDependencies) {
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
std::vector<std::thread> threads;
threads.reserve(partitions.size());
for(std::unique_ptr<ModulePartition>& part : partitions) {
if(part->needsRecompiling) {
threads.emplace_back(&ModulePartition::Compile, part.get(), clang, pcmDir, buildDir, std::ref(buildCancelled), std::ref(buildError));
}
}
for(std::thread& thread : threads){
thread.join();
}
if (buildCancelled.load(std::memory_order_relaxed)) {
compiled.store(true);
compiled.notify_all();
return;
}
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
compiled.store(true);
compiled.notify_all();
return;
}
}
compiled.store(true);
compiled.notify_all();
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
} else {
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
}
scheduled = true;
return precompileJob;
}
}

View file

@ -0,0 +1,218 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Crafter.Build:Jobs_impl;
import std;
import :Jobs;
import :Progress;
namespace {
// The pool this thread is a worker of; null on every other thread.
thread_local const Crafter::JobPool* WorkerOf = nullptr;
}
namespace Crafter {
JobPool::JobPool(std::uint32_t workers) : limit(std::max(workers, 1u)) {}
JobPool::~JobPool() {
{
std::lock_guard lock(mutex);
stopping = true;
}
wake.notify_all();
for (std::thread& thread : threads) thread.join();
}
JobPool& JobPool::Process() {
static JobPool* const pool = new JobPool(std::thread::hardware_concurrency());
return *pool;
}
std::uint32_t JobPool::Workers() const {
return limit;
}
void JobPool::Submit(std::function<void()> job) {
std::lock_guard lock(mutex);
queue.push_back(std::move(job));
if (queue.size() <= idle || threads.size() >= limit) {
wake.notify_one();
return;
}
try {
threads.emplace_back([this] { Work(); });
} catch (...) {
// The system has no thread to give. The workers there are take
// the job when they get to it. With none it would stay queued
// for good, and whoever waits for it with it.
if (!threads.empty()) return;
queue.pop_back();
throw;
}
}
void JobPool::Work() {
WorkerOf = this;
std::unique_lock lock(mutex);
for (;;) {
while (queue.empty() && !stopping) {
++idle;
wake.wait(lock);
--idle;
}
if (queue.empty()) return;
std::function<void()> job = std::move(queue.front());
queue.pop_front();
lock.unlock();
job();
// Before the lock is taken again: what the job captured is
// released without holding up the queue.
job = nullptr;
lock.lock();
}
}
void JobPool::Run(const std::function<void()>& work) {
if (WorkerOf == this) {
work();
return;
}
// Shared with the job, not a local of this function: this thread
// goes on as soon as the value is set, which is before set_value has
// returned on the worker.
const std::shared_ptr<std::promise<void>> done = std::make_shared<std::promise<void>>();
std::future<void> finished = done->get_future();
Submit([&work, done] {
try {
work();
done->set_value();
} catch (...) {
done->set_exception(std::current_exception());
}
});
finished.get();
}
struct JobGroup::Node {
std::string label;
std::function<std::string()> work;
std::unique_ptr<Progress::Task> task;
// The jobs added after this one that it has yet to release, and how
// many jobs this one still waits for. Both under the group's mutex;
// the members above belong to whoever runs the job.
std::vector<Node*> dependents;
std::size_t waiting = 0;
bool finished = false;
};
JobGroup::JobGroup(JobPool& pool) : pool(pool) {
if (WorkerOf == &pool) throw std::logic_error("a JobGroup cannot be made on a worker of its own pool: it would wait there for jobs that need that worker");
}
JobGroup::~JobGroup() {
std::unique_lock lock(mutex);
failed = true;
settled.wait(lock, [this] { return unfinished == 0; });
}
JobGroup::Job JobGroup::Add(std::string label, std::function<std::string()> work, std::span<const Job> after) {
std::unique_ptr<Node> made = std::make_unique<Node>();
// Counted from here on, not from when it starts: the total a build
// shows is then what it has queued, and not only what the workers
// have got to.
made->task = std::make_unique<Progress::Task>(label);
made->label = std::move(label);
made->work = std::move(work);
std::lock_guard lock(mutex);
// Room for the new job in each list it may join, made before the
// group knows of it: from there to the count below nothing can throw,
// so no job is ever waited on by half of what it comes after.
for (const Job job : after) {
if (job >= nodes.size()) throw std::out_of_range("JobGroup::Add: a job can only come after jobs added before it");
std::vector<Node*>& dependents = nodes[job]->dependents;
dependents.reserve(dependents.size() + after.size());
}
const Job id = nodes.size();
Node& node = *nodes.emplace_back(std::move(made));
for (const Job job : after) {
Node& before = *nodes[job];
if (before.finished) continue;
before.dependents.push_back(&node);
++node.waiting;
}
++unfinished;
if (node.waiting != 0) return id;
try {
Start(node);
} catch (...) {
// Not queued (JobPool::Submit), so nothing will ever finish it:
// it is taken back, or Wait() would never return.
node.work = nullptr;
node.task.reset();
node.finished = true;
if (--unfinished == 0) settled.notify_all();
throw;
}
return id;
}
void JobGroup::Start(Node& node) {
pool.Submit([this, &node] { Execute(node); });
}
void JobGroup::Execute(Node& node) {
bool skipped = false;
{
std::lock_guard lock(mutex);
skipped = failed;
}
std::string result;
if (!skipped) {
try {
result = node.work();
} catch (const std::exception& e) {
result = std::format("{}: {}", node.label, e.what());
} catch (...) {
result = std::format("{}: threw something that isn't a std::exception", node.label);
}
}
// Both before the group hears of it: what the work captured is gone,
// and the step counted as done, by the time Wait() returns.
node.work = nullptr;
node.task.reset();
// Nothing of the group is touched once this lock is released: with
// the last job finished, whoever waited may destroy it.
std::lock_guard lock(mutex);
if (!result.empty() && !failed) {
failed = true;
error = std::move(result);
}
node.finished = true;
// Released after a failure as well: they are skipped when they run,
// which is what counts them as finished.
for (Node* dependent : node.dependents) {
if (--dependent->waiting == 0) Start(*dependent);
}
if (--unfinished == 0) settled.notify_all();
}
void JobGroup::Fail(std::string why) {
std::lock_guard lock(mutex);
if (failed) return;
failed = true;
error = std::move(why);
}
bool JobGroup::Failed() const {
std::lock_guard lock(mutex);
return failed;
}
std::string JobGroup::Wait() {
std::unique_lock lock(mutex);
settled.wait(lock, [this] { return unfinished == 0; });
return error;
}
}

View file

@ -43,6 +43,7 @@ namespace {
decltype(&clang_createIndex) createIndex = nullptr;
decltype(&clang_disposeIndex) disposeIndex = nullptr;
decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr;
decltype(&clang_parseTranslationUnit2FullArgv) parseTranslationUnit2FullArgv = nullptr;
decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr;
decltype(&clang_getFile) getFile = nullptr;
decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr;
@ -133,6 +134,7 @@ namespace {
bind(lib.createIndex, "clang_createIndex");
bind(lib.disposeIndex, "clang_disposeIndex");
bind(lib.parseTranslationUnit, "clang_parseTranslationUnit");
bind(lib.parseTranslationUnit2FullArgv, "clang_parseTranslationUnit2FullArgv");
bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit");
bind(lib.getFile, "clang_getFile");
bind(lib.getLocationForOffset, "clang_getLocationForOffset");
@ -705,11 +707,12 @@ namespace {
return decls;
}
// libclang locates its builtin headers relative to its own install path,
// which need not agree with the clang++ on PATH that produced the PCMs.
// When it disagrees the failure is total and unhelpful — every parse dies
// on "'stddef.h' file not found" — so ask the driver and pass it
// explicitly. Cached like HostTarget, and for the same reason.
// The resource directory, which holds clang's own headers such as
// stddef.h, as the compiler names it. libclang's driver would otherwise
// derive one from argv[0] for libclang's own release, so with a libclang
// of another release than the compiler, a file that includes a header of
// the C++ standard library would fail on "'stddef.h' file not found".
// Cached like HostTarget, and for the same reason.
const std::string& ClangResourceDir() {
static const std::string Cached = []() -> std::string {
CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string()));
@ -752,7 +755,26 @@ namespace {
// Byte-length preserving, so cursor line/column land on the original.
std::string buffer = BlankExportKeywords(content, tokens);
std::string path = file.string();
std::vector<std::string> args = CommandToArgs(compileCommand);
// In a build for the host whose compile command names no libc++
// 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
// .cppm extension, and silently treats every flag as a linker input if
// left to guess.
@ -772,8 +794,8 @@ namespace {
result.error = "clang_createIndex failed";
return result;
}
CXTranslationUnit tu = lc.parseTranslationUnit(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None);
if (!tu) {
CXTranslationUnit tu = nullptr;
if (lc.parseTranslationUnit2FullArgv(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None, &tu) != CXError_Success || !tu) {
lc.disposeIndex(index);
result.error = "clang could not create a translation unit";
return result;
@ -866,18 +888,28 @@ namespace {
// whose path lies inside the project root — GitProject / external deps
// live under the global cache and are foreign code: they contribute
// neither rules nor files. Root-first order so the root's rules win the
// by-name dedup.
std::vector<Configuration*> CollectLocalConfigs(Configuration& root, const fs::path& projectRoot) {
// by-name dedup. Of several roots, the configurations a project file
// returns, every root comes first, in the order given, and what they
// depend on after them: walked one root's graph after another, a root
// that an earlier one depends on would come before the roots between
// the two, and its rule would win over theirs.
std::vector<Configuration*> CollectLocalConfigs(std::span<Configuration* const> roots, const fs::path& projectRoot) {
std::vector<Configuration*> local;
std::unordered_set<Configuration*> seen;
std::function<void(Configuration*)> walk = [&](Configuration* c) {
if (!seen.insert(c).second) return;
if (PathInsideRoot(fs::absolute(c->path), projectRoot)) {
local.push_back(c);
}
for (Configuration* dep : c->dependencies) walk(dep);
const auto keep = [&](Configuration* c) {
if (PathInsideRoot(fs::absolute(c->path), projectRoot)) local.push_back(c);
};
walk(&root);
std::function<void(Configuration*)> below = [&](Configuration* c) {
for (Configuration* dep : c->dependencies) {
if (!seen.insert(dep).second) continue;
keep(dep);
below(dep);
}
};
for (Configuration* root : roots) {
if (seen.insert(root).second) keep(root);
}
for (Configuration* root : roots) below(root);
return local;
}
@ -893,15 +925,10 @@ namespace {
// First owner wins, matching the root-first rule dedup: a source
// reachable through two configurations parses with the nearer one.
auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); };
for (const std::unique_ptr<Module>& mod : c.interfaces) {
own(fs::path(std::format("{}.cppm", mod->path.string())));
for (const std::unique_ptr<ModulePartition>& part : mod->partitions) {
own(fs::path(std::format("{}.cppm", part->path.string())));
}
}
for (const Implementation& impl : c.implementations) {
own(fs::path(std::format("{}.cpp", impl.path.string())));
}
// The sources as they are listed: which module each one is a unit
// of, only a build reads.
for (const fs::path& source : c.interfaceSources) own(source);
for (const fs::path& source : c.implementationSources) own(source);
// cFiles/cuda resolve against cwd at build time (see Build's compile
// loops); mirror that here.
for (const fs::path& cf : c.cFiles) {
@ -1069,6 +1096,11 @@ void Configuration::AddAstLintRule(std::string name, std::function<void(LintCont
}
LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& opts) {
std::array<Configuration*, 1> one = { &projectCfg };
return RunLint(std::span<Configuration* const>(one), opts);
}
LintSummary Crafter::RunLint(std::span<Configuration* const> configurations, const RunLintOptions& opts) {
LintSummary summary;
// libclang backs the lexer every rule reads through, so a failed load is
@ -1081,10 +1113,10 @@ LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& op
}
fs::path projectRoot = opts.projectFile.empty()
? fs::absolute(projectCfg.path)
? fs::absolute(configurations.empty() ? fs::path() : configurations.front()->path)
: opts.projectFile.parent_path();
std::vector<Configuration*> localConfigs = CollectLocalConfigs(projectCfg, projectRoot);
std::vector<Configuration*> localConfigs = CollectLocalConfigs(configurations, projectRoot);
// The tests' compile commands are worked out as RunTests builds them.
for (Configuration* c : localConfigs) UnpackageTests(*c);
@ -1133,7 +1165,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
CollectConfigSources(*c, files);
for (const Test& t : c->tests) CollectConfigSources(t.config, files);
}
// project.cpp is not built by Build() at all — LoadProject compiles it
// project.cpp is not built by Build() at all — its load compiles it
// against the host PCM cache with its own flags, so it is owned by nothing
// here and gets no compile command. Token rules still cover it.
if (!opts.projectFile.empty()) files.emplace(opts.projectFile, nullptr);
@ -1191,7 +1223,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
for (const auto& [file, owner] : files) {
std::ifstream in(file, std::ios::binary);
if (!in) continue; // config parse already read it; a vanished file fails the build first
if (!in) continue; // a listed file that is not there is the build's to report
std::stringstream buffer;
buffer << in.rdbuf();
LintContext ctx;
@ -1217,7 +1249,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
continue;
}
// No compile command means this file is not a translation unit
// of the build graph — project.cpp, which LoadProject compiles
// of the build graph — project.cpp, which its load compiles
// with its own flags, or a header. A semantic rule does not
// apply there, the same way a rule self-filters by extension,
// so skip it quietly. That is a different thing from a file we

View file

@ -9,6 +9,8 @@ module;
#include <dlfcn.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/prctl.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
module Crafter.Build:Platform_impl;
@ -18,6 +20,7 @@ import :Toolchain;
import :Clang;
import :Interface;
import :External;
import :Jobs;
import :Progress;
namespace fs = std::filesystem;
using namespace Crafter;
@ -25,7 +28,7 @@ using namespace Crafter;
namespace {
// Exclusive advisory lock over one PCM cache dir (`<cache>/<target>-<march>/`),
// held for the duration of a (re)build. Concurrent crafter-build invocations —
// and the worker threads inside a single invocation — that share a cache
// and the threads of a single invocation that build at once — that share a cache
// serialize their builds through it: the first builder to acquire the lock
// precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else
// blocks, then re-checks freshness and reuses the finished file instead of
@ -276,9 +279,11 @@ bool Crafter::MatchAny(std::span<const std::string> globs, std::string_view name
return false;
}
// See the declaration in Crafter.Build-Platform.cppm for why this branches on
// the exit code rather than on whether the command said anything.
std::string Crafter::RunBuildCommand(std::string_view cmd) {
namespace {
// RunBuildCommand's command, run on the thread that calls. See the
// declaration in Crafter.Build-Platform.cppm for why this branches on the
// exit code rather than on whether the command said anything.
std::string RunBuildStep(std::string_view cmd) {
Progress::EchoCommand(cmd);
CommandResult r = RunCommandChecked(cmd);
// A mingw build against a system prefix sees mingw-w64 through a view in
@ -304,6 +309,16 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) {
return std::format("{}\nterminated by signal {}", r.output, r.signal);
}
return r.output;
}
}
std::string Crafter::RunBuildCommand(std::string_view cmd) {
// A job is on a worker already and runs the command where it is. A link,
// or the precompile of the std module, comes from the thread of a Build()
// or of a project file's load and waits here for its turn among the jobs.
std::string result;
JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); });
return result;
}
// --- Dependencies of project.cpp itself -------------------------------------
@ -315,7 +330,7 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) {
// file, so this is a directive next to the `import` it enables — where
// `#include` lives. Each one is fetched, built for the host, and put on
// project.so's module path and link line before project.cpp is compiled. The
// dependency's own project.cpp goes through LoadProject, so its pragmas
// dependency's own project.cpp is loaded the same way, so its pragmas
// resolve recursively.
namespace {
struct PragmaDependency {
@ -416,18 +431,18 @@ namespace {
struct ProjectFileFrame {
fs::path project;
// What LoadProject was given, for ProjectArgs(), and only once
// CrafterBuildProject is about to be called (see LoadProject). A view
// is enough: the caller's storage outlives LoadProject, and the frame
// is popped before LoadProject returns.
// What the load was given, for ProjectArgs(), and only once the
// entry point is about to be called (see OpenProjectFile). A view
// is enough: the caller's storage outlives the load, and the frame
// is popped before the load returns.
std::span<const std::string_view> args;
std::vector<Configuration*> dependencies;
};
// LoadProject nests: a dependency's project.cpp loads inside its
// consumer's pre-pass, and GitProject inside CrafterBuildProject nests
// again. Several threads may also load at once (ConcurrentCacheRace), so
// the stack is per thread. ProjectDependency() reads the top frame.
// Loads nest: a dependency's project.cpp loads inside its consumer's
// pre-pass, and GitProject inside an entry point nests again. Several
// threads may also load at once (ConcurrentCacheRace), so the stack is
// per thread. ProjectDependency() reads the top frame.
thread_local std::vector<ProjectFileFrame> LoadingFrames;
// A frame's dependencies, kept past the frame for PragmaDependencies().
@ -437,7 +452,7 @@ namespace {
std::mutex PragmaDependenciesMutex;
std::unordered_map<fs::path, std::vector<Configuration*>> PragmaDependenciesByProject;
// Held for the whole of one LoadProject call. Pushing a file that is
// Held for the whole of one load of a project file. Pushing one that is
// already on the stack is a cycle, which used to recurse forever.
class ProjectFileGuard {
public:
@ -478,7 +493,7 @@ namespace {
// A pre-dependency is host tooling: project.so is loaded into the running
// crafter-build, so the dependency is built for the host and against the
// same PCM cache LoadProject populates — the hostConfig LoadProject itself
// same PCM cache a load populates — the hostConfig the load itself
// compiles project.so with, so the dependency's std/Crafter.Build PCMs
// land in the cache dir project.so is built against. Recursive, because
// the dependency's project.cpp is loaded with no arguments and so passes
@ -510,7 +525,7 @@ namespace {
// Every dependency's BuildResult.libs, verbatim, then its runtimeLibs,
// the CUDA runtime, then a run path per directory of its runPaths
// (RunPathFlags), as Build() links a program: the shared libraries a
// pragma dependency is built on are found there when LoadProject
// pragma dependency is built on are found there when the load
// dlopens project.so.
std::string linkFlags;
fs::file_time_type newestArtifact = fs::file_time_type::min();
@ -535,7 +550,7 @@ namespace {
for (const PragmaDependency& pragma : pragmas) {
// Neither spec sets args, and the tool still gets none of the
// consumer's: this pre-pass runs before LoadProject hands the
// consumer's: this pre-pass runs before the load hands the
// frame its args, so ProjectArgs() is empty. Given the consumer's
// --target=, the tool's project.cpp would pick sources and flags
// for the wrong triple, and its flags would split the tool's
@ -553,7 +568,7 @@ namespace {
cfg = GitProject(spec);
} else {
if (!pragma.branch.empty() || !pragma.commit.empty()) PragmaError(absProject, pragma.line, "'branch' and 'commit' only apply to a git source");
// Relative to the project file, not the cwd: LoadProject runs
// Relative to the project file, not the cwd: the load runs
// from wherever the consumer was invoked.
fs::path local = (absProject.parent_path() / pragma.source).lexically_normal();
if (fs::is_directory(local)) {
@ -861,6 +876,168 @@ CommandResult Crafter::RunCommandWithTimeout(std::string_view cmd, std::chrono::
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) {
CacheLock lock(stdPcm.parent_path());
if(config.target == "x86_64-w64-mingw32") {
@ -874,7 +1051,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// and, when clang finds no gcc directory, an empty entry that would
// name a manifest in the working directory. A toolchain that isn't
// there is a build error, not an exception: Build() runs this with
// its worker threads started.
// the threads of its external dependencies started.
const Toolchain& tc = GetToolchain();
const std::string where = tc.mingwPrefix.empty()
? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH")
@ -921,7 +1098,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// The std.cc → std.cppm copy uses a plain filename: held under the
// cache lock, no other builder writes this path concurrently.
fs::path stdCppm = stdPcm.parent_path() / "std.cppm";
std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config), stdCppm.string(), stdPcm.string());
std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm.string(), stdPcm.string());
std::string stamp = HashStamp(command + '\0' + FileBytes(stdCc));
if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return "";
std::error_code copyEc;
@ -939,7 +1116,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// <sysroot>/usr/share/libc++/v1/.
std::string stdCppm;
if (isWasm) {
stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.sysroot);
stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.ResolvedSysroot(GetToolchain()));
} else if (config.sysroot.empty()) {
stdCppm = GetToolchain().stdCppm.string();
} else {
@ -955,7 +1132,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// mtimes: an installed std.cppm can be dated at the epoch (OSTree),
// and a libc++ update under the same clang changes the bytes but
// not the path.
std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config), stdCppm, stdPcm.string());
std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm, stdPcm.string());
std::string stamp = HashStamp(command + '\0' + FileBytes(stdCppm));
if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return "";
std::string result = RunBuildCommand(command);
@ -990,16 +1167,17 @@ std::string Crafter::GetBaseCommand(const Configuration& config) {
command += " -stdlib=libc++";
// A sysroot build (wasm, a cross rootfs) takes libc++ from the sysroot;
// only host builds can be pointed at an explicit libc++ install.
if (config.sysroot.empty()) command += tc.LibcxxCompileFlags();
if (config.ResolvedSysroot(tc).empty()) command += tc.LibcxxCompileFlags();
return command;
}
namespace {
constexpr std::array<std::string_view, 15> CrafterBuildModules = {
constexpr std::array<std::string_view, 16> CrafterBuildModules = {
"Crafter.Build-Toolchain",
"Crafter.Build-Shader",
"Crafter.Build-Platform",
"Crafter.Build-Flatpak",
"Crafter.Build-Jobs",
"Crafter.Build-Interface",
"Crafter.Build-Implementation",
"Crafter.Build-External",
@ -1053,10 +1231,32 @@ namespace {
}
}
Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const std::string_view> args) {
RequireToolchain();
fs::path absProject = fs::canonical(projectFile);
ProjectFileGuard guard(absProject);
namespace {
using ProjectFn = Configuration (*)(std::span<const std::string_view>);
using ConfigurationsFn = std::vector<Configuration*> (*)(std::span<const std::string_view>);
// The entry point of a loaded project file: one of the two is set.
struct ProjectEntry {
ProjectFn one = nullptr;
ConfigurationsFn several = nullptr;
};
// Every Configuration a CrafterBuildProject returned to
// LoadConfigurations, kept for the rest of the process like the ones a
// CrafterBuildConfigurations returns, which its project file keeps:
// whoever holds a pointer LoadConfigurations gave out, the project cache
// or a consumer's `dependencies`, holds it that long.
std::mutex ReturnedConfigurationsMutex;
std::vector<std::unique_ptr<Configuration>> ReturnedConfigurations;
}
// Compiles the project file `guard` holds into project.so, unless the one
// there is current, loads it and finds its entry point. The frame holds
// `args` once this returns, for the call the caller makes next.
static ProjectEntry OpenProjectFile(ProjectFileGuard& guard, std::span<const std::string_view> args) {
// A copy: the loads of the file's dependencies push frames of their own,
// which can move this one.
const fs::path absProject = guard.Frame().project;
fs::path buildDir = absProject.parent_path() / "build";
if (!fs::exists(buildDir)) {
fs::create_directories(buildDir);
@ -1140,11 +1340,20 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const
throw std::runtime_error(std::format("Failed to load project {}: {}", soPath.string(), dlerror()));
}
using ProjectFn = Configuration (*)(std::span<const std::string_view>);
dlerror();
auto fn = reinterpret_cast<ProjectFn>(dlsym(handle, "CrafterBuildProject"));
if (const char* err = dlerror()) {
throw std::runtime_error(std::format("CrafterBuildProject not found in {}: {}", soPath.string(), err));
// Looked up in project.so and the libraries it links, which is where
// dlsym searches for a handle: every project file this process has
// loaded exports an entry point under one of these two names, and none
// of the others is found here.
ProjectEntry entry;
entry.one = reinterpret_cast<ProjectFn>(dlsym(handle, "CrafterBuildProject"));
entry.several = reinterpret_cast<ConfigurationsFn>(dlsym(handle, "CrafterBuildConfigurations"));
if (!entry.one && !entry.several) {
throw std::runtime_error(std::format("{} defines neither CrafterBuildProject nor CrafterBuildConfigurations (looked in {})", absProject.string(), soPath.string()));
}
// Calling the first would leave what the second returns unbuilt, and
// the other way around, without a word.
if (entry.one && entry.several) {
throw std::runtime_error(std::format("{} defines both CrafterBuildProject and CrafterBuildConfigurations; a project file has one entry point", absProject.string()));
}
// The args only for the call itself, unlike the dependencies. A static
@ -1154,5 +1363,67 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const
// Now it gets none, whichever load ran it. The pragma pre-pass above
// also ran on this frame and relies on the args not being there yet.
guard.Frame().args = args;
return fn(args);
return entry;
}
Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const std::string_view> args) {
RequireToolchain();
const fs::path absProject = fs::canonical(projectFile);
ProjectFileGuard guard(absProject);
const ProjectEntry entry = OpenProjectFile(guard, args);
if (!entry.one) {
throw std::runtime_error(std::format("{} defines CrafterBuildConfigurations, which LoadProject cannot return by value; load it with LoadConfigurations", absProject.string()));
}
return entry.one(args);
}
std::vector<Configuration*> Crafter::LoadConfigurations(const fs::path& projectFile, std::span<const std::string_view> args) {
RequireToolchain();
const fs::path absProject = fs::canonical(projectFile);
ProjectFileGuard guard(absProject);
const ProjectEntry entry = OpenProjectFile(guard, args);
if (entry.one) {
// The call's return value is the initialiser of the new-expression,
// so the Configuration is constructed where it stays and is never
// moved; std::make_unique would move a temporary into place. A
// project file takes pointers to the configuration it returns, for a
// test that links the library it describes (cfg.AddTest(...)
// .Dependencies({ &cfg })), and they are pointers to this object
// when the compiler constructed the local the file returns in place
// of the return value, as clang does for a function that returns one
// local.
std::unique_ptr<Configuration> returned(new Configuration(entry.one(args)));
Configuration* const configuration = returned.get();
const std::lock_guard lock(ReturnedConfigurationsMutex);
ReturnedConfigurations.push_back(std::move(returned));
return { configuration };
}
std::vector<Configuration*> configurations = entry.several(args);
if (configurations.empty()) {
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned no configuration", absProject.string()));
}
std::unordered_set<const Configuration*> seen;
for (const Configuration* configuration : configurations) {
if (!configuration) {
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned a null pointer", absProject.string()));
}
// Most often a pasted `&lib` where `&tool` was meant, which would
// leave `tool` unbuilt without a word.
if (!seen.insert(configuration).second) {
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {} twice", absProject.string(), configuration->name));
}
// One that a project GitProject or LocalProject loaded keeps to
// itself, taken out of the `dependencies` or the `tests` of what
// that project's file returned. Returned from here it would count
// as one this file
// made: `test` would run its tests and `run` offer its scripts,
// which are that project's. And only the configurations a project
// file returns are rebased onto its directory, so this one would be
// built wherever its relative `path` leads from here.
if (const std::optional<LoadedProject> keeper = KeptBy(*configuration)) {
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {}, which {} keeps to itself: a project file returns the configurations it makes and the ones GitProject or LocalProject returned", absProject.string(), configuration->name, keeper->name));
}
}
return configurations;
}

View file

@ -11,11 +11,18 @@ namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::string JoinNames(std::span<const Script> scripts) {
// A script and the configuration it is declared on, which is the
// project its callback is handed.
struct Declared {
const Script* script;
Configuration* owner;
};
std::string JoinNames(std::span<const Declared> scripts) {
std::string out;
for (const Script& script : scripts) {
for (const Declared& declared : scripts) {
if (!out.empty()) out += ", ";
out += script.name;
out += declared.script->name;
}
return out;
}
@ -29,10 +36,22 @@ std::int32_t ScriptContext::Run(std::string_view command) const {
}
std::int32_t Crafter::RunScript(Configuration& projectCfg, const RunScriptOptions& opts) {
std::array<Configuration*, 1> one = { &projectCfg };
return RunScript(std::span<Configuration* const>(one), opts);
}
std::int32_t Crafter::RunScript(std::span<Configuration* const> configurations, const RunScriptOptions& opts) {
// Loading the project may have left an in-place status line behind.
Progress::Clear();
const std::span<const Script> scripts = projectCfg.scripts;
std::vector<Declared> scripts;
std::unordered_set<const Configuration*> listed;
for (Configuration* cfg : configurations) {
// Once, however often the list names it: its scripts are not names
// declared twice.
if (!listed.insert(cfg).second) continue;
for (const Script& script : cfg->scripts) scripts.push_back({ &script, cfg });
}
if (scripts.empty()) {
std::println(std::cerr,
R"msg(No scripts defined.
@ -51,7 +70,8 @@ returned; ctx.args holds the arguments.)msg");
// declaration is reported the first time anyone uses `run` and not only
// when that one name is asked for.
std::unordered_set<std::string_view> seen;
for (const Script& script : scripts) {
for (const Declared& declared : scripts) {
const Script& script = *declared.script;
if (script.name.empty() || script.name.starts_with('-')) {
std::println(std::cerr, "script name '{}' cannot be run: a name must not be empty or start with '-'", script.name);
return 1;
@ -69,36 +89,37 @@ returned; ctx.args holds the arguments.)msg");
}
if (opts.listOnly || !opts.named) {
for (const Script& script : scripts) std::println("{}", script.name);
for (const Declared& declared : scripts) std::println("{}", declared.script->name);
return 0;
}
const auto found = std::ranges::find(scripts, opts.name, &Script::name);
const auto found = std::ranges::find_if(scripts, [&](const Declared& declared) { return declared.script->name == opts.name; });
if (found == scripts.end()) {
std::println(std::cerr, "No script named '{}'. Scripts: {}", opts.name, JoinNames(scripts));
return 1;
}
const Script& script = *found->script;
ScriptContext ctx{
.project = projectCfg,
.project = *found->owner,
// lexically_normal: fs::absolute keeps a "./" component.
.projectDir = opts.projectFile.empty() ? fs::absolute(projectCfg.path).lexically_normal() : opts.projectFile.parent_path(),
.projectDir = opts.projectFile.empty() ? fs::absolute(found->owner->path).lexically_normal() : opts.projectFile.parent_path(),
.args = opts.args,
};
try {
const std::int32_t code = found->run(ctx);
const std::int32_t code = script.run(ctx);
if (code >= 0 && code <= 255) return code;
std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", found->name, code);
std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", script.name, code);
return 1;
} catch (const std::exception& e) {
// Never let a script's exception unwind across the project.so
// boundary and out of Run: report it as this script's failure.
Progress::Clear();
std::println(std::cerr, "script '{}' failed: {}", found->name, e.what());
std::println(std::cerr, "script '{}' failed: {}", script.name, e.what());
return 1;
} catch (...) {
Progress::Clear();
std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", found->name);
std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", script.name);
return 1;
}
}

View file

@ -64,12 +64,78 @@ namespace {
}
}
void WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) {
// Writes build/test-logs/<name>.log and returns its path, or nothing
// 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";
std::error_code ec;
fs::create_directories(logDir, ec);
if (ec) return;
std::ofstream(logDir / (std::format("{}.log", name))) << output;
if (ec) return std::nullopt;
const fs::path log = logDir / std::format("{}.log", name);
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) {
@ -111,7 +177,8 @@ namespace {
}
namespace {
std::atomic<Configuration*> ParentProject{nullptr};
std::mutex ParentProjectsMutex;
std::vector<Configuration*> ParentProjects;
Configuration* FindLibInTree(Configuration* root, std::string_view name, std::unordered_set<Configuration*>& seen) {
if (!seen.insert(root).second) return nullptr;
@ -124,17 +191,31 @@ namespace {
}
void Crafter::SetParentProject(Configuration* parent) {
ParentProject.store(parent);
SetParentProject(parent ? std::span<Configuration* const>(&parent, 1) : std::span<Configuration* const>());
}
void Crafter::SetParentProject(std::span<Configuration* const> parents) {
const std::lock_guard lock(ParentProjectsMutex);
ParentProjects.assign(parents.begin(), parents.end());
}
Configuration* Crafter::ParentLib(std::string_view name) {
Configuration* root = ParentProject.load();
if (!root) {
std::vector<Configuration*> roots;
{
const std::lock_guard lock(ParentProjectsMutex);
roots = ParentProjects;
}
if (roots.empty()) {
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name));
}
std::unordered_set<Configuration*> seen;
std::string names;
for (Configuration* root : roots) {
if (auto found = FindLibInTree(root, name, seen)) return found;
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, root->name));
if (!names.empty()) names += ", ";
names += root->name;
}
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, names));
}
TestRunner TestRunner::Local() {
@ -244,27 +325,91 @@ TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) {
return fallback;
}
TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout) {
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 result;
result.name = test.config.name;
std::map<std::string, std::string> ph;
ph["{args}"] = JoinAndQuoteArgs(test.args);
auto start = std::chrono::steady_clock::now();
CommandResult r;
std::string cmd;
if (test.runner.exec.empty()) {
// Local runner: spawn the binary directly through the host shell.
std::string cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]);
r = RunCommandWithTimeout(cmd, timeout);
cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]);
} else {
// Prefix runner (qemu-user, wasmtime, wine, ...): templated exec
// wraps the local binary.
ph["{bin}"] = binary.string();
r = RunCommandWithTimeout(Substitute(test.runner.exec, ph), timeout);
cmd = Substitute(test.runner.exec, ph);
}
// 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();
result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
result.output = std::move(r.output);
@ -277,6 +422,19 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std:
else if (r.exitCode != 0) result.outcome = TestOutcome::Fail;
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;
}
@ -429,29 +587,48 @@ TestBuilder& TestBuilder::Define(std::string n, std::string v) {
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::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);
// 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::Dependencies(std::vector<Configuration*> d) { Ref().config.dependencies = std::move(d); 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::Wayland(bool w) { Ref().wayland = w; return *this; }
void Crafter::UnpackageTests(Configuration& cfg) {
for (Test& test : cfg.tests) test.config.packaging = Packaging::None;
}
TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
UnpackageTests(projectCfg);
std::array<Configuration*, 1> one = { &projectCfg };
return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
}
namespace {
// 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
// configuration would have each of its tests built twice at once.
std::vector<Configuration*> distinct;
for (Configuration* cfg : configurations) {
if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg);
}
if (distinct.size() != configurations.size()) return RunTestsWith(distinct, opts, projectArgs, run);
for (Configuration* cfg : configurations) UnpackageTests(*cfg);
// Multi-target sweep: when no --target= was given, the run covers every
// distinct target declared across projectCfg.tests plus the host target.
// distinct target declared across the tests plus the host target.
// Lets a bare `crafter-build test` exercise cross-arch tests without the
// user having to know which targets exist. An explicit --target=X
// bypasses the sweep and runs that target only.
@ -461,9 +638,11 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
// the one shown and filtered on.
std::map<std::string, std::string> sweep;
sweep.emplace(NormalizeTarget(HostTarget()), HostTarget());
for (const Test& t : projectCfg.tests) {
for (const Configuration* cfg : configurations) {
for (const Test& t : cfg->tests) {
if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target);
}
}
TestSummary aggregate;
for (const auto& [normalized, target] : sweep) {
RunTestsOptions perTarget = opts;
@ -472,7 +651,7 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
Progress::Clear();
std::println("\n=== target: {} ===", target);
}
TestSummary s = RunTests(projectCfg, perTarget, projectArgs);
TestSummary s = RunTestsWith(configurations, perTarget, projectArgs, run);
aggregate.passed += s.passed;
aggregate.failed += s.failed;
aggregate.crashed += s.crashed;
@ -490,8 +669,11 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
// time) because runnerOverride and FromEnv resolution depend on the
// run's options, which the project.cpp doesn't know about.
std::vector<Test*> filtered;
filtered.reserve(projectCfg.tests.size());
for (auto& test : projectCfg.tests) {
// The configuration that declares each of them, whose path its log is
// written under.
std::vector<const Configuration*> owners;
for (Configuration* cfg : configurations) {
for (auto& test : cfg->tests) {
if (!SameTarget(test.config.target, opts.targetFilter)) continue;
if (!MatchAny(opts.globs, test.config.name)) continue;
test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config));
@ -501,6 +683,8 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
}
}
filtered.push_back(&test);
owners.push_back(cfg);
}
}
if (opts.listOnly) {
@ -515,6 +699,60 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
return summary;
}
// A test is built in a directory named after the test and what it is
// compiled as, not after the configuration that declares it, and its
// sources are tests/<name> whichever one does. Two configurations that
// each declare a test of one name, compiled alike, would have the two
// built in that one directory, at once when the run has the jobs for
// it, each with the dependencies and link flags of its own declaration.
// Neither is built: both fail, and say which configurations declare
// them. Only tests of different configurations are looked at: a test
// one configuration declares twice is as it was.
std::vector<std::string> clashes(filtered.size());
{
std::unordered_map<fs::path, std::vector<std::size_t>> builtInto;
for (std::size_t i = 0; i < filtered.size(); ++i) {
builtInto[fs::absolute(filtered[i]->config.PcmDir()).lexically_normal()].push_back(i);
}
for (const auto& [directory, sharing] : builtInto) {
std::vector<const Configuration*> declaring;
for (const std::size_t i : sharing) {
if (!std::ranges::contains(declaring, owners[i])) declaring.push_back(owners[i]);
}
if (declaring.size() < 2) continue;
std::string names;
for (const Configuration* cfg : declaring) {
if (!names.empty()) names += ", ";
names += cfg->name;
}
for (const std::size_t i : sharing) {
clashes[i] = std::format("{} each declare a test named {}, which would be built for each of them in {}: give each test a name of its own", names, filtered[i]->config.name, directory.string());
}
}
}
// 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
? opts.jobs
: std::max(1u, std::thread::hardware_concurrency());
@ -549,6 +787,18 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
TestResult r;
r.name = t.config.name;
if (!clashes[i].empty()) {
r.outcome = TestOutcome::Fail;
r.output = clashes[i];
r.exitCode = -1;
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
continue;
}
// Declarative preconditions set via TestBuilder::Requires. Evaluated
// before the build so a missing tool/file/env turns into a Skip without
// paying the compile cost. Reports the first failure only — once one
@ -623,16 +873,47 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
// triple and nothing for wasm, so every wasm test was handed to
// wasmtime without the .wasm it was linked as.
fs::path binary = ExpectedOutput(t.config);
std::error_code temporaryError;
fs::create_directories(temporary[i], temporaryError);
try {
r = RunSingleTest(t, binary, timeout);
if (temporaryError) throw std::runtime_error(std::format("cannot make the test's TMPDIR {}: {}", temporary[i].string(), temporaryError.message()));
r = RunSingleTest(t, binary, timeout, opts.compositorOverride, temporary[i]);
} catch (const std::exception& e) {
r.outcome = TestOutcome::Fail;
r.output = std::format("runner threw: {}", e.what());
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()) {
WriteLog(projectCfg.path, r.name, r.output);
WriteLog(owners[i]->path, logName, r.output);
}
{
@ -678,3 +959,8 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
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,6 +151,24 @@ namespace {
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 {
if (libcxxDir.empty()) return {};
return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string());
@ -207,11 +225,13 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.clang = "clang";
tc.llvmAr = "llvm-ar";
tc.llvmReadelf = "llvm-readelf";
tc.clangScanDeps = "clang-scan-deps";
} else {
tc.clangxx = tc.prefix / "bin" / "clang++";
tc.clang = tc.prefix / "bin" / "clang";
tc.llvmAr = tc.prefix / "bin" / "llvm-ar";
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")) {
tc.llvmIncludeDir = tc.prefix / "include";
}
@ -396,11 +416,22 @@ const Toolchain& Crafter::GetToolchain() {
return tc;
}
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()));
if (version.exitCode == 0) {
std::string first = version.output.substr(0, version.output.find('\n'));
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 Resolved;

View file

@ -70,7 +70,7 @@ export namespace Crafter {
// Write the AGENTS.md beside `projectFile` from the AGENTS.template.md
// beside it, with the AGENTS.consumer.md of every dependency
// project.dependencyNotes selects merged in. `project` is the
// Configuration that file returned, after LoadProject: loading is what
// Configuration that file returned, once it is loaded: loading is what
// found the dependencies. Creates AGENTS.md when it is missing, and
// replaces only one a build wrote: an AGENTS.md someone wrote is left
// alone, with a warning. Without a template it writes nothing, and only
@ -81,4 +81,17 @@ export namespace Crafter {
// a dependency's unusable notes are warnings: the notes never fail a
// build, and nothing is reported when nothing would have been written.
bool UpdateAgentsMd(const Configuration& project, const fs::path& projectFile);
// The same for a project file that returned several configurations.
// Each one the file made itself selects, by its dependencyNotes, among
// the projects that one is built against, and the notes are merged: a
// dependency's are in when a configuration that asks for them leads to
// it. The file's `#pragma crafter dependency` lines, and a
// configuration it loaded from another project and returns, which
// counts as a dependency here, go by the widest of those settings, and
// by Transitive when the file made no configuration itself. A
// configuration is another project's when GitProject or LocalProject
// loaded it from another project file than `projectFile`, two files
// being one when they resolve to one path: one they loaded from
// `projectFile` itself is that file's own.
bool UpdateAgentsMd(std::span<const Configuration* const> configurations, const fs::path& projectFile);
}

View file

@ -69,6 +69,15 @@ export namespace Crafter {
// path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from
// these directories into files/lib.
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 {
@ -167,6 +176,11 @@ export namespace Crafter {
std::int32_t signal = 0;
std::chrono::milliseconds duration{0};
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
@ -440,9 +454,11 @@ export namespace Crafter {
// What a Script's callback is handed when `crafter-build run <name>`
// starts it.
struct ScriptContext {
// The Configuration project.cpp returned. Read the project through
// this rather than capturing the local in CrafterBuildProject by
// reference: that local is gone by the time a script runs.
// The Configuration the script is declared on: the one project.cpp
// returned, or of several the one whose `scripts` holds it. Read the
// project through this rather than capturing a local of the entry
// point by reference: the local need not be the object that the
// entry point returned.
Configuration& project;
// Absolute directory of the project file. Commands run in the
// directory crafter-build was started from, like everything else it
@ -507,6 +523,26 @@ export namespace Crafter {
// sandbox permissions any configuration may declare for the
// executables built on it.
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<Implementation> implementations;
std::vector<fs::path> cFiles;
@ -595,19 +631,19 @@ export namespace Crafter {
// Crafter.Build:Agents):
// cfg.dependencyNotes = DependencyNotes::Direct;
// Only read on the Configuration project.cpp returns; a dependency's
// setting decides nothing for its consumers. Not part of VariantId:
// the notes change nothing that is compiled.
// setting decides nothing for its consumers. Of several returned
// configurations, each one the project file made itself has its own
// read, for what that one is built against (see UpdateAgentsMd). Not
// part of VariantId: the notes change nothing that is compiled.
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);
// 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
// against this Configuration's path; target/march/mtune/sysroot/debug
// and cudaArch are inherited from this Configuration so cross-arch
@ -662,7 +698,7 @@ export namespace Crafter {
compileKey += '|';
compileKey += debug ? '1' : '0';
compileKey += '|';
compileKey += sysroot;
compileKey += ResolvedSysroot(toolchain);
for (const Define& d : defines) {
compileKey += "|D:";
compileKey += d.name;
@ -748,6 +784,25 @@ export namespace Crafter {
Packaging ResolvedPackaging() const {
return type == ConfigurationType::Executable && packaging == Packaging::Flatpak ? Packaging::Flatpak : Packaging::None;
}
// What `sysroot` comes to for this configuration under `toolchain`:
// the toolchain's WASI sysroot for a wasm32 target that names none,
// `sysroot` as it stands for every other configuration. The
// commands that compile and link a wasm32 configuration and the
// names of its directories read the sysroot through here, so the
// configuration is the same thing before its build as during it and
// after. Build() used to store the WASI sysroot in `sysroot` on its
// way in instead, and VariantId hashes the sysroot: a wasm32
// configuration whose target was set without ApplyStandardArgs,
// which stores it when the project file is loaded, had one
// BuildDir, BinDir and PcmDir until its build started and others
// from then on. A build pass records a dependency's build under its
// PcmDir, so one that two configurations of the pass were built on
// was looked up under the first directory by the one that asked
// before its build had started and under the second by the one
// that asked after, and was built a second time.
std::string ResolvedSysroot(const Toolchain& toolchain) const {
return sysroot.empty() && target.starts_with("wasm32") ? toolchain.wasiSysroot.string() : sysroot;
}
fs::path PcmDir() const {
return type == ConfigurationType::Executable ? BuildDir() : BinDir();
}
@ -767,6 +822,19 @@ export namespace Crafter {
// unavailable runner becomes a Fail instead of a silent Skip — the
// dependency has to be declared to be allowed to be missing.
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,
@ -781,6 +849,36 @@ export namespace Crafter {
// disagree about the file name.
fs::path ExpectedOutput(const Configuration& config);
// Where Build leaves the object of `source`, one of this Configuration's
// implementation units (.cpp), C sources (.c) or CUDA sources (.cu),
// given with its extension; a relative `source` is taken against the
// working directory, as Build takes cFiles and cuda. The dependency file
// the compiler writes lies beside it, as <object>.d.
//
// The object is named from where the source lies: under
// BuildDir()/objects by the source's path from the Configuration's
// `path`, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source
// outside that directory, under BuildDir()/objects-outside by its whole
// path. The name ends in _impl.o for a .cpp, _source.o for a .c and
// _cuda.o for a .cu. So two sources have one object only when their
// paths are one once `.` and `..` are taken out of them as they are
// written: any other two differ by path or by ending in one of the two
// directories, and the two directories share nothing.
//
// Objects were named from the file name alone, in BuildDir() itself:
// a/Thing.cpp and b/Thing.cpp were both compiled into Thing_impl.o,
// each over the other, and the link was given that object twice. The
// link then failed, or, in a debug build of two sources that define
// nothing another file names, gave a program with one source's code
// twice and the other's not at all (issue #50).
//
// An interface unit's object is not named here. It lies in BuildDir()
// itself, named by the unit's file name alone, as its BMI is: clang
// looks a BMI up by its module's name, so two interface files of one
// name would have to be one module. Throws std::invalid_argument for a
// `source` with any other extension.
fs::path ObjectPath(const Configuration& config, const fs::path& source);
// `crafter-build install`: makes the Flatpak of the files/ `config` was
// built as (see Packaging::Flatpak), with its permissions, puts it into
// the project's repo, and installs it for this user from a user remote
@ -848,6 +946,35 @@ export namespace Crafter {
// checks everything again and pulls unpinned externals again.
BuildResult Build(Configuration& config, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
// Builds every one of `configurations`, the configurations a project
// file returns, in the pass `depResults` records. Each is built by
// Build(), as a project's one configuration is, and its result then
// goes into the record under its PcmDir, where Build() records a
// dependency. What two of them depend on is built once, and so is one
// that another of them is built on: it is built before the other
// starts, and the other finds it in the record. The first is built on
// the calling thread and each other one on a thread of its own, all of
// them to the end: one that fails stops none of the others. Returns the
// errors of the ones that failed, in the order given and each message
// once, so a dependency that failed for three of them is reported once,
// and an empty string when all were built. A configuration the list
// names twice is built once.
//
// With a wasm executable that declares wasmVariants among them, or
// among what they are built on, they are built one after the other on
// the calling thread instead: its build rewrites the configurations it
// is built on for each variant, which no other build may be reading.
//
// Refuses, before building anything, two of them that would be built
// into one directory (same path, name, target and compile state), which
// would be two builds writing the same files at once; a set of them in
// which each is built on something that is built into the directory of
// another, so that none could be built first; and one that is built on
// something of its own directory when another of them is built on that
// directory too, since the record holds one result for a directory and
// the other could be given either.
std::string BuildAll(std::span<Configuration* const> configurations, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
// Takes main's argv verbatim so the CLI entry point is a one-liner;
// the shape is inherited from the language, not chosen here.
// lint-disable-next-line no-char-pointer
@ -930,9 +1057,9 @@ namespace Crafter {
// compile command and of the std module's, which have to agree flag for
// flag.
std::string WasmCompileFlags(const Configuration& config);
// The flags BuildStdPcm compiles the std module with, after the base
// command and before the source, each with a leading space. StdPcmKey
// hashes the same string, so the command and the directory it writes to
// cannot disagree about what decides the BMI.
std::string StdPcmFlags(const Configuration& config);
// The flags BuildStdPcm compiles the std module with under `toolchain`,
// after the base command and before the source, each with a leading
// space. StdPcmKey hashes the same string, so the command and the
// directory it writes to cannot disagree about what decides the BMI.
std::string StdPcmFlags(const Configuration& config, const Toolchain& toolchain);
}

View file

@ -76,14 +76,14 @@ export namespace Crafter {
// clone can still differ in includeDirs, libDirs and libs.
ExternalBuildResult ExternalOutputs(const ExternalDependency& dep, std::string_view target);
// The args the project file now running its CrafterBuildProject was
// loaded with: everything that function receives, --target=, --debug and
// The args the project file now running its entry point was loaded
// with: everything that function receives, --target=, --debug and
// the other standard flags included. Not cfg.projectArgs, which holds
// only what ApplyStandardArgs left uninterpreted: `.args =
// cfg.projectArgs` would drop the target and the build type. Empty
// everywhere else, because it reads the stack LoadProject keeps per
// everywhere else, because it reads the stack the loader keeps per
// thread, as IsTopLevelProject does: outside a project file, on any
// thread but the one running it, once CrafterBuildProject has returned
// thread but the one running it, once the entry point has returned
// (a script runs later), and before it is called, which covers the
// file's static initialisers and its `#pragma crafter dependency`
// pre-pass. The specs below default their args to it. Defined beside
@ -97,7 +97,7 @@ export namespace Crafter {
// GitSource picks the revision: leave branch + commit empty for the
// remote's default branch HEAD (sloppy but convenient), set branch to
// track a branch tip, or set commit to pin to an immutable SHA. args are
// what the dep's CrafterBuildProject receives. They default to this
// what the dep's entry point receives. They default to this
// project's own, read when the spec is made, so --target=, --march=,
// --debug and the project's own flags reach every sibling down a chain
// without being passed. Set them to forward something else: {} for
@ -105,19 +105,28 @@ export namespace Crafter {
// a flag only this project reads. Give such a list to every sibling:
// Build() refuses a graph in which two paths load one project with two
// different lists, since the program would end up with both builds.
// configuration picks among the configurations of a project file that
// returns several (CrafterBuildConfigurations), by Configuration::name.
// Left empty it is the first one the file returns, so a project that
// grows a second configuration puts it after the one its consumers
// already get.
struct GitProjectSpec {
GitSource source;
fs::path projectFile = "project.cpp";
std::vector<std::string> args = ProjectArgs();
std::string configuration;
};
// Clones the spec's git URL into the external cache, recursively
// LoadProject's the remote's project.cpp, and returns a stable
// Configuration* you can drop into cfg.dependencies. The clone is keyed by
// url+branch+commit+projectFile alone, so every arg list builds in the
// same working tree, each into variant directories of its own. The
// Configuration is owned by an internal cache for the lifetime of the
// build, keyed by the clone and the args: identical specs share one.
// Clones the spec's git URL into the external cache, loads the remote's
// project.cpp in turn, and returns a stable Configuration* you can drop
// into cfg.dependencies: the configuration the spec picks of the ones
// that file describes. The clone is keyed by url+branch+commit+projectFile
// alone, so every arg list builds in the same working tree, each into
// variant directories of its own. What the file describes is kept in an
// internal cache for the lifetime of the build, keyed by the clone and
// the args: identical specs share one Configuration, and two that differ
// only in `configuration` share one load of the file. Throws when the
// file has no configuration of the name the spec asks for, or two.
Configuration* GitProject(const GitProjectSpec& spec);
// Specification for a local sibling crafter-build project (e.g. an
@ -126,12 +135,13 @@ export namespace Crafter {
struct LocalProjectSpec {
fs::path projectFile; // relative to cwd or absolute
std::vector<std::string> args = ProjectArgs(); // as GitProjectSpec::args
std::string configuration; // as GitProjectSpec::configuration
};
// Same as GitProject but for a local on-disk project — no fetch, no
// cache copy. Resolves projectFile to its canonical absolute path and
// recursively LoadProject's it. Returns a stable Configuration* owned
// by the same internal cache as GitProject.
// loads it in turn. Returns a stable Configuration* kept by the same
// internal cache as GitProject.
Configuration* LocalProject(const LocalProjectSpec& spec);
// Clone (or update) the given git source into the shared external
@ -147,11 +157,11 @@ export namespace Crafter {
namespace Crafter {
// Where GitProject or LocalProject loaded a Configuration from. The
// loader keeps this beside the cache that owns the Configuration, since
// the Configuration itself cannot say: only the one they return has its
// path rebased, and the configurations a dependency's project file makes
// for itself keep a path such as "./", which resolves against the
// consumer's directory.
// loader keeps this beside the cache that holds the Configuration, since
// the Configuration itself cannot say: only the ones its project file
// returns have their paths rebased, and the configurations a
// dependency's project file makes for itself and does not return keep a
// path such as "./", which resolves against the consumer's directory.
struct LoadedProject {
fs::path projectFile; // absolute
// What a consumer's AGENTS.md calls it: the repository's name for a
@ -166,8 +176,20 @@ namespace Crafter {
// Two specs that pin one library differently are one library.
std::string identity;
};
// The LoadedProject behind a Configuration that GitProject or
// LocalProject returned; nullopt for any other: the project crafter-build
// was pointed at, and every configuration a project file makes itself.
// The LoadedProject behind a Configuration that a project file GitProject
// or LocalProject loaded returned, the ones the spec did not pick
// included; nullopt for any other: what the project file crafter-build
// was pointed at makes itself, and what a loaded project file makes for
// itself and does not return.
std::optional<LoadedProject> LoadedProjectOf(const Configuration& cfg);
// The project that keeps `cfg` to itself: one GitProject or LocalProject
// loaded whose project file did not return `cfg`, while a configuration
// that file did return led to it when the file was loaded. A
// configuration leads to what it is built on (`dependencies`) and to
// the configurations of its tests (`tests`), and through each of those
// to what that one leads to. nullopt for every other configuration: one
// a loaded project file returned, and one that nothing a loaded project
// file returned led to, such as what the project file crafter-build was
// pointed at makes itself.
std::optional<LoadedProject> KeptBy(const Configuration& cfg);
}

View file

@ -3,6 +3,7 @@
export module Crafter.Build:Implementation;
import std;
import :Jobs;
namespace fs = std::filesystem;
namespace Crafter {
@ -10,15 +11,21 @@ namespace Crafter {
export class ModulePartition;
export class Implementation {
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<ModulePartition*> partitionDependencies;
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;
Implementation(fs::path&& path);
bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const;
void Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const;
// Whether `object`, the object Build() keeps for this unit
// (ObjectPath), has to be written again.
bool Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const;
// Adds the job that compiles this unit into `object` to `jobs`, after
// the BMIs of the stale interface units it imports
// (ModulePartition::Schedule, Module::Schedule), whose own objects go
// to `buildDir`. For a unit Check found stale. `shown` is the source
// as the job's progress line names it.
void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const;
};
}

View file

@ -3,51 +3,83 @@
export module Crafter.Build:Interface;
import std;
import :Jobs;
namespace fs = std::filesystem;
namespace Crafter {
export class Module;
export class ModulePartition {
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<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
// Names from `import X;` that matched neither a module in this
// Configuration nor one reachable through its dependencies at the time
// the source was scanned. Retried by ResolvePendingImports (see
// 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;
std::atomic<bool> compiled;
// The state of the Build() that made this unit: 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 checked = false;
bool scheduled = false;
std::optional<JobGroup::Job> precompileJob;
std::string name;
fs::path path;
ModulePartition(std::string&& name, fs::path&& path);
// Whether this unit's BMI has to be written again. The object made
// from the BMI is not Check's to judge: see Schedule.
bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min());
void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError);
// Adds the jobs this unit needs to `jobs`, once however often it is
// called, and returns the one that writes its BMI, if there is one.
//
// A unit Check found stale gets two, one for each run of `clang`: the
// BMI, after the BMIs of the stale units this one imports, which are
// scheduled here as well, and then the object from that BMI, which
// only the link waits for, so that the units importing this one start
// when the first is done.
//
// A unit whose BMI is up to date gets the second job alone when its
// object is missing or older than the BMI. A build that fails or is
// interrupted between the two leaves a unit like that, and by its BMI
// alone every build after it would call the unit built: the link then
// took the object of the source before the edit, or found none.
//
// Every unit this one imports must have been checked: Build() checks
// all of a configuration's interfaces before it schedules any.
std::optional<JobGroup::Job> Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir);
};
export class Module {
public:
// A primary module interface unit imports things too — `import Base;`
// in `export module Widget;` is as much a layout dependency as the
// same line in a partition. Recorded on the same three vectors, with
// the same meanings, so Check() can see through them and Compile()
// can order itself behind a sibling module in the same Configuration
// (issue #26).
// same line in a partition. Recorded as a partition records the
// modules it imports, with the same meanings, so Check() can see
// through them and Schedule() can order itself behind a sibling
// module in the same Configuration (issue #26). The partitions it
// imports need no entry: it is checked and built after all of its
// module's partitions.
std::vector<Module*> moduleDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
std::vector<std::string> pendingImports;
std::atomic<bool> compiled;
// As in ModulePartition.
bool needsRecompiling = false;
bool checked = false;
bool scheduled = false;
std::optional<JobGroup::Job> precompileJob;
std::vector<std::unique_ptr<ModulePartition>> partitions;
std::string name;
fs::path path;
Module(std::string&& name, fs::path&& path);
bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min());
void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError);
// As ModulePartition::Schedule, for the primary interface, and
// schedules every partition of the module with it. The primary
// interface comes after every stale partition of the module,
// whichever of them it imports, and after the stale sibling modules
// it imports.
std::optional<JobGroup::Job> Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir);
};
}

View file

@ -0,0 +1,129 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Build:Jobs;
import std;
export namespace Crafter {
// The threads build steps run on: a fixed number of workers taking jobs
// from one queue, so that no more steps run at once than there are
// workers, whichever builds they belong to. Process() is the pool every
// build in this process shares, with a worker per hardware thread.
//
// A job is one step of a build: one compiler, linker or archiver run, one
// shader or asset compiled in process. The pool bounds the steps that run
// at once, not the threads a step starts for itself, as lld does for a
// link and the compressor of Crafter.Asset for an asset.
//
// A job never waits for another job. Whatever waits does so on a
// thread that is not a worker: a Build() for the builds of its
// dependencies, a step for the steps it comes after (JobGroup holds it
// back instead). A worker that waited for a job still in the queue would
// keep from it the very thread it needs, and with every worker waiting
// like that nothing would run again.
//
// Before this, Build() started a thread for every stale shader, asset
// to compress, C, CUDA and C++ unit, and nothing bounded how many of
// them ran at once.
class JobPool {
public:
// At most `workers` jobs at once, at least one. The threads are
// started as jobs need them: a build with two stale files starts two.
explicit JobPool(std::uint32_t workers);
// Runs what is still queued, then joins the workers. Nothing may be
// handing it jobs any more: every group on it is gone by then.
~JobPool();
JobPool(const JobPool&) = delete;
JobPool& operator=(const JobPool&) = delete;
// The pool of this process: one worker per hardware thread
// (std::thread::hardware_concurrency), and one where that is not
// known. Never destroyed, so that its workers are not joined while
// the statics the last job may still be using are being destroyed.
static JobPool& Process();
std::uint32_t Workers() const;
// Runs `work` on a worker and returns when it has finished; what it
// throws is thrown here. For a step that stands by itself, as
// RunBuildCommand uses it for a link. Called on a worker of this
// pool it runs `work` there and then, since that thread is the one
// the step would have occupied.
void Run(const std::function<void()>& work);
private:
friend class JobGroup;
// Queues `job`, which must not throw. Throws only when the pool has
// no thread and cannot start one, and then `job` is not queued.
void Submit(std::function<void()> job);
void Work();
const std::uint32_t limit;
std::mutex mutex;
std::condition_variable wake;
std::deque<std::function<void()>> queue;
std::vector<std::thread> threads;
// Workers waiting for a job. A job queued while one waits is its to
// take, so a thread is only started for a job beyond those.
std::uint32_t idle = 0;
bool stopping = false;
};
// The jobs of one piece of work, such as the build of a configuration,
// on the workers of a pool. A job starts once every job it was added
// after has finished, so the order steps need (a unit after the BMIs it
// imports) costs no thread while it is waited for.
//
// The first job to fail fails the group: no job of it starts after that,
// the ones already running finish, and Wait() returns that first error.
// Fail() does the same for work done outside the jobs, so one group
// holds the outcome of everything a build runs at once.
class JobGroup {
public:
using Job = std::size_t;
// Throws std::logic_error on a worker of `pool`: a job that waited
// for jobs of its own would occupy a worker they need (see JobPool).
explicit JobGroup(JobPool& pool = JobPool::Process());
// Keeps what has not started from starting and waits for what is
// running, so a job never outlives what it was given by reference,
// whichever way the scope that made the group is left.
~JobGroup();
JobGroup(const JobGroup&) = delete;
JobGroup& operator=(const JobGroup&) = delete;
// Adds a job, counted as a Progress::Task under `label` from now
// until it has finished or been skipped. It starts once every job in
// `after` has finished, at once when there is none; `after` names
// jobs of this group, so a job can only come after ones added before
// it and no two can wait for each other. `work` returns what went
// wrong, empty when nothing did; an exception it throws is its error
// too. It runs on a worker: it must not wait for other jobs, and it
// must own what it uses or use only what outlives the group.
Job Add(std::string label, std::function<std::string()> work, std::span<const Job> after = {});
// Fails the group with `error`, as a job returning it would. Without
// effect on a group that has already failed.
void Fail(std::string error);
bool Failed() const;
// Returns once every job added so far has finished or been skipped:
// the first error, empty when there was none.
std::string Wait();
private:
struct Node;
void Start(Node& node);
void Execute(Node& node);
JobPool& pool;
mutable std::mutex mutex;
std::condition_variable settled;
// Owned through pointers: a job on a worker holds on to its node
// while Add() grows the vector.
std::vector<std::unique_ptr<Node>> nodes;
std::size_t unfinished = 0;
bool failed = false;
std::string error;
};
}

View file

@ -30,7 +30,8 @@ export namespace Crafter {
// Absolute path of the loaded project.cpp. It is linted too, and its
// parent directory is the project root that decides which dependency
// Configurations contribute rules/files (GitProject / cache-dir deps
// are foreign code and skipped). Empty => fall back to cfg.path.
// are foreign code and skipped). Empty => fall back to cfg.path, of
// several configurations the first one's.
std::filesystem::path projectFile;
};
@ -62,4 +63,10 @@ export namespace Crafter {
// findings compiler-style (Report), would-change paths (Check), or
// formatted paths (Apply), plus a summary line.
LintSummary RunLint(Configuration& projectCfg, const RunLintOptions& opts);
// The same for the several configurations a project file returns, as
// one run over all of them: each is a root, and the roots come before
// what any of them depends on, in the order given. A rule two of them
// register under one name runs once, as the first of them in that order
// registered it, and a source two of them reach is linted once.
LintSummary RunLint(std::span<Configuration* const> configurations, const RunLintOptions& opts);
}

View file

@ -42,6 +42,11 @@ namespace Crafter {
// Returns an empty string on success (any warnings go to the user via
// Progress::Diagnostic), otherwise the compiler's diagnostics. Callers
// therefore keep the `if (!result.empty())` shape they already had.
//
// The command runs on a worker of JobPool::Process(), so no more of these
// steps run at once than that pool has workers: called on one of its
// workers it runs there, called from any other thread it waits for one.
// A step that runs a compiler any other way is not counted.
std::string RunBuildCommand(std::string_view command);
export CommandResult RunCommandWithTimeout(std::string_view command, std::chrono::seconds timeout);
// Runs `command` through sh with this process's own stdin, stdout and
@ -53,6 +58,67 @@ namespace Crafter {
// and not to crafter-build, which then sees it as exit code 130.
// Project scripts reach this through ScriptContext::Run.
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
// 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
@ -93,17 +159,47 @@ namespace Crafter {
// or the org.flatpak.Builder app where the host has none.
std::int32_t RunHostFlatpakBuilder(std::string_view arguments);
std::string GetBaseCommand(const Configuration& config);
// The configurations `projectFile` describes, in the order it gives them.
// Compiles the file into a shared object in the build/ beside it, unless
// the one there is current, loads that into this process and calls the
// file's entry point with `args`. A project file defines one of two:
// extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args);
// extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view> args);
// The first is a project of one configuration, which comes back as a
// list of one. The second is a project of several that need not have
// anything to do with each other, such as a library and a tool, or the
// programs of one repository; they come back as the file returned them.
// The two names are how a loaded file says which it is: both are C
// symbols, which carry no return type, so one name with two return types
// would be called as whichever the loader guessed. Throws for a file
// that defines neither or both, and for a CrafterBuildConfigurations
// that returns nothing, a null pointer, one configuration twice, or one
// that a project GitProject or LocalProject loaded keeps to itself
// (KeptBy): every configuration in the list is one the file made or one
// those two returned.
//
// The pointers are used for as long as the process runs. What a
// CrafterBuildConfigurations returns is its project file's to keep that
// long, at addresses that do not change: in a std::deque the file only
// adds to, one new set per call, or what GitProject and LocalProject
// gave it. What a CrafterBuildProject returns is kept here, constructed
// by that call and never moved.
export std::vector<Configuration*> LoadConfigurations(const fs::path& projectFile, std::span<const std::string_view> args);
// What the CrafterBuildProject of `projectFile` returns, loaded as
// LoadConfigurations loads it. Throws for a project file that defines
// CrafterBuildConfigurations: the configurations that one returns stay
// where the file keeps them and cannot be returned by value.
export Configuration LoadProject(const fs::path& projectFile, std::span<const std::string_view> args);
// A dependency the project file currently running its CrafterBuildProject
// A dependency the project file currently running its entry point
// declared with `#pragma crafter dependency`, so it can also be wired
// into the build graph (a test that links the same module, say) without
// spelling the source twice. `name` is the dependency's Configuration
// name or any module it exports — whatever the project file `import`s.
// Throws when no such dependency was declared, or when called from
// anywhere other than inside LoadProject.
// anywhere other than inside a project file's load.
export Configuration* ProjectDependency(std::string_view name);
// True while the project file crafter-build was pointed at runs its
// CrafterBuildProject, and when no project file is running at all; false
// entry point, and when no project file is running at all; false
// inside a dependency's project file (a `#pragma crafter dependency`,
// GitProject or LocalProject target). Wire anything only the project's
// own build or test run needs behind it. The case that forced it: a
@ -112,9 +208,9 @@ namespace Crafter {
// project file in turn and the two recurse until the cycle guard throws.
export bool IsTopLevelProject();
// What the `#pragma crafter dependency` lines of `projectFile` resolved
// to the last time LoadProject loaded it in this process, in file order;
// to the last time it was loaded in this process, in file order;
// empty when it has none or was never loaded. Unlike ProjectDependency
// this still answers once LoadProject has returned, which is when the
// this still answers once the load has returned, which is when the
// dependency notes of the project crafter-build was pointed at are
// gathered (Crafter.Build:Agents).
std::vector<Configuration*> PragmaDependencies(const fs::path& projectFile);
@ -129,10 +225,10 @@ namespace Crafter {
// derives <prefix>/share/crafter-build from the running executable's path.
export fs::path GetCrafterBuildHome();
// Newest mtime among the prerequisites a compiler recorded in `depFile`
// (clang's `-MD -MF <artifact>.d`). This is how a build step learns which
// headers its source pulled in: the module scanner only reads `import`
// lines, so an `#include`d file is invisible to it until the compiler
// reports what it actually opened.
// (clang's `-MD -MF <artifact>.d`), or clang-scan-deps for the scan of
// a C++ source. This is how a build step learns which headers its
// source pulled in: only the tool that preprocessed the source knows
// which files its #includes opened.
//
// Returns file_time_type::max() when freshness cannot be proven — no
// depfile (nothing has compiled this artifact since depfiles were emitted,

View file

@ -12,8 +12,10 @@ export namespace Crafter::Progress {
// RAII work-unit marker. Construction inflates the running total; destruction
// increments completed and (on Default + TTY) redraws the status line. Move
// semantics are disabled — keep these as plain stack locals inside the worker
// lambda so the destructor fires when that thread's work ends.
// semantics are disabled — keep these as plain stack locals around the work
// they count, so the destructor fires when it ends. A job of a JobGroup
// gets one from Add(), made when the job is queued, which is what puts
// work that has not started yet in the total.
class Task {
public:
explicit Task(std::string label);

View file

@ -19,7 +19,8 @@ export namespace Crafter {
// Print the script names instead of running one.
bool listOnly = false;
// Absolute path of the loaded project.cpp; its directory becomes
// ScriptContext::projectDir. Empty => fall back to cfg.path.
// ScriptContext::projectDir. Empty => fall back to the path of the
// configuration the script is declared on.
std::filesystem::path projectFile;
};
@ -37,4 +38,10 @@ export namespace Crafter {
// (a raw wait status passed along by mistake) would otherwise wrap to
// success.
std::int32_t RunScript(Configuration& projectCfg, const RunScriptOptions& opts);
// The same over the scripts of several configurations, the ones a
// project file returns, as one list in the order given: a name two of
// them declare is a name declared twice, and a configuration the list
// names twice counts once. The script's ScriptContext::project is the
// configuration it is declared on.
std::int32_t RunScript(std::span<Configuration* const> configurations, const RunScriptOptions& opts);
}

View file

@ -24,8 +24,8 @@ export namespace Crafter {
// interfaces. The builder only mutates compile state, deps, runtime
// args, and requires; it deliberately does NOT expose Sources() to
// avoid the double-`GetInterfacesAndImplementations` footgun (calling
// it twice would re-parse the same .cppm files into duplicate Module
// entries).
// it twice would list the same .cppm files twice, and the build would
// make a Module entry of each listing).
struct TestBuilder {
Configuration* parent;
std::size_t index;
@ -53,10 +53,17 @@ export namespace Crafter {
TestBuilder& LinkFlag(std::string f);
// Append a single compile flag.
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 {
std::vector<std::string> globs;
// Tests built and run at once, from --jobs=; 0 is one per hardware
// thread. It counts tests, not build steps: the steps of their builds
// run on JobPool::Process() under that pool's own limit, and a test
// that is running is not one of them.
std::int32_t jobs = 0;
std::optional<std::chrono::seconds> timeoutOverride;
bool listOnly = false;
@ -71,6 +78,10 @@ export namespace Crafter {
// Target scoping is unnecessary because targetFilter ensures the run
// contains only one target's tests.
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 {
@ -84,15 +95,53 @@ export namespace Crafter {
};
TestSummary RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs = {});
TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout);
// The tests of several configurations, those a project file returns, as
// one run: one sweep over the targets they declare, one summary, and
// one build pass per target, so a library that tests of two of them link
// is built once. The log a failed, crashed or timed-out test leaves
// goes under the path of the configuration that declares it. A test
// belongs to one configuration: where two of them each declare one that
// would be built into the same directory, which two tests of one name
// compiled alike are, both fail without being built and name the
// 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 = {});
// Runs `binary` as `test` with its runner, its arguments and `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 = {});
// Parent-project access for test fixtures. Run() sets the pointer to the
// root project's Configuration before discovery; fixtures call ParentLib()
// to obtain a Configuration* for one of the parent's libraries (or the
// parent itself) so they can declare it as a dependency without rebuilding
// the lib config from scratch. Lookup is by Configuration::name and
// recurses through the parent's dependency graph.
// The configurations of the project crafter-build was pointed at, by
// name. Run() hands SetParentProject what the project file returned,
// once it has loaded. ParentLib() then finds a Configuration* by
// Configuration::name among them and what they depend on, searching the
// dependency graph of each in the order the file returned them, and
// throws when none has that name or no project is set.
void SetParentProject(Configuration* parent);
void SetParentProject(std::span<Configuration* const> parents);
Configuration* ParentLib(std::string_view name);
}

View file

@ -7,11 +7,11 @@ namespace fs = std::filesystem;
export namespace Crafter {
// The compiler crafter-build drives and what sits next to it, resolved
// once per process by GetToolchain(). Every clang++, clang and llvm-ar
// the tool spawns, the libclang the linter dlopens, the std module
// source and the default sysroots come from here, so a toolchain
// installed anywhere other than /usr (the Flatpak carries its own under
// /app) needs no per-call-site knowledge.
// once per process by GetToolchain(). Every clang++, clang, llvm-ar and
// clang-scan-deps the tool spawns, the libclang the linter dlopens, the
// std module source and the default sysroots come from here, so a
// toolchain installed anywhere other than /usr (the Flatpak carries its
// own under /app) needs no per-call-site knowledge.
struct Toolchain {
// LLVM install prefix. Empty when the tools are bare names on PATH.
fs::path prefix;
@ -20,6 +20,9 @@ export namespace Crafter {
fs::path llvmAr;
// What a packaged program's shared libraries are read with.
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
// path; empty otherwise.
fs::path llvmIncludeDir;
@ -97,9 +100,37 @@ export namespace Crafter {
// `clang++ --version`; both empty when clang++ could not be run.
std::string hostTriple;
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.
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.
std::string LibcxxCompileFlags() const;
// Where libc++.so.1 is when clang would not find it itself: an

View file

@ -6,6 +6,7 @@ export import :Toolchain;
export import :Flatpak;
export import :Clang;
export import :Platform;
export import :Jobs;
export import :Implementation;
export import :Shader;
export import :External;

View file

@ -12,9 +12,10 @@
<description>
<p>
A build system for C++26 modules. Project descriptions are C++: a
project.cpp constructs a Configuration and returns it, and crafter-build
compiles, loads and executes it. The Flatpak carries its own LLVM, so
every machine builds with the same clang, lld, libc++ and WASI sysroot.
project.cpp constructs a Configuration, or several, and returns them,
and crafter-build compiles, loads and executes it. The Flatpak carries
its own LLVM, so every machine builds with the same clang, lld, libc++
and WASI sysroot.
</p>
</description>
<url type="homepage">https://forgejo.catcrafts.net/Catcrafts/Crafter.Build</url>
@ -25,6 +26,74 @@
</provides>
<content_rating type="oars-1.1"/>
<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">
<description>
<p>Fixes</p>
<ul>
<li>Two sources of a configuration may have the same file name in different directories, <code>a/Thing.cpp</code> beside <code>b/Thing.cpp</code>, and a <code>.c</code> may lie beside a <code>.cu</code> of its name (#50). An object was named from its source's file name alone, so two such sources were compiled into one object, each over the other, and the link was given that object twice: it failed, or, in a debug build of sources that define nothing another file names, gave a program with one file's code twice and the other's not at all. A <code>.cpp</code>, <code>.c</code> or <code>.cu</code> is now compiled into an object named from its path: in the build directory under <code>objects/</code>, at the source's path from <code>cfg.path</code>, or under <code>objects-outside/</code> at its whole path when it lies outside that directory, and the progress line of its compile names it by that path. An existing build directory compiles those sources once more.</li>
<li>A static library holds the objects of the sources its configuration lists and no others. Its archive was added to where it lay, which kept the object of a source that had left the project: once a source had been renamed, what was built on the library went on linking the object of the file under its old name.</li>
<li>A configuration of many sources links. The path of every object was written into the link or archive command, which the shell that runs it is given as one argument, and Linux holds one argument to 131,072 bytes on x86_64: with objects whose paths came to more, the build ended with <code>popen() failed!</code>. The link and the archive step now read their objects from a file in the build directory.</li>
</ul>
</description>
</release>
<release version="6.4.0" date="2026-11-15">
<description>
<p>New</p>
<ul>
<li>A <code>project.cpp</code> can describe several configurations that need not have anything to do with each other, such as a library and the tool that comes with it, or the programs of one repository. It defines <code>CrafterBuildConfigurations</code>, which returns a pointer to each of them, in place of <code>CrafterBuildProject</code>, which returns one configuration as before. <code>crafter-build</code> builds all of them in one pass, and one that fails does not stop the others. <code>test</code> runs the tests and <code>run</code> offers the scripts of every one the file made itself, <code>-r</code> runs the executable when exactly one of them is one, and <code>install</code> and <code>bundle</code> export the one that is packaged as a Flatpak; with more than one to choose from they stop and name them. The README's new "Several configurations" section has the details.</li>
<li>A <code>GitProject</code> or <code>LocalProject</code> spec picks one of a sibling's configurations by its name with <code>.configuration</code>, and gets the first one without it.</li>
</ul>
<p>Fixes</p>
<ul>
<li>A project loaded through <code>GitProject</code> or <code>LocalProject</code> keeps the pointers its <code>project.cpp</code> took to the <code>Configuration</code> it returns, as a test declared with <code>cfg.AddTest("T").Dependencies({ &amp;cfg })</code> holds one. The loader moved that <code>Configuration</code> after the project file had returned it, which left such a pointer dangling, and <code>crafter-build lint</code> followed it for a sibling inside the project's own directory when a rule needed an AST.</li>
<li>A wasm32 library that two configurations of one build are built on is built once when its <code>project.cpp</code> sets the target without calling <code>ApplyStandardArgs</code>. The directories such a library is built into had one name until its build started and another from then on, so a configuration that asked for the library after that did not find the build already under way and started a second one.</li>
</ul>
</description>
</release>
<release version="6.3.0" date="2026-11-14">
<description>
<p>New</p>
<ul>
<li>A build runs at most as many of its steps at once as the machine has hardware threads: 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. Until now every stale source and shader, and every asset to compress, got a thread of its own, and nothing bounded how many compilers ran side by side. An <code>ExternalDependency</code>'s CMake build is not among those steps and keeps that many jobs of its own, and <code>crafter-build test --jobs=</code> counts the tests built and run at once, as before. 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. Progress has two lines for every module interface unit, <code>Precompiling X.cppm</code> and <code>Compiling X.cppm</code>, where a module and its partitions shared one <code>Compiling interface X</code>.</li>
</ul>
<p>Fixes</p>
<ul>
<li>A module interface unit left with its BMI and without the object made from it, or with the object of its source before an edit, is given its object by the next build. A build interrupted between the two compiler runs, or whose second run failed, left a unit like that, and every later build called it up to date: the link took the old object, or failed with <code>no such file or directory</code> until the source was touched.</li>
<li>Module interface units that import each other are refused with an error that names them: two partitions, a partition and its own module, or two modules of one configuration. A first build of them used to hang with no compiler running.</li>
</ul>
</description>
</release>
<release version="6.2.0" date="2026-11-11">
<description>
<p>New</p>

View file

@ -378,6 +378,114 @@ modules:
url: https://github.com/KhronosGroup/Vulkan-ValidationLayers/archive/refs/tags/vulkan-sdk-1.4.357.0.tar.gz
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
buildsystem: simple
build-options:

View file

@ -173,12 +173,13 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
// it reaches clang, which must still see a string literal.
CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)});
{
std::array<fs::path, 15> interfaces = {
std::array<fs::path, 16> interfaces = {
"interfaces/Crafter.Build",
"interfaces/Crafter.Build-Toolchain",
"interfaces/Crafter.Build-Shader",
"interfaces/Crafter.Build-Platform",
"interfaces/Crafter.Build-Flatpak",
"interfaces/Crafter.Build-Jobs",
"interfaces/Crafter.Build-Interface",
"interfaces/Crafter.Build-Implementation",
"interfaces/Crafter.Build-External",
@ -190,11 +191,12 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
"interfaces/Crafter.Build-Progress",
"interfaces/Crafter.Build-Asset",
};
std::array<fs::path, 14> implementations = {
std::array<fs::path, 15> implementations = {
"implementations/Crafter.Build-Toolchain",
"implementations/Crafter.Build-Shader",
"implementations/Crafter.Build-Platform",
"implementations/Crafter.Build-Flatpak",
"implementations/Crafter.Build-Jobs",
"implementations/Crafter.Build-Interface",
"implementations/Crafter.Build-Implementation",
"implementations/Crafter.Build-External",
@ -245,6 +247,10 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
if (linuxTarget) {
cfg.AddTest("HelloWorld").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StaticLib").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StaticLibSourceRemoved").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("LinkManyObjects").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SameNamedSources").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ObjectPath").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ModuleInterface").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("DependencyLink").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SharedLibraryRuns").Dependencies({ CrafterBuildLib.get() });
@ -252,6 +258,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("IncrementalInterfaceChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("TransitiveInterfaceChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("IncrementalInterfaceObject").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StdPcmRebuild").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("CompilerWarning").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("CleanProject").Dependencies({ CrafterBuildLib.get() });
@ -305,14 +312,17 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("WasmExceptions").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasiSysrootWithoutExceptions").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() });
// LoadProject dlopens the synthesized project.so, which references
// Crafter:: symbols (HostTarget, Configuration ctors) that have to be
// visible from the test exe — same wiring crafter-build itself uses
// for project.so.
cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("TestTemporaryDirectory").Dependencies({ CrafterBuildLib.get() });
// Loading a project file dlopens the project.so compiled from it,
// which references Crafter:: symbols (HostTarget, Configuration
// ctors) that have to be visible from the test exe — same wiring
// crafter-build itself uses for project.so.
cfg.AddTest("ConcurrentCacheRace").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
// Same LoadProject wiring as ConcurrentCacheRace above.
// Same wiring as ConcurrentCacheRace above.
cfg.AddTest("HostCacheSourceStamp").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("HostCacheToolchainKey").Dependencies({ CrafterBuildLib.get() })
@ -331,8 +341,20 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("SiblingOwnPointers").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("ProjectConfigurations").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("SiblingConfigurations").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("BuildAll").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

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Broken;
import std;
// Does not compile: the library two of the test's programs are built on.
export std::int32_t Value() {
return Undeclared;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Broken;
int main() {
return Value();
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("good");
return 0;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Greeter;
import std;
export namespace Greeter {
std::string Greet(std::string_view name) {
return std::format("hello {}", name);
}
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Greeter;
int main() {
std::println("{}", Greeter::Greet("world"));
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Broken;
int main() {
return Value();
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("tool");
return 0;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Lower;
import std;
// Built by a configuration with the name, path and type of the one that
// builds Upper, which is built on this one.
export std::int32_t Lower() {
return 1;
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Upper;
import std;
import Lower;
export std::int32_t Upper() {
return Lower() + 1;
}

273
tests/BuildAll/main.cpp Normal file
View file

@ -0,0 +1,273 @@
// 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;
// BuildAll builds the configurations a project file returns, which need not
// have anything to do with each other, in one pass: every one of them, and
// what two of them share once.
//
// What it guards against is a configuration that goes missing or is built
// wrongly without a word: left unbuilt because another one failed, or
// because it shares an output directory with another and was taken for it;
// built twice at once because another one depends on it, each build
// writing what the other reads; and built at once with a wasm executable
// that declares variants, which rewrites the configurations it is built on
// while it builds. And against a build that never ends: a configuration
// waiting for a build of its own directory that is waiting for it.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::size_t Count(std::string_view text, std::string_view needle) {
std::size_t count = 0;
for (std::size_t pos = text.find(needle); pos != std::string_view::npos; pos = text.find(needle, pos + needle.size())) ++count;
return count;
}
// A library made of `dir`/`interface`.cppm.
void MakeLibrary(Configuration& cfg, const fs::path& dir, std::string_view name, std::string_view interface) {
cfg.path = dir;
cfg.name = name;
cfg.outputName = name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 1> interfaces = { interface };
std::array<fs::path, 0> implementations = {};
cfg.GetInterfacesAndImplementations(interfaces, implementations);
}
// A program made of `dir`/main.cpp.
void MakeProgram(Configuration& cfg, const fs::path& dir, std::string_view name) {
cfg.path = dir;
cfg.name = name;
cfg.outputName = name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::Executable;
std::array<fs::path, 0> interfaces = {};
std::array<fs::path, 1> implementations = { "main" };
cfg.GetInterfacesAndImplementations(interfaces, implementations);
}
}
int main() {
// Staged: the cases below compare what a build left behind, so each run
// starts from sources alone.
const fs::path scratch = fs::temp_directory_path() / "crafter-build-build-all";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::copy(fs::current_path() / "tests" / "BuildAll" / "fixture", scratch, fs::copy_options::recursive);
// Every one of them is built and left in the record of the pass, where
// a configuration that depends on it looks for it. hello depends on
// greeter, and greeter built from here as well as through hello was two
// builds of it at once, one of which archived the objects while the
// other was still writing them.
{
Configuration greeter;
MakeLibrary(greeter, scratch / "greeter", "greeter", "Greeter");
Configuration hello;
hello.dependencies = { &greeter };
MakeProgram(hello, scratch / "hello", "hello");
Configuration tool;
MakeProgram(tool, scratch / "tool", "tool");
std::array<Configuration*, 3> all = { &greeter, &hello, &tool };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(failed.empty(), std::format("a library, a program built on it and an unrelated program build: {}", failed));
for (const Configuration* cfg : all) {
Check(fs::exists(ExpectedOutput(*cfg)), std::format("{} was built", cfg->name));
Check(depResults.contains(cfg->PcmDir()), std::format("{} is in the record of the pass, where a configuration that depends on it finds its build", cfg->name));
}
// A list that names one of them twice builds it like any other:
// once, from nothing here, since what the build above left of it is
// removed first.
fs::remove_all(tool.BinDir(), ec);
fs::remove_all(tool.BuildDir(), ec);
std::array<Configuration*, 2> twice = { &tool, &tool };
std::unordered_map<fs::path, std::shared_future<BuildResult>> twiceResults;
Check(BuildAll(twice, twiceResults, depMutex).empty() && fs::exists(ExpectedOutput(tool)), "a configuration the list names twice is built");
Check(twiceResults.size() == 1 && twiceResults.contains(tool.PcmDir()), std::format("and is in the record of the pass once ({} entries)", twiceResults.size()));
}
// A configuration built on another of its own name, path and type: the
// two are built into one directory, the dependency first, as they were
// when a project had one configuration and Build() was all there was.
// In the record of the pass while it is still being built, the first
// would be what the record hands its dependency, which would wait for
// it while it waits for the dependency: a build that never ends.
{
Configuration lower;
MakeLibrary(lower, scratch / "twins", "twins", "Lower");
lower.outputName = "lower";
Configuration upper;
upper.dependencies = { &lower };
MakeLibrary(upper, scratch / "twins", "twins", "Upper");
std::array<Configuration*, 1> one = { &upper };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(one, depResults, depMutex);
Check(failed.empty(), std::format("a configuration built on another of the same directory builds: {}", failed));
Check(upper.PcmDir() == lower.PcmDir() && fs::exists(ExpectedOutput(upper)) && fs::exists(ExpectedOutput(lower)), "both into that one directory");
// With a program built on the upper one returned beside it, that
// directory holds two builds and the record of the pass one result:
// the program would be handed the lower one's, and be linked without
// the library it names.
Configuration program;
program.dependencies = { &upper };
MakeProgram(program, scratch / "good", "on-twins");
std::array<Configuration*, 2> both = { &program, &upper };
std::unordered_map<fs::path, std::shared_future<BuildResult>> bothResults;
const std::string refused = BuildAll(both, bothResults, depMutex);
Check(refused.contains("twins and a configuration it is built on would both be built into") && refused.contains("where on-twins looks"), std::format("a configuration built on that one, returned beside it, is refused, both by name: {}", refused));
Check(bothResults.empty() && !fs::exists(program.BuildDir()) && !fs::exists(program.BinDir()), "and refused before anything is built");
}
// Two that are each built on something of the other's directory cannot
// be put in an order, and are refused before either is built. Nothing
// here has a source: the refusal comes first.
{
const auto named = [&](Configuration& cfg, std::string_view name) {
cfg.path = scratch / "crossed";
cfg.name = name;
cfg.outputName = name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::LibraryStatic;
};
Configuration left;
Configuration right;
Configuration leftAgain;
Configuration rightAgain;
named(left, "left");
named(right, "right");
named(leftAgain, "left");
named(rightAgain, "right");
left.dependencies = { &rightAgain };
right.dependencies = { &leftAgain };
std::array<Configuration*, 2> crossed = { &left, &right };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string refused = BuildAll(crossed, depResults, depMutex);
Check(refused.contains("left, right") && refused.contains("none of them can be built first"), std::format("two configurations that each wait for the other's directory are refused, by name: {}", refused));
Check(depResults.empty() && !fs::exists(scratch / "crossed" / "bin") && !fs::exists(scratch / "crossed" / "build"), "and refused before anything is built");
}
// A wasm32 library whose target is set here and not by
// ApplyStandardArgs, so that it names no sysroot, and a program built on
// it: the program finds the library's build in the record, under the
// directory the library has before its build and after it alike. The
// library has a flag no wasm build accepts, so its build is refused on
// every machine, with a WASI sysroot or without, and a refused build is
// recorded like any other. The program is one for the host, whose own
// build gets as far as asking for the library wherever the test runs.
{
Configuration library;
MakeLibrary(library, scratch / "greeter", "wasm-greeter", "Greeter");
library.target = "wasm32-wasip1";
library.compileFlags.push_back("-fno-exceptions");
Configuration program;
program.dependencies = { &library };
MakeProgram(program, scratch / "hello", "on-wasm-greeter");
std::array<Configuration*, 2> all = { &program, &library };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(Count(failed, "wasm-greeter: -fno-exceptions") == 1, std::format("the library's refusal comes back once, for the two of them: {}", failed));
const auto recorded = std::ranges::count_if(depResults, [](const auto& entry) { return entry.first.filename().string().starts_with("wasm-greeter-"); });
Check(recorded == 1 && depResults.contains(library.PcmDir()), std::format("and the library is in the record of the pass once, under the directory it has now ({} times)", recorded));
}
// One that fails stops none of the others, and what failed is said
// once: two programs built on a library that does not compile, and a
// third that has nothing to do with it.
{
Configuration broken;
MakeLibrary(broken, scratch / "broken", "broken", "Broken");
Configuration first;
first.dependencies = { &broken };
MakeProgram(first, scratch / "first", "first");
Configuration second;
second.dependencies = { &broken };
MakeProgram(second, scratch / "second", "second");
Configuration good;
MakeProgram(good, scratch / "good", "good");
std::array<Configuration*, 3> all = { &first, &second, &good };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(failed.contains("Undeclared"), std::format("the library's compile error comes back: {}", failed));
Check(Count(failed, "error:") == 1, std::format("a dependency that failed for two configurations is reported once: {}", failed));
Check(fs::exists(ExpectedOutput(good)), "a configuration that has nothing to do with the failure is still built");
Check(!fs::exists(ExpectedOutput(first)) && !fs::exists(ExpectedOutput(second)), "the two built on the broken library are not");
// Two configurations in one directory would be one piece of work to
// the pass, which would build the first and hand the second its
// result.
Configuration twin;
MakeProgram(twin, scratch / "good", "good");
std::array<Configuration*, 2> clash = { &good, &twin };
fs::remove_all(good.BinDir(), ec);
fs::remove_all(good.BuildDir(), ec);
std::unordered_map<fs::path, std::shared_future<BuildResult>> clashResults;
const std::string refused = BuildAll(clash, clashResults, depMutex);
Check(refused.contains("would both be built into"), std::format("two configurations that build into one directory are refused: {}", refused));
Check(!fs::exists(good.BinDir()), "and refused before either is built");
}
// A wasm executable with variants rewrites the configurations it is
// built on, once for each variant, so with one among them the
// configurations are built one after the other: built at once, a
// library two of them share would change under the other's build. The
// slow one comes first here, a program and the library it is built on,
// and the quick one, a single source, is only linked once the slow one
// is. The wasm one is refused before it builds anything, on every
// machine, for its -fno-exceptions, so no wasm build is waited for.
{
Configuration library;
MakeLibrary(library, scratch / "greeter", "ordered-greeter", "Greeter");
Configuration slow;
slow.dependencies = { &library };
MakeProgram(slow, scratch / "hello", "ordered-slow");
Configuration quick;
MakeProgram(quick, scratch / "good", "ordered-quick");
Configuration variants;
MakeProgram(variants, scratch / "good", "ordered-variants");
variants.target = "wasm32-wasip1";
variants.compileFlags.push_back("-fno-exceptions");
EnableWasiRelaxedSimdVariant(variants);
std::array<Configuration*, 3> all = { &slow, &quick, &variants };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(failed.contains("-fno-exceptions"), std::format("the wasm configuration is the one that is refused: {}", failed));
const fs::file_time_type slowBuilt = fs::last_write_time(ExpectedOutput(slow), ec);
Check(!ec, "the slow configuration is built");
const fs::file_time_type quickBuilt = fs::last_write_time(ExpectedOutput(quick), ec);
Check(!ec && quickBuilt >= slowBuilt, "with a wasm executable that declares variants among them, a configuration is built once the one before it is");
}
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
fs::remove_all(scratch, ec);
return 0;
}

View file

@ -5,6 +5,8 @@ module DepMod;
// Implementation unit of the DepMod interface. Because it declares
// `module DepMod;` it gains an intra-config module dependency on the DepMod
// interface, so its compile waits on DepMod's `compiled` flag — the exact
// flag a stale recursive reset used to clobber (issue #16).
// interface, so its compile job comes after the job that writes DepMod's BMI
// (Implementation::Schedule), which reads DepMod's per-build state: what a
// recursive reset would clear. Its compile used to wait on DepMod's
// `compiled` flag, the flag such a reset clobbered (issue #16).
int dep_value() { return 21; }

View file

@ -8,26 +8,35 @@ using namespace Crafter;
// Regression for the concurrent dependency-reset deadlock (issue #16).
//
// Build() resets each Module/ModulePartition's per-build `compiled` /`checked`
// flags so a reused Configuration re-evaluates mtimes. That reset MUST stay
// scoped to the configuration being built. It used to recurse into
// cfg.dependencies — but dependency Configurations are shared across the build
// DAG and each is compiled concurrently by its own Build() call. A parent's
// recursive reset could therefore clear a dependency's module `compiled` flag
// Each Module/ModulePartition holds the state of one build (`checked`,
// `scheduled` and the job that precompiles the unit). Build() used to reset
// it so a reused Configuration re-evaluates mtimes, and now makes the units
// anew from what it reads in the sources. Either way that MUST stay scoped
// 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
// 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
// parent's recursive reset could clear a dependency's module `compiled` flag
// *after* that dependency's module-compile thread had set it true and exited,
// but before an intra-config waiter (its impl / a dependent partition) ran
// `compiled.wait(false)`. The waiter then blocked forever on a flag nothing
// re-signalled: the build froze mid-compile, idle, with no compiler process
// alive.
//
// Units are jobs now and wait on no flag, but the state is still the building
// configuration's alone: cleared from outside between two Schedule() calls of
// its own build, a unit is scheduled twice and compiled twice at once.
//
// This test pins the invariant deterministically, without depending on thread
// timing: build a static-lib dependency fully (its module ends up compiled),
// then build a consumer that depends on it while the dependency is already
// cached in depResults (so it is NOT rebuilt). Before the fix, the consumer's
// recursive reset flipped the dependency's module `compiled` flag back to false
// and, because the dependency never rebuilds, it stayed false. After the fix
// the consumer resets only its own modules, so the dependency's flag is left
// intact. We assert it is still set once the consumer build completes.
// 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
// 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
// module with `checked` and `scheduled` false and, because the dependency
// never rebuilds, they would stay false. The consumer makes only its own
// units, so the dependency's flags are left intact. We assert both are still
// set once the consumer build completes.
int main() {
fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture";
@ -51,11 +60,6 @@ int main() {
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::mutex depMutex;
@ -64,8 +68,12 @@ int main() {
std::println(std::cerr, "dependency build failed: {}", r.result);
return 1;
}
if (!dep.interfaces[0]->compiled.load()) {
std::println(std::cerr, "dependency module not marked compiled after its own build");
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) {
std::println(std::cerr, "dependency module not marked checked and scheduled after its own build");
return 1;
}
// Seed a consumer-facing cache so the consumer reuses this build instead
@ -98,10 +106,9 @@ int main() {
}
// The core regression assertion: building the consumer must not have
// reset the (cached, never-rebuilt) dependency's module flag. Before the
// fix this was false and an intra-config waiter would have deadlocked.
if (!dep.interfaces[0]->compiled.load()) {
std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module 'compiled' " "flag (issue #16 regression) — this is the state that deadlocks a " "concurrent build");
// reset the (cached, never-rebuilt) dependency's module state.
if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module state " "(issue #16 regression): done while that dependency is building, " "this compiles its units twice at once");
return 1;
}

View file

@ -0,0 +1,5 @@
/* SPDX-License-Identifier: LGPL-3.0-only
SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */
/* A C source of kernel.cu's name, in its directory. */
int KernelInC(void) { return 1; }

View file

@ -28,11 +28,14 @@ using namespace Crafter;
// libcheckpoint.so and a libm.so that are no libraries, so a link that
// searched it would stop on one: an executable with CUDA sources built on a
// library of the project's named checkpoint has to take the project's, and
// clang++ adds -lm to every C++ link. A last build names the shared runtime
// clang++ adds -lm to every C++ link. Another build names the shared runtime
// itself, as a project with CUDA sources had to, and has its -lcudart ahead of
// the static archive. Where nvcc is looked for, and the runtime beside it, is
// ToolchainResolve's to check; this is the build that uses them. Skips without
// a CUDA toolkit whose lib64 holds the static runtime; CI has none.
// the static archive. A last one is a static library of the .cu and a C source
// of its name beside it: the archive has to hold an object of each, where the
// two used to be compiled into one (issue #50). Where nvcc is looked for, and
// the runtime beside it, is ToolchainResolve's to check; this is the build
// that uses them. Skips without a CUDA toolkit whose lib64 holds the static
// runtime; CI has none.
namespace {
std::int32_t Failures = 0;
@ -259,6 +262,27 @@ int main() {
const std::size_t archive = link.find(runtime);
Check(shared != std::string::npos && archive != std::string::npos && shared < archive, std::format("with its -lcudart ahead of the static runtime (link: {})", link));
}
{
// A C source of the .cu's name beside it, in a static library: each
// has an object of its own, and the archive lists the two. Both used
// to be compiled into kernel_source.o, each over the other (issue
// #50).
const fs::path twins = scratch / "twins";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", twins, fs::copy_options::recursive);
Configuration kernels;
kernels.path = twins;
kernels.name = "twins";
kernels.outputName = "twins";
kernels.type = ConfigurationType::LibraryStatic;
kernels.cFiles = { twins / "kernel" };
kernels.cuda = { twins / "kernel" };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(kernels, depResults, depMutex);
Check(built.result.empty(), std::format("a library of a kernel.c and a kernel.cu in one directory builds: {}", built.result));
const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(kernels).string())), std::chrono::seconds(30));
Check(members.exitCode == 0 && members.output == "kernel_source.o\nkernel_cuda.o\n", std::format("with an object of each in its archive: llvm-ar t lists '{}' (exit {})", members.output, members.exitCode));
}
fs::remove_all(scratch, ec);
return Failures == 0 ? 0 : 1;

View file

@ -38,6 +38,15 @@ int main() {
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) {
std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size());
return 1;
@ -56,14 +65,6 @@ int main() {
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";
if (!fs::exists(libArchive)) {
std::println(std::cerr, "dep archive not produced at {}", libArchive.string());

View file

@ -0,0 +1,3 @@
## outer
outer wraps lib.

View file

@ -0,0 +1,21 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// A project that builds against lib, and so against base one ring further
// out. app does not name it: the test loads it for the cases in which a
// project has several configurations, where it is what a second
// configuration names.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view>) {
Configuration cfg;
cfg.path = "./";
cfg.name = "outer";
cfg.outputName = "outer";
cfg.type = ConfigurationType::LibraryStatic;
// Loaded from outer/, so this resolves against it.
cfg.dependencies = { LocalProject({ .projectFile = "../lib/project.cpp" }) };
return cfg;
}

View file

@ -294,6 +294,86 @@ int main() {
Check(Read(agents) == generated, "under None, AGENTS.md holds the template's text alone");
cfg.dependencyNotes = DependencyNotes::Transitive;
// A project file that returns several configurations: each one's setting
// selects among what that one is built against, and the notes are
// merged. `second` stands in for a second configuration of app's project
// file, and outer is a project that builds against lib, and so against
// base one ring further out.
{
Configuration* outer = nullptr;
try {
outer = LocalProject({ .projectFile = scratch / "outer" / "project.cpp" });
} catch (const std::exception& e) {
std::println(std::cerr, "FAIL: loading outer threw: {}", e.what());
return 1;
}
Configuration* const baseProject = cfg.dependencies[0]->dependencies[0];
Configuration second;
std::array<const Configuration*, 2> both = { &cfg, &second };
// The projects the section names, in its order, once AGENTS.md is
// written for `configurations`.
const auto named = [&](std::span<const Configuration* const> configurations) {
(void)UpdateAgentsMd(configurations, projectFile);
const std::string now = Read(agents);
constexpr std::string_view from = "<!-- from ";
std::vector<std::string> names;
for (std::size_t pos = now.find(from); pos != std::string::npos; pos = now.find(from, pos + 1)) {
names.push_back(now.substr(pos + from.size(), now.find(" -->", pos) - pos - from.size()));
}
return names;
};
using Names = std::vector<std::string>;
cfg.dependencyNotes = DependencyNotes::Direct;
second.dependencies = { outer };
second.dependencyNotes = DependencyNotes::Direct;
Check(named(both) == Names{"tool", "lib", "outer"}, std::format("two Direct configurations give what each of them names (got {})", named(both)));
// lib is in the first ring through app, which asks for no more. The
// second configuration reaches it through outer and asks for
// everything, so what lib builds against is in.
second.dependencyNotes = DependencyNotes::Transitive;
Check(named(both) == Names{"tool", "lib", "outer", "base"}, std::format("a project a Direct configuration names is followed when a Transitive one leads to it (got {})", named(both)));
cfg.dependencyNotes = DependencyNotes::None;
second.dependencies = { baseProject };
Check(named(both) == Names{"tool", "base"}, std::format("a configuration under None keeps out what only it is built against (got {})", named(both)));
second.dependencyNotes = DependencyNotes::None;
Check(named(both).empty() && Read(agents) == generated, "with every configuration under None, AGENTS.md holds the template's text alone");
// A configuration the file loaded from another project and returns
// is one of the projects it is built against, and its own setting
// counts for nothing here: it goes by the widest of the others.
std::array<const Configuration*, 2> withOuter = { &cfg, outer };
cfg.dependencyNotes = DependencyNotes::Direct;
Check(named(withOuter) == Names{"tool", "lib", "outer"}, std::format("a returned configuration of another project is in the first ring, and under Direct no more of it (got {})", named(withOuter)));
cfg.dependencyNotes = DependencyNotes::Transitive;
Check(named(withOuter) == Names{"tool", "lib", "outer", "base"}, std::format("under Transitive what it builds against follows (got {})", named(withOuter)));
std::array<const Configuration*, 1> onlyOuter = { outer };
Check(named(onlyOuter) == Names{"tool", "outer", "lib", "base"}, std::format("a file that made no configuration itself gets everything (got {})", named(onlyOuter)));
// The same Configuration, for outer's own AGENTS.md: outer's project
// file made it, so here its setting is the one that selects, though
// a loader holds it. Told apart by being held, it was another
// project's configuration to its own file, and got everything.
const fs::path outerFile = scratch / "outer" / "project.cpp";
const fs::path outerAgents = scratch / "outer" / "AGENTS.md";
Write(scratch / "outer" / "AGENTS.template.md", templateText);
const auto outerNamed = [&](DependencyNotes setting) {
outer->dependencyNotes = setting;
(void)UpdateAgentsMd(*outer, outerFile);
const std::string now = Read(outerAgents);
constexpr std::string_view from = "<!-- from ";
Names names;
for (std::size_t pos = now.find(from); pos != std::string::npos; pos = now.find(from, pos + 1)) {
names.push_back(now.substr(pos + from.size(), now.find(" -->", pos) - pos - from.size()));
}
return names;
};
Check(outerNamed(DependencyNotes::Direct) == Names{"lib"}, std::format("a project loaded by another gets what its own Direct selects in its own AGENTS.md (got {})", outerNamed(DependencyNotes::Direct)));
Check(outerNamed(DependencyNotes::Transitive) == Names{"lib", "base"}, std::format("and what its Transitive does (got {})", outerNamed(DependencyNotes::Transitive)));
Check(outerNamed(DependencyNotes::None).empty() && Read(outerAgents) == generated, "and under None the template's text alone");
outer->dependencyNotes = DependencyNotes::Transitive;
}
// Linked to the template, AGENTS.md would have every build write the
// file that is committed.
fs::remove(agents);

View file

@ -8,13 +8,16 @@ using namespace Crafter;
// 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
// sibling would, and the two paths load M with two different lists.
// sibling would, and the two paths load M with two different lists. With
// --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) {
const bool split = std::ranges::contains(args, std::string_view("--split"));
std::vector<std::string> mArgs;
for (std::string_view arg : args) {
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* a = LocalProject({ .projectFile = "../a/project.cpp" });

View file

@ -8,13 +8,14 @@ using namespace Crafter;
// 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
// along two paths with two arg lists, say. It used to build both and put
// both on the consumer's module path. Clang took the first for every import
// of the module, the ones inside the other build's consumers included, and
// the program linked code compiled against two layouts of one struct: it
// built cleanly, then read garbage or crashed (issue #41). The fixture is
// P -> M and P -> A -> M. With --split, P gives M its args without --wide,
// which changes what M declares, while A passes them on whole.
// along two paths with two arg lists, say. It used to build both and compile
// the consumer with both on its module path. Clang took the first for every
// import of the module, the ones inside the other build's consumers
// included, and the program linked code compiled against two layouts of one
// struct: it built cleanly, then read garbage or crashed (issue #41). The
// fixture is P -> M and P -> A -> M. With --split, P gives M its args
// without --wide, which changes what M declares, while A passes them on
// whole.
namespace {
std::int32_t Failures = 0;
@ -53,7 +54,9 @@ int main() {
const fs::path cwd = fs::current_path();
fs::current_path(scratch / "p");
try {
// Two lists for M: refused before anything is built.
// Two lists for M: refused before P compiles anything of its own.
// 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" };
Configuration cfg = LoadProject("project.cpp", args);
@ -61,7 +64,73 @@ int main() {
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("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result));
Check(!fs::exists(scratch / "m" / "bin") && !fs::exists(scratch / "a" / "bin") && !fs::exists(scratch / "p" / "bin"), "nothing was built");
Check(!fs::exists(ObjectPath(cfg, scratch / "p" / "main.cpp")) && !fs::exists(ExpectedOutput(cfg)), "P compiled and linked nothing");
}
// 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.

View file

@ -0,0 +1,517 @@
// 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,11 +79,18 @@ int main() {
}
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";
fs::create_directories(link.parent_path(), ec);
fs::remove(link, ec);
fs::create_directory_symlink("/tmp", link, ec);
const std::array<fs::path, 2> unseen = {"/tmp/crafter-build-host-flatpak", link / "crafter-build-host-flatpak-linked"};
fs::create_directory_symlink(scratch, link, ec);
const std::array<fs::path, 2> unseen = {scratch / "project", link / "linked"};
for (const fs::path& project : unseen) {
if (tmpShared) {
std::println("an override shares the host's /tmp with the sandbox, so the host sees {}: left out", project.string());
@ -100,6 +107,8 @@ int main() {
Check(fs::is_empty(project, ec), std::format("and asking leaves nothing in {}", project.string()));
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
// all the same, and sees the fixture.
if (permitted) {

View file

@ -0,0 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Own:Part;
import Own;
export bool Part();

View file

@ -0,0 +1,5 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Own;
export import :Part;

View file

@ -0,0 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Ring:First;
import :Second;
export bool First();

View file

@ -0,0 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Ring:Second;
import :First;
export bool Second();

View file

@ -0,0 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Ring;
export import :First;
export import :Second;

View file

@ -0,0 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module East;
import West;
export bool East();

View file

@ -0,0 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module West;
import East;
export bool West();

View file

@ -0,0 +1,80 @@
// 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;
// Interface units that import each other are refused before any .cppm or
// .cpp of their configuration is compiled, with an error naming them. No
// order builds them. Before the refusal such a build hung with no compiler
// running, each unit waiting for the units it imports, which is how this
// test failed then: by running into its timeout.
//
// 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
// partitions, and two modules of one configuration that import each other.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// 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 that gets past the refusal can compile units before it fails, and
// in the checkout the next run would find them there and report them
// against a refusal that works.
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;
fs::remove_all(staged);
fs::create_directories(staged.parent_path());
fs::copy(fs::current_path() / "tests" / "ImportCycle" / "fixture" / dir, staged, fs::copy_options::recursive);
Configuration cfg;
cfg.path = staged;
cfg.name = std::format("cycle-{}", dir);
cfg.outputName = cfg.name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 0> implementations = {};
cfg.GetInterfacesAndImplementations(interfaces, implementations);
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(cfg, depResults, depMutex);
// Refused once the build has read what the units import, which is
// before it compiles any of them: no unit has a BMI or an object.
for (const fs::path& interface : interfaces) {
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;
}
}
int main() {
{
std::array<fs::path, 3> interfaces = { "Ring", "Ring-First", "Ring-Second" };
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));
}
{
std::array<fs::path, 2> interfaces = { "Own", "Own-Part" };
const std::string error = BuildError("own-module", interfaces);
Check(error.contains("Own -> Own:Part -> Own"), std::format("a partition that imports its own module is named with it, got: '{}'", error));
}
{
std::array<fs::path, 2> interfaces = { "East", "West" };
const std::string error = BuildError("siblings", interfaces);
Check(error.contains("East -> West -> East"), std::format("modules that import each other are named, got: '{}'", error));
}
return Failures == 0 ? 0 : 1;
}

View file

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

View file

@ -8,7 +8,7 @@ using namespace Crafter;
// Editing a header must rebuild everything that #includes it. The staleness
// check used to compare an artifact against its own source and its module
// imports only — and the module scanner reads `import` lines, so a header was
// imports only — and the module scanner read `import` lines, so a header was
// 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
// mixed-layout binary as issue #27, reached through #include instead.
@ -111,9 +111,9 @@ int main() {
// source, and the consumer that imports the module.
fs::path interfacePcm = lib->PcmDir() / "Widget.pcm";
fs::path interfaceObject = lib->BuildDir() / "Widget.o";
fs::path libraryObject = lib->BuildDir() / "Widget_impl.o";
fs::path counterObject = lib->BuildDir() / "counter_source.o";
fs::path consumerObject = app.BuildDir() / "main_impl.o";
fs::path libraryObject = ObjectPath(*lib, staged / "lib" / "Widget.cpp");
fs::path counterObject = ObjectPath(*lib, staged / "lib" / "counter.c");
fs::path consumerObject = ObjectPath(app, staged / "main.cpp");
if (!BuildOk(app, "first pass")) {
std::println(std::cerr, "{} assertions failed", Failures);
@ -187,7 +187,7 @@ int main() {
// safe reading is "rebuild it once".
{
std::array<fs::file_time_type, 5> before = stamps();
fs::remove(lib->BuildDir() / "Widget_impl.o.d");
fs::remove(fs::path(libraryObject) += ".d");
if (BuildOk(app, "missing depfile pass")) {
std::array<fs::file_time_type, 5> after = stamps();
Check(after[2] > before[2], "an object whose dependency record is missing is rebuilt");

View file

@ -3,10 +3,7 @@
// 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.
// 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.
// Kept as a .cppm.in so that no build takes it for a source of its own.
export module Widget;
import std;

View file

@ -7,15 +7,17 @@ namespace fs = std::filesystem;
using namespace Crafter;
// 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) is a
// object compiled against the old layout. The dangerous shape (issue #27) was a
// consumer whose sources were scanned *before* its `dependencies` were assigned:
// its `import <DepModule>;` matched nothing, so its object carried no staleness
// 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.
//
// `AddTest` is exactly that shape — it scans tests/<name>/main.cpp and only then
// `AddTest` is exactly that shape — it lists tests/<name>/main.cpp and only then
// returns a builder whose .Dependencies() supplies the library — which is why
// 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 {
std::int32_t Failures = 0;
@ -36,10 +38,7 @@ namespace {
return staged;
}
// 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.
// Swap in the variant carrying the extra member, kept beside the original.
void GrowWidget(const fs::path& staged) {
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
@ -60,9 +59,9 @@ namespace {
return lib;
}
// Scan first, wire the dependency up afterwards — the ordering that used to
// silently drop the staleness edge.
Configuration MakeConsumerScannedBeforeDependencies(const fs::path& staged, Configuration* lib) {
// Sources first, the dependency wired up afterwards — the ordering that
// used to silently drop the staleness edge.
Configuration MakeConsumerListedBeforeDependencies(const fs::path& staged, Configuration* lib) {
Configuration app;
app.path = staged;
app.name = "widget-app";
@ -94,45 +93,31 @@ namespace {
int main() {
{
// The scan leaves the unmatched import recorded rather than forgotten,
// and ResolvePendingImports places it once the library is reachable.
// The build places the consumer's import on the library's module,
// although the library became a dependency after the consumer's
// sources were listed.
fs::path staged = StageFixture();
std::unique_ptr<Configuration> lib = MakeLib(staged);
Configuration app;
app.path = staged;
app.name = "widget-app";
app.outputName = "widget-app";
app.target = HostTarget();
app.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get());
if (BuildOk(app, "consumer with the dependency wired up last")) {
Check(app.implementations.size() == 1, "consumer has one implementation");
if (app.implementations.size() == 1) {
const Implementation& impl = app.implementations[0];
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");
Check(impl.externalModuleDependencies.size() == 1, "the import of the library's module is one 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");
}
// A second build makes the units anew: the edge is there once.
if (BuildOk(app, "consumer built again")) {
Check(app.implementations.size() == 1 && app.implementations[0].externalModuleDependencies.size() == 1, "a second build has the one edge again");
}
}
}
{
// AddTest is the reported path: it scans the test source, then hands
// AddTest is the reported path: it lists the test source, then hands
// back a builder whose .Dependencies() names the library.
fs::path staged = StageFixture();
fs::create_directories(staged / "tests" / "Consumer");
@ -146,30 +131,33 @@ int main() {
app.target = HostTarget();
app.type = ConfigurationType::Executable;
// AddTest resolves tests/<name>/main against the cwd, which for a real
// run is the directory holding project.cpp. Stand in the staged project
// for the declaration so the fixture's test source is the one scanned.
// run is the directory holding project.cpp, and the test's "./" path
// is read against it when the test is built. Stand in the staged
// 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::current_path(staged);
app.AddTest("Consumer").Dependencies({ lib.get() });
fs::current_path(restore);
Check(app.tests.size() == 1, "one test declared");
if (app.tests.size() == 1 && app.tests[0].config.implementations.size() == 1) {
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() 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");
Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() gives the test's import of the library module its edge");
}
}
fs::current_path(restore);
}
{
// End to end, and deliberately without calling ResolvePendingImports:
// the guarantee under test is that Build() closes the window on its own,
// for consumers that never knew they had to ask.
// End to end: the guarantee under test is that a build of a consumer
// declared in that order recompiles it, for consumers that never knew
// the order mattered.
fs::path staged = StageFixture();
std::unique_ptr<Configuration> lib = MakeLib(staged);
Configuration app = MakeConsumerScannedBeforeDependencies(staged, lib.get());
Configuration app = MakeConsumerListedBeforeDependencies(staged, lib.get());
fs::path binary = app.BinDir() / "widget-app";
fs::path consumerObject = app.BuildDir() / "main_impl.o";
fs::path consumerObject = ObjectPath(app, staged / "main.cpp");
if (BuildOk(app, "first pass")) {
auto first = RunCommandWithTimeout(binary.string(), std::chrono::seconds(30));

View file

@ -0,0 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Value:Part;
import std;
export std::int32_t Part() { return 10; }

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Value;
import std;
export import :Part;
export std::int32_t Value() { return Part() + 2; }

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Value;
import std;
export import :Part;
export std::int32_t Value() { return Part() + 1; }

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Value;
int main() {
std::print("{}", Value());
}

View file

@ -0,0 +1,144 @@
// 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;
// An interface unit takes two compiler runs: one writes its BMI, the other
// the object made from the BMI. Whether a unit is stale is read off the BMI,
// so a unit left with a current BMI and the object of its source before an
// edit, or no object at all, was called built by every build after: the link
// took the old object without a word, or failed on the missing file until the
// source was touched. A build ends between the two runs when it is
// interrupted, when the second run fails, and, with the two as jobs of their
// own, when another step fails first and keeps the second from starting.
//
// The fixture is a module with a partition and a program that prints what
// the module's function returns. Built without optimisation, so the program
// gets that function from the unit's object alone and what it prints says
// which object was linked. First the primary interface is edited and, once
// that is built, its object put back as it was before the edit, dated before
// the new BMI: once with the program still there, which has to be linked
// again, and once with the program deleted, so that it is linked from
// whatever object is there. Then both objects and the program are deleted. A
// last build of the intact tree has to leave the objects alone.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The fixture is edited during the run, so work on a copy outside the repo.
fs::path StageFixture() {
fs::path source = fs::current_path() / "tests" / "IncrementalInterfaceObject" / "fixture";
fs::path staged = fs::temp_directory_path() / "crafter-build-incremental-interface-object";
fs::remove_all(staged);
fs::copy(source, staged, fs::copy_options::recursive);
// An earlier run in the checkout may have left these; the copy starts cold.
fs::remove_all(staged / "bin");
fs::remove_all(staged / "build");
return staged;
}
bool BuildOk(Configuration& app, std::string_view label) {
// A fresh depResults per pass, so every pass checks everything again.
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(app, depResults, depMutex);
Check(built.result.empty(), std::format("{}: the build failed: {}", label, built.result));
return built.result.empty();
}
std::string Printed(const Configuration& app) {
const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30));
return run.exitCode == 0 ? run.output : std::format("<exit {}: {}>", run.exitCode, run.output);
}
}
int main() {
const fs::path staged = StageFixture();
Configuration app;
app.path = staged;
app.name = "value-app";
app.outputName = "value-app";
app.target = HostTarget();
app.type = ConfigurationType::Executable;
app.debug = true;
std::array<fs::path, 2> interfaces = { "Value", "Value-Part" };
std::array<fs::path, 1> implementations = { "main" };
app.GetInterfacesAndImplementations(interfaces, implementations);
const fs::path primaryPcm = app.PcmDir() / "Value.pcm";
const fs::path primaryObject = app.BuildDir() / "Value.o";
const fs::path partitionObject = app.BuildDir() / "Value-Part.o";
const fs::path program = ExpectedOutput(app);
if (!BuildOk(app, "the first build")) return 1;
Check(Printed(app) == "11", std::format("the first build's program prints 11, got '{}'", Printed(app)));
if (!fs::exists(primaryObject) || !fs::exists(partitionObject) || !fs::exists(primaryPcm)) {
std::println(std::cerr, "FAIL: the first build left no {}, {} or {}", primaryObject.string(), partitionObject.string(), primaryPcm.string());
return 1;
}
const fs::path oldObject = staged / "Value.o.before-edit";
fs::copy_file(primaryObject, oldObject, fs::copy_options::overwrite_existing);
// After an edit, the BMI of the new source next to the object of the old
// one: what a build that ends between the two runs leaves of a unit that
// was built before.
fs::copy_file(staged / "Value-edited.cppm.in", staged / "Value.cppm", fs::copy_options::overwrite_existing);
if (!BuildOk(app, "the build after the edit")) return 1;
Check(Printed(app) == "12", std::format("the edited program prints 12, got '{}'", Printed(app)));
const auto putOldObjectBack = [&] {
fs::copy_file(oldObject, primaryObject, fs::copy_options::overwrite_existing);
fs::last_write_time(primaryObject, fs::last_write_time(primaryPcm) - std::chrono::seconds(2));
};
// With the program the last build linked still there, as a build that
// failed leaves it: nothing but the object made again is newer than it.
putOldObjectBack();
if (BuildOk(app, "the build with the object of before the edit")) {
Check(fs::last_write_time(primaryObject) >= fs::last_write_time(primaryPcm), "an object older than its BMI is made again");
Check(fs::last_write_time(program) >= fs::last_write_time(primaryObject), "the program is linked again from the object made again");
Check(Printed(app) == "12", std::format("the program linked again prints 12, got '{}'", Printed(app)));
}
// And with the program gone, so that the link takes whatever object is
// there.
putOldObjectBack();
fs::remove(program);
if (BuildOk(app, "the build with the object of before the edit and no program")) {
Check(fs::last_write_time(primaryObject) >= fs::last_write_time(primaryPcm), "an object older than its BMI is made again, with no program either");
Check(Printed(app) == "12", std::format("the program is linked from the object of the edited source and prints 12, got '{}'", Printed(app)));
}
// BMIs and no objects: what such a build leaves of units it built for
// the first time.
fs::remove(primaryObject);
fs::remove(partitionObject);
fs::remove(program);
if (BuildOk(app, "the build after the objects went missing")) {
Check(fs::exists(primaryObject) && fs::exists(partitionObject), "a unit with a BMI and no object gets its object back");
Check(Printed(app) == "12", std::format("the program linked from the restored objects prints 12, got '{}'", Printed(app)));
}
// What follows reads the objects the builds above should have left.
if (Failures != 0) return 1;
// With every object newer than its BMI there is nothing to make again.
const fs::file_time_type primaryTime = fs::last_write_time(primaryObject);
const fs::file_time_type partitionTime = fs::last_write_time(partitionObject);
if (BuildOk(app, "the build of the intact tree")) {
Check(fs::last_write_time(primaryObject) == primaryTime && fs::last_write_time(partitionObject) == partitionTime, "objects that are newer than their BMIs are left as they are");
}
return Failures == 0 ? 0 : 1;
}

308
tests/JobGroup/main.cpp Normal file
View file

@ -0,0 +1,308 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// JobPool and JobGroup, which every build step runs on. A pool runs as many
// jobs at once as it has workers and no more; a job of a group starts when the
// jobs it was added after have finished; the first error keeps what has not
// started from starting; and nothing that waits for jobs does so on a worker,
// where it would keep from them the thread they need.
//
// The pools here are the test's own, of one to four workers, so what is
// counted does not depend on the machine. Build() runs on the process's pool:
// tests/JobLimit holds a whole build to that one.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// Twelve jobs on three workers. Each holds its worker until three run at
// once, so the pool is seen to reach its limit however the threads are
// scheduled, and then a moment longer with the lock released, counted as
// running all the while: jobs a pool let in beyond its workers would be
// counted on top of the ones in that moment. A pool that never gets to
// three is waited on once, then given up on.
void RunsAsManyAsItHasWorkers() {
constexpr std::int32_t workers = 3;
constexpr std::int32_t count = 12;
JobPool pool(workers);
std::mutex mutex;
std::condition_variable changed;
std::int32_t running = 0;
std::int32_t peak = 0;
std::int32_t ran = 0;
bool gaveUp = false;
JobGroup jobs(pool);
for (std::int32_t i = 0; i < count; ++i) {
jobs.Add(std::format("gauge {}", i), [&]() -> std::string {
std::unique_lock lock(mutex);
++running;
peak = std::max(peak, running);
changed.notify_all();
if (!changed.wait_for(lock, std::chrono::seconds(20), [&] { return peak >= workers || gaveUp; })) gaveUp = true;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
lock.lock();
--running;
++ran;
return {};
});
}
Check(jobs.Wait().empty(), "jobs that return nothing leave the group without an error");
Check(ran == count, std::format("every job runs: {} of {} did", ran, count));
Check(peak == workers, std::format("a pool of {} workers runs {} jobs at once, not {}", workers, workers, peak));
}
// a, then b and c, then d: each records when it runs. The ones that
// others wait for take a moment first, so a group that started everything
// at once would record them last.
void StartsAJobAfterTheOnesItComesAfter() {
JobPool pool(3);
std::mutex mutex;
std::vector<std::string> order;
const auto record = [&mutex, &order](std::string name, std::int32_t milliseconds) {
return [&mutex, &order, name = std::move(name), milliseconds]() -> std::string {
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
std::lock_guard lock(mutex);
order.push_back(name);
return {};
};
};
const auto position = [&order](std::string_view name) {
return std::ranges::find(order, name) - order.begin();
};
JobGroup jobs(pool);
const JobGroup::Job a = jobs.Add("a", record("a", 60));
const std::array<JobGroup::Job, 1> afterA = {a};
const JobGroup::Job b = jobs.Add("b", record("b", 30), afterA);
const JobGroup::Job c = jobs.Add("c", record("c", 0), afterA);
const std::array<JobGroup::Job, 2> afterBoth = {b, c};
const JobGroup::Job d = jobs.Add("d", record("d", 0), afterBoth);
Check(jobs.Wait().empty(), "the ordered jobs leave no error");
Check(order.size() == 4, std::format("all four ordered jobs run: {}", order));
Check(position("a") < position("b") && position("a") < position("c"), std::format("b and c start after a has finished: {}", order));
Check(position("b") < position("d") && position("c") < position("d"), std::format("d starts after both b and c have finished: {}", order));
// After jobs that finished long ago: nothing is left to release it,
// so it has to start by itself.
const std::array<JobGroup::Job, 2> afterDone = {a, d};
jobs.Add("e", record("e", 0), afterDone);
Check(jobs.Wait().empty() && order.size() == 5, std::format("a job added after finished jobs runs: {}", order));
bool refused = false;
try {
const std::array<JobGroup::Job, 1> afterNone = {JobGroup::Job(99)};
jobs.Add("f", record("f", 0), afterNone);
} catch (const std::out_of_range&) {
refused = true;
}
Check(refused, "a job cannot be added after one the group does not have");
Check(jobs.Wait().empty() && order.size() == 5, std::format("the refused job never runs: {}", order));
}
// Three hundred jobs on four workers, each after up to three picked among
// the ones added before it, the same pick every run: every job runs
// once, and none before a job it comes after has finished.
void KeepsTheOrderOfALargerGraph() {
constexpr std::int32_t count = 300;
JobPool pool(4);
std::vector<std::atomic<std::int32_t>> runs(count);
std::atomic<std::int32_t> early{0};
std::mt19937 random(20261112);
JobGroup jobs(pool);
std::vector<JobGroup::Job> added;
for (std::int32_t i = 0; i < count; ++i) {
std::vector<JobGroup::Job> after;
std::vector<std::int32_t> before;
for (std::int32_t pick = 0; i > 0 && pick < 3; ++pick) {
if (random() % 2 == 0) continue;
const std::int32_t chosen = static_cast<std::int32_t>(random() % static_cast<std::uint32_t>(i));
after.push_back(added[chosen]);
before.push_back(chosen);
}
added.push_back(jobs.Add(std::format("node {}", i), [&runs, &early, before = std::move(before), i]() -> std::string {
for (const std::int32_t earlier : before) {
if (runs[earlier].load() != 1) ++early;
}
++runs[i];
return {};
}, after));
}
Check(jobs.Wait().empty(), "the larger graph leaves no error");
const std::int64_t once = std::ranges::count_if(runs, [](const std::atomic<std::int32_t>& ran) { return ran.load() == 1; });
Check(once == count, std::format("each of {} jobs runs once: {} did", count, once));
Check(early.load() == 0, std::format("no job starts before the ones it comes after have finished: {} did", early.load()));
}
void TheFirstErrorStopsTheRest() {
JobPool pool(2);
{
JobGroup jobs(pool);
std::atomic<bool> dependentRan{false};
std::atomic<bool> lateRan{false};
const JobGroup::Job failing = jobs.Add("failing", [] { return std::string("boom"); });
const std::array<JobGroup::Job, 1> afterFailing = {failing};
jobs.Add("dependent", [&dependentRan]() -> std::string {
dependentRan = true;
return {};
}, afterFailing);
Check(jobs.Wait() == "boom", "Wait returns what the failed job returned");
Check(jobs.Failed(), "a group with a failed job has failed");
Check(!dependentRan, "a job that comes after a failed one does not run");
jobs.Add("late", [&lateRan]() -> std::string {
lateRan = true;
return {};
});
jobs.Add("second", [] { return std::string("second"); });
Check(jobs.Wait() == "boom", "the first error stays the group's error");
Check(!lateRan, "a job added to a failed group does not run");
}
{
JobGroup jobs(pool);
jobs.Add("thrower", []() -> std::string { throw std::runtime_error("bang"); });
const std::string error = jobs.Wait();
Check(error == "thrower: bang", std::format("what a job throws is its error, under its label: '{}'", error));
}
{
JobGroup jobs(pool);
std::atomic<bool> ran{false};
Check(!jobs.Failed(), "a new group has not failed");
jobs.Fail("outside");
jobs.Fail("again");
jobs.Add("after", [&ran]() -> std::string {
ran = true;
return {};
});
Check(jobs.Wait() == "outside", "Fail gives the group its error, the first time");
Check(!ran, "no job starts in a group failed from outside");
}
}
// One worker and jobs that wait for each other: a job held back costs no
// thread, so the chain gets through on the one there is.
void OneWorkerIsEnough() {
JobPool pool(1);
std::mutex mutex;
std::int32_t running = 0;
std::int32_t peak = 0;
std::vector<std::int32_t> order;
JobGroup jobs(pool);
std::vector<JobGroup::Job> previous;
for (std::int32_t i = 0; i < 6; ++i) {
const auto work = [&mutex, &running, &peak, &order, i]() -> std::string {
{
std::lock_guard lock(mutex);
++running;
peak = std::max(peak, running);
}
std::this_thread::sleep_for(std::chrono::milliseconds(2));
std::lock_guard lock(mutex);
--running;
order.push_back(i);
return {};
};
// Every second one independent of the chain.
const JobGroup::Job job = i % 2 == 0 ? jobs.Add(std::format("link {}", i), work, previous) : jobs.Add(std::format("free {}", i), work);
if (i % 2 == 0) previous = {job};
}
Check(jobs.Wait().empty(), "the chain on one worker leaves no error");
Check(order.size() == 6 && peak == 1, std::format("six jobs run one at a time on one worker: {} ran, {} at once", order.size(), peak));
const auto position = [&order](std::int32_t i) {
return std::ranges::find(order, i) - order.begin();
};
Check(position(0) < position(2) && position(2) < position(4), std::format("the chain runs in its order: {}", order));
}
void RunIsOneJob() {
JobPool pool(1);
const std::thread::id here = std::this_thread::get_id();
std::thread::id ranOn = here;
pool.Run([&ranOn] { ranOn = std::this_thread::get_id(); });
Check(ranOn != here, "Run runs the work on a worker and returns once it has");
bool rethrown = false;
try {
pool.Run([] { throw std::runtime_error("from the work"); });
} catch (const std::runtime_error& e) {
rethrown = std::string_view(e.what()) == "from the work";
}
Check(rethrown, "what the work throws, Run throws");
// On the pool's only worker: queued, the inner step would wait for
// the thread its caller holds.
std::thread::id outer;
std::thread::id inner;
JobGroup jobs(pool);
jobs.Add("outer", [&pool, &outer, &inner]() -> std::string {
outer = std::this_thread::get_id();
pool.Run([&inner] { inner = std::this_thread::get_id(); });
return {};
});
Check(jobs.Wait().empty() && outer == inner && outer != here, "Run on a worker of the pool runs the work on that worker");
// And a group there is refused, where it would have waited the same way.
jobs.Add("nested", [&pool]() -> std::string {
JobGroup nested(pool);
return {};
});
const std::string error = jobs.Wait();
Check(error.starts_with("nested: ") && error.contains("JobGroup"), std::format("a JobGroup on a worker of its own pool is refused: '{}'", error));
}
// Leaving the scope of a group without Wait(), as an early return does:
// the job that runs is waited for, the one behind it never starts. The
// scope is left once the first runs, and the first goes on until the
// group has failed, which is what its destructor does first, so the
// second cannot have started before.
void LeavingWaitsForWhatRuns() {
JobPool pool(1);
std::atomic<bool> firstStarted{false};
std::atomic<bool> firstFinished{false};
std::atomic<bool> secondRan{false};
{
JobGroup jobs(pool);
jobs.Add("first", [&jobs, &firstStarted, &firstFinished]() -> std::string {
firstStarted = true;
firstStarted.notify_all();
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20);
while (!jobs.Failed() && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1));
firstFinished = true;
return {};
});
jobs.Add("second", [&secondRan]() -> std::string {
secondRan = true;
return {};
});
firstStarted.wait(false);
}
Check(firstFinished, "leaving a group waits for the job that is running");
Check(!secondRan, "leaving a group keeps the jobs that have not started from starting");
}
}
int main() {
// The labels of a few dozen jobs say nothing here.
Progress::SetVerbosity(Progress::Verbosity::Quiet);
const std::uint32_t hardware = std::max(1u, std::thread::hardware_concurrency());
Check(JobPool::Process().Workers() == hardware, std::format("the process's pool has a worker per hardware thread: {} for {}", JobPool::Process().Workers(), hardware));
Check(JobPool(0).Workers() == 1, "a pool has at least one worker");
RunsAsManyAsItHasWorkers();
StartsAJobAfterTheOnesItComesAfter();
KeepsTheOrderOfALargerGraph();
TheFirstErrorStopsTheRest();
OneWorkerIsEnough();
RunIsOneJob();
LeavingWaitsForWhatRuns();
return Failures == 0 ? 0 : 1;
}

170
tests/JobLimit/main.cpp Normal file
View file

@ -0,0 +1,170 @@
// 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;
// Builds run at most as many of their steps at once as the machine has
// hardware threads, however many files are stale and however many builds run
// side by side. Build() used to start a thread for every stale unit, and
// nothing bounded how many of them ran their compiler at once, on 8 hardware
// threads as on 56.
//
// Several projects are made here and built at once, each from a thread of
// this test, as RunTests builds its tests: enough of them to have two stale
// sources and more for every hardware thread. A project is 69 sources: 64
// that import nothing, half C and half C++, then a module of two partitions,
// one importing the other, with its implementation unit, and a main.cpp that
// imports the module, so that steps waiting for other steps queue with the
// rest. It is the same size on every machine, so no command of its build
// grows with the machine; the number of projects does. While they build from
// nothing, the threads of this process are counted: a job occupies a worker
// for as long as it runs, so the builds may add as many threads as there are
// hardware threads and no more. Before, they added one per source. A link is
// no job: its Build() runs it through RunBuildCommand from a thread that was
// there before the count, which therefore does not tell whether it waited
// for a worker. Every program is then run, since a limit kept by leaving
// steps out would pass the count as well.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The threads of this process, as the kernel counts them: one read, so
// no thread is counted twice or missed between two of them.
std::int32_t ThreadCount() {
std::ifstream status("/proc/self/status");
std::string line;
while (std::getline(status, line)) {
constexpr std::string_view key = "Threads:";
if (line.starts_with(key)) return std::stoi(line.substr(key.size()));
}
return 0;
}
void Write(const fs::path& file, std::string_view text) {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
}
// The C sources of one project, and as many C++ ones.
constexpr std::int32_t PerKind = 32;
// The units of one project: those sources, the module's primary
// interface, two partitions and implementation unit, and main.cpp.
constexpr std::int32_t Units = 2 * PerKind + 5;
// What a project's program prints: every C unit returns its index and so
// does every C++ one; Top() is 3.
constexpr std::int32_t Printed = 3 + PerKind * (PerKind - 1);
// Writes one project into `root` and returns its configuration.
std::unique_ptr<Configuration> MakeProject(const fs::path& root) {
fs::create_directories(root);
std::unique_ptr<Configuration> cfg = std::make_unique<Configuration>();
cfg->path = root;
cfg->name = "job-limit";
cfg->outputName = "job-limit";
cfg->target = HostTarget();
cfg->type = ConfigurationType::Executable;
// Limit:High imports Limit:Low, the primary interface both, the
// module's implementation unit the primary interface, and main.cpp
// the module.
Write(root / "Limit-Low.cppm", "export module Limit:Low;\nexport int Low() { return 1; }\n");
Write(root / "Limit-High.cppm", "export module Limit:High;\nimport :Low;\nexport int High() { return Low() + 1; }\n");
Write(root / "Limit.cppm", "export module Limit;\nexport import :Low;\nexport import :High;\nexport int Top();\n");
Write(root / "Limit-impl.cpp", "module Limit;\nint Top() { return High() + 1; }\n");
std::string declarations;
std::string sum;
std::vector<fs::path> implementations = { "main", "Limit-impl" };
for (std::int32_t i = 0; i < PerKind; ++i) {
Write(root / std::format("c{}.c", i), std::format("int c_unit_{0}(void) {{ return {0}; }}\n", i));
// Without the extension and absolute: cFiles resolve against the
// working directory, not cfg.path.
cfg->cFiles.push_back(root / std::format("c{}", i));
Write(root / std::format("x{}.cpp", i), std::format("int cpp_unit_{0}() {{ return {0}; }}\n", i));
implementations.emplace_back(std::format("x{}", 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);
}
Write(root / "main.cpp", std::format("import std;\nimport Limit;\n{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", declarations, sum));
std::array<fs::path, 3> interfaces = { "Limit", "Limit-Low", "Limit-High" };
cfg->GetInterfacesAndImplementations(interfaces, implementations);
return cfg;
}
}
int main() {
const std::int32_t workers = static_cast<std::int32_t>(std::max(1u, std::thread::hardware_concurrency()));
// Two projects and one more for every 32 hardware threads: 64 sources
// each, so twice as many sources as hardware threads, and more.
const std::int32_t count = workers / PerKind + 2;
const fs::path root = fs::temp_directory_path() / "crafter-build-job-limit";
fs::remove_all(root);
std::vector<std::unique_ptr<Configuration>> projects;
for (std::int32_t i = 0; i < count; ++i) projects.push_back(MakeProject(root / std::to_string(i)));
// What went wrong in each build; empty where nothing did.
std::vector<std::string> errors(projects.size());
std::atomic<bool> start{false};
std::atomic<std::int32_t> peak{0};
std::int32_t before = 0;
{
std::jthread sampler([&peak](std::stop_token stop) {
while (!stop.stop_requested()) {
const std::int32_t seen = ThreadCount();
if (seen > peak.load()) peak.store(seen);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
std::vector<std::jthread> builders;
for (std::size_t i = 0; i < projects.size(); ++i) {
builders.emplace_back([&projects, &errors, &start, i] {
start.wait(false);
try {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
errors[i] = Build(*projects[i], depResults, depMutex).result;
} catch (const std::exception& e) {
errors[i] = std::format("Build() threw: {}", e.what());
}
});
}
// With the sampler running and every builder waiting to start, so
// that they are part of what was there before the builds.
before = ThreadCount();
start = true;
start.notify_all();
// Leaving the scope joins the builders, then stops the sampler.
}
const std::int32_t added = peak.load() - before;
bool built = true;
for (std::size_t i = 0; i < projects.size(); ++i) {
Check(errors[i].empty(), std::format("the build of project {} failed: {}", i, errors[i]));
built = built && errors[i].empty();
}
Check(added <= workers, std::format("{} builds of {} sources in all ran on {} threads at once, on a machine with {} hardware threads", count, count * Units, added, workers));
// The other way round: builds that ran one step at a time would keep
// the limit too.
Check(added >= std::min(workers, 2), std::format("the builds never had two steps running at once: {} thread(s) at most, with {} hardware threads", added, workers));
if (built) {
for (std::size_t i = 0; i < projects.size(); ++i) {
const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(*projects[i]).string()), std::chrono::seconds(30));
Check(run.exitCode == 0 && run.output == std::to_string(Printed), std::format("the program of project {} printed '{}' (exit {}), expected {}: a unit is missing from it or was built out of order", i, run.output, run.exitCode, Printed));
}
}
return Failures == 0 ? 0 : 1;
}

View file

@ -0,0 +1,168 @@
// 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 configuration is linked from however many objects it has. Build() used
// to write the path of every object into the link or archive command, and a
// command is handed to a shell as one argument, which Linux holds to 32
// pages: 131,072 bytes with pages of 4 KiB, the terminating byte included.
// With objects whose paths came to more, no shell started, and the build
// ended with "popen() failed!".
//
// The test makes a project six directories deep, each with a name of 200
// characters, so that the path of its build directory alone is long, and
// gives it 120 C sources and a main.cpp that adds up what each of them
// returns. Every object lies in the build directory, so the paths of the
// 120 come to more than one argument holds. It builds the sources three
// ways: as one executable, whose link is given the objects, as a static
// library, whose archive step is, and as a shared library, the two
// libraries each with an executable of main.cpp built on it. Every program
// has to print the sum, which it does only when every object reached its
// link.
//
// The step reads its objects from a list in the build directory, and a step
// may be reading that list when the next build writes another: a library
// that two projects are built on is built by the crafter-build of each, in
// one clone in the cache. So the test holds the static library's list open,
// as a step that reads it does, builds the library again with one source
// fewer, and then reads what it has open: that has to be the whole list of
// the first build, not the next list or part of either.
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& file, std::string_view text) {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
}
constexpr std::int32_t Sources = 120;
// What every program prints: source i returns i.
constexpr std::int32_t Sum = Sources * (Sources - 1) / 2;
// The most one argument of a command may be where a page is 4 KiB.
constexpr std::size_t ArgumentLimit = 32 * 4096;
// A configuration in `project` that is linked for the machine that
// builds.
Configuration Named(const fs::path& project, std::string_view name, ConfigurationType type) {
Configuration cfg;
cfg.path = project;
cfg.name = std::string(name);
cfg.outputName = std::string(name);
cfg.target = HostTarget();
cfg.type = type;
return cfg;
}
// An executable of main.cpp alone.
Configuration Program(const fs::path& project, std::string_view name) {
Configuration cfg = Named(project, name, ConfigurationType::Executable);
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
return cfg;
}
// What went wrong building `cfg`; empty when nothing did. Before the
// fix the build threw where the shell did not start.
std::string BuildError(Configuration& cfg) {
try {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(cfg, depResults, depMutex).result;
} catch (const std::exception& e) {
return std::format("Build() threw: {}", e.what());
}
}
// Builds `cfg` and runs what it links.
void CheckBuildsAndPrintsSum(Configuration& cfg, std::string_view label) {
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("{} builds: {}", label, error));
if (!error.empty()) return;
const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30));
Check(run.exitCode == 0 && run.output == std::to_string(Sum), std::format("{}: the program printed '{}' (exit {}), expected {}", label, run.output, run.exitCode, Sum));
}
// How many lines `text` has.
std::int64_t Lines(std::string_view text) {
return std::ranges::count(text, '\n');
}
}
int main() {
const fs::path root = fs::temp_directory_path() / "crafter-build-link-many-objects";
fs::remove_all(root);
fs::path project = root;
for (const char letter : std::string_view("abcdef")) project /= std::string(200, letter);
fs::create_directories(project);
// Without their extension and whole, as cFiles are read against the
// working directory.
std::vector<fs::path> sources;
std::string declarations;
std::string sum;
for (std::int32_t i = 0; i < Sources; ++i) {
const fs::path source = project / std::format("unit{}", i);
Write(fs::path(source) += ".c", std::format("int unit_{0}(void) {{ return {0}; }}\n", i));
sources.push_back(source);
declarations += std::format("extern \"C\" int unit_{}(void);\n", i);
sum += std::format(" + unit_{}()", i);
}
// printf by its declaration, so that main.cpp, which is compiled once
// for each of the three programs, needs no header and no module.
Write(project / "main.cpp", std::format("extern \"C\" int printf(const char* format, ...);\n{}int main() {{ printf(\"%d\", 0{}); return 0; }}\n", declarations, sum));
Configuration whole = Program(project, "many");
whole.cFiles = sources;
// What the test rests on: with a shorter list the builds below would
// have passed before the fix as well. Each object lies in the build
// directory, wherever in it, so its path is longer than that
// directory's.
const std::size_t listed = static_cast<std::size_t>(Sources) * whole.BuildDir().string().size();
Check(listed > ArgumentLimit, std::format("the paths of the {} objects come to more than {} bytes, more than the {} one argument may be", Sources, listed, ArgumentLimit));
CheckBuildsAndPrintsSum(whole, "an executable of the sources");
Configuration archive = Named(project, "many-static", ConfigurationType::LibraryStatic);
archive.cFiles = sources;
Configuration onArchive = Program(project, "on-static");
onArchive.dependencies = { &archive };
CheckBuildsAndPrintsSum(onArchive, "an executable built on a static library of the sources");
Configuration shared = Named(project, "many-shared", ConfigurationType::LibraryDynamic);
shared.cFiles = sources;
Configuration onShared = Program(project, "on-shared");
onShared.dependencies = { &shared };
CheckBuildsAndPrintsSum(onShared, "an executable built on a shared library of the sources");
// The static library's list, opened as its archive step opens it, and
// not read yet.
const fs::path list = archive.BuildDir() / "many-static.objects";
std::ifstream opened(list, std::ios::binary);
Check(opened.is_open(), std::format("the archive step read its objects from {}", list.string()));
Configuration fewer = Named(project, "many-static", ConfigurationType::LibraryStatic);
fewer.cFiles.assign(sources.begin(), sources.end() - 1);
const std::string error = BuildError(fewer);
Check(error.empty(), std::format("the static library builds again with one source fewer: {}", error));
const std::string held((std::istreambuf_iterator<char>(opened)), std::istreambuf_iterator<char>());
Check(Lines(held) == Sources, std::format("a list that is open when the next build writes its own is still the whole list it was: {} lines read, {} objects listed", Lines(held), Sources));
std::ifstream next(list, std::ios::binary);
const std::string written((std::istreambuf_iterator<char>(next)), std::istreambuf_iterator<char>());
Check(Lines(written) == Sources - 1, std::format("and the list in its place is the next build's: {} lines, {} objects listed", Lines(written), Sources - 1));
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -246,6 +246,52 @@ int main() {
Check(s.Read("a") == "hello \n", "Check mode never writes");
}
// The configurations a project file returns: one run over the rules and
// the sources of all of them. The second lies inside the first's
// directory, which is the project root when no project file is given.
{
Scratch first("several");
Scratch second("several/second");
first.Write("a", "one \n");
second.Write("b", "two \n");
Configuration one = first.Config({"a"});
Configuration two = second.Config({"b"});
AddTrimRule(one);
AddTrimRule(two);
std::int32_t noted = 0;
two.AddLintRule("note", [&noted](LintContext&) { ++noted; });
std::array<Configuration*, 2> both = { &one, &two };
LintSummary sum = RunLint(both, Mode(LintMode::Apply));
Check(first.Read("a") == "one\n" && second.Read("b") == "two\n", "several: the sources of every configuration are formatted");
Check(sum.rulesRun == 2, "several: a rule two configurations register under one name is one rule");
Check(noted == 2, "several: a rule one configuration registers runs over the sources of all");
}
// A rule two of the returned configurations register under one name is
// the one the first of them registered, in the order the file returned
// them, whatever depends on the other: app depends on tools, so a walk
// of one configuration's graph after another's meets tools before
// `other` and would run its rule.
{
Scratch appDir("order");
Scratch otherDir("order/other");
Scratch toolsDir("order/tools");
appDir.Write("a", "app\n");
otherDir.Write("b", "other\n");
toolsDir.Write("c", "tools\n");
Configuration app = appDir.Config({"a"});
Configuration other = otherDir.Config({"b"});
Configuration tools = toolsDir.Config({"c"});
app.dependencies = { &tools };
std::atomic<std::int32_t> otherRan = 0;
std::atomic<std::int32_t> toolsRan = 0;
other.AddLintRule("pick", [&otherRan](LintContext&) { ++otherRan; });
tools.AddLintRule("pick", [&toolsRan](LintContext&) { ++toolsRan; });
std::array<Configuration*, 3> roots = { &app, &other, &tools };
const LintSummary sum = RunLint(roots, Mode(LintMode::Report));
Check(sum.rulesRun == 1 && otherRan == 3 && toolsRan == 0, std::format("several: the rule of the first configuration that registers the name runs, over every source (rules {}, the first's {} times, the later one's {} times)", sum.rulesRun, otherRan.load(), toolsRan.load()));
}
// Chaining: rule2 sees rule1's output; both attributed in Report mode.
{
Scratch s("chain");
@ -583,7 +629,9 @@ int main() {
Scratch s("ast");
s.Write("f", Source);
Configuration cfg = s.Config({"f"});
cfg.AddAstLintRule("ast", [](LintContext& ctx) {
bool ran = false;
cfg.AddAstLintRule("ast", [&ran](LintContext& ctx) {
ran = true;
Check(ctx.AstAvailable(), std::format("ast: parse succeeded ({})", ctx.AstUnavailableReason()));
std::span<const LintDecl> decls = ctx.Decls();
Check(!decls.empty(), "ast: declarations found");
@ -642,7 +690,13 @@ int main() {
Check(std::string_view(ctx.content).substr(count->begin, count->end - count->begin) == "int count", "ast: extent brackets exactly the declaration");
}
});
RunLint(cfg, Mode(LintMode::Report));
const LintSummary summary = 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
@ -651,9 +705,8 @@ int main() {
// 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.
//
// The source lives in fixture/ExportNamespace.cppm.in rather than inline:
// 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.
// The source lives in fixture/ExportNamespace.cppm.in, copied into the
// scratch directory as Demo.cppm.
{
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);
@ -665,7 +718,9 @@ int main() {
std::array<fs::path, 1> ifaces = { "Demo" };
std::array<fs::path, 0> impls = {};
cfg.GetInterfacesAndImplementations(ifaces, impls);
cfg.AddAstLintRule("ast-module", [](LintContext& ctx) {
bool ran = false;
cfg.AddAstLintRule("ast-module", [&ran](LintContext& ctx) {
ran = true;
Check(ctx.AstAvailable(), std::format("ast-module: parse succeeded ({})", ctx.AstUnavailableReason()));
std::span<const LintDecl> decls = ctx.Decls();
auto find = [&](LintDeclKind kind, std::string_view name) -> const LintDecl* {
@ -687,7 +742,9 @@ int main() {
Check(count != nullptr && count->line == 18, "ast-module: field line matches");
Check(exported != nullptr && exported->line == 20, "ast-module: exported variable line matches");
});
RunLint(cfg, Mode(LintMode::Report));
const LintSummary summary = 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

View file

@ -0,0 +1,235 @@
// 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,10 +83,7 @@ int main() {
Write(mingw / "include" / "_mingw.h", "");
Write(mingw / "include" / "crafter_probe_error.h", "#error stopped in a mingw-w64 header\n");
Write(mingw / "include" / "c++" / "15.1.0" / "memory", "");
// 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 / "include" / "c++" / "15.1.0" / "bits" / "std.cc", "export module std;\n");
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,8 +21,16 @@ int main() {
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
// Implementation should have picked up the import Greeter; through the
// interface list resolution in GetInterfacesAndImplementations.
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;
}
// 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) {
std::println(std::cerr, "expected 1 implementation, got {}", cfg.implementations.size());
return 1;
@ -36,14 +44,6 @@ int main() {
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";
if (!fs::exists(bin)) {
std::println(std::cerr, "binary not produced at {}", bin.string());

114
tests/ObjectPath/main.cpp Normal file
View file

@ -0,0 +1,114 @@
// 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;
// ObjectPath names the object of a source from where the source lies, so
// that two sources have one object only when their paths, with . and ..
// taken out of them, are one: by its path from the configuration's
// directory under BuildDir()/objects, by its whole path under
// BuildDir()/objects-outside when it lies outside that directory, and with
// an ending of its own for a .cpp, a .c and a .cu. Named from the file name
// alone, a/Thing.cpp and b/Thing.cpp shared an object (issue #50), and so
// did a Thing.c and a Thing.cu in one directory.
//
// Nothing is built here: the rule is asked for the object of sources that
// need not exist, which is how the CUDA ending is checked on a machine
// without nvcc, and the tree of outside sources against a directory of the
// configuration's own that is named like it. SameNamedSources builds
// configurations with such sources.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
Configuration Named(const fs::path& path) {
Configuration cfg;
cfg.path = path;
cfg.name = "paths";
cfg.outputName = "paths";
cfg.target = HostTarget();
return cfg;
}
}
int main() {
// Never made: the rule reads no file.
const fs::path root = fs::temp_directory_path() / "crafter-build-object-path";
const Configuration cfg = Named(root / "project");
const fs::path inside = cfg.BuildDir() / "objects";
const fs::path outside = cfg.BuildDir() / "objects-outside";
// Every source asked about below with the object it was given, to see
// at the end that no two of them were given one.
std::vector<std::pair<fs::path, fs::path>> given;
const auto expect = [&](const fs::path& source, const fs::path& object, std::string_view what) {
const fs::path got = ObjectPath(cfg, source);
Check(got == object, std::format("{}: {} has the object {}, expected {}", what, source.string(), got.string(), object.string()));
given.emplace_back(source, got);
};
expect(cfg.path / "main.cpp", inside / "main_impl.o", "a source in the configuration's directory itself");
expect(cfg.path / "a" / "Thing.cpp", inside / "a" / "Thing_impl.o", "a source in a directory of it");
expect(cfg.path / "b" / "Thing.cpp", inside / "b" / "Thing_impl.o", "a source of the same file name in another directory");
expect(cfg.path / "a" / "Thing.c", inside / "a" / "Thing_source.o", "a C source beside a C++ one of its name");
expect(cfg.path / "a" / "Thing.cu", inside / "a" / "Thing_cuda.o", "a CUDA source beside a C one of its name");
expect(cfg.path / "implementations" / "Crafter.Build-Clang.cpp", inside / "implementations" / "Crafter.Build-Clang_impl.o", "a file name with a dot in it");
// Outside the configuration's directory: by the whole path, in a tree
// of its own.
const fs::path shared = root / "shared" / "Thing.cpp";
expect(shared, outside / (root / "shared" / "Thing_impl.o").relative_path(), "a source beside the configuration's directory");
expect(root / "project-more" / "Thing.cpp", outside / (root / "project-more" / "Thing_impl.o").relative_path(), "a source in a directory whose name begins with the configuration's");
// A directory of the configuration's own named like that tree, with
// the whole path of the outside source in it: an object of the first
// tree all the same.
const fs::path mimic = cfg.path / "objects-outside" / shared.relative_path();
expect(mimic, inside / "objects-outside" / (root / "shared" / "Thing_impl.o").relative_path(), "a source under a directory of the configuration's named objects-outside");
for (std::size_t i = 0; i < given.size(); ++i) {
for (std::size_t j = i + 1; j < given.size(); ++j) {
Check(given[i].second != given[j].second, std::format("{} and {} have one object, {}", given[i].first.string(), given[j].first.string(), given[i].second.string()));
}
}
// One source however its path is spelled.
Check(ObjectPath(cfg, cfg.path / "b" / ".." / "a" / "." / "Thing.cpp") == inside / "a" / "Thing_impl.o", "a path with . and .. in it names the source it leads to");
Check(ObjectPath(cfg, cfg.path / ".." / "shared" / "Thing.cpp") == ObjectPath(cfg, shared), "a path that leaves the configuration's directory through .. names the source outside it");
Check(ObjectPath(cfg, fs::path("sources") / "Thing.c") == ObjectPath(cfg, fs::current_path() / "sources" / "Thing.c"), "a relative source is taken against the working directory");
// The configuration's directory however it is spelled: with a
// separator at its end, or relative as a project file's "./" is.
const Configuration trailing = Named(root / "project" / "");
Check(ObjectPath(trailing, root / "project" / "a" / "Thing.cpp") == trailing.BuildDir() / "objects" / "a" / "Thing_impl.o", std::format("a configuration whose path ends in a separator: {}", ObjectPath(trailing, root / "project" / "a" / "Thing.cpp").string()));
const Configuration relative = Named("./");
Check(ObjectPath(relative, fs::path("lib") / "unit.c") == relative.BuildDir() / "objects" / "lib" / "unit_source.o", std::format("a relative source of a configuration whose path is ./: {}", ObjectPath(relative, fs::path("lib") / "unit.c").string()));
Check(ObjectPath(relative, fs::current_path() / "lib" / "unit.c") == relative.BuildDir() / "objects" / "lib" / "unit_source.o", "and the same source by its whole path");
// An interface unit's object is not ObjectPath's to name, nor is any
// other file's.
for (const std::string_view name : {"Thing.cppm", "Thing.h", "Thing"}) {
bool refused = false;
try {
ObjectPath(cfg, cfg.path / name);
} catch (const std::invalid_argument&) {
refused = true;
}
Check(refused, std::format("{} is refused: not a .cpp, .c or .cu", name));
}
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,16 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// Both entry points: whichever the loader called, what the other returns
// would go unbuilt.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view>) {
return {};
}
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view>) {
return {};
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// Returns nothing to build.
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view>) {
return {};
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// No entry point: the function has a name the loader does not look for.
extern "C" Configuration CrafterBuildProjects(std::span<const std::string_view>) {
return {};
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// Returns a pointer to nothing.
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view>) {
return { nullptr };
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Greeter;
import std;
export namespace Greeter {
std::string Greet(std::string_view name) {
return std::format("hello {}", name);
}
}

View file

@ -0,0 +1,12 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Greeter;
// -r runs this in its own directory, where it leaves what it would have
// printed for the test to find.
int main() {
std::ofstream("hello.ran") << Greeter::Greet("world");
return 0;
}

View file

@ -0,0 +1,94 @@
// 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 project of three configurations: a library, a program built on it, and
// a tool that shares nothing with either. The library and the tool each
// declare a test and a script. --no-tool leaves the tool out, which leaves
// one executable for -r to run. --packaged packages both programs as
// Flatpaks, for install and bundle to choose between, and makes them wasm
// builds, which a build refuses to package wherever the test runs: nothing
// is ever exported, let alone installed. --twin-test has the library
// declare the tool's test as well, which a test run refuses to build.
// --twin adds a fourth configuration of the tool's name and path, which
// would be built into the tool's directory.
namespace {
// One new set per call, at addresses that never change: whoever loads
// this file keeps the pointers it returns.
std::deque<Configuration> Owned;
// Leaves `<script>.ran` in the project's directory, holding the name of
// the configuration the script was handed.
std::int32_t Stamp(const ScriptContext& ctx, std::string_view script) {
std::ofstream(ctx.projectDir / std::format("{}.ran", script)) << ctx.project.name;
return 0;
}
}
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view> args) {
Configuration& greeter = Owned.emplace_back();
greeter.path = "./";
greeter.name = "greeter";
greeter.outputName = "greeter";
greeter.type = ConfigurationType::LibraryStatic;
{
std::array<fs::path, 1> interfaces = { "greeter/Greeter" };
std::array<fs::path, 0> implementations = {};
greeter.GetInterfacesAndImplementations(interfaces, implementations);
}
greeter.AddTest("GreeterTest").Dependencies({ &greeter });
if (std::ranges::contains(args, std::string_view("--twin-test"))) greeter.AddTest("ToolTest");
greeter.scripts.push_back({"greet", [](ScriptContext& ctx) { return Stamp(ctx, "greet"); }});
Configuration& hello = Owned.emplace_back();
hello.path = "./";
hello.name = "hello";
hello.outputName = "hello";
hello.type = ConfigurationType::Executable;
hello.dependencies = { &greeter };
{
std::array<fs::path, 0> interfaces = {};
std::array<fs::path, 1> implementations = { "hello/main" };
hello.GetInterfacesAndImplementations(interfaces, implementations);
}
const bool packaged = std::ranges::contains(args, std::string_view("--packaged"));
if (packaged) {
hello.packaging = Packaging::Flatpak;
hello.target = "wasm32-wasip1";
}
if (std::ranges::contains(args, std::string_view("--no-tool"))) return { &greeter, &hello };
Configuration& tool = Owned.emplace_back();
tool.path = "./";
tool.name = "tool";
tool.outputName = "tool";
tool.type = ConfigurationType::Executable;
{
std::array<fs::path, 0> interfaces = {};
std::array<fs::path, 1> implementations = { "tool/main" };
tool.GetInterfacesAndImplementations(interfaces, implementations);
}
tool.AddTest("ToolTest");
tool.scripts.push_back({"stamp", [](ScriptContext& ctx) { return Stamp(ctx, "stamp"); }});
if (packaged) {
tool.packaging = Packaging::Flatpak;
tool.target = "wasm32-wasip1";
}
if (std::ranges::contains(args, std::string_view("--twin"))) {
Configuration& twin = Owned.emplace_back();
twin.path = "./";
twin.name = "tool";
twin.outputName = "tool-twin";
twin.type = ConfigurationType::Executable;
return { &greeter, &hello, &tool, &twin };
}
return { &greeter, &hello, &tool };
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Greeter;
int main() {
return Greeter::Greet("test") == "hello test" ? 0 : 1;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
// Leaves a file where it ran: the directory of the project whose test run
// started it.
int main() {
std::ofstream("ToolTest.ran") << "ran";
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("tool");
return 0;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Single;
import std;
export namespace Single {
std::int32_t Answer() {
return 42;
}
}

View file

@ -0,0 +1,22 @@
// 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;
// The form with one configuration: a library whose test links it, so the
// test's dependency is a pointer to the Configuration this function returns.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view>) {
Configuration cfg;
cfg.path = "./";
cfg.name = "single";
cfg.outputName = "single";
cfg.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 1> interfaces = { "Single" };
std::array<fs::path, 0> implementations = {};
cfg.GetInterfacesAndImplementations(interfaces, implementations);
cfg.AddTest("SelfTest").Dependencies({ &cfg });
return cfg;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Single;
int main() {
return Single::Answer() == 42 ? 0 : 1;
}

View file

@ -0,0 +1,17 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// Returns one configuration twice, as a pasted line does.
namespace {
std::deque<Configuration> Owned;
}
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view>) {
Configuration& same = Owned.emplace_back();
same.name = "same";
return { &same, &same };
}

View file

@ -0,0 +1,228 @@
// 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 project file describes one configuration, returned by value from
// CrafterBuildProject, or several that need not have anything to do with
// each other, returned as pointers from CrafterBuildConfigurations, and
// crafter-build's verbs act on every one of them.
//
// Before the second entry point a project had one configuration, and
// whatever else it wanted built had to be made a dependency of that one.
// What this guards against is one of several going missing without a word:
// left out because the file returned it twice by mistake, or because a verb
// only looks at the first, so that its tests never run and its scripts
// cannot be reached; a verb that needs one of them picking one by guessing;
// and a test that two of them declare being built for both at once, in the
// one directory a test of that name has. And the form with one
// configuration keeps what it relied on all along: a pointer the file took
// to the Configuration it returns, which a test that links the project's
// library holds, still points at it once the file is loaded.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::string Read(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
// What `call` throws, or "" when it returns.
std::string Thrown(const std::function<void()>& call) {
try {
call();
} catch (const std::exception& e) {
return e.what();
}
return "";
}
// Run() as the command line reaches it, and what it wrote to stderr.
struct Ran {
std::int32_t status = 0;
std::string err;
};
Ran RunWith(std::vector<std::string> args) {
std::vector<char*> argv;
for (std::string& arg : args) argv.push_back(arg.data());
std::ostringstream err;
std::streambuf* const saved = std::cerr.rdbuf(err.rdbuf());
const std::int32_t status = Run(static_cast<std::int32_t>(argv.size()), argv.data());
std::cerr.rdbuf(saved);
return { status, err.str() };
}
std::vector<std::string> Names(std::span<Configuration* const> configurations) {
std::vector<std::string> names;
for (const Configuration* cfg : configurations) names.push_back(cfg->name);
return names;
}
}
int main() {
const fs::path installedHome = GetCrafterBuildHome();
if (!fs::exists(installedHome / "Crafter.Build.cppm")) {
std::println(std::cerr, "SKIP: no module sources at {}", installedHome.string());
return 77;
}
// Staged because every load drops a build/ tree next to its project
// file.
const fs::path home = fs::current_path();
const fs::path scratch = fs::temp_directory_path() / "crafter-build-project-configurations";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::copy(home / "tests" / "ProjectConfigurations" / "fixture", scratch, fs::copy_options::recursive);
std::array<std::string_view, 0> noArgs = {};
std::array<std::string_view, 1> noTool = { "--no-tool" };
// The loader: what each entry point comes back as. From the project's
// own directory, as crafter-build runs it: the fixtures name their
// sources relative to it.
fs::current_path(scratch / "several");
std::vector<Configuration*> several;
try {
several = LoadConfigurations("project.cpp", noArgs);
} catch (const std::exception& e) {
std::println(std::cerr, "FAIL: loading a project of several configurations threw: {}", e.what());
return 1;
}
Check(Names(several) == std::vector<std::string>{"greeter", "hello", "tool"}, std::format("CrafterBuildConfigurations comes back as the file returned it (got {})", Names(several)));
// Every case below reads the three of them.
if (several.size() != 3) return 1;
Check(several[1]->dependencies == std::vector<Configuration*>{several[0]}, "the pointers the file took between its configurations are the ones it returned");
Check(Names(LoadConfigurations("project.cpp", noTool)) == std::vector<std::string>{"greeter", "hello"}, "the file decides what it returns from its args");
Check(Thrown([&] { (void)LoadProject("project.cpp", noArgs); }).contains("LoadConfigurations"), "LoadProject refuses a file of several configurations and names the function that loads it");
fs::current_path(scratch / "single");
{
const std::vector<Configuration*> single = LoadConfigurations("project.cpp", noArgs);
Check(Names(single) == std::vector<std::string>{"single"}, "CrafterBuildProject comes back as a list of one");
// The file handed its test `&cfg`. Moved after the call returned
// it, the Configuration would leave that pointer behind.
Check(single.size() == 1 && single[0]->tests.size() == 1 && single[0]->tests[0].config.dependencies == std::vector<Configuration*>{single[0]}, "a pointer the file took to the Configuration it returns points at the one that is loaded");
// And the test builds through that pointer.
RunTestsOptions opts;
opts.targetFilter = HostTarget();
const TestSummary summary = RunTests(single, opts);
Check(summary.passed == 1 && summary.AllPassed(), std::format("a test that links the project's own library through that pointer builds and passes ({} passed, {} failed, {} crashed)", summary.passed, summary.failed, summary.crashed));
Check(LoadProject("project.cpp", noArgs).name == "single", "LoadProject still returns a CrafterBuildProject's Configuration by value");
}
// A file the loader cannot make sense of says so when it is loaded. By
// now this process holds project files with each entry point, so these
// also show that one file's entry point is never taken for another's.
for (const auto& [project, expected] : std::initializer_list<std::pair<std::string_view, std::string_view>>{
{"both", "defines both CrafterBuildProject and CrafterBuildConfigurations"},
{"neither", "defines neither CrafterBuildProject nor CrafterBuildConfigurations"},
{"empty", "returned no configuration"},
{"null", "returned a null pointer"},
{"twice", "returned same twice"},
}) {
const std::string thrown = Thrown([&] { (void)LoadConfigurations(scratch / project / "project.cpp", noArgs); });
Check(thrown.contains(expected), std::format("{}/project.cpp is refused, saying '{}' (got '{}')", project, expected, thrown));
}
// The verbs, over the project crafter-build is pointed at. A build
// builds every one of them.
fs::current_path(scratch / "several");
Check(RunWith({"crafter-build", "-q"}).status == 0, "a build of the project succeeds");
for (const Configuration* cfg : several) {
Check(fs::exists(ExpectedOutput(*cfg)), std::format("the build built {}", cfg->name));
}
{
const Ran run = RunWith({"crafter-build", "-q", "-r"});
Check(run.status == 1 && run.err.contains("hello, tool are executables"), std::format("-r runs one program and says which two it will not pick between (exit {}): {}", run.status, run.err));
}
{
// -r leaves this process in the program's directory.
const fs::path ran = fs::absolute(several[1]->ProgramDir()) / "hello.ran";
fs::remove(ran, ec);
const Ran run = RunWith({"crafter-build", "-q", "--no-tool", "-r"});
fs::current_path(scratch / "several");
Check(run.status == 0 && Read(ran) == "hello world", std::format("with one executable among the configurations, -r runs it (exit {}): {}", run.status, run.err));
}
{
// The library declares the tool's test as well: one tests/ToolTest
// and one directory to build it in, for two configurations. Built
// for both at once, that directory would end up holding either.
std::array<std::string_view, 1> twinTest = { "--twin-test" };
const std::vector<Configuration*> twins = LoadConfigurations("project.cpp", twinTest);
RunTestsOptions opts;
opts.targetFilter = HostTarget();
const TestSummary summary = RunTests(twins, opts);
std::int32_t refused = 0;
for (const TestResult& result : summary.results) {
if (result.name == "ToolTest" && result.outcome == TestOutcome::Fail && result.output.contains("greeter, tool each declare a test named ToolTest")) ++refused;
}
Check(refused == 2 && summary.failed == 2 && summary.passed == 1, std::format("a test two configurations declare fails for both, naming them, and the library's own test still passes ({} refused, {} failed, {} passed)", refused, summary.failed, summary.passed));
Check(twins.size() == 3 && twins[2]->tests.size() == 1 && !fs::exists(ExpectedOutput(twins[2]->tests[0].config)), "and it is built for neither");
}
{
RunTestsOptions opts;
opts.targetFilter = HostTarget();
const TestSummary summary = RunTests(several, opts);
std::vector<std::string> ran;
for (const TestResult& result : summary.results) ran.push_back(result.name);
std::ranges::sort(ran);
Check(ran == std::vector<std::string>{"GreeterTest", "ToolTest"} && summary.passed == 2, std::format("the tests of every configuration run in one run (ran {}, {} passed)", ran, summary.passed));
// Named twice in the list, a configuration's tests would each be
// built twice at once.
std::array<Configuration*, 2> same = { several[0], several[0] };
const TestSummary once = RunTests(same, opts);
Check(once.results.size() == 1 && once.passed == 1, std::format("a list that names one configuration twice runs its tests once ({} results, {} passed)", once.results.size(), once.passed));
}
{
// Two returned configurations of one directory are refused by a
// test run as by a build, though a test run never builds the
// configurations themselves: a test built on the one would be
// handed the other's build.
// Refused from the loaded project alone, so before anything is
// built or written: with a template beside the project file, a
// build or a test run that gets as far as building writes AGENTS.md.
const fs::path templateFile = scratch / "several" / "AGENTS.template.md";
std::ofstream(templateFile) << "# several\n";
const Ran test = RunWith({"crafter-build", "-q", "--twin", "test"});
Check(test.status == 1 && test.err.contains("two configurations named tool would both be built into"), std::format("a test run refuses two configurations that would be built into one directory (exit {}): {}", test.status, test.err));
const Ran build = RunWith({"crafter-build", "-q", "--twin"});
Check(build.status == 1 && build.err.contains("two configurations named tool would both be built into"), std::format("and so does a build (exit {}): {}", build.status, build.err));
Check(!fs::exists(scratch / "several" / "AGENTS.md"), "and neither has written AGENTS.md");
Check(RunWith({"crafter-build", "-q"}).status == 0 && fs::exists(scratch / "several" / "AGENTS.md"), "which a build that is not refused writes");
fs::remove(templateFile, ec);
fs::remove(scratch / "several" / "AGENTS.md", ec);
}
Check(RunWith({"crafter-build", "-q", "run", "stamp"}).status == 0 && Read(scratch / "several" / "stamp.ran") == "tool", "a script of the third configuration runs, handed the configuration that declares it");
Check(RunWith({"crafter-build", "-q", "run", "greet"}).status == 0 && Read(scratch / "several" / "greet.ran") == "greeter", "and so does one of the first");
// install and bundle export one app: the configuration packaged as a
// Flatpak. The fixture's packaged programs are wasm builds, which no
// build packages, so the one case that gets past the choice ends there
// or, where the host's flatpak is out of reach, before it.
{
const Ran none = RunWith({"crafter-build", "-q", "install"});
Check(none.status == 1 && none.err.contains("none of greeter, hello, tool is packaged as a Flatpak"), std::format("install refuses a project none of whose configurations is packaged (exit {}): {}", none.status, none.err));
const Ran two = RunWith({"crafter-build", "-q", "--packaged", "bundle"});
Check(two.status == 1 && two.err.contains("hello, tool are each packaged as a Flatpak"), std::format("bundle refuses to pick between two packaged configurations (exit {}): {}", two.status, two.err));
const Ran one = RunWith({"crafter-build", "-q", "--packaged", "--no-tool", "bundle"});
Check(one.status == 1 && !one.err.contains("none of") && !one.err.contains("are each packaged") && !one.err.contains("greeter is not packaged"), std::format("with one packaged configuration among them, bundle takes that one (exit {}): {}", one.status, one.err));
}
fs::current_path(home);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
fs::remove_all(scratch, ec);
return 0;
}

View file

@ -34,6 +34,8 @@ namespace {
// 0 -> Pass
// 77 -> Skipped (autoconf convention)
// anything else -> Fail
// and that a binary whose path has an '=' in it runs, with a TMPDIR as
// RunTests gives it.
int main() {
fs::path dir = fs::temp_directory_path() / "crafter-build-run-single-test";
std::error_code ec;
@ -76,6 +78,23 @@ int main() {
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);
if (Failures > 0) {

View file

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

View file

@ -0,0 +1,4 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#define LIMIT 100

View file

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

View file

@ -0,0 +1,4 @@
/* SPDX-License-Identifier: LGPL-3.0-only
SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */
int AUnit(void) { return 4; }

View file

@ -0,0 +1,4 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
int B() { return 200; }

Some files were not shown because too many files have changed in this diff Show more