compiler: allow emitting tests to an object file

This is fairly straightforward; the actual compiler changes are limited
to the CLI, since `Compilation` already supports this combination.

A new `std.Build` API is introduced to allow representing this. By
passing the `emit_object` option to `std.Build.addTest`, you get a
`Step.Compile` which emits an object file; you can then use that as you
would any other object, such as either installing it for external use,
or linking it into another step.

A standalone test is added to cover the build system API. It builds a
test into an object, and links it into a final executable, which it then
runs.

Using this build system mechanism prevents the build system from
noticing that you're running a `zig test`, so the build runner and test
runner do not communicate over stdio. However, that's okay, because the
real-world use cases for this feature don't want to do that anyway!

Resolves: #23374
This commit is contained in:
mlugg
2025-04-20 17:54:11 +01:00
committed by Matthew Lugg
parent 6a7ca4b8b0
commit 927f233ff8
8 changed files with 118 additions and 42 deletions

View File

@@ -1019,6 +1019,10 @@ pub const TestOptions = struct {
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Emits an object file instead of a test binary.
/// The object must be linked separately.
/// Usually used in conjunction with a custom `test_runner`.
emit_object: bool = false,
/// Prefer populating this field (using e.g. `createModule`) instead of populating
/// the following fields (`root_source_file` etc). In a future release, those fields
@@ -1067,7 +1071,7 @@ pub fn addTest(b: *Build, options: TestOptions) *Step.Compile {
}
return .create(b, .{
.name = options.name,
.kind = .@"test",
.kind = if (options.emit_object) .test_obj else .@"test",
.root_module = options.root_module orelse b.createModule(.{
.root_source_file = options.root_source_file orelse @panic("`root_module` and `root_source_file` cannot both be null"),
.target = options.target orelse b.graph.host,