authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-05-08 19:36:11-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-05-08 19:36:11-07:00
log6bc0cef607e2007234d04f369dac7e5e382b0aad
tree422000c3e569f16e60bd9ade44bac0e1f8aabda1
parent5c9eb408167672f1389c6fe58bb7851be80204de
parentdee9f82f69db0d034251b844e0bc4083a1b25fdd
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #19826 from jacobly0/outdirarg

Run: add output directory arguments

63 files changed, 1611 insertions(+), 1430 deletions(-)

doc/langref/Assembly Syntax Explained.zig +36-36
......@@ -15,44 +15,44 @@ pub fn syscall1(number: usize, arg1: usize) usize {
1515 // the below code, this is not used. A literal `%` can be
1616 // obtained by escaping it with a double percent: `%%`.
1717 // Often multiline string syntax comes in handy here.
18 \\syscall
19 // Next is the output. It is possible in the future Zig will
20 // support multiple outputs, depending on how
21 // https://github.com/ziglang/zig/issues/215 is resolved.
22 // It is allowed for there to be no outputs, in which case
23 // this colon would be directly followed by the colon for the inputs.
18 \\syscall
19 // Next is the output. It is possible in the future Zig will
20 // support multiple outputs, depending on how
21 // https://github.com/ziglang/zig/issues/215 is resolved.
22 // It is allowed for there to be no outputs, in which case
23 // this colon would be directly followed by the colon for the inputs.
2424 :
25 // This specifies the name to be used in `%[ret]` syntax in
26 // the above assembly string. This example does not use it,
27 // but the syntax is mandatory.
28 [ret]
29 // Next is the output constraint string. This feature is still
30 // considered unstable in Zig, and so LLVM/GCC documentation
31 // must be used to understand the semantics.
32 // http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string
33 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
34 // In this example, the constraint string means "the result value of
35 // this inline assembly instruction is whatever is in $rax".
36 "={rax}"
37 // Next is either a value binding, or `->` and then a type. The
38 // type is the result type of the inline assembly expression.
39 // If it is a value binding, then `%[ret]` syntax would be used
40 // to refer to the register bound to the value.
41 (-> usize),
42 // Next is the list of inputs.
43 // The constraint for these inputs means, "when the assembly code is
44 // executed, $rax shall have the value of `number` and $rdi shall have
45 // the value of `arg1`". Any number of input parameters is allowed,
46 // including none.
25 // This specifies the name to be used in `%[ret]` syntax in
26 // the above assembly string. This example does not use it,
27 // but the syntax is mandatory.
28 [ret]
29 // Next is the output constraint string. This feature is still
30 // considered unstable in Zig, and so LLVM/GCC documentation
31 // must be used to understand the semantics.
32 // http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string
33 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
34 // In this example, the constraint string means "the result value of
35 // this inline assembly instruction is whatever is in $rax".
36 "={rax}"
37 // Next is either a value binding, or `->` and then a type. The
38 // type is the result type of the inline assembly expression.
39 // If it is a value binding, then `%[ret]` syntax would be used
40 // to refer to the register bound to the value.
41 (-> usize),
42 // Next is the list of inputs.
43 // The constraint for these inputs means, "when the assembly code is
44 // executed, $rax shall have the value of `number` and $rdi shall have
45 // the value of `arg1`". Any number of input parameters is allowed,
46 // including none.
4747 : [number] "{rax}" (number),
48 [arg1] "{rdi}" (arg1),
49 // Next is the list of clobbers. These declare a set of registers whose
50 // values will not be preserved by the execution of this assembly code.
51 // These do not include output or input registers. The special clobber
52 // value of "memory" means that the assembly writes to arbitrary undeclared
53 // memory locations - not only the memory pointed to by a declared indirect
54 // output. In this example we list $rcx and $r11 because it is known the
55 // kernel syscall does not preserve these registers.
48 [arg1] "{rdi}" (arg1),
49 // Next is the list of clobbers. These declare a set of registers whose
50 // values will not be preserved by the execution of this assembly code.
51 // These do not include output or input registers. The special clobber
52 // value of "memory" means that the assembly writes to arbitrary undeclared
53 // memory locations - not only the memory pointed to by a declared indirect
54 // output. In this example we list $rcx and $r11 because it is known the
55 // kernel syscall does not preserve these registers.
5656 : "rcx", "r11"
5757 );
5858}
doc/langref/build.zig+1-1
......@@ -4,7 +4,7 @@ pub fn build(b: *std.Build) void {
44 const optimize = b.standardOptimizeOption(.{});
55 const exe = b.addExecutable(.{
66 .name = "example",
7 .root_source_file = .{ .path = "example.zig" },
7 .root_source_file = b.path("example.zig"),
88 .optimize = optimize,
99 });
1010 b.default_step.dependOn(&exe.step);
doc/langref/build_c.zig+2-2
......@@ -3,13 +3,13 @@ const std = @import("std");
33pub fn build(b: *std.Build) void {
44 const lib = b.addSharedLibrary(.{
55 .name = "mathtest",
6 .root_source_file = .{ .path = "mathtest.zig" },
6 .root_source_file = b.path("mathtest.zig"),
77 .version = .{ .major = 1, .minor = 0, .patch = 0 },
88 });
99 const exe = b.addExecutable(.{
1010 .name = "test",
1111 });
12 exe.addCSourceFile(.{ .file = .{ .path = "test.c" }, .flags = &.{"-std=c99"} });
12 exe.addCSourceFile(.{ .file = b.path("test.c"), .flags = &.{"-std=c99"} });
1313 exe.linkLibrary(lib);
1414 exe.linkSystemLibrary("c");
1515
doc/langref/build_object.zig+2-2
......@@ -3,13 +3,13 @@ const std = @import("std");
33pub fn build(b: *std.Build) void {
44 const obj = b.addObject(.{
55 .name = "base64",
6 .root_source_file = .{ .path = "base64.zig" },
6 .root_source_file = b.path("base64.zig"),
77 });
88
99 const exe = b.addExecutable(.{
1010 .name = "test",
1111 });
12 exe.addCSourceFile(.{ .file = .{ .path = "test.c" }, .flags = &.{"-std=c99",} });
12 exe.addCSourceFile(.{ .file = b.path("test.c"), .flags = &.{"-std=c99"} });
1313 exe.addObject(obj);
1414 exe.linkSystemLibrary("c");
1515 b.installArtifact(exe);
doc/langref/checking_null_in_zig.zig+5-3
......@@ -1,11 +1,13 @@
1const Foo = struct{};
2fn doSomethingWithFoo(foo: *Foo) void { _ = foo; }
1const Foo = struct {};
2fn doSomethingWithFoo(foo: *Foo) void {
3 _ = foo;
4}
35
46fn doAThing(optional_foo: ?*Foo) void {
57 // do some stuff
68
79 if (optional_foo) |foo| {
8 doSomethingWithFoo(foo);
10 doSomethingWithFoo(foo);
911 }
1012
1113 // do some stuff
doc/langref/doc_comments.zig+1-1
......@@ -2,7 +2,7 @@
22/// multiline doc comment).
33const Timestamp = struct {
44 /// The number of seconds since the epoch (this is also a doc comment).
5 seconds: i64, // signed so we can represent pre-1970 (not a doc comment)
5 seconds: i64, // signed so we can represent pre-1970 (not a doc comment)
66 /// The number of nanoseconds past the second (doc comment again).
77 nanos: u32,
88
doc/langref/enum_export.zig+3-1
......@@ -1,4 +1,6 @@
11const Foo = enum(c_int) { a, b, c };
2export fn entry(foo: Foo) void { _ = foo; }
2export fn entry(foo: Foo) void {
3 _ = foo;
4}
35
46// obj
doc/langref/enum_export_error.zig+3-1
......@@ -1,4 +1,6 @@
11const Foo = enum { a, b, c };
2export fn entry(foo: Foo) void { _ = foo; }
2export fn entry(foo: Foo) void {
3 _ = foo;
4}
35
46// obj=parameter of type 'enum_export_error.Foo' not allowed in function with calling convention 'C'
doc/langref/error_union_parsing_u64.zig+3-3
......@@ -26,9 +26,9 @@ pub fn parseU64(buf: []const u8, radix: u8) !u64 {
2626
2727fn charToDigit(c: u8) u8 {
2828 return switch (c) {
29 '0' ... '9' => c - '0',
30 'A' ... 'Z' => c - 'A' + 10,
31 'a' ... 'z' => c - 'a' + 10,
29 '0'...'9' => c - '0',
30 'A'...'Z' => c - 'A' + 10,
31 'a'...'z' => c - 'a' + 10,
3232 else => maxInt(u8),
3333 };
3434}
doc/langref/identifiers.zig+2-2
......@@ -6,8 +6,8 @@ pub extern "c" fn @"error"() void;
66pub extern "c" fn @"fstat$INODE64"(fd: c.fd_t, buf: *c.Stat) c_int;
77
88const Color = enum {
9 red,
10 @"really red",
9 red,
10 @"really red",
1111};
1212const color: Color = .@"really red";
1313
doc/langref/print.zig+1-1
......@@ -4,7 +4,7 @@ const a_number: i32 = 1234;
44const a_string = "foobar";
55
66pub fn main() void {
7 print("here is a string: '{s}' here is a number: {}\n", .{a_string, a_number});
7 print("here is a string: '{s}' here is a number: {}\n", .{ a_string, a_number });
88}
99
1010// exe=succeed
doc/langref/print_comptime-known_format.zig+1-1
......@@ -5,7 +5,7 @@ const a_string = "foobar";
55const fmt = "here is a string: '{s}' here is a number: {}\n";
66
77pub fn main() void {
8 print(fmt, .{a_string, a_number});
8 print(fmt, .{ a_string, a_number });
99}
1010
1111// exe=succeed
doc/langref/single_value_error_set.zig+1-1
......@@ -1,3 +1,3 @@
1const err = (error {FileNotFound}).FileNotFound;
1const err = (error{FileNotFound}).FileNotFound;
22
33// syntax
doc/langref/string_literals.zig+10-10
......@@ -3,19 +3,19 @@ const mem = @import("std").mem; // will be used to compare bytes
33
44pub fn main() void {
55 const bytes = "hello";
6 print("{}\n", .{@TypeOf(bytes)}); // *const [5:0]u8
7 print("{d}\n", .{bytes.len}); // 5
8 print("{c}\n", .{bytes[1]}); // 'e'
9 print("{d}\n", .{bytes[5]}); // 0
10 print("{}\n", .{'e' == '\x65'}); // true
11 print("{d}\n", .{'\u{1f4a9}'}); // 128169
12 print("{d}\n", .{'💯'}); // 128175
6 print("{}\n", .{@TypeOf(bytes)}); // *const [5:0]u8
7 print("{d}\n", .{bytes.len}); // 5
8 print("{c}\n", .{bytes[1]}); // 'e'
9 print("{d}\n", .{bytes[5]}); // 0
10 print("{}\n", .{'e' == '\x65'}); // true
11 print("{d}\n", .{'\u{1f4a9}'}); // 128169
12 print("{d}\n", .{'💯'}); // 128175
1313 print("{u}\n", .{'âš¡'});
14 print("{}\n", .{mem.eql(u8, "hello", "h\x65llo")}); // true
14 print("{}\n", .{mem.eql(u8, "hello", "h\x65llo")}); // true
1515 print("{}\n", .{mem.eql(u8, "💯", "\xf0\x9f\x92\xaf")}); // also true
16 const invalid_utf8 = "\xff\xfe"; // non-UTF-8 strings are possible with \xNN notation.
16 const invalid_utf8 = "\xff\xfe"; // non-UTF-8 strings are possible with \xNN notation.
1717 print("0x{x}\n", .{invalid_utf8[1]}); // indexing them returns individual bytes...
18 print("0x{x}\n", .{"💯"[1]}); // ...as does indexing part-way through non-ASCII characters
18 print("0x{x}\n", .{"💯"[1]}); // ...as does indexing part-way through non-ASCII characters
1919}
2020
2121// exe=succeed
doc/langref/test_call_builtin.zig+1-1
......@@ -1,7 +1,7 @@
11const expect = @import("std").testing.expect;
22
33test "noinline function call" {
4 try expect(@call(.auto, add, .{3, 9}) == 12);
4 try expect(@call(.auto, add, .{ 3, 9 }) == 12);
55}
66
77fn add(a: i32, b: i32) i32 {
doc/langref/test_coerce_error_subset_to_superset.zig+2-2
......@@ -1,12 +1,12 @@
11const std = @import("std");
22
3const FileOpenError = error {
3const FileOpenError = error{
44 AccessDenied,
55 OutOfMemory,
66 FileNotFound,
77};
88
9const AllocationError = error {
9const AllocationError = error{
1010 OutOfMemory,
1111};
1212
doc/langref/test_coerce_error_superset_to_subset.zig+2-2
......@@ -1,10 +1,10 @@
1const FileOpenError = error {
1const FileOpenError = error{
22 AccessDenied,
33 OutOfMemory,
44 FileNotFound,
55};
66
7const AllocationError = error {
7const AllocationError = error{
88 OutOfMemory,
99};
1010
doc/langref/test_coerce_tuples_arrays.zig+4-4
......@@ -1,11 +1,11 @@
11const std = @import("std");
22const expect = std.testing.expect;
33
4const Tuple = struct{ u8, u8 };
4const Tuple = struct { u8, u8 };
55test "coercion from homogenous tuple to array" {
6 const tuple: Tuple = .{5, 6};
7 const array: [2]u8 = tuple;
8 _ = array;
6 const tuple: Tuple = .{ 5, 6 };
7 const array: [2]u8 = tuple;
8 _ = array;
99}
1010
1111// test
doc/langref/test_comptime_evaluation.zig+13-7
......@@ -2,17 +2,23 @@ const expect = @import("std").testing.expect;
22
33const CmdFn = struct {
44 name: []const u8,
5 func: fn(i32) i32,
5 func: fn (i32) i32,
66};
77
88const cmd_fns = [_]CmdFn{
9 CmdFn {.name = "one", .func = one},
10 CmdFn {.name = "two", .func = two},
11 CmdFn {.name = "three", .func = three},
9 CmdFn{ .name = "one", .func = one },
10 CmdFn{ .name = "two", .func = two },
11 CmdFn{ .name = "three", .func = three },
1212};
13fn one(value: i32) i32 { return value + 1; }
14fn two(value: i32) i32 { return value + 2; }
15fn three(value: i32) i32 { return value + 3; }
13fn one(value: i32) i32 {
14 return value + 1;
15}
16fn two(value: i32) i32 {
17 return value + 2;
18}
19fn three(value: i32) i32 {
20 return value + 3;
21}
1622
1723fn performFn(comptime prefix_char: u8, start_value: i32) i32 {
1824 var result: i32 = start_value;
doc/langref/test_errdefer_loop.zig+1-3
......@@ -1,9 +1,7 @@
11const std = @import("std");
22const Allocator = std.mem.Allocator;
33
4const Foo = struct {
5 data: *u32
6};
4const Foo = struct { data: *u32 };
75
86fn getData() !u32 {
97 return 666;
doc/langref/test_errdefer_loop_leak.zig+2-4
......@@ -1,9 +1,7 @@
11const std = @import("std");
22const Allocator = std.mem.Allocator;
33
4const Foo = struct {
5 data: *u32
6};
4const Foo = struct { data: *u32 };
75
86fn getData() !u32 {
97 return 666;
......@@ -19,7 +17,7 @@ fn genFoos(allocator: Allocator, num: usize) ![]Foo {
1917 errdefer allocator.destroy(foo.data);
2018
2119 // The data for the first 3 foos will be leaked
22 if(i >= 3) return error.TooManyFoos;
20 if (i >= 3) return error.TooManyFoos;
2321
2422 foo.data.* = try getData();
2523 }
doc/langref/test_for.zig+2-2
......@@ -1,7 +1,7 @@
11const expect = @import("std").testing.expect;
22
33test "for basics" {
4 const items = [_]i32 { 4, 5, 3, 4, 0 };
4 const items = [_]i32{ 4, 5, 3, 4, 0 };
55 var sum: i32 = 0;
66
77 // For loops iterate over slices and arrays.
......@@ -31,7 +31,7 @@ test "for basics" {
3131
3232 // To iterate over consecutive integers, use the range syntax.
3333 // Unbounded range is always a compile error.
34 var sum3 : usize = 0;
34 var sum3: usize = 0;
3535 for (0..5) |i| {
3636 sum3 += i;
3737 }
doc/langref/test_functions.zig+7-3
......@@ -14,7 +14,9 @@ fn add(a: i8, b: i8) i8 {
1414
1515// The export specifier makes a function externally visible in the generated
1616// object file, and makes it use the C ABI.
17export fn sub(a: i8, b: i8) i8 { return a - b; }
17export fn sub(a: i8, b: i8) i8 {
18 return a - b;
19}
1820
1921// The extern specifier is used to declare a function that will be resolved
2022// at link time, when linking statically, or at runtime, when linking
......@@ -39,13 +41,15 @@ fn _start() callconv(.Naked) noreturn {
3941
4042// The inline calling convention forces a function to be inlined at all call sites.
4143// If the function cannot be inlined, it is a compile-time error.
42fn shiftLeftOne(a: u32) callconv(.Inline) u32 {
44inline fn shiftLeftOne(a: u32) u32 {
4345 return a << 1;
4446}
4547
4648// The pub specifier allows the function to be visible when importing.
4749// Another file can use @import and call sub2
48pub fn sub2(a: i8, b: i8) i8 { return a - b; }
50pub fn sub2(a: i8, b: i8) i8 {
51 return a - b;
52}
4953
5054// Function pointers are prefixed with `*const `.
5155const Call2Op = *const fn (a: i8, b: i8) i8;
doc/langref/test_inferred_error_sets.zig+1-1
......@@ -12,7 +12,7 @@ pub fn add_explicit(comptime T: type, a: T, b: T) Error!T {
1212 return ov[0];
1313}
1414
15const Error = error {
15const Error = error{
1616 Overflow,
1717};
1818
doc/langref/test_inline_for.zig+1-1
......@@ -1,7 +1,7 @@
11const expect = @import("std").testing.expect;
22
33test "inline for loop" {
4 const nums = [_]i32{2, 4, 6};
4 const nums = [_]i32{ 2, 4, 6 };
55 var sum: usize = 0;
66 inline for (nums) |i| {
77 const T = switch (i) {
doc/langref/test_inline_switch_union_tag.zig+1-1
......@@ -15,7 +15,7 @@ fn getNum(u: U) u32 {
1515 return @intFromFloat(num);
1616 }
1717 return num;
18 }
18 },
1919 }
2020}
2121
doc/langref/test_null_terminated_array.zig+2-2
......@@ -2,7 +2,7 @@ const std = @import("std");
22const expect = std.testing.expect;
33
44test "0-terminated sentinel array" {
5 const array = [_:0]u8 {1, 2, 3, 4};
5 const array = [_:0]u8{ 1, 2, 3, 4 };
66
77 try expect(@TypeOf(array) == [4:0]u8);
88 try expect(array.len == 4);
......@@ -11,7 +11,7 @@ test "0-terminated sentinel array" {
1111
1212test "extra 0s in 0-terminated sentinel array" {
1313 // The sentinel value may appear earlier, but does not influence the compile-time 'len'.
14 const array = [_:0]u8 {1, 0, 0, 4};
14 const array = [_:0]u8{ 1, 0, 0, 4 };
1515
1616 try expect(@TypeOf(array) == [4:0]u8);
1717 try expect(array.len == 4);
doc/langref/test_struct_result.zig+1-1
......@@ -1,7 +1,7 @@
11const std = @import("std");
22const expect = std.testing.expect;
33
4const Point = struct {x: i32, y: i32};
4const Point = struct { x: i32, y: i32 };
55
66test "anonymous struct literal" {
77 const pt: Point = .{
doc/langref/test_structs.zig+7-8
......@@ -13,15 +13,14 @@ const Point2 = packed struct {
1313 y: f32,
1414};
1515
16
1716// Declare an instance of a struct.
18const p = Point {
17const p = Point{
1918 .x = 0.12,
2019 .y = 0.34,
2120};
2221
2322// Maybe we're not ready to fill out some of the fields.
24var p2 = Point {
23var p2 = Point{
2524 .x = 0.12,
2625 .y = undefined,
2726};
......@@ -35,7 +34,7 @@ const Vec3 = struct {
3534 z: f32,
3635
3736 pub fn init(x: f32, y: f32, z: f32) Vec3 {
38 return Vec3 {
37 return Vec3{
3938 .x = x,
4039 .y = y,
4140 .z = z,
......@@ -69,7 +68,7 @@ test "struct namespaced variable" {
6968 try expect(@sizeOf(Empty) == 0);
7069
7170 // you can still instantiate an empty struct
72 const does_nothing = Empty {};
71 const does_nothing = Empty{};
7372
7473 _ = does_nothing;
7574}
......@@ -81,7 +80,7 @@ fn setYBasedOnX(x: *f32, y: f32) void {
8180 point.y = y;
8281}
8382test "field parent pointer" {
84 var point = Point {
83 var point = Point{
8584 .x = 0.1234,
8685 .y = 0.5678,
8786 };
......@@ -100,8 +99,8 @@ fn LinkedList(comptime T: type) type {
10099 };
101100
102101 first: ?*Node,
103 last: ?*Node,
104 len: usize,
102 last: ?*Node,
103 len: usize,
105104 };
106105}
107106
doc/langref/test_switch_non-exhaustive.zig+1-2
......@@ -12,8 +12,7 @@ test "switch on non-exhaustive enum" {
1212 const number = Number.one;
1313 const result = switch (number) {
1414 .one => true,
15 .two,
16 .three => false,
15 .two, .three => false,
1716 _ => false,
1817 };
1918 try expect(result);
doc/langref/test_unresolved_comptime_value.zig+1-4
......@@ -5,10 +5,7 @@ test "try to pass a runtime type" {
55 foo(false);
66}
77fn foo(condition: bool) void {
8 const result = max(
9 if (condition) f32 else u64,
10 1234,
11 5678);
8 const result = max(if (condition) f32 else u64, 1234, 5678);
129 _ = result;
1310}
1411
doc/langref/test_while_continue_expression.zig+4-1
......@@ -9,7 +9,10 @@ test "while loop continue expression" {
99test "while loop continue expression, more complicated" {
1010 var i: usize = 1;
1111 var j: usize = 1;
12 while (i * j < 2000) : ({ i *= 2; j *= 3; }) {
12 while (i * j < 2000) : ({
13 i *= 2;
14 j *= 3;
15 }) {
1316 const my_ij = i * j;
1417 try expect(my_ij < 2000);
1518 }
doc/langref/values.zig+3-1
......@@ -39,7 +39,9 @@ pub fn main() void {
3939 var number_or_error: anyerror!i32 = error.ArgNotFound;
4040
4141 print("\nerror union 1\ntype: {}\nvalue: {!}\n", .{
42 @TypeOf(number_or_error), number_or_error, });
42 @TypeOf(number_or_error),
43 number_or_error,
44 });
4345
4446 number_or_error = 1234;
4547
lib/std/Build.zig+266-265
......@@ -13,8 +13,7 @@ const Allocator = mem.Allocator;
1313const Target = std.Target;
1414const process = std.process;
1515const EnvMap = std.process.EnvMap;
16const fmt_lib = std.fmt;
17const File = std.fs.File;
16const File = fs.File;
1817const Sha256 = std.crypto.hash.sha2.Sha256;
1918const Build = @This();
2019
......@@ -149,15 +148,14 @@ const InitializedDepKey = struct {
149148const InitializedDepContext = struct {
150149 allocator: Allocator,
151150
152 pub fn hash(self: @This(), k: InitializedDepKey) u64 {
151 pub fn hash(ctx: @This(), k: InitializedDepKey) u64 {
153152 var hasher = std.hash.Wyhash.init(0);
154153 hasher.update(k.build_root_string);
155 hashUserInputOptionsMap(self.allocator, k.user_input_options, &hasher);
154 hashUserInputOptionsMap(ctx.allocator, k.user_input_options, &hasher);
156155 return hasher.final();
157156 }
158157
159 pub fn eql(self: @This(), lhs: InitializedDepKey, rhs: InitializedDepKey) bool {
160 _ = self;
158 pub fn eql(_: @This(), lhs: InitializedDepKey, rhs: InitializedDepKey) bool {
161159 if (!std.mem.eql(u8, lhs.build_root_string, rhs.build_root_string))
162160 return false;
163161
......@@ -229,7 +227,7 @@ const TypeId = enum {
229227};
230228
231229const TopLevelStep = struct {
232 pub const base_id = .top_level;
230 pub const base_id: Step.Id = .top_level;
233231
234232 step: Step,
235233 description: []const u8,
......@@ -251,8 +249,8 @@ pub fn create(
251249 const initialized_deps = try arena.create(InitializedDepMap);
252250 initialized_deps.* = InitializedDepMap.initContext(arena, .{ .allocator = arena });
253251
254 const self = try arena.create(Build);
255 self.* = .{
252 const b = try arena.create(Build);
253 b.* = .{
256254 .graph = graph,
257255 .build_root = build_root,
258256 .cache_root = cache_root,
......@@ -280,17 +278,17 @@ pub fn create(
280278 .installed_files = ArrayList(InstalledFile).init(arena),
281279 .install_tls = .{
282280 .step = Step.init(.{
283 .id = .top_level,
281 .id = TopLevelStep.base_id,
284282 .name = "install",
285 .owner = self,
283 .owner = b,
286284 }),
287285 .description = "Copy build artifacts to prefix path",
288286 },
289287 .uninstall_tls = .{
290288 .step = Step.init(.{
291 .id = .top_level,
289 .id = TopLevelStep.base_id,
292290 .name = "uninstall",
293 .owner = self,
291 .owner = b,
294292 .makeFn = makeUninstall,
295293 }),
296294 .description = "Remove build artifacts from prefix path",
......@@ -306,10 +304,10 @@ pub fn create(
306304 .available_deps = available_deps,
307305 .release_mode = .off,
308306 };
309 try self.top_level_steps.put(arena, self.install_tls.step.name, &self.install_tls);
310 try self.top_level_steps.put(arena, self.uninstall_tls.step.name, &self.uninstall_tls);
311 self.default_step = &self.install_tls.step;
312 return self;
307 try b.top_level_steps.put(arena, b.install_tls.step.name, &b.install_tls);
308 try b.top_level_steps.put(arena, b.uninstall_tls.step.name, &b.uninstall_tls);
309 b.default_step = &b.install_tls.step;
310 return b;
313311}
314312
315313fn createChild(
......@@ -340,7 +338,7 @@ fn createChildOnly(
340338 .allocator = allocator,
341339 .install_tls = .{
342340 .step = Step.init(.{
343 .id = .top_level,
341 .id = TopLevelStep.base_id,
344342 .name = "install",
345343 .owner = child,
346344 }),
......@@ -348,7 +346,7 @@ fn createChildOnly(
348346 },
349347 .uninstall_tls = .{
350348 .step = Step.init(.{
351 .id = .top_level,
349 .id = TopLevelStep.base_id,
352350 .name = "uninstall",
353351 .owner = child,
354352 .makeFn = makeUninstall,
......@@ -498,8 +496,8 @@ const OrderedUserValue = union(enum) {
498496 }
499497 };
500498
501 fn hash(self: OrderedUserValue, hasher: *std.hash.Wyhash) void {
502 switch (self) {
499 fn hash(val: OrderedUserValue, hasher: *std.hash.Wyhash) void {
500 switch (val) {
503501 .flag => {},
504502 .scalar => |scalar| hasher.update(scalar),
505503 // lists are already ordered
......@@ -541,9 +539,9 @@ const OrderedUserInputOption = struct {
541539 value: OrderedUserValue,
542540 used: bool,
543541
544 fn hash(self: OrderedUserInputOption, hasher: *std.hash.Wyhash) void {
545 hasher.update(self.name);
546 self.value.hash(hasher);
542 fn hash(opt: OrderedUserInputOption, hasher: *std.hash.Wyhash) void {
543 hasher.update(opt.name);
544 opt.value.hash(hasher);
547545 }
548546
549547 fn fromUnordered(allocator: Allocator, user_input_option: UserInputOption) OrderedUserInputOption {
......@@ -593,38 +591,38 @@ fn determineAndApplyInstallPrefix(b: *Build) !void {
593591}
594592
595593/// This function is intended to be called by lib/build_runner.zig, not a build.zig file.
596pub fn resolveInstallPrefix(self: *Build, install_prefix: ?[]const u8, dir_list: DirList) void {
597 if (self.dest_dir) |dest_dir| {
598 self.install_prefix = install_prefix orelse "/usr";
599 self.install_path = self.pathJoin(&.{ dest_dir, self.install_prefix });
594pub fn resolveInstallPrefix(b: *Build, install_prefix: ?[]const u8, dir_list: DirList) void {
595 if (b.dest_dir) |dest_dir| {
596 b.install_prefix = install_prefix orelse "/usr";
597 b.install_path = b.pathJoin(&.{ dest_dir, b.install_prefix });
600598 } else {
601 self.install_prefix = install_prefix orelse
602 (self.build_root.join(self.allocator, &.{"zig-out"}) catch @panic("unhandled error"));
603 self.install_path = self.install_prefix;
599 b.install_prefix = install_prefix orelse
600 (b.build_root.join(b.allocator, &.{"zig-out"}) catch @panic("unhandled error"));
601 b.install_path = b.install_prefix;
604602 }
605603
606 var lib_list = [_][]const u8{ self.install_path, "lib" };
607 var exe_list = [_][]const u8{ self.install_path, "bin" };
608 var h_list = [_][]const u8{ self.install_path, "include" };
604 var lib_list = [_][]const u8{ b.install_path, "lib" };
605 var exe_list = [_][]const u8{ b.install_path, "bin" };
606 var h_list = [_][]const u8{ b.install_path, "include" };
609607
610608 if (dir_list.lib_dir) |dir| {
611 if (fs.path.isAbsolute(dir)) lib_list[0] = self.dest_dir orelse "";
609 if (fs.path.isAbsolute(dir)) lib_list[0] = b.dest_dir orelse "";
612610 lib_list[1] = dir;
613611 }
614612
615613 if (dir_list.exe_dir) |dir| {
616 if (fs.path.isAbsolute(dir)) exe_list[0] = self.dest_dir orelse "";
614 if (fs.path.isAbsolute(dir)) exe_list[0] = b.dest_dir orelse "";
617615 exe_list[1] = dir;
618616 }
619617
620618 if (dir_list.include_dir) |dir| {
621 if (fs.path.isAbsolute(dir)) h_list[0] = self.dest_dir orelse "";
619 if (fs.path.isAbsolute(dir)) h_list[0] = b.dest_dir orelse "";
622620 h_list[1] = dir;
623621 }
624622
625 self.lib_dir = self.pathJoin(&lib_list);
626 self.exe_dir = self.pathJoin(&exe_list);
627 self.h_dir = self.pathJoin(&h_list);
623 b.lib_dir = b.pathJoin(&lib_list);
624 b.exe_dir = b.pathJoin(&exe_list);
625 b.h_dir = b.pathJoin(&h_list);
628626}
629627
630628/// Create a set of key-value pairs that can be converted into a Zig source
......@@ -632,8 +630,8 @@ pub fn resolveInstallPrefix(self: *Build, install_prefix: ?[]const u8, dir_list:
632630/// In other words, this provides a way to expose build.zig values to Zig
633631/// source code with `@import`.
634632/// Related: `Module.addOptions`.
635pub fn addOptions(self: *Build) *Step.Options {
636 return Step.Options.create(self);
633pub fn addOptions(b: *Build) *Step.Options {
634 return Step.Options.create(b);
637635}
638636
639637pub const ExecutableOptions = struct {
......@@ -959,9 +957,9 @@ pub fn createModule(b: *Build, options: Module.CreateOptions) *Module {
959957/// `addArgs`, and `addArtifactArg`.
960958/// Be careful using this function, as it introduces a system dependency.
961959/// To run an executable built with zig build, see `Step.Compile.run`.
962pub fn addSystemCommand(self: *Build, argv: []const []const u8) *Step.Run {
960pub fn addSystemCommand(b: *Build, argv: []const []const u8) *Step.Run {
963961 assert(argv.len >= 1);
964 const run_step = Step.Run.create(self, self.fmt("run {s}", .{argv[0]}));
962 const run_step = Step.Run.create(b, b.fmt("run {s}", .{argv[0]}));
965963 run_step.addArgs(argv);
966964 return run_step;
967965}
......@@ -1002,20 +1000,20 @@ pub fn addConfigHeader(
10021000}
10031001
10041002/// Allocator.dupe without the need to handle out of memory.
1005pub fn dupe(self: *Build, bytes: []const u8) []u8 {
1006 return self.allocator.dupe(u8, bytes) catch @panic("OOM");
1003pub fn dupe(b: *Build, bytes: []const u8) []u8 {
1004 return b.allocator.dupe(u8, bytes) catch @panic("OOM");
10071005}
10081006
10091007/// Duplicates an array of strings without the need to handle out of memory.
1010pub fn dupeStrings(self: *Build, strings: []const []const u8) [][]u8 {
1011 const array = self.allocator.alloc([]u8, strings.len) catch @panic("OOM");
1012 for (array, strings) |*dest, source| dest.* = self.dupe(source);
1008pub fn dupeStrings(b: *Build, strings: []const []const u8) [][]u8 {
1009 const array = b.allocator.alloc([]u8, strings.len) catch @panic("OOM");
1010 for (array, strings) |*dest, source| dest.* = b.dupe(source);
10131011 return array;
10141012}
10151013
10161014/// Duplicates a path and converts all slashes to the OS's canonical path separator.
1017pub fn dupePath(self: *Build, bytes: []const u8) []u8 {
1018 const the_copy = self.dupe(bytes);
1015pub fn dupePath(b: *Build, bytes: []const u8) []u8 {
1016 const the_copy = b.dupe(bytes);
10191017 for (the_copy) |*byte| {
10201018 switch (byte.*) {
10211019 '/', '\\' => byte.* = fs.path.sep,
......@@ -1025,8 +1023,8 @@ pub fn dupePath(self: *Build, bytes: []const u8) []u8 {
10251023 return the_copy;
10261024}
10271025
1028pub fn addWriteFile(self: *Build, file_path: []const u8, data: []const u8) *Step.WriteFile {
1029 const write_file_step = self.addWriteFiles();
1026pub fn addWriteFile(b: *Build, file_path: []const u8, data: []const u8) *Step.WriteFile {
1027 const write_file_step = b.addWriteFiles();
10301028 _ = write_file_step.add(file_path, data);
10311029 return write_file_step;
10321030}
......@@ -1041,34 +1039,34 @@ pub fn addWriteFiles(b: *Build) *Step.WriteFile {
10411039 return Step.WriteFile.create(b);
10421040}
10431041
1044pub fn addRemoveDirTree(self: *Build, dir_path: []const u8) *Step.RemoveDir {
1045 return Step.RemoveDir.create(self, dir_path);
1042pub fn addRemoveDirTree(b: *Build, dir_path: []const u8) *Step.RemoveDir {
1043 return Step.RemoveDir.create(b, dir_path);
10461044}
10471045
10481046pub fn addFmt(b: *Build, options: Step.Fmt.Options) *Step.Fmt {
10491047 return Step.Fmt.create(b, options);
10501048}
10511049
1052pub fn addTranslateC(self: *Build, options: Step.TranslateC.Options) *Step.TranslateC {
1053 return Step.TranslateC.create(self, options);
1050pub fn addTranslateC(b: *Build, options: Step.TranslateC.Options) *Step.TranslateC {
1051 return Step.TranslateC.create(b, options);
10541052}
10551053
1056pub fn getInstallStep(self: *Build) *Step {
1057 return &self.install_tls.step;
1054pub fn getInstallStep(b: *Build) *Step {
1055 return &b.install_tls.step;
10581056}
10591057
1060pub fn getUninstallStep(self: *Build) *Step {
1061 return &self.uninstall_tls.step;
1058pub fn getUninstallStep(b: *Build) *Step {
1059 return &b.uninstall_tls.step;
10621060}
10631061
10641062fn makeUninstall(uninstall_step: *Step, prog_node: *std.Progress.Node) anyerror!void {
10651063 _ = prog_node;
10661064 const uninstall_tls: *TopLevelStep = @fieldParentPtr("step", uninstall_step);
1067 const self: *Build = @fieldParentPtr("uninstall_tls", uninstall_tls);
1065 const b: *Build = @fieldParentPtr("uninstall_tls", uninstall_tls);
10681066
1069 for (self.installed_files.items) |installed_file| {
1070 const full_path = self.getInstallPath(installed_file.dir, installed_file.path);
1071 if (self.verbose) {
1067 for (b.installed_files.items) |installed_file| {
1068 const full_path = b.getInstallPath(installed_file.dir, installed_file.path);
1069 if (b.verbose) {
10721070 log.info("rm {s}", .{full_path});
10731071 }
10741072 fs.cwd().deleteTree(full_path) catch {};
......@@ -1082,13 +1080,13 @@ fn makeUninstall(uninstall_step: *Step, prog_node: *std.Progress.Node) anyerror!
10821080/// When a project depends on a Zig package as a dependency, it programmatically sets
10831081/// these options when calling the dependency's build.zig script as a function.
10841082/// `null` is returned when an option is left to default.
1085pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_raw: []const u8) ?T {
1086 const name = self.dupe(name_raw);
1087 const description = self.dupe(description_raw);
1083pub fn option(b: *Build, comptime T: type, name_raw: []const u8, description_raw: []const u8) ?T {
1084 const name = b.dupe(name_raw);
1085 const description = b.dupe(description_raw);
10881086 const type_id = comptime typeToEnum(T);
10891087 const enum_options = if (type_id == .@"enum") blk: {
10901088 const fields = comptime std.meta.fields(T);
1091 var options = ArrayList([]const u8).initCapacity(self.allocator, fields.len) catch @panic("OOM");
1089 var options = ArrayList([]const u8).initCapacity(b.allocator, fields.len) catch @panic("OOM");
10921090
10931091 inline for (fields) |field| {
10941092 options.appendAssumeCapacity(field.name);
......@@ -1102,12 +1100,12 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11021100 .description = description,
11031101 .enum_options = enum_options,
11041102 };
1105 if ((self.available_options_map.fetchPut(name, available_option) catch @panic("OOM")) != null) {
1103 if ((b.available_options_map.fetchPut(name, available_option) catch @panic("OOM")) != null) {
11061104 panic("Option '{s}' declared twice", .{name});
11071105 }
1108 self.available_options_list.append(available_option) catch @panic("OOM");
1106 b.available_options_list.append(available_option) catch @panic("OOM");
11091107
1110 const option_ptr = self.user_input_options.getPtr(name) orelse return null;
1108 const option_ptr = b.user_input_options.getPtr(name) orelse return null;
11111109 option_ptr.used = true;
11121110 switch (type_id) {
11131111 .bool => switch (option_ptr.value) {
......@@ -1119,7 +1117,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11191117 return false;
11201118 } else {
11211119 log.err("Expected -D{s} to be a boolean, but received '{s}'", .{ name, s });
1122 self.markInvalidUserInput();
1120 b.markInvalidUserInput();
11231121 return null;
11241122 }
11251123 },
......@@ -1127,7 +1125,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11271125 log.err("Expected -D{s} to be a boolean, but received a {s}.", .{
11281126 name, @tagName(option_ptr.value),
11291127 });
1130 self.markInvalidUserInput();
1128 b.markInvalidUserInput();
11311129 return null;
11321130 },
11331131 },
......@@ -1136,19 +1134,19 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11361134 log.err("Expected -D{s} to be an integer, but received a {s}.", .{
11371135 name, @tagName(option_ptr.value),
11381136 });
1139 self.markInvalidUserInput();
1137 b.markInvalidUserInput();
11401138 return null;
11411139 },
11421140 .scalar => |s| {
11431141 const n = std.fmt.parseInt(T, s, 10) catch |err| switch (err) {
11441142 error.Overflow => {
11451143 log.err("-D{s} value {s} cannot fit into type {s}.", .{ name, s, @typeName(T) });
1146 self.markInvalidUserInput();
1144 b.markInvalidUserInput();
11471145 return null;
11481146 },
11491147 else => {
11501148 log.err("Expected -D{s} to be an integer of type {s}.", .{ name, @typeName(T) });
1151 self.markInvalidUserInput();
1149 b.markInvalidUserInput();
11521150 return null;
11531151 },
11541152 };
......@@ -1160,13 +1158,13 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11601158 log.err("Expected -D{s} to be a float, but received a {s}.", .{
11611159 name, @tagName(option_ptr.value),
11621160 });
1163 self.markInvalidUserInput();
1161 b.markInvalidUserInput();
11641162 return null;
11651163 },
11661164 .scalar => |s| {
11671165 const n = std.fmt.parseFloat(T, s) catch {
11681166 log.err("Expected -D{s} to be a float of type {s}.", .{ name, @typeName(T) });
1169 self.markInvalidUserInput();
1167 b.markInvalidUserInput();
11701168 return null;
11711169 };
11721170 return n;
......@@ -1177,7 +1175,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11771175 log.err("Expected -D{s} to be an enum, but received a {s}.", .{
11781176 name, @tagName(option_ptr.value),
11791177 });
1180 self.markInvalidUserInput();
1178 b.markInvalidUserInput();
11811179 return null;
11821180 },
11831181 .scalar => |s| {
......@@ -1185,7 +1183,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11851183 return enum_lit;
11861184 } else {
11871185 log.err("Expected -D{s} to be of type {s}.", .{ name, @typeName(T) });
1188 self.markInvalidUserInput();
1186 b.markInvalidUserInput();
11891187 return null;
11901188 }
11911189 },
......@@ -1195,7 +1193,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
11951193 log.err("Expected -D{s} to be a string, but received a {s}.", .{
11961194 name, @tagName(option_ptr.value),
11971195 });
1198 self.markInvalidUserInput();
1196 b.markInvalidUserInput();
11991197 return null;
12001198 },
12011199 .scalar => |s| return s,
......@@ -1205,7 +1203,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
12051203 log.err("Expected -D{s} to be an enum, but received a {s}.", .{
12061204 name, @tagName(option_ptr.value),
12071205 });
1208 self.markInvalidUserInput();
1206 b.markInvalidUserInput();
12091207 return null;
12101208 },
12111209 .scalar => |s| {
......@@ -1213,7 +1211,7 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
12131211 return build_id;
12141212 } else |err| {
12151213 log.err("unable to parse option '-D{s}': {s}", .{ name, @errorName(err) });
1216 self.markInvalidUserInput();
1214 b.markInvalidUserInput();
12171215 return null;
12181216 }
12191217 },
......@@ -1223,28 +1221,28 @@ pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_
12231221 log.err("Expected -D{s} to be a list, but received a {s}.", .{
12241222 name, @tagName(option_ptr.value),
12251223 });
1226 self.markInvalidUserInput();
1224 b.markInvalidUserInput();
12271225 return null;
12281226 },
12291227 .scalar => |s| {
1230 return self.allocator.dupe([]const u8, &[_][]const u8{s}) catch @panic("OOM");
1228 return b.allocator.dupe([]const u8, &[_][]const u8{s}) catch @panic("OOM");
12311229 },
12321230 .list => |lst| return lst.items,
12331231 },
12341232 }
12351233}
12361234
1237pub fn step(self: *Build, name: []const u8, description: []const u8) *Step {
1238 const step_info = self.allocator.create(TopLevelStep) catch @panic("OOM");
1235pub fn step(b: *Build, name: []const u8, description: []const u8) *Step {
1236 const step_info = b.allocator.create(TopLevelStep) catch @panic("OOM");
12391237 step_info.* = .{
12401238 .step = Step.init(.{
1241 .id = .top_level,
1239 .id = TopLevelStep.base_id,
12421240 .name = name,
1243 .owner = self,
1241 .owner = b,
12441242 }),
1245 .description = self.dupe(description),
1243 .description = b.dupe(description),
12461244 };
1247 const gop = self.top_level_steps.getOrPut(self.allocator, name) catch @panic("OOM");
1245 const gop = b.top_level_steps.getOrPut(b.allocator, name) catch @panic("OOM");
12481246 if (gop.found_existing) std.debug.panic("A top-level step with name \"{s}\" already exists", .{name});
12491247
12501248 gop.key_ptr.* = step_info.step.name;
......@@ -1406,10 +1404,10 @@ pub fn standardTargetOptionsQueryOnly(b: *Build, args: StandardTargetOptionsArgs
14061404 return args.default_target;
14071405}
14081406
1409pub fn addUserInputOption(self: *Build, name_raw: []const u8, value_raw: []const u8) !bool {
1410 const name = self.dupe(name_raw);
1411 const value = self.dupe(value_raw);
1412 const gop = try self.user_input_options.getOrPut(name);
1407pub fn addUserInputOption(b: *Build, name_raw: []const u8, value_raw: []const u8) !bool {
1408 const name = b.dupe(name_raw);
1409 const value = b.dupe(value_raw);
1410 const gop = try b.user_input_options.getOrPut(name);
14131411 if (!gop.found_existing) {
14141412 gop.value_ptr.* = UserInputOption{
14151413 .name = name,
......@@ -1423,10 +1421,10 @@ pub fn addUserInputOption(self: *Build, name_raw: []const u8, value_raw: []const
14231421 switch (gop.value_ptr.value) {
14241422 .scalar => |s| {
14251423 // turn it into a list
1426 var list = ArrayList([]const u8).init(self.allocator);
1424 var list = ArrayList([]const u8).init(b.allocator);
14271425 try list.append(s);
14281426 try list.append(value);
1429 try self.user_input_options.put(name, .{
1427 try b.user_input_options.put(name, .{
14301428 .name = name,
14311429 .value = .{ .list = list },
14321430 .used = false,
......@@ -1435,7 +1433,7 @@ pub fn addUserInputOption(self: *Build, name_raw: []const u8, value_raw: []const
14351433 .list => |*list| {
14361434 // append to the list
14371435 try list.append(value);
1438 try self.user_input_options.put(name, .{
1436 try b.user_input_options.put(name, .{
14391437 .name = name,
14401438 .value = .{ .list = list.* },
14411439 .used = false,
......@@ -1454,9 +1452,9 @@ pub fn addUserInputOption(self: *Build, name_raw: []const u8, value_raw: []const
14541452 return false;
14551453}
14561454
1457pub fn addUserInputFlag(self: *Build, name_raw: []const u8) !bool {
1458 const name = self.dupe(name_raw);
1459 const gop = try self.user_input_options.getOrPut(name);
1455pub fn addUserInputFlag(b: *Build, name_raw: []const u8) !bool {
1456 const name = b.dupe(name_raw);
1457 const gop = try b.user_input_options.getOrPut(name);
14601458 if (!gop.found_existing) {
14611459 gop.value_ptr.* = .{
14621460 .name = name,
......@@ -1498,8 +1496,8 @@ fn typeToEnum(comptime T: type) TypeId {
14981496 };
14991497}
15001498
1501fn markInvalidUserInput(self: *Build) void {
1502 self.invalid_user_input = true;
1499fn markInvalidUserInput(b: *Build) void {
1500 b.invalid_user_input = true;
15031501}
15041502
15051503pub fn validateUserInputDidItFail(b: *Build) bool {
......@@ -1532,18 +1530,18 @@ fn printCmd(ally: Allocator, cwd: ?[]const u8, argv: []const []const u8) void {
15321530/// This creates the install step and adds it to the dependencies of the
15331531/// top-level install step, using all the default options.
15341532/// See `addInstallArtifact` for a more flexible function.
1535pub fn installArtifact(self: *Build, artifact: *Step.Compile) void {
1536 self.getInstallStep().dependOn(&self.addInstallArtifact(artifact, .{}).step);
1533pub fn installArtifact(b: *Build, artifact: *Step.Compile) void {
1534 b.getInstallStep().dependOn(&b.addInstallArtifact(artifact, .{}).step);
15371535}
15381536
15391537/// This merely creates the step; it does not add it to the dependencies of the
15401538/// top-level install step.
15411539pub fn addInstallArtifact(
1542 self: *Build,
1540 b: *Build,
15431541 artifact: *Step.Compile,
15441542 options: Step.InstallArtifact.Options,
15451543) *Step.InstallArtifact {
1546 return Step.InstallArtifact.create(self, artifact, options);
1544 return Step.InstallArtifact.create(b, artifact, options);
15471545}
15481546
15491547///`dest_rel_path` is relative to prefix path
......@@ -1590,16 +1588,16 @@ pub fn addInstallHeaderFile(b: *Build, source: LazyPath, dest_rel_path: []const
15901588}
15911589
15921590pub fn addInstallFileWithDir(
1593 self: *Build,
1591 b: *Build,
15941592 source: LazyPath,
15951593 install_dir: InstallDir,
15961594 dest_rel_path: []const u8,
15971595) *Step.InstallFile {
1598 return Step.InstallFile.create(self, source, install_dir, dest_rel_path);
1596 return Step.InstallFile.create(b, source, install_dir, dest_rel_path);
15991597}
16001598
1601pub fn addInstallDirectory(self: *Build, options: Step.InstallDir.Options) *Step.InstallDir {
1602 return Step.InstallDir.create(self, options);
1599pub fn addInstallDirectory(b: *Build, options: Step.InstallDir.Options) *Step.InstallDir {
1600 return Step.InstallDir.create(b, options);
16031601}
16041602
16051603pub fn addCheckFile(
......@@ -1611,16 +1609,16 @@ pub fn addCheckFile(
16111609}
16121610
16131611/// deprecated: https://github.com/ziglang/zig/issues/14943
1614pub fn pushInstalledFile(self: *Build, dir: InstallDir, dest_rel_path: []const u8) void {
1612pub fn pushInstalledFile(b: *Build, dir: InstallDir, dest_rel_path: []const u8) void {
16151613 const file = InstalledFile{
16161614 .dir = dir,
16171615 .path = dest_rel_path,
16181616 };
1619 self.installed_files.append(file.dupe(self)) catch @panic("OOM");
1617 b.installed_files.append(file.dupe(b)) catch @panic("OOM");
16201618}
16211619
1622pub fn truncateFile(self: *Build, dest_path: []const u8) !void {
1623 if (self.verbose) {
1620pub fn truncateFile(b: *Build, dest_path: []const u8) !void {
1621 if (b.verbose) {
16241622 log.info("truncate {s}", .{dest_path});
16251623 }
16261624 const cwd = fs.cwd();
......@@ -1652,50 +1650,54 @@ pub fn path(b: *Build, sub_path: []const u8) LazyPath {
16521650/// This is low-level implementation details of the build system, not meant to
16531651/// be called by users' build scripts. Even in the build system itself it is a
16541652/// code smell to call this function.
1655pub fn pathFromRoot(b: *Build, p: []const u8) []u8 {
1656 return fs.path.resolve(b.allocator, &.{ b.build_root.path orelse ".", p }) catch @panic("OOM");
1653pub fn pathFromRoot(b: *Build, sub_path: []const u8) []u8 {
1654 return b.pathResolve(&.{ b.build_root.path orelse ".", sub_path });
16571655}
16581656
1659fn pathFromCwd(b: *Build, p: []const u8) []u8 {
1657fn pathFromCwd(b: *Build, sub_path: []const u8) []u8 {
16601658 const cwd = process.getCwdAlloc(b.allocator) catch @panic("OOM");
1661 return fs.path.resolve(b.allocator, &.{ cwd, p }) catch @panic("OOM");
1659 return b.pathResolve(&.{ cwd, sub_path });
1660}
1661
1662pub fn pathJoin(b: *Build, paths: []const []const u8) []u8 {
1663 return fs.path.join(b.allocator, paths) catch @panic("OOM");
16621664}
16631665
1664pub fn pathJoin(self: *Build, paths: []const []const u8) []u8 {
1665 return fs.path.join(self.allocator, paths) catch @panic("OOM");
1666pub fn pathResolve(b: *Build, paths: []const []const u8) []u8 {
1667 return fs.path.resolve(b.allocator, paths) catch @panic("OOM");
16661668}
16671669
1668pub fn fmt(self: *Build, comptime format: []const u8, args: anytype) []u8 {
1669 return fmt_lib.allocPrint(self.allocator, format, args) catch @panic("OOM");
1670pub fn fmt(b: *Build, comptime format: []const u8, args: anytype) []u8 {
1671 return std.fmt.allocPrint(b.allocator, format, args) catch @panic("OOM");
16701672}
16711673
1672pub fn findProgram(self: *Build, names: []const []const u8, paths: []const []const u8) ![]const u8 {
1674pub fn findProgram(b: *Build, names: []const []const u8, paths: []const []const u8) ![]const u8 {
16731675 // TODO report error for ambiguous situations
1674 const exe_extension = self.host.result.exeFileExt();
1675 for (self.search_prefixes.items) |search_prefix| {
1676 const exe_extension = b.host.result.exeFileExt();
1677 for (b.search_prefixes.items) |search_prefix| {
16761678 for (names) |name| {
16771679 if (fs.path.isAbsolute(name)) {
16781680 return name;
16791681 }
1680 const full_path = self.pathJoin(&.{
1682 const full_path = b.pathJoin(&.{
16811683 search_prefix,
16821684 "bin",
1683 self.fmt("{s}{s}", .{ name, exe_extension }),
1685 b.fmt("{s}{s}", .{ name, exe_extension }),
16841686 });
1685 return fs.realpathAlloc(self.allocator, full_path) catch continue;
1687 return fs.realpathAlloc(b.allocator, full_path) catch continue;
16861688 }
16871689 }
1688 if (self.graph.env_map.get("PATH")) |PATH| {
1690 if (b.graph.env_map.get("PATH")) |PATH| {
16891691 for (names) |name| {
16901692 if (fs.path.isAbsolute(name)) {
16911693 return name;
16921694 }
16931695 var it = mem.tokenizeScalar(u8, PATH, fs.path.delimiter);
16941696 while (it.next()) |p| {
1695 const full_path = self.pathJoin(&.{
1696 p, self.fmt("{s}{s}", .{ name, exe_extension }),
1697 const full_path = b.pathJoin(&.{
1698 p, b.fmt("{s}{s}", .{ name, exe_extension }),
16971699 });
1698 return fs.realpathAlloc(self.allocator, full_path) catch continue;
1700 return fs.realpathAlloc(b.allocator, full_path) catch continue;
16991701 }
17001702 }
17011703 }
......@@ -1704,17 +1706,17 @@ pub fn findProgram(self: *Build, names: []const []const u8, paths: []const []con
17041706 return name;
17051707 }
17061708 for (paths) |p| {
1707 const full_path = self.pathJoin(&.{
1708 p, self.fmt("{s}{s}", .{ name, exe_extension }),
1709 const full_path = b.pathJoin(&.{
1710 p, b.fmt("{s}{s}", .{ name, exe_extension }),
17091711 });
1710 return fs.realpathAlloc(self.allocator, full_path) catch continue;
1712 return fs.realpathAlloc(b.allocator, full_path) catch continue;
17111713 }
17121714 }
17131715 return error.FileNotFound;
17141716}
17151717
17161718pub fn runAllowFail(
1717 self: *Build,
1719 b: *Build,
17181720 argv: []const []const u8,
17191721 out_code: *u8,
17201722 stderr_behavior: std.ChildProcess.StdIo,
......@@ -1725,18 +1727,18 @@ pub fn runAllowFail(
17251727 return error.ExecNotSupported;
17261728
17271729 const max_output_size = 400 * 1024;
1728 var child = std.ChildProcess.init(argv, self.allocator);
1730 var child = std.ChildProcess.init(argv, b.allocator);
17291731 child.stdin_behavior = .Ignore;
17301732 child.stdout_behavior = .Pipe;
17311733 child.stderr_behavior = stderr_behavior;
1732 child.env_map = &self.graph.env_map;
1734 child.env_map = &b.graph.env_map;
17331735
17341736 try child.spawn();
17351737
1736 const stdout = child.stdout.?.reader().readAllAlloc(self.allocator, max_output_size) catch {
1738 const stdout = child.stdout.?.reader().readAllAlloc(b.allocator, max_output_size) catch {
17371739 return error.ReadFailure;
17381740 };
1739 errdefer self.allocator.free(stdout);
1741 errdefer b.allocator.free(stdout);
17401742
17411743 const term = try child.wait();
17421744 switch (term) {
......@@ -1779,19 +1781,16 @@ pub fn addSearchPrefix(b: *Build, search_prefix: []const u8) void {
17791781 b.search_prefixes.append(b.allocator, b.dupePath(search_prefix)) catch @panic("OOM");
17801782}
17811783
1782pub fn getInstallPath(self: *Build, dir: InstallDir, dest_rel_path: []const u8) []const u8 {
1784pub fn getInstallPath(b: *Build, dir: InstallDir, dest_rel_path: []const u8) []const u8 {
17831785 assert(!fs.path.isAbsolute(dest_rel_path)); // Install paths must be relative to the prefix
17841786 const base_dir = switch (dir) {
1785 .prefix => self.install_path,
1786 .bin => self.exe_dir,
1787 .lib => self.lib_dir,
1788 .header => self.h_dir,
1789 .custom => |p| self.pathJoin(&.{ self.install_path, p }),
1787 .prefix => b.install_path,
1788 .bin => b.exe_dir,
1789 .lib => b.lib_dir,
1790 .header => b.h_dir,
1791 .custom => |p| b.pathJoin(&.{ b.install_path, p }),
17901792 };
1791 return fs.path.resolve(
1792 self.allocator,
1793 &[_][]const u8{ base_dir, dest_rel_path },
1794 ) catch @panic("OOM");
1793 return b.pathResolve(&.{ base_dir, dest_rel_path });
17951794}
17961795
17971796pub const Dependency = struct {
......@@ -2092,11 +2091,11 @@ pub const GeneratedFile = struct {
20922091 /// This value must be set in the `fn make()` of the `step` and must not be `null` afterwards.
20932092 path: ?[]const u8 = null,
20942093
2095 pub fn getPath(self: GeneratedFile) []const u8 {
2096 return self.path orelse std.debug.panic(
2094 pub fn getPath(gen: GeneratedFile) []const u8 {
2095 return gen.step.owner.pathFromRoot(gen.path orelse std.debug.panic(
20972096 "getPath() was called on a GeneratedFile that wasn't built yet. Is there a missing Step dependency on step '{s}'?",
2098 .{self.step.name},
2099 );
2097 .{gen.step.name},
2098 ));
21002099 }
21012100};
21022101
......@@ -2132,28 +2131,23 @@ test dirnameAllowEmpty {
21322131
21332132/// A reference to an existing or future path.
21342133pub const LazyPath = union(enum) {
2135 /// Deprecated; use the `path` function instead.
2136 path: []const u8,
2137
21382134 /// A source file path relative to build root.
21392135 src_path: struct {
21402136 owner: *std.Build,
21412137 sub_path: []const u8,
21422138 },
21432139
2144 /// A file that is generated by an interface. Those files usually are
2145 /// not available until built by a build step.
2146 generated: *const GeneratedFile,
2147
2148 /// One of the parent directories of a file generated by an interface.
2149 /// The path is not available until built by a build step.
2150 generated_dirname: struct {
2151 generated: *const GeneratedFile,
2140 generated: struct {
2141 file: *const GeneratedFile,
21522142
21532143 /// The number of parent directories to go up.
2154 /// 0 means the directory of the generated file,
2155 /// 1 means the parent of that directory, and so on.
2156 up: usize,
2144 /// 0 means the generated file itself.
2145 /// 1 means the directory of the generated file.
2146 /// 2 means the parent of that directory, and so on.
2147 up: usize = 0,
2148
2149 /// Applied after `up`.
2150 sub_path: []const u8 = "",
21572151 },
21582152
21592153 /// An absolute path or a path relative to the current working directory of
......@@ -2169,12 +2163,6 @@ pub const LazyPath = union(enum) {
21692163 sub_path: []const u8,
21702164 },
21712165
2172 /// Deprecated. Call `path` instead.
2173 pub fn relative(p: []const u8) LazyPath {
2174 std.log.warn("deprecated. call std.Build.path instead", .{});
2175 return .{ .path = p };
2176 }
2177
21782166 /// Returns a lazy path referring to the directory containing this path.
21792167 ///
21802168 /// The dirname is not allowed to escape the logical root for underlying path.
......@@ -2182,10 +2170,8 @@ pub const LazyPath = union(enum) {
21822170 /// the dirname is not allowed to traverse outside of the build root.
21832171 /// Similarly, if the path is a generated file inside zig-cache,
21842172 /// the dirname is not allowed to traverse outside of zig-cache.
2185 pub fn dirname(self: LazyPath) LazyPath {
2186 return switch (self) {
2187 .generated => |gen| .{ .generated_dirname = .{ .generated = gen, .up = 0 } },
2188 .generated_dirname => |gen| .{ .generated_dirname = .{ .generated = gen.generated, .up = gen.up + 1 } },
2173 pub fn dirname(lazy_path: LazyPath) LazyPath {
2174 return switch (lazy_path) {
21892175 .src_path => |sp| .{ .src_path = .{
21902176 .owner = sp.owner,
21912177 .sub_path = dirnameAllowEmpty(sp.sub_path) orelse {
......@@ -2193,20 +2179,23 @@ pub const LazyPath = union(enum) {
21932179 @panic("misconfigured build script");
21942180 },
21952181 } },
2196 .path => |p| .{
2197 .path = dirnameAllowEmpty(p) orelse {
2198 dumpBadDirnameHelp(null, null, "dirname() attempted to traverse outside the build root\n", .{}) catch {};
2199 @panic("misconfigured build script");
2200 },
2201 },
2202 .cwd_relative => |p| .{
2203 .cwd_relative = dirnameAllowEmpty(p) orelse {
2182 .generated => |generated| .{ .generated = if (dirnameAllowEmpty(generated.sub_path)) |sub_dirname| .{
2183 .file = generated.file,
2184 .up = generated.up,
2185 .sub_path = sub_dirname,
2186 } else .{
2187 .file = generated.file,
2188 .up = generated.up + 1,
2189 .sub_path = "",
2190 } },
2191 .cwd_relative => |rel_path| .{
2192 .cwd_relative = dirnameAllowEmpty(rel_path) orelse {
22042193 // If we get null, it means one of two things:
2205 // - p was absolute, and is now root
2206 // - p was relative, and is now ""
2194 // - rel_path was absolute, and is now root
2195 // - rel_path was relative, and is now ""
22072196 // In either case, the build script tried to go too far
22082197 // and we should panic.
2209 if (fs.path.isAbsolute(p)) {
2198 if (fs.path.isAbsolute(rel_path)) {
22102199 dumpBadDirnameHelp(null, null,
22112200 \\dirname() attempted to traverse outside the root.
22122201 \\No more directories left to go up.
......@@ -2235,31 +2224,50 @@ pub const LazyPath = union(enum) {
22352224 };
22362225 }
22372226
2227 pub fn path(lazy_path: LazyPath, b: *Build, sub_path: []const u8) LazyPath {
2228 return switch (lazy_path) {
2229 .src_path => |src| .{ .src_path = .{
2230 .owner = src.owner,
2231 .sub_path = b.pathResolve(&.{ src.sub_path, sub_path }),
2232 } },
2233 .generated => |gen| .{ .generated = .{
2234 .file = gen.file,
2235 .up = gen.up,
2236 .sub_path = b.pathResolve(&.{ gen.sub_path, sub_path }),
2237 } },
2238 .cwd_relative => |cwd_relative| .{
2239 .cwd_relative = b.pathResolve(&.{ cwd_relative, sub_path }),
2240 },
2241 .dependency => |dep| .{ .dependency = .{
2242 .dependency = dep.dependency,
2243 .sub_path = b.pathResolve(&.{ dep.sub_path, sub_path }),
2244 } },
2245 };
2246 }
2247
22382248 /// Returns a string that can be shown to represent the file source.
2239 /// Either returns the path or `"generated"`.
2240 pub fn getDisplayName(self: LazyPath) []const u8 {
2241 return switch (self) {
2249 /// Either returns the path, `"generated"`, or `"dependency"`.
2250 pub fn getDisplayName(lazy_path: LazyPath) []const u8 {
2251 return switch (lazy_path) {
22422252 .src_path => |sp| sp.sub_path,
2243 .path, .cwd_relative => |p| p,
2253 .cwd_relative => |p| p,
22442254 .generated => "generated",
2245 .generated_dirname => "generated",
22462255 .dependency => "dependency",
22472256 };
22482257 }
22492258
22502259 /// Adds dependencies this file source implies to the given step.
2251 pub fn addStepDependencies(self: LazyPath, other_step: *Step) void {
2252 switch (self) {
2253 .src_path, .path, .cwd_relative, .dependency => {},
2254 .generated => |gen| other_step.dependOn(gen.step),
2255 .generated_dirname => |gen| other_step.dependOn(gen.generated.step),
2260 pub fn addStepDependencies(lazy_path: LazyPath, other_step: *Step) void {
2261 switch (lazy_path) {
2262 .src_path, .cwd_relative, .dependency => {},
2263 .generated => |gen| other_step.dependOn(gen.file.step),
22562264 }
22572265 }
22582266
22592267 /// Returns an absolute path.
22602268 /// Intended to be used during the make phase only.
2261 pub fn getPath(self: LazyPath, src_builder: *Build) []const u8 {
2262 return getPath2(self, src_builder, null);
2269 pub fn getPath(lazy_path: LazyPath, src_builder: *Build) []const u8 {
2270 return getPath2(lazy_path, src_builder, null);
22632271 }
22642272
22652273 /// Returns an absolute path.
......@@ -2267,56 +2275,52 @@ pub const LazyPath = union(enum) {
22672275 ///
22682276 /// `asking_step` is only used for debugging purposes; it's the step being
22692277 /// run that is asking for the path.
2270 pub fn getPath2(self: LazyPath, src_builder: *Build, asking_step: ?*Step) []const u8 {
2271 switch (self) {
2272 .path => |p| return src_builder.pathFromRoot(p),
2278 pub fn getPath2(lazy_path: LazyPath, src_builder: *Build, asking_step: ?*Step) []const u8 {
2279 switch (lazy_path) {
22732280 .src_path => |sp| return sp.owner.pathFromRoot(sp.sub_path),
22742281 .cwd_relative => |p| return src_builder.pathFromCwd(p),
2275 .generated => |gen| return gen.path orelse {
2276 std.debug.getStderrMutex().lock();
2277 const stderr = std.io.getStdErr();
2278 dumpBadGetPathHelp(gen.step, stderr, src_builder, asking_step) catch {};
2279 @panic("misconfigured build script");
2280 },
2281 .generated_dirname => |gen| {
2282 const cache_root_path = src_builder.cache_root.path orelse
2283 (src_builder.cache_root.join(src_builder.allocator, &.{"."}) catch @panic("OOM"));
2284
2285 const gen_step = gen.generated.step;
2286 var p = getPath2(LazyPath{ .generated = gen.generated }, src_builder, asking_step);
2287 var i: usize = 0;
2288 while (i <= gen.up) : (i += 1) {
2289 // path is absolute.
2290 // dirname will return null only if we're at root.
2291 // Typically, we'll stop well before that at the cache root.
2292 p = fs.path.dirname(p) orelse {
2293 dumpBadDirnameHelp(gen_step, asking_step,
2294 \\dirname() reached root.
2295 \\No more directories left to go up.
2296 \\
2297 , .{}) catch {};
2298 @panic("misconfigured build script");
2299 };
2300
2301 if (mem.eql(u8, p, cache_root_path) and i < gen.up) {
2302 // If we hit the cache root and there's still more to go,
2303 // the script attempted to go too far.
2304 dumpBadDirnameHelp(gen_step, asking_step,
2305 \\dirname() attempted to traverse outside the cache root.
2306 \\This is not allowed.
2307 \\
2308 , .{}) catch {};
2309 @panic("misconfigured build script");
2282 .generated => |gen| {
2283 var file_path: []const u8 = gen.file.step.owner.pathFromRoot(gen.file.path orelse {
2284 std.debug.getStderrMutex().lock();
2285 const stderr = std.io.getStdErr();
2286 dumpBadGetPathHelp(gen.file.step, stderr, src_builder, asking_step) catch {};
2287 std.debug.getStderrMutex().unlock();
2288 @panic("misconfigured build script");
2289 });
2290
2291 if (gen.up > 0) {
2292 const cache_root_path = src_builder.cache_root.path orelse
2293 (src_builder.cache_root.join(src_builder.allocator, &.{"."}) catch @panic("OOM"));
2294
2295 for (0..gen.up) |_| {
2296 if (mem.eql(u8, file_path, cache_root_path)) {
2297 // If we hit the cache root and there's still more to go,
2298 // the script attempted to go too far.
2299 dumpBadDirnameHelp(gen.file.step, asking_step,
2300 \\dirname() attempted to traverse outside the cache root.
2301 \\This is not allowed.
2302 \\
2303 , .{}) catch {};
2304 @panic("misconfigured build script");
2305 }
2306
2307 // path is absolute.
2308 // dirname will return null only if we're at root.
2309 // Typically, we'll stop well before that at the cache root.
2310 file_path = fs.path.dirname(file_path) orelse {
2311 dumpBadDirnameHelp(gen.file.step, asking_step,
2312 \\dirname() reached root.
2313 \\No more directories left to go up.
2314 \\
2315 , .{}) catch {};
2316 @panic("misconfigured build script");
2317 };
23102318 }
23112319 }
2312 return p;
2313 },
2314 .dependency => |dep| {
2315 return dep.dependency.builder.pathJoin(&[_][]const u8{
2316 dep.dependency.builder.build_root.path.?,
2317 dep.sub_path,
2318 });
2320
2321 return src_builder.pathResolve(&.{ file_path, gen.sub_path });
23192322 },
2323 .dependency => |dep| return dep.dependency.builder.pathFromRoot(dep.sub_path),
23202324 }
23212325 }
23222326
......@@ -2324,21 +2328,18 @@ pub const LazyPath = union(enum) {
23242328 ///
23252329 /// The `b` parameter is only used for its allocator. All *Build instances
23262330 /// share the same allocator.
2327 pub fn dupe(self: LazyPath, b: *Build) LazyPath {
2328 return switch (self) {
2331 pub fn dupe(lazy_path: LazyPath, b: *Build) LazyPath {
2332 return switch (lazy_path) {
23292333 .src_path => |sp| .{ .src_path = .{
23302334 .owner = sp.owner,
23312335 .sub_path = sp.owner.dupePath(sp.sub_path),
23322336 } },
2333 .path => |p| .{ .path = b.dupePath(p) },
23342337 .cwd_relative => |p| .{ .cwd_relative = b.dupePath(p) },
2335 .generated => |gen| .{ .generated = gen },
2336 .generated_dirname => |gen| .{
2337 .generated_dirname = .{
2338 .generated = gen.generated,
2339 .up = gen.up,
2340 },
2341 },
2338 .generated => |gen| .{ .generated = .{
2339 .file = gen.file,
2340 .up = gen.up,
2341 .sub_path = b.dupePath(gen.sub_path),
2342 } },
23422343 .dependency => |dep| .{ .dependency = dep },
23432344 };
23442345 }
......@@ -2425,11 +2426,11 @@ pub const InstallDir = union(enum) {
24252426 custom: []const u8,
24262427
24272428 /// Duplicates the install directory including the path if set to custom.
2428 pub fn dupe(self: InstallDir, builder: *Build) InstallDir {
2429 if (self == .custom) {
2430 return .{ .custom = builder.dupe(self.custom) };
2429 pub fn dupe(dir: InstallDir, builder: *Build) InstallDir {
2430 if (dir == .custom) {
2431 return .{ .custom = builder.dupe(dir.custom) };
24312432 } else {
2432 return self;
2433 return dir;
24332434 }
24342435 }
24352436};
......@@ -2439,10 +2440,10 @@ pub const InstalledFile = struct {
24392440 path: []const u8,
24402441
24412442 /// Duplicates the installed file path and directory.
2442 pub fn dupe(self: InstalledFile, builder: *Build) InstalledFile {
2443 pub fn dupe(file: InstalledFile, builder: *Build) InstalledFile {
24432444 return .{
2444 .dir = self.dir.dupe(builder),
2445 .path = builder.dupe(self.path),
2445 .dir = file.dir.dupe(builder),
2446 .path = builder.dupe(file.path),
24462447 };
24472448 }
24482449};
lib/std/Build/Module.zig+13-18
......@@ -89,10 +89,10 @@ pub const CSourceFile = struct {
8989 file: LazyPath,
9090 flags: []const []const u8 = &.{},
9191
92 pub fn dupe(self: CSourceFile, b: *std.Build) CSourceFile {
92 pub fn dupe(file: CSourceFile, b: *std.Build) CSourceFile {
9393 return .{
94 .file = self.file.dupe(b),
95 .flags = b.dupeStrings(self.flags),
94 .file = file.file.dupe(b),
95 .flags = b.dupeStrings(file.flags),
9696 };
9797 }
9898};
......@@ -115,12 +115,12 @@ pub const RcSourceFile = struct {
115115 /// as `/I <resolved path>`.
116116 include_paths: []const LazyPath = &.{},
117117
118 pub fn dupe(self: RcSourceFile, b: *std.Build) RcSourceFile {
119 const include_paths = b.allocator.alloc(LazyPath, self.include_paths.len) catch @panic("OOM");
120 for (include_paths, self.include_paths) |*dest, lazy_path| dest.* = lazy_path.dupe(b);
118 pub fn dupe(file: RcSourceFile, b: *std.Build) RcSourceFile {
119 const include_paths = b.allocator.alloc(LazyPath, file.include_paths.len) catch @panic("OOM");
120 for (include_paths, file.include_paths) |*dest, lazy_path| dest.* = lazy_path.dupe(b);
121121 return .{
122 .file = self.file.dupe(b),
123 .flags = b.dupeStrings(self.flags),
122 .file = file.file.dupe(b),
123 .flags = b.dupeStrings(file.flags),
124124 .include_paths = include_paths,
125125 };
126126 }
......@@ -665,24 +665,19 @@ pub fn appendZigProcessFlags(
665665 for (m.include_dirs.items) |include_dir| {
666666 switch (include_dir) {
667667 .path => |include_path| {
668 try zig_args.append("-I");
669 try zig_args.append(include_path.getPath(b));
668 try zig_args.appendSlice(&.{ "-I", include_path.getPath2(b, asking_step) });
670669 },
671670 .path_system => |include_path| {
672 try zig_args.append("-isystem");
673 try zig_args.append(include_path.getPath(b));
671 try zig_args.appendSlice(&.{ "-isystem", include_path.getPath2(b, asking_step) });
674672 },
675673 .path_after => |include_path| {
676 try zig_args.append("-idirafter");
677 try zig_args.append(include_path.getPath(b));
674 try zig_args.appendSlice(&.{ "-idirafter", include_path.getPath2(b, asking_step) });
678675 },
679676 .framework_path => |include_path| {
680 try zig_args.append("-F");
681 try zig_args.append(include_path.getPath2(b, asking_step));
677 try zig_args.appendSlice(&.{ "-F", include_path.getPath2(b, asking_step) });
682678 },
683679 .framework_path_system => |include_path| {
684 try zig_args.append("-iframework");
685 try zig_args.append(include_path.getPath2(b, asking_step));
680 try zig_args.appendSlice(&.{ "-iframework", include_path.getPath2(b, asking_step) });
686681 },
687682 .other_step => |other| {
688683 if (other.generated_h) |header| {
lib/std/Build/Step.zig+3-3
......@@ -58,7 +58,7 @@ pub const TestResults = struct {
5858 }
5959};
6060
61pub const MakeFn = *const fn (self: *Step, prog_node: *std.Progress.Node) anyerror!void;
61pub const MakeFn = *const fn (step: *Step, prog_node: *std.Progress.Node) anyerror!void;
6262
6363pub const State = enum {
6464 precheck_unstarted,
......@@ -201,8 +201,8 @@ pub fn make(s: *Step, prog_node: *std.Progress.Node) error{ MakeFailed, MakeSkip
201201 }
202202}
203203
204pub fn dependOn(self: *Step, other: *Step) void {
205 self.dependencies.append(other) catch @panic("OOM");
204pub fn dependOn(step: *Step, other: *Step) void {
205 step.dependencies.append(other) catch @panic("OOM");
206206}
207207
208208pub fn getStackTrace(s: *Step) ?std.builtin.StackTrace {
lib/std/Build/Step/CheckFile.zig+13-13
......@@ -14,7 +14,7 @@ expected_exact: ?[]const u8,
1414source: std.Build.LazyPath,
1515max_bytes: usize = 20 * 1024 * 1024,
1616
17pub const base_id = .check_file;
17pub const base_id: Step.Id = .check_file;
1818
1919pub const Options = struct {
2020 expected_matches: []const []const u8 = &.{},
......@@ -26,10 +26,10 @@ pub fn create(
2626 source: std.Build.LazyPath,
2727 options: Options,
2828) *CheckFile {
29 const self = owner.allocator.create(CheckFile) catch @panic("OOM");
30 self.* = .{
29 const check_file = owner.allocator.create(CheckFile) catch @panic("OOM");
30 check_file.* = .{
3131 .step = Step.init(.{
32 .id = .check_file,
32 .id = base_id,
3333 .name = "CheckFile",
3434 .owner = owner,
3535 .makeFn = make,
......@@ -38,27 +38,27 @@ pub fn create(
3838 .expected_matches = owner.dupeStrings(options.expected_matches),
3939 .expected_exact = options.expected_exact,
4040 };
41 self.source.addStepDependencies(&self.step);
42 return self;
41 check_file.source.addStepDependencies(&check_file.step);
42 return check_file;
4343}
4444
45pub fn setName(self: *CheckFile, name: []const u8) void {
46 self.step.name = name;
45pub fn setName(check_file: *CheckFile, name: []const u8) void {
46 check_file.step.name = name;
4747}
4848
4949fn make(step: *Step, prog_node: *std.Progress.Node) !void {
5050 _ = prog_node;
5151 const b = step.owner;
52 const self: *CheckFile = @fieldParentPtr("step", step);
52 const check_file: *CheckFile = @fieldParentPtr("step", step);
5353
54 const src_path = self.source.getPath(b);
55 const contents = fs.cwd().readFileAlloc(b.allocator, src_path, self.max_bytes) catch |err| {
54 const src_path = check_file.source.getPath2(b, step);
55 const contents = fs.cwd().readFileAlloc(b.allocator, src_path, check_file.max_bytes) catch |err| {
5656 return step.fail("unable to read '{s}': {s}", .{
5757 src_path, @errorName(err),
5858 });
5959 };
6060
61 for (self.expected_matches) |expected_match| {
61 for (check_file.expected_matches) |expected_match| {
6262 if (mem.indexOf(u8, contents, expected_match) == null) {
6363 return step.fail(
6464 \\
......@@ -71,7 +71,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
7171 }
7272 }
7373
74 if (self.expected_exact) |expected_exact| {
74 if (check_file.expected_exact) |expected_exact| {
7575 if (!mem.eql(u8, expected_exact, contents)) {
7676 return step.fail(
7777 \\
lib/std/Build/Step/CheckObject.zig+107-107
......@@ -12,7 +12,7 @@ const CheckObject = @This();
1212const Allocator = mem.Allocator;
1313const Step = std.Build.Step;
1414
15pub const base_id = .check_object;
15pub const base_id: Step.Id = .check_object;
1616
1717step: Step,
1818source: std.Build.LazyPath,
......@@ -26,10 +26,10 @@ pub fn create(
2626 obj_format: std.Target.ObjectFormat,
2727) *CheckObject {
2828 const gpa = owner.allocator;
29 const self = gpa.create(CheckObject) catch @panic("OOM");
30 self.* = .{
29 const check_object = gpa.create(CheckObject) catch @panic("OOM");
30 check_object.* = .{
3131 .step = Step.init(.{
32 .id = .check_file,
32 .id = base_id,
3333 .name = "CheckObject",
3434 .owner = owner,
3535 .makeFn = make,
......@@ -38,8 +38,8 @@ pub fn create(
3838 .checks = std.ArrayList(Check).init(gpa),
3939 .obj_format = obj_format,
4040 };
41 self.source.addStepDependencies(&self.step);
42 return self;
41 check_object.source.addStepDependencies(&check_object.step);
42 return check_object;
4343}
4444
4545const SearchPhrase = struct {
......@@ -268,36 +268,36 @@ const Check = struct {
268268 return check;
269269 }
270270
271 fn extract(self: *Check, phrase: SearchPhrase) void {
272 self.actions.append(.{
271 fn extract(check: *Check, phrase: SearchPhrase) void {
272 check.actions.append(.{
273273 .tag = .extract,
274274 .phrase = phrase,
275275 }) catch @panic("OOM");
276276 }
277277
278 fn exact(self: *Check, phrase: SearchPhrase) void {
279 self.actions.append(.{
278 fn exact(check: *Check, phrase: SearchPhrase) void {
279 check.actions.append(.{
280280 .tag = .exact,
281281 .phrase = phrase,
282282 }) catch @panic("OOM");
283283 }
284284
285 fn contains(self: *Check, phrase: SearchPhrase) void {
286 self.actions.append(.{
285 fn contains(check: *Check, phrase: SearchPhrase) void {
286 check.actions.append(.{
287287 .tag = .contains,
288288 .phrase = phrase,
289289 }) catch @panic("OOM");
290290 }
291291
292 fn notPresent(self: *Check, phrase: SearchPhrase) void {
293 self.actions.append(.{
292 fn notPresent(check: *Check, phrase: SearchPhrase) void {
293 check.actions.append(.{
294294 .tag = .not_present,
295295 .phrase = phrase,
296296 }) catch @panic("OOM");
297297 }
298298
299 fn computeCmp(self: *Check, phrase: SearchPhrase, expected: ComputeCompareExpected) void {
300 self.actions.append(.{
299 fn computeCmp(check: *Check, phrase: SearchPhrase, expected: ComputeCompareExpected) void {
300 check.actions.append(.{
301301 .tag = .compute_cmp,
302302 .phrase = phrase,
303303 .expected = expected,
......@@ -328,246 +328,246 @@ const Check = struct {
328328};
329329
330330/// Creates a new empty sequence of actions.
331fn checkStart(self: *CheckObject, kind: Check.Kind) void {
332 const new_check = Check.create(self.step.owner.allocator, kind);
333 self.checks.append(new_check) catch @panic("OOM");
331fn checkStart(check_object: *CheckObject, kind: Check.Kind) void {
332 const check = Check.create(check_object.step.owner.allocator, kind);
333 check_object.checks.append(check) catch @panic("OOM");
334334}
335335
336336/// Adds an exact match phrase to the latest created Check.
337pub fn checkExact(self: *CheckObject, phrase: []const u8) void {
338 self.checkExactInner(phrase, null);
337pub fn checkExact(check_object: *CheckObject, phrase: []const u8) void {
338 check_object.checkExactInner(phrase, null);
339339}
340340
341341/// Like `checkExact()` but takes an additional argument `LazyPath` which will be
342342/// resolved to a full search query in `make()`.
343pub fn checkExactPath(self: *CheckObject, phrase: []const u8, lazy_path: std.Build.LazyPath) void {
344 self.checkExactInner(phrase, lazy_path);
343pub fn checkExactPath(check_object: *CheckObject, phrase: []const u8, lazy_path: std.Build.LazyPath) void {
344 check_object.checkExactInner(phrase, lazy_path);
345345}
346346
347fn checkExactInner(self: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
348 assert(self.checks.items.len > 0);
349 const last = &self.checks.items[self.checks.items.len - 1];
350 last.exact(.{ .string = self.step.owner.dupe(phrase), .lazy_path = lazy_path });
347fn checkExactInner(check_object: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
348 assert(check_object.checks.items.len > 0);
349 const last = &check_object.checks.items[check_object.checks.items.len - 1];
350 last.exact(.{ .string = check_object.step.owner.dupe(phrase), .lazy_path = lazy_path });
351351}
352352
353353/// Adds a fuzzy match phrase to the latest created Check.
354pub fn checkContains(self: *CheckObject, phrase: []const u8) void {
355 self.checkContainsInner(phrase, null);
354pub fn checkContains(check_object: *CheckObject, phrase: []const u8) void {
355 check_object.checkContainsInner(phrase, null);
356356}
357357
358358/// Like `checkContains()` but takes an additional argument `lazy_path` which will be
359359/// resolved to a full search query in `make()`.
360360pub fn checkContainsPath(
361 self: *CheckObject,
361 check_object: *CheckObject,
362362 phrase: []const u8,
363363 lazy_path: std.Build.LazyPath,
364364) void {
365 self.checkContainsInner(phrase, lazy_path);
365 check_object.checkContainsInner(phrase, lazy_path);
366366}
367367
368fn checkContainsInner(self: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
369 assert(self.checks.items.len > 0);
370 const last = &self.checks.items[self.checks.items.len - 1];
371 last.contains(.{ .string = self.step.owner.dupe(phrase), .lazy_path = lazy_path });
368fn checkContainsInner(check_object: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
369 assert(check_object.checks.items.len > 0);
370 const last = &check_object.checks.items[check_object.checks.items.len - 1];
371 last.contains(.{ .string = check_object.step.owner.dupe(phrase), .lazy_path = lazy_path });
372372}
373373
374374/// Adds an exact match phrase with variable extractor to the latest created Check.
375pub fn checkExtract(self: *CheckObject, phrase: []const u8) void {
376 self.checkExtractInner(phrase, null);
375pub fn checkExtract(check_object: *CheckObject, phrase: []const u8) void {
376 check_object.checkExtractInner(phrase, null);
377377}
378378
379379/// Like `checkExtract()` but takes an additional argument `LazyPath` which will be
380380/// resolved to a full search query in `make()`.
381pub fn checkExtractLazyPath(self: *CheckObject, phrase: []const u8, lazy_path: std.Build.LazyPath) void {
382 self.checkExtractInner(phrase, lazy_path);
381pub fn checkExtractLazyPath(check_object: *CheckObject, phrase: []const u8, lazy_path: std.Build.LazyPath) void {
382 check_object.checkExtractInner(phrase, lazy_path);
383383}
384384
385fn checkExtractInner(self: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
386 assert(self.checks.items.len > 0);
387 const last = &self.checks.items[self.checks.items.len - 1];
388 last.extract(.{ .string = self.step.owner.dupe(phrase), .lazy_path = lazy_path });
385fn checkExtractInner(check_object: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
386 assert(check_object.checks.items.len > 0);
387 const last = &check_object.checks.items[check_object.checks.items.len - 1];
388 last.extract(.{ .string = check_object.step.owner.dupe(phrase), .lazy_path = lazy_path });
389389}
390390
391391/// Adds another searched phrase to the latest created Check
392392/// however ensures there is no matching phrase in the output.
393pub fn checkNotPresent(self: *CheckObject, phrase: []const u8) void {
394 self.checkNotPresentInner(phrase, null);
393pub fn checkNotPresent(check_object: *CheckObject, phrase: []const u8) void {
394 check_object.checkNotPresentInner(phrase, null);
395395}
396396
397397/// Like `checkExtract()` but takes an additional argument `LazyPath` which will be
398398/// resolved to a full search query in `make()`.
399pub fn checkNotPresentLazyPath(self: *CheckObject, phrase: []const u8, lazy_path: std.Build.LazyPath) void {
400 self.checkNotPresentInner(phrase, lazy_path);
399pub fn checkNotPresentLazyPath(check_object: *CheckObject, phrase: []const u8, lazy_path: std.Build.LazyPath) void {
400 check_object.checkNotPresentInner(phrase, lazy_path);
401401}
402402
403fn checkNotPresentInner(self: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
404 assert(self.checks.items.len > 0);
405 const last = &self.checks.items[self.checks.items.len - 1];
406 last.notPresent(.{ .string = self.step.owner.dupe(phrase), .lazy_path = lazy_path });
403fn checkNotPresentInner(check_object: *CheckObject, phrase: []const u8, lazy_path: ?std.Build.LazyPath) void {
404 assert(check_object.checks.items.len > 0);
405 const last = &check_object.checks.items[check_object.checks.items.len - 1];
406 last.notPresent(.{ .string = check_object.step.owner.dupe(phrase), .lazy_path = lazy_path });
407407}
408408
409409/// Creates a new check checking in the file headers (section, program headers, etc.).
410pub fn checkInHeaders(self: *CheckObject) void {
411 self.checkStart(.headers);
410pub fn checkInHeaders(check_object: *CheckObject) void {
411 check_object.checkStart(.headers);
412412}
413413
414414/// Creates a new check checking specifically symbol table parsed and dumped from the object
415415/// file.
416pub fn checkInSymtab(self: *CheckObject) void {
417 const label = switch (self.obj_format) {
416pub fn checkInSymtab(check_object: *CheckObject) void {
417 const label = switch (check_object.obj_format) {
418418 .macho => MachODumper.symtab_label,
419419 .elf => ElfDumper.symtab_label,
420420 .wasm => WasmDumper.symtab_label,
421421 .coff => @panic("TODO symtab for coff"),
422422 else => @panic("TODO other file formats"),
423423 };
424 self.checkStart(.symtab);
425 self.checkExact(label);
424 check_object.checkStart(.symtab);
425 check_object.checkExact(label);
426426}
427427
428428/// Creates a new check checking specifically dyld rebase opcodes contents parsed and dumped
429429/// from the object file.
430430/// This check is target-dependent and applicable to MachO only.
431pub fn checkInDyldRebase(self: *CheckObject) void {
432 const label = switch (self.obj_format) {
431pub fn checkInDyldRebase(check_object: *CheckObject) void {
432 const label = switch (check_object.obj_format) {
433433 .macho => MachODumper.dyld_rebase_label,
434434 else => @panic("Unsupported target platform"),
435435 };
436 self.checkStart(.dyld_rebase);
437 self.checkExact(label);
436 check_object.checkStart(.dyld_rebase);
437 check_object.checkExact(label);
438438}
439439
440440/// Creates a new check checking specifically dyld bind opcodes contents parsed and dumped
441441/// from the object file.
442442/// This check is target-dependent and applicable to MachO only.
443pub fn checkInDyldBind(self: *CheckObject) void {
444 const label = switch (self.obj_format) {
443pub fn checkInDyldBind(check_object: *CheckObject) void {
444 const label = switch (check_object.obj_format) {
445445 .macho => MachODumper.dyld_bind_label,
446446 else => @panic("Unsupported target platform"),
447447 };
448 self.checkStart(.dyld_bind);
449 self.checkExact(label);
448 check_object.checkStart(.dyld_bind);
449 check_object.checkExact(label);
450450}
451451
452452/// Creates a new check checking specifically dyld weak bind opcodes contents parsed and dumped
453453/// from the object file.
454454/// This check is target-dependent and applicable to MachO only.
455pub fn checkInDyldWeakBind(self: *CheckObject) void {
456 const label = switch (self.obj_format) {
455pub fn checkInDyldWeakBind(check_object: *CheckObject) void {
456 const label = switch (check_object.obj_format) {
457457 .macho => MachODumper.dyld_weak_bind_label,
458458 else => @panic("Unsupported target platform"),
459459 };
460 self.checkStart(.dyld_weak_bind);
461 self.checkExact(label);
460 check_object.checkStart(.dyld_weak_bind);
461 check_object.checkExact(label);
462462}
463463
464464/// Creates a new check checking specifically dyld lazy bind opcodes contents parsed and dumped
465465/// from the object file.
466466/// This check is target-dependent and applicable to MachO only.
467pub fn checkInDyldLazyBind(self: *CheckObject) void {
468 const label = switch (self.obj_format) {
467pub fn checkInDyldLazyBind(check_object: *CheckObject) void {
468 const label = switch (check_object.obj_format) {
469469 .macho => MachODumper.dyld_lazy_bind_label,
470470 else => @panic("Unsupported target platform"),
471471 };
472 self.checkStart(.dyld_lazy_bind);
473 self.checkExact(label);
472 check_object.checkStart(.dyld_lazy_bind);
473 check_object.checkExact(label);
474474}
475475
476476/// Creates a new check checking specifically exports info contents parsed and dumped
477477/// from the object file.
478478/// This check is target-dependent and applicable to MachO only.
479pub fn checkInExports(self: *CheckObject) void {
480 const label = switch (self.obj_format) {
479pub fn checkInExports(check_object: *CheckObject) void {
480 const label = switch (check_object.obj_format) {
481481 .macho => MachODumper.exports_label,
482482 else => @panic("Unsupported target platform"),
483483 };
484 self.checkStart(.exports);
485 self.checkExact(label);
484 check_object.checkStart(.exports);
485 check_object.checkExact(label);
486486}
487487
488488/// Creates a new check checking specifically indirect symbol table parsed and dumped
489489/// from the object file.
490490/// This check is target-dependent and applicable to MachO only.
491pub fn checkInIndirectSymtab(self: *CheckObject) void {
492 const label = switch (self.obj_format) {
491pub fn checkInIndirectSymtab(check_object: *CheckObject) void {
492 const label = switch (check_object.obj_format) {
493493 .macho => MachODumper.indirect_symtab_label,
494494 else => @panic("Unsupported target platform"),
495495 };
496 self.checkStart(.indirect_symtab);
497 self.checkExact(label);
496 check_object.checkStart(.indirect_symtab);
497 check_object.checkExact(label);
498498}
499499
500500/// Creates a new check checking specifically dynamic symbol table parsed and dumped from the object
501501/// file.
502502/// This check is target-dependent and applicable to ELF only.
503pub fn checkInDynamicSymtab(self: *CheckObject) void {
504 const label = switch (self.obj_format) {
503pub fn checkInDynamicSymtab(check_object: *CheckObject) void {
504 const label = switch (check_object.obj_format) {
505505 .elf => ElfDumper.dynamic_symtab_label,
506506 else => @panic("Unsupported target platform"),
507507 };
508 self.checkStart(.dynamic_symtab);
509 self.checkExact(label);
508 check_object.checkStart(.dynamic_symtab);
509 check_object.checkExact(label);
510510}
511511
512512/// Creates a new check checking specifically dynamic section parsed and dumped from the object
513513/// file.
514514/// This check is target-dependent and applicable to ELF only.
515pub fn checkInDynamicSection(self: *CheckObject) void {
516 const label = switch (self.obj_format) {
515pub fn checkInDynamicSection(check_object: *CheckObject) void {
516 const label = switch (check_object.obj_format) {
517517 .elf => ElfDumper.dynamic_section_label,
518518 else => @panic("Unsupported target platform"),
519519 };
520 self.checkStart(.dynamic_section);
521 self.checkExact(label);
520 check_object.checkStart(.dynamic_section);
521 check_object.checkExact(label);
522522}
523523
524524/// Creates a new check checking specifically symbol table parsed and dumped from the archive
525525/// file.
526pub fn checkInArchiveSymtab(self: *CheckObject) void {
527 const label = switch (self.obj_format) {
526pub fn checkInArchiveSymtab(check_object: *CheckObject) void {
527 const label = switch (check_object.obj_format) {
528528 .elf => ElfDumper.archive_symtab_label,
529529 else => @panic("TODO other file formats"),
530530 };
531 self.checkStart(.archive_symtab);
532 self.checkExact(label);
531 check_object.checkStart(.archive_symtab);
532 check_object.checkExact(label);
533533}
534534
535pub fn dumpSection(self: *CheckObject, name: [:0]const u8) void {
536 const new_check = Check.dumpSection(self.step.owner.allocator, name);
537 self.checks.append(new_check) catch @panic("OOM");
535pub fn dumpSection(check_object: *CheckObject, name: [:0]const u8) void {
536 const check = Check.dumpSection(check_object.step.owner.allocator, name);
537 check_object.checks.append(check) catch @panic("OOM");
538538}
539539
540540/// Creates a new standalone, singular check which allows running simple binary operations
541541/// on the extracted variables. It will then compare the reduced program with the value of
542542/// the expected variable.
543543pub fn checkComputeCompare(
544 self: *CheckObject,
544 check_object: *CheckObject,
545545 program: []const u8,
546546 expected: ComputeCompareExpected,
547547) void {
548 var new_check = Check.create(self.step.owner.allocator, .compute_compare);
549 new_check.computeCmp(.{ .string = self.step.owner.dupe(program) }, expected);
550 self.checks.append(new_check) catch @panic("OOM");
548 var check = Check.create(check_object.step.owner.allocator, .compute_compare);
549 check.computeCmp(.{ .string = check_object.step.owner.dupe(program) }, expected);
550 check_object.checks.append(check) catch @panic("OOM");
551551}
552552
553553fn make(step: *Step, prog_node: *std.Progress.Node) !void {
554554 _ = prog_node;
555555 const b = step.owner;
556556 const gpa = b.allocator;
557 const self: *CheckObject = @fieldParentPtr("step", step);
557 const check_object: *CheckObject = @fieldParentPtr("step", step);
558558
559 const src_path = self.source.getPath(b);
559 const src_path = check_object.source.getPath2(b, step);
560560 const contents = fs.cwd().readFileAllocOptions(
561561 gpa,
562562 src_path,
563 self.max_bytes,
563 check_object.max_bytes,
564564 null,
565565 @alignOf(u64),
566566 null,
567567 ) catch |err| return step.fail("unable to read '{s}': {s}", .{ src_path, @errorName(err) });
568568
569569 var vars = std.StringHashMap(u64).init(gpa);
570 for (self.checks.items) |chk| {
570 for (check_object.checks.items) |chk| {
571571 if (chk.kind == .compute_compare) {
572572 assert(chk.actions.items.len == 1);
573573 const act = chk.actions.items[0];
......@@ -587,7 +587,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
587587 continue;
588588 }
589589
590 const output = switch (self.obj_format) {
590 const output = switch (check_object.obj_format) {
591591 .macho => try MachODumper.parseAndDump(step, chk, contents),
592592 .elf => try ElfDumper.parseAndDump(step, chk, contents),
593593 .coff => return step.fail("TODO coff parser", .{}),
......@@ -1597,8 +1597,8 @@ const MachODumper = struct {
15971597 },
15981598 },
15991599
1600 inline fn rankByTag(self: Export) u3 {
1601 return switch (self.tag) {
1600 inline fn rankByTag(@"export": Export) u3 {
1601 return switch (@"export".tag) {
16021602 .@"export" => 1,
16031603 .reexport => 2,
16041604 .stub_resolver => 3,
lib/std/Build/Step/Compile.zig+352-355
......@@ -263,10 +263,10 @@ pub const HeaderInstallation = union(enum) {
263263 source: LazyPath,
264264 dest_rel_path: []const u8,
265265
266 pub fn dupe(self: File, b: *std.Build) File {
266 pub fn dupe(file: File, b: *std.Build) File {
267267 return .{
268 .source = self.source.dupe(b),
269 .dest_rel_path = b.dupePath(self.dest_rel_path),
268 .source = file.source.dupe(b),
269 .dest_rel_path = b.dupePath(file.dest_rel_path),
270270 };
271271 }
272272 };
......@@ -284,31 +284,31 @@ pub const HeaderInstallation = union(enum) {
284284 /// `exclude_extensions` takes precedence over `include_extensions`.
285285 include_extensions: ?[]const []const u8 = &.{".h"},
286286
287 pub fn dupe(self: Directory.Options, b: *std.Build) Directory.Options {
287 pub fn dupe(opts: Directory.Options, b: *std.Build) Directory.Options {
288288 return .{
289 .exclude_extensions = b.dupeStrings(self.exclude_extensions),
290 .include_extensions = if (self.include_extensions) |incs| b.dupeStrings(incs) else null,
289 .exclude_extensions = b.dupeStrings(opts.exclude_extensions),
290 .include_extensions = if (opts.include_extensions) |incs| b.dupeStrings(incs) else null,
291291 };
292292 }
293293 };
294294
295 pub fn dupe(self: Directory, b: *std.Build) Directory {
295 pub fn dupe(dir: Directory, b: *std.Build) Directory {
296296 return .{
297 .source = self.source.dupe(b),
298 .dest_rel_path = b.dupePath(self.dest_rel_path),
299 .options = self.options.dupe(b),
297 .source = dir.source.dupe(b),
298 .dest_rel_path = b.dupePath(dir.dest_rel_path),
299 .options = dir.options.dupe(b),
300300 };
301301 }
302302 };
303303
304 pub fn getSource(self: HeaderInstallation) LazyPath {
305 return switch (self) {
304 pub fn getSource(installation: HeaderInstallation) LazyPath {
305 return switch (installation) {
306306 inline .file, .directory => |x| x.source,
307307 };
308308 }
309309
310 pub fn dupe(self: HeaderInstallation, b: *std.Build) HeaderInstallation {
311 return switch (self) {
310 pub fn dupe(installation: HeaderInstallation, b: *std.Build) HeaderInstallation {
311 return switch (installation) {
312312 .file => |f| .{ .file = f.dupe(b) },
313313 .directory => |d| .{ .directory = d.dupe(b) },
314314 };
......@@ -354,8 +354,8 @@ pub fn create(owner: *std.Build, options: Options) *Compile {
354354 .version = options.version,
355355 }) catch @panic("OOM");
356356
357 const self = owner.allocator.create(Compile) catch @panic("OOM");
358 self.* = .{
357 const compile = owner.allocator.create(Compile) catch @panic("OOM");
358 compile.* = .{
359359 .root_module = undefined,
360360 .verbose_link = false,
361361 .verbose_cc = false,
......@@ -398,57 +398,57 @@ pub fn create(owner: *std.Build, options: Options) *Compile {
398398 .use_lld = options.use_lld,
399399 };
400400
401 self.root_module.init(owner, options.root_module, self);
401 compile.root_module.init(owner, options.root_module, compile);
402402
403403 if (options.zig_lib_dir) |lp| {
404 self.zig_lib_dir = lp.dupe(self.step.owner);
405 lp.addStepDependencies(&self.step);
404 compile.zig_lib_dir = lp.dupe(compile.step.owner);
405 lp.addStepDependencies(&compile.step);
406406 }
407407
408408 if (options.test_runner) |lp| {
409 self.test_runner = lp.dupe(self.step.owner);
410 lp.addStepDependencies(&self.step);
409 compile.test_runner = lp.dupe(compile.step.owner);
410 lp.addStepDependencies(&compile.step);
411411 }
412412
413413 // Only the PE/COFF format has a Resource Table which is where the manifest
414414 // gets embedded, so for any other target the manifest file is just ignored.
415415 if (target.ofmt == .coff) {
416416 if (options.win32_manifest) |lp| {
417 self.win32_manifest = lp.dupe(self.step.owner);
418 lp.addStepDependencies(&self.step);
417 compile.win32_manifest = lp.dupe(compile.step.owner);
418 lp.addStepDependencies(&compile.step);
419419 }
420420 }
421421
422 if (self.kind == .lib) {
423 if (self.linkage != null and self.linkage.? == .static) {
424 self.out_lib_filename = self.out_filename;
425 } else if (self.version) |version| {
422 if (compile.kind == .lib) {
423 if (compile.linkage != null and compile.linkage.? == .static) {
424 compile.out_lib_filename = compile.out_filename;
425 } else if (compile.version) |version| {
426426 if (target.isDarwin()) {
427 self.major_only_filename = owner.fmt("lib{s}.{d}.dylib", .{
428 self.name,
427 compile.major_only_filename = owner.fmt("lib{s}.{d}.dylib", .{
428 compile.name,
429429 version.major,
430430 });
431 self.name_only_filename = owner.fmt("lib{s}.dylib", .{self.name});
432 self.out_lib_filename = self.out_filename;
431 compile.name_only_filename = owner.fmt("lib{s}.dylib", .{compile.name});
432 compile.out_lib_filename = compile.out_filename;
433433 } else if (target.os.tag == .windows) {
434 self.out_lib_filename = owner.fmt("{s}.lib", .{self.name});
434 compile.out_lib_filename = owner.fmt("{s}.lib", .{compile.name});
435435 } else {
436 self.major_only_filename = owner.fmt("lib{s}.so.{d}", .{ self.name, version.major });
437 self.name_only_filename = owner.fmt("lib{s}.so", .{self.name});
438 self.out_lib_filename = self.out_filename;
436 compile.major_only_filename = owner.fmt("lib{s}.so.{d}", .{ compile.name, version.major });
437 compile.name_only_filename = owner.fmt("lib{s}.so", .{compile.name});
438 compile.out_lib_filename = compile.out_filename;
439439 }
440440 } else {
441441 if (target.isDarwin()) {
442 self.out_lib_filename = self.out_filename;
442 compile.out_lib_filename = compile.out_filename;
443443 } else if (target.os.tag == .windows) {
444 self.out_lib_filename = owner.fmt("{s}.lib", .{self.name});
444 compile.out_lib_filename = owner.fmt("{s}.lib", .{compile.name});
445445 } else {
446 self.out_lib_filename = self.out_filename;
446 compile.out_lib_filename = compile.out_filename;
447447 }
448448 }
449449 }
450450
451 return self;
451 return compile;
452452}
453453
454454/// Marks the specified header for installation alongside this artifact.
......@@ -545,38 +545,38 @@ pub fn addObjCopy(cs: *Compile, options: Step.ObjCopy.Options) *Step.ObjCopy {
545545 return b.addObjCopy(cs.getEmittedBin(), copy);
546546}
547547
548pub fn checkObject(self: *Compile) *Step.CheckObject {
549 return Step.CheckObject.create(self.step.owner, self.getEmittedBin(), self.rootModuleTarget().ofmt);
548pub fn checkObject(compile: *Compile) *Step.CheckObject {
549 return Step.CheckObject.create(compile.step.owner, compile.getEmittedBin(), compile.rootModuleTarget().ofmt);
550550}
551551
552552/// deprecated: use `setLinkerScript`
553553pub const setLinkerScriptPath = setLinkerScript;
554554
555pub fn setLinkerScript(self: *Compile, source: LazyPath) void {
556 const b = self.step.owner;
557 self.linker_script = source.dupe(b);
558 source.addStepDependencies(&self.step);
555pub fn setLinkerScript(compile: *Compile, source: LazyPath) void {
556 const b = compile.step.owner;
557 compile.linker_script = source.dupe(b);
558 source.addStepDependencies(&compile.step);
559559}
560560
561pub fn setVersionScript(self: *Compile, source: LazyPath) void {
562 const b = self.step.owner;
563 self.version_script = source.dupe(b);
564 source.addStepDependencies(&self.step);
561pub fn setVersionScript(compile: *Compile, source: LazyPath) void {
562 const b = compile.step.owner;
563 compile.version_script = source.dupe(b);
564 source.addStepDependencies(&compile.step);
565565}
566566
567pub fn forceUndefinedSymbol(self: *Compile, symbol_name: []const u8) void {
568 const b = self.step.owner;
569 self.force_undefined_symbols.put(b.dupe(symbol_name), {}) catch @panic("OOM");
567pub fn forceUndefinedSymbol(compile: *Compile, symbol_name: []const u8) void {
568 const b = compile.step.owner;
569 compile.force_undefined_symbols.put(b.dupe(symbol_name), {}) catch @panic("OOM");
570570}
571571
572572/// Returns whether the library, executable, or object depends on a particular system library.
573573/// Includes transitive dependencies.
574pub fn dependsOnSystemLibrary(self: *const Compile, name: []const u8) bool {
574pub fn dependsOnSystemLibrary(compile: *const Compile, name: []const u8) bool {
575575 var is_linking_libc = false;
576576 var is_linking_libcpp = false;
577577
578 var it = self.root_module.iterateDependencies(self, true);
579 while (it.next()) |module| {
578 var dep_it = compile.root_module.iterateDependencies(compile, true);
579 while (dep_it.next()) |module| {
580580 for (module.link_objects.items) |link_object| {
581581 switch (link_object) {
582582 .system_lib => |lib| if (mem.eql(u8, lib.name, name)) return true,
......@@ -587,31 +587,31 @@ pub fn dependsOnSystemLibrary(self: *const Compile, name: []const u8) bool {
587587 is_linking_libcpp = is_linking_libcpp or module.link_libcpp == true;
588588 }
589589
590 if (self.rootModuleTarget().is_libc_lib_name(name)) {
590 if (compile.rootModuleTarget().is_libc_lib_name(name)) {
591591 return is_linking_libc;
592592 }
593593
594 if (self.rootModuleTarget().is_libcpp_lib_name(name)) {
594 if (compile.rootModuleTarget().is_libcpp_lib_name(name)) {
595595 return is_linking_libcpp;
596596 }
597597
598598 return false;
599599}
600600
601pub fn isDynamicLibrary(self: *const Compile) bool {
602 return self.kind == .lib and self.linkage == .dynamic;
601pub fn isDynamicLibrary(compile: *const Compile) bool {
602 return compile.kind == .lib and compile.linkage == .dynamic;
603603}
604604
605pub fn isStaticLibrary(self: *const Compile) bool {
606 return self.kind == .lib and self.linkage != .dynamic;
605pub fn isStaticLibrary(compile: *const Compile) bool {
606 return compile.kind == .lib and compile.linkage != .dynamic;
607607}
608608
609pub fn isDll(self: *Compile) bool {
610 return self.isDynamicLibrary() and self.rootModuleTarget().os.tag == .windows;
609pub fn isDll(compile: *Compile) bool {
610 return compile.isDynamicLibrary() and compile.rootModuleTarget().os.tag == .windows;
611611}
612612
613pub fn producesPdbFile(self: *Compile) bool {
614 const target = self.rootModuleTarget();
613pub fn producesPdbFile(compile: *Compile) bool {
614 const target = compile.rootModuleTarget();
615615 // TODO: Is this right? Isn't PDB for *any* PE/COFF file?
616616 // TODO: just share this logic with the compiler, silly!
617617 switch (target.os.tag) {
......@@ -619,24 +619,24 @@ pub fn producesPdbFile(self: *Compile) bool {
619619 else => return false,
620620 }
621621 if (target.ofmt == .c) return false;
622 if (self.root_module.strip == true or
623 (self.root_module.strip == null and self.root_module.optimize == .ReleaseSmall))
622 if (compile.root_module.strip == true or
623 (compile.root_module.strip == null and compile.root_module.optimize == .ReleaseSmall))
624624 {
625625 return false;
626626 }
627 return self.isDynamicLibrary() or self.kind == .exe or self.kind == .@"test";
627 return compile.isDynamicLibrary() or compile.kind == .exe or compile.kind == .@"test";
628628}
629629
630pub fn producesImplib(self: *Compile) bool {
631 return self.isDll();
630pub fn producesImplib(compile: *Compile) bool {
631 return compile.isDll();
632632}
633633
634pub fn linkLibC(self: *Compile) void {
635 self.root_module.link_libc = true;
634pub fn linkLibC(compile: *Compile) void {
635 compile.root_module.link_libc = true;
636636}
637637
638pub fn linkLibCpp(self: *Compile) void {
639 self.root_module.link_libcpp = true;
638pub fn linkLibCpp(compile: *Compile) void {
639 compile.root_module.link_libcpp = true;
640640}
641641
642642/// Deprecated. Use `c.root_module.addCMacro`.
......@@ -651,8 +651,8 @@ const PkgConfigResult = struct {
651651
652652/// Run pkg-config for the given library name and parse the output, returning the arguments
653653/// that should be passed to zig to link the given library.
654fn runPkgConfig(self: *Compile, lib_name: []const u8) !PkgConfigResult {
655 const b = self.step.owner;
654fn runPkgConfig(compile: *Compile, lib_name: []const u8) !PkgConfigResult {
655 const b = compile.step.owner;
656656 const pkg_name = match: {
657657 // First we have to map the library name to pkg config name. Unfortunately,
658658 // there are several examples where this is not straightforward:
......@@ -717,30 +717,30 @@ fn runPkgConfig(self: *Compile, lib_name: []const u8) !PkgConfigResult {
717717 var zig_libs = ArrayList([]const u8).init(b.allocator);
718718 defer zig_libs.deinit();
719719
720 var it = mem.tokenizeAny(u8, stdout, " \r\n\t");
721 while (it.next()) |tok| {
722 if (mem.eql(u8, tok, "-I")) {
723 const dir = it.next() orelse return error.PkgConfigInvalidOutput;
720 var arg_it = mem.tokenizeAny(u8, stdout, " \r\n\t");
721 while (arg_it.next()) |arg| {
722 if (mem.eql(u8, arg, "-I")) {
723 const dir = arg_it.next() orelse return error.PkgConfigInvalidOutput;
724724 try zig_cflags.appendSlice(&[_][]const u8{ "-I", dir });
725 } else if (mem.startsWith(u8, tok, "-I")) {
726 try zig_cflags.append(tok);
727 } else if (mem.eql(u8, tok, "-L")) {
728 const dir = it.next() orelse return error.PkgConfigInvalidOutput;
725 } else if (mem.startsWith(u8, arg, "-I")) {
726 try zig_cflags.append(arg);
727 } else if (mem.eql(u8, arg, "-L")) {
728 const dir = arg_it.next() orelse return error.PkgConfigInvalidOutput;
729729 try zig_libs.appendSlice(&[_][]const u8{ "-L", dir });
730 } else if (mem.startsWith(u8, tok, "-L")) {
731 try zig_libs.append(tok);
732 } else if (mem.eql(u8, tok, "-l")) {
733 const lib = it.next() orelse return error.PkgConfigInvalidOutput;
730 } else if (mem.startsWith(u8, arg, "-L")) {
731 try zig_libs.append(arg);
732 } else if (mem.eql(u8, arg, "-l")) {
733 const lib = arg_it.next() orelse return error.PkgConfigInvalidOutput;
734734 try zig_libs.appendSlice(&[_][]const u8{ "-l", lib });
735 } else if (mem.startsWith(u8, tok, "-l")) {
736 try zig_libs.append(tok);
737 } else if (mem.eql(u8, tok, "-D")) {
738 const macro = it.next() orelse return error.PkgConfigInvalidOutput;
735 } else if (mem.startsWith(u8, arg, "-l")) {
736 try zig_libs.append(arg);
737 } else if (mem.eql(u8, arg, "-D")) {
738 const macro = arg_it.next() orelse return error.PkgConfigInvalidOutput;
739739 try zig_cflags.appendSlice(&[_][]const u8{ "-D", macro });
740 } else if (mem.startsWith(u8, tok, "-D")) {
741 try zig_cflags.append(tok);
740 } else if (mem.startsWith(u8, arg, "-D")) {
741 try zig_cflags.append(arg);
742742 } else if (b.debug_pkg_config) {
743 return self.step.fail("unknown pkg-config flag '{s}'", .{tok});
743 return compile.step.fail("unknown pkg-config flag '{s}'", .{arg});
744744 }
745745 }
746746
......@@ -750,16 +750,16 @@ fn runPkgConfig(self: *Compile, lib_name: []const u8) !PkgConfigResult {
750750 };
751751}
752752
753pub fn linkSystemLibrary(self: *Compile, name: []const u8) void {
754 return self.root_module.linkSystemLibrary(name, .{});
753pub fn linkSystemLibrary(compile: *Compile, name: []const u8) void {
754 return compile.root_module.linkSystemLibrary(name, .{});
755755}
756756
757757pub fn linkSystemLibrary2(
758 self: *Compile,
758 compile: *Compile,
759759 name: []const u8,
760760 options: Module.LinkSystemLibraryOptions,
761761) void {
762 return self.root_module.linkSystemLibrary(name, options);
762 return compile.root_module.linkSystemLibrary(name, options);
763763}
764764
765765pub fn linkFramework(c: *Compile, name: []const u8) void {
......@@ -777,155 +777,153 @@ pub fn linkFrameworkWeak(c: *Compile, name: []const u8) void {
777777}
778778
779779/// Handy when you have many C/C++ source files and want them all to have the same flags.
780pub fn addCSourceFiles(self: *Compile, options: Module.AddCSourceFilesOptions) void {
781 self.root_module.addCSourceFiles(options);
780pub fn addCSourceFiles(compile: *Compile, options: Module.AddCSourceFilesOptions) void {
781 compile.root_module.addCSourceFiles(options);
782782}
783783
784pub fn addCSourceFile(self: *Compile, source: Module.CSourceFile) void {
785 self.root_module.addCSourceFile(source);
784pub fn addCSourceFile(compile: *Compile, source: Module.CSourceFile) void {
785 compile.root_module.addCSourceFile(source);
786786}
787787
788788/// Resource files must have the extension `.rc`.
789789/// Can be called regardless of target. The .rc file will be ignored
790790/// if the target object format does not support embedded resources.
791pub fn addWin32ResourceFile(self: *Compile, source: Module.RcSourceFile) void {
792 self.root_module.addWin32ResourceFile(source);
791pub fn addWin32ResourceFile(compile: *Compile, source: Module.RcSourceFile) void {
792 compile.root_module.addWin32ResourceFile(source);
793793}
794794
795pub fn setVerboseLink(self: *Compile, value: bool) void {
796 self.verbose_link = value;
795pub fn setVerboseLink(compile: *Compile, value: bool) void {
796 compile.verbose_link = value;
797797}
798798
799pub fn setVerboseCC(self: *Compile, value: bool) void {
800 self.verbose_cc = value;
799pub fn setVerboseCC(compile: *Compile, value: bool) void {
800 compile.verbose_cc = value;
801801}
802802
803pub fn setLibCFile(self: *Compile, libc_file: ?LazyPath) void {
804 const b = self.step.owner;
805 self.libc_file = if (libc_file) |f| f.dupe(b) else null;
803pub fn setLibCFile(compile: *Compile, libc_file: ?LazyPath) void {
804 const b = compile.step.owner;
805 compile.libc_file = if (libc_file) |f| f.dupe(b) else null;
806806}
807807
808fn getEmittedFileGeneric(self: *Compile, output_file: *?*GeneratedFile) LazyPath {
809 if (output_file.*) |g| {
810 return .{ .generated = g };
811 }
812 const arena = self.step.owner.allocator;
808fn getEmittedFileGeneric(compile: *Compile, output_file: *?*GeneratedFile) LazyPath {
809 if (output_file.*) |file| return .{ .generated = .{ .file = file } };
810 const arena = compile.step.owner.allocator;
813811 const generated_file = arena.create(GeneratedFile) catch @panic("OOM");
814 generated_file.* = .{ .step = &self.step };
812 generated_file.* = .{ .step = &compile.step };
815813 output_file.* = generated_file;
816 return .{ .generated = generated_file };
814 return .{ .generated = .{ .file = generated_file } };
817815}
818816
819817/// Returns the path to the directory that contains the emitted binary file.
820pub fn getEmittedBinDirectory(self: *Compile) LazyPath {
821 _ = self.getEmittedBin();
822 return self.getEmittedFileGeneric(&self.emit_directory);
818pub fn getEmittedBinDirectory(compile: *Compile) LazyPath {
819 _ = compile.getEmittedBin();
820 return compile.getEmittedFileGeneric(&compile.emit_directory);
823821}
824822
825823/// Returns the path to the generated executable, library or object file.
826824/// To run an executable built with zig build, use `run`, or create an install step and invoke it.
827pub fn getEmittedBin(self: *Compile) LazyPath {
828 return self.getEmittedFileGeneric(&self.generated_bin);
825pub fn getEmittedBin(compile: *Compile) LazyPath {
826 return compile.getEmittedFileGeneric(&compile.generated_bin);
829827}
830828
831829/// Returns the path to the generated import library.
832830/// This function can only be called for libraries.
833pub fn getEmittedImplib(self: *Compile) LazyPath {
834 assert(self.kind == .lib);
835 return self.getEmittedFileGeneric(&self.generated_implib);
831pub fn getEmittedImplib(compile: *Compile) LazyPath {
832 assert(compile.kind == .lib);
833 return compile.getEmittedFileGeneric(&compile.generated_implib);
836834}
837835
838836/// Returns the path to the generated header file.
839837/// This function can only be called for libraries or objects.
840pub fn getEmittedH(self: *Compile) LazyPath {
841 assert(self.kind != .exe and self.kind != .@"test");
842 return self.getEmittedFileGeneric(&self.generated_h);
838pub fn getEmittedH(compile: *Compile) LazyPath {
839 assert(compile.kind != .exe and compile.kind != .@"test");
840 return compile.getEmittedFileGeneric(&compile.generated_h);
843841}
844842
845843/// Returns the generated PDB file.
846844/// If the compilation does not produce a PDB file, this causes a FileNotFound error
847845/// at build time.
848pub fn getEmittedPdb(self: *Compile) LazyPath {
849 _ = self.getEmittedBin();
850 return self.getEmittedFileGeneric(&self.generated_pdb);
846pub fn getEmittedPdb(compile: *Compile) LazyPath {
847 _ = compile.getEmittedBin();
848 return compile.getEmittedFileGeneric(&compile.generated_pdb);
851849}
852850
853851/// Returns the path to the generated documentation directory.
854pub fn getEmittedDocs(self: *Compile) LazyPath {
855 return self.getEmittedFileGeneric(&self.generated_docs);
852pub fn getEmittedDocs(compile: *Compile) LazyPath {
853 return compile.getEmittedFileGeneric(&compile.generated_docs);
856854}
857855
858856/// Returns the path to the generated assembly code.
859pub fn getEmittedAsm(self: *Compile) LazyPath {
860 return self.getEmittedFileGeneric(&self.generated_asm);
857pub fn getEmittedAsm(compile: *Compile) LazyPath {
858 return compile.getEmittedFileGeneric(&compile.generated_asm);
861859}
862860
863861/// Returns the path to the generated LLVM IR.
864pub fn getEmittedLlvmIr(self: *Compile) LazyPath {
865 return self.getEmittedFileGeneric(&self.generated_llvm_ir);
862pub fn getEmittedLlvmIr(compile: *Compile) LazyPath {
863 return compile.getEmittedFileGeneric(&compile.generated_llvm_ir);
866864}
867865
868866/// Returns the path to the generated LLVM BC.
869pub fn getEmittedLlvmBc(self: *Compile) LazyPath {
870 return self.getEmittedFileGeneric(&self.generated_llvm_bc);
867pub fn getEmittedLlvmBc(compile: *Compile) LazyPath {
868 return compile.getEmittedFileGeneric(&compile.generated_llvm_bc);
871869}
872870
873pub fn addAssemblyFile(self: *Compile, source: LazyPath) void {
874 self.root_module.addAssemblyFile(source);
871pub fn addAssemblyFile(compile: *Compile, source: LazyPath) void {
872 compile.root_module.addAssemblyFile(source);
875873}
876874
877pub fn addObjectFile(self: *Compile, source: LazyPath) void {
878 self.root_module.addObjectFile(source);
875pub fn addObjectFile(compile: *Compile, source: LazyPath) void {
876 compile.root_module.addObjectFile(source);
879877}
880878
881pub fn addObject(self: *Compile, object: *Compile) void {
882 self.root_module.addObject(object);
879pub fn addObject(compile: *Compile, object: *Compile) void {
880 compile.root_module.addObject(object);
883881}
884882
885pub fn linkLibrary(self: *Compile, library: *Compile) void {
886 self.root_module.linkLibrary(library);
883pub fn linkLibrary(compile: *Compile, library: *Compile) void {
884 compile.root_module.linkLibrary(library);
887885}
888886
889pub fn addAfterIncludePath(self: *Compile, lazy_path: LazyPath) void {
890 self.root_module.addAfterIncludePath(lazy_path);
887pub fn addAfterIncludePath(compile: *Compile, lazy_path: LazyPath) void {
888 compile.root_module.addAfterIncludePath(lazy_path);
891889}
892890
893pub fn addSystemIncludePath(self: *Compile, lazy_path: LazyPath) void {
894 self.root_module.addSystemIncludePath(lazy_path);
891pub fn addSystemIncludePath(compile: *Compile, lazy_path: LazyPath) void {
892 compile.root_module.addSystemIncludePath(lazy_path);
895893}
896894
897pub fn addIncludePath(self: *Compile, lazy_path: LazyPath) void {
898 self.root_module.addIncludePath(lazy_path);
895pub fn addIncludePath(compile: *Compile, lazy_path: LazyPath) void {
896 compile.root_module.addIncludePath(lazy_path);
899897}
900898
901pub fn addConfigHeader(self: *Compile, config_header: *Step.ConfigHeader) void {
902 self.root_module.addConfigHeader(config_header);
899pub fn addConfigHeader(compile: *Compile, config_header: *Step.ConfigHeader) void {
900 compile.root_module.addConfigHeader(config_header);
903901}
904902
905pub fn addLibraryPath(self: *Compile, directory_path: LazyPath) void {
906 self.root_module.addLibraryPath(directory_path);
903pub fn addLibraryPath(compile: *Compile, directory_path: LazyPath) void {
904 compile.root_module.addLibraryPath(directory_path);
907905}
908906
909pub fn addRPath(self: *Compile, directory_path: LazyPath) void {
910 self.root_module.addRPath(directory_path);
907pub fn addRPath(compile: *Compile, directory_path: LazyPath) void {
908 compile.root_module.addRPath(directory_path);
911909}
912910
913pub fn addSystemFrameworkPath(self: *Compile, directory_path: LazyPath) void {
914 self.root_module.addSystemFrameworkPath(directory_path);
911pub fn addSystemFrameworkPath(compile: *Compile, directory_path: LazyPath) void {
912 compile.root_module.addSystemFrameworkPath(directory_path);
915913}
916914
917pub fn addFrameworkPath(self: *Compile, directory_path: LazyPath) void {
918 self.root_module.addFrameworkPath(directory_path);
915pub fn addFrameworkPath(compile: *Compile, directory_path: LazyPath) void {
916 compile.root_module.addFrameworkPath(directory_path);
919917}
920918
921pub fn setExecCmd(self: *Compile, args: []const ?[]const u8) void {
922 const b = self.step.owner;
923 assert(self.kind == .@"test");
919pub fn setExecCmd(compile: *Compile, args: []const ?[]const u8) void {
920 const b = compile.step.owner;
921 assert(compile.kind == .@"test");
924922 const duped_args = b.allocator.alloc(?[]u8, args.len) catch @panic("OOM");
925923 for (args, 0..) |arg, i| {
926924 duped_args[i] = if (arg) |a| b.dupe(a) else null;
927925 }
928 self.exec_cmd_args = duped_args;
926 compile.exec_cmd_args = duped_args;
929927}
930928
931929const CliNamedModules = struct {
......@@ -937,42 +935,42 @@ const CliNamedModules = struct {
937935 /// It will help here to have both a mapping from module to name and a set
938936 /// of all the currently-used names.
939937 fn init(arena: Allocator, root_module: *Module) Allocator.Error!CliNamedModules {
940 var self: CliNamedModules = .{
938 var compile: CliNamedModules = .{
941939 .modules = .{},
942940 .names = .{},
943941 };
944 var it = root_module.iterateDependencies(null, false);
942 var dep_it = root_module.iterateDependencies(null, false);
945943 {
946 const item = it.next().?;
944 const item = dep_it.next().?;
947945 assert(root_module == item.module);
948 try self.modules.put(arena, root_module, {});
949 try self.names.put(arena, "root", {});
946 try compile.modules.put(arena, root_module, {});
947 try compile.names.put(arena, "root", {});
950948 }
951 while (it.next()) |item| {
949 while (dep_it.next()) |item| {
952950 var name = item.name;
953951 var n: usize = 0;
954952 while (true) {
955 const gop = try self.names.getOrPut(arena, name);
953 const gop = try compile.names.getOrPut(arena, name);
956954 if (!gop.found_existing) {
957 try self.modules.putNoClobber(arena, item.module, {});
955 try compile.modules.putNoClobber(arena, item.module, {});
958956 break;
959957 }
960958 name = try std.fmt.allocPrint(arena, "{s}{d}", .{ item.name, n });
961959 n += 1;
962960 }
963961 }
964 return self;
962 return compile;
965963 }
966964};
967965
968fn getGeneratedFilePath(self: *Compile, comptime tag_name: []const u8, asking_step: ?*Step) []const u8 {
969 const maybe_path: ?*GeneratedFile = @field(self, tag_name);
966fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking_step: ?*Step) []const u8 {
967 const maybe_path: ?*GeneratedFile = @field(compile, tag_name);
970968
971969 const generated_file = maybe_path orelse {
972970 std.debug.getStderrMutex().lock();
973971 const stderr = std.io.getStdErr();
974972
975 std.Build.dumpBadGetPathHelp(&self.step, stderr, self.step.owner, asking_step) catch {};
973 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
976974
977975 @panic("missing emit option for " ++ tag_name);
978976 };
......@@ -981,7 +979,7 @@ fn getGeneratedFilePath(self: *Compile, comptime tag_name: []const u8, asking_st
981979 std.debug.getStderrMutex().lock();
982980 const stderr = std.io.getStdErr();
983981
984 std.Build.dumpBadGetPathHelp(&self.step, stderr, self.step.owner, asking_step) catch {};
982 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
985983
986984 @panic(tag_name ++ " is null. Is there a missing step dependency?");
987985 };
......@@ -992,14 +990,14 @@ fn getGeneratedFilePath(self: *Compile, comptime tag_name: []const u8, asking_st
992990fn make(step: *Step, prog_node: *std.Progress.Node) !void {
993991 const b = step.owner;
994992 const arena = b.allocator;
995 const self: *Compile = @fieldParentPtr("step", step);
993 const compile: *Compile = @fieldParentPtr("step", step);
996994
997995 var zig_args = ArrayList([]const u8).init(arena);
998996 defer zig_args.deinit();
999997
1000998 try zig_args.append(b.graph.zig_exe);
1001999
1002 const cmd = switch (self.kind) {
1000 const cmd = switch (compile.kind) {
10031001 .lib => "build-lib",
10041002 .exe => "build-exe",
10051003 .obj => "build-obj",
......@@ -1011,14 +1009,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
10111009 try zig_args.append(try std.fmt.allocPrint(arena, "-freference-trace={d}", .{some}));
10121010 }
10131011
1014 try addFlag(&zig_args, "llvm", self.use_llvm);
1015 try addFlag(&zig_args, "lld", self.use_lld);
1012 try addFlag(&zig_args, "llvm", compile.use_llvm);
1013 try addFlag(&zig_args, "lld", compile.use_lld);
10161014
1017 if (self.root_module.resolved_target.?.query.ofmt) |ofmt| {
1015 if (compile.root_module.resolved_target.?.query.ofmt) |ofmt| {
10181016 try zig_args.append(try std.fmt.allocPrint(arena, "-ofmt={s}", .{@tagName(ofmt)}));
10191017 }
10201018
1021 switch (self.entry) {
1019 switch (compile.entry) {
10221020 .default => {},
10231021 .disabled => try zig_args.append("-fno-entry"),
10241022 .enabled => try zig_args.append("-fentry"),
......@@ -1028,14 +1026,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
10281026 }
10291027
10301028 {
1031 var it = self.force_undefined_symbols.keyIterator();
1032 while (it.next()) |symbol_name| {
1029 var symbol_it = compile.force_undefined_symbols.keyIterator();
1030 while (symbol_it.next()) |symbol_name| {
10331031 try zig_args.append("--force_undefined");
10341032 try zig_args.append(symbol_name.*);
10351033 }
10361034 }
10371035
1038 if (self.stack_size) |stack_size| {
1036 if (compile.stack_size) |stack_size| {
10391037 try zig_args.append("--stack");
10401038 try zig_args.append(try std.fmt.allocPrint(arena, "{}", .{stack_size}));
10411039 }
......@@ -1053,47 +1051,44 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
10531051 var prev_preferred_link_mode: std.builtin.LinkMode = .dynamic;
10541052 // Track the number of positional arguments so that a nice error can be
10551053 // emitted if there is nothing to link.
1056 var total_linker_objects: usize = @intFromBool(self.root_module.root_source_file != null);
1054 var total_linker_objects: usize = @intFromBool(compile.root_module.root_source_file != null);
10571055
10581056 {
10591057 // Fully recursive iteration including dynamic libraries to detect
10601058 // libc and libc++ linkage.
1061 var it = self.root_module.iterateDependencies(self, true);
1062 while (it.next()) |key| {
1063 if (key.module.link_libc == true) self.is_linking_libc = true;
1064 if (key.module.link_libcpp == true) self.is_linking_libcpp = true;
1059 var dep_it = compile.root_module.iterateDependencies(compile, true);
1060 while (dep_it.next()) |key| {
1061 if (key.module.link_libc == true) compile.is_linking_libc = true;
1062 if (key.module.link_libcpp == true) compile.is_linking_libcpp = true;
10651063 }
10661064 }
10671065
1068 var cli_named_modules = try CliNamedModules.init(arena, &self.root_module);
1066 var cli_named_modules = try CliNamedModules.init(arena, &compile.root_module);
10691067
10701068 // For this loop, don't chase dynamic libraries because their link
10711069 // objects are already linked.
1072 var it = self.root_module.iterateDependencies(self, false);
1073
1074 while (it.next()) |key| {
1075 const module = key.module;
1076 const compile = key.compile.?;
1070 var dep_it = compile.root_module.iterateDependencies(compile, false);
10771071
1072 while (dep_it.next()) |dep| {
10781073 // While walking transitive dependencies, if a given link object is
10791074 // already included in a library, it should not redundantly be
10801075 // placed on the linker line of the dependee.
1081 const my_responsibility = compile == self;
1082 const already_linked = !my_responsibility and compile.isDynamicLibrary();
1076 const my_responsibility = dep.compile.? == compile;
1077 const already_linked = !my_responsibility and dep.compile.?.isDynamicLibrary();
10831078
10841079 // Inherit dependencies on darwin frameworks.
10851080 if (!already_linked) {
1086 for (module.frameworks.keys(), module.frameworks.values()) |name, info| {
1081 for (dep.module.frameworks.keys(), dep.module.frameworks.values()) |name, info| {
10871082 try frameworks.put(arena, name, info);
10881083 }
10891084 }
10901085
10911086 // Inherit dependencies on system libraries and static libraries.
1092 for (module.link_objects.items) |link_object| {
1087 for (dep.module.link_objects.items) |link_object| {
10931088 switch (link_object) {
10941089 .static_path => |static_path| {
10951090 if (my_responsibility) {
1096 try zig_args.append(static_path.getPath2(module.owner, step));
1091 try zig_args.append(static_path.getPath2(dep.module.owner, step));
10971092 total_linker_objects += 1;
10981093 }
10991094 },
......@@ -1111,7 +1106,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11111106
11121107 if ((system_lib.search_strategy != prev_search_strategy or
11131108 system_lib.preferred_link_mode != prev_preferred_link_mode) and
1114 self.linkage != .static)
1109 compile.linkage != .static)
11151110 {
11161111 switch (system_lib.search_strategy) {
11171112 .no_fallback => switch (system_lib.preferred_link_mode) {
......@@ -1139,7 +1134,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11391134 switch (system_lib.use_pkg_config) {
11401135 .no => try zig_args.append(b.fmt("{s}{s}", .{ prefix, system_lib.name })),
11411136 .yes, .force => {
1142 if (self.runPkgConfig(system_lib.name)) |result| {
1137 if (compile.runPkgConfig(system_lib.name)) |result| {
11431138 try zig_args.appendSlice(result.cflags);
11441139 try zig_args.appendSlice(result.libs);
11451140 try seen_system_libs.put(arena, system_lib.name, result.cflags);
......@@ -1174,9 +1169,10 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11741169 .exe => return step.fail("cannot link with an executable build artifact", .{}),
11751170 .@"test" => return step.fail("cannot link with a test", .{}),
11761171 .obj => {
1177 const included_in_lib_or_obj = !my_responsibility and (compile.kind == .lib or compile.kind == .obj);
1172 const included_in_lib_or_obj = !my_responsibility and
1173 (dep.compile.?.kind == .lib or dep.compile.?.kind == .obj);
11781174 if (!already_linked and !included_in_lib_or_obj) {
1179 try zig_args.append(other.getEmittedBin().getPath(b));
1175 try zig_args.append(other.getEmittedBin().getPath2(b, step));
11801176 total_linker_objects += 1;
11811177 }
11821178 },
......@@ -1184,7 +1180,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11841180 const other_produces_implib = other.producesImplib();
11851181 const other_is_static = other_produces_implib or other.isStaticLibrary();
11861182
1187 if (self.isStaticLibrary() and other_is_static) {
1183 if (compile.isStaticLibrary() and other_is_static) {
11881184 // Avoid putting a static library inside a static library.
11891185 break :l;
11901186 }
......@@ -1193,15 +1189,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11931189 // For everything else, we directly link
11941190 // against the library file.
11951191 const full_path_lib = if (other_produces_implib)
1196 other.getGeneratedFilePath("generated_implib", &self.step)
1192 other.getGeneratedFilePath("generated_implib", &compile.step)
11971193 else
1198 other.getGeneratedFilePath("generated_bin", &self.step);
1194 other.getGeneratedFilePath("generated_bin", &compile.step);
11991195
12001196 try zig_args.append(full_path_lib);
12011197 total_linker_objects += 1;
12021198
12031199 if (other.linkage == .dynamic and
1204 self.rootModuleTarget().os.tag != .windows)
1200 compile.rootModuleTarget().os.tag != .windows)
12051201 {
12061202 if (fs.path.dirname(full_path_lib)) |dirname| {
12071203 try zig_args.append("-rpath");
......@@ -1219,7 +1215,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12191215 try zig_args.append("--");
12201216 prev_has_cflags = false;
12211217 }
1222 try zig_args.append(asm_file.getPath2(module.owner, step));
1218 try zig_args.append(asm_file.getPath2(dep.module.owner, step));
12231219 total_linker_objects += 1;
12241220 },
12251221
......@@ -1240,7 +1236,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12401236 try zig_args.append("--");
12411237 prev_has_cflags = true;
12421238 }
1243 try zig_args.append(c_source_file.file.getPath2(module.owner, step));
1239 try zig_args.append(c_source_file.file.getPath2(dep.module.owner, step));
12441240 total_linker_objects += 1;
12451241 },
12461242
......@@ -1262,7 +1258,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12621258 prev_has_cflags = true;
12631259 }
12641260
1265 const root_path = c_source_files.root.getPath2(module.owner, step);
1261 const root_path = c_source_files.root.getPath2(dep.module.owner, step);
12661262 for (c_source_files.files) |file| {
12671263 try zig_args.append(b.pathJoin(&.{ root_path, file }));
12681264 }
......@@ -1286,12 +1282,12 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12861282 }
12871283 for (rc_source_file.include_paths) |include_path| {
12881284 try zig_args.append("/I");
1289 try zig_args.append(include_path.getPath2(module.owner, step));
1285 try zig_args.append(include_path.getPath2(dep.module.owner, step));
12901286 }
12911287 try zig_args.append("--");
12921288 prev_has_rcflags = true;
12931289 }
1294 try zig_args.append(rc_source_file.file.getPath2(module.owner, step));
1290 try zig_args.append(rc_source_file.file.getPath2(dep.module.owner, step));
12951291 total_linker_objects += 1;
12961292 },
12971293 }
......@@ -1300,20 +1296,20 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13001296 // We need to emit the --mod argument here so that the above link objects
13011297 // have the correct parent module, but only if the module is part of
13021298 // this compilation.
1303 if (cli_named_modules.modules.getIndex(module)) |module_cli_index| {
1299 if (cli_named_modules.modules.getIndex(dep.module)) |module_cli_index| {
13041300 const module_cli_name = cli_named_modules.names.keys()[module_cli_index];
1305 try module.appendZigProcessFlags(&zig_args, step);
1301 try dep.module.appendZigProcessFlags(&zig_args, step);
13061302
13071303 // --dep arguments
1308 try zig_args.ensureUnusedCapacity(module.import_table.count() * 2);
1309 for (module.import_table.keys(), module.import_table.values()) |name, dep| {
1310 const dep_index = cli_named_modules.modules.getIndex(dep).?;
1311 const dep_cli_name = cli_named_modules.names.keys()[dep_index];
1304 try zig_args.ensureUnusedCapacity(dep.module.import_table.count() * 2);
1305 for (dep.module.import_table.keys(), dep.module.import_table.values()) |name, import| {
1306 const import_index = cli_named_modules.modules.getIndex(import).?;
1307 const import_cli_name = cli_named_modules.names.keys()[import_index];
13121308 zig_args.appendAssumeCapacity("--dep");
1313 if (std.mem.eql(u8, dep_cli_name, name)) {
1314 zig_args.appendAssumeCapacity(dep_cli_name);
1309 if (std.mem.eql(u8, import_cli_name, name)) {
1310 zig_args.appendAssumeCapacity(import_cli_name);
13151311 } else {
1316 zig_args.appendAssumeCapacity(b.fmt("{s}={s}", .{ name, dep_cli_name }));
1312 zig_args.appendAssumeCapacity(b.fmt("{s}={s}", .{ name, import_cli_name }));
13171313 }
13181314 }
13191315
......@@ -1324,10 +1320,10 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13241320 // perhaps a set of linker objects, or C source files instead.
13251321 // Linker objects are added to the CLI globally, while C source
13261322 // files must have a module parent.
1327 if (module.root_source_file) |lp| {
1328 const src = lp.getPath2(module.owner, step);
1323 if (dep.module.root_source_file) |lp| {
1324 const src = lp.getPath2(dep.module.owner, step);
13291325 try zig_args.append(b.fmt("-M{s}={s}", .{ module_cli_name, src }));
1330 } else if (moduleNeedsCliArg(module)) {
1326 } else if (moduleNeedsCliArg(dep.module)) {
13311327 try zig_args.append(b.fmt("-M{s}", .{module_cli_name}));
13321328 }
13331329 }
......@@ -1348,32 +1344,32 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13481344 try zig_args.append(name);
13491345 }
13501346
1351 if (self.is_linking_libcpp) {
1347 if (compile.is_linking_libcpp) {
13521348 try zig_args.append("-lc++");
13531349 }
13541350
1355 if (self.is_linking_libc) {
1351 if (compile.is_linking_libc) {
13561352 try zig_args.append("-lc");
13571353 }
13581354 }
13591355
1360 if (self.win32_manifest) |manifest_file| {
1361 try zig_args.append(manifest_file.getPath(b));
1356 if (compile.win32_manifest) |manifest_file| {
1357 try zig_args.append(manifest_file.getPath2(b, step));
13621358 }
13631359
1364 if (self.image_base) |image_base| {
1360 if (compile.image_base) |image_base| {
13651361 try zig_args.append("--image-base");
13661362 try zig_args.append(b.fmt("0x{x}", .{image_base}));
13671363 }
13681364
1369 for (self.filters) |filter| {
1365 for (compile.filters) |filter| {
13701366 try zig_args.append("--test-filter");
13711367 try zig_args.append(filter);
13721368 }
13731369
1374 if (self.test_runner) |test_runner| {
1370 if (compile.test_runner) |test_runner| {
13751371 try zig_args.append("--test-runner");
1376 try zig_args.append(test_runner.getPath(b));
1372 try zig_args.append(test_runner.getPath2(b, step));
13771373 }
13781374
13791375 for (b.debug_log_scopes) |log_scope| {
......@@ -1389,71 +1385,71 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13891385 if (b.verbose_air) try zig_args.append("--verbose-air");
13901386 if (b.verbose_llvm_ir) |path| try zig_args.append(b.fmt("--verbose-llvm-ir={s}", .{path}));
13911387 if (b.verbose_llvm_bc) |path| try zig_args.append(b.fmt("--verbose-llvm-bc={s}", .{path}));
1392 if (b.verbose_link or self.verbose_link) try zig_args.append("--verbose-link");
1393 if (b.verbose_cc or self.verbose_cc) try zig_args.append("--verbose-cc");
1388 if (b.verbose_link or compile.verbose_link) try zig_args.append("--verbose-link");
1389 if (b.verbose_cc or compile.verbose_cc) try zig_args.append("--verbose-cc");
13941390 if (b.verbose_llvm_cpu_features) try zig_args.append("--verbose-llvm-cpu-features");
13951391
1396 if (self.generated_asm != null) try zig_args.append("-femit-asm");
1397 if (self.generated_bin == null) try zig_args.append("-fno-emit-bin");
1398 if (self.generated_docs != null) try zig_args.append("-femit-docs");
1399 if (self.generated_implib != null) try zig_args.append("-femit-implib");
1400 if (self.generated_llvm_bc != null) try zig_args.append("-femit-llvm-bc");
1401 if (self.generated_llvm_ir != null) try zig_args.append("-femit-llvm-ir");
1402 if (self.generated_h != null) try zig_args.append("-femit-h");
1392 if (compile.generated_asm != null) try zig_args.append("-femit-asm");
1393 if (compile.generated_bin == null) try zig_args.append("-fno-emit-bin");
1394 if (compile.generated_docs != null) try zig_args.append("-femit-docs");
1395 if (compile.generated_implib != null) try zig_args.append("-femit-implib");
1396 if (compile.generated_llvm_bc != null) try zig_args.append("-femit-llvm-bc");
1397 if (compile.generated_llvm_ir != null) try zig_args.append("-femit-llvm-ir");
1398 if (compile.generated_h != null) try zig_args.append("-femit-h");
14031399
1404 try addFlag(&zig_args, "formatted-panics", self.formatted_panics);
1400 try addFlag(&zig_args, "formatted-panics", compile.formatted_panics);
14051401
1406 switch (self.compress_debug_sections) {
1402 switch (compile.compress_debug_sections) {
14071403 .none => {},
14081404 .zlib => try zig_args.append("--compress-debug-sections=zlib"),
14091405 .zstd => try zig_args.append("--compress-debug-sections=zstd"),
14101406 }
14111407
1412 if (self.link_eh_frame_hdr) {
1408 if (compile.link_eh_frame_hdr) {
14131409 try zig_args.append("--eh-frame-hdr");
14141410 }
1415 if (self.link_emit_relocs) {
1411 if (compile.link_emit_relocs) {
14161412 try zig_args.append("--emit-relocs");
14171413 }
1418 if (self.link_function_sections) {
1414 if (compile.link_function_sections) {
14191415 try zig_args.append("-ffunction-sections");
14201416 }
1421 if (self.link_data_sections) {
1417 if (compile.link_data_sections) {
14221418 try zig_args.append("-fdata-sections");
14231419 }
1424 if (self.link_gc_sections) |x| {
1420 if (compile.link_gc_sections) |x| {
14251421 try zig_args.append(if (x) "--gc-sections" else "--no-gc-sections");
14261422 }
1427 if (!self.linker_dynamicbase) {
1423 if (!compile.linker_dynamicbase) {
14281424 try zig_args.append("--no-dynamicbase");
14291425 }
1430 if (self.linker_allow_shlib_undefined) |x| {
1426 if (compile.linker_allow_shlib_undefined) |x| {
14311427 try zig_args.append(if (x) "-fallow-shlib-undefined" else "-fno-allow-shlib-undefined");
14321428 }
1433 if (self.link_z_notext) {
1429 if (compile.link_z_notext) {
14341430 try zig_args.append("-z");
14351431 try zig_args.append("notext");
14361432 }
1437 if (!self.link_z_relro) {
1433 if (!compile.link_z_relro) {
14381434 try zig_args.append("-z");
14391435 try zig_args.append("norelro");
14401436 }
1441 if (self.link_z_lazy) {
1437 if (compile.link_z_lazy) {
14421438 try zig_args.append("-z");
14431439 try zig_args.append("lazy");
14441440 }
1445 if (self.link_z_common_page_size) |size| {
1441 if (compile.link_z_common_page_size) |size| {
14461442 try zig_args.append("-z");
14471443 try zig_args.append(b.fmt("common-page-size={d}", .{size}));
14481444 }
1449 if (self.link_z_max_page_size) |size| {
1445 if (compile.link_z_max_page_size) |size| {
14501446 try zig_args.append("-z");
14511447 try zig_args.append(b.fmt("max-page-size={d}", .{size}));
14521448 }
14531449
1454 if (self.libc_file) |libc_file| {
1450 if (compile.libc_file) |libc_file| {
14551451 try zig_args.append("--libc");
1456 try zig_args.append(libc_file.getPath(b));
1452 try zig_args.append(libc_file.getPath2(b, step));
14571453 } else if (b.libc_file) |libc_file| {
14581454 try zig_args.append("--libc");
14591455 try zig_args.append(libc_file);
......@@ -1466,105 +1462,105 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
14661462 try zig_args.append(b.graph.global_cache_root.path orelse ".");
14671463
14681464 try zig_args.append("--name");
1469 try zig_args.append(self.name);
1465 try zig_args.append(compile.name);
14701466
1471 if (self.linkage) |some| switch (some) {
1467 if (compile.linkage) |some| switch (some) {
14721468 .dynamic => try zig_args.append("-dynamic"),
14731469 .static => try zig_args.append("-static"),
14741470 };
1475 if (self.kind == .lib and self.linkage != null and self.linkage.? == .dynamic) {
1476 if (self.version) |version| {
1471 if (compile.kind == .lib and compile.linkage != null and compile.linkage.? == .dynamic) {
1472 if (compile.version) |version| {
14771473 try zig_args.append("--version");
14781474 try zig_args.append(b.fmt("{}", .{version}));
14791475 }
14801476
1481 if (self.rootModuleTarget().isDarwin()) {
1482 const install_name = self.install_name orelse b.fmt("@rpath/{s}{s}{s}", .{
1483 self.rootModuleTarget().libPrefix(),
1484 self.name,
1485 self.rootModuleTarget().dynamicLibSuffix(),
1477 if (compile.rootModuleTarget().isDarwin()) {
1478 const install_name = compile.install_name orelse b.fmt("@rpath/{s}{s}{s}", .{
1479 compile.rootModuleTarget().libPrefix(),
1480 compile.name,
1481 compile.rootModuleTarget().dynamicLibSuffix(),
14861482 });
14871483 try zig_args.append("-install_name");
14881484 try zig_args.append(install_name);
14891485 }
14901486 }
14911487
1492 if (self.entitlements) |entitlements| {
1488 if (compile.entitlements) |entitlements| {
14931489 try zig_args.appendSlice(&[_][]const u8{ "--entitlements", entitlements });
14941490 }
1495 if (self.pagezero_size) |pagezero_size| {
1491 if (compile.pagezero_size) |pagezero_size| {
14961492 const size = try std.fmt.allocPrint(arena, "{x}", .{pagezero_size});
14971493 try zig_args.appendSlice(&[_][]const u8{ "-pagezero_size", size });
14981494 }
1499 if (self.headerpad_size) |headerpad_size| {
1495 if (compile.headerpad_size) |headerpad_size| {
15001496 const size = try std.fmt.allocPrint(arena, "{x}", .{headerpad_size});
15011497 try zig_args.appendSlice(&[_][]const u8{ "-headerpad", size });
15021498 }
1503 if (self.headerpad_max_install_names) {
1499 if (compile.headerpad_max_install_names) {
15041500 try zig_args.append("-headerpad_max_install_names");
15051501 }
1506 if (self.dead_strip_dylibs) {
1502 if (compile.dead_strip_dylibs) {
15071503 try zig_args.append("-dead_strip_dylibs");
15081504 }
1509 if (self.force_load_objc) {
1505 if (compile.force_load_objc) {
15101506 try zig_args.append("-ObjC");
15111507 }
15121508
1513 try addFlag(&zig_args, "compiler-rt", self.bundle_compiler_rt);
1514 try addFlag(&zig_args, "dll-export-fns", self.dll_export_fns);
1515 if (self.rdynamic) {
1509 try addFlag(&zig_args, "compiler-rt", compile.bundle_compiler_rt);
1510 try addFlag(&zig_args, "dll-export-fns", compile.dll_export_fns);
1511 if (compile.rdynamic) {
15161512 try zig_args.append("-rdynamic");
15171513 }
1518 if (self.import_memory) {
1514 if (compile.import_memory) {
15191515 try zig_args.append("--import-memory");
15201516 }
1521 if (self.export_memory) {
1517 if (compile.export_memory) {
15221518 try zig_args.append("--export-memory");
15231519 }
1524 if (self.import_symbols) {
1520 if (compile.import_symbols) {
15251521 try zig_args.append("--import-symbols");
15261522 }
1527 if (self.import_table) {
1523 if (compile.import_table) {
15281524 try zig_args.append("--import-table");
15291525 }
1530 if (self.export_table) {
1526 if (compile.export_table) {
15311527 try zig_args.append("--export-table");
15321528 }
1533 if (self.initial_memory) |initial_memory| {
1529 if (compile.initial_memory) |initial_memory| {
15341530 try zig_args.append(b.fmt("--initial-memory={d}", .{initial_memory}));
15351531 }
1536 if (self.max_memory) |max_memory| {
1532 if (compile.max_memory) |max_memory| {
15371533 try zig_args.append(b.fmt("--max-memory={d}", .{max_memory}));
15381534 }
1539 if (self.shared_memory) {
1535 if (compile.shared_memory) {
15401536 try zig_args.append("--shared-memory");
15411537 }
1542 if (self.global_base) |global_base| {
1538 if (compile.global_base) |global_base| {
15431539 try zig_args.append(b.fmt("--global-base={d}", .{global_base}));
15441540 }
15451541
1546 if (self.wasi_exec_model) |model| {
1542 if (compile.wasi_exec_model) |model| {
15471543 try zig_args.append(b.fmt("-mexec-model={s}", .{@tagName(model)}));
15481544 }
1549 if (self.linker_script) |linker_script| {
1545 if (compile.linker_script) |linker_script| {
15501546 try zig_args.append("--script");
1551 try zig_args.append(linker_script.getPath(b));
1547 try zig_args.append(linker_script.getPath2(b, step));
15521548 }
15531549
1554 if (self.version_script) |version_script| {
1550 if (compile.version_script) |version_script| {
15551551 try zig_args.append("--version-script");
1556 try zig_args.append(version_script.getPath(b));
1552 try zig_args.append(version_script.getPath2(b, step));
15571553 }
1558 if (self.linker_allow_undefined_version) |x| {
1554 if (compile.linker_allow_undefined_version) |x| {
15591555 try zig_args.append(if (x) "--undefined-version" else "--no-undefined-version");
15601556 }
15611557
1562 if (self.linker_enable_new_dtags) |enabled| {
1558 if (compile.linker_enable_new_dtags) |enabled| {
15631559 try zig_args.append(if (enabled) "--enable-new-dtags" else "--disable-new-dtags");
15641560 }
15651561
1566 if (self.kind == .@"test") {
1567 if (self.exec_cmd_args) |exec_cmd_args| {
1562 if (compile.kind == .@"test") {
1563 if (compile.exec_cmd_args) |exec_cmd_args| {
15681564 for (exec_cmd_args) |cmd_arg| {
15691565 if (cmd_arg) |arg| {
15701566 try zig_args.append("--test-cmd");
......@@ -1595,7 +1591,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
15951591
15961592 if (prefix_dir.accessZ("lib", .{})) |_| {
15971593 try zig_args.appendSlice(&.{
1598 "-L", try fs.path.join(arena, &.{ search_prefix, "lib" }),
1594 "-L", b.pathJoin(&.{ search_prefix, "lib" }),
15991595 });
16001596 } else |err| switch (err) {
16011597 error.FileNotFound => {},
......@@ -1606,7 +1602,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16061602
16071603 if (prefix_dir.accessZ("include", .{})) |_| {
16081604 try zig_args.appendSlice(&.{
1609 "-I", try fs.path.join(arena, &.{ search_prefix, "include" }),
1605 "-I", b.pathJoin(&.{ search_prefix, "include" }),
16101606 });
16111607 } else |err| switch (err) {
16121608 error.FileNotFound => {},
......@@ -1616,14 +1612,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16161612 }
16171613 }
16181614
1619 if (self.rc_includes != .any) {
1615 if (compile.rc_includes != .any) {
16201616 try zig_args.append("-rcincludes");
1621 try zig_args.append(@tagName(self.rc_includes));
1617 try zig_args.append(@tagName(compile.rc_includes));
16221618 }
16231619
1624 try addFlag(&zig_args, "each-lib-rpath", self.each_lib_rpath);
1620 try addFlag(&zig_args, "each-lib-rpath", compile.each_lib_rpath);
16251621
1626 if (self.build_id) |build_id| {
1622 if (compile.build_id) |build_id| {
16271623 try zig_args.append(switch (build_id) {
16281624 .hexstring => |hs| b.fmt("--build-id=0x{s}", .{
16291625 std.fmt.fmtSliceHexLower(hs.toSlice()),
......@@ -1632,15 +1628,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16321628 });
16331629 }
16341630
1635 if (self.zig_lib_dir) |dir| {
1631 if (compile.zig_lib_dir) |dir| {
16361632 try zig_args.append("--zig-lib-dir");
1637 try zig_args.append(dir.getPath(b));
1633 try zig_args.append(dir.getPath2(b, step));
16381634 }
16391635
1640 try addFlag(&zig_args, "PIE", self.pie);
1641 try addFlag(&zig_args, "lto", self.want_lto);
1636 try addFlag(&zig_args, "PIE", compile.pie);
1637 try addFlag(&zig_args, "lto", compile.want_lto);
16421638
1643 if (self.subsystem) |subsystem| {
1639 if (compile.subsystem) |subsystem| {
16441640 try zig_args.append("--subsystem");
16451641 try zig_args.append(switch (subsystem) {
16461642 .Console => "console",
......@@ -1654,11 +1650,11 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16541650 });
16551651 }
16561652
1657 if (self.mingw_unicode_entry_point) {
1653 if (compile.mingw_unicode_entry_point) {
16581654 try zig_args.append("-municode");
16591655 }
16601656
1661 if (self.error_limit) |err_limit| try zig_args.appendSlice(&.{
1657 if (compile.error_limit) |err_limit| try zig_args.appendSlice(&.{
16621658 "--error-limit",
16631659 b.fmt("{}", .{err_limit}),
16641660 });
......@@ -1724,8 +1720,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
17241720
17251721 const maybe_output_bin_path = step.evalZigProcess(zig_args.items, prog_node) catch |err| switch (err) {
17261722 error.NeedCompileErrorCheck => {
1727 assert(self.expect_errors != null);
1728 try checkCompileErrors(self);
1723 assert(compile.expect_errors != null);
1724 try checkCompileErrors(compile);
17291725 return;
17301726 },
17311727 else => |e| return e,
......@@ -1735,61 +1731,61 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
17351731 if (maybe_output_bin_path) |output_bin_path| {
17361732 const output_dir = fs.path.dirname(output_bin_path).?;
17371733
1738 if (self.emit_directory) |lp| {
1734 if (compile.emit_directory) |lp| {
17391735 lp.path = output_dir;
17401736 }
17411737
17421738 // -femit-bin[=path] (default) Output machine code
1743 if (self.generated_bin) |bin| {
1744 bin.path = b.pathJoin(&.{ output_dir, self.out_filename });
1739 if (compile.generated_bin) |bin| {
1740 bin.path = b.pathJoin(&.{ output_dir, compile.out_filename });
17451741 }
17461742
17471743 const sep = std.fs.path.sep;
17481744
17491745 // output PDB if someone requested it
1750 if (self.generated_pdb) |pdb| {
1751 pdb.path = b.fmt("{s}{c}{s}.pdb", .{ output_dir, sep, self.name });
1746 if (compile.generated_pdb) |pdb| {
1747 pdb.path = b.fmt("{s}{c}{s}.pdb", .{ output_dir, sep, compile.name });
17521748 }
17531749
17541750 // -femit-implib[=path] (default) Produce an import .lib when building a Windows DLL
1755 if (self.generated_implib) |implib| {
1756 implib.path = b.fmt("{s}{c}{s}.lib", .{ output_dir, sep, self.name });
1751 if (compile.generated_implib) |implib| {
1752 implib.path = b.fmt("{s}{c}{s}.lib", .{ output_dir, sep, compile.name });
17571753 }
17581754
17591755 // -femit-h[=path] Generate a C header file (.h)
1760 if (self.generated_h) |lp| {
1761 lp.path = b.fmt("{s}{c}{s}.h", .{ output_dir, sep, self.name });
1756 if (compile.generated_h) |lp| {
1757 lp.path = b.fmt("{s}{c}{s}.h", .{ output_dir, sep, compile.name });
17621758 }
17631759
17641760 // -femit-docs[=path] Create a docs/ dir with html documentation
1765 if (self.generated_docs) |generated_docs| {
1761 if (compile.generated_docs) |generated_docs| {
17661762 generated_docs.path = b.pathJoin(&.{ output_dir, "docs" });
17671763 }
17681764
17691765 // -femit-asm[=path] Output .s (assembly code)
1770 if (self.generated_asm) |lp| {
1771 lp.path = b.fmt("{s}{c}{s}.s", .{ output_dir, sep, self.name });
1766 if (compile.generated_asm) |lp| {
1767 lp.path = b.fmt("{s}{c}{s}.s", .{ output_dir, sep, compile.name });
17721768 }
17731769
17741770 // -femit-llvm-ir[=path] Produce a .ll file with optimized LLVM IR (requires LLVM extensions)
1775 if (self.generated_llvm_ir) |lp| {
1776 lp.path = b.fmt("{s}{c}{s}.ll", .{ output_dir, sep, self.name });
1771 if (compile.generated_llvm_ir) |lp| {
1772 lp.path = b.fmt("{s}{c}{s}.ll", .{ output_dir, sep, compile.name });
17771773 }
17781774
17791775 // -femit-llvm-bc[=path] Produce an optimized LLVM module as a .bc file (requires LLVM extensions)
1780 if (self.generated_llvm_bc) |lp| {
1781 lp.path = b.fmt("{s}{c}{s}.bc", .{ output_dir, sep, self.name });
1776 if (compile.generated_llvm_bc) |lp| {
1777 lp.path = b.fmt("{s}{c}{s}.bc", .{ output_dir, sep, compile.name });
17821778 }
17831779 }
17841780
1785 if (self.kind == .lib and self.linkage != null and self.linkage.? == .dynamic and
1786 self.version != null and std.Build.wantSharedLibSymLinks(self.rootModuleTarget()))
1781 if (compile.kind == .lib and compile.linkage != null and compile.linkage.? == .dynamic and
1782 compile.version != null and std.Build.wantSharedLibSymLinks(compile.rootModuleTarget()))
17871783 {
17881784 try doAtomicSymLinks(
17891785 step,
1790 self.getEmittedBin().getPath(b),
1791 self.major_only_filename.?,
1792 self.name_only_filename.?,
1786 compile.getEmittedBin().getPath2(b, step),
1787 compile.major_only_filename.?,
1788 compile.name_only_filename.?,
17931789 );
17941790 }
17951791}
......@@ -1800,18 +1796,19 @@ pub fn doAtomicSymLinks(
18001796 filename_major_only: []const u8,
18011797 filename_name_only: []const u8,
18021798) !void {
1803 const arena = step.owner.allocator;
1799 const b = step.owner;
1800 const arena = b.allocator;
18041801 const out_dir = fs.path.dirname(output_path) orelse ".";
18051802 const out_basename = fs.path.basename(output_path);
18061803 // sym link for libfoo.so.1 to libfoo.so.1.2.3
1807 const major_only_path = try fs.path.join(arena, &.{ out_dir, filename_major_only });
1804 const major_only_path = b.pathJoin(&.{ out_dir, filename_major_only });
18081805 fs.atomicSymLink(arena, out_basename, major_only_path) catch |err| {
18091806 return step.fail("unable to symlink {s} -> {s}: {s}", .{
18101807 major_only_path, out_basename, @errorName(err),
18111808 });
18121809 };
18131810 // sym link for libfoo.so to libfoo.so.1
1814 const name_only_path = try fs.path.join(arena, &.{ out_dir, filename_name_only });
1811 const name_only_path = b.pathJoin(&.{ out_dir, filename_name_only });
18151812 fs.atomicSymLink(arena, filename_major_only, name_only_path) catch |err| {
18161813 return step.fail("Unable to symlink {s} -> {s}: {s}", .{
18171814 name_only_path, filename_major_only, @errorName(err),
......@@ -1819,9 +1816,9 @@ pub fn doAtomicSymLinks(
18191816 };
18201817}
18211818
1822fn execPkgConfigList(self: *std.Build, out_code: *u8) (PkgConfigError || RunError)![]const PkgConfigPkg {
1823 const stdout = try self.runAllowFail(&[_][]const u8{ "pkg-config", "--list-all" }, out_code, .Ignore);
1824 var list = ArrayList(PkgConfigPkg).init(self.allocator);
1819fn execPkgConfigList(compile: *std.Build, out_code: *u8) (PkgConfigError || RunError)![]const PkgConfigPkg {
1820 const stdout = try compile.runAllowFail(&[_][]const u8{ "pkg-config", "--list-all" }, out_code, .Ignore);
1821 var list = ArrayList(PkgConfigPkg).init(compile.allocator);
18251822 errdefer list.deinit();
18261823 var line_it = mem.tokenizeAny(u8, stdout, "\r\n");
18271824 while (line_it.next()) |line| {
......@@ -1835,13 +1832,13 @@ fn execPkgConfigList(self: *std.Build, out_code: *u8) (PkgConfigError || RunErro
18351832 return list.toOwnedSlice();
18361833}
18371834
1838fn getPkgConfigList(self: *std.Build) ![]const PkgConfigPkg {
1839 if (self.pkg_config_pkg_list) |res| {
1835fn getPkgConfigList(compile: *std.Build) ![]const PkgConfigPkg {
1836 if (compile.pkg_config_pkg_list) |res| {
18401837 return res;
18411838 }
18421839 var code: u8 = undefined;
1843 if (execPkgConfigList(self, &code)) |list| {
1844 self.pkg_config_pkg_list = list;
1840 if (execPkgConfigList(compile, &code)) |list| {
1841 compile.pkg_config_pkg_list = list;
18451842 return list;
18461843 } else |err| {
18471844 const result = switch (err) {
......@@ -1853,7 +1850,7 @@ fn getPkgConfigList(self: *std.Build) ![]const PkgConfigPkg {
18531850 error.PkgConfigInvalidOutput => error.PkgConfigInvalidOutput,
18541851 else => return err,
18551852 };
1856 self.pkg_config_pkg_list = result;
1853 compile.pkg_config_pkg_list = result;
18571854 return result;
18581855 }
18591856}
......@@ -1868,12 +1865,12 @@ fn addFlag(args: *ArrayList([]const u8), comptime name: []const u8, opt: ?bool)
18681865 }
18691866}
18701867
1871fn checkCompileErrors(self: *Compile) !void {
1868fn checkCompileErrors(compile: *Compile) !void {
18721869 // Clear this field so that it does not get printed by the build runner.
1873 const actual_eb = self.step.result_error_bundle;
1874 self.step.result_error_bundle = std.zig.ErrorBundle.empty;
1870 const actual_eb = compile.step.result_error_bundle;
1871 compile.step.result_error_bundle = std.zig.ErrorBundle.empty;
18751872
1876 const arena = self.step.owner.allocator;
1873 const arena = compile.step.owner.allocator;
18771874
18781875 var actual_stderr_list = std.ArrayList(u8).init(arena);
18791876 try actual_eb.renderToWriter(.{
......@@ -1885,7 +1882,7 @@ fn checkCompileErrors(self: *Compile) !void {
18851882
18861883 // Render the expected lines into a string that we can compare verbatim.
18871884 var expected_generated = std.ArrayList(u8).init(arena);
1888 const expect_errors = self.expect_errors.?;
1885 const expect_errors = compile.expect_errors.?;
18891886
18901887 var actual_line_it = mem.splitScalar(u8, actual_stderr, '\n');
18911888
......@@ -1897,7 +1894,7 @@ fn checkCompileErrors(self: *Compile) !void {
18971894 return;
18981895 }
18991896
1900 return self.step.fail(
1897 return compile.step.fail(
19011898 \\
19021899 \\========= should contain: ===============
19031900 \\{s}
......@@ -1924,7 +1921,7 @@ fn checkCompileErrors(self: *Compile) !void {
19241921
19251922 if (mem.eql(u8, expected_generated.items, actual_stderr)) return;
19261923
1927 return self.step.fail(
1924 return compile.step.fail(
19281925 \\
19291926 \\========= expected: =====================
19301927 \\{s}
lib/std/Build/Step/ConfigHeader.zig+38-39
......@@ -52,15 +52,14 @@ pub const Options = struct {
5252};
5353
5454pub fn create(owner: *std.Build, options: Options) *ConfigHeader {
55 const self = owner.allocator.create(ConfigHeader) catch @panic("OOM");
55 const config_header = owner.allocator.create(ConfigHeader) catch @panic("OOM");
5656
5757 var include_path: []const u8 = "config.h";
5858
5959 if (options.style.getPath()) |s| default_include_path: {
6060 const sub_path = switch (s) {
6161 .src_path => |sp| sp.sub_path,
62 .path => |path| path,
63 .generated, .generated_dirname => break :default_include_path,
62 .generated => break :default_include_path,
6463 .cwd_relative => |sub_path| sub_path,
6564 .dependency => |dependency| dependency.sub_path,
6665 };
......@@ -81,7 +80,7 @@ pub fn create(owner: *std.Build, options: Options) *ConfigHeader {
8180 else
8281 owner.fmt("configure {s} header to {s}", .{ @tagName(options.style), include_path });
8382
84 self.* = .{
83 config_header.* = .{
8584 .step = Step.init(.{
8685 .id = base_id,
8786 .name = name,
......@@ -95,64 +94,64 @@ pub fn create(owner: *std.Build, options: Options) *ConfigHeader {
9594 .max_bytes = options.max_bytes,
9695 .include_path = include_path,
9796 .include_guard_override = options.include_guard_override,
98 .output_file = .{ .step = &self.step },
97 .output_file = .{ .step = &config_header.step },
9998 };
10099
101 return self;
100 return config_header;
102101}
103102
104pub fn addValues(self: *ConfigHeader, values: anytype) void {
105 return addValuesInner(self, values) catch @panic("OOM");
103pub fn addValues(config_header: *ConfigHeader, values: anytype) void {
104 return addValuesInner(config_header, values) catch @panic("OOM");
106105}
107106
108pub fn getOutput(self: *ConfigHeader) std.Build.LazyPath {
109 return .{ .generated = &self.output_file };
107pub fn getOutput(config_header: *ConfigHeader) std.Build.LazyPath {
108 return .{ .generated = .{ .file = &config_header.output_file } };
110109}
111110
112fn addValuesInner(self: *ConfigHeader, values: anytype) !void {
111fn addValuesInner(config_header: *ConfigHeader, values: anytype) !void {
113112 inline for (@typeInfo(@TypeOf(values)).Struct.fields) |field| {
114 try putValue(self, field.name, field.type, @field(values, field.name));
113 try putValue(config_header, field.name, field.type, @field(values, field.name));
115114 }
116115}
117116
118fn putValue(self: *ConfigHeader, field_name: []const u8, comptime T: type, v: T) !void {
117fn putValue(config_header: *ConfigHeader, field_name: []const u8, comptime T: type, v: T) !void {
119118 switch (@typeInfo(T)) {
120119 .Null => {
121 try self.values.put(field_name, .undef);
120 try config_header.values.put(field_name, .undef);
122121 },
123122 .Void => {
124 try self.values.put(field_name, .defined);
123 try config_header.values.put(field_name, .defined);
125124 },
126125 .Bool => {
127 try self.values.put(field_name, .{ .boolean = v });
126 try config_header.values.put(field_name, .{ .boolean = v });
128127 },
129128 .Int => {
130 try self.values.put(field_name, .{ .int = v });
129 try config_header.values.put(field_name, .{ .int = v });
131130 },
132131 .ComptimeInt => {
133 try self.values.put(field_name, .{ .int = v });
132 try config_header.values.put(field_name, .{ .int = v });
134133 },
135134 .EnumLiteral => {
136 try self.values.put(field_name, .{ .ident = @tagName(v) });
135 try config_header.values.put(field_name, .{ .ident = @tagName(v) });
137136 },
138137 .Optional => {
139138 if (v) |x| {
140 return putValue(self, field_name, @TypeOf(x), x);
139 return putValue(config_header, field_name, @TypeOf(x), x);
141140 } else {
142 try self.values.put(field_name, .undef);
141 try config_header.values.put(field_name, .undef);
143142 }
144143 },
145144 .Pointer => |ptr| {
146145 switch (@typeInfo(ptr.child)) {
147146 .Array => |array| {
148147 if (ptr.size == .One and array.child == u8) {
149 try self.values.put(field_name, .{ .string = v });
148 try config_header.values.put(field_name, .{ .string = v });
150149 return;
151150 }
152151 },
153152 .Int => {
154153 if (ptr.size == .Slice and ptr.child == u8) {
155 try self.values.put(field_name, .{ .string = v });
154 try config_header.values.put(field_name, .{ .string = v });
156155 return;
157156 }
158157 },
......@@ -168,7 +167,7 @@ fn putValue(self: *ConfigHeader, field_name: []const u8, comptime T: type, v: T)
168167fn make(step: *Step, prog_node: *std.Progress.Node) !void {
169168 _ = prog_node;
170169 const b = step.owner;
171 const self: *ConfigHeader = @fieldParentPtr("step", step);
170 const config_header: *ConfigHeader = @fieldParentPtr("step", step);
172171 const gpa = b.allocator;
173172 const arena = b.allocator;
174173
......@@ -179,8 +178,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
179178 // random bytes when ConfigHeader implementation is modified in a
180179 // non-backwards-compatible way.
181180 man.hash.add(@as(u32, 0xdef08d23));
182 man.hash.addBytes(self.include_path);
183 man.hash.addOptionalBytes(self.include_guard_override);
181 man.hash.addBytes(config_header.include_path);
182 man.hash.addOptionalBytes(config_header.include_guard_override);
184183
185184 var output = std.ArrayList(u8).init(gpa);
186185 defer output.deinit();
......@@ -189,34 +188,34 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
189188 const c_generated_line = "/* " ++ header_text ++ " */\n";
190189 const asm_generated_line = "; " ++ header_text ++ "\n";
191190
192 switch (self.style) {
191 switch (config_header.style) {
193192 .autoconf => |file_source| {
194193 try output.appendSlice(c_generated_line);
195 const src_path = file_source.getPath(b);
196 const contents = std.fs.cwd().readFileAlloc(arena, src_path, self.max_bytes) catch |err| {
194 const src_path = file_source.getPath2(b, step);
195 const contents = std.fs.cwd().readFileAlloc(arena, src_path, config_header.max_bytes) catch |err| {
197196 return step.fail("unable to read autoconf input file '{s}': {s}", .{
198197 src_path, @errorName(err),
199198 });
200199 };
201 try render_autoconf(step, contents, &output, self.values, src_path);
200 try render_autoconf(step, contents, &output, config_header.values, src_path);
202201 },
203202 .cmake => |file_source| {
204203 try output.appendSlice(c_generated_line);
205 const src_path = file_source.getPath(b);
206 const contents = std.fs.cwd().readFileAlloc(arena, src_path, self.max_bytes) catch |err| {
204 const src_path = file_source.getPath2(b, step);
205 const contents = std.fs.cwd().readFileAlloc(arena, src_path, config_header.max_bytes) catch |err| {
207206 return step.fail("unable to read cmake input file '{s}': {s}", .{
208207 src_path, @errorName(err),
209208 });
210209 };
211 try render_cmake(step, contents, &output, self.values, src_path);
210 try render_cmake(step, contents, &output, config_header.values, src_path);
212211 },
213212 .blank => {
214213 try output.appendSlice(c_generated_line);
215 try render_blank(&output, self.values, self.include_path, self.include_guard_override);
214 try render_blank(&output, config_header.values, config_header.include_path, config_header.include_guard_override);
216215 },
217216 .nasm => {
218217 try output.appendSlice(asm_generated_line);
219 try render_nasm(&output, self.values);
218 try render_nasm(&output, config_header.values);
220219 },
221220 }
222221
......@@ -224,8 +223,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
224223
225224 if (try step.cacheHit(&man)) {
226225 const digest = man.final();
227 self.output_file.path = try b.cache_root.join(arena, &.{
228 "o", &digest, self.include_path,
226 config_header.output_file.path = try b.cache_root.join(arena, &.{
227 "o", &digest, config_header.include_path,
229228 });
230229 return;
231230 }
......@@ -237,7 +236,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
237236 // output_path is libavutil/avconfig.h
238237 // We want to open directory zig-cache/o/HASH/libavutil/
239238 // but keep output_dir as zig-cache/o/HASH for -I include
240 const sub_path = try std.fs.path.join(arena, &.{ "o", &digest, self.include_path });
239 const sub_path = b.pathJoin(&.{ "o", &digest, config_header.include_path });
241240 const sub_path_dirname = std.fs.path.dirname(sub_path).?;
242241
243242 b.cache_root.handle.makePath(sub_path_dirname) catch |err| {
......@@ -252,7 +251,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
252251 });
253252 };
254253
255 self.output_file.path = try b.cache_root.join(arena, &.{sub_path});
254 config_header.output_file.path = try b.cache_root.join(arena, &.{sub_path});
256255 try man.writeManifest();
257256}
258257
lib/std/Build/Step/Fmt.zig+9-9
......@@ -10,7 +10,7 @@ paths: []const []const u8,
1010exclude_paths: []const []const u8,
1111check: bool,
1212
13pub const base_id = .fmt;
13pub const base_id: Step.Id = .fmt;
1414
1515pub const Options = struct {
1616 paths: []const []const u8 = &.{},
......@@ -20,9 +20,9 @@ pub const Options = struct {
2020};
2121
2222pub fn create(owner: *std.Build, options: Options) *Fmt {
23 const self = owner.allocator.create(Fmt) catch @panic("OOM");
23 const fmt = owner.allocator.create(Fmt) catch @panic("OOM");
2424 const name = if (options.check) "zig fmt --check" else "zig fmt";
25 self.* = .{
25 fmt.* = .{
2626 .step = Step.init(.{
2727 .id = base_id,
2828 .name = name,
......@@ -33,7 +33,7 @@ pub fn create(owner: *std.Build, options: Options) *Fmt {
3333 .exclude_paths = owner.dupeStrings(options.exclude_paths),
3434 .check = options.check,
3535 };
36 return self;
36 return fmt;
3737}
3838
3939fn make(step: *Step, prog_node: *std.Progress.Node) !void {
......@@ -47,23 +47,23 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
4747
4848 const b = step.owner;
4949 const arena = b.allocator;
50 const self: *Fmt = @fieldParentPtr("step", step);
50 const fmt: *Fmt = @fieldParentPtr("step", step);
5151
5252 var argv: std.ArrayListUnmanaged([]const u8) = .{};
53 try argv.ensureUnusedCapacity(arena, 2 + 1 + self.paths.len + 2 * self.exclude_paths.len);
53 try argv.ensureUnusedCapacity(arena, 2 + 1 + fmt.paths.len + 2 * fmt.exclude_paths.len);
5454
5555 argv.appendAssumeCapacity(b.graph.zig_exe);
5656 argv.appendAssumeCapacity("fmt");
5757
58 if (self.check) {
58 if (fmt.check) {
5959 argv.appendAssumeCapacity("--check");
6060 }
6161
62 for (self.paths) |p| {
62 for (fmt.paths) |p| {
6363 argv.appendAssumeCapacity(b.pathFromRoot(p));
6464 }
6565
66 for (self.exclude_paths) |p| {
66 for (fmt.exclude_paths) |p| {
6767 argv.appendAssumeCapacity("--exclude");
6868 argv.appendAssumeCapacity(b.pathFromRoot(p));
6969 }
lib/std/Build/Step/InstallArtifact.zig+22-22
......@@ -29,7 +29,7 @@ const DylibSymlinkInfo = struct {
2929 name_only_filename: []const u8,
3030};
3131
32pub const base_id = .install_artifact;
32pub const base_id: Step.Id = .install_artifact;
3333
3434pub const Options = struct {
3535 /// Which installation directory to put the main output file into.
......@@ -52,7 +52,7 @@ pub const Options = struct {
5252};
5353
5454pub fn create(owner: *std.Build, artifact: *Step.Compile, options: Options) *InstallArtifact {
55 const self = owner.allocator.create(InstallArtifact) catch @panic("OOM");
55 const install_artifact = owner.allocator.create(InstallArtifact) catch @panic("OOM");
5656 const dest_dir: ?InstallDir = switch (options.dest_dir) {
5757 .disabled => null,
5858 .default => switch (artifact.kind) {
......@@ -62,7 +62,7 @@ pub fn create(owner: *std.Build, artifact: *Step.Compile, options: Options) *Ins
6262 },
6363 .override => |o| o,
6464 };
65 self.* = .{
65 install_artifact.* = .{
6666 .step = Step.init(.{
6767 .id = base_id,
6868 .name = owner.fmt("install {s}", .{artifact.name}),
......@@ -104,28 +104,28 @@ pub fn create(owner: *std.Build, artifact: *Step.Compile, options: Options) *Ins
104104 .artifact = artifact,
105105 };
106106
107 self.step.dependOn(&artifact.step);
107 install_artifact.step.dependOn(&artifact.step);
108108
109 if (self.dest_dir != null) self.emitted_bin = artifact.getEmittedBin();
110 if (self.pdb_dir != null) self.emitted_pdb = artifact.getEmittedPdb();
109 if (install_artifact.dest_dir != null) install_artifact.emitted_bin = artifact.getEmittedBin();
110 if (install_artifact.pdb_dir != null) install_artifact.emitted_pdb = artifact.getEmittedPdb();
111111 // https://github.com/ziglang/zig/issues/9698
112 //if (self.h_dir != null) self.emitted_h = artifact.getEmittedH();
113 if (self.implib_dir != null) self.emitted_implib = artifact.getEmittedImplib();
112 //if (install_artifact.h_dir != null) install_artifact.emitted_h = artifact.getEmittedH();
113 if (install_artifact.implib_dir != null) install_artifact.emitted_implib = artifact.getEmittedImplib();
114114
115 return self;
115 return install_artifact;
116116}
117117
118118fn make(step: *Step, prog_node: *std.Progress.Node) !void {
119119 _ = prog_node;
120 const self: *InstallArtifact = @fieldParentPtr("step", step);
120 const install_artifact: *InstallArtifact = @fieldParentPtr("step", step);
121121 const b = step.owner;
122122 const cwd = fs.cwd();
123123
124124 var all_cached = true;
125125
126 if (self.dest_dir) |dest_dir| {
127 const full_dest_path = b.getInstallPath(dest_dir, self.dest_sub_path);
128 const full_src_path = self.emitted_bin.?.getPath2(b, step);
126 if (install_artifact.dest_dir) |dest_dir| {
127 const full_dest_path = b.getInstallPath(dest_dir, install_artifact.dest_sub_path);
128 const full_src_path = install_artifact.emitted_bin.?.getPath2(b, step);
129129 const p = fs.Dir.updateFile(cwd, full_src_path, cwd, full_dest_path, .{}) catch |err| {
130130 return step.fail("unable to update file from '{s}' to '{s}': {s}", .{
131131 full_src_path, full_dest_path, @errorName(err),
......@@ -133,15 +133,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
133133 };
134134 all_cached = all_cached and p == .fresh;
135135
136 if (self.dylib_symlinks) |dls| {
136 if (install_artifact.dylib_symlinks) |dls| {
137137 try Step.Compile.doAtomicSymLinks(step, full_dest_path, dls.major_only_filename, dls.name_only_filename);
138138 }
139139
140 self.artifact.installed_path = full_dest_path;
140 install_artifact.artifact.installed_path = full_dest_path;
141141 }
142142
143 if (self.implib_dir) |implib_dir| {
144 const full_src_path = self.emitted_implib.?.getPath2(b, step);
143 if (install_artifact.implib_dir) |implib_dir| {
144 const full_src_path = install_artifact.emitted_implib.?.getPath2(b, step);
145145 const full_implib_path = b.getInstallPath(implib_dir, fs.path.basename(full_src_path));
146146 const p = fs.Dir.updateFile(cwd, full_src_path, cwd, full_implib_path, .{}) catch |err| {
147147 return step.fail("unable to update file from '{s}' to '{s}': {s}", .{
......@@ -151,8 +151,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
151151 all_cached = all_cached and p == .fresh;
152152 }
153153
154 if (self.pdb_dir) |pdb_dir| {
155 const full_src_path = self.emitted_pdb.?.getPath2(b, step);
154 if (install_artifact.pdb_dir) |pdb_dir| {
155 const full_src_path = install_artifact.emitted_pdb.?.getPath2(b, step);
156156 const full_pdb_path = b.getInstallPath(pdb_dir, fs.path.basename(full_src_path));
157157 const p = fs.Dir.updateFile(cwd, full_src_path, cwd, full_pdb_path, .{}) catch |err| {
158158 return step.fail("unable to update file from '{s}' to '{s}': {s}", .{
......@@ -162,8 +162,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
162162 all_cached = all_cached and p == .fresh;
163163 }
164164
165 if (self.h_dir) |h_dir| {
166 if (self.emitted_h) |emitted_h| {
165 if (install_artifact.h_dir) |h_dir| {
166 if (install_artifact.emitted_h) |emitted_h| {
167167 const full_src_path = emitted_h.getPath2(b, step);
168168 const full_h_path = b.getInstallPath(h_dir, fs.path.basename(full_src_path));
169169 const p = fs.Dir.updateFile(cwd, full_src_path, cwd, full_h_path, .{}) catch |err| {
......@@ -174,7 +174,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
174174 all_cached = all_cached and p == .fresh;
175175 }
176176
177 for (self.artifact.installed_headers.items) |installation| switch (installation) {
177 for (install_artifact.artifact.installed_headers.items) |installation| switch (installation) {
178178 .file => |file| {
179179 const full_src_path = file.source.getPath2(b, step);
180180 const full_h_path = b.getInstallPath(h_dir, file.dest_rel_path);
lib/std/Build/Step/InstallDir.zig+24-25
......@@ -3,17 +3,16 @@ const mem = std.mem;
33const fs = std.fs;
44const Step = std.Build.Step;
55const LazyPath = std.Build.LazyPath;
6const InstallDir = std.Build.InstallDir;
7const InstallDirStep = @This();
6const InstallDir = @This();
87
98step: Step,
109options: Options,
1110
12pub const base_id = .install_dir;
11pub const base_id: Step.Id = .install_dir;
1312
1413pub const Options = struct {
1514 source_dir: LazyPath,
16 install_dir: InstallDir,
15 install_dir: std.Build.InstallDir,
1716 install_subdir: []const u8,
1817 /// File paths which end in any of these suffixes will be excluded
1918 /// from being installed.
......@@ -29,41 +28,41 @@ pub const Options = struct {
2928 /// `@import("test.zig")` would be a compile error.
3029 blank_extensions: []const []const u8 = &.{},
3130
32 fn dupe(self: Options, b: *std.Build) Options {
31 fn dupe(opts: Options, b: *std.Build) Options {
3332 return .{
34 .source_dir = self.source_dir.dupe(b),
35 .install_dir = self.install_dir.dupe(b),
36 .install_subdir = b.dupe(self.install_subdir),
37 .exclude_extensions = b.dupeStrings(self.exclude_extensions),
38 .include_extensions = if (self.include_extensions) |incs| b.dupeStrings(incs) else null,
39 .blank_extensions = b.dupeStrings(self.blank_extensions),
33 .source_dir = opts.source_dir.dupe(b),
34 .install_dir = opts.install_dir.dupe(b),
35 .install_subdir = b.dupe(opts.install_subdir),
36 .exclude_extensions = b.dupeStrings(opts.exclude_extensions),
37 .include_extensions = if (opts.include_extensions) |incs| b.dupeStrings(incs) else null,
38 .blank_extensions = b.dupeStrings(opts.blank_extensions),
4039 };
4140 }
4241};
4342
44pub fn create(owner: *std.Build, options: Options) *InstallDirStep {
43pub fn create(owner: *std.Build, options: Options) *InstallDir {
4544 owner.pushInstalledFile(options.install_dir, options.install_subdir);
46 const self = owner.allocator.create(InstallDirStep) catch @panic("OOM");
47 self.* = .{
45 const install_dir = owner.allocator.create(InstallDir) catch @panic("OOM");
46 install_dir.* = .{
4847 .step = Step.init(.{
49 .id = .install_dir,
48 .id = base_id,
5049 .name = owner.fmt("install {s}/", .{options.source_dir.getDisplayName()}),
5150 .owner = owner,
5251 .makeFn = make,
5352 }),
5453 .options = options.dupe(owner),
5554 };
56 options.source_dir.addStepDependencies(&self.step);
57 return self;
55 options.source_dir.addStepDependencies(&install_dir.step);
56 return install_dir;
5857}
5958
6059fn make(step: *Step, prog_node: *std.Progress.Node) !void {
6160 _ = prog_node;
6261 const b = step.owner;
63 const self: *InstallDirStep = @fieldParentPtr("step", step);
62 const install_dir: *InstallDir = @fieldParentPtr("step", step);
6463 const arena = b.allocator;
65 const dest_prefix = b.getInstallPath(self.options.install_dir, self.options.install_subdir);
66 const src_dir_path = self.options.source_dir.getPath2(b, step);
64 const dest_prefix = b.getInstallPath(install_dir.options.install_dir, install_dir.options.install_subdir);
65 const src_dir_path = install_dir.options.source_dir.getPath2(b, step);
6766 var src_dir = b.build_root.handle.openDir(src_dir_path, .{ .iterate = true }) catch |err| {
6867 return step.fail("unable to open source directory '{}{s}': {s}", .{
6968 b.build_root, src_dir_path, @errorName(err),
......@@ -73,12 +72,12 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
7372 var it = try src_dir.walk(arena);
7473 var all_cached = true;
7574 next_entry: while (try it.next()) |entry| {
76 for (self.options.exclude_extensions) |ext| {
75 for (install_dir.options.exclude_extensions) |ext| {
7776 if (mem.endsWith(u8, entry.path, ext)) {
7877 continue :next_entry;
7978 }
8079 }
81 if (self.options.include_extensions) |incs| {
80 if (install_dir.options.include_extensions) |incs| {
8281 var found = false;
8382 for (incs) |inc| {
8483 if (mem.endsWith(u8, entry.path, inc)) {
......@@ -90,14 +89,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
9089 }
9190
9291 // relative to src build root
93 const src_sub_path = try fs.path.join(arena, &.{ src_dir_path, entry.path });
94 const dest_path = try fs.path.join(arena, &.{ dest_prefix, entry.path });
92 const src_sub_path = b.pathJoin(&.{ src_dir_path, entry.path });
93 const dest_path = b.pathJoin(&.{ dest_prefix, entry.path });
9594 const cwd = fs.cwd();
9695
9796 switch (entry.kind) {
9897 .directory => try cwd.makePath(dest_path),
9998 .file => {
100 for (self.options.blank_extensions) |ext| {
99 for (install_dir.options.blank_extensions) |ext| {
101100 if (mem.endsWith(u8, entry.path, ext)) {
102101 try b.truncateFile(dest_path);
103102 continue :next_entry;
lib/std/Build/Step/InstallFile.zig+8-8
......@@ -5,7 +5,7 @@ const InstallDir = std.Build.InstallDir;
55const InstallFile = @This();
66const assert = std.debug.assert;
77
8pub const base_id = .install_file;
8pub const base_id: Step.Id = .install_file;
99
1010step: Step,
1111source: LazyPath,
......@@ -20,8 +20,8 @@ pub fn create(
2020) *InstallFile {
2121 assert(dest_rel_path.len != 0);
2222 owner.pushInstalledFile(dir, dest_rel_path);
23 const self = owner.allocator.create(InstallFile) catch @panic("OOM");
24 self.* = .{
23 const install_file = owner.allocator.create(InstallFile) catch @panic("OOM");
24 install_file.* = .{
2525 .step = Step.init(.{
2626 .id = base_id,
2727 .name = owner.fmt("install {s} to {s}", .{ source.getDisplayName(), dest_rel_path }),
......@@ -32,16 +32,16 @@ pub fn create(
3232 .dir = dir.dupe(owner),
3333 .dest_rel_path = owner.dupePath(dest_rel_path),
3434 };
35 source.addStepDependencies(&self.step);
36 return self;
35 source.addStepDependencies(&install_file.step);
36 return install_file;
3737}
3838
3939fn make(step: *Step, prog_node: *std.Progress.Node) !void {
4040 _ = prog_node;
4141 const b = step.owner;
42 const self: *InstallFile = @fieldParentPtr("step", step);
43 const full_src_path = self.source.getPath2(b, step);
44 const full_dest_path = b.getInstallPath(self.dir, self.dest_rel_path);
42 const install_file: *InstallFile = @fieldParentPtr("step", step);
43 const full_src_path = install_file.source.getPath2(b, step);
44 const full_dest_path = b.getInstallPath(install_file.dir, install_file.dest_rel_path);
4545 const cwd = std.fs.cwd();
4646 const prev = std.fs.Dir.updateFile(cwd, full_src_path, cwd, full_dest_path, .{}) catch |err| {
4747 return step.fail("unable to update file from '{s}' to '{s}': {s}", .{
lib/std/Build/Step/ObjCopy.zig+32-32
......@@ -58,8 +58,8 @@ pub fn create(
5858 input_file: std.Build.LazyPath,
5959 options: Options,
6060) *ObjCopy {
61 const self = owner.allocator.create(ObjCopy) catch @panic("OOM");
62 self.* = ObjCopy{
61 const objcopy = owner.allocator.create(ObjCopy) catch @panic("OOM");
62 objcopy.* = ObjCopy{
6363 .step = Step.init(.{
6464 .id = base_id,
6565 .name = owner.fmt("objcopy {s}", .{input_file.getDisplayName()}),
......@@ -68,31 +68,31 @@ pub fn create(
6868 }),
6969 .input_file = input_file,
7070 .basename = options.basename orelse input_file.getDisplayName(),
71 .output_file = std.Build.GeneratedFile{ .step = &self.step },
72 .output_file_debug = if (options.strip != .none and options.extract_to_separate_file) std.Build.GeneratedFile{ .step = &self.step } else null,
71 .output_file = std.Build.GeneratedFile{ .step = &objcopy.step },
72 .output_file_debug = if (options.strip != .none and options.extract_to_separate_file) std.Build.GeneratedFile{ .step = &objcopy.step } else null,
7373 .format = options.format,
7474 .only_sections = options.only_sections,
7575 .pad_to = options.pad_to,
7676 .strip = options.strip,
7777 .compress_debug = options.compress_debug,
7878 };
79 input_file.addStepDependencies(&self.step);
80 return self;
79 input_file.addStepDependencies(&objcopy.step);
80 return objcopy;
8181}
8282
8383/// deprecated: use getOutput
8484pub const getOutputSource = getOutput;
8585
86pub fn getOutput(self: *const ObjCopy) std.Build.LazyPath {
87 return .{ .generated = &self.output_file };
86pub fn getOutput(objcopy: *const ObjCopy) std.Build.LazyPath {
87 return .{ .generated = .{ .file = &objcopy.output_file } };
8888}
89pub fn getOutputSeparatedDebug(self: *const ObjCopy) ?std.Build.LazyPath {
90 return if (self.output_file_debug) |*file| .{ .generated = file } else null;
89pub fn getOutputSeparatedDebug(objcopy: *const ObjCopy) ?std.Build.LazyPath {
90 return if (objcopy.output_file_debug) |*file| .{ .generated = .{ .file = file } } else null;
9191}
9292
9393fn make(step: *Step, prog_node: *std.Progress.Node) !void {
9494 const b = step.owner;
95 const self: *ObjCopy = @fieldParentPtr("step", step);
95 const objcopy: *ObjCopy = @fieldParentPtr("step", step);
9696
9797 var man = b.graph.cache.obtain();
9898 defer man.deinit();
......@@ -101,24 +101,24 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
101101 // bytes when ObjCopy implementation is modified incompatibly.
102102 man.hash.add(@as(u32, 0xe18b7baf));
103103
104 const full_src_path = self.input_file.getPath(b);
104 const full_src_path = objcopy.input_file.getPath2(b, step);
105105 _ = try man.addFile(full_src_path, null);
106 man.hash.addOptionalListOfBytes(self.only_sections);
107 man.hash.addOptional(self.pad_to);
108 man.hash.addOptional(self.format);
109 man.hash.add(self.compress_debug);
110 man.hash.add(self.strip);
111 man.hash.add(self.output_file_debug != null);
106 man.hash.addOptionalListOfBytes(objcopy.only_sections);
107 man.hash.addOptional(objcopy.pad_to);
108 man.hash.addOptional(objcopy.format);
109 man.hash.add(objcopy.compress_debug);
110 man.hash.add(objcopy.strip);
111 man.hash.add(objcopy.output_file_debug != null);
112112
113113 if (try step.cacheHit(&man)) {
114114 // Cache hit, skip subprocess execution.
115115 const digest = man.final();
116 self.output_file.path = try b.cache_root.join(b.allocator, &.{
117 "o", &digest, self.basename,
116 objcopy.output_file.path = try b.cache_root.join(b.allocator, &.{
117 "o", &digest, objcopy.basename,
118118 });
119 if (self.output_file_debug) |*file| {
119 if (objcopy.output_file_debug) |*file| {
120120 file.path = try b.cache_root.join(b.allocator, &.{
121 "o", &digest, b.fmt("{s}.debug", .{self.basename}),
121 "o", &digest, b.fmt("{s}.debug", .{objcopy.basename}),
122122 });
123123 }
124124 return;
......@@ -126,8 +126,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
126126
127127 const digest = man.final();
128128 const cache_path = "o" ++ fs.path.sep_str ++ digest;
129 const full_dest_path = try b.cache_root.join(b.allocator, &.{ cache_path, self.basename });
130 const full_dest_path_debug = try b.cache_root.join(b.allocator, &.{ cache_path, b.fmt("{s}.debug", .{self.basename}) });
129 const full_dest_path = try b.cache_root.join(b.allocator, &.{ cache_path, objcopy.basename });
130 const full_dest_path_debug = try b.cache_root.join(b.allocator, &.{ cache_path, b.fmt("{s}.debug", .{objcopy.basename}) });
131131 b.cache_root.handle.makePath(cache_path) catch |err| {
132132 return step.fail("unable to make path {s}: {s}", .{ cache_path, @errorName(err) });
133133 };
......@@ -135,28 +135,28 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
135135 var argv = std.ArrayList([]const u8).init(b.allocator);
136136 try argv.appendSlice(&.{ b.graph.zig_exe, "objcopy" });
137137
138 if (self.only_sections) |only_sections| {
138 if (objcopy.only_sections) |only_sections| {
139139 for (only_sections) |only_section| {
140140 try argv.appendSlice(&.{ "-j", only_section });
141141 }
142142 }
143 switch (self.strip) {
143 switch (objcopy.strip) {
144144 .none => {},
145145 .debug => try argv.appendSlice(&.{"--strip-debug"}),
146146 .debug_and_symbols => try argv.appendSlice(&.{"--strip-all"}),
147147 }
148 if (self.pad_to) |pad_to| {
148 if (objcopy.pad_to) |pad_to| {
149149 try argv.appendSlice(&.{ "--pad-to", b.fmt("{d}", .{pad_to}) });
150150 }
151 if (self.format) |format| switch (format) {
151 if (objcopy.format) |format| switch (format) {
152152 .bin => try argv.appendSlice(&.{ "-O", "binary" }),
153153 .hex => try argv.appendSlice(&.{ "-O", "hex" }),
154154 .elf => try argv.appendSlice(&.{ "-O", "elf" }),
155155 };
156 if (self.compress_debug) {
156 if (objcopy.compress_debug) {
157157 try argv.appendSlice(&.{"--compress-debug-sections"});
158158 }
159 if (self.output_file_debug != null) {
159 if (objcopy.output_file_debug != null) {
160160 try argv.appendSlice(&.{b.fmt("--extract-to={s}", .{full_dest_path_debug})});
161161 }
162162
......@@ -165,7 +165,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
165165 try argv.append("--listen=-");
166166 _ = try step.evalZigProcess(argv.items, prog_node);
167167
168 self.output_file.path = full_dest_path;
169 if (self.output_file_debug) |*file| file.path = full_dest_path_debug;
168 objcopy.output_file.path = full_dest_path;
169 if (objcopy.output_file_debug) |*file| file.path = full_dest_path_debug;
170170 try man.writeManifest();
171171}
lib/std/Build/Step/Options.zig+52-52
......@@ -7,7 +7,7 @@ const LazyPath = std.Build.LazyPath;
77
88const Options = @This();
99
10pub const base_id = .options;
10pub const base_id: Step.Id = .options;
1111
1212step: Step,
1313generated_file: GeneratedFile,
......@@ -17,8 +17,8 @@ args: std.ArrayList(Arg),
1717encountered_types: std.StringHashMap(void),
1818
1919pub fn create(owner: *std.Build) *Options {
20 const self = owner.allocator.create(Options) catch @panic("OOM");
21 self.* = .{
20 const options = owner.allocator.create(Options) catch @panic("OOM");
21 options.* = .{
2222 .step = Step.init(.{
2323 .id = base_id,
2424 .name = "options",
......@@ -30,21 +30,21 @@ pub fn create(owner: *std.Build) *Options {
3030 .args = std.ArrayList(Arg).init(owner.allocator),
3131 .encountered_types = std.StringHashMap(void).init(owner.allocator),
3232 };
33 self.generated_file = .{ .step = &self.step };
33 options.generated_file = .{ .step = &options.step };
3434
35 return self;
35 return options;
3636}
3737
38pub fn addOption(self: *Options, comptime T: type, name: []const u8, value: T) void {
39 return addOptionFallible(self, T, name, value) catch @panic("unhandled error");
38pub fn addOption(options: *Options, comptime T: type, name: []const u8, value: T) void {
39 return addOptionFallible(options, T, name, value) catch @panic("unhandled error");
4040}
4141
42fn addOptionFallible(self: *Options, comptime T: type, name: []const u8, value: T) !void {
43 const out = self.contents.writer();
44 try printType(self, out, T, value, 0, name);
42fn addOptionFallible(options: *Options, comptime T: type, name: []const u8, value: T) !void {
43 const out = options.contents.writer();
44 try printType(options, out, T, value, 0, name);
4545}
4646
47fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u8, name: ?[]const u8) !void {
47fn printType(options: *Options, out: anytype, comptime T: type, value: T, indent: u8, name: ?[]const u8) !void {
4848 switch (T) {
4949 []const []const u8 => {
5050 if (name) |payload| {
......@@ -159,7 +159,7 @@ fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u
159159 try out.print("{s} {{\n", .{@typeName(T)});
160160 for (value) |item| {
161161 try out.writeByteNTimes(' ', indent + 4);
162 try printType(self, out, @TypeOf(item), item, indent + 4, null);
162 try printType(options, out, @TypeOf(item), item, indent + 4, null);
163163 }
164164 try out.writeByteNTimes(' ', indent);
165165 try out.writeAll("}");
......@@ -183,7 +183,7 @@ fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u
183183 try out.print("&[_]{s} {{\n", .{@typeName(p.child)});
184184 for (value) |item| {
185185 try out.writeByteNTimes(' ', indent + 4);
186 try printType(self, out, @TypeOf(item), item, indent + 4, null);
186 try printType(options, out, @TypeOf(item), item, indent + 4, null);
187187 }
188188 try out.writeByteNTimes(' ', indent);
189189 try out.writeAll("}");
......@@ -201,10 +201,10 @@ fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u
201201 }
202202
203203 if (value) |inner| {
204 try printType(self, out, @TypeOf(inner), inner, indent + 4, null);
204 try printType(options, out, @TypeOf(inner), inner, indent + 4, null);
205205 // Pop the '\n' and ',' chars
206 _ = self.contents.pop();
207 _ = self.contents.pop();
206 _ = options.contents.pop();
207 _ = options.contents.pop();
208208 } else {
209209 try out.writeAll("null");
210210 }
......@@ -231,7 +231,7 @@ fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u
231231 return;
232232 },
233233 .Enum => |info| {
234 try printEnum(self, out, T, info, indent);
234 try printEnum(options, out, T, info, indent);
235235
236236 if (name) |some| {
237237 try out.print("pub const {}: {} = .{p_};\n", .{
......@@ -243,14 +243,14 @@ fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u
243243 return;
244244 },
245245 .Struct => |info| {
246 try printStruct(self, out, T, info, indent);
246 try printStruct(options, out, T, info, indent);
247247
248248 if (name) |some| {
249249 try out.print("pub const {}: {} = ", .{
250250 std.zig.fmtId(some),
251251 std.zig.fmtId(@typeName(T)),
252252 });
253 try printStructValue(self, out, info, value, indent);
253 try printStructValue(options, out, info, value, indent);
254254 }
255255 return;
256256 },
......@@ -258,20 +258,20 @@ fn printType(self: *Options, out: anytype, comptime T: type, value: T, indent: u
258258 }
259259}
260260
261fn printUserDefinedType(self: *Options, out: anytype, comptime T: type, indent: u8) !void {
261fn printUserDefinedType(options: *Options, out: anytype, comptime T: type, indent: u8) !void {
262262 switch (@typeInfo(T)) {
263263 .Enum => |info| {
264 return try printEnum(self, out, T, info, indent);
264 return try printEnum(options, out, T, info, indent);
265265 },
266266 .Struct => |info| {
267 return try printStruct(self, out, T, info, indent);
267 return try printStruct(options, out, T, info, indent);
268268 },
269269 else => {},
270270 }
271271}
272272
273fn printEnum(self: *Options, out: anytype, comptime T: type, comptime val: std.builtin.Type.Enum, indent: u8) !void {
274 const gop = try self.encountered_types.getOrPut(@typeName(T));
273fn printEnum(options: *Options, out: anytype, comptime T: type, comptime val: std.builtin.Type.Enum, indent: u8) !void {
274 const gop = try options.encountered_types.getOrPut(@typeName(T));
275275 if (gop.found_existing) return;
276276
277277 try out.writeByteNTimes(' ', indent);
......@@ -291,8 +291,8 @@ fn printEnum(self: *Options, out: anytype, comptime T: type, comptime val: std.b
291291 try out.writeAll("};\n");
292292}
293293
294fn printStruct(self: *Options, out: anytype, comptime T: type, comptime val: std.builtin.Type.Struct, indent: u8) !void {
295 const gop = try self.encountered_types.getOrPut(@typeName(T));
294fn printStruct(options: *Options, out: anytype, comptime T: type, comptime val: std.builtin.Type.Struct, indent: u8) !void {
295 const gop = try options.encountered_types.getOrPut(@typeName(T));
296296 if (gop.found_existing) return;
297297
298298 try out.writeByteNTimes(' ', indent);
......@@ -325,9 +325,9 @@ fn printStruct(self: *Options, out: anytype, comptime T: type, comptime val: std
325325 switch (@typeInfo(@TypeOf(default_value))) {
326326 .Enum => try out.print(".{s},\n", .{@tagName(default_value)}),
327327 .Struct => |info| {
328 try printStructValue(self, out, info, default_value, indent + 4);
328 try printStructValue(options, out, info, default_value, indent + 4);
329329 },
330 else => try printType(self, out, @TypeOf(default_value), default_value, indent, null),
330 else => try printType(options, out, @TypeOf(default_value), default_value, indent, null),
331331 }
332332 } else {
333333 try out.writeAll(",\n");
......@@ -340,17 +340,17 @@ fn printStruct(self: *Options, out: anytype, comptime T: type, comptime val: std
340340 try out.writeAll("};\n");
341341
342342 inline for (val.fields) |field| {
343 try printUserDefinedType(self, out, field.type, 0);
343 try printUserDefinedType(options, out, field.type, 0);
344344 }
345345}
346346
347fn printStructValue(self: *Options, out: anytype, comptime struct_val: std.builtin.Type.Struct, val: anytype, indent: u8) !void {
347fn printStructValue(options: *Options, out: anytype, comptime struct_val: std.builtin.Type.Struct, val: anytype, indent: u8) !void {
348348 try out.writeAll(".{\n");
349349
350350 if (struct_val.is_tuple) {
351351 inline for (struct_val.fields) |field| {
352352 try out.writeByteNTimes(' ', indent);
353 try printType(self, out, @TypeOf(@field(val, field.name)), @field(val, field.name), indent, null);
353 try printType(options, out, @TypeOf(@field(val, field.name)), @field(val, field.name), indent, null);
354354 }
355355 } else {
356356 inline for (struct_val.fields) |field| {
......@@ -361,9 +361,9 @@ fn printStructValue(self: *Options, out: anytype, comptime struct_val: std.built
361361 switch (@typeInfo(@TypeOf(field_name))) {
362362 .Enum => try out.print(".{s},\n", .{@tagName(field_name)}),
363363 .Struct => |struct_info| {
364 try printStructValue(self, out, struct_info, field_name, indent + 4);
364 try printStructValue(options, out, struct_info, field_name, indent + 4);
365365 },
366 else => try printType(self, out, @TypeOf(field_name), field_name, indent, null),
366 else => try printType(options, out, @TypeOf(field_name), field_name, indent, null),
367367 }
368368 }
369369 }
......@@ -379,25 +379,25 @@ fn printStructValue(self: *Options, out: anytype, comptime struct_val: std.built
379379/// The value is the path in the cache dir.
380380/// Adds a dependency automatically.
381381pub fn addOptionPath(
382 self: *Options,
382 options: *Options,
383383 name: []const u8,
384384 path: LazyPath,
385385) void {
386 self.args.append(.{
387 .name = self.step.owner.dupe(name),
388 .path = path.dupe(self.step.owner),
386 options.args.append(.{
387 .name = options.step.owner.dupe(name),
388 .path = path.dupe(options.step.owner),
389389 }) catch @panic("OOM");
390 path.addStepDependencies(&self.step);
390 path.addStepDependencies(&options.step);
391391}
392392
393393/// Deprecated: use `addOptionPath(options, name, artifact.getEmittedBin())` instead.
394pub fn addOptionArtifact(self: *Options, name: []const u8, artifact: *Step.Compile) void {
395 return addOptionPath(self, name, artifact.getEmittedBin());
394pub fn addOptionArtifact(options: *Options, name: []const u8, artifact: *Step.Compile) void {
395 return addOptionPath(options, name, artifact.getEmittedBin());
396396}
397397
398pub fn createModule(self: *Options) *std.Build.Module {
399 return self.step.owner.createModule(.{
400 .root_source_file = self.getOutput(),
398pub fn createModule(options: *Options) *std.Build.Module {
399 return options.step.owner.createModule(.{
400 .root_source_file = options.getOutput(),
401401 });
402402}
403403
......@@ -406,8 +406,8 @@ pub const getSource = getOutput;
406406
407407/// Returns the main artifact of this Build Step which is a Zig source file
408408/// generated from the key-value pairs of the Options.
409pub fn getOutput(self: *Options) LazyPath {
410 return .{ .generated = &self.generated_file };
409pub fn getOutput(options: *Options) LazyPath {
410 return .{ .generated = .{ .file = &options.generated_file } };
411411}
412412
413413fn make(step: *Step, prog_node: *std.Progress.Node) !void {
......@@ -415,13 +415,13 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
415415 _ = prog_node;
416416
417417 const b = step.owner;
418 const self: *Options = @fieldParentPtr("step", step);
418 const options: *Options = @fieldParentPtr("step", step);
419419
420 for (self.args.items) |item| {
421 self.addOption(
420 for (options.args.items) |item| {
421 options.addOption(
422422 []const u8,
423423 item.name,
424 item.path.getPath(b),
424 item.path.getPath2(b, step),
425425 );
426426 }
427427
......@@ -432,10 +432,10 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
432432 // Random bytes to make unique. Refresh this with new random bytes when
433433 // implementation is modified in a non-backwards-compatible way.
434434 hash.add(@as(u32, 0xad95e922));
435 hash.addBytes(self.contents.items);
435 hash.addBytes(options.contents.items);
436436 const sub_path = "c" ++ fs.path.sep_str ++ hash.final() ++ fs.path.sep_str ++ basename;
437437
438 self.generated_file.path = try b.cache_root.join(b.allocator, &.{sub_path});
438 options.generated_file.path = try b.cache_root.join(b.allocator, &.{sub_path});
439439
440440 // Optimize for the hot path. Stat the file, and if it already exists,
441441 // cache hit.
......@@ -464,7 +464,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
464464 });
465465 };
466466
467 b.cache_root.handle.writeFile(.{ .sub_path = tmp_sub_path, .data = self.contents.items }) catch |err| {
467 b.cache_root.handle.writeFile(.{ .sub_path = tmp_sub_path, .data = options.contents.items }) catch |err| {
468468 return step.fail("unable to write options to '{}{s}': {s}", .{
469469 b.cache_root, tmp_sub_path, @errorName(err),
470470 });
lib/std/Build/Step/RemoveDir.zig+9-9
......@@ -3,23 +3,23 @@ const fs = std.fs;
33const Step = std.Build.Step;
44const RemoveDir = @This();
55
6pub const base_id = .remove_dir;
6pub const base_id: Step.Id = .remove_dir;
77
88step: Step,
99dir_path: []const u8,
1010
1111pub fn create(owner: *std.Build, dir_path: []const u8) *RemoveDir {
12 const self = owner.allocator.create(RemoveDir) catch @panic("OOM");
13 self.* = .{
12 const remove_dir = owner.allocator.create(RemoveDir) catch @panic("OOM");
13 remove_dir.* = .{
1414 .step = Step.init(.{
15 .id = .remove_dir,
15 .id = base_id,
1616 .name = owner.fmt("RemoveDir {s}", .{dir_path}),
1717 .owner = owner,
1818 .makeFn = make,
1919 }),
2020 .dir_path = owner.dupePath(dir_path),
2121 };
22 return self;
22 return remove_dir;
2323}
2424
2525fn make(step: *Step, prog_node: *std.Progress.Node) !void {
......@@ -28,16 +28,16 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
2828 _ = prog_node;
2929
3030 const b = step.owner;
31 const self: *RemoveDir = @fieldParentPtr("step", step);
31 const remove_dir: *RemoveDir = @fieldParentPtr("step", step);
3232
33 b.build_root.handle.deleteTree(self.dir_path) catch |err| {
33 b.build_root.handle.deleteTree(remove_dir.dir_path) catch |err| {
3434 if (b.build_root.path) |base| {
3535 return step.fail("unable to recursively delete path '{s}/{s}': {s}", .{
36 base, self.dir_path, @errorName(err),
36 base, remove_dir.dir_path, @errorName(err),
3737 });
3838 } else {
3939 return step.fail("unable to recursively delete path '{s}': {s}", .{
40 self.dir_path, @errorName(err),
40 remove_dir.dir_path, @errorName(err),
4141 });
4242 }
4343 };
lib/std/Build/Step/Run.zig+356-237
......@@ -5,7 +5,6 @@ const Step = Build.Step;
55const fs = std.fs;
66const mem = std.mem;
77const process = std.process;
8const ArrayList = std.ArrayList;
98const EnvMap = process.EnvMap;
109const assert = std.debug.assert;
1110
......@@ -16,7 +15,7 @@ pub const base_id: Step.Id = .run;
1615step: Step,
1716
1817/// See also addArg and addArgs to modifying this directly
19argv: ArrayList(Arg),
18argv: std.ArrayListUnmanaged(Arg),
2019
2120/// Use `setCwd` to set the initial current working directory
2221cwd: ?Build.LazyPath,
......@@ -32,22 +31,26 @@ env_map: ?*EnvMap,
3231/// If the Run step is determined to not have side-effects, then execution will
3332/// be skipped if all output files are up-to-date and input files are
3433/// unchanged.
35stdio: StdIo = .infer_from_args,
34stdio: StdIo,
3635
3736/// This field must be `.none` if stdio is `inherit`.
3837/// It should be only set using `setStdIn`.
39stdin: StdIn = .none,
38stdin: StdIn,
4039
41/// Additional file paths relative to build.zig that, when modified, indicate
42/// that the Run step should be re-executed.
43/// If the Run step is determined to have side-effects, this field is ignored
44/// and the Run step is always executed when it appears in the build graph.
45extra_file_dependencies: []const []const u8 = &.{},
40/// Deprecated: use `addFileInput`
41extra_file_dependencies: []const []const u8,
42
43/// Additional input files that, when modified, indicate that the Run step
44/// should be re-executed.
45/// If the Run step is determined to have side-effects, the Run step is always
46/// executed when it appears in the build graph, regardless of whether these
47/// files have been modified.
48file_inputs: std.ArrayListUnmanaged(std.Build.LazyPath),
4649
4750/// After adding an output argument, this step will by default rename itself
4851/// for a better display name in the build summary.
4952/// This can be disabled by setting this to false.
50rename_step_with_output_arg: bool = true,
53rename_step_with_output_arg: bool,
5154
5255/// If this is true, a Run step which is configured to check the output of the
5356/// executed binary will not fail the build if the binary cannot be executed
......@@ -58,25 +61,25 @@ rename_step_with_output_arg: bool = true,
5861/// Rosetta (macOS) and binfmt_misc (Linux).
5962/// If this Run step is considered to have side-effects, then this flag does
6063/// nothing.
61skip_foreign_checks: bool = false,
64skip_foreign_checks: bool,
6265
6366/// If this is true, failing to execute a foreign binary will be considered an
6467/// error. However if this is false, the step will be skipped on failure instead.
6568///
6669/// This allows for a Run step to attempt to execute a foreign binary using an
6770/// external executor (such as qemu) but not fail if the executor is unavailable.
68failing_to_execute_foreign_is_an_error: bool = true,
71failing_to_execute_foreign_is_an_error: bool,
6972
7073/// If stderr or stdout exceeds this amount, the child process is killed and
7174/// the step fails.
72max_stdio_size: usize = 10 * 1024 * 1024,
75max_stdio_size: usize,
7376
74captured_stdout: ?*Output = null,
75captured_stderr: ?*Output = null,
77captured_stdout: ?*Output,
78captured_stderr: ?*Output,
7679
77dep_output_file: ?*Output = null,
80dep_output_file: ?*Output,
7881
79has_side_effects: bool = false,
82has_side_effects: bool,
8083
8184pub const StdIn = union(enum) {
8285 none,
......@@ -103,7 +106,7 @@ pub const StdIo = union(enum) {
103106 /// conditions.
104107 /// Note that an explicit check for exit code 0 needs to be added to this
105108 /// list if such a check is desirable.
106 check: std.ArrayList(Check),
109 check: std.ArrayListUnmanaged(Check),
107110 /// This Run step is running a zig unit test binary and will communicate
108111 /// extra metadata over the IPC protocol.
109112 zig_test,
......@@ -122,7 +125,8 @@ pub const Arg = union(enum) {
122125 lazy_path: PrefixedLazyPath,
123126 directory_source: PrefixedLazyPath,
124127 bytes: []u8,
125 output: *Output,
128 output_file: *Output,
129 output_directory: *Output,
126130};
127131
128132pub const PrefixedLazyPath = struct {
......@@ -137,35 +141,48 @@ pub const Output = struct {
137141};
138142
139143pub fn create(owner: *std.Build, name: []const u8) *Run {
140 const self = owner.allocator.create(Run) catch @panic("OOM");
141 self.* = .{
144 const run = owner.allocator.create(Run) catch @panic("OOM");
145 run.* = .{
142146 .step = Step.init(.{
143147 .id = base_id,
144148 .name = name,
145149 .owner = owner,
146150 .makeFn = make,
147151 }),
148 .argv = ArrayList(Arg).init(owner.allocator),
152 .argv = .{},
149153 .cwd = null,
150154 .env_map = null,
155 .stdio = .infer_from_args,
156 .stdin = .none,
157 .extra_file_dependencies = &.{},
158 .file_inputs = .{},
159 .rename_step_with_output_arg = true,
160 .skip_foreign_checks = false,
161 .failing_to_execute_foreign_is_an_error = true,
162 .max_stdio_size = 10 * 1024 * 1024,
163 .captured_stdout = null,
164 .captured_stderr = null,
165 .dep_output_file = null,
166 .has_side_effects = false,
151167 };
152 return self;
168 return run;
153169}
154170
155pub fn setName(self: *Run, name: []const u8) void {
156 self.step.name = name;
157 self.rename_step_with_output_arg = false;
171pub fn setName(run: *Run, name: []const u8) void {
172 run.step.name = name;
173 run.rename_step_with_output_arg = false;
158174}
159175
160pub fn enableTestRunnerMode(self: *Run) void {
161 self.stdio = .zig_test;
162 self.addArgs(&.{"--listen=-"});
176pub fn enableTestRunnerMode(run: *Run) void {
177 run.stdio = .zig_test;
178 run.addArgs(&.{"--listen=-"});
163179}
164180
165pub fn addArtifactArg(self: *Run, artifact: *Step.Compile) void {
181pub fn addArtifactArg(run: *Run, artifact: *Step.Compile) void {
182 const b = run.step.owner;
166183 const bin_file = artifact.getEmittedBin();
167 bin_file.addStepDependencies(&self.step);
168 self.argv.append(Arg{ .artifact = artifact }) catch @panic("OOM");
184 bin_file.addStepDependencies(&run.step);
185 run.argv.append(b.allocator, Arg{ .artifact = artifact }) catch @panic("OOM");
169186}
170187
171188/// Provides a file path as a command line argument to the command being run.
......@@ -176,11 +193,12 @@ pub fn addArtifactArg(self: *Run, artifact: *Step.Compile) void {
176193/// Related:
177194/// * `addPrefixedOutputFileArg` - same thing but prepends a string to the argument
178195/// * `addFileArg` - for input files given to the child process
179pub fn addOutputFileArg(self: *Run, basename: []const u8) std.Build.LazyPath {
180 return self.addPrefixedOutputFileArg("", basename);
196pub fn addOutputFileArg(run: *Run, basename: []const u8) std.Build.LazyPath {
197 return run.addPrefixedOutputFileArg("", basename);
181198}
182199
183200/// Provides a file path as a command line argument to the command being run.
201/// Asserts `basename` is not empty.
184202///
185203/// For example, a prefix of "-o" and basename of "output.txt" will result in
186204/// the child process seeing something like this: "-ozig-cache/.../output.txt"
......@@ -195,25 +213,26 @@ pub fn addOutputFileArg(self: *Run, basename: []const u8) std.Build.LazyPath {
195213/// * `addOutputFileArg` - same thing but without the prefix
196214/// * `addFileArg` - for input files given to the child process
197215pub fn addPrefixedOutputFileArg(
198 self: *Run,
216 run: *Run,
199217 prefix: []const u8,
200218 basename: []const u8,
201219) std.Build.LazyPath {
202 const b = self.step.owner;
220 const b = run.step.owner;
221 if (basename.len == 0) @panic("basename must not be empty");
203222
204223 const output = b.allocator.create(Output) catch @panic("OOM");
205224 output.* = .{
206 .prefix = prefix,
207 .basename = basename,
208 .generated_file = .{ .step = &self.step },
225 .prefix = b.dupe(prefix),
226 .basename = b.dupe(basename),
227 .generated_file = .{ .step = &run.step },
209228 };
210 self.argv.append(.{ .output = output }) catch @panic("OOM");
229 run.argv.append(b.allocator, .{ .output_file = output }) catch @panic("OOM");
211230
212 if (self.rename_step_with_output_arg) {
213 self.setName(b.fmt("{s} ({s})", .{ self.step.name, basename }));
231 if (run.rename_step_with_output_arg) {
232 run.setName(b.fmt("{s} ({s})", .{ run.step.name, basename }));
214233 }
215234
216 return .{ .generated = &output.generated_file };
235 return .{ .generated = .{ .file = &output.generated_file } };
217236}
218237
219238/// Appends an input file to the command line arguments.
......@@ -225,8 +244,8 @@ pub fn addPrefixedOutputFileArg(
225244/// Related:
226245/// * `addPrefixedFileArg` - same thing but prepends a string to the argument
227246/// * `addOutputFileArg` - for files generated by the child process
228pub fn addFileArg(self: *Run, lp: std.Build.LazyPath) void {
229 self.addPrefixedFileArg("", lp);
247pub fn addFileArg(run: *Run, lp: std.Build.LazyPath) void {
248 run.addPrefixedFileArg("", lp);
230249}
231250
232251/// Appends an input file to the command line arguments prepended with a string.
......@@ -241,100 +260,148 @@ pub fn addFileArg(self: *Run, lp: std.Build.LazyPath) void {
241260/// Related:
242261/// * `addFileArg` - same thing but without the prefix
243262/// * `addOutputFileArg` - for files generated by the child process
244pub fn addPrefixedFileArg(self: *Run, prefix: []const u8, lp: std.Build.LazyPath) void {
245 const b = self.step.owner;
263pub fn addPrefixedFileArg(run: *Run, prefix: []const u8, lp: std.Build.LazyPath) void {
264 const b = run.step.owner;
246265
247266 const prefixed_file_source: PrefixedLazyPath = .{
248267 .prefix = b.dupe(prefix),
249268 .lazy_path = lp.dupe(b),
250269 };
251 self.argv.append(.{ .lazy_path = prefixed_file_source }) catch @panic("OOM");
252 lp.addStepDependencies(&self.step);
270 run.argv.append(b.allocator, .{ .lazy_path = prefixed_file_source }) catch @panic("OOM");
271 lp.addStepDependencies(&run.step);
272}
273
274/// Provides a directory path as a command line argument to the command being run.
275///
276/// Returns a `std.Build.LazyPath` which can be used as inputs to other APIs
277/// throughout the build system.
278///
279/// Related:
280/// * `addPrefixedOutputDirectoryArg` - same thing but prepends a string to the argument
281/// * `addDirectoryArg` - for input directories given to the child process
282pub fn addOutputDirectoryArg(run: *Run, basename: []const u8) std.Build.LazyPath {
283 return run.addPrefixedOutputDirectoryArg("", basename);
284}
285
286/// Provides a directory path as a command line argument to the command being run.
287/// Asserts `basename` is not empty.
288///
289/// For example, a prefix of "-o" and basename of "output_dir" will result in
290/// the child process seeing something like this: "-ozig-cache/.../output_dir"
291///
292/// The child process will see a single argument, regardless of whether the
293/// prefix or basename have spaces.
294///
295/// The returned `std.Build.LazyPath` can be used as inputs to other APIs
296/// throughout the build system.
297///
298/// Related:
299/// * `addOutputDirectoryArg` - same thing but without the prefix
300/// * `addDirectoryArg` - for input directories given to the child process
301pub fn addPrefixedOutputDirectoryArg(
302 run: *Run,
303 prefix: []const u8,
304 basename: []const u8,
305) std.Build.LazyPath {
306 if (basename.len == 0) @panic("basename must not be empty");
307 const b = run.step.owner;
308
309 const output = b.allocator.create(Output) catch @panic("OOM");
310 output.* = .{
311 .prefix = b.dupe(prefix),
312 .basename = b.dupe(basename),
313 .generated_file = .{ .step = &run.step },
314 };
315 run.argv.append(b.allocator, .{ .output_directory = output }) catch @panic("OOM");
316
317 if (run.rename_step_with_output_arg) {
318 run.setName(b.fmt("{s} ({s})", .{ run.step.name, basename }));
319 }
320
321 return .{ .generated = .{ .file = &output.generated_file } };
253322}
254323
255324/// deprecated: use `addDirectoryArg`
256325pub const addDirectorySourceArg = addDirectoryArg;
257326
258pub fn addDirectoryArg(self: *Run, directory_source: std.Build.LazyPath) void {
259 self.addPrefixedDirectoryArg("", directory_source);
327pub fn addDirectoryArg(run: *Run, directory_source: std.Build.LazyPath) void {
328 run.addPrefixedDirectoryArg("", directory_source);
260329}
261330
262331// deprecated: use `addPrefixedDirectoryArg`
263332pub const addPrefixedDirectorySourceArg = addPrefixedDirectoryArg;
264333
265pub fn addPrefixedDirectoryArg(self: *Run, prefix: []const u8, directory_source: std.Build.LazyPath) void {
266 const b = self.step.owner;
334pub fn addPrefixedDirectoryArg(run: *Run, prefix: []const u8, directory_source: std.Build.LazyPath) void {
335 const b = run.step.owner;
267336
268337 const prefixed_directory_source: PrefixedLazyPath = .{
269338 .prefix = b.dupe(prefix),
270339 .lazy_path = directory_source.dupe(b),
271340 };
272 self.argv.append(.{ .directory_source = prefixed_directory_source }) catch @panic("OOM");
273 directory_source.addStepDependencies(&self.step);
341 run.argv.append(b.allocator, .{ .directory_source = prefixed_directory_source }) catch @panic("OOM");
342 directory_source.addStepDependencies(&run.step);
274343}
275344
276345/// Add a path argument to a dep file (.d) for the child process to write its
277346/// discovered additional dependencies.
278347/// Only one dep file argument is allowed by instance.
279pub fn addDepFileOutputArg(self: *Run, basename: []const u8) std.Build.LazyPath {
280 return self.addPrefixedDepFileOutputArg("", basename);
348pub fn addDepFileOutputArg(run: *Run, basename: []const u8) std.Build.LazyPath {
349 return run.addPrefixedDepFileOutputArg("", basename);
281350}
282351
283352/// Add a prefixed path argument to a dep file (.d) for the child process to
284353/// write its discovered additional dependencies.
285354/// Only one dep file argument is allowed by instance.
286pub fn addPrefixedDepFileOutputArg(self: *Run, prefix: []const u8, basename: []const u8) std.Build.LazyPath {
287 assert(self.dep_output_file == null);
288
289 const b = self.step.owner;
355pub fn addPrefixedDepFileOutputArg(run: *Run, prefix: []const u8, basename: []const u8) std.Build.LazyPath {
356 const b = run.step.owner;
357 assert(run.dep_output_file == null);
290358
291359 const dep_file = b.allocator.create(Output) catch @panic("OOM");
292360 dep_file.* = .{
293361 .prefix = b.dupe(prefix),
294362 .basename = b.dupe(basename),
295 .generated_file = .{ .step = &self.step },
363 .generated_file = .{ .step = &run.step },
296364 };
297365
298 self.dep_output_file = dep_file;
366 run.dep_output_file = dep_file;
299367
300 self.argv.append(.{ .output = dep_file }) catch @panic("OOM");
368 run.argv.append(b.allocator, .{ .output_file = dep_file }) catch @panic("OOM");
301369
302 return .{ .generated = &dep_file.generated_file };
370 return .{ .generated = .{ .file = &dep_file.generated_file } };
303371}
304372
305pub fn addArg(self: *Run, arg: []const u8) void {
306 self.argv.append(.{ .bytes = self.step.owner.dupe(arg) }) catch @panic("OOM");
373pub fn addArg(run: *Run, arg: []const u8) void {
374 const b = run.step.owner;
375 run.argv.append(b.allocator, .{ .bytes = b.dupe(arg) }) catch @panic("OOM");
307376}
308377
309pub fn addArgs(self: *Run, args: []const []const u8) void {
310 for (args) |arg| {
311 self.addArg(arg);
312 }
378pub fn addArgs(run: *Run, args: []const []const u8) void {
379 for (args) |arg| run.addArg(arg);
313380}
314381
315pub fn setStdIn(self: *Run, stdin: StdIn) void {
382pub fn setStdIn(run: *Run, stdin: StdIn) void {
316383 switch (stdin) {
317 .lazy_path => |lazy_path| lazy_path.addStepDependencies(&self.step),
384 .lazy_path => |lazy_path| lazy_path.addStepDependencies(&run.step),
318385 .bytes, .none => {},
319386 }
320 self.stdin = stdin;
387 run.stdin = stdin;
321388}
322389
323pub fn setCwd(self: *Run, cwd: Build.LazyPath) void {
324 cwd.addStepDependencies(&self.step);
325 self.cwd = cwd;
390pub fn setCwd(run: *Run, cwd: Build.LazyPath) void {
391 cwd.addStepDependencies(&run.step);
392 run.cwd = cwd.dupe(run.step.owner);
326393}
327394
328pub fn clearEnvironment(self: *Run) void {
329 const b = self.step.owner;
395pub fn clearEnvironment(run: *Run) void {
396 const b = run.step.owner;
330397 const new_env_map = b.allocator.create(EnvMap) catch @panic("OOM");
331398 new_env_map.* = EnvMap.init(b.allocator);
332 self.env_map = new_env_map;
399 run.env_map = new_env_map;
333400}
334401
335pub fn addPathDir(self: *Run, search_path: []const u8) void {
336 const b = self.step.owner;
337 const env_map = getEnvMapInternal(self);
402pub fn addPathDir(run: *Run, search_path: []const u8) void {
403 const b = run.step.owner;
404 const env_map = getEnvMapInternal(run);
338405
339406 const key = "PATH";
340407 const prev_path = env_map.get(key);
......@@ -347,116 +414,128 @@ pub fn addPathDir(self: *Run, search_path: []const u8) void {
347414 }
348415}
349416
350pub fn getEnvMap(self: *Run) *EnvMap {
351 return getEnvMapInternal(self);
417pub fn getEnvMap(run: *Run) *EnvMap {
418 return getEnvMapInternal(run);
352419}
353420
354fn getEnvMapInternal(self: *Run) *EnvMap {
355 const arena = self.step.owner.allocator;
356 return self.env_map orelse {
421fn getEnvMapInternal(run: *Run) *EnvMap {
422 const arena = run.step.owner.allocator;
423 return run.env_map orelse {
357424 const env_map = arena.create(EnvMap) catch @panic("OOM");
358425 env_map.* = process.getEnvMap(arena) catch @panic("unhandled error");
359 self.env_map = env_map;
426 run.env_map = env_map;
360427 return env_map;
361428 };
362429}
363430
364pub fn setEnvironmentVariable(self: *Run, key: []const u8, value: []const u8) void {
365 const b = self.step.owner;
366 const env_map = self.getEnvMap();
431pub fn setEnvironmentVariable(run: *Run, key: []const u8, value: []const u8) void {
432 const b = run.step.owner;
433 const env_map = run.getEnvMap();
367434 env_map.put(b.dupe(key), b.dupe(value)) catch @panic("unhandled error");
368435}
369436
370pub fn removeEnvironmentVariable(self: *Run, key: []const u8) void {
371 self.getEnvMap().remove(key);
437pub fn removeEnvironmentVariable(run: *Run, key: []const u8) void {
438 run.getEnvMap().remove(key);
372439}
373440
374441/// Adds a check for exact stderr match. Does not add any other checks.
375pub fn expectStdErrEqual(self: *Run, bytes: []const u8) void {
376 const new_check: StdIo.Check = .{ .expect_stderr_exact = self.step.owner.dupe(bytes) };
377 self.addCheck(new_check);
442pub fn expectStdErrEqual(run: *Run, bytes: []const u8) void {
443 const new_check: StdIo.Check = .{ .expect_stderr_exact = run.step.owner.dupe(bytes) };
444 run.addCheck(new_check);
378445}
379446
380447/// Adds a check for exact stdout match as well as a check for exit code 0, if
381448/// there is not already an expected termination check.
382pub fn expectStdOutEqual(self: *Run, bytes: []const u8) void {
383 const new_check: StdIo.Check = .{ .expect_stdout_exact = self.step.owner.dupe(bytes) };
384 self.addCheck(new_check);
385 if (!self.hasTermCheck()) {
386 self.expectExitCode(0);
449pub fn expectStdOutEqual(run: *Run, bytes: []const u8) void {
450 const new_check: StdIo.Check = .{ .expect_stdout_exact = run.step.owner.dupe(bytes) };
451 run.addCheck(new_check);
452 if (!run.hasTermCheck()) {
453 run.expectExitCode(0);
387454 }
388455}
389456
390pub fn expectExitCode(self: *Run, code: u8) void {
457pub fn expectExitCode(run: *Run, code: u8) void {
391458 const new_check: StdIo.Check = .{ .expect_term = .{ .Exited = code } };
392 self.addCheck(new_check);
459 run.addCheck(new_check);
393460}
394461
395pub fn hasTermCheck(self: Run) bool {
396 for (self.stdio.check.items) |check| switch (check) {
462pub fn hasTermCheck(run: Run) bool {
463 for (run.stdio.check.items) |check| switch (check) {
397464 .expect_term => return true,
398465 else => continue,
399466 };
400467 return false;
401468}
402469
403pub fn addCheck(self: *Run, new_check: StdIo.Check) void {
404 switch (self.stdio) {
470pub fn addCheck(run: *Run, new_check: StdIo.Check) void {
471 const b = run.step.owner;
472
473 switch (run.stdio) {
405474 .infer_from_args => {
406 self.stdio = .{ .check = std.ArrayList(StdIo.Check).init(self.step.owner.allocator) };
407 self.stdio.check.append(new_check) catch @panic("OOM");
475 run.stdio = .{ .check = .{} };
476 run.stdio.check.append(b.allocator, new_check) catch @panic("OOM");
408477 },
409 .check => |*checks| checks.append(new_check) catch @panic("OOM"),
478 .check => |*checks| checks.append(b.allocator, new_check) catch @panic("OOM"),
410479 else => @panic("illegal call to addCheck: conflicting helper method calls. Suggest to directly set stdio field of Run instead"),
411480 }
412481}
413482
414pub fn captureStdErr(self: *Run) std.Build.LazyPath {
415 assert(self.stdio != .inherit);
483pub fn captureStdErr(run: *Run) std.Build.LazyPath {
484 assert(run.stdio != .inherit);
416485
417 if (self.captured_stderr) |output| return .{ .generated = &output.generated_file };
486 if (run.captured_stderr) |output| return .{ .generated = .{ .file = &output.generated_file } };
418487
419 const output = self.step.owner.allocator.create(Output) catch @panic("OOM");
488 const output = run.step.owner.allocator.create(Output) catch @panic("OOM");
420489 output.* = .{
421490 .prefix = "",
422491 .basename = "stderr",
423 .generated_file = .{ .step = &self.step },
492 .generated_file = .{ .step = &run.step },
424493 };
425 self.captured_stderr = output;
426 return .{ .generated = &output.generated_file };
494 run.captured_stderr = output;
495 return .{ .generated = .{ .file = &output.generated_file } };
427496}
428497
429pub fn captureStdOut(self: *Run) std.Build.LazyPath {
430 assert(self.stdio != .inherit);
498pub fn captureStdOut(run: *Run) std.Build.LazyPath {
499 assert(run.stdio != .inherit);
431500
432 if (self.captured_stdout) |output| return .{ .generated = &output.generated_file };
501 if (run.captured_stdout) |output| return .{ .generated = .{ .file = &output.generated_file } };
433502
434 const output = self.step.owner.allocator.create(Output) catch @panic("OOM");
503 const output = run.step.owner.allocator.create(Output) catch @panic("OOM");
435504 output.* = .{
436505 .prefix = "",
437506 .basename = "stdout",
438 .generated_file = .{ .step = &self.step },
507 .generated_file = .{ .step = &run.step },
439508 };
440 self.captured_stdout = output;
441 return .{ .generated = &output.generated_file };
509 run.captured_stdout = output;
510 return .{ .generated = .{ .file = &output.generated_file } };
511}
512
513/// Adds an additional input files that, when modified, indicates that this Run
514/// step should be re-executed.
515/// If the Run step is determined to have side-effects, the Run step is always
516/// executed when it appears in the build graph, regardless of whether this
517/// file has been modified.
518pub fn addFileInput(self: *Run, file_input: std.Build.LazyPath) void {
519 file_input.addStepDependencies(&self.step);
520 self.file_inputs.append(self.step.owner.allocator, file_input.dupe(self.step.owner)) catch @panic("OOM");
442521}
443522
444523/// Returns whether the Run step has side effects *other than* updating the output arguments.
445fn hasSideEffects(self: Run) bool {
446 if (self.has_side_effects) return true;
447 return switch (self.stdio) {
448 .infer_from_args => !self.hasAnyOutputArgs(),
524fn hasSideEffects(run: Run) bool {
525 if (run.has_side_effects) return true;
526 return switch (run.stdio) {
527 .infer_from_args => !run.hasAnyOutputArgs(),
449528 .inherit => true,
450529 .check => false,
451530 .zig_test => false,
452531 };
453532}
454533
455fn hasAnyOutputArgs(self: Run) bool {
456 if (self.captured_stdout != null) return true;
457 if (self.captured_stderr != null) return true;
458 for (self.argv.items) |arg| switch (arg) {
459 .output => return true,
534fn hasAnyOutputArgs(run: Run) bool {
535 if (run.captured_stdout != null) return true;
536 if (run.captured_stderr != null) return true;
537 for (run.argv.items) |arg| switch (arg) {
538 .output_file, .output_directory => return true,
460539 else => continue,
461540 };
462541 return false;
......@@ -492,34 +571,35 @@ fn checksContainStderr(checks: []const StdIo.Check) bool {
492571
493572const IndexedOutput = struct {
494573 index: usize,
574 tag: @typeInfo(Arg).Union.tag_type.?,
495575 output: *Output,
496576};
497577fn make(step: *Step, prog_node: *std.Progress.Node) !void {
498578 const b = step.owner;
499579 const arena = b.allocator;
500 const self: *Run = @fieldParentPtr("step", step);
501 const has_side_effects = self.hasSideEffects();
580 const run: *Run = @fieldParentPtr("step", step);
581 const has_side_effects = run.hasSideEffects();
502582
503 var argv_list = ArrayList([]const u8).init(arena);
504 var output_placeholders = ArrayList(IndexedOutput).init(arena);
583 var argv_list = std.ArrayList([]const u8).init(arena);
584 var output_placeholders = std.ArrayList(IndexedOutput).init(arena);
505585
506586 var man = b.graph.cache.obtain();
507587 defer man.deinit();
508588
509 for (self.argv.items) |arg| {
589 for (run.argv.items) |arg| {
510590 switch (arg) {
511591 .bytes => |bytes| {
512592 try argv_list.append(bytes);
513593 man.hash.addBytes(bytes);
514594 },
515595 .lazy_path => |file| {
516 const file_path = file.lazy_path.getPath(b);
596 const file_path = file.lazy_path.getPath2(b, step);
517597 try argv_list.append(b.fmt("{s}{s}", .{ file.prefix, file_path }));
518598 man.hash.addBytes(file.prefix);
519599 _ = try man.addFile(file_path, null);
520600 },
521601 .directory_source => |file| {
522 const file_path = file.lazy_path.getPath(b);
602 const file_path = file.lazy_path.getPath2(b, step);
523603 try argv_list.append(b.fmt("{s}{s}", .{ file.prefix, file_path }));
524604 man.hash.addBytes(file.prefix);
525605 man.hash.addBytes(file_path);
......@@ -527,7 +607,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
527607 .artifact => |artifact| {
528608 if (artifact.rootModuleTarget().os.tag == .windows) {
529609 // On Windows we don't have rpaths so we have to add .dll search paths to PATH
530 self.addPathForDynLibs(artifact);
610 run.addPathForDynLibs(artifact);
531611 }
532612 const file_path = artifact.installed_path orelse artifact.generated_bin.?.path.?; // the path is guaranteed to be set
533613
......@@ -535,60 +615,59 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
535615
536616 _ = try man.addFile(file_path, null);
537617 },
538 .output => |output| {
618 .output_file, .output_directory => |output| {
539619 man.hash.addBytes(output.prefix);
540620 man.hash.addBytes(output.basename);
541621 // Add a placeholder into the argument list because we need the
542622 // manifest hash to be updated with all arguments before the
543623 // object directory is computed.
544 try argv_list.append("");
545624 try output_placeholders.append(.{
546 .index = argv_list.items.len - 1,
625 .index = argv_list.items.len,
626 .tag = arg,
547627 .output = output,
548628 });
629 _ = try argv_list.addOne();
549630 },
550631 }
551632 }
552633
553 switch (self.stdin) {
634 switch (run.stdin) {
554635 .bytes => |bytes| {
555636 man.hash.addBytes(bytes);
556637 },
557638 .lazy_path => |lazy_path| {
558 const file_path = lazy_path.getPath(b);
639 const file_path = lazy_path.getPath2(b, step);
559640 _ = try man.addFile(file_path, null);
560641 },
561642 .none => {},
562643 }
563644
564 if (self.captured_stdout) |output| {
645 if (run.captured_stdout) |output| {
565646 man.hash.addBytes(output.basename);
566647 }
567648
568 if (self.captured_stderr) |output| {
649 if (run.captured_stderr) |output| {
569650 man.hash.addBytes(output.basename);
570651 }
571652
572 hashStdIo(&man.hash, self.stdio);
653 hashStdIo(&man.hash, run.stdio);
573654
574 if (has_side_effects) {
575 try runCommand(self, argv_list.items, has_side_effects, null, prog_node);
576 return;
577 }
578
579 for (self.extra_file_dependencies) |file_path| {
655 for (run.extra_file_dependencies) |file_path| {
580656 _ = try man.addFile(b.pathFromRoot(file_path), null);
581657 }
658 for (run.file_inputs.items) |lazy_path| {
659 _ = try man.addFile(lazy_path.getPath2(b, step), null);
660 }
582661
583 if (try step.cacheHit(&man)) {
662 if (try step.cacheHit(&man) and !has_side_effects) {
584663 // cache hit, skip running command
585664 const digest = man.final();
586665
587666 try populateGeneratedPaths(
588667 arena,
589668 output_placeholders.items,
590 self.captured_stdout,
591 self.captured_stderr,
669 run.captured_stdout,
670 run.captured_stderr,
592671 b.cache_root,
593672 &digest,
594673 );
......@@ -597,13 +676,54 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
597676 return;
598677 }
599678
679 const dep_output_file = run.dep_output_file orelse {
680 // We already know the final output paths, use them directly.
681 const digest = man.final();
682
683 try populateGeneratedPaths(
684 arena,
685 output_placeholders.items,
686 run.captured_stdout,
687 run.captured_stderr,
688 b.cache_root,
689 &digest,
690 );
691
692 const output_dir_path = "o" ++ fs.path.sep_str ++ &digest;
693 for (output_placeholders.items) |placeholder| {
694 const output_sub_path = b.pathJoin(&.{ output_dir_path, placeholder.output.basename });
695 const output_sub_dir_path = switch (placeholder.tag) {
696 .output_file => fs.path.dirname(output_sub_path).?,
697 .output_directory => output_sub_path,
698 else => unreachable,
699 };
700 b.cache_root.handle.makePath(output_sub_dir_path) catch |err| {
701 return step.fail("unable to make path '{}{s}': {s}", .{
702 b.cache_root, output_sub_dir_path, @errorName(err),
703 });
704 };
705 const output_path = placeholder.output.generated_file.path.?;
706 argv_list.items[placeholder.index] = if (placeholder.output.prefix.len == 0)
707 output_path
708 else
709 b.fmt("{s}{s}", .{ placeholder.output.prefix, output_path });
710 }
711
712 return runCommand(run, argv_list.items, has_side_effects, output_dir_path, prog_node);
713 };
714
715 // We do not know the final output paths yet, use temp paths to run the command.
600716 const rand_int = std.crypto.random.int(u64);
601717 const tmp_dir_path = "tmp" ++ fs.path.sep_str ++ std.Build.hex64(rand_int);
602718
603719 for (output_placeholders.items) |placeholder| {
604720 const output_components = .{ tmp_dir_path, placeholder.output.basename };
605 const output_sub_path = try fs.path.join(arena, &output_components);
606 const output_sub_dir_path = fs.path.dirname(output_sub_path).?;
721 const output_sub_path = b.pathJoin(&output_components);
722 const output_sub_dir_path = switch (placeholder.tag) {
723 .output_file => fs.path.dirname(output_sub_path).?,
724 .output_directory => output_sub_path,
725 else => unreachable,
726 };
607727 b.cache_root.handle.makePath(output_sub_dir_path) catch |err| {
608728 return step.fail("unable to make path '{}{s}': {s}", .{
609729 b.cache_root, output_sub_dir_path, @errorName(err),
......@@ -611,22 +731,20 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
611731 };
612732 const output_path = try b.cache_root.join(arena, &output_components);
613733 placeholder.output.generated_file.path = output_path;
614 const cli_arg = if (placeholder.output.prefix.len == 0)
734 argv_list.items[placeholder.index] = if (placeholder.output.prefix.len == 0)
615735 output_path
616736 else
617737 b.fmt("{s}{s}", .{ placeholder.output.prefix, output_path });
618 argv_list.items[placeholder.index] = cli_arg;
619738 }
620739
621 try runCommand(self, argv_list.items, has_side_effects, tmp_dir_path, prog_node);
740 try runCommand(run, argv_list.items, has_side_effects, tmp_dir_path, prog_node);
622741
623 if (self.dep_output_file) |dep_output_file|
624 try man.addDepFilePost(std.fs.cwd(), dep_output_file.generated_file.getPath());
742 try man.addDepFilePost(std.fs.cwd(), dep_output_file.generated_file.getPath());
625743
626744 const digest = man.final();
627745
628746 const any_output = output_placeholders.items.len > 0 or
629 self.captured_stdout != null or self.captured_stderr != null;
747 run.captured_stdout != null or run.captured_stderr != null;
630748
631749 // Rename into place
632750 if (any_output) {
......@@ -663,8 +781,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
663781 try populateGeneratedPaths(
664782 arena,
665783 output_placeholders.items,
666 self.captured_stdout,
667 self.captured_stderr,
784 run.captured_stdout,
785 run.captured_stderr,
668786 b.cache_root,
669787 &digest,
670788 );
......@@ -743,30 +861,30 @@ fn termMatches(expected: ?std.process.Child.Term, actual: std.process.Child.Term
743861}
744862
745863fn runCommand(
746 self: *Run,
864 run: *Run,
747865 argv: []const []const u8,
748866 has_side_effects: bool,
749 tmp_dir_path: ?[]const u8,
867 output_dir_path: []const u8,
750868 prog_node: *std.Progress.Node,
751869) !void {
752 const step = &self.step;
870 const step = &run.step;
753871 const b = step.owner;
754872 const arena = b.allocator;
755873
756 const cwd: ?[]const u8 = if (self.cwd) |lazy_cwd| lazy_cwd.getPath(b) else null;
874 const cwd: ?[]const u8 = if (run.cwd) |lazy_cwd| lazy_cwd.getPath2(b, step) else null;
757875
758876 try step.handleChildProcUnsupported(cwd, argv);
759 try Step.handleVerbose2(step.owner, cwd, self.env_map, argv);
877 try Step.handleVerbose2(step.owner, cwd, run.env_map, argv);
760878
761 const allow_skip = switch (self.stdio) {
762 .check, .zig_test => self.skip_foreign_checks,
879 const allow_skip = switch (run.stdio) {
880 .check, .zig_test => run.skip_foreign_checks,
763881 else => false,
764882 };
765883
766884 var interp_argv = std.ArrayList([]const u8).init(b.allocator);
767885 defer interp_argv.deinit();
768886
769 const result = spawnChildAndCollect(self, argv, has_side_effects, prog_node) catch |err| term: {
887 const result = spawnChildAndCollect(run, argv, has_side_effects, prog_node) catch |err| term: {
770888 // InvalidExe: cpu arch mismatch
771889 // FileNotFound: can happen with a wrong dynamic linker path
772890 if (err == error.InvalidExe or err == error.FileNotFound) interpret: {
......@@ -774,7 +892,7 @@ fn runCommand(
774892 // relying on it being a Compile step. This will make this logic
775893 // work even for the edge case that the binary was produced by a
776894 // third party.
777 const exe = switch (self.argv.items[0]) {
895 const exe = switch (run.argv.items[0]) {
778896 .artifact => |exe| exe,
779897 else => break :interpret,
780898 };
......@@ -799,14 +917,14 @@ fn runCommand(
799917 try interp_argv.append(bin_name);
800918 try interp_argv.appendSlice(argv);
801919 } else {
802 return failForeign(self, "-fwine", argv[0], exe);
920 return failForeign(run, "-fwine", argv[0], exe);
803921 }
804922 },
805923 .qemu => |bin_name| {
806924 if (b.enable_qemu) {
807925 const glibc_dir_arg = if (need_cross_glibc)
808926 b.glibc_runtimes_dir orelse
809 return failForeign(self, "--glibc-runtimes", argv[0], exe)
927 return failForeign(run, "--glibc-runtimes", argv[0], exe)
810928 else
811929 null;
812930
......@@ -834,7 +952,7 @@ fn runCommand(
834952
835953 try interp_argv.appendSlice(argv);
836954 } else {
837 return failForeign(self, "-fqemu", argv[0], exe);
955 return failForeign(run, "-fqemu", argv[0], exe);
838956 }
839957 },
840958 .darling => |bin_name| {
......@@ -842,7 +960,7 @@ fn runCommand(
842960 try interp_argv.append(bin_name);
843961 try interp_argv.appendSlice(argv);
844962 } else {
845 return failForeign(self, "-fdarling", argv[0], exe);
963 return failForeign(run, "-fdarling", argv[0], exe);
846964 }
847965 },
848966 .wasmtime => |bin_name| {
......@@ -853,7 +971,7 @@ fn runCommand(
853971 try interp_argv.append("--");
854972 try interp_argv.appendSlice(argv[1..]);
855973 } else {
856 return failForeign(self, "-fwasmtime", argv[0], exe);
974 return failForeign(run, "-fwasmtime", argv[0], exe);
857975 }
858976 },
859977 .bad_dl => |foreign_dl| {
......@@ -882,13 +1000,13 @@ fn runCommand(
8821000
8831001 if (exe.rootModuleTarget().os.tag == .windows) {
8841002 // On Windows we don't have rpaths so we have to add .dll search paths to PATH
885 self.addPathForDynLibs(exe);
1003 run.addPathForDynLibs(exe);
8861004 }
8871005
888 try Step.handleVerbose2(step.owner, cwd, self.env_map, interp_argv.items);
1006 try Step.handleVerbose2(step.owner, cwd, run.env_map, interp_argv.items);
8891007
890 break :term spawnChildAndCollect(self, interp_argv.items, has_side_effects, prog_node) catch |e| {
891 if (!self.failing_to_execute_foreign_is_an_error) return error.MakeSkipped;
1008 break :term spawnChildAndCollect(run, interp_argv.items, has_side_effects, prog_node) catch |e| {
1009 if (!run.failing_to_execute_foreign_is_an_error) return error.MakeSkipped;
8921010
8931011 return step.fail("unable to spawn interpreter {s}: {s}", .{
8941012 interp_argv.items[0], @errorName(e),
......@@ -910,20 +1028,20 @@ fn runCommand(
9101028 };
9111029 for ([_]Stream{
9121030 .{
913 .captured = self.captured_stdout,
1031 .captured = run.captured_stdout,
9141032 .bytes = result.stdio.stdout,
9151033 },
9161034 .{
917 .captured = self.captured_stderr,
1035 .captured = run.captured_stderr,
9181036 .bytes = result.stdio.stderr,
9191037 },
9201038 }) |stream| {
9211039 if (stream.captured) |output| {
922 const output_components = .{ tmp_dir_path.?, output.basename };
1040 const output_components = .{ output_dir_path, output.basename };
9231041 const output_path = try b.cache_root.join(arena, &output_components);
9241042 output.generated_file.path = output_path;
9251043
926 const sub_path = try fs.path.join(arena, &output_components);
1044 const sub_path = b.pathJoin(&output_components);
9271045 const sub_path_dirname = fs.path.dirname(sub_path).?;
9281046 b.cache_root.handle.makePath(sub_path_dirname) catch |err| {
9291047 return step.fail("unable to make path '{}{s}': {s}", .{
......@@ -940,7 +1058,7 @@ fn runCommand(
9401058
9411059 const final_argv = if (interp_argv.items.len == 0) argv else interp_argv.items;
9421060
943 switch (self.stdio) {
1061 switch (run.stdio) {
9441062 .check => |checks| for (checks.items) |check| switch (check) {
9451063 .expect_stderr_exact => |expected_bytes| {
9461064 if (!mem.eql(u8, expected_bytes, result.stdio.stderr.?)) {
......@@ -1061,56 +1179,56 @@ const ChildProcResult = struct {
10611179};
10621180
10631181fn spawnChildAndCollect(
1064 self: *Run,
1182 run: *Run,
10651183 argv: []const []const u8,
10661184 has_side_effects: bool,
10671185 prog_node: *std.Progress.Node,
10681186) !ChildProcResult {
1069 const b = self.step.owner;
1187 const b = run.step.owner;
10701188 const arena = b.allocator;
10711189
10721190 var child = std.process.Child.init(argv, arena);
1073 if (self.cwd) |lazy_cwd| {
1074 child.cwd = lazy_cwd.getPath(b);
1191 if (run.cwd) |lazy_cwd| {
1192 child.cwd = lazy_cwd.getPath2(b, &run.step);
10751193 } else {
10761194 child.cwd = b.build_root.path;
10771195 child.cwd_dir = b.build_root.handle;
10781196 }
1079 child.env_map = self.env_map orelse &b.graph.env_map;
1197 child.env_map = run.env_map orelse &b.graph.env_map;
10801198 child.request_resource_usage_statistics = true;
10811199
1082 child.stdin_behavior = switch (self.stdio) {
1200 child.stdin_behavior = switch (run.stdio) {
10831201 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
10841202 .inherit => .Inherit,
10851203 .check => .Ignore,
10861204 .zig_test => .Pipe,
10871205 };
1088 child.stdout_behavior = switch (self.stdio) {
1206 child.stdout_behavior = switch (run.stdio) {
10891207 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
10901208 .inherit => .Inherit,
10911209 .check => |checks| if (checksContainStdout(checks.items)) .Pipe else .Ignore,
10921210 .zig_test => .Pipe,
10931211 };
1094 child.stderr_behavior = switch (self.stdio) {
1212 child.stderr_behavior = switch (run.stdio) {
10951213 .infer_from_args => if (has_side_effects) .Inherit else .Pipe,
10961214 .inherit => .Inherit,
10971215 .check => .Pipe,
10981216 .zig_test => .Pipe,
10991217 };
1100 if (self.captured_stdout != null) child.stdout_behavior = .Pipe;
1101 if (self.captured_stderr != null) child.stderr_behavior = .Pipe;
1102 if (self.stdin != .none) {
1103 assert(self.stdio != .inherit);
1218 if (run.captured_stdout != null) child.stdout_behavior = .Pipe;
1219 if (run.captured_stderr != null) child.stderr_behavior = .Pipe;
1220 if (run.stdin != .none) {
1221 assert(run.stdio != .inherit);
11041222 child.stdin_behavior = .Pipe;
11051223 }
11061224
11071225 try child.spawn();
11081226 var timer = try std.time.Timer.start();
11091227
1110 const result = if (self.stdio == .zig_test)
1111 evalZigTest(self, &child, prog_node)
1228 const result = if (run.stdio == .zig_test)
1229 evalZigTest(run, &child, prog_node)
11121230 else
1113 evalGeneric(self, &child);
1231 evalGeneric(run, &child);
11141232
11151233 const term = try child.wait();
11161234 const elapsed_ns = timer.read();
......@@ -1131,12 +1249,12 @@ const StdIoResult = struct {
11311249};
11321250
11331251fn evalZigTest(
1134 self: *Run,
1252 run: *Run,
11351253 child: *std.process.Child,
11361254 prog_node: *std.Progress.Node,
11371255) !StdIoResult {
1138 const gpa = self.step.owner.allocator;
1139 const arena = self.step.owner.allocator;
1256 const gpa = run.step.owner.allocator;
1257 const arena = run.step.owner.allocator;
11401258
11411259 var poller = std.io.poll(gpa, enum { stdout, stderr }, .{
11421260 .stdout = child.stdout.?,
......@@ -1175,7 +1293,7 @@ fn evalZigTest(
11751293 switch (header.tag) {
11761294 .zig_version => {
11771295 if (!std.mem.eql(u8, builtin.zig_version_string, body)) {
1178 return self.step.fail(
1296 return run.step.fail(
11791297 "zig version mismatch build runner vs compiler: '{s}' vs '{s}'",
11801298 .{ builtin.zig_version_string, body },
11811299 );
......@@ -1233,9 +1351,9 @@ fn evalZigTest(
12331351 else
12341352 unreachable;
12351353 if (msg.len > 0) {
1236 try self.step.addError("'{s}' {s}: {s}", .{ name, label, msg });
1354 try run.step.addError("'{s}' {s}: {s}", .{ name, label, msg });
12371355 } else {
1238 try self.step.addError("'{s}' {s}", .{ name, label });
1356 try run.step.addError("'{s}' {s}", .{ name, label });
12391357 }
12401358 }
12411359
......@@ -1249,7 +1367,7 @@ fn evalZigTest(
12491367
12501368 if (stderr.readableLength() > 0) {
12511369 const msg = std.mem.trim(u8, try stderr.toOwnedSlice(), "\n");
1252 if (msg.len > 0) self.step.result_stderr = msg;
1370 if (msg.len > 0) run.step.result_stderr = msg;
12531371 }
12541372
12551373 // Send EOF to stdin.
......@@ -1317,25 +1435,26 @@ fn sendRunTestMessage(file: std.fs.File, index: u32) !void {
13171435 try file.writeAll(full_msg);
13181436}
13191437
1320fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult {
1321 const arena = self.step.owner.allocator;
1438fn evalGeneric(run: *Run, child: *std.process.Child) !StdIoResult {
1439 const b = run.step.owner;
1440 const arena = b.allocator;
13221441
1323 switch (self.stdin) {
1442 switch (run.stdin) {
13241443 .bytes => |bytes| {
13251444 child.stdin.?.writeAll(bytes) catch |err| {
1326 return self.step.fail("unable to write stdin: {s}", .{@errorName(err)});
1445 return run.step.fail("unable to write stdin: {s}", .{@errorName(err)});
13271446 };
13281447 child.stdin.?.close();
13291448 child.stdin = null;
13301449 },
13311450 .lazy_path => |lazy_path| {
1332 const path = lazy_path.getPath(self.step.owner);
1333 const file = self.step.owner.build_root.handle.openFile(path, .{}) catch |err| {
1334 return self.step.fail("unable to open stdin file: {s}", .{@errorName(err)});
1451 const path = lazy_path.getPath2(b, &run.step);
1452 const file = b.build_root.handle.openFile(path, .{}) catch |err| {
1453 return run.step.fail("unable to open stdin file: {s}", .{@errorName(err)});
13351454 };
13361455 defer file.close();
13371456 child.stdin.?.writeFileAll(file, .{}) catch |err| {
1338 return self.step.fail("unable to write file to stdin: {s}", .{@errorName(err)});
1457 return run.step.fail("unable to write file to stdin: {s}", .{@errorName(err)});
13391458 };
13401459 child.stdin.?.close();
13411460 child.stdin = null;
......@@ -1355,29 +1474,29 @@ fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult {
13551474 defer poller.deinit();
13561475
13571476 while (try poller.poll()) {
1358 if (poller.fifo(.stdout).count > self.max_stdio_size)
1477 if (poller.fifo(.stdout).count > run.max_stdio_size)
13591478 return error.StdoutStreamTooLong;
1360 if (poller.fifo(.stderr).count > self.max_stdio_size)
1479 if (poller.fifo(.stderr).count > run.max_stdio_size)
13611480 return error.StderrStreamTooLong;
13621481 }
13631482
13641483 stdout_bytes = try poller.fifo(.stdout).toOwnedSlice();
13651484 stderr_bytes = try poller.fifo(.stderr).toOwnedSlice();
13661485 } else {
1367 stdout_bytes = try stdout.reader().readAllAlloc(arena, self.max_stdio_size);
1486 stdout_bytes = try stdout.reader().readAllAlloc(arena, run.max_stdio_size);
13681487 }
13691488 } else if (child.stderr) |stderr| {
1370 stderr_bytes = try stderr.reader().readAllAlloc(arena, self.max_stdio_size);
1489 stderr_bytes = try stderr.reader().readAllAlloc(arena, run.max_stdio_size);
13711490 }
13721491
13731492 if (stderr_bytes) |bytes| if (bytes.len > 0) {
13741493 // Treat stderr as an error message.
1375 const stderr_is_diagnostic = self.captured_stderr == null and switch (self.stdio) {
1494 const stderr_is_diagnostic = run.captured_stderr == null and switch (run.stdio) {
13761495 .check => |checks| !checksContainStderr(checks.items),
13771496 else => true,
13781497 };
13791498 if (stderr_is_diagnostic) {
1380 self.step.result_stderr = bytes;
1499 run.step.result_stderr = bytes;
13811500 }
13821501 };
13831502
......@@ -1389,8 +1508,8 @@ fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult {
13891508 };
13901509}
13911510
1392fn addPathForDynLibs(self: *Run, artifact: *Step.Compile) void {
1393 const b = self.step.owner;
1511fn addPathForDynLibs(run: *Run, artifact: *Step.Compile) void {
1512 const b = run.step.owner;
13941513 var it = artifact.root_module.iterateDependencies(artifact, true);
13951514 while (it.next()) |item| {
13961515 const other = item.compile.?;
......@@ -1398,34 +1517,34 @@ fn addPathForDynLibs(self: *Run, artifact: *Step.Compile) void {
13981517 if (item.module.resolved_target.?.result.os.tag == .windows and
13991518 other.isDynamicLibrary())
14001519 {
1401 addPathDir(self, fs.path.dirname(other.getEmittedBin().getPath(b)).?);
1520 addPathDir(run, fs.path.dirname(other.getEmittedBin().getPath2(b, &run.step)).?);
14021521 }
14031522 }
14041523 }
14051524}
14061525
14071526fn failForeign(
1408 self: *Run,
1527 run: *Run,
14091528 suggested_flag: []const u8,
14101529 argv0: []const u8,
14111530 exe: *Step.Compile,
14121531) error{ MakeFailed, MakeSkipped, OutOfMemory } {
1413 switch (self.stdio) {
1532 switch (run.stdio) {
14141533 .check, .zig_test => {
1415 if (self.skip_foreign_checks)
1534 if (run.skip_foreign_checks)
14161535 return error.MakeSkipped;
14171536
1418 const b = self.step.owner;
1537 const b = run.step.owner;
14191538 const host_name = try b.host.result.zigTriple(b.allocator);
14201539 const foreign_name = try exe.rootModuleTarget().zigTriple(b.allocator);
14211540
1422 return self.step.fail(
1541 return run.step.fail(
14231542 \\unable to spawn foreign binary '{s}' ({s}) on host system ({s})
14241543 \\ consider using {s} or enabling skip_foreign_checks in the Run step
14251544 , .{ argv0, foreign_name, host_name, suggested_flag });
14261545 },
14271546 else => {
1428 return self.step.fail("unable to spawn foreign binary '{s}'", .{argv0});
1547 return run.step.fail("unable to spawn foreign binary '{s}'", .{argv0});
14291548 },
14301549 }
14311550}
lib/std/Build/Step/TranslateC.zig+42-45
......@@ -5,7 +5,7 @@ const mem = std.mem;
55
66const TranslateC = @This();
77
8pub const base_id = .translate_c;
8pub const base_id: Step.Id = .translate_c;
99
1010step: Step,
1111source: std.Build.LazyPath,
......@@ -27,11 +27,11 @@ pub const Options = struct {
2727};
2828
2929pub fn create(owner: *std.Build, options: Options) *TranslateC {
30 const self = owner.allocator.create(TranslateC) catch @panic("OOM");
30 const translate_c = owner.allocator.create(TranslateC) catch @panic("OOM");
3131 const source = options.root_source_file.dupe(owner);
32 self.* = TranslateC{
32 translate_c.* = TranslateC{
3333 .step = Step.init(.{
34 .id = .translate_c,
34 .id = base_id,
3535 .name = "translate-c",
3636 .owner = owner,
3737 .makeFn = make,
......@@ -42,12 +42,12 @@ pub fn create(owner: *std.Build, options: Options) *TranslateC {
4242 .out_basename = undefined,
4343 .target = options.target,
4444 .optimize = options.optimize,
45 .output_file = std.Build.GeneratedFile{ .step = &self.step },
45 .output_file = std.Build.GeneratedFile{ .step = &translate_c.step },
4646 .link_libc = options.link_libc,
4747 .use_clang = options.use_clang,
4848 };
49 source.addStepDependencies(&self.step);
50 return self;
49 source.addStepDependencies(&translate_c.step);
50 return translate_c;
5151}
5252
5353pub const AddExecutableOptions = struct {
......@@ -58,18 +58,18 @@ pub const AddExecutableOptions = struct {
5858 linkage: ?std.builtin.LinkMode = null,
5959};
6060
61pub fn getOutput(self: *TranslateC) std.Build.LazyPath {
62 return .{ .generated = &self.output_file };
61pub fn getOutput(translate_c: *TranslateC) std.Build.LazyPath {
62 return .{ .generated = .{ .file = &translate_c.output_file } };
6363}
6464
6565/// Creates a step to build an executable from the translated source.
66pub fn addExecutable(self: *TranslateC, options: AddExecutableOptions) *Step.Compile {
67 return self.step.owner.addExecutable(.{
68 .root_source_file = self.getOutput(),
66pub fn addExecutable(translate_c: *TranslateC, options: AddExecutableOptions) *Step.Compile {
67 return translate_c.step.owner.addExecutable(.{
68 .root_source_file = translate_c.getOutput(),
6969 .name = options.name orelse "translated_c",
7070 .version = options.version,
71 .target = options.target orelse self.target,
72 .optimize = options.optimize orelse self.optimize,
71 .target = options.target orelse translate_c.target,
72 .optimize = options.optimize orelse translate_c.optimize,
7373 .linkage = options.linkage,
7474 });
7575}
......@@ -77,90 +77,87 @@ pub fn addExecutable(self: *TranslateC, options: AddExecutableOptions) *Step.Com
7777/// Creates a module from the translated source and adds it to the package's
7878/// module set making it available to other packages which depend on this one.
7979/// `createModule` can be used instead to create a private module.
80pub fn addModule(self: *TranslateC, name: []const u8) *std.Build.Module {
81 return self.step.owner.addModule(name, .{
82 .root_source_file = self.getOutput(),
80pub fn addModule(translate_c: *TranslateC, name: []const u8) *std.Build.Module {
81 return translate_c.step.owner.addModule(name, .{
82 .root_source_file = translate_c.getOutput(),
8383 });
8484}
8585
8686/// Creates a private module from the translated source to be used by the
8787/// current package, but not exposed to other packages depending on this one.
8888/// `addModule` can be used instead to create a public module.
89pub fn createModule(self: *TranslateC) *std.Build.Module {
90 return self.step.owner.createModule(.{
91 .root_source_file = self.getOutput(),
89pub fn createModule(translate_c: *TranslateC) *std.Build.Module {
90 return translate_c.step.owner.createModule(.{
91 .root_source_file = translate_c.getOutput(),
9292 });
9393}
9494
95pub fn addIncludeDir(self: *TranslateC, include_dir: []const u8) void {
96 self.include_dirs.append(self.step.owner.dupePath(include_dir)) catch @panic("OOM");
95pub fn addIncludeDir(translate_c: *TranslateC, include_dir: []const u8) void {
96 translate_c.include_dirs.append(translate_c.step.owner.dupePath(include_dir)) catch @panic("OOM");
9797}
9898
99pub fn addCheckFile(self: *TranslateC, expected_matches: []const []const u8) *Step.CheckFile {
99pub fn addCheckFile(translate_c: *TranslateC, expected_matches: []const []const u8) *Step.CheckFile {
100100 return Step.CheckFile.create(
101 self.step.owner,
102 self.getOutput(),
101 translate_c.step.owner,
102 translate_c.getOutput(),
103103 .{ .expected_matches = expected_matches },
104104 );
105105}
106106
107107/// If the value is omitted, it is set to 1.
108108/// `name` and `value` need not live longer than the function call.
109pub fn defineCMacro(self: *TranslateC, name: []const u8, value: ?[]const u8) void {
110 const macro = std.Build.constructCMacro(self.step.owner.allocator, name, value);
111 self.c_macros.append(macro) catch @panic("OOM");
109pub fn defineCMacro(translate_c: *TranslateC, name: []const u8, value: ?[]const u8) void {
110 const macro = std.Build.constructranslate_cMacro(translate_c.step.owner.allocator, name, value);
111 translate_c.c_macros.append(macro) catch @panic("OOM");
112112}
113113
114114/// name_and_value looks like [name]=[value]. If the value is omitted, it is set to 1.
115pub fn defineCMacroRaw(self: *TranslateC, name_and_value: []const u8) void {
116 self.c_macros.append(self.step.owner.dupe(name_and_value)) catch @panic("OOM");
115pub fn defineCMacroRaw(translate_c: *TranslateC, name_and_value: []const u8) void {
116 translate_c.c_macros.append(translate_c.step.owner.dupe(name_and_value)) catch @panic("OOM");
117117}
118118
119119fn make(step: *Step, prog_node: *std.Progress.Node) !void {
120120 const b = step.owner;
121 const self: *TranslateC = @fieldParentPtr("step", step);
121 const translate_c: *TranslateC = @fieldParentPtr("step", step);
122122
123123 var argv_list = std.ArrayList([]const u8).init(b.allocator);
124124 try argv_list.append(b.graph.zig_exe);
125125 try argv_list.append("translate-c");
126 if (self.link_libc) {
126 if (translate_c.link_libc) {
127127 try argv_list.append("-lc");
128128 }
129 if (!self.use_clang) {
129 if (!translate_c.use_clang) {
130130 try argv_list.append("-fno-clang");
131131 }
132132
133133 try argv_list.append("--listen=-");
134134
135 if (!self.target.query.isNative()) {
135 if (!translate_c.target.query.isNative()) {
136136 try argv_list.append("-target");
137 try argv_list.append(try self.target.query.zigTriple(b.allocator));
137 try argv_list.append(try translate_c.target.query.zigTriple(b.allocator));
138138 }
139139
140 switch (self.optimize) {
140 switch (translate_c.optimize) {
141141 .Debug => {}, // Skip since it's the default.
142 else => try argv_list.append(b.fmt("-O{s}", .{@tagName(self.optimize)})),
142 else => try argv_list.append(b.fmt("-O{s}", .{@tagName(translate_c.optimize)})),
143143 }
144144
145 for (self.include_dirs.items) |include_dir| {
145 for (translate_c.include_dirs.items) |include_dir| {
146146 try argv_list.append("-I");
147147 try argv_list.append(include_dir);
148148 }
149149
150 for (self.c_macros.items) |c_macro| {
150 for (translate_c.c_macros.items) |c_macro| {
151151 try argv_list.append("-D");
152152 try argv_list.append(c_macro);
153153 }
154154
155 try argv_list.append(self.source.getPath(b));
155 try argv_list.append(translate_c.source.getPath2(b, step));
156156
157157 const output_path = try step.evalZigProcess(argv_list.items, prog_node);
158158
159 self.out_basename = fs.path.basename(output_path.?);
159 translate_c.out_basename = fs.path.basename(output_path.?);
160160 const output_dir = fs.path.dirname(output_path.?).?;
161161
162 self.output_file.path = try fs.path.join(
163 b.allocator,
164 &[_][]const u8{ output_dir, self.out_basename },
165 );
162 translate_c.output_file.path = b.pathJoin(&.{ output_dir, translate_c.out_basename });
166163}
lib/std/Build/Step/WriteFile.zig+58-58
......@@ -23,15 +23,15 @@ directories: std.ArrayListUnmanaged(*Directory),
2323output_source_files: std.ArrayListUnmanaged(OutputSourceFile),
2424generated_directory: std.Build.GeneratedFile,
2525
26pub const base_id = .write_file;
26pub const base_id: Step.Id = .write_file;
2727
2828pub const File = struct {
2929 generated_file: std.Build.GeneratedFile,
3030 sub_path: []const u8,
3131 contents: Contents,
3232
33 pub fn getPath(self: *File) std.Build.LazyPath {
34 return .{ .generated = &self.generated_file };
33 pub fn getPath(file: *File) std.Build.LazyPath {
34 return .{ .generated = .{ .file = &file.generated_file } };
3535 }
3636};
3737
......@@ -49,16 +49,16 @@ pub const Directory = struct {
4949 /// `exclude_extensions` takes precedence over `include_extensions`.
5050 include_extensions: ?[]const []const u8 = null,
5151
52 pub fn dupe(self: Options, b: *std.Build) Options {
52 pub fn dupe(opts: Options, b: *std.Build) Options {
5353 return .{
54 .exclude_extensions = b.dupeStrings(self.exclude_extensions),
55 .include_extensions = if (self.include_extensions) |incs| b.dupeStrings(incs) else null,
54 .exclude_extensions = b.dupeStrings(opts.exclude_extensions),
55 .include_extensions = if (opts.include_extensions) |incs| b.dupeStrings(incs) else null,
5656 };
5757 }
5858 };
5959
60 pub fn getPath(self: *Directory) std.Build.LazyPath {
61 return .{ .generated = &self.generated_dir };
60 pub fn getPath(dir: *Directory) std.Build.LazyPath {
61 return .{ .generated = .{ .file = &dir.generated_dir } };
6262 }
6363};
6464
......@@ -73,10 +73,10 @@ pub const Contents = union(enum) {
7373};
7474
7575pub fn create(owner: *std.Build) *WriteFile {
76 const wf = owner.allocator.create(WriteFile) catch @panic("OOM");
77 wf.* = .{
76 const write_file = owner.allocator.create(WriteFile) catch @panic("OOM");
77 write_file.* = .{
7878 .step = Step.init(.{
79 .id = .write_file,
79 .id = base_id,
8080 .name = "WriteFile",
8181 .owner = owner,
8282 .makeFn = make,
......@@ -84,22 +84,22 @@ pub fn create(owner: *std.Build) *WriteFile {
8484 .files = .{},
8585 .directories = .{},
8686 .output_source_files = .{},
87 .generated_directory = .{ .step = &wf.step },
87 .generated_directory = .{ .step = &write_file.step },
8888 };
89 return wf;
89 return write_file;
9090}
9191
92pub fn add(wf: *WriteFile, sub_path: []const u8, bytes: []const u8) std.Build.LazyPath {
93 const b = wf.step.owner;
92pub fn add(write_file: *WriteFile, sub_path: []const u8, bytes: []const u8) std.Build.LazyPath {
93 const b = write_file.step.owner;
9494 const gpa = b.allocator;
9595 const file = gpa.create(File) catch @panic("OOM");
9696 file.* = .{
97 .generated_file = .{ .step = &wf.step },
97 .generated_file = .{ .step = &write_file.step },
9898 .sub_path = b.dupePath(sub_path),
9999 .contents = .{ .bytes = b.dupe(bytes) },
100100 };
101 wf.files.append(gpa, file) catch @panic("OOM");
102 wf.maybeUpdateName();
101 write_file.files.append(gpa, file) catch @panic("OOM");
102 write_file.maybeUpdateName();
103103 return file.getPath();
104104}
105105
......@@ -110,19 +110,19 @@ pub fn add(wf: *WriteFile, sub_path: []const u8, bytes: []const u8) std.Build.La
110110/// include sub-directories, in which case this step will ensure the
111111/// required sub-path exists.
112112/// This is the option expected to be used most commonly with `addCopyFile`.
113pub fn addCopyFile(wf: *WriteFile, source: std.Build.LazyPath, sub_path: []const u8) std.Build.LazyPath {
114 const b = wf.step.owner;
113pub fn addCopyFile(write_file: *WriteFile, source: std.Build.LazyPath, sub_path: []const u8) std.Build.LazyPath {
114 const b = write_file.step.owner;
115115 const gpa = b.allocator;
116116 const file = gpa.create(File) catch @panic("OOM");
117117 file.* = .{
118 .generated_file = .{ .step = &wf.step },
118 .generated_file = .{ .step = &write_file.step },
119119 .sub_path = b.dupePath(sub_path),
120120 .contents = .{ .copy = source },
121121 };
122 wf.files.append(gpa, file) catch @panic("OOM");
122 write_file.files.append(gpa, file) catch @panic("OOM");
123123
124 wf.maybeUpdateName();
125 source.addStepDependencies(&wf.step);
124 write_file.maybeUpdateName();
125 source.addStepDependencies(&write_file.step);
126126 return file.getPath();
127127}
128128
......@@ -130,24 +130,24 @@ pub fn addCopyFile(wf: *WriteFile, source: std.Build.LazyPath, sub_path: []const
130130/// relative to this step's generated directory.
131131/// The returned value is a lazy path to the generated subdirectory.
132132pub fn addCopyDirectory(
133 wf: *WriteFile,
133 write_file: *WriteFile,
134134 source: std.Build.LazyPath,
135135 sub_path: []const u8,
136136 options: Directory.Options,
137137) std.Build.LazyPath {
138 const b = wf.step.owner;
138 const b = write_file.step.owner;
139139 const gpa = b.allocator;
140140 const dir = gpa.create(Directory) catch @panic("OOM");
141141 dir.* = .{
142142 .source = source.dupe(b),
143143 .sub_path = b.dupePath(sub_path),
144144 .options = options.dupe(b),
145 .generated_dir = .{ .step = &wf.step },
145 .generated_dir = .{ .step = &write_file.step },
146146 };
147 wf.directories.append(gpa, dir) catch @panic("OOM");
147 write_file.directories.append(gpa, dir) catch @panic("OOM");
148148
149 wf.maybeUpdateName();
150 source.addStepDependencies(&wf.step);
149 write_file.maybeUpdateName();
150 source.addStepDependencies(&write_file.step);
151151 return dir.getPath();
152152}
153153
......@@ -156,13 +156,13 @@ pub fn addCopyDirectory(
156156/// used as part of the normal build process, but as a utility occasionally
157157/// run by a developer with intent to modify source files and then commit
158158/// those changes to version control.
159pub fn addCopyFileToSource(wf: *WriteFile, source: std.Build.LazyPath, sub_path: []const u8) void {
160 const b = wf.step.owner;
161 wf.output_source_files.append(b.allocator, .{
159pub fn addCopyFileToSource(write_file: *WriteFile, source: std.Build.LazyPath, sub_path: []const u8) void {
160 const b = write_file.step.owner;
161 write_file.output_source_files.append(b.allocator, .{
162162 .contents = .{ .copy = source },
163163 .sub_path = sub_path,
164164 }) catch @panic("OOM");
165 source.addStepDependencies(&wf.step);
165 source.addStepDependencies(&write_file.step);
166166}
167167
168168/// A path relative to the package root.
......@@ -170,9 +170,9 @@ pub fn addCopyFileToSource(wf: *WriteFile, source: std.Build.LazyPath, sub_path:
170170/// used as part of the normal build process, but as a utility occasionally
171171/// run by a developer with intent to modify source files and then commit
172172/// those changes to version control.
173pub fn addBytesToSource(wf: *WriteFile, bytes: []const u8, sub_path: []const u8) void {
174 const b = wf.step.owner;
175 wf.output_source_files.append(b.allocator, .{
173pub fn addBytesToSource(write_file: *WriteFile, bytes: []const u8, sub_path: []const u8) void {
174 const b = write_file.step.owner;
175 write_file.output_source_files.append(b.allocator, .{
176176 .contents = .{ .bytes = bytes },
177177 .sub_path = sub_path,
178178 }) catch @panic("OOM");
......@@ -180,20 +180,20 @@ pub fn addBytesToSource(wf: *WriteFile, bytes: []const u8, sub_path: []const u8)
180180
181181/// Returns a `LazyPath` representing the base directory that contains all the
182182/// files from this `WriteFile`.
183pub fn getDirectory(wf: *WriteFile) std.Build.LazyPath {
184 return .{ .generated = &wf.generated_directory };
183pub fn getDirectory(write_file: *WriteFile) std.Build.LazyPath {
184 return .{ .generated = .{ .file = &write_file.generated_directory } };
185185}
186186
187fn maybeUpdateName(wf: *WriteFile) void {
188 if (wf.files.items.len == 1 and wf.directories.items.len == 0) {
187fn maybeUpdateName(write_file: *WriteFile) void {
188 if (write_file.files.items.len == 1 and write_file.directories.items.len == 0) {
189189 // First time adding a file; update name.
190 if (std.mem.eql(u8, wf.step.name, "WriteFile")) {
191 wf.step.name = wf.step.owner.fmt("WriteFile {s}", .{wf.files.items[0].sub_path});
190 if (std.mem.eql(u8, write_file.step.name, "WriteFile")) {
191 write_file.step.name = write_file.step.owner.fmt("WriteFile {s}", .{write_file.files.items[0].sub_path});
192192 }
193 } else if (wf.directories.items.len == 1 and wf.files.items.len == 0) {
193 } else if (write_file.directories.items.len == 1 and write_file.files.items.len == 0) {
194194 // First time adding a directory; update name.
195 if (std.mem.eql(u8, wf.step.name, "WriteFile")) {
196 wf.step.name = wf.step.owner.fmt("WriteFile {s}", .{wf.directories.items[0].sub_path});
195 if (std.mem.eql(u8, write_file.step.name, "WriteFile")) {
196 write_file.step.name = write_file.step.owner.fmt("WriteFile {s}", .{write_file.directories.items[0].sub_path});
197197 }
198198 }
199199}
......@@ -201,14 +201,14 @@ fn maybeUpdateName(wf: *WriteFile) void {
201201fn make(step: *Step, prog_node: *std.Progress.Node) !void {
202202 _ = prog_node;
203203 const b = step.owner;
204 const wf: *WriteFile = @fieldParentPtr("step", step);
204 const write_file: *WriteFile = @fieldParentPtr("step", step);
205205
206206 // Writing to source files is kind of an extra capability of this
207207 // WriteFile - arguably it should be a different step. But anyway here
208208 // it is, it happens unconditionally and does not interact with the other
209209 // files here.
210210 var any_miss = false;
211 for (wf.output_source_files.items) |output_source_file| {
211 for (write_file.output_source_files.items) |output_source_file| {
212212 if (fs.path.dirname(output_source_file.sub_path)) |dirname| {
213213 b.build_root.handle.makePath(dirname) catch |err| {
214214 return step.fail("unable to make path '{}{s}': {s}", .{
......@@ -226,7 +226,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
226226 any_miss = true;
227227 },
228228 .copy => |file_source| {
229 const source_path = file_source.getPath(b);
229 const source_path = file_source.getPath2(b, step);
230230 const prev_status = fs.Dir.updateFile(
231231 fs.cwd(),
232232 source_path,
......@@ -258,18 +258,18 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
258258 // in a non-backwards-compatible way.
259259 man.hash.add(@as(u32, 0xd767ee59));
260260
261 for (wf.files.items) |file| {
261 for (write_file.files.items) |file| {
262262 man.hash.addBytes(file.sub_path);
263263 switch (file.contents) {
264264 .bytes => |bytes| {
265265 man.hash.addBytes(bytes);
266266 },
267267 .copy => |file_source| {
268 _ = try man.addFile(file_source.getPath(b), null);
268 _ = try man.addFile(file_source.getPath2(b, step), null);
269269 },
270270 }
271271 }
272 for (wf.directories.items) |dir| {
272 for (write_file.directories.items) |dir| {
273273 man.hash.addBytes(dir.source.getPath2(b, step));
274274 man.hash.addBytes(dir.sub_path);
275275 for (dir.options.exclude_extensions) |ext| man.hash.addBytes(ext);
......@@ -278,19 +278,19 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
278278
279279 if (try step.cacheHit(&man)) {
280280 const digest = man.final();
281 for (wf.files.items) |file| {
281 for (write_file.files.items) |file| {
282282 file.generated_file.path = try b.cache_root.join(b.allocator, &.{
283283 "o", &digest, file.sub_path,
284284 });
285285 }
286 wf.generated_directory.path = try b.cache_root.join(b.allocator, &.{ "o", &digest });
286 write_file.generated_directory.path = try b.cache_root.join(b.allocator, &.{ "o", &digest });
287287 return;
288288 }
289289
290290 const digest = man.final();
291291 const cache_path = "o" ++ fs.path.sep_str ++ digest;
292292
293 wf.generated_directory.path = try b.cache_root.join(b.allocator, &.{ "o", &digest });
293 write_file.generated_directory.path = try b.cache_root.join(b.allocator, &.{ "o", &digest });
294294
295295 var cache_dir = b.cache_root.handle.makeOpenPath(cache_path, .{}) catch |err| {
296296 return step.fail("unable to make path '{}{s}': {s}", .{
......@@ -301,7 +301,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
301301
302302 const cwd = fs.cwd();
303303
304 for (wf.files.items) |file| {
304 for (write_file.files.items) |file| {
305305 if (fs.path.dirname(file.sub_path)) |dirname| {
306306 cache_dir.makePath(dirname) catch |err| {
307307 return step.fail("unable to make path '{}{s}{c}{s}': {s}", .{
......@@ -318,7 +318,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
318318 };
319319 },
320320 .copy => |file_source| {
321 const source_path = file_source.getPath(b);
321 const source_path = file_source.getPath2(b, step);
322322 const prev_status = fs.Dir.updateFile(
323323 cwd,
324324 source_path,
......@@ -347,7 +347,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
347347 cache_path, file.sub_path,
348348 });
349349 }
350 for (wf.directories.items) |dir| {
350 for (write_file.directories.items) |dir| {
351351 const full_src_dir_path = dir.source.getPath2(b, step);
352352 const dest_dirname = dir.sub_path;
353353
test/standalone/build.zig.zon+3
......@@ -164,6 +164,9 @@
164164 .dependencyFromBuildZig = .{
165165 .path = "dependencyFromBuildZig",
166166 },
167 .run_output_paths = .{
168 .path = "run_output_paths",
169 },
167170 },
168171 .paths = .{
169172 "build.zig",
test/standalone/coff_dwarf/build.zig+2-2
......@@ -18,7 +18,7 @@ pub fn build(b: *std.Build) void {
1818
1919 const exe = b.addExecutable(.{
2020 .name = "main",
21 .root_source_file = .{ .path = "main.zig" },
21 .root_source_file = b.path("main.zig"),
2222 .optimize = optimize,
2323 .target = target,
2424 });
......@@ -28,7 +28,7 @@ pub fn build(b: *std.Build) void {
2828 .optimize = optimize,
2929 .target = target,
3030 });
31 lib.addCSourceFile(.{ .file = .{ .path = "shared_lib.c" }, .flags = &.{"-gdwarf"} });
31 lib.addCSourceFile(.{ .file = b.path("shared_lib.c"), .flags = &.{"-gdwarf"} });
3232 lib.linkLibC();
3333 exe.linkLibrary(lib);
3434
test/standalone/emit_asm_and_bin/build.zig+1-1
......@@ -5,7 +5,7 @@ pub fn build(b: *std.Build) void {
55 b.default_step = test_step;
66
77 const main = b.addTest(.{
8 .root_source_file = .{ .path = "main.zig" },
8 .root_source_file = b.path("main.zig"),
99 .optimize = b.standardOptimizeOption(.{}),
1010 });
1111 // TODO: actually check these two artifacts for correctness
test/standalone/issue_12588/build.zig+1-1
......@@ -8,7 +8,7 @@ pub fn build(b: *std.Build) void {
88
99 const obj = b.addObject(.{
1010 .name = "main",
11 .root_source_file = .{ .path = "main.zig" },
11 .root_source_file = b.path("main.zig"),
1212 .optimize = optimize,
1313 .target = b.host,
1414 });
test/standalone/issue_13970/build.zig+3-3
......@@ -5,15 +5,15 @@ pub fn build(b: *std.Build) void {
55 b.default_step = test_step;
66
77 const test1 = b.addTest(.{
8 .root_source_file = .{ .path = "test_root/empty.zig" },
8 .root_source_file = b.path("test_root/empty.zig"),
99 .test_runner = "src/main.zig",
1010 });
1111 const test2 = b.addTest(.{
12 .root_source_file = .{ .path = "src/empty.zig" },
12 .root_source_file = b.path("src/empty.zig"),
1313 .test_runner = "src/main.zig",
1414 });
1515 const test3 = b.addTest(.{
16 .root_source_file = .{ .path = "empty.zig" },
16 .root_source_file = b.path("empty.zig"),
1717 .test_runner = "src/main.zig",
1818 });
1919
test/standalone/issue_5825/build.zig+1-1
......@@ -16,7 +16,7 @@ pub fn build(b: *std.Build) void {
1616 const optimize: std.builtin.OptimizeMode = .Debug;
1717 const obj = b.addObject(.{
1818 .name = "issue_5825",
19 .root_source_file = .{ .path = "main.zig" },
19 .root_source_file = b.path("main.zig"),
2020 .optimize = optimize,
2121 .target = target,
2222 });
test/standalone/options/build.zig+1-1
......@@ -2,7 +2,7 @@ const std = @import("std");
22
33pub fn build(b: *std.Build) void {
44 const main = b.addTest(.{
5 .root_source_file = .{ .path = "src/main.zig" },
5 .root_source_file = b.path("src/main.zig"),
66 .target = b.host,
77 .optimize = .Debug,
88 });
test/standalone/run_output_paths/build.zig created+40
......@@ -0,0 +1,40 @@
1const std = @import("std");
2
3pub fn build(b: *std.Build) void {
4 const test_step = b.step("test", "Test it");
5 b.default_step = test_step;
6
7 const target = b.standardTargetOptions(.{});
8 const optimize = b.standardOptimizeOption(.{});
9
10 const create_file_exe = b.addExecutable(.{
11 .name = "create_file",
12 .root_source_file = b.path("create_file.zig"),
13 .target = target,
14 .optimize = optimize,
15 });
16
17 const create_first = b.addRunArtifact(create_file_exe);
18 const first_dir = create_first.addOutputDirectoryArg("first");
19 create_first.addArg("hello1.txt");
20 test_step.dependOn(&b.addCheckFile(first_dir.path(b, "hello1.txt"), .{ .expected_matches = &.{
21 std.fs.path.sep_str ++
22 \\first
23 \\hello1.txt
24 \\Hello, world!
25 \\
26 ,
27 } }).step);
28
29 const create_second = b.addRunArtifact(create_file_exe);
30 const second_dir = create_second.addPrefixedOutputDirectoryArg("--dir=", "second");
31 create_second.addArg("hello2.txt");
32 test_step.dependOn(&b.addCheckFile(second_dir.path(b, "hello2.txt"), .{ .expected_matches = &.{
33 std.fs.path.sep_str ++
34 \\second
35 \\hello2.txt
36 \\Hello, world!
37 \\
38 ,
39 } }).step);
40}
test/standalone/run_output_paths/create_file.zig created+19
......@@ -0,0 +1,19 @@
1const std = @import("std");
2
3pub fn main() !void {
4 var args = try std.process.argsWithAllocator(std.heap.page_allocator);
5 _ = args.skip();
6 const dir_name = args.next().?;
7 const dir = try std.fs.cwd().openDir(if (std.mem.startsWith(u8, dir_name, "--dir="))
8 dir_name["--dir=".len..]
9 else
10 dir_name, .{});
11 const file_name = args.next().?;
12 const file = try dir.createFile(file_name, .{});
13 try file.writer().print(
14 \\{s}
15 \\{s}
16 \\Hello, world!
17 \\
18 , .{ dir_name, file_name });
19}
test/standalone/sigpipe/build.zig+1-1
......@@ -29,7 +29,7 @@ pub fn build(b: *std.build.Builder) !void {
2929 options.addOption(bool, "keep_sigpipe", keep_sigpipe);
3030 const exe = b.addExecutable(.{
3131 .name = "breakpipe",
32 .root_source_file = .{ .path = "breakpipe.zig" },
32 .root_source_file = b.path("breakpipe.zig"),
3333 });
3434 exe.addOptions("build_options", options);
3535 const run = b.addRunArtifact(exe);
test/standalone/windows_argv/build.zig+5-5
......@@ -11,7 +11,7 @@ pub fn build(b: *std.Build) !void {
1111
1212 const lib_gnu = b.addStaticLibrary(.{
1313 .name = "toargv-gnu",
14 .root_source_file = .{ .path = "lib.zig" },
14 .root_source_file = b.path("lib.zig"),
1515 .target = b.resolveTargetQuery(.{
1616 .abi = .gnu,
1717 }),
......@@ -25,7 +25,7 @@ pub fn build(b: *std.Build) !void {
2525 .optimize = optimize,
2626 });
2727 verify_gnu.addCSourceFile(.{
28 .file = .{ .path = "verify.c" },
28 .file = b.path("verify.c"),
2929 .flags = &.{ "-DUNICODE", "-D_UNICODE" },
3030 });
3131 verify_gnu.mingw_unicode_entry_point = true;
......@@ -34,7 +34,7 @@ pub fn build(b: *std.Build) !void {
3434
3535 const fuzz = b.addExecutable(.{
3636 .name = "fuzz",
37 .root_source_file = .{ .path = "fuzz.zig" },
37 .root_source_file = b.path("fuzz.zig"),
3838 .target = b.host,
3939 .optimize = optimize,
4040 });
......@@ -69,7 +69,7 @@ pub fn build(b: *std.Build) !void {
6969 if (has_msvc) {
7070 const lib_msvc = b.addStaticLibrary(.{
7171 .name = "toargv-msvc",
72 .root_source_file = .{ .path = "lib.zig" },
72 .root_source_file = b.path("lib.zig"),
7373 .target = b.resolveTargetQuery(.{
7474 .abi = .msvc,
7575 }),
......@@ -83,7 +83,7 @@ pub fn build(b: *std.Build) !void {
8383 .optimize = optimize,
8484 });
8585 verify_msvc.addCSourceFile(.{
86 .file = .{ .path = "verify.c" },
86 .file = b.path("verify.c"),
8787 .flags = &.{ "-DUNICODE", "-D_UNICODE" },
8888 });
8989 verify_msvc.linkLibrary(lib_msvc);
test/standalone/windows_resources/build.zig+1-1
......@@ -36,7 +36,7 @@ fn add(
3636 .file = b.path("res/zig.rc"),
3737 .flags = &.{"/c65001"}, // UTF-8 code page
3838 .include_paths = &.{
39 .{ .generated = &generated_h_step.generated_directory },
39 .{ .generated = .{ .file = &generated_h_step.generated_directory } },
4040 },
4141 });
4242 exe.rc_includes = switch (rc_includes) {
test/standalone/windows_spawn/build.zig+2-2
......@@ -12,14 +12,14 @@ pub fn build(b: *std.Build) void {
1212
1313 const hello = b.addExecutable(.{
1414 .name = "hello",
15 .root_source_file = .{ .path = "hello.zig" },
15 .root_source_file = b.path("hello.zig"),
1616 .optimize = optimize,
1717 .target = target,
1818 });
1919
2020 const main = b.addExecutable(.{
2121 .name = "main",
22 .root_source_file = .{ .path = "main.zig" },
22 .root_source_file = b.path("main.zig"),
2323 .optimize = optimize,
2424 .target = target,
2525 });