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
89 changed files with 4428 additions and 649 deletions

View file

@ -16,20 +16,20 @@ crafter-build is a C++26 modules build system. A project is described by a `proj
| `examples/` | Standalone user-facing projects, MIT licensed. |
| `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 `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 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.
@ -40,7 +40,7 @@ Partitions and what they own:
The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop.
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/
@ -90,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.
@ -124,6 +125,8 @@ Beyond the rules:
- 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
@ -159,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.
- `--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
@ -203,7 +207,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary:
- A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps.
- 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.
- The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then.
- `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.
@ -211,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.

View file

@ -43,9 +43,11 @@ 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.
crafter-build orders a configuration's units by the `import` lines of its sources: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused before anything of it is built, with an error that names the units in the order they wait. The imports are read from the source text without compiling it, so one in a string literal, in a comment that spans lines or under `#if 0` counts too, and such text can make a round in a project the compiler accepts.
A `.cpp`, `.c` or `.cu` of a configuration is compiled into an object named from its path: `a/Thing.cpp` into `objects/a/Thing_impl.o` in that `build/` directory, at the source's path from `cfg.path`, and a source outside `cfg.path` into `objects-outside/` there, at its whole path. Two sources may therefore have the same file name in different directories, and a `.c` may lie beside a `.cpp` or a `.cu` of its name. The progress line of such a source's compile names it by the same path, `Compiling a/Thing.cpp`. The link, and the archive step of a static library, read their objects from a file in that directory, `<outputName>.objects`, so the command is no longer for many sources than for one.
A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts.
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
@ -180,7 +182,7 @@ Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project.
cfg.dependencies = { math };
```
The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that 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 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.
@ -297,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.
- 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. Failed/crashed/timed-out tests also write to `build/test-logs/<name>.log`.
- 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:
@ -311,6 +314,7 @@ crafter-build test --target=x86_64-w64-mingw32 # only tests for
crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine
crafter-build test --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.
@ -373,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:
@ -540,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

@ -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

File diff suppressed because it is too large Load diff

View file

@ -13,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;
}
@ -36,7 +36,7 @@ namespace Crafter {
}
return false;
}
void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) 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 (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
@ -50,7 +50,11 @@ namespace Crafter {
// 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.
jobs.Add(std::format("Compiling {}.cpp", path.filename().string()), [command = 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())] {
//
// 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

@ -185,10 +185,10 @@ namespace Crafter {
if (scheduled) return precompileJob;
std::vector<JobGroup::Job> after;
// All of the module's partitions, not the ones the primary interface
// names: the scanner records no edge for its `import :Part;` lines
// (see GetInterfacesAndImplementations). 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.
// 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);
}

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;
@ -903,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) {
@ -1206,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;

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;
@ -874,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") {

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) {
@ -259,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);
@ -292,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;
}
@ -444,20 +587,10 @@ 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;
@ -468,14 +601,30 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
}
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> 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 RunTests(distinct, opts, projectArgs);
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
@ -502,7 +651,7 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, co
Progress::Clear();
std::println("\n=== target: {} ===", target);
}
TestSummary s = RunTests(configurations, perTarget, projectArgs);
TestSummary s = RunTestsWith(configurations, perTarget, projectArgs, run);
aggregate.passed += s.passed;
aggregate.failed += s.failed;
aggregate.crashed += s.crashed;
@ -582,6 +731,28 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, co
}
}
// 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());
@ -702,16 +873,47 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, co
// 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(owners[i]->path, r.name, r.output);
WriteLog(owners[i]->path, logName, r.output);
}
{
@ -757,3 +959,8 @@ TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, co
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

@ -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
@ -509,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;
@ -602,16 +636,14 @@ export namespace Crafter {
// 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
@ -790,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,
@ -804,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

View file

@ -11,18 +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;
// Adds the job that compiles this unit to `jobs`, after the BMIs of
// the stale interface units it imports (ModulePartition::Schedule,
// Module::Schedule). For a unit Check found stale.
void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) 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

@ -10,20 +10,19 @@ 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;
// The state of one Build(), which clears it before it checks: whether
// Check has run, what it found, whether Schedule has added this
// unit's jobs, and the one among them that writes its BMI, which is
// the job the units importing it come after.
// 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;
@ -58,13 +57,14 @@ namespace Crafter {
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 Schedule()
// 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;
// As in ModulePartition.
bool needsRecompiling = false;
bool checked = false;

View file

@ -58,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
@ -164,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

@ -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,6 +53,9 @@ 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 {
@ -75,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 {
@ -98,7 +105,34 @@ export namespace Crafter {
// 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 = {});
TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout);
// 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 = {});
// The configurations of the project crafter-build was pointed at, by
// name. Run() hands SetParentProject what the project file returned,

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

@ -26,6 +26,47 @@
</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>

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

@ -247,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() });
@ -310,6 +314,8 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("TestTemporaryDirectory").Dependencies({ CrafterBuildLib.get() });
// Loading a project file dlopens the project.so compiled from it,
// which references Crafter:: symbols (HostTarget, Configuration
// ctors) that have to be visible from the test exe — same wiring
@ -345,8 +351,10 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
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

@ -8,10 +8,12 @@ using namespace Crafter;
// Regression for the concurrent dependency-reset deadlock (issue #16).
//
// Build() resets each Module/ModulePartition's per-build state (`checked`,
// `scheduled` and the job that precompiles the unit) 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
// 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
@ -30,11 +32,11 @@ using namespace Crafter;
// 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 would flip the dependency's module `checked` and
// `scheduled` flags back to false and, because the dependency never rebuilds,
// they would stay false. The consumer resets only its own modules, so the
// dependency's flags are left intact. We assert both are still set once the
// consumer build completes.
// 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";
@ -58,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;
@ -71,6 +68,10 @@ int main() {
std::println(std::cerr, "dependency build failed: {}", r.result);
return 1;
}
if (dep.interfaces.size() != 1) {
std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size());
return 1;
}
if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
std::println(std::cerr, "dependency module not marked checked and scheduled after its own build");
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

@ -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

@ -6,11 +6,11 @@ import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// Interface units that import each other are refused before their
// configuration builds anything, 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.
// 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
@ -28,9 +28,9 @@ namespace {
// 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 has made its directories before it
// fails, and in the checkout the next run would find them there and
// report them against a refusal that works.
// 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);
@ -49,9 +49,13 @@ namespace {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(cfg, depResults, depMutex);
// Refused like a graph with a module built twice: before a directory
// is made for it.
Check(!fs::exists(cfg.BuildDir()) && !fs::exists(cfg.BinDir()), std::format("{}: the refused build left {} or {} behind", dir, cfg.BuildDir().string(), cfg.BinDir().string()));
// 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;
}
}
@ -61,9 +65,6 @@ 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));
// The scanner reads imports the compiler does not see, so the error
// has to say where a round nobody wrote can come from.
Check(error.contains("string literal") && error.contains("#if 0"), std::format("the error says which text the scanner reads as an import, got: '{}'", error));
}
{
std::array<fs::path, 2> interfaces = { "Own", "Own-Part" };

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);
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");
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");
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.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");
}
}
// 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");
}
Check(std::ranges::find(impl.pendingImports, "Widget") == impl.pendingImports.end(), "resolved import is no longer pending");
// Idempotent: a second sweep must not duplicate the edge (Build
// runs one unconditionally, on top of whatever callers already did).
app.ResolvePendingImports();
Check(impl.externalModuleDependencies.size() == 1, "ResolvePendingImports is idempotent");
}
}
{
// AddTest is the reported path: it 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) {
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");
if (app.tests.size() == 1 && BuildOk(app.tests[0].config, "test declared with AddTest")) {
Check(app.tests[0].config.implementations.size() == 1, "the test has one implementation");
if (app.tests[0].config.implementations.size() == 1) {
const Implementation& impl = app.tests[0].config.implementations[0];
Check(impl.externalModuleDependencies.size() == 1, "AddTest(...).Dependencies() gives the test's import of the library module its edge");
}
}
fs::current_path(restore);
}
{
// 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

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

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

@ -629,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");
@ -688,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
@ -697,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);
@ -711,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* {
@ -733,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

@ -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; }

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,18 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int A();
int B();
int Shared();
extern "C" int AUnit(void);
extern "C" int BUnit(void);
extern "C" int BThingInC(void);
// Prints what each of the other sources returns, a/Thing.cpp's first: every
// one of them has to be in the program, and as it stands now.
int main() {
std::printf("%d %d %d %d %d %d", A(), B(), AUnit(), BUnit(), BThingInC(), Shared());
return 0;
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
void Register(int source);
// Nothing in this file is named by another: it is in the program for what it
// does when the program starts.
namespace {
const int registered = (Register(1), 0);
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
void Register(int source);
// Nothing in this file is named by another: it is in the program for what it
// does when the program starts.
namespace {
const int registered = (Register(2), 0);
}

View file

@ -0,0 +1,19 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
namespace {
// How often each source has registered: [1] is a/Self.cpp's count and
// [2] is b/Self.cpp's.
int Registered[3];
}
// Called by a/Self.cpp with 1 and by b/Self.cpp with 2, as the program starts.
void Register(int source) { ++Registered[source]; }
// Prints the two counts: "1 1" when each of the two is in the program once.
int main() {
std::printf("%d %d", Registered[1], Registered[2]);
return 0;
}

View file

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

View file

@ -0,0 +1,208 @@
// 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;
// Two sources of one configuration may have the same file name in different
// directories: each has an object of its own. An object used to be named
// from its source's file name alone, so a/Thing.cpp and b/Thing.cpp were
// compiled into one Thing_impl.o, each over the other, and the link was
// given that object twice (issue #50). A build of sources that define what
// another file calls failed at the link, with duplicate symbols of one of
// them and no word of the other. A debug build of sources that define
// nothing another file names, and are in the program for what they do when
// it starts, succeeded: the program had one of them twice and the other not
// at all.
//
// The fixture has both. `names` is an executable of a/Thing.cpp and
// 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 of them returns. A header only
// a/Thing.cpp includes is then changed, and after that b/Thing.cpp and
// b/unit.c: each time the program has to print the new values of the
// sources that changed and the values the others had. `registry` is a debug
// executable of a/Self.cpp and b/Self.cpp, which register themselves when
// the program starts, and prints how often each did. `things` is a static
// library of a/Thing.cpp, b/Thing.cpp, b/Thing.c and the two unit.c, whose
// archive then holds members of one name, and `things-app` a program of
// main.cpp and ../shared/Thing.cpp built on it.
//
// The object of a source outside its configuration's directory is named by
// the source's whole path, so that path holds every directory above the
// source. `outside`, which the test makes last, is a static library of one
// such C source, listed relative to the working directory and built from a
// working directory with a space in its name: the object's path then holds
// the space, where neither the source as listed nor the build directory
// does, and has to reach the compiler and the archive as one path.
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 changed during the run, so it is a copy outside the
// checkout that is built.
fs::path StageFixture() {
const fs::path source = fs::current_path() / "tests" / "SameNamedSources" / "fixture";
const fs::path staged = fs::temp_directory_path() / "crafter-build-same-named-sources";
fs::remove_all(staged);
fs::copy(source, staged, fs::copy_options::recursive);
return staged;
}
// Puts <name>-grown<extension>.in in the place of `file`. The other
// text is a file of the fixture rather than a string here, so that the
// one under the source's name is the only one a build sees.
void Grow(const fs::path& file) {
const fs::path grown = file.parent_path() / std::format("{}-grown{}.in", file.stem().string(), file.extension().string());
fs::copy_file(grown, file, fs::copy_options::overwrite_existing);
// copy_file gives the copy the time of what it copied, which would
// leave the changed file older than the object built from it.
fs::last_write_time(file, fs::file_time_type::clock::now());
}
// The C sources of `names`, without their extensions and whole: cFiles
// are read against the working directory, not against cfg.path.
std::vector<fs::path> CSources(const fs::path& staged) {
return { staged / "names" / "a" / "unit", staged / "names" / "b" / "unit", staged / "names" / "b" / "Thing" };
}
// The issue's first case, and more of the kind: every source defines
// something main.cpp calls. ../shared/Thing lies outside the
// configuration's directory.
Configuration MakeNames(const fs::path& staged) {
Configuration cfg;
cfg.path = staged / "names";
cfg.name = "names";
cfg.outputName = "names";
cfg.target = HostTarget();
cfg.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 4> impls = { "main", "a/Thing", "b/Thing", "../shared/Thing" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
cfg.cFiles = CSources(staged);
return cfg;
}
// The issue's second case: a debug build of sources nothing names.
Configuration MakeRegistry(const fs::path& staged) {
Configuration cfg;
cfg.path = staged / "registry";
cfg.name = "registry";
cfg.outputName = "registry";
cfg.target = HostTarget();
cfg.debug = true;
cfg.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 3> impls = { "main", "a/Self", "b/Self" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
return cfg;
}
// a/Thing.cpp, b/Thing.cpp and the C sources of `names` as a static
// library.
std::unique_ptr<Configuration> MakeThings(const fs::path& staged) {
std::unique_ptr<Configuration> lib = std::make_unique<Configuration>();
lib->path = staged / "names";
lib->name = "things";
lib->outputName = "things";
lib->target = HostTarget();
lib->type = ConfigurationType::LibraryStatic;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 2> impls = { "a/Thing", "b/Thing" };
lib->GetInterfacesAndImplementations(ifaces, impls);
lib->cFiles = CSources(staged);
return lib;
}
Configuration MakeThingsApp(const fs::path& staged, Configuration* things) {
Configuration cfg;
cfg.path = staged / "names";
cfg.name = "things-app";
cfg.outputName = "things-app";
cfg.target = HostTarget();
cfg.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 2> impls = { "main", "../shared/Thing" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
cfg.dependencies = { things };
return cfg;
}
bool BuildOk(Configuration& cfg, std::string_view label) {
// A fresh record for each pass: one that holds a configuration's
// build already would hand it to the next pass unbuilt.
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult r = Build(cfg, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "FAIL: {} failed: {}", label, r.result);
++Failures;
return false;
}
return true;
}
void CheckPrints(const Configuration& cfg, std::string_view expected, std::string_view label) {
const auto r = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30));
Check(r.exitCode == 0 && r.output == expected, std::format("{}: the program printed '{}' (exit {}), expected '{}'", label, r.output, r.exitCode, expected));
}
}
int main() {
const fs::path staged = StageFixture();
// A() B() AUnit() BUnit() BThingInC() Shared(), see the fixture's
// names/main.cpp.
Configuration names = MakeNames(staged);
if (BuildOk(names, "the build of names")) CheckPrints(names, "1 2 4 8 16 32", "names");
Grow(staged / "names" / "a" / "limit.h");
if (BuildOk(names, "the build of names after a header of a/Thing.cpp changed")) CheckPrints(names, "100 2 4 8 16 32", "names after a header of a/Thing.cpp changed");
Grow(staged / "names" / "b" / "Thing.cpp");
Grow(staged / "names" / "b" / "unit.c");
if (BuildOk(names, "the build of names after b/Thing.cpp and b/unit.c changed")) CheckPrints(names, "100 200 4 800 16 32", "names after b/Thing.cpp and b/unit.c changed");
// How often a/Self.cpp registered, then b/Self.cpp.
Configuration registry = MakeRegistry(staged);
if (BuildOk(registry, "the debug build of registry")) CheckPrints(registry, "1 1", "registry");
// The sources as they are after the changes above.
const std::unique_ptr<Configuration> things = MakeThings(staged);
Configuration app = MakeThingsApp(staged, things.get());
if (BuildOk(app, "the build of things-app on the static library things")) CheckPrints(app, "100 200 4 800 16 32", "things-app");
// Last, because it changes the working directory of the test: a
// relative cfg.path and a relative C source are read against it.
const fs::path spaced = staged / "with space";
fs::create_directories(spaced / "app");
fs::create_directories(spaced / "shared");
std::ofstream(spaced / "shared" / "unit.c") << "int Outside(void) { return 64; }\n";
fs::current_path(spaced / "app");
Configuration outside;
outside.path = "./";
outside.name = "outside";
outside.outputName = "outside";
outside.target = HostTarget();
outside.type = ConfigurationType::LibraryStatic;
outside.cFiles = { "../shared/unit" };
if (BuildOk(outside, "the build of outside, from a working directory with a space in its name")) {
const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(outside).string())), std::chrono::seconds(30));
Check(members.exitCode == 0 && members.output == "unit_source.o\n", std::format("outside: llvm-ar t lists '{}' (exit {}), expected the object of ../shared/unit.c", members.output, members.exitCode));
}
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

288
tests/SourceScan/main.cpp Normal file
View file

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

View file

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

View file

@ -0,0 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Nothing calls this: the test looks for the object of this file among the
// members of the library's archive.
int Extra() { return 3; }

View file

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

View file

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

View file

@ -0,0 +1,13 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int Value();
// Prints what the library's Value() returns: 1 from lib/first.cpp, 2 from
// lib/second.cpp, whichever the library was built from.
int main() {
std::printf("%d", Value());
return 0;
}

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 static library holds the objects of the sources its configuration lists
// and no others. Its archive used to be updated where it lay: `llvm-ar rcs`
// into an archive that is there replaces the members it is given and leaves
// every other member as it is, so the object of a source that had left the
// project stayed in the library. The link takes a symbol from the first
// member that defines it, and a member left behind comes before the ones
// added after it: once a source had been renamed, whatever was built on the
// library went on linking the object of the file under its old name.
//
// The fixture's 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. The library is built three times, by
// configurations of one name and directory, so into one archive: from the
// first and the extra source; from the first alone, the extra one taken out
// of the project and nothing else changed; and from the second in the
// first's place, as the project of a renamed source lists it. Each time the
// archive has to hold the objects of the sources listed and no other, and
// the program built on the library to print what the Value() listed returns.
//
// The archive also has to be in its place for as long as it is written
// anew: a library that another project is built on may be linked by that
// project's crafter-build at any moment, where both build it in one clone
// in the cache. While the second and the third build run, a thread looks
// for the archive again and again.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// Built into the fixture's own bin/ and build/, which an earlier run
// would have left with the last archive in them: a copy that starts
// with neither.
fs::path StageFixture() {
const fs::path source = fs::current_path() / "tests" / "StaticLibSourceRemoved" / "fixture";
const fs::path staged = fs::temp_directory_path() / "crafter-build-static-lib-source-removed";
fs::remove_all(staged);
fs::copy(source, staged, fs::copy_options::recursive);
return staged;
}
// The library, of the lib/<source>.cpp listed. One name and one
// directory whichever sources it lists, so one build directory and one
// archive: the same library before and after a source leaves it.
std::unique_ptr<Configuration> MakeLib(const fs::path& staged, std::vector<fs::path> sources) {
std::unique_ptr<Configuration> lib = std::make_unique<Configuration>();
lib->path = staged / "lib";
lib->name = "value";
lib->outputName = "value";
lib->target = HostTarget();
lib->type = ConfigurationType::LibraryStatic;
std::array<fs::path, 0> ifaces = {};
lib->GetInterfacesAndImplementations(ifaces, sources);
return lib;
}
Configuration MakeApp(const fs::path& staged, Configuration* lib) {
Configuration app;
app.path = staged;
app.name = "value-app";
app.outputName = "value-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);
app.dependencies = { lib };
return app;
}
bool BuildOk(Configuration& app, std::string_view label) {
// A fresh record for each pass: one that already holds the library's
// build would hand it to the next pass unbuilt.
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult r = Build(app, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "FAIL: {} failed: {}", label, r.result);
++Failures;
return false;
}
return true;
}
// Builds `app` as BuildOk does, with a thread looking for `archive` from
// before the build starts until it has ended: whether the build
// succeeded and the archive was there every time.
bool BuildOkWithArchiveInPlace(Configuration& app, const fs::path& archive, std::string_view label) {
std::atomic<bool> missing{false};
bool built = false;
{
std::jthread watcher([&archive, &missing](std::stop_token stop) {
while (!stop.stop_requested()) {
std::error_code ec;
if (!fs::exists(archive, ec)) missing = true;
}
});
built = BuildOk(app, label);
// Leaving the scope stops the watcher and waits for it.
}
Check(!missing, std::format("{}: the archive is in its place for as long as the build writes it anew", label));
return built;
}
void CheckPrints(const Configuration& app, std::string_view expected, std::string_view label) {
const auto r = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30));
Check(r.exitCode == 0 && r.output == expected, std::format("{}: the program printed '{}' (exit {}), expected '{}'", label, r.output, r.exitCode, expected));
}
// The members of `lib`'s archive, as `llvm-ar t` lists them, have to be
// `expected`, one to a line.
void CheckMembers(const Configuration& lib, std::string_view expected, std::string_view label) {
const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(lib).string())), std::chrono::seconds(30));
Check(members.exitCode == 0 && members.output == expected, std::format("{}: llvm-ar t lists '{}' (exit {}), expected '{}'", label, members.output, members.exitCode, expected));
}
}
int main() {
const fs::path staged = StageFixture();
const std::unique_ptr<Configuration> both = MakeLib(staged, { "first", "extra" });
Configuration withExtra = MakeApp(staged, both.get());
if (!BuildOk(withExtra, "the build with lib/first.cpp and lib/extra.cpp")) return 1;
CheckPrints(withExtra, "1", "built with lib/first.cpp and lib/extra.cpp");
CheckMembers(*both, "first_impl.o\nextra_impl.o\n", "the archive of lib/first.cpp and lib/extra.cpp");
// What the passes below rest on: were the configurations built into
// directories of their own, each archive would be made from nothing and
// the later passes would prove nothing.
const fs::path archive = ExpectedOutput(*both);
// No source is compiled for this one and no object is newer than the
// archive: that the library lists one object fewer is all that changed.
const std::unique_ptr<Configuration> alone = MakeLib(staged, { "first" });
Check(ExpectedOutput(*alone) == archive, "the library is one archive whichever sources it lists");
Configuration withoutExtra = MakeApp(staged, alone.get());
if (BuildOkWithArchiveInPlace(withoutExtra, archive, "the build with lib/extra.cpp taken out")) {
CheckPrints(withoutExtra, "1", "built with lib/extra.cpp taken out");
CheckMembers(*alone, "first_impl.o\n", "the archive with lib/extra.cpp taken out");
}
const std::unique_ptr<Configuration> renamed = MakeLib(staged, { "second" });
Check(ExpectedOutput(*renamed) == archive, "and when another source is in the first's place");
Configuration afterRename = MakeApp(staged, renamed.get());
if (BuildOkWithArchiveInPlace(afterRename, archive, "the build with lib/second.cpp in the place of lib/first.cpp")) {
CheckPrints(afterRename, "2", "built with lib/second.cpp in the place of lib/first.cpp");
CheckMembers(*renamed, "second_impl.o\n", "the archive with lib/second.cpp in the place of lib/first.cpp");
}
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -57,7 +57,7 @@ int main() {
BuildResult built = BuildOnce(cfg);
Check(built.result.empty(), std::format("the project builds: {}", built.result));
const fs::path object = cfg.BuildDir() / "main_impl.o";
const fs::path object = ObjectPath(cfg, project / "main.cpp");
const fs::path stdPcm = StdPcmDir(cfg) / "std.pcm";
Check(fs::exists(object) && fs::exists(stdPcm), std::format("{} and {} exist", object.string(), stdPcm.string()));
if (!fs::exists(object) || !fs::exists(stdPcm)) return 1;

View file

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

View file

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

View file

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

View file

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

View file

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