authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-05-04 14:29:17-04:00
committergravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-05-05 09:42:51-04:00
loge3424332d3fa1264e1f6861b76bb0d1b2996728d
tree2d786805328dd51b8d8e804ab6b655fc398d2f3f
parentd582575aba5264aaa02a8af0cdb7da7c4f4c6220

Build: cleanup

* `doc/langref` formatting * upgrade `.{ .path = "..." }` to `b.path("...")` * avoid using arguments named `self` * make `Build.Step.Id` usage more consistent * add `Build.pathResolve` * use `pathJoin` and `pathResolve` everywhere * make sure `Build.LazyPath.getPath2` returns an absolute path

59 files changed, 1306 insertions(+), 1311 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+188-194
......@@ -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 });
16621660}
16631661
1664pub fn pathJoin(self: *Build, paths: []const []const u8) []u8 {
1665 return fs.path.join(self.allocator, paths) catch @panic("OOM");
1662pub fn pathJoin(b: *Build, paths: []const []const u8) []u8 {
1663 return fs.path.join(b.allocator, paths) catch @panic("OOM");
16661664}
16671665
1668pub fn fmt(self: *Build, comptime format: []const u8, args: anytype) []u8 {
1669 return fmt_lib.allocPrint(self.allocator, format, args) catch @panic("OOM");
1666pub fn pathResolve(b: *Build, paths: []const []const u8) []u8 {
1667 return fs.path.resolve(b.allocator, paths) catch @panic("OOM");
16701668}
16711669
1672pub fn findProgram(self: *Build, names: []const []const u8, paths: []const []const u8) ![]const u8 {
1670pub fn fmt(b: *Build, comptime format: []const u8, args: anytype) []u8 {
1671 return std.fmt.allocPrint(b.allocator, format, args) catch @panic("OOM");
1672}
1673
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
......@@ -2170,9 +2169,9 @@ pub const LazyPath = union(enum) {
21702169 },
21712170
21722171 /// Deprecated. Call `path` instead.
2173 pub fn relative(p: []const u8) LazyPath {
2172 pub fn relative(sub_path: []const u8) LazyPath {
21742173 std.log.warn("deprecated. call std.Build.path instead", .{});
2175 return .{ .path = p };
2174 return .{ .path = sub_path };
21762175 }
21772176
21782177 /// Returns a lazy path referring to the directory containing this path.
......@@ -2182,8 +2181,8 @@ pub const LazyPath = union(enum) {
21822181 /// the dirname is not allowed to traverse outside of the build root.
21832182 /// Similarly, if the path is a generated file inside zig-cache,
21842183 /// the dirname is not allowed to traverse outside of zig-cache.
2185 pub fn dirname(self: LazyPath) LazyPath {
2186 return switch (self) {
2184 pub fn dirname(lazy_path: LazyPath) LazyPath {
2185 return switch (lazy_path) {
21872186 .generated => |gen| .{ .generated_dirname = .{ .generated = gen, .up = 0 } },
21882187 .generated_dirname => |gen| .{ .generated_dirname = .{ .generated = gen.generated, .up = gen.up + 1 } },
21892188 .src_path => |sp| .{ .src_path = .{
......@@ -2193,20 +2192,20 @@ pub const LazyPath = union(enum) {
21932192 @panic("misconfigured build script");
21942193 },
21952194 } },
2196 .path => |p| .{
2197 .path = dirnameAllowEmpty(p) orelse {
2195 .path => |sub_path| .{
2196 .path = dirnameAllowEmpty(sub_path) orelse {
21982197 dumpBadDirnameHelp(null, null, "dirname() attempted to traverse outside the build root\n", .{}) catch {};
21992198 @panic("misconfigured build script");
22002199 },
22012200 },
2202 .cwd_relative => |p| .{
2203 .cwd_relative = dirnameAllowEmpty(p) orelse {
2201 .cwd_relative => |rel_path| .{
2202 .cwd_relative = dirnameAllowEmpty(rel_path) orelse {
22042203 // 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 ""
2204 // - rel_path was absolute, and is now root
2205 // - rel_path was relative, and is now ""
22072206 // In either case, the build script tried to go too far
22082207 // and we should panic.
2209 if (fs.path.isAbsolute(p)) {
2208 if (fs.path.isAbsolute(rel_path)) {
22102209 dumpBadDirnameHelp(null, null,
22112210 \\dirname() attempted to traverse outside the root.
22122211 \\No more directories left to go up.
......@@ -2237,10 +2236,10 @@ pub const LazyPath = union(enum) {
22372236
22382237 /// Returns a string that can be shown to represent the file source.
22392238 /// Either returns the path or `"generated"`.
2240 pub fn getDisplayName(self: LazyPath) []const u8 {
2241 return switch (self) {
2242 .src_path => |sp| sp.sub_path,
2243 .path, .cwd_relative => |p| p,
2239 pub fn getDisplayName(lazy_path: LazyPath) []const u8 {
2240 return switch (lazy_path) {
2241 .src_path => |src_path| src_path.sub_path,
2242 .path, .cwd_relative => |sub_path| sub_path,
22442243 .generated => "generated",
22452244 .generated_dirname => "generated",
22462245 .dependency => "dependency",
......@@ -2248,8 +2247,8 @@ pub const LazyPath = union(enum) {
22482247 }
22492248
22502249 /// Adds dependencies this file source implies to the given step.
2251 pub fn addStepDependencies(self: LazyPath, other_step: *Step) void {
2252 switch (self) {
2250 pub fn addStepDependencies(lazy_path: LazyPath, other_step: *Step) void {
2251 switch (lazy_path) {
22532252 .src_path, .path, .cwd_relative, .dependency => {},
22542253 .generated => |gen| other_step.dependOn(gen.step),
22552254 .generated_dirname => |gen| other_step.dependOn(gen.generated.step),
......@@ -2258,8 +2257,8 @@ pub const LazyPath = union(enum) {
22582257
22592258 /// Returns an absolute path.
22602259 /// 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);
2260 pub fn getPath(lazy_path: LazyPath, src_builder: *Build) []const u8 {
2261 return getPath2(lazy_path, src_builder, null);
22632262 }
22642263
22652264 /// Returns an absolute path.
......@@ -2267,17 +2266,17 @@ pub const LazyPath = union(enum) {
22672266 ///
22682267 /// `asking_step` is only used for debugging purposes; it's the step being
22692268 /// run that is asking for the path.
2270 pub fn getPath2(self: LazyPath, src_builder: *Build, asking_step: ?*Step) []const u8 {
2271 switch (self) {
2269 pub fn getPath2(lazy_path: LazyPath, src_builder: *Build, asking_step: ?*Step) []const u8 {
2270 switch (lazy_path) {
22722271 .path => |p| return src_builder.pathFromRoot(p),
22732272 .src_path => |sp| return sp.owner.pathFromRoot(sp.sub_path),
22742273 .cwd_relative => |p| return src_builder.pathFromCwd(p),
2275 .generated => |gen| return gen.path orelse {
2274 .generated => |gen| return gen.step.owner.pathFromRoot(gen.path orelse {
22762275 std.debug.getStderrMutex().lock();
22772276 const stderr = std.io.getStdErr();
22782277 dumpBadGetPathHelp(gen.step, stderr, src_builder, asking_step) catch {};
22792278 @panic("misconfigured build script");
2280 },
2279 }),
22812280 .generated_dirname => |gen| {
22822281 const cache_root_path = src_builder.cache_root.path orelse
22832282 (src_builder.cache_root.join(src_builder.allocator, &.{"."}) catch @panic("OOM"));
......@@ -2311,12 +2310,7 @@ pub const LazyPath = union(enum) {
23112310 }
23122311 return p;
23132312 },
2314 .dependency => |dep| {
2315 return dep.dependency.builder.pathJoin(&[_][]const u8{
2316 dep.dependency.builder.build_root.path.?,
2317 dep.sub_path,
2318 });
2319 },
2313 .dependency => |dep| return dep.dependency.builder.pathFromRoot(dep.sub_path),
23202314 }
23212315 }
23222316
......@@ -2324,8 +2318,8 @@ pub const LazyPath = union(enum) {
23242318 ///
23252319 /// The `b` parameter is only used for its allocator. All *Build instances
23262320 /// share the same allocator.
2327 pub fn dupe(self: LazyPath, b: *Build) LazyPath {
2328 return switch (self) {
2321 pub fn dupe(lazy_path: LazyPath, b: *Build) LazyPath {
2322 return switch (lazy_path) {
23292323 .src_path => |sp| .{ .src_path = .{
23302324 .owner = sp.owner,
23312325 .sub_path = sp.owner.dupePath(sp.sub_path),
......@@ -2425,11 +2419,11 @@ pub const InstallDir = union(enum) {
24252419 custom: []const u8,
24262420
24272421 /// 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) };
2422 pub fn dupe(dir: InstallDir, builder: *Build) InstallDir {
2423 if (dir == .custom) {
2424 return .{ .custom = builder.dupe(dir.custom) };
24312425 } else {
2432 return self;
2426 return dir;
24332427 }
24342428 }
24352429};
......@@ -2439,10 +2433,10 @@ pub const InstalledFile = struct {
24392433 path: []const u8,
24402434
24412435 /// Duplicates the installed file path and directory.
2442 pub fn dupe(self: InstalledFile, builder: *Build) InstalledFile {
2436 pub fn dupe(file: InstalledFile, builder: *Build) InstalledFile {
24432437 return .{
2444 .dir = self.dir.dupe(builder),
2445 .path = builder.dupe(self.path),
2438 .dir = file.dir.dupe(builder),
2439 .path = builder.dupe(file.path),
24462440 };
24472441 }
24482442};
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+350-351
......@@ -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,155 @@ 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 {
808fn getEmittedFileGeneric(compile: *Compile, output_file: *?*GeneratedFile) LazyPath {
809809 if (output_file.*) |g| {
810810 return .{ .generated = g };
811811 }
812 const arena = self.step.owner.allocator;
812 const arena = compile.step.owner.allocator;
813813 const generated_file = arena.create(GeneratedFile) catch @panic("OOM");
814 generated_file.* = .{ .step = &self.step };
814 generated_file.* = .{ .step = &compile.step };
815815 output_file.* = generated_file;
816816 return .{ .generated = generated_file };
817817}
818818
819819/// 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);
820pub fn getEmittedBinDirectory(compile: *Compile) LazyPath {
821 _ = compile.getEmittedBin();
822 return compile.getEmittedFileGeneric(&compile.emit_directory);
823823}
824824
825825/// Returns the path to the generated executable, library or object file.
826826/// 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);
827pub fn getEmittedBin(compile: *Compile) LazyPath {
828 return compile.getEmittedFileGeneric(&compile.generated_bin);
829829}
830830
831831/// Returns the path to the generated import library.
832832/// 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);
833pub fn getEmittedImplib(compile: *Compile) LazyPath {
834 assert(compile.kind == .lib);
835 return compile.getEmittedFileGeneric(&compile.generated_implib);
836836}
837837
838838/// Returns the path to the generated header file.
839839/// 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);
840pub fn getEmittedH(compile: *Compile) LazyPath {
841 assert(compile.kind != .exe and compile.kind != .@"test");
842 return compile.getEmittedFileGeneric(&compile.generated_h);
843843}
844844
845845/// Returns the generated PDB file.
846846/// If the compilation does not produce a PDB file, this causes a FileNotFound error
847847/// at build time.
848pub fn getEmittedPdb(self: *Compile) LazyPath {
849 _ = self.getEmittedBin();
850 return self.getEmittedFileGeneric(&self.generated_pdb);
848pub fn getEmittedPdb(compile: *Compile) LazyPath {
849 _ = compile.getEmittedBin();
850 return compile.getEmittedFileGeneric(&compile.generated_pdb);
851851}
852852
853853/// Returns the path to the generated documentation directory.
854pub fn getEmittedDocs(self: *Compile) LazyPath {
855 return self.getEmittedFileGeneric(&self.generated_docs);
854pub fn getEmittedDocs(compile: *Compile) LazyPath {
855 return compile.getEmittedFileGeneric(&compile.generated_docs);
856856}
857857
858858/// Returns the path to the generated assembly code.
859pub fn getEmittedAsm(self: *Compile) LazyPath {
860 return self.getEmittedFileGeneric(&self.generated_asm);
859pub fn getEmittedAsm(compile: *Compile) LazyPath {
860 return compile.getEmittedFileGeneric(&compile.generated_asm);
861861}
862862
863863/// Returns the path to the generated LLVM IR.
864pub fn getEmittedLlvmIr(self: *Compile) LazyPath {
865 return self.getEmittedFileGeneric(&self.generated_llvm_ir);
864pub fn getEmittedLlvmIr(compile: *Compile) LazyPath {
865 return compile.getEmittedFileGeneric(&compile.generated_llvm_ir);
866866}
867867
868868/// Returns the path to the generated LLVM BC.
869pub fn getEmittedLlvmBc(self: *Compile) LazyPath {
870 return self.getEmittedFileGeneric(&self.generated_llvm_bc);
869pub fn getEmittedLlvmBc(compile: *Compile) LazyPath {
870 return compile.getEmittedFileGeneric(&compile.generated_llvm_bc);
871871}
872872
873pub fn addAssemblyFile(self: *Compile, source: LazyPath) void {
874 self.root_module.addAssemblyFile(source);
873pub fn addAssemblyFile(compile: *Compile, source: LazyPath) void {
874 compile.root_module.addAssemblyFile(source);
875875}
876876
877pub fn addObjectFile(self: *Compile, source: LazyPath) void {
878 self.root_module.addObjectFile(source);
877pub fn addObjectFile(compile: *Compile, source: LazyPath) void {
878 compile.root_module.addObjectFile(source);
879879}
880880
881pub fn addObject(self: *Compile, object: *Compile) void {
882 self.root_module.addObject(object);
881pub fn addObject(compile: *Compile, object: *Compile) void {
882 compile.root_module.addObject(object);
883883}
884884
885pub fn linkLibrary(self: *Compile, library: *Compile) void {
886 self.root_module.linkLibrary(library);
885pub fn linkLibrary(compile: *Compile, library: *Compile) void {
886 compile.root_module.linkLibrary(library);
887887}
888888
889pub fn addAfterIncludePath(self: *Compile, lazy_path: LazyPath) void {
890 self.root_module.addAfterIncludePath(lazy_path);
889pub fn addAfterIncludePath(compile: *Compile, lazy_path: LazyPath) void {
890 compile.root_module.addAfterIncludePath(lazy_path);
891891}
892892
893pub fn addSystemIncludePath(self: *Compile, lazy_path: LazyPath) void {
894 self.root_module.addSystemIncludePath(lazy_path);
893pub fn addSystemIncludePath(compile: *Compile, lazy_path: LazyPath) void {
894 compile.root_module.addSystemIncludePath(lazy_path);
895895}
896896
897pub fn addIncludePath(self: *Compile, lazy_path: LazyPath) void {
898 self.root_module.addIncludePath(lazy_path);
897pub fn addIncludePath(compile: *Compile, lazy_path: LazyPath) void {
898 compile.root_module.addIncludePath(lazy_path);
899899}
900900
901pub fn addConfigHeader(self: *Compile, config_header: *Step.ConfigHeader) void {
902 self.root_module.addConfigHeader(config_header);
901pub fn addConfigHeader(compile: *Compile, config_header: *Step.ConfigHeader) void {
902 compile.root_module.addConfigHeader(config_header);
903903}
904904
905pub fn addLibraryPath(self: *Compile, directory_path: LazyPath) void {
906 self.root_module.addLibraryPath(directory_path);
905pub fn addLibraryPath(compile: *Compile, directory_path: LazyPath) void {
906 compile.root_module.addLibraryPath(directory_path);
907907}
908908
909pub fn addRPath(self: *Compile, directory_path: LazyPath) void {
910 self.root_module.addRPath(directory_path);
909pub fn addRPath(compile: *Compile, directory_path: LazyPath) void {
910 compile.root_module.addRPath(directory_path);
911911}
912912
913pub fn addSystemFrameworkPath(self: *Compile, directory_path: LazyPath) void {
914 self.root_module.addSystemFrameworkPath(directory_path);
913pub fn addSystemFrameworkPath(compile: *Compile, directory_path: LazyPath) void {
914 compile.root_module.addSystemFrameworkPath(directory_path);
915915}
916916
917pub fn addFrameworkPath(self: *Compile, directory_path: LazyPath) void {
918 self.root_module.addFrameworkPath(directory_path);
917pub fn addFrameworkPath(compile: *Compile, directory_path: LazyPath) void {
918 compile.root_module.addFrameworkPath(directory_path);
919919}
920920
921pub fn setExecCmd(self: *Compile, args: []const ?[]const u8) void {
922 const b = self.step.owner;
923 assert(self.kind == .@"test");
921pub fn setExecCmd(compile: *Compile, args: []const ?[]const u8) void {
922 const b = compile.step.owner;
923 assert(compile.kind == .@"test");
924924 const duped_args = b.allocator.alloc(?[]u8, args.len) catch @panic("OOM");
925925 for (args, 0..) |arg, i| {
926926 duped_args[i] = if (arg) |a| b.dupe(a) else null;
927927 }
928 self.exec_cmd_args = duped_args;
928 compile.exec_cmd_args = duped_args;
929929}
930930
931931const CliNamedModules = struct {
......@@ -937,42 +937,42 @@ const CliNamedModules = struct {
937937 /// It will help here to have both a mapping from module to name and a set
938938 /// of all the currently-used names.
939939 fn init(arena: Allocator, root_module: *Module) Allocator.Error!CliNamedModules {
940 var self: CliNamedModules = .{
940 var compile: CliNamedModules = .{
941941 .modules = .{},
942942 .names = .{},
943943 };
944 var it = root_module.iterateDependencies(null, false);
944 var dep_it = root_module.iterateDependencies(null, false);
945945 {
946 const item = it.next().?;
946 const item = dep_it.next().?;
947947 assert(root_module == item.module);
948 try self.modules.put(arena, root_module, {});
949 try self.names.put(arena, "root", {});
948 try compile.modules.put(arena, root_module, {});
949 try compile.names.put(arena, "root", {});
950950 }
951 while (it.next()) |item| {
951 while (dep_it.next()) |item| {
952952 var name = item.name;
953953 var n: usize = 0;
954954 while (true) {
955 const gop = try self.names.getOrPut(arena, name);
955 const gop = try compile.names.getOrPut(arena, name);
956956 if (!gop.found_existing) {
957 try self.modules.putNoClobber(arena, item.module, {});
957 try compile.modules.putNoClobber(arena, item.module, {});
958958 break;
959959 }
960960 name = try std.fmt.allocPrint(arena, "{s}{d}", .{ item.name, n });
961961 n += 1;
962962 }
963963 }
964 return self;
964 return compile;
965965 }
966966};
967967
968fn getGeneratedFilePath(self: *Compile, comptime tag_name: []const u8, asking_step: ?*Step) []const u8 {
969 const maybe_path: ?*GeneratedFile = @field(self, tag_name);
968fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking_step: ?*Step) []const u8 {
969 const maybe_path: ?*GeneratedFile = @field(compile, tag_name);
970970
971971 const generated_file = maybe_path orelse {
972972 std.debug.getStderrMutex().lock();
973973 const stderr = std.io.getStdErr();
974974
975 std.Build.dumpBadGetPathHelp(&self.step, stderr, self.step.owner, asking_step) catch {};
975 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
976976
977977 @panic("missing emit option for " ++ tag_name);
978978 };
......@@ -981,7 +981,7 @@ fn getGeneratedFilePath(self: *Compile, comptime tag_name: []const u8, asking_st
981981 std.debug.getStderrMutex().lock();
982982 const stderr = std.io.getStdErr();
983983
984 std.Build.dumpBadGetPathHelp(&self.step, stderr, self.step.owner, asking_step) catch {};
984 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
985985
986986 @panic(tag_name ++ " is null. Is there a missing step dependency?");
987987 };
......@@ -992,14 +992,14 @@ fn getGeneratedFilePath(self: *Compile, comptime tag_name: []const u8, asking_st
992992fn make(step: *Step, prog_node: *std.Progress.Node) !void {
993993 const b = step.owner;
994994 const arena = b.allocator;
995 const self: *Compile = @fieldParentPtr("step", step);
995 const compile: *Compile = @fieldParentPtr("step", step);
996996
997997 var zig_args = ArrayList([]const u8).init(arena);
998998 defer zig_args.deinit();
999999
10001000 try zig_args.append(b.graph.zig_exe);
10011001
1002 const cmd = switch (self.kind) {
1002 const cmd = switch (compile.kind) {
10031003 .lib => "build-lib",
10041004 .exe => "build-exe",
10051005 .obj => "build-obj",
......@@ -1011,14 +1011,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
10111011 try zig_args.append(try std.fmt.allocPrint(arena, "-freference-trace={d}", .{some}));
10121012 }
10131013
1014 try addFlag(&zig_args, "llvm", self.use_llvm);
1015 try addFlag(&zig_args, "lld", self.use_lld);
1014 try addFlag(&zig_args, "llvm", compile.use_llvm);
1015 try addFlag(&zig_args, "lld", compile.use_lld);
10161016
1017 if (self.root_module.resolved_target.?.query.ofmt) |ofmt| {
1017 if (compile.root_module.resolved_target.?.query.ofmt) |ofmt| {
10181018 try zig_args.append(try std.fmt.allocPrint(arena, "-ofmt={s}", .{@tagName(ofmt)}));
10191019 }
10201020
1021 switch (self.entry) {
1021 switch (compile.entry) {
10221022 .default => {},
10231023 .disabled => try zig_args.append("-fno-entry"),
10241024 .enabled => try zig_args.append("-fentry"),
......@@ -1028,14 +1028,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
10281028 }
10291029
10301030 {
1031 var it = self.force_undefined_symbols.keyIterator();
1032 while (it.next()) |symbol_name| {
1031 var symbol_it = compile.force_undefined_symbols.keyIterator();
1032 while (symbol_it.next()) |symbol_name| {
10331033 try zig_args.append("--force_undefined");
10341034 try zig_args.append(symbol_name.*);
10351035 }
10361036 }
10371037
1038 if (self.stack_size) |stack_size| {
1038 if (compile.stack_size) |stack_size| {
10391039 try zig_args.append("--stack");
10401040 try zig_args.append(try std.fmt.allocPrint(arena, "{}", .{stack_size}));
10411041 }
......@@ -1053,47 +1053,44 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
10531053 var prev_preferred_link_mode: std.builtin.LinkMode = .dynamic;
10541054 // Track the number of positional arguments so that a nice error can be
10551055 // emitted if there is nothing to link.
1056 var total_linker_objects: usize = @intFromBool(self.root_module.root_source_file != null);
1056 var total_linker_objects: usize = @intFromBool(compile.root_module.root_source_file != null);
10571057
10581058 {
10591059 // Fully recursive iteration including dynamic libraries to detect
10601060 // 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;
1061 var dep_it = compile.root_module.iterateDependencies(compile, true);
1062 while (dep_it.next()) |key| {
1063 if (key.module.link_libc == true) compile.is_linking_libc = true;
1064 if (key.module.link_libcpp == true) compile.is_linking_libcpp = true;
10651065 }
10661066 }
10671067
1068 var cli_named_modules = try CliNamedModules.init(arena, &self.root_module);
1068 var cli_named_modules = try CliNamedModules.init(arena, &compile.root_module);
10691069
10701070 // For this loop, don't chase dynamic libraries because their link
10711071 // 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.?;
1072 var dep_it = compile.root_module.iterateDependencies(compile, false);
10771073
1074 while (dep_it.next()) |dep| {
10781075 // While walking transitive dependencies, if a given link object is
10791076 // already included in a library, it should not redundantly be
10801077 // placed on the linker line of the dependee.
1081 const my_responsibility = compile == self;
1082 const already_linked = !my_responsibility and compile.isDynamicLibrary();
1078 const my_responsibility = dep.compile.? == compile;
1079 const already_linked = !my_responsibility and dep.compile.?.isDynamicLibrary();
10831080
10841081 // Inherit dependencies on darwin frameworks.
10851082 if (!already_linked) {
1086 for (module.frameworks.keys(), module.frameworks.values()) |name, info| {
1083 for (dep.module.frameworks.keys(), dep.module.frameworks.values()) |name, info| {
10871084 try frameworks.put(arena, name, info);
10881085 }
10891086 }
10901087
10911088 // Inherit dependencies on system libraries and static libraries.
1092 for (module.link_objects.items) |link_object| {
1089 for (dep.module.link_objects.items) |link_object| {
10931090 switch (link_object) {
10941091 .static_path => |static_path| {
10951092 if (my_responsibility) {
1096 try zig_args.append(static_path.getPath2(module.owner, step));
1093 try zig_args.append(static_path.getPath2(dep.module.owner, step));
10971094 total_linker_objects += 1;
10981095 }
10991096 },
......@@ -1111,7 +1108,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11111108
11121109 if ((system_lib.search_strategy != prev_search_strategy or
11131110 system_lib.preferred_link_mode != prev_preferred_link_mode) and
1114 self.linkage != .static)
1111 compile.linkage != .static)
11151112 {
11161113 switch (system_lib.search_strategy) {
11171114 .no_fallback => switch (system_lib.preferred_link_mode) {
......@@ -1139,7 +1136,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11391136 switch (system_lib.use_pkg_config) {
11401137 .no => try zig_args.append(b.fmt("{s}{s}", .{ prefix, system_lib.name })),
11411138 .yes, .force => {
1142 if (self.runPkgConfig(system_lib.name)) |result| {
1139 if (compile.runPkgConfig(system_lib.name)) |result| {
11431140 try zig_args.appendSlice(result.cflags);
11441141 try zig_args.appendSlice(result.libs);
11451142 try seen_system_libs.put(arena, system_lib.name, result.cflags);
......@@ -1174,9 +1171,10 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11741171 .exe => return step.fail("cannot link with an executable build artifact", .{}),
11751172 .@"test" => return step.fail("cannot link with a test", .{}),
11761173 .obj => {
1177 const included_in_lib_or_obj = !my_responsibility and (compile.kind == .lib or compile.kind == .obj);
1174 const included_in_lib_or_obj = !my_responsibility and
1175 (dep.compile.?.kind == .lib or dep.compile.?.kind == .obj);
11781176 if (!already_linked and !included_in_lib_or_obj) {
1179 try zig_args.append(other.getEmittedBin().getPath(b));
1177 try zig_args.append(other.getEmittedBin().getPath2(b, step));
11801178 total_linker_objects += 1;
11811179 }
11821180 },
......@@ -1184,7 +1182,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11841182 const other_produces_implib = other.producesImplib();
11851183 const other_is_static = other_produces_implib or other.isStaticLibrary();
11861184
1187 if (self.isStaticLibrary() and other_is_static) {
1185 if (compile.isStaticLibrary() and other_is_static) {
11881186 // Avoid putting a static library inside a static library.
11891187 break :l;
11901188 }
......@@ -1193,15 +1191,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
11931191 // For everything else, we directly link
11941192 // against the library file.
11951193 const full_path_lib = if (other_produces_implib)
1196 other.getGeneratedFilePath("generated_implib", &self.step)
1194 other.getGeneratedFilePath("generated_implib", &compile.step)
11971195 else
1198 other.getGeneratedFilePath("generated_bin", &self.step);
1196 other.getGeneratedFilePath("generated_bin", &compile.step);
11991197
12001198 try zig_args.append(full_path_lib);
12011199 total_linker_objects += 1;
12021200
12031201 if (other.linkage == .dynamic and
1204 self.rootModuleTarget().os.tag != .windows)
1202 compile.rootModuleTarget().os.tag != .windows)
12051203 {
12061204 if (fs.path.dirname(full_path_lib)) |dirname| {
12071205 try zig_args.append("-rpath");
......@@ -1219,7 +1217,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12191217 try zig_args.append("--");
12201218 prev_has_cflags = false;
12211219 }
1222 try zig_args.append(asm_file.getPath2(module.owner, step));
1220 try zig_args.append(asm_file.getPath2(dep.module.owner, step));
12231221 total_linker_objects += 1;
12241222 },
12251223
......@@ -1240,7 +1238,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12401238 try zig_args.append("--");
12411239 prev_has_cflags = true;
12421240 }
1243 try zig_args.append(c_source_file.file.getPath2(module.owner, step));
1241 try zig_args.append(c_source_file.file.getPath2(dep.module.owner, step));
12441242 total_linker_objects += 1;
12451243 },
12461244
......@@ -1262,7 +1260,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12621260 prev_has_cflags = true;
12631261 }
12641262
1265 const root_path = c_source_files.root.getPath2(module.owner, step);
1263 const root_path = c_source_files.root.getPath2(dep.module.owner, step);
12661264 for (c_source_files.files) |file| {
12671265 try zig_args.append(b.pathJoin(&.{ root_path, file }));
12681266 }
......@@ -1286,12 +1284,12 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
12861284 }
12871285 for (rc_source_file.include_paths) |include_path| {
12881286 try zig_args.append("/I");
1289 try zig_args.append(include_path.getPath2(module.owner, step));
1287 try zig_args.append(include_path.getPath2(dep.module.owner, step));
12901288 }
12911289 try zig_args.append("--");
12921290 prev_has_rcflags = true;
12931291 }
1294 try zig_args.append(rc_source_file.file.getPath2(module.owner, step));
1292 try zig_args.append(rc_source_file.file.getPath2(dep.module.owner, step));
12951293 total_linker_objects += 1;
12961294 },
12971295 }
......@@ -1300,20 +1298,20 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13001298 // We need to emit the --mod argument here so that the above link objects
13011299 // have the correct parent module, but only if the module is part of
13021300 // this compilation.
1303 if (cli_named_modules.modules.getIndex(module)) |module_cli_index| {
1301 if (cli_named_modules.modules.getIndex(dep.module)) |module_cli_index| {
13041302 const module_cli_name = cli_named_modules.names.keys()[module_cli_index];
1305 try module.appendZigProcessFlags(&zig_args, step);
1303 try dep.module.appendZigProcessFlags(&zig_args, step);
13061304
13071305 // --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];
1306 try zig_args.ensureUnusedCapacity(dep.module.import_table.count() * 2);
1307 for (dep.module.import_table.keys(), dep.module.import_table.values()) |name, import| {
1308 const import_index = cli_named_modules.modules.getIndex(import).?;
1309 const import_cli_name = cli_named_modules.names.keys()[import_index];
13121310 zig_args.appendAssumeCapacity("--dep");
1313 if (std.mem.eql(u8, dep_cli_name, name)) {
1314 zig_args.appendAssumeCapacity(dep_cli_name);
1311 if (std.mem.eql(u8, import_cli_name, name)) {
1312 zig_args.appendAssumeCapacity(import_cli_name);
13151313 } else {
1316 zig_args.appendAssumeCapacity(b.fmt("{s}={s}", .{ name, dep_cli_name }));
1314 zig_args.appendAssumeCapacity(b.fmt("{s}={s}", .{ name, import_cli_name }));
13171315 }
13181316 }
13191317
......@@ -1324,10 +1322,10 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13241322 // perhaps a set of linker objects, or C source files instead.
13251323 // Linker objects are added to the CLI globally, while C source
13261324 // files must have a module parent.
1327 if (module.root_source_file) |lp| {
1328 const src = lp.getPath2(module.owner, step);
1325 if (dep.module.root_source_file) |lp| {
1326 const src = lp.getPath2(dep.module.owner, step);
13291327 try zig_args.append(b.fmt("-M{s}={s}", .{ module_cli_name, src }));
1330 } else if (moduleNeedsCliArg(module)) {
1328 } else if (moduleNeedsCliArg(dep.module)) {
13311329 try zig_args.append(b.fmt("-M{s}", .{module_cli_name}));
13321330 }
13331331 }
......@@ -1348,32 +1346,32 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13481346 try zig_args.append(name);
13491347 }
13501348
1351 if (self.is_linking_libcpp) {
1349 if (compile.is_linking_libcpp) {
13521350 try zig_args.append("-lc++");
13531351 }
13541352
1355 if (self.is_linking_libc) {
1353 if (compile.is_linking_libc) {
13561354 try zig_args.append("-lc");
13571355 }
13581356 }
13591357
1360 if (self.win32_manifest) |manifest_file| {
1361 try zig_args.append(manifest_file.getPath(b));
1358 if (compile.win32_manifest) |manifest_file| {
1359 try zig_args.append(manifest_file.getPath2(b, step));
13621360 }
13631361
1364 if (self.image_base) |image_base| {
1362 if (compile.image_base) |image_base| {
13651363 try zig_args.append("--image-base");
13661364 try zig_args.append(b.fmt("0x{x}", .{image_base}));
13671365 }
13681366
1369 for (self.filters) |filter| {
1367 for (compile.filters) |filter| {
13701368 try zig_args.append("--test-filter");
13711369 try zig_args.append(filter);
13721370 }
13731371
1374 if (self.test_runner) |test_runner| {
1372 if (compile.test_runner) |test_runner| {
13751373 try zig_args.append("--test-runner");
1376 try zig_args.append(test_runner.getPath(b));
1374 try zig_args.append(test_runner.getPath2(b, step));
13771375 }
13781376
13791377 for (b.debug_log_scopes) |log_scope| {
......@@ -1389,71 +1387,71 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
13891387 if (b.verbose_air) try zig_args.append("--verbose-air");
13901388 if (b.verbose_llvm_ir) |path| try zig_args.append(b.fmt("--verbose-llvm-ir={s}", .{path}));
13911389 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");
1390 if (b.verbose_link or compile.verbose_link) try zig_args.append("--verbose-link");
1391 if (b.verbose_cc or compile.verbose_cc) try zig_args.append("--verbose-cc");
13941392 if (b.verbose_llvm_cpu_features) try zig_args.append("--verbose-llvm-cpu-features");
13951393
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");
1394 if (compile.generated_asm != null) try zig_args.append("-femit-asm");
1395 if (compile.generated_bin == null) try zig_args.append("-fno-emit-bin");
1396 if (compile.generated_docs != null) try zig_args.append("-femit-docs");
1397 if (compile.generated_implib != null) try zig_args.append("-femit-implib");
1398 if (compile.generated_llvm_bc != null) try zig_args.append("-femit-llvm-bc");
1399 if (compile.generated_llvm_ir != null) try zig_args.append("-femit-llvm-ir");
1400 if (compile.generated_h != null) try zig_args.append("-femit-h");
14031401
1404 try addFlag(&zig_args, "formatted-panics", self.formatted_panics);
1402 try addFlag(&zig_args, "formatted-panics", compile.formatted_panics);
14051403
1406 switch (self.compress_debug_sections) {
1404 switch (compile.compress_debug_sections) {
14071405 .none => {},
14081406 .zlib => try zig_args.append("--compress-debug-sections=zlib"),
14091407 .zstd => try zig_args.append("--compress-debug-sections=zstd"),
14101408 }
14111409
1412 if (self.link_eh_frame_hdr) {
1410 if (compile.link_eh_frame_hdr) {
14131411 try zig_args.append("--eh-frame-hdr");
14141412 }
1415 if (self.link_emit_relocs) {
1413 if (compile.link_emit_relocs) {
14161414 try zig_args.append("--emit-relocs");
14171415 }
1418 if (self.link_function_sections) {
1416 if (compile.link_function_sections) {
14191417 try zig_args.append("-ffunction-sections");
14201418 }
1421 if (self.link_data_sections) {
1419 if (compile.link_data_sections) {
14221420 try zig_args.append("-fdata-sections");
14231421 }
1424 if (self.link_gc_sections) |x| {
1422 if (compile.link_gc_sections) |x| {
14251423 try zig_args.append(if (x) "--gc-sections" else "--no-gc-sections");
14261424 }
1427 if (!self.linker_dynamicbase) {
1425 if (!compile.linker_dynamicbase) {
14281426 try zig_args.append("--no-dynamicbase");
14291427 }
1430 if (self.linker_allow_shlib_undefined) |x| {
1428 if (compile.linker_allow_shlib_undefined) |x| {
14311429 try zig_args.append(if (x) "-fallow-shlib-undefined" else "-fno-allow-shlib-undefined");
14321430 }
1433 if (self.link_z_notext) {
1431 if (compile.link_z_notext) {
14341432 try zig_args.append("-z");
14351433 try zig_args.append("notext");
14361434 }
1437 if (!self.link_z_relro) {
1435 if (!compile.link_z_relro) {
14381436 try zig_args.append("-z");
14391437 try zig_args.append("norelro");
14401438 }
1441 if (self.link_z_lazy) {
1439 if (compile.link_z_lazy) {
14421440 try zig_args.append("-z");
14431441 try zig_args.append("lazy");
14441442 }
1445 if (self.link_z_common_page_size) |size| {
1443 if (compile.link_z_common_page_size) |size| {
14461444 try zig_args.append("-z");
14471445 try zig_args.append(b.fmt("common-page-size={d}", .{size}));
14481446 }
1449 if (self.link_z_max_page_size) |size| {
1447 if (compile.link_z_max_page_size) |size| {
14501448 try zig_args.append("-z");
14511449 try zig_args.append(b.fmt("max-page-size={d}", .{size}));
14521450 }
14531451
1454 if (self.libc_file) |libc_file| {
1452 if (compile.libc_file) |libc_file| {
14551453 try zig_args.append("--libc");
1456 try zig_args.append(libc_file.getPath(b));
1454 try zig_args.append(libc_file.getPath2(b, step));
14571455 } else if (b.libc_file) |libc_file| {
14581456 try zig_args.append("--libc");
14591457 try zig_args.append(libc_file);
......@@ -1466,105 +1464,105 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
14661464 try zig_args.append(b.graph.global_cache_root.path orelse ".");
14671465
14681466 try zig_args.append("--name");
1469 try zig_args.append(self.name);
1467 try zig_args.append(compile.name);
14701468
1471 if (self.linkage) |some| switch (some) {
1469 if (compile.linkage) |some| switch (some) {
14721470 .dynamic => try zig_args.append("-dynamic"),
14731471 .static => try zig_args.append("-static"),
14741472 };
1475 if (self.kind == .lib and self.linkage != null and self.linkage.? == .dynamic) {
1476 if (self.version) |version| {
1473 if (compile.kind == .lib and compile.linkage != null and compile.linkage.? == .dynamic) {
1474 if (compile.version) |version| {
14771475 try zig_args.append("--version");
14781476 try zig_args.append(b.fmt("{}", .{version}));
14791477 }
14801478
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(),
1479 if (compile.rootModuleTarget().isDarwin()) {
1480 const install_name = compile.install_name orelse b.fmt("@rpath/{s}{s}{s}", .{
1481 compile.rootModuleTarget().libPrefix(),
1482 compile.name,
1483 compile.rootModuleTarget().dynamicLibSuffix(),
14861484 });
14871485 try zig_args.append("-install_name");
14881486 try zig_args.append(install_name);
14891487 }
14901488 }
14911489
1492 if (self.entitlements) |entitlements| {
1490 if (compile.entitlements) |entitlements| {
14931491 try zig_args.appendSlice(&[_][]const u8{ "--entitlements", entitlements });
14941492 }
1495 if (self.pagezero_size) |pagezero_size| {
1493 if (compile.pagezero_size) |pagezero_size| {
14961494 const size = try std.fmt.allocPrint(arena, "{x}", .{pagezero_size});
14971495 try zig_args.appendSlice(&[_][]const u8{ "-pagezero_size", size });
14981496 }
1499 if (self.headerpad_size) |headerpad_size| {
1497 if (compile.headerpad_size) |headerpad_size| {
15001498 const size = try std.fmt.allocPrint(arena, "{x}", .{headerpad_size});
15011499 try zig_args.appendSlice(&[_][]const u8{ "-headerpad", size });
15021500 }
1503 if (self.headerpad_max_install_names) {
1501 if (compile.headerpad_max_install_names) {
15041502 try zig_args.append("-headerpad_max_install_names");
15051503 }
1506 if (self.dead_strip_dylibs) {
1504 if (compile.dead_strip_dylibs) {
15071505 try zig_args.append("-dead_strip_dylibs");
15081506 }
1509 if (self.force_load_objc) {
1507 if (compile.force_load_objc) {
15101508 try zig_args.append("-ObjC");
15111509 }
15121510
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) {
1511 try addFlag(&zig_args, "compiler-rt", compile.bundle_compiler_rt);
1512 try addFlag(&zig_args, "dll-export-fns", compile.dll_export_fns);
1513 if (compile.rdynamic) {
15161514 try zig_args.append("-rdynamic");
15171515 }
1518 if (self.import_memory) {
1516 if (compile.import_memory) {
15191517 try zig_args.append("--import-memory");
15201518 }
1521 if (self.export_memory) {
1519 if (compile.export_memory) {
15221520 try zig_args.append("--export-memory");
15231521 }
1524 if (self.import_symbols) {
1522 if (compile.import_symbols) {
15251523 try zig_args.append("--import-symbols");
15261524 }
1527 if (self.import_table) {
1525 if (compile.import_table) {
15281526 try zig_args.append("--import-table");
15291527 }
1530 if (self.export_table) {
1528 if (compile.export_table) {
15311529 try zig_args.append("--export-table");
15321530 }
1533 if (self.initial_memory) |initial_memory| {
1531 if (compile.initial_memory) |initial_memory| {
15341532 try zig_args.append(b.fmt("--initial-memory={d}", .{initial_memory}));
15351533 }
1536 if (self.max_memory) |max_memory| {
1534 if (compile.max_memory) |max_memory| {
15371535 try zig_args.append(b.fmt("--max-memory={d}", .{max_memory}));
15381536 }
1539 if (self.shared_memory) {
1537 if (compile.shared_memory) {
15401538 try zig_args.append("--shared-memory");
15411539 }
1542 if (self.global_base) |global_base| {
1540 if (compile.global_base) |global_base| {
15431541 try zig_args.append(b.fmt("--global-base={d}", .{global_base}));
15441542 }
15451543
1546 if (self.wasi_exec_model) |model| {
1544 if (compile.wasi_exec_model) |model| {
15471545 try zig_args.append(b.fmt("-mexec-model={s}", .{@tagName(model)}));
15481546 }
1549 if (self.linker_script) |linker_script| {
1547 if (compile.linker_script) |linker_script| {
15501548 try zig_args.append("--script");
1551 try zig_args.append(linker_script.getPath(b));
1549 try zig_args.append(linker_script.getPath2(b, step));
15521550 }
15531551
1554 if (self.version_script) |version_script| {
1552 if (compile.version_script) |version_script| {
15551553 try zig_args.append("--version-script");
1556 try zig_args.append(version_script.getPath(b));
1554 try zig_args.append(version_script.getPath2(b, step));
15571555 }
1558 if (self.linker_allow_undefined_version) |x| {
1556 if (compile.linker_allow_undefined_version) |x| {
15591557 try zig_args.append(if (x) "--undefined-version" else "--no-undefined-version");
15601558 }
15611559
1562 if (self.linker_enable_new_dtags) |enabled| {
1560 if (compile.linker_enable_new_dtags) |enabled| {
15631561 try zig_args.append(if (enabled) "--enable-new-dtags" else "--disable-new-dtags");
15641562 }
15651563
1566 if (self.kind == .@"test") {
1567 if (self.exec_cmd_args) |exec_cmd_args| {
1564 if (compile.kind == .@"test") {
1565 if (compile.exec_cmd_args) |exec_cmd_args| {
15681566 for (exec_cmd_args) |cmd_arg| {
15691567 if (cmd_arg) |arg| {
15701568 try zig_args.append("--test-cmd");
......@@ -1595,7 +1593,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
15951593
15961594 if (prefix_dir.accessZ("lib", .{})) |_| {
15971595 try zig_args.appendSlice(&.{
1598 "-L", try fs.path.join(arena, &.{ search_prefix, "lib" }),
1596 "-L", b.pathJoin(&.{ search_prefix, "lib" }),
15991597 });
16001598 } else |err| switch (err) {
16011599 error.FileNotFound => {},
......@@ -1606,7 +1604,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16061604
16071605 if (prefix_dir.accessZ("include", .{})) |_| {
16081606 try zig_args.appendSlice(&.{
1609 "-I", try fs.path.join(arena, &.{ search_prefix, "include" }),
1607 "-I", b.pathJoin(&.{ search_prefix, "include" }),
16101608 });
16111609 } else |err| switch (err) {
16121610 error.FileNotFound => {},
......@@ -1616,14 +1614,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16161614 }
16171615 }
16181616
1619 if (self.rc_includes != .any) {
1617 if (compile.rc_includes != .any) {
16201618 try zig_args.append("-rcincludes");
1621 try zig_args.append(@tagName(self.rc_includes));
1619 try zig_args.append(@tagName(compile.rc_includes));
16221620 }
16231621
1624 try addFlag(&zig_args, "each-lib-rpath", self.each_lib_rpath);
1622 try addFlag(&zig_args, "each-lib-rpath", compile.each_lib_rpath);
16251623
1626 if (self.build_id) |build_id| {
1624 if (compile.build_id) |build_id| {
16271625 try zig_args.append(switch (build_id) {
16281626 .hexstring => |hs| b.fmt("--build-id=0x{s}", .{
16291627 std.fmt.fmtSliceHexLower(hs.toSlice()),
......@@ -1632,15 +1630,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16321630 });
16331631 }
16341632
1635 if (self.zig_lib_dir) |dir| {
1633 if (compile.zig_lib_dir) |dir| {
16361634 try zig_args.append("--zig-lib-dir");
1637 try zig_args.append(dir.getPath(b));
1635 try zig_args.append(dir.getPath2(b, step));
16381636 }
16391637
1640 try addFlag(&zig_args, "PIE", self.pie);
1641 try addFlag(&zig_args, "lto", self.want_lto);
1638 try addFlag(&zig_args, "PIE", compile.pie);
1639 try addFlag(&zig_args, "lto", compile.want_lto);
16421640
1643 if (self.subsystem) |subsystem| {
1641 if (compile.subsystem) |subsystem| {
16441642 try zig_args.append("--subsystem");
16451643 try zig_args.append(switch (subsystem) {
16461644 .Console => "console",
......@@ -1654,11 +1652,11 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
16541652 });
16551653 }
16561654
1657 if (self.mingw_unicode_entry_point) {
1655 if (compile.mingw_unicode_entry_point) {
16581656 try zig_args.append("-municode");
16591657 }
16601658
1661 if (self.error_limit) |err_limit| try zig_args.appendSlice(&.{
1659 if (compile.error_limit) |err_limit| try zig_args.appendSlice(&.{
16621660 "--error-limit",
16631661 b.fmt("{}", .{err_limit}),
16641662 });
......@@ -1724,8 +1722,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
17241722
17251723 const maybe_output_bin_path = step.evalZigProcess(zig_args.items, prog_node) catch |err| switch (err) {
17261724 error.NeedCompileErrorCheck => {
1727 assert(self.expect_errors != null);
1728 try checkCompileErrors(self);
1725 assert(compile.expect_errors != null);
1726 try checkCompileErrors(compile);
17291727 return;
17301728 },
17311729 else => |e| return e,
......@@ -1735,61 +1733,61 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
17351733 if (maybe_output_bin_path) |output_bin_path| {
17361734 const output_dir = fs.path.dirname(output_bin_path).?;
17371735
1738 if (self.emit_directory) |lp| {
1736 if (compile.emit_directory) |lp| {
17391737 lp.path = output_dir;
17401738 }
17411739
17421740 // -femit-bin[=path] (default) Output machine code
1743 if (self.generated_bin) |bin| {
1744 bin.path = b.pathJoin(&.{ output_dir, self.out_filename });
1741 if (compile.generated_bin) |bin| {
1742 bin.path = b.pathJoin(&.{ output_dir, compile.out_filename });
17451743 }
17461744
17471745 const sep = std.fs.path.sep;
17481746
17491747 // 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 });
1748 if (compile.generated_pdb) |pdb| {
1749 pdb.path = b.fmt("{s}{c}{s}.pdb", .{ output_dir, sep, compile.name });
17521750 }
17531751
17541752 // -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 });
1753 if (compile.generated_implib) |implib| {
1754 implib.path = b.fmt("{s}{c}{s}.lib", .{ output_dir, sep, compile.name });
17571755 }
17581756
17591757 // -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 });
1758 if (compile.generated_h) |lp| {
1759 lp.path = b.fmt("{s}{c}{s}.h", .{ output_dir, sep, compile.name });
17621760 }
17631761
17641762 // -femit-docs[=path] Create a docs/ dir with html documentation
1765 if (self.generated_docs) |generated_docs| {
1763 if (compile.generated_docs) |generated_docs| {
17661764 generated_docs.path = b.pathJoin(&.{ output_dir, "docs" });
17671765 }
17681766
17691767 // -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 });
1768 if (compile.generated_asm) |lp| {
1769 lp.path = b.fmt("{s}{c}{s}.s", .{ output_dir, sep, compile.name });
17721770 }
17731771
17741772 // -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 });
1773 if (compile.generated_llvm_ir) |lp| {
1774 lp.path = b.fmt("{s}{c}{s}.ll", .{ output_dir, sep, compile.name });
17771775 }
17781776
17791777 // -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 });
1778 if (compile.generated_llvm_bc) |lp| {
1779 lp.path = b.fmt("{s}{c}{s}.bc", .{ output_dir, sep, compile.name });
17821780 }
17831781 }
17841782
1785 if (self.kind == .lib and self.linkage != null and self.linkage.? == .dynamic and
1786 self.version != null and std.Build.wantSharedLibSymLinks(self.rootModuleTarget()))
1783 if (compile.kind == .lib and compile.linkage != null and compile.linkage.? == .dynamic and
1784 compile.version != null and std.Build.wantSharedLibSymLinks(compile.rootModuleTarget()))
17871785 {
17881786 try doAtomicSymLinks(
17891787 step,
1790 self.getEmittedBin().getPath(b),
1791 self.major_only_filename.?,
1792 self.name_only_filename.?,
1788 compile.getEmittedBin().getPath2(b, step),
1789 compile.major_only_filename.?,
1790 compile.name_only_filename.?,
17931791 );
17941792 }
17951793}
......@@ -1800,18 +1798,19 @@ pub fn doAtomicSymLinks(
18001798 filename_major_only: []const u8,
18011799 filename_name_only: []const u8,
18021800) !void {
1803 const arena = step.owner.allocator;
1801 const b = step.owner;
1802 const arena = b.allocator;
18041803 const out_dir = fs.path.dirname(output_path) orelse ".";
18051804 const out_basename = fs.path.basename(output_path);
18061805 // 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 });
1806 const major_only_path = b.pathJoin(&.{ out_dir, filename_major_only });
18081807 fs.atomicSymLink(arena, out_basename, major_only_path) catch |err| {
18091808 return step.fail("unable to symlink {s} -> {s}: {s}", .{
18101809 major_only_path, out_basename, @errorName(err),
18111810 });
18121811 };
18131812 // sym link for libfoo.so to libfoo.so.1
1814 const name_only_path = try fs.path.join(arena, &.{ out_dir, filename_name_only });
1813 const name_only_path = b.pathJoin(&.{ out_dir, filename_name_only });
18151814 fs.atomicSymLink(arena, filename_major_only, name_only_path) catch |err| {
18161815 return step.fail("Unable to symlink {s} -> {s}: {s}", .{
18171816 name_only_path, filename_major_only, @errorName(err),
......@@ -1819,9 +1818,9 @@ pub fn doAtomicSymLinks(
18191818 };
18201819}
18211820
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);
1821fn execPkgConfigList(compile: *std.Build, out_code: *u8) (PkgConfigError || RunError)![]const PkgConfigPkg {
1822 const stdout = try compile.runAllowFail(&[_][]const u8{ "pkg-config", "--list-all" }, out_code, .Ignore);
1823 var list = ArrayList(PkgConfigPkg).init(compile.allocator);
18251824 errdefer list.deinit();
18261825 var line_it = mem.tokenizeAny(u8, stdout, "\r\n");
18271826 while (line_it.next()) |line| {
......@@ -1835,13 +1834,13 @@ fn execPkgConfigList(self: *std.Build, out_code: *u8) (PkgConfigError || RunErro
18351834 return list.toOwnedSlice();
18361835}
18371836
1838fn getPkgConfigList(self: *std.Build) ![]const PkgConfigPkg {
1839 if (self.pkg_config_pkg_list) |res| {
1837fn getPkgConfigList(compile: *std.Build) ![]const PkgConfigPkg {
1838 if (compile.pkg_config_pkg_list) |res| {
18401839 return res;
18411840 }
18421841 var code: u8 = undefined;
1843 if (execPkgConfigList(self, &code)) |list| {
1844 self.pkg_config_pkg_list = list;
1842 if (execPkgConfigList(compile, &code)) |list| {
1843 compile.pkg_config_pkg_list = list;
18451844 return list;
18461845 } else |err| {
18471846 const result = switch (err) {
......@@ -1853,7 +1852,7 @@ fn getPkgConfigList(self: *std.Build) ![]const PkgConfigPkg {
18531852 error.PkgConfigInvalidOutput => error.PkgConfigInvalidOutput,
18541853 else => return err,
18551854 };
1856 self.pkg_config_pkg_list = result;
1855 compile.pkg_config_pkg_list = result;
18571856 return result;
18581857 }
18591858}
......@@ -1868,12 +1867,12 @@ fn addFlag(args: *ArrayList([]const u8), comptime name: []const u8, opt: ?bool)
18681867 }
18691868}
18701869
1871fn checkCompileErrors(self: *Compile) !void {
1870fn checkCompileErrors(compile: *Compile) !void {
18721871 // 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;
1872 const actual_eb = compile.step.result_error_bundle;
1873 compile.step.result_error_bundle = std.zig.ErrorBundle.empty;
18751874
1876 const arena = self.step.owner.allocator;
1875 const arena = compile.step.owner.allocator;
18771876
18781877 var actual_stderr_list = std.ArrayList(u8).init(arena);
18791878 try actual_eb.renderToWriter(.{
......@@ -1885,7 +1884,7 @@ fn checkCompileErrors(self: *Compile) !void {
18851884
18861885 // Render the expected lines into a string that we can compare verbatim.
18871886 var expected_generated = std.ArrayList(u8).init(arena);
1888 const expect_errors = self.expect_errors.?;
1887 const expect_errors = compile.expect_errors.?;
18891888
18901889 var actual_line_it = mem.splitScalar(u8, actual_stderr, '\n');
18911890
......@@ -1897,7 +1896,7 @@ fn checkCompileErrors(self: *Compile) !void {
18971896 return;
18981897 }
18991898
1900 return self.step.fail(
1899 return compile.step.fail(
19011900 \\
19021901 \\========= should contain: ===============
19031902 \\{s}
......@@ -1924,7 +1923,7 @@ fn checkCompileErrors(self: *Compile) !void {
19241923
19251924 if (mem.eql(u8, expected_generated.items, actual_stderr)) return;
19261925
1927 return self.step.fail(
1926 return compile.step.fail(
19281927 \\
19291928 \\========= expected: =====================
19301929 \\{s}
lib/std/Build/Step/ConfigHeader.zig+37-37
......@@ -52,7 +52,7 @@ 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
......@@ -81,7 +81,7 @@ pub fn create(owner: *std.Build, options: Options) *ConfigHeader {
8181 else
8282 owner.fmt("configure {s} header to {s}", .{ @tagName(options.style), include_path });
8383
84 self.* = .{
84 config_header.* = .{
8585 .step = Step.init(.{
8686 .id = base_id,
8787 .name = name,
......@@ -95,64 +95,64 @@ pub fn create(owner: *std.Build, options: Options) *ConfigHeader {
9595 .max_bytes = options.max_bytes,
9696 .include_path = include_path,
9797 .include_guard_override = options.include_guard_override,
98 .output_file = .{ .step = &self.step },
98 .output_file = .{ .step = &config_header.step },
9999 };
100100
101 return self;
101 return config_header;
102102}
103103
104pub fn addValues(self: *ConfigHeader, values: anytype) void {
105 return addValuesInner(self, values) catch @panic("OOM");
104pub fn addValues(config_header: *ConfigHeader, values: anytype) void {
105 return addValuesInner(config_header, values) catch @panic("OOM");
106106}
107107
108pub fn getOutput(self: *ConfigHeader) std.Build.LazyPath {
109 return .{ .generated = &self.output_file };
108pub fn getOutput(config_header: *ConfigHeader) std.Build.LazyPath {
109 return .{ .generated = &config_header.output_file };
110110}
111111
112fn addValuesInner(self: *ConfigHeader, values: anytype) !void {
112fn addValuesInner(config_header: *ConfigHeader, values: anytype) !void {
113113 inline for (@typeInfo(@TypeOf(values)).Struct.fields) |field| {
114 try putValue(self, field.name, field.type, @field(values, field.name));
114 try putValue(config_header, field.name, field.type, @field(values, field.name));
115115 }
116116}
117117
118fn putValue(self: *ConfigHeader, field_name: []const u8, comptime T: type, v: T) !void {
118fn putValue(config_header: *ConfigHeader, field_name: []const u8, comptime T: type, v: T) !void {
119119 switch (@typeInfo(T)) {
120120 .Null => {
121 try self.values.put(field_name, .undef);
121 try config_header.values.put(field_name, .undef);
122122 },
123123 .Void => {
124 try self.values.put(field_name, .defined);
124 try config_header.values.put(field_name, .defined);
125125 },
126126 .Bool => {
127 try self.values.put(field_name, .{ .boolean = v });
127 try config_header.values.put(field_name, .{ .boolean = v });
128128 },
129129 .Int => {
130 try self.values.put(field_name, .{ .int = v });
130 try config_header.values.put(field_name, .{ .int = v });
131131 },
132132 .ComptimeInt => {
133 try self.values.put(field_name, .{ .int = v });
133 try config_header.values.put(field_name, .{ .int = v });
134134 },
135135 .EnumLiteral => {
136 try self.values.put(field_name, .{ .ident = @tagName(v) });
136 try config_header.values.put(field_name, .{ .ident = @tagName(v) });
137137 },
138138 .Optional => {
139139 if (v) |x| {
140 return putValue(self, field_name, @TypeOf(x), x);
140 return putValue(config_header, field_name, @TypeOf(x), x);
141141 } else {
142 try self.values.put(field_name, .undef);
142 try config_header.values.put(field_name, .undef);
143143 }
144144 },
145145 .Pointer => |ptr| {
146146 switch (@typeInfo(ptr.child)) {
147147 .Array => |array| {
148148 if (ptr.size == .One and array.child == u8) {
149 try self.values.put(field_name, .{ .string = v });
149 try config_header.values.put(field_name, .{ .string = v });
150150 return;
151151 }
152152 },
153153 .Int => {
154154 if (ptr.size == .Slice and ptr.child == u8) {
155 try self.values.put(field_name, .{ .string = v });
155 try config_header.values.put(field_name, .{ .string = v });
156156 return;
157157 }
158158 },
......@@ -168,7 +168,7 @@ fn putValue(self: *ConfigHeader, field_name: []const u8, comptime T: type, v: T)
168168fn make(step: *Step, prog_node: *std.Progress.Node) !void {
169169 _ = prog_node;
170170 const b = step.owner;
171 const self: *ConfigHeader = @fieldParentPtr("step", step);
171 const config_header: *ConfigHeader = @fieldParentPtr("step", step);
172172 const gpa = b.allocator;
173173 const arena = b.allocator;
174174
......@@ -179,8 +179,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
179179 // random bytes when ConfigHeader implementation is modified in a
180180 // non-backwards-compatible way.
181181 man.hash.add(@as(u32, 0xdef08d23));
182 man.hash.addBytes(self.include_path);
183 man.hash.addOptionalBytes(self.include_guard_override);
182 man.hash.addBytes(config_header.include_path);
183 man.hash.addOptionalBytes(config_header.include_guard_override);
184184
185185 var output = std.ArrayList(u8).init(gpa);
186186 defer output.deinit();
......@@ -189,34 +189,34 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
189189 const c_generated_line = "/* " ++ header_text ++ " */\n";
190190 const asm_generated_line = "; " ++ header_text ++ "\n";
191191
192 switch (self.style) {
192 switch (config_header.style) {
193193 .autoconf => |file_source| {
194194 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| {
195 const src_path = file_source.getPath2(b, step);
196 const contents = std.fs.cwd().readFileAlloc(arena, src_path, config_header.max_bytes) catch |err| {
197197 return step.fail("unable to read autoconf input file '{s}': {s}", .{
198198 src_path, @errorName(err),
199199 });
200200 };
201 try render_autoconf(step, contents, &output, self.values, src_path);
201 try render_autoconf(step, contents, &output, config_header.values, src_path);
202202 },
203203 .cmake => |file_source| {
204204 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| {
205 const src_path = file_source.getPath2(b, step);
206 const contents = std.fs.cwd().readFileAlloc(arena, src_path, config_header.max_bytes) catch |err| {
207207 return step.fail("unable to read cmake input file '{s}': {s}", .{
208208 src_path, @errorName(err),
209209 });
210210 };
211 try render_cmake(step, contents, &output, self.values, src_path);
211 try render_cmake(step, contents, &output, config_header.values, src_path);
212212 },
213213 .blank => {
214214 try output.appendSlice(c_generated_line);
215 try render_blank(&output, self.values, self.include_path, self.include_guard_override);
215 try render_blank(&output, config_header.values, config_header.include_path, config_header.include_guard_override);
216216 },
217217 .nasm => {
218218 try output.appendSlice(asm_generated_line);
219 try render_nasm(&output, self.values);
219 try render_nasm(&output, config_header.values);
220220 },
221221 }
222222
......@@ -224,8 +224,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
224224
225225 if (try step.cacheHit(&man)) {
226226 const digest = man.final();
227 self.output_file.path = try b.cache_root.join(arena, &.{
228 "o", &digest, self.include_path,
227 config_header.output_file.path = try b.cache_root.join(arena, &.{
228 "o", &digest, config_header.include_path,
229229 });
230230 return;
231231 }
......@@ -237,7 +237,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
237237 // output_path is libavutil/avconfig.h
238238 // We want to open directory zig-cache/o/HASH/libavutil/
239239 // 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 });
240 const sub_path = b.pathJoin(&.{ "o", &digest, config_header.include_path });
241241 const sub_path_dirname = std.fs.path.dirname(sub_path).?;
242242
243243 b.cache_root.handle.makePath(sub_path_dirname) catch |err| {
......@@ -252,7 +252,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
252252 });
253253 };
254254
255 self.output_file.path = try b.cache_root.join(arena, &.{sub_path});
255 config_header.output_file.path = try b.cache_root.join(arena, &.{sub_path});
256256 try man.writeManifest();
257257}
258258
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 = &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 } 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 = &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+195-196
......@@ -140,8 +140,8 @@ pub const Output = struct {
140140};
141141
142142pub fn create(owner: *std.Build, name: []const u8) *Run {
143 const self = owner.allocator.create(Run) catch @panic("OOM");
144 self.* = .{
143 const run = owner.allocator.create(Run) catch @panic("OOM");
144 run.* = .{
145145 .step = Step.init(.{
146146 .id = base_id,
147147 .name = name,
......@@ -164,24 +164,24 @@ pub fn create(owner: *std.Build, name: []const u8) *Run {
164164 .dep_output_file = null,
165165 .has_side_effects = false,
166166 };
167 return self;
167 return run;
168168}
169169
170pub fn setName(self: *Run, name: []const u8) void {
171 self.step.name = name;
172 self.rename_step_with_output_arg = false;
170pub fn setName(run: *Run, name: []const u8) void {
171 run.step.name = name;
172 run.rename_step_with_output_arg = false;
173173}
174174
175pub fn enableTestRunnerMode(self: *Run) void {
176 self.stdio = .zig_test;
177 self.addArgs(&.{"--listen=-"});
175pub fn enableTestRunnerMode(run: *Run) void {
176 run.stdio = .zig_test;
177 run.addArgs(&.{"--listen=-"});
178178}
179179
180pub fn addArtifactArg(self: *Run, artifact: *Step.Compile) void {
181 const b = self.step.owner;
180pub fn addArtifactArg(run: *Run, artifact: *Step.Compile) void {
181 const b = run.step.owner;
182182 const bin_file = artifact.getEmittedBin();
183 bin_file.addStepDependencies(&self.step);
184 self.argv.append(b.allocator, Arg{ .artifact = artifact }) catch @panic("OOM");
183 bin_file.addStepDependencies(&run.step);
184 run.argv.append(b.allocator, Arg{ .artifact = artifact }) catch @panic("OOM");
185185}
186186
187187/// Provides a file path as a command line argument to the command being run.
......@@ -192,8 +192,8 @@ pub fn addArtifactArg(self: *Run, artifact: *Step.Compile) void {
192192/// Related:
193193/// * `addPrefixedOutputFileArg` - same thing but prepends a string to the argument
194194/// * `addFileArg` - for input files given to the child process
195pub fn addOutputFileArg(self: *Run, basename: []const u8) std.Build.LazyPath {
196 return self.addPrefixedOutputFileArg("", basename);
195pub fn addOutputFileArg(run: *Run, basename: []const u8) std.Build.LazyPath {
196 return run.addPrefixedOutputFileArg("", basename);
197197}
198198
199199/// Provides a file path as a command line argument to the command being run.
......@@ -212,23 +212,23 @@ pub fn addOutputFileArg(self: *Run, basename: []const u8) std.Build.LazyPath {
212212/// * `addOutputFileArg` - same thing but without the prefix
213213/// * `addFileArg` - for input files given to the child process
214214pub fn addPrefixedOutputFileArg(
215 self: *Run,
215 run: *Run,
216216 prefix: []const u8,
217217 basename: []const u8,
218218) std.Build.LazyPath {
219 const b = self.step.owner;
219 const b = run.step.owner;
220220 if (basename.len == 0) @panic("basename must not be empty");
221221
222222 const output = b.allocator.create(Output) catch @panic("OOM");
223223 output.* = .{
224224 .prefix = b.dupe(prefix),
225225 .basename = b.dupe(basename),
226 .generated_file = .{ .step = &self.step },
226 .generated_file = .{ .step = &run.step },
227227 };
228 self.argv.append(b.allocator, .{ .output = output }) catch @panic("OOM");
228 run.argv.append(b.allocator, .{ .output = output }) catch @panic("OOM");
229229
230 if (self.rename_step_with_output_arg) {
231 self.setName(b.fmt("{s} ({s})", .{ self.step.name, basename }));
230 if (run.rename_step_with_output_arg) {
231 run.setName(b.fmt("{s} ({s})", .{ run.step.name, basename }));
232232 }
233233
234234 return .{ .generated = &output.generated_file };
......@@ -243,8 +243,8 @@ pub fn addPrefixedOutputFileArg(
243243/// Related:
244244/// * `addPrefixedFileArg` - same thing but prepends a string to the argument
245245/// * `addOutputFileArg` - for files generated by the child process
246pub fn addFileArg(self: *Run, lp: std.Build.LazyPath) void {
247 self.addPrefixedFileArg("", lp);
246pub fn addFileArg(run: *Run, lp: std.Build.LazyPath) void {
247 run.addPrefixedFileArg("", lp);
248248}
249249
250250/// Appends an input file to the command line arguments prepended with a string.
......@@ -259,100 +259,98 @@ pub fn addFileArg(self: *Run, lp: std.Build.LazyPath) void {
259259/// Related:
260260/// * `addFileArg` - same thing but without the prefix
261261/// * `addOutputFileArg` - for files generated by the child process
262pub fn addPrefixedFileArg(self: *Run, prefix: []const u8, lp: std.Build.LazyPath) void {
263 const b = self.step.owner;
262pub fn addPrefixedFileArg(run: *Run, prefix: []const u8, lp: std.Build.LazyPath) void {
263 const b = run.step.owner;
264264
265265 const prefixed_file_source: PrefixedLazyPath = .{
266266 .prefix = b.dupe(prefix),
267267 .lazy_path = lp.dupe(b),
268268 };
269 self.argv.append(b.allocator, .{ .lazy_path = prefixed_file_source }) catch @panic("OOM");
270 lp.addStepDependencies(&self.step);
269 run.argv.append(b.allocator, .{ .lazy_path = prefixed_file_source }) catch @panic("OOM");
270 lp.addStepDependencies(&run.step);
271271}
272272
273273/// deprecated: use `addDirectoryArg`
274274pub const addDirectorySourceArg = addDirectoryArg;
275275
276pub fn addDirectoryArg(self: *Run, directory_source: std.Build.LazyPath) void {
277 self.addPrefixedDirectoryArg("", directory_source);
276pub fn addDirectoryArg(run: *Run, directory_source: std.Build.LazyPath) void {
277 run.addPrefixedDirectoryArg("", directory_source);
278278}
279279
280280// deprecated: use `addPrefixedDirectoryArg`
281281pub const addPrefixedDirectorySourceArg = addPrefixedDirectoryArg;
282282
283pub fn addPrefixedDirectoryArg(self: *Run, prefix: []const u8, directory_source: std.Build.LazyPath) void {
284 const b = self.step.owner;
283pub fn addPrefixedDirectoryArg(run: *Run, prefix: []const u8, directory_source: std.Build.LazyPath) void {
284 const b = run.step.owner;
285285
286286 const prefixed_directory_source: PrefixedLazyPath = .{
287287 .prefix = b.dupe(prefix),
288288 .lazy_path = directory_source.dupe(b),
289289 };
290 self.argv.append(b.allocator, .{ .directory_source = prefixed_directory_source }) catch @panic("OOM");
291 directory_source.addStepDependencies(&self.step);
290 run.argv.append(b.allocator, .{ .directory_source = prefixed_directory_source }) catch @panic("OOM");
291 directory_source.addStepDependencies(&run.step);
292292}
293293
294294/// Add a path argument to a dep file (.d) for the child process to write its
295295/// discovered additional dependencies.
296296/// Only one dep file argument is allowed by instance.
297pub fn addDepFileOutputArg(self: *Run, basename: []const u8) std.Build.LazyPath {
298 return self.addPrefixedDepFileOutputArg("", basename);
297pub fn addDepFileOutputArg(run: *Run, basename: []const u8) std.Build.LazyPath {
298 return run.addPrefixedDepFileOutputArg("", basename);
299299}
300300
301301/// Add a prefixed path argument to a dep file (.d) for the child process to
302302/// write its discovered additional dependencies.
303303/// Only one dep file argument is allowed by instance.
304pub fn addPrefixedDepFileOutputArg(self: *Run, prefix: []const u8, basename: []const u8) std.Build.LazyPath {
305 const b = self.step.owner;
306 assert(self.dep_output_file == null);
304pub fn addPrefixedDepFileOutputArg(run: *Run, prefix: []const u8, basename: []const u8) std.Build.LazyPath {
305 const b = run.step.owner;
306 assert(run.dep_output_file == null);
307307
308308 const dep_file = b.allocator.create(Output) catch @panic("OOM");
309309 dep_file.* = .{
310310 .prefix = b.dupe(prefix),
311311 .basename = b.dupe(basename),
312 .generated_file = .{ .step = &self.step },
312 .generated_file = .{ .step = &run.step },
313313 };
314314
315 self.dep_output_file = dep_file;
315 run.dep_output_file = dep_file;
316316
317 self.argv.append(b.allocator, .{ .output = dep_file }) catch @panic("OOM");
317 run.argv.append(b.allocator, .{ .output = dep_file }) catch @panic("OOM");
318318
319319 return .{ .generated = &dep_file.generated_file };
320320}
321321
322pub fn addArg(self: *Run, arg: []const u8) void {
323 const b = self.step.owner;
324 self.argv.append(b.allocator, .{ .bytes = self.step.owner.dupe(arg) }) catch @panic("OOM");
322pub fn addArg(run: *Run, arg: []const u8) void {
323 const b = run.step.owner;
324 run.argv.append(b.allocator, .{ .bytes = b.dupe(arg) }) catch @panic("OOM");
325325}
326326
327pub fn addArgs(self: *Run, args: []const []const u8) void {
328 for (args) |arg| {
329 self.addArg(arg);
330 }
327pub fn addArgs(run: *Run, args: []const []const u8) void {
328 for (args) |arg| run.addArg(arg);
331329}
332330
333pub fn setStdIn(self: *Run, stdin: StdIn) void {
331pub fn setStdIn(run: *Run, stdin: StdIn) void {
334332 switch (stdin) {
335 .lazy_path => |lazy_path| lazy_path.addStepDependencies(&self.step),
333 .lazy_path => |lazy_path| lazy_path.addStepDependencies(&run.step),
336334 .bytes, .none => {},
337335 }
338 self.stdin = stdin;
336 run.stdin = stdin;
339337}
340338
341pub fn setCwd(self: *Run, cwd: Build.LazyPath) void {
342 cwd.addStepDependencies(&self.step);
343 self.cwd = cwd;
339pub fn setCwd(run: *Run, cwd: Build.LazyPath) void {
340 cwd.addStepDependencies(&run.step);
341 run.cwd = cwd.dupe(run.step.owner);
344342}
345343
346pub fn clearEnvironment(self: *Run) void {
347 const b = self.step.owner;
344pub fn clearEnvironment(run: *Run) void {
345 const b = run.step.owner;
348346 const new_env_map = b.allocator.create(EnvMap) catch @panic("OOM");
349347 new_env_map.* = EnvMap.init(b.allocator);
350 self.env_map = new_env_map;
348 run.env_map = new_env_map;
351349}
352350
353pub fn addPathDir(self: *Run, search_path: []const u8) void {
354 const b = self.step.owner;
355 const env_map = getEnvMapInternal(self);
351pub fn addPathDir(run: *Run, search_path: []const u8) void {
352 const b = run.step.owner;
353 const env_map = getEnvMapInternal(run);
356354
357355 const key = "PATH";
358356 const prev_path = env_map.get(key);
......@@ -365,99 +363,99 @@ pub fn addPathDir(self: *Run, search_path: []const u8) void {
365363 }
366364}
367365
368pub fn getEnvMap(self: *Run) *EnvMap {
369 return getEnvMapInternal(self);
366pub fn getEnvMap(run: *Run) *EnvMap {
367 return getEnvMapInternal(run);
370368}
371369
372fn getEnvMapInternal(self: *Run) *EnvMap {
373 const arena = self.step.owner.allocator;
374 return self.env_map orelse {
370fn getEnvMapInternal(run: *Run) *EnvMap {
371 const arena = run.step.owner.allocator;
372 return run.env_map orelse {
375373 const env_map = arena.create(EnvMap) catch @panic("OOM");
376374 env_map.* = process.getEnvMap(arena) catch @panic("unhandled error");
377 self.env_map = env_map;
375 run.env_map = env_map;
378376 return env_map;
379377 };
380378}
381379
382pub fn setEnvironmentVariable(self: *Run, key: []const u8, value: []const u8) void {
383 const b = self.step.owner;
384 const env_map = self.getEnvMap();
380pub fn setEnvironmentVariable(run: *Run, key: []const u8, value: []const u8) void {
381 const b = run.step.owner;
382 const env_map = run.getEnvMap();
385383 env_map.put(b.dupe(key), b.dupe(value)) catch @panic("unhandled error");
386384}
387385
388pub fn removeEnvironmentVariable(self: *Run, key: []const u8) void {
389 self.getEnvMap().remove(key);
386pub fn removeEnvironmentVariable(run: *Run, key: []const u8) void {
387 run.getEnvMap().remove(key);
390388}
391389
392390/// Adds a check for exact stderr match. Does not add any other checks.
393pub fn expectStdErrEqual(self: *Run, bytes: []const u8) void {
394 const new_check: StdIo.Check = .{ .expect_stderr_exact = self.step.owner.dupe(bytes) };
395 self.addCheck(new_check);
391pub fn expectStdErrEqual(run: *Run, bytes: []const u8) void {
392 const new_check: StdIo.Check = .{ .expect_stderr_exact = run.step.owner.dupe(bytes) };
393 run.addCheck(new_check);
396394}
397395
398396/// Adds a check for exact stdout match as well as a check for exit code 0, if
399397/// there is not already an expected termination check.
400pub fn expectStdOutEqual(self: *Run, bytes: []const u8) void {
401 const new_check: StdIo.Check = .{ .expect_stdout_exact = self.step.owner.dupe(bytes) };
402 self.addCheck(new_check);
403 if (!self.hasTermCheck()) {
404 self.expectExitCode(0);
398pub fn expectStdOutEqual(run: *Run, bytes: []const u8) void {
399 const new_check: StdIo.Check = .{ .expect_stdout_exact = run.step.owner.dupe(bytes) };
400 run.addCheck(new_check);
401 if (!run.hasTermCheck()) {
402 run.expectExitCode(0);
405403 }
406404}
407405
408pub fn expectExitCode(self: *Run, code: u8) void {
406pub fn expectExitCode(run: *Run, code: u8) void {
409407 const new_check: StdIo.Check = .{ .expect_term = .{ .Exited = code } };
410 self.addCheck(new_check);
408 run.addCheck(new_check);
411409}
412410
413pub fn hasTermCheck(self: Run) bool {
414 for (self.stdio.check.items) |check| switch (check) {
411pub fn hasTermCheck(run: Run) bool {
412 for (run.stdio.check.items) |check| switch (check) {
415413 .expect_term => return true,
416414 else => continue,
417415 };
418416 return false;
419417}
420418
421pub fn addCheck(self: *Run, new_check: StdIo.Check) void {
422 const b = self.step.owner;
419pub fn addCheck(run: *Run, new_check: StdIo.Check) void {
420 const b = run.step.owner;
423421
424 switch (self.stdio) {
422 switch (run.stdio) {
425423 .infer_from_args => {
426 self.stdio = .{ .check = .{} };
427 self.stdio.check.append(b.allocator, new_check) catch @panic("OOM");
424 run.stdio = .{ .check = .{} };
425 run.stdio.check.append(b.allocator, new_check) catch @panic("OOM");
428426 },
429427 .check => |*checks| checks.append(b.allocator, new_check) catch @panic("OOM"),
430428 else => @panic("illegal call to addCheck: conflicting helper method calls. Suggest to directly set stdio field of Run instead"),
431429 }
432430}
433431
434pub fn captureStdErr(self: *Run) std.Build.LazyPath {
435 assert(self.stdio != .inherit);
432pub fn captureStdErr(run: *Run) std.Build.LazyPath {
433 assert(run.stdio != .inherit);
436434
437 if (self.captured_stderr) |output| return .{ .generated = &output.generated_file };
435 if (run.captured_stderr) |output| return .{ .generated = &output.generated_file };
438436
439 const output = self.step.owner.allocator.create(Output) catch @panic("OOM");
437 const output = run.step.owner.allocator.create(Output) catch @panic("OOM");
440438 output.* = .{
441439 .prefix = "",
442440 .basename = "stderr",
443 .generated_file = .{ .step = &self.step },
441 .generated_file = .{ .step = &run.step },
444442 };
445 self.captured_stderr = output;
443 run.captured_stderr = output;
446444 return .{ .generated = &output.generated_file };
447445}
448446
449pub fn captureStdOut(self: *Run) std.Build.LazyPath {
450 assert(self.stdio != .inherit);
447pub fn captureStdOut(run: *Run) std.Build.LazyPath {
448 assert(run.stdio != .inherit);
451449
452 if (self.captured_stdout) |output| return .{ .generated = &output.generated_file };
450 if (run.captured_stdout) |output| return .{ .generated = &output.generated_file };
453451
454 const output = self.step.owner.allocator.create(Output) catch @panic("OOM");
452 const output = run.step.owner.allocator.create(Output) catch @panic("OOM");
455453 output.* = .{
456454 .prefix = "",
457455 .basename = "stdout",
458 .generated_file = .{ .step = &self.step },
456 .generated_file = .{ .step = &run.step },
459457 };
460 self.captured_stdout = output;
458 run.captured_stdout = output;
461459 return .{ .generated = &output.generated_file };
462460}
463461
......@@ -472,20 +470,20 @@ pub fn addFileInput(self: *Run, file_input: std.Build.LazyPath) void {
472470}
473471
474472/// Returns whether the Run step has side effects *other than* updating the output arguments.
475fn hasSideEffects(self: Run) bool {
476 if (self.has_side_effects) return true;
477 return switch (self.stdio) {
478 .infer_from_args => !self.hasAnyOutputArgs(),
473fn hasSideEffects(run: Run) bool {
474 if (run.has_side_effects) return true;
475 return switch (run.stdio) {
476 .infer_from_args => !run.hasAnyOutputArgs(),
479477 .inherit => true,
480478 .check => false,
481479 .zig_test => false,
482480 };
483481}
484482
485fn hasAnyOutputArgs(self: Run) bool {
486 if (self.captured_stdout != null) return true;
487 if (self.captured_stderr != null) return true;
488 for (self.argv.items) |arg| switch (arg) {
483fn hasAnyOutputArgs(run: Run) bool {
484 if (run.captured_stdout != null) return true;
485 if (run.captured_stderr != null) return true;
486 for (run.argv.items) |arg| switch (arg) {
489487 .output => return true,
490488 else => continue,
491489 };
......@@ -527,8 +525,8 @@ const IndexedOutput = struct {
527525fn make(step: *Step, prog_node: *std.Progress.Node) !void {
528526 const b = step.owner;
529527 const arena = b.allocator;
530 const self: *Run = @fieldParentPtr("step", step);
531 const has_side_effects = self.hasSideEffects();
528 const run: *Run = @fieldParentPtr("step", step);
529 const has_side_effects = run.hasSideEffects();
532530
533531 var argv_list = std.ArrayList([]const u8).init(arena);
534532 var output_placeholders = std.ArrayList(IndexedOutput).init(arena);
......@@ -536,20 +534,20 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
536534 var man = b.graph.cache.obtain();
537535 defer man.deinit();
538536
539 for (self.argv.items) |arg| {
537 for (run.argv.items) |arg| {
540538 switch (arg) {
541539 .bytes => |bytes| {
542540 try argv_list.append(bytes);
543541 man.hash.addBytes(bytes);
544542 },
545543 .lazy_path => |file| {
546 const file_path = file.lazy_path.getPath(b);
544 const file_path = file.lazy_path.getPath2(b, step);
547545 try argv_list.append(b.fmt("{s}{s}", .{ file.prefix, file_path }));
548546 man.hash.addBytes(file.prefix);
549547 _ = try man.addFile(file_path, null);
550548 },
551549 .directory_source => |file| {
552 const file_path = file.lazy_path.getPath(b);
550 const file_path = file.lazy_path.getPath2(b, step);
553551 try argv_list.append(b.fmt("{s}{s}", .{ file.prefix, file_path }));
554552 man.hash.addBytes(file.prefix);
555553 man.hash.addBytes(file_path);
......@@ -557,7 +555,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
557555 .artifact => |artifact| {
558556 if (artifact.rootModuleTarget().os.tag == .windows) {
559557 // On Windows we don't have rpaths so we have to add .dll search paths to PATH
560 self.addPathForDynLibs(artifact);
558 run.addPathForDynLibs(artifact);
561559 }
562560 const file_path = artifact.installed_path orelse artifact.generated_bin.?.path.?; // the path is guaranteed to be set
563561
......@@ -580,36 +578,36 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
580578 }
581579 }
582580
583 switch (self.stdin) {
581 switch (run.stdin) {
584582 .bytes => |bytes| {
585583 man.hash.addBytes(bytes);
586584 },
587585 .lazy_path => |lazy_path| {
588 const file_path = lazy_path.getPath(b);
586 const file_path = lazy_path.getPath2(b, step);
589587 _ = try man.addFile(file_path, null);
590588 },
591589 .none => {},
592590 }
593591
594 if (self.captured_stdout) |output| {
592 if (run.captured_stdout) |output| {
595593 man.hash.addBytes(output.basename);
596594 }
597595
598 if (self.captured_stderr) |output| {
596 if (run.captured_stderr) |output| {
599597 man.hash.addBytes(output.basename);
600598 }
601599
602 hashStdIo(&man.hash, self.stdio);
600 hashStdIo(&man.hash, run.stdio);
603601
604602 if (has_side_effects) {
605 try runCommand(self, argv_list.items, has_side_effects, null, prog_node);
603 try runCommand(run, argv_list.items, has_side_effects, null, prog_node);
606604 return;
607605 }
608606
609 for (self.extra_file_dependencies) |file_path| {
607 for (run.extra_file_dependencies) |file_path| {
610608 _ = try man.addFile(b.pathFromRoot(file_path), null);
611609 }
612 for (self.file_inputs.items) |lazy_path| {
610 for (run.file_inputs.items) |lazy_path| {
613611 _ = try man.addFile(lazy_path.getPath2(b, step), null);
614612 }
615613
......@@ -620,8 +618,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
620618 try populateGeneratedPaths(
621619 arena,
622620 output_placeholders.items,
623 self.captured_stdout,
624 self.captured_stderr,
621 run.captured_stdout,
622 run.captured_stderr,
625623 b.cache_root,
626624 &digest,
627625 );
......@@ -635,7 +633,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
635633
636634 for (output_placeholders.items) |placeholder| {
637635 const output_components = .{ tmp_dir_path, placeholder.output.basename };
638 const output_sub_path = try fs.path.join(arena, &output_components);
636 const output_sub_path = b.pathJoin(&output_components);
639637 const output_sub_dir_path = fs.path.dirname(output_sub_path).?;
640638 b.cache_root.handle.makePath(output_sub_dir_path) catch |err| {
641639 return step.fail("unable to make path '{}{s}': {s}", .{
......@@ -651,15 +649,15 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
651649 argv_list.items[placeholder.index] = cli_arg;
652650 }
653651
654 try runCommand(self, argv_list.items, has_side_effects, tmp_dir_path, prog_node);
652 try runCommand(run, argv_list.items, has_side_effects, tmp_dir_path, prog_node);
655653
656 if (self.dep_output_file) |dep_output_file|
654 if (run.dep_output_file) |dep_output_file|
657655 try man.addDepFilePost(std.fs.cwd(), dep_output_file.generated_file.getPath());
658656
659657 const digest = man.final();
660658
661659 const any_output = output_placeholders.items.len > 0 or
662 self.captured_stdout != null or self.captured_stderr != null;
660 run.captured_stdout != null or run.captured_stderr != null;
663661
664662 // Rename into place
665663 if (any_output) {
......@@ -696,8 +694,8 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void {
696694 try populateGeneratedPaths(
697695 arena,
698696 output_placeholders.items,
699 self.captured_stdout,
700 self.captured_stderr,
697 run.captured_stdout,
698 run.captured_stderr,
701699 b.cache_root,
702700 &digest,
703701 );
......@@ -776,30 +774,30 @@ fn termMatches(expected: ?std.process.Child.Term, actual: std.process.Child.Term
776774}
777775
778776fn runCommand(
779 self: *Run,
777 run: *Run,
780778 argv: []const []const u8,
781779 has_side_effects: bool,
782780 tmp_dir_path: ?[]const u8,
783781 prog_node: *std.Progress.Node,
784782) !void {
785 const step = &self.step;
783 const step = &run.step;
786784 const b = step.owner;
787785 const arena = b.allocator;
788786
789 const cwd: ?[]const u8 = if (self.cwd) |lazy_cwd| lazy_cwd.getPath(b) else null;
787 const cwd: ?[]const u8 = if (run.cwd) |lazy_cwd| lazy_cwd.getPath2(b, step) else null;
790788
791789 try step.handleChildProcUnsupported(cwd, argv);
792 try Step.handleVerbose2(step.owner, cwd, self.env_map, argv);
790 try Step.handleVerbose2(step.owner, cwd, run.env_map, argv);
793791
794 const allow_skip = switch (self.stdio) {
795 .check, .zig_test => self.skip_foreign_checks,
792 const allow_skip = switch (run.stdio) {
793 .check, .zig_test => run.skip_foreign_checks,
796794 else => false,
797795 };
798796
799797 var interp_argv = std.ArrayList([]const u8).init(b.allocator);
800798 defer interp_argv.deinit();
801799
802 const result = spawnChildAndCollect(self, argv, has_side_effects, prog_node) catch |err| term: {
800 const result = spawnChildAndCollect(run, argv, has_side_effects, prog_node) catch |err| term: {
803801 // InvalidExe: cpu arch mismatch
804802 // FileNotFound: can happen with a wrong dynamic linker path
805803 if (err == error.InvalidExe or err == error.FileNotFound) interpret: {
......@@ -807,7 +805,7 @@ fn runCommand(
807805 // relying on it being a Compile step. This will make this logic
808806 // work even for the edge case that the binary was produced by a
809807 // third party.
810 const exe = switch (self.argv.items[0]) {
808 const exe = switch (run.argv.items[0]) {
811809 .artifact => |exe| exe,
812810 else => break :interpret,
813811 };
......@@ -832,14 +830,14 @@ fn runCommand(
832830 try interp_argv.append(bin_name);
833831 try interp_argv.appendSlice(argv);
834832 } else {
835 return failForeign(self, "-fwine", argv[0], exe);
833 return failForeign(run, "-fwine", argv[0], exe);
836834 }
837835 },
838836 .qemu => |bin_name| {
839837 if (b.enable_qemu) {
840838 const glibc_dir_arg = if (need_cross_glibc)
841839 b.glibc_runtimes_dir orelse
842 return failForeign(self, "--glibc-runtimes", argv[0], exe)
840 return failForeign(run, "--glibc-runtimes", argv[0], exe)
843841 else
844842 null;
845843
......@@ -867,7 +865,7 @@ fn runCommand(
867865
868866 try interp_argv.appendSlice(argv);
869867 } else {
870 return failForeign(self, "-fqemu", argv[0], exe);
868 return failForeign(run, "-fqemu", argv[0], exe);
871869 }
872870 },
873871 .darling => |bin_name| {
......@@ -875,7 +873,7 @@ fn runCommand(
875873 try interp_argv.append(bin_name);
876874 try interp_argv.appendSlice(argv);
877875 } else {
878 return failForeign(self, "-fdarling", argv[0], exe);
876 return failForeign(run, "-fdarling", argv[0], exe);
879877 }
880878 },
881879 .wasmtime => |bin_name| {
......@@ -886,7 +884,7 @@ fn runCommand(
886884 try interp_argv.append("--");
887885 try interp_argv.appendSlice(argv[1..]);
888886 } else {
889 return failForeign(self, "-fwasmtime", argv[0], exe);
887 return failForeign(run, "-fwasmtime", argv[0], exe);
890888 }
891889 },
892890 .bad_dl => |foreign_dl| {
......@@ -915,13 +913,13 @@ fn runCommand(
915913
916914 if (exe.rootModuleTarget().os.tag == .windows) {
917915 // On Windows we don't have rpaths so we have to add .dll search paths to PATH
918 self.addPathForDynLibs(exe);
916 run.addPathForDynLibs(exe);
919917 }
920918
921 try Step.handleVerbose2(step.owner, cwd, self.env_map, interp_argv.items);
919 try Step.handleVerbose2(step.owner, cwd, run.env_map, interp_argv.items);
922920
923 break :term spawnChildAndCollect(self, interp_argv.items, has_side_effects, prog_node) catch |e| {
924 if (!self.failing_to_execute_foreign_is_an_error) return error.MakeSkipped;
921 break :term spawnChildAndCollect(run, interp_argv.items, has_side_effects, prog_node) catch |e| {
922 if (!run.failing_to_execute_foreign_is_an_error) return error.MakeSkipped;
925923
926924 return step.fail("unable to spawn interpreter {s}: {s}", .{
927925 interp_argv.items[0], @errorName(e),
......@@ -943,11 +941,11 @@ fn runCommand(
943941 };
944942 for ([_]Stream{
945943 .{
946 .captured = self.captured_stdout,
944 .captured = run.captured_stdout,
947945 .bytes = result.stdio.stdout,
948946 },
949947 .{
950 .captured = self.captured_stderr,
948 .captured = run.captured_stderr,
951949 .bytes = result.stdio.stderr,
952950 },
953951 }) |stream| {
......@@ -956,7 +954,7 @@ fn runCommand(
956954 const output_path = try b.cache_root.join(arena, &output_components);
957955 output.generated_file.path = output_path;
958956
959 const sub_path = try fs.path.join(arena, &output_components);
957 const sub_path = b.pathJoin(&output_components);
960958 const sub_path_dirname = fs.path.dirname(sub_path).?;
961959 b.cache_root.handle.makePath(sub_path_dirname) catch |err| {
962960 return step.fail("unable to make path '{}{s}': {s}", .{
......@@ -973,7 +971,7 @@ fn runCommand(
973971
974972 const final_argv = if (interp_argv.items.len == 0) argv else interp_argv.items;
975973
976 switch (self.stdio) {
974 switch (run.stdio) {
977975 .check => |checks| for (checks.items) |check| switch (check) {
978976 .expect_stderr_exact => |expected_bytes| {
979977 if (!mem.eql(u8, expected_bytes, result.stdio.stderr.?)) {
......@@ -1094,56 +1092,56 @@ const ChildProcResult = struct {
10941092};
10951093
10961094fn spawnChildAndCollect(
1097 self: *Run,
1095 run: *Run,
10981096 argv: []const []const u8,
10991097 has_side_effects: bool,
11001098 prog_node: *std.Progress.Node,
11011099) !ChildProcResult {
1102 const b = self.step.owner;
1100 const b = run.step.owner;
11031101 const arena = b.allocator;
11041102
11051103 var child = std.process.Child.init(argv, arena);
1106 if (self.cwd) |lazy_cwd| {
1107 child.cwd = lazy_cwd.getPath(b);
1104 if (run.cwd) |lazy_cwd| {
1105 child.cwd = lazy_cwd.getPath2(b, &run.step);
11081106 } else {
11091107 child.cwd = b.build_root.path;
11101108 child.cwd_dir = b.build_root.handle;
11111109 }
1112 child.env_map = self.env_map orelse &b.graph.env_map;
1110 child.env_map = run.env_map orelse &b.graph.env_map;
11131111 child.request_resource_usage_statistics = true;
11141112
1115 child.stdin_behavior = switch (self.stdio) {
1113 child.stdin_behavior = switch (run.stdio) {
11161114 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
11171115 .inherit => .Inherit,
11181116 .check => .Ignore,
11191117 .zig_test => .Pipe,
11201118 };
1121 child.stdout_behavior = switch (self.stdio) {
1119 child.stdout_behavior = switch (run.stdio) {
11221120 .infer_from_args => if (has_side_effects) .Inherit else .Ignore,
11231121 .inherit => .Inherit,
11241122 .check => |checks| if (checksContainStdout(checks.items)) .Pipe else .Ignore,
11251123 .zig_test => .Pipe,
11261124 };
1127 child.stderr_behavior = switch (self.stdio) {
1125 child.stderr_behavior = switch (run.stdio) {
11281126 .infer_from_args => if (has_side_effects) .Inherit else .Pipe,
11291127 .inherit => .Inherit,
11301128 .check => .Pipe,
11311129 .zig_test => .Pipe,
11321130 };
1133 if (self.captured_stdout != null) child.stdout_behavior = .Pipe;
1134 if (self.captured_stderr != null) child.stderr_behavior = .Pipe;
1135 if (self.stdin != .none) {
1136 assert(self.stdio != .inherit);
1131 if (run.captured_stdout != null) child.stdout_behavior = .Pipe;
1132 if (run.captured_stderr != null) child.stderr_behavior = .Pipe;
1133 if (run.stdin != .none) {
1134 assert(run.stdio != .inherit);
11371135 child.stdin_behavior = .Pipe;
11381136 }
11391137
11401138 try child.spawn();
11411139 var timer = try std.time.Timer.start();
11421140
1143 const result = if (self.stdio == .zig_test)
1144 evalZigTest(self, &child, prog_node)
1141 const result = if (run.stdio == .zig_test)
1142 evalZigTest(run, &child, prog_node)
11451143 else
1146 evalGeneric(self, &child);
1144 evalGeneric(run, &child);
11471145
11481146 const term = try child.wait();
11491147 const elapsed_ns = timer.read();
......@@ -1164,12 +1162,12 @@ const StdIoResult = struct {
11641162};
11651163
11661164fn evalZigTest(
1167 self: *Run,
1165 run: *Run,
11681166 child: *std.process.Child,
11691167 prog_node: *std.Progress.Node,
11701168) !StdIoResult {
1171 const gpa = self.step.owner.allocator;
1172 const arena = self.step.owner.allocator;
1169 const gpa = run.step.owner.allocator;
1170 const arena = run.step.owner.allocator;
11731171
11741172 var poller = std.io.poll(gpa, enum { stdout, stderr }, .{
11751173 .stdout = child.stdout.?,
......@@ -1208,7 +1206,7 @@ fn evalZigTest(
12081206 switch (header.tag) {
12091207 .zig_version => {
12101208 if (!std.mem.eql(u8, builtin.zig_version_string, body)) {
1211 return self.step.fail(
1209 return run.step.fail(
12121210 "zig version mismatch build runner vs compiler: '{s}' vs '{s}'",
12131211 .{ builtin.zig_version_string, body },
12141212 );
......@@ -1266,9 +1264,9 @@ fn evalZigTest(
12661264 else
12671265 unreachable;
12681266 if (msg.len > 0) {
1269 try self.step.addError("'{s}' {s}: {s}", .{ name, label, msg });
1267 try run.step.addError("'{s}' {s}: {s}", .{ name, label, msg });
12701268 } else {
1271 try self.step.addError("'{s}' {s}", .{ name, label });
1269 try run.step.addError("'{s}' {s}", .{ name, label });
12721270 }
12731271 }
12741272
......@@ -1282,7 +1280,7 @@ fn evalZigTest(
12821280
12831281 if (stderr.readableLength() > 0) {
12841282 const msg = std.mem.trim(u8, try stderr.toOwnedSlice(), "\n");
1285 if (msg.len > 0) self.step.result_stderr = msg;
1283 if (msg.len > 0) run.step.result_stderr = msg;
12861284 }
12871285
12881286 // Send EOF to stdin.
......@@ -1350,25 +1348,26 @@ fn sendRunTestMessage(file: std.fs.File, index: u32) !void {
13501348 try file.writeAll(full_msg);
13511349}
13521350
1353fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult {
1354 const arena = self.step.owner.allocator;
1351fn evalGeneric(run: *Run, child: *std.process.Child) !StdIoResult {
1352 const b = run.step.owner;
1353 const arena = b.allocator;
13551354
1356 switch (self.stdin) {
1355 switch (run.stdin) {
13571356 .bytes => |bytes| {
13581357 child.stdin.?.writeAll(bytes) catch |err| {
1359 return self.step.fail("unable to write stdin: {s}", .{@errorName(err)});
1358 return run.step.fail("unable to write stdin: {s}", .{@errorName(err)});
13601359 };
13611360 child.stdin.?.close();
13621361 child.stdin = null;
13631362 },
13641363 .lazy_path => |lazy_path| {
1365 const path = lazy_path.getPath(self.step.owner);
1366 const file = self.step.owner.build_root.handle.openFile(path, .{}) catch |err| {
1367 return self.step.fail("unable to open stdin file: {s}", .{@errorName(err)});
1364 const path = lazy_path.getPath2(b, &run.step);
1365 const file = b.build_root.handle.openFile(path, .{}) catch |err| {
1366 return run.step.fail("unable to open stdin file: {s}", .{@errorName(err)});
13681367 };
13691368 defer file.close();
13701369 child.stdin.?.writeFileAll(file, .{}) catch |err| {
1371 return self.step.fail("unable to write file to stdin: {s}", .{@errorName(err)});
1370 return run.step.fail("unable to write file to stdin: {s}", .{@errorName(err)});
13721371 };
13731372 child.stdin.?.close();
13741373 child.stdin = null;
......@@ -1388,29 +1387,29 @@ fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult {
13881387 defer poller.deinit();
13891388
13901389 while (try poller.poll()) {
1391 if (poller.fifo(.stdout).count > self.max_stdio_size)
1390 if (poller.fifo(.stdout).count > run.max_stdio_size)
13921391 return error.StdoutStreamTooLong;
1393 if (poller.fifo(.stderr).count > self.max_stdio_size)
1392 if (poller.fifo(.stderr).count > run.max_stdio_size)
13941393 return error.StderrStreamTooLong;
13951394 }
13961395
13971396 stdout_bytes = try poller.fifo(.stdout).toOwnedSlice();
13981397 stderr_bytes = try poller.fifo(.stderr).toOwnedSlice();
13991398 } else {
1400 stdout_bytes = try stdout.reader().readAllAlloc(arena, self.max_stdio_size);
1399 stdout_bytes = try stdout.reader().readAllAlloc(arena, run.max_stdio_size);
14011400 }
14021401 } else if (child.stderr) |stderr| {
1403 stderr_bytes = try stderr.reader().readAllAlloc(arena, self.max_stdio_size);
1402 stderr_bytes = try stderr.reader().readAllAlloc(arena, run.max_stdio_size);
14041403 }
14051404
14061405 if (stderr_bytes) |bytes| if (bytes.len > 0) {
14071406 // Treat stderr as an error message.
1408 const stderr_is_diagnostic = self.captured_stderr == null and switch (self.stdio) {
1407 const stderr_is_diagnostic = run.captured_stderr == null and switch (run.stdio) {
14091408 .check => |checks| !checksContainStderr(checks.items),
14101409 else => true,
14111410 };
14121411 if (stderr_is_diagnostic) {
1413 self.step.result_stderr = bytes;
1412 run.step.result_stderr = bytes;
14141413 }
14151414 };
14161415
......@@ -1422,8 +1421,8 @@ fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult {
14221421 };
14231422}
14241423
1425fn addPathForDynLibs(self: *Run, artifact: *Step.Compile) void {
1426 const b = self.step.owner;
1424fn addPathForDynLibs(run: *Run, artifact: *Step.Compile) void {
1425 const b = run.step.owner;
14271426 var it = artifact.root_module.iterateDependencies(artifact, true);
14281427 while (it.next()) |item| {
14291428 const other = item.compile.?;
......@@ -1431,34 +1430,34 @@ fn addPathForDynLibs(self: *Run, artifact: *Step.Compile) void {
14311430 if (item.module.resolved_target.?.result.os.tag == .windows and
14321431 other.isDynamicLibrary())
14331432 {
1434 addPathDir(self, fs.path.dirname(other.getEmittedBin().getPath(b)).?);
1433 addPathDir(run, fs.path.dirname(other.getEmittedBin().getPath2(b, &run.step)).?);
14351434 }
14361435 }
14371436 }
14381437}
14391438
14401439fn failForeign(
1441 self: *Run,
1440 run: *Run,
14421441 suggested_flag: []const u8,
14431442 argv0: []const u8,
14441443 exe: *Step.Compile,
14451444) error{ MakeFailed, MakeSkipped, OutOfMemory } {
1446 switch (self.stdio) {
1445 switch (run.stdio) {
14471446 .check, .zig_test => {
1448 if (self.skip_foreign_checks)
1447 if (run.skip_foreign_checks)
14491448 return error.MakeSkipped;
14501449
1451 const b = self.step.owner;
1450 const b = run.step.owner;
14521451 const host_name = try b.host.result.zigTriple(b.allocator);
14531452 const foreign_name = try exe.rootModuleTarget().zigTriple(b.allocator);
14541453
1455 return self.step.fail(
1454 return run.step.fail(
14561455 \\unable to spawn foreign binary '{s}' ({s}) on host system ({s})
14571456 \\ consider using {s} or enabling skip_foreign_checks in the Run step
14581457 , .{ argv0, foreign_name, host_name, suggested_flag });
14591458 },
14601459 else => {
1461 return self.step.fail("unable to spawn foreign binary '{s}'", .{argv0});
1460 return run.step.fail("unable to spawn foreign binary '{s}'", .{argv0});
14621461 },
14631462 }
14641463}
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 = &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.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 = &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 = &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/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/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_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 });