From 13eb7251d37759bd47403db304c6120c706fe353 Mon Sep 17 00:00:00 2001 From: Nicolas Sterchele Date: Mon, 20 Mar 2023 09:23:10 +0100 Subject: build: rename std.Build.*Step to std.Build.Step.* Follow-up actions from #14647 Fixes #14947 --- lib/std/Build/Step/CheckObject.zig | 1055 ++++++++++++++++++++++++++++++++++++ 1 file changed, 1055 insertions(+) create mode 100644 lib/std/Build/Step/CheckObject.zig (limited to 'lib/std/Build/Step/CheckObject.zig') diff --git a/lib/std/Build/Step/CheckObject.zig b/lib/std/Build/Step/CheckObject.zig new file mode 100644 index 0000000000..431f74eccc --- /dev/null +++ b/lib/std/Build/Step/CheckObject.zig @@ -0,0 +1,1055 @@ +const std = @import("std"); +const assert = std.debug.assert; +const fs = std.fs; +const macho = std.macho; +const math = std.math; +const mem = std.mem; +const testing = std.testing; + +const CheckObjectStep = @This(); + +const Allocator = mem.Allocator; +const Step = std.Build.Step; + +pub const base_id = .check_object; + +step: Step, +source: std.Build.FileSource, +max_bytes: usize = 20 * 1024 * 1024, +checks: std.ArrayList(Check), +dump_symtab: bool = false, +obj_format: std.Target.ObjectFormat, + +pub fn create( + owner: *std.Build, + source: std.Build.FileSource, + obj_format: std.Target.ObjectFormat, +) *CheckObjectStep { + const gpa = owner.allocator; + const self = gpa.create(CheckObjectStep) catch @panic("OOM"); + self.* = .{ + .step = Step.init(.{ + .id = .check_file, + .name = "CheckObject", + .owner = owner, + .makeFn = make, + }), + .source = source.dupe(owner), + .checks = std.ArrayList(Check).init(gpa), + .obj_format = obj_format, + }; + self.source.addStepDependencies(&self.step); + return self; +} + +/// Runs and (optionally) compares the output of a binary. +/// Asserts `self` was generated from an executable step. +/// TODO this doesn't actually compare, and there's no apparent reason for it +/// to depend on the check object step. I don't see why this function should exist, +/// the caller could just add the run step directly. +pub fn runAndCompare(self: *CheckObjectStep) *std.Build.RunStep { + const dependencies_len = self.step.dependencies.items.len; + assert(dependencies_len > 0); + const exe_step = self.step.dependencies.items[dependencies_len - 1]; + const exe = exe_step.cast(std.Build.CompileStep).?; + const run = self.step.owner.addRunArtifact(exe); + run.skip_foreign_checks = true; + run.step.dependOn(&self.step); + return run; +} + +const SearchPhrase = struct { + string: []const u8, + file_source: ?std.Build.FileSource = null, + + fn resolve(phrase: SearchPhrase, b: *std.Build, step: *Step) []const u8 { + const file_source = phrase.file_source orelse return phrase.string; + return b.fmt("{s} {s}", .{ phrase.string, file_source.getPath2(b, step) }); + } +}; + +/// There two types of actions currently supported: +/// * `.match` - is the main building block of standard matchers with optional eat-all token `{*}` +/// and extractors by name such as `{n_value}`. Please note this action is very simplistic in nature +/// i.e., it won't really handle edge cases/nontrivial examples. But given that we do want to use +/// it mainly to test the output of our object format parser-dumpers when testing the linkers, etc. +/// it should be plenty useful in its current form. +/// * `.compute_cmp` - can be used to perform an operation on the extracted global variables +/// using the MatchAction. It currently only supports an addition. The operation is required +/// to be specified in Reverse Polish Notation to ease in operator-precedence parsing (well, +/// to avoid any parsing really). +/// For example, if the two extracted values were saved as `vmaddr` and `entryoff` respectively +/// they could then be added with this simple program `vmaddr entryoff +`. +const Action = struct { + tag: enum { match, not_present, compute_cmp }, + phrase: SearchPhrase, + expected: ?ComputeCompareExpected = null, + + /// Will return true if the `phrase` was found in the `haystack`. + /// Some examples include: + /// + /// LC 0 => will match in its entirety + /// vmaddr {vmaddr} => will match `vmaddr` and then extract the following value as u64 + /// and save under `vmaddr` global name (see `global_vars` param) + /// name {*}libobjc{*}.dylib => will match `name` followed by a token which contains `libobjc` and `.dylib` + /// in that order with other letters in between + fn match( + act: Action, + b: *std.Build, + step: *Step, + haystack: []const u8, + global_vars: anytype, + ) !bool { + assert(act.tag == .match or act.tag == .not_present); + const phrase = act.phrase.resolve(b, step); + var candidate_var: ?struct { name: []const u8, value: u64 } = null; + var hay_it = mem.tokenize(u8, mem.trim(u8, haystack, " "), " "); + var needle_it = mem.tokenize(u8, mem.trim(u8, phrase, " "), " "); + + while (needle_it.next()) |needle_tok| { + const hay_tok = hay_it.next() orelse return false; + + if (mem.indexOf(u8, needle_tok, "{*}")) |index| { + // We have fuzzy matchers within the search pattern, so we match substrings. + var start = index; + var n_tok = needle_tok; + var h_tok = hay_tok; + while (true) { + n_tok = n_tok[start + 3 ..]; + const inner = if (mem.indexOf(u8, n_tok, "{*}")) |sub_end| + n_tok[0..sub_end] + else + n_tok; + if (mem.indexOf(u8, h_tok, inner) == null) return false; + start = mem.indexOf(u8, n_tok, "{*}") orelse break; + } + } else if (mem.startsWith(u8, needle_tok, "{")) { + const closing_brace = mem.indexOf(u8, needle_tok, "}") orelse return error.MissingClosingBrace; + if (closing_brace != needle_tok.len - 1) return error.ClosingBraceNotLast; + + const name = needle_tok[1..closing_brace]; + if (name.len == 0) return error.MissingBraceValue; + const value = try std.fmt.parseInt(u64, hay_tok, 16); + candidate_var = .{ + .name = name, + .value = value, + }; + } else { + if (!mem.eql(u8, hay_tok, needle_tok)) return false; + } + } + + if (candidate_var) |v| { + try global_vars.putNoClobber(v.name, v.value); + } + + return true; + } + + /// Will return true if the `phrase` is correctly parsed into an RPN program and + /// its reduced, computed value compares using `op` with the expected value, either + /// a literal or another extracted variable. + fn computeCmp(act: Action, b: *std.Build, step: *Step, global_vars: anytype) !bool { + const gpa = step.owner.allocator; + const phrase = act.phrase.resolve(b, step); + var op_stack = std.ArrayList(enum { add, sub, mod, mul }).init(gpa); + var values = std.ArrayList(u64).init(gpa); + + var it = mem.tokenize(u8, phrase, " "); + while (it.next()) |next| { + if (mem.eql(u8, next, "+")) { + try op_stack.append(.add); + } else if (mem.eql(u8, next, "-")) { + try op_stack.append(.sub); + } else if (mem.eql(u8, next, "%")) { + try op_stack.append(.mod); + } else if (mem.eql(u8, next, "*")) { + try op_stack.append(.mul); + } else { + const val = std.fmt.parseInt(u64, next, 0) catch blk: { + break :blk global_vars.get(next) orelse { + try step.addError( + \\ + \\========= variable was not extracted: =========== + \\{s} + \\================================================= + , .{next}); + return error.UnknownVariable; + }; + }; + try values.append(val); + } + } + + var op_i: usize = 1; + var reduced: u64 = values.items[0]; + for (op_stack.items) |op| { + const other = values.items[op_i]; + switch (op) { + .add => { + reduced += other; + }, + .sub => { + reduced -= other; + }, + .mod => { + reduced %= other; + }, + .mul => { + reduced *= other; + }, + } + op_i += 1; + } + + const exp_value = switch (act.expected.?.value) { + .variable => |name| global_vars.get(name) orelse { + try step.addError( + \\ + \\========= variable was not extracted: =========== + \\{s} + \\================================================= + , .{name}); + return error.UnknownVariable; + }, + .literal => |x| x, + }; + return math.compare(reduced, act.expected.?.op, exp_value); + } +}; + +const ComputeCompareExpected = struct { + op: math.CompareOperator, + value: union(enum) { + variable: []const u8, + literal: u64, + }, + + pub fn format( + value: @This(), + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + if (fmt.len != 0) std.fmt.invalidFmtError(fmt, value); + _ = options; + try writer.print("{s} ", .{@tagName(value.op)}); + switch (value.value) { + .variable => |name| try writer.writeAll(name), + .literal => |x| try writer.print("{x}", .{x}), + } + } +}; + +const Check = struct { + actions: std.ArrayList(Action), + + fn create(allocator: Allocator) Check { + return .{ + .actions = std.ArrayList(Action).init(allocator), + }; + } + + fn match(self: *Check, phrase: SearchPhrase) void { + self.actions.append(.{ + .tag = .match, + .phrase = phrase, + }) catch @panic("OOM"); + } + + fn notPresent(self: *Check, phrase: SearchPhrase) void { + self.actions.append(.{ + .tag = .not_present, + .phrase = phrase, + }) catch @panic("OOM"); + } + + fn computeCmp(self: *Check, phrase: SearchPhrase, expected: ComputeCompareExpected) void { + self.actions.append(.{ + .tag = .compute_cmp, + .phrase = phrase, + .expected = expected, + }) catch @panic("OOM"); + } +}; + +/// Creates a new sequence of actions with `phrase` as the first anchor searched phrase. +pub fn checkStart(self: *CheckObjectStep, phrase: []const u8) void { + var new_check = Check.create(self.step.owner.allocator); + new_check.match(.{ .string = self.step.owner.dupe(phrase) }); + self.checks.append(new_check) catch @panic("OOM"); +} + +/// Adds another searched phrase to the latest created Check with `CheckObjectStep.checkStart(...)`. +/// Asserts at least one check already exists. +pub fn checkNext(self: *CheckObjectStep, phrase: []const u8) void { + assert(self.checks.items.len > 0); + const last = &self.checks.items[self.checks.items.len - 1]; + last.match(.{ .string = self.step.owner.dupe(phrase) }); +} + +/// Like `checkNext()` but takes an additional argument `FileSource` which will be +/// resolved to a full search query in `make()`. +pub fn checkNextFileSource( + self: *CheckObjectStep, + phrase: []const u8, + file_source: std.Build.FileSource, +) void { + assert(self.checks.items.len > 0); + const last = &self.checks.items[self.checks.items.len - 1]; + last.match(.{ .string = self.step.owner.dupe(phrase), .file_source = file_source }); +} + +/// Adds another searched phrase to the latest created Check with `CheckObjectStep.checkStart(...)` +/// however ensures there is no matching phrase in the output. +/// Asserts at least one check already exists. +pub fn checkNotPresent(self: *CheckObjectStep, phrase: []const u8) void { + assert(self.checks.items.len > 0); + const last = &self.checks.items[self.checks.items.len - 1]; + last.notPresent(.{ .string = self.step.owner.dupe(phrase) }); +} + +/// Creates a new check checking specifically symbol table parsed and dumped from the object +/// file. +/// Issuing this check will force parsing and dumping of the symbol table. +pub fn checkInSymtab(self: *CheckObjectStep) void { + self.dump_symtab = true; + const symtab_label = switch (self.obj_format) { + .macho => MachODumper.symtab_label, + else => @panic("TODO other parsers"), + }; + self.checkStart(symtab_label); +} + +/// Creates a new standalone, singular check which allows running simple binary operations +/// on the extracted variables. It will then compare the reduced program with the value of +/// the expected variable. +pub fn checkComputeCompare( + self: *CheckObjectStep, + program: []const u8, + expected: ComputeCompareExpected, +) void { + var new_check = Check.create(self.step.owner.allocator); + new_check.computeCmp(.{ .string = self.step.owner.dupe(program) }, expected); + self.checks.append(new_check) catch @panic("OOM"); +} + +fn make(step: *Step, prog_node: *std.Progress.Node) !void { + _ = prog_node; + const b = step.owner; + const gpa = b.allocator; + const self = @fieldParentPtr(CheckObjectStep, "step", step); + + const src_path = self.source.getPath(b); + const contents = fs.cwd().readFileAllocOptions( + gpa, + src_path, + self.max_bytes, + null, + @alignOf(u64), + null, + ) catch |err| return step.fail("unable to read '{s}': {s}", .{ src_path, @errorName(err) }); + + const output = switch (self.obj_format) { + .macho => try MachODumper.parseAndDump(step, contents, .{ + .dump_symtab = self.dump_symtab, + }), + .elf => @panic("TODO elf parser"), + .coff => @panic("TODO coff parser"), + .wasm => try WasmDumper.parseAndDump(step, contents, .{ + .dump_symtab = self.dump_symtab, + }), + else => unreachable, + }; + + var vars = std.StringHashMap(u64).init(gpa); + + for (self.checks.items) |chk| { + var it = mem.tokenize(u8, output, "\r\n"); + for (chk.actions.items) |act| { + switch (act.tag) { + .match => { + while (it.next()) |line| { + if (try act.match(b, step, line, &vars)) break; + } else { + return step.fail( + \\ + \\========= expected to find: ========================== + \\{s} + \\========= but parsed file does not contain it: ======= + \\{s} + \\====================================================== + , .{ act.phrase.resolve(b, step), output }); + } + }, + .not_present => { + while (it.next()) |line| { + if (try act.match(b, step, line, &vars)) { + return step.fail( + \\ + \\========= expected not to find: =================== + \\{s} + \\========= but parsed file does contain it: ======== + \\{s} + \\=================================================== + , .{ act.phrase.resolve(b, step), output }); + } + } + }, + .compute_cmp => { + const res = act.computeCmp(b, step, vars) catch |err| switch (err) { + error.UnknownVariable => { + return step.fail( + \\========= from parsed file: ===================== + \\{s} + \\================================================= + , .{output}); + }, + else => |e| return e, + }; + if (!res) { + return step.fail( + \\ + \\========= comparison failed for action: =========== + \\{s} {} + \\========= from parsed file: ======================= + \\{s} + \\=================================================== + , .{ act.phrase.resolve(b, step), act.expected.?, output }); + } + }, + } + } + } +} + +const Opts = struct { + dump_symtab: bool = false, +}; + +const MachODumper = struct { + const LoadCommandIterator = macho.LoadCommandIterator; + const symtab_label = "symtab"; + + fn parseAndDump(step: *Step, bytes: []align(@alignOf(u64)) const u8, opts: Opts) ![]const u8 { + const gpa = step.owner.allocator; + var stream = std.io.fixedBufferStream(bytes); + const reader = stream.reader(); + + const hdr = try reader.readStruct(macho.mach_header_64); + if (hdr.magic != macho.MH_MAGIC_64) { + return error.InvalidMagicNumber; + } + + var output = std.ArrayList(u8).init(gpa); + const writer = output.writer(); + + var symtab: []const macho.nlist_64 = undefined; + var strtab: []const u8 = undefined; + var sections = std.ArrayList(macho.section_64).init(gpa); + var imports = std.ArrayList([]const u8).init(gpa); + + var it = LoadCommandIterator{ + .ncmds = hdr.ncmds, + .buffer = bytes[@sizeOf(macho.mach_header_64)..][0..hdr.sizeofcmds], + }; + var i: usize = 0; + while (it.next()) |cmd| { + switch (cmd.cmd()) { + .SEGMENT_64 => { + const seg = cmd.cast(macho.segment_command_64).?; + try sections.ensureUnusedCapacity(seg.nsects); + for (cmd.getSections()) |sect| { + sections.appendAssumeCapacity(sect); + } + }, + .SYMTAB => if (opts.dump_symtab) { + const lc = cmd.cast(macho.symtab_command).?; + symtab = @ptrCast( + [*]const macho.nlist_64, + @alignCast(@alignOf(macho.nlist_64), &bytes[lc.symoff]), + )[0..lc.nsyms]; + strtab = bytes[lc.stroff..][0..lc.strsize]; + }, + .LOAD_DYLIB, + .LOAD_WEAK_DYLIB, + .REEXPORT_DYLIB, + => { + try imports.append(cmd.getDylibPathName()); + }, + else => {}, + } + + try dumpLoadCommand(cmd, i, writer); + try writer.writeByte('\n'); + + i += 1; + } + + if (opts.dump_symtab) { + try writer.print("{s}\n", .{symtab_label}); + for (symtab) |sym| { + if (sym.stab()) continue; + const sym_name = mem.sliceTo(@ptrCast([*:0]const u8, strtab.ptr + sym.n_strx), 0); + if (sym.sect()) { + const sect = sections.items[sym.n_sect - 1]; + try writer.print("{x} ({s},{s})", .{ + sym.n_value, + sect.segName(), + sect.sectName(), + }); + if (sym.ext()) { + try writer.writeAll(" external"); + } + try writer.print(" {s}\n", .{sym_name}); + } else if (sym.undf()) { + const ordinal = @divTrunc(@bitCast(i16, sym.n_desc), macho.N_SYMBOL_RESOLVER); + const import_name = blk: { + if (ordinal <= 0) { + if (ordinal == macho.BIND_SPECIAL_DYLIB_SELF) + break :blk "self import"; + if (ordinal == macho.BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) + break :blk "main executable"; + if (ordinal == macho.BIND_SPECIAL_DYLIB_FLAT_LOOKUP) + break :blk "flat lookup"; + unreachable; + } + const full_path = imports.items[@bitCast(u16, ordinal) - 1]; + const basename = fs.path.basename(full_path); + assert(basename.len > 0); + const ext = mem.lastIndexOfScalar(u8, basename, '.') orelse basename.len; + break :blk basename[0..ext]; + }; + try writer.writeAll("(undefined)"); + if (sym.weakRef()) { + try writer.writeAll(" weak"); + } + if (sym.ext()) { + try writer.writeAll(" external"); + } + try writer.print(" {s} (from {s})\n", .{ + sym_name, + import_name, + }); + } else unreachable; + } + } + + return output.toOwnedSlice(); + } + + fn dumpLoadCommand(lc: macho.LoadCommandIterator.LoadCommand, index: usize, writer: anytype) !void { + // print header first + try writer.print( + \\LC {d} + \\cmd {s} + \\cmdsize {d} + , .{ index, @tagName(lc.cmd()), lc.cmdsize() }); + + switch (lc.cmd()) { + .SEGMENT_64 => { + const seg = lc.cast(macho.segment_command_64).?; + try writer.writeByte('\n'); + try writer.print( + \\segname {s} + \\vmaddr {x} + \\vmsize {x} + \\fileoff {x} + \\filesz {x} + , .{ + seg.segName(), + seg.vmaddr, + seg.vmsize, + seg.fileoff, + seg.filesize, + }); + + for (lc.getSections()) |sect| { + try writer.writeByte('\n'); + try writer.print( + \\sectname {s} + \\addr {x} + \\size {x} + \\offset {x} + \\align {x} + , .{ + sect.sectName(), + sect.addr, + sect.size, + sect.offset, + sect.@"align", + }); + } + }, + + .ID_DYLIB, + .LOAD_DYLIB, + .LOAD_WEAK_DYLIB, + .REEXPORT_DYLIB, + => { + const dylib = lc.cast(macho.dylib_command).?; + try writer.writeByte('\n'); + try writer.print( + \\name {s} + \\timestamp {d} + \\current version {x} + \\compatibility version {x} + , .{ + lc.getDylibPathName(), + dylib.dylib.timestamp, + dylib.dylib.current_version, + dylib.dylib.compatibility_version, + }); + }, + + .MAIN => { + const main = lc.cast(macho.entry_point_command).?; + try writer.writeByte('\n'); + try writer.print( + \\entryoff {x} + \\stacksize {x} + , .{ main.entryoff, main.stacksize }); + }, + + .RPATH => { + try writer.writeByte('\n'); + try writer.print( + \\path {s} + , .{ + lc.getRpathPathName(), + }); + }, + + .UUID => { + const uuid = lc.cast(macho.uuid_command).?; + try writer.writeByte('\n'); + try writer.print("uuid {x}", .{std.fmt.fmtSliceHexLower(&uuid.uuid)}); + }, + + .DATA_IN_CODE, + .FUNCTION_STARTS, + .CODE_SIGNATURE, + => { + const llc = lc.cast(macho.linkedit_data_command).?; + try writer.writeByte('\n'); + try writer.print( + \\dataoff {x} + \\datasize {x} + , .{ llc.dataoff, llc.datasize }); + }, + + .DYLD_INFO_ONLY => { + const dlc = lc.cast(macho.dyld_info_command).?; + try writer.writeByte('\n'); + try writer.print( + \\rebaseoff {x} + \\rebasesize {x} + \\bindoff {x} + \\bindsize {x} + \\weakbindoff {x} + \\weakbindsize {x} + \\lazybindoff {x} + \\lazybindsize {x} + \\exportoff {x} + \\exportsize {x} + , .{ + dlc.rebase_off, + dlc.rebase_size, + dlc.bind_off, + dlc.bind_size, + dlc.weak_bind_off, + dlc.weak_bind_size, + dlc.lazy_bind_off, + dlc.lazy_bind_size, + dlc.export_off, + dlc.export_size, + }); + }, + + .SYMTAB => { + const slc = lc.cast(macho.symtab_command).?; + try writer.writeByte('\n'); + try writer.print( + \\symoff {x} + \\nsyms {x} + \\stroff {x} + \\strsize {x} + , .{ + slc.symoff, + slc.nsyms, + slc.stroff, + slc.strsize, + }); + }, + + .DYSYMTAB => { + const dlc = lc.cast(macho.dysymtab_command).?; + try writer.writeByte('\n'); + try writer.print( + \\ilocalsym {x} + \\nlocalsym {x} + \\iextdefsym {x} + \\nextdefsym {x} + \\iundefsym {x} + \\nundefsym {x} + \\indirectsymoff {x} + \\nindirectsyms {x} + , .{ + dlc.ilocalsym, + dlc.nlocalsym, + dlc.iextdefsym, + dlc.nextdefsym, + dlc.iundefsym, + dlc.nundefsym, + dlc.indirectsymoff, + dlc.nindirectsyms, + }); + }, + + else => {}, + } + } +}; + +const WasmDumper = struct { + const symtab_label = "symbols"; + + fn parseAndDump(step: *Step, bytes: []const u8, opts: Opts) ![]const u8 { + const gpa = step.owner.allocator; + if (opts.dump_symtab) { + @panic("TODO: Implement symbol table parsing and dumping"); + } + + var fbs = std.io.fixedBufferStream(bytes); + const reader = fbs.reader(); + + const buf = try reader.readBytesNoEof(8); + if (!mem.eql(u8, buf[0..4], &std.wasm.magic)) { + return error.InvalidMagicByte; + } + if (!mem.eql(u8, buf[4..], &std.wasm.version)) { + return error.UnsupportedWasmVersion; + } + + var output = std.ArrayList(u8).init(gpa); + errdefer output.deinit(); + const writer = output.writer(); + + while (reader.readByte()) |current_byte| { + const section = std.meta.intToEnum(std.wasm.Section, current_byte) catch { + return step.fail("Found invalid section id '{d}'", .{current_byte}); + }; + + const section_length = try std.leb.readULEB128(u32, reader); + try parseAndDumpSection(step, section, bytes[fbs.pos..][0..section_length], writer); + fbs.pos += section_length; + } else |_| {} // reached end of stream + + return output.toOwnedSlice(); + } + + fn parseAndDumpSection( + step: *Step, + section: std.wasm.Section, + data: []const u8, + writer: anytype, + ) !void { + var fbs = std.io.fixedBufferStream(data); + const reader = fbs.reader(); + + try writer.print( + \\Section {s} + \\size {d} + , .{ @tagName(section), data.len }); + + switch (section) { + .type, + .import, + .function, + .table, + .memory, + .global, + .@"export", + .element, + .code, + .data, + => { + const entries = try std.leb.readULEB128(u32, reader); + try writer.print("\nentries {d}\n", .{entries}); + try dumpSection(step, section, data[fbs.pos..], entries, writer); + }, + .custom => { + const name_length = try std.leb.readULEB128(u32, reader); + const name = data[fbs.pos..][0..name_length]; + fbs.pos += name_length; + try writer.print("\nname {s}\n", .{name}); + + if (mem.eql(u8, name, "name")) { + try parseDumpNames(step, reader, writer, data); + } else if (mem.eql(u8, name, "producers")) { + try parseDumpProducers(reader, writer, data); + } else if (mem.eql(u8, name, "target_features")) { + try parseDumpFeatures(reader, writer, data); + } + // TODO: Implement parsing and dumping other custom sections (such as relocations) + }, + .start => { + const start = try std.leb.readULEB128(u32, reader); + try writer.print("\nstart {d}\n", .{start}); + }, + else => {}, // skip unknown sections + } + } + + fn dumpSection(step: *Step, section: std.wasm.Section, data: []const u8, entries: u32, writer: anytype) !void { + var fbs = std.io.fixedBufferStream(data); + const reader = fbs.reader(); + + switch (section) { + .type => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + const func_type = try reader.readByte(); + if (func_type != std.wasm.function_type) { + return step.fail("expected function type, found byte '{d}'", .{func_type}); + } + const params = try std.leb.readULEB128(u32, reader); + try writer.print("params {d}\n", .{params}); + var index: u32 = 0; + while (index < params) : (index += 1) { + try parseDumpType(step, std.wasm.Valtype, reader, writer); + } else index = 0; + const returns = try std.leb.readULEB128(u32, reader); + try writer.print("returns {d}\n", .{returns}); + while (index < returns) : (index += 1) { + try parseDumpType(step, std.wasm.Valtype, reader, writer); + } + } + }, + .import => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + const module_name_len = try std.leb.readULEB128(u32, reader); + const module_name = data[fbs.pos..][0..module_name_len]; + fbs.pos += module_name_len; + const name_len = try std.leb.readULEB128(u32, reader); + const name = data[fbs.pos..][0..name_len]; + fbs.pos += name_len; + + const kind = std.meta.intToEnum(std.wasm.ExternalKind, try reader.readByte()) catch { + return step.fail("invalid import kind", .{}); + }; + + try writer.print( + \\module {s} + \\name {s} + \\kind {s} + , .{ module_name, name, @tagName(kind) }); + try writer.writeByte('\n'); + switch (kind) { + .function => { + try writer.print("index {d}\n", .{try std.leb.readULEB128(u32, reader)}); + }, + .memory => { + try parseDumpLimits(reader, writer); + }, + .global => { + try parseDumpType(step, std.wasm.Valtype, reader, writer); + try writer.print("mutable {}\n", .{0x01 == try std.leb.readULEB128(u32, reader)}); + }, + .table => { + try parseDumpType(step, std.wasm.RefType, reader, writer); + try parseDumpLimits(reader, writer); + }, + } + } + }, + .function => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + try writer.print("index {d}\n", .{try std.leb.readULEB128(u32, reader)}); + } + }, + .table => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + try parseDumpType(step, std.wasm.RefType, reader, writer); + try parseDumpLimits(reader, writer); + } + }, + .memory => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + try parseDumpLimits(reader, writer); + } + }, + .global => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + try parseDumpType(step, std.wasm.Valtype, reader, writer); + try writer.print("mutable {}\n", .{0x01 == try std.leb.readULEB128(u1, reader)}); + try parseDumpInit(step, reader, writer); + } + }, + .@"export" => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + const name_len = try std.leb.readULEB128(u32, reader); + const name = data[fbs.pos..][0..name_len]; + fbs.pos += name_len; + const kind_byte = try std.leb.readULEB128(u8, reader); + const kind = std.meta.intToEnum(std.wasm.ExternalKind, kind_byte) catch { + return step.fail("invalid export kind value '{d}'", .{kind_byte}); + }; + const index = try std.leb.readULEB128(u32, reader); + try writer.print( + \\name {s} + \\kind {s} + \\index {d} + , .{ name, @tagName(kind), index }); + try writer.writeByte('\n'); + } + }, + .element => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + try writer.print("table index {d}\n", .{try std.leb.readULEB128(u32, reader)}); + try parseDumpInit(step, reader, writer); + + const function_indexes = try std.leb.readULEB128(u32, reader); + var function_index: u32 = 0; + try writer.print("indexes {d}\n", .{function_indexes}); + while (function_index < function_indexes) : (function_index += 1) { + try writer.print("index {d}\n", .{try std.leb.readULEB128(u32, reader)}); + } + } + }, + .code => {}, // code section is considered opaque to linker + .data => { + var i: u32 = 0; + while (i < entries) : (i += 1) { + const index = try std.leb.readULEB128(u32, reader); + try writer.print("memory index 0x{x}\n", .{index}); + try parseDumpInit(step, reader, writer); + const size = try std.leb.readULEB128(u32, reader); + try writer.print("size {d}\n", .{size}); + try reader.skipBytes(size, .{}); // we do not care about the content of the segments + } + }, + else => unreachable, + } + } + + fn parseDumpType(step: *Step, comptime WasmType: type, reader: anytype, writer: anytype) !void { + const type_byte = try reader.readByte(); + const valtype = std.meta.intToEnum(WasmType, type_byte) catch { + return step.fail("Invalid wasm type value '{d}'", .{type_byte}); + }; + try writer.print("type {s}\n", .{@tagName(valtype)}); + } + + fn parseDumpLimits(reader: anytype, writer: anytype) !void { + const flags = try std.leb.readULEB128(u8, reader); + const min = try std.leb.readULEB128(u32, reader); + + try writer.print("min {x}\n", .{min}); + if (flags != 0) { + try writer.print("max {x}\n", .{try std.leb.readULEB128(u32, reader)}); + } + } + + fn parseDumpInit(step: *Step, reader: anytype, writer: anytype) !void { + const byte = try std.leb.readULEB128(u8, reader); + const opcode = std.meta.intToEnum(std.wasm.Opcode, byte) catch { + return step.fail("invalid wasm opcode '{d}'", .{byte}); + }; + switch (opcode) { + .i32_const => try writer.print("i32.const {x}\n", .{try std.leb.readILEB128(i32, reader)}), + .i64_const => try writer.print("i64.const {x}\n", .{try std.leb.readILEB128(i64, reader)}), + .f32_const => try writer.print("f32.const {x}\n", .{@bitCast(f32, try reader.readIntLittle(u32))}), + .f64_const => try writer.print("f64.const {x}\n", .{@bitCast(f64, try reader.readIntLittle(u64))}), + .global_get => try writer.print("global.get {x}\n", .{try std.leb.readULEB128(u32, reader)}), + else => unreachable, + } + const end_opcode = try std.leb.readULEB128(u8, reader); + if (end_opcode != std.wasm.opcode(.end)) { + return step.fail("expected 'end' opcode in init expression", .{}); + } + } + + fn parseDumpNames(step: *Step, reader: anytype, writer: anytype, data: []const u8) !void { + while (reader.context.pos < data.len) { + try parseDumpType(step, std.wasm.NameSubsection, reader, writer); + const size = try std.leb.readULEB128(u32, reader); + const entries = try std.leb.readULEB128(u32, reader); + try writer.print( + \\size {d} + \\names {d} + , .{ size, entries }); + try writer.writeByte('\n'); + var i: u32 = 0; + while (i < entries) : (i += 1) { + const index = try std.leb.readULEB128(u32, reader); + const name_len = try std.leb.readULEB128(u32, reader); + const pos = reader.context.pos; + const name = data[pos..][0..name_len]; + reader.context.pos += name_len; + + try writer.print( + \\index {d} + \\name {s} + , .{ index, name }); + try writer.writeByte('\n'); + } + } + } + + fn parseDumpProducers(reader: anytype, writer: anytype, data: []const u8) !void { + const field_count = try std.leb.readULEB128(u32, reader); + try writer.print("fields {d}\n", .{field_count}); + var current_field: u32 = 0; + while (current_field < field_count) : (current_field += 1) { + const field_name_length = try std.leb.readULEB128(u32, reader); + const field_name = data[reader.context.pos..][0..field_name_length]; + reader.context.pos += field_name_length; + + const value_count = try std.leb.readULEB128(u32, reader); + try writer.print( + \\field_name {s} + \\values {d} + , .{ field_name, value_count }); + try writer.writeByte('\n'); + var current_value: u32 = 0; + while (current_value < value_count) : (current_value += 1) { + const value_length = try std.leb.readULEB128(u32, reader); + const value = data[reader.context.pos..][0..value_length]; + reader.context.pos += value_length; + + const version_length = try std.leb.readULEB128(u32, reader); + const version = data[reader.context.pos..][0..version_length]; + reader.context.pos += version_length; + + try writer.print( + \\value_name {s} + \\version {s} + , .{ value, version }); + try writer.writeByte('\n'); + } + } + } + + fn parseDumpFeatures(reader: anytype, writer: anytype, data: []const u8) !void { + const feature_count = try std.leb.readULEB128(u32, reader); + try writer.print("features {d}\n", .{feature_count}); + + var index: u32 = 0; + while (index < feature_count) : (index += 1) { + const prefix_byte = try std.leb.readULEB128(u8, reader); + const name_length = try std.leb.readULEB128(u32, reader); + const feature_name = data[reader.context.pos..][0..name_length]; + reader.context.pos += name_length; + + try writer.print("{c} {s}\n", .{ prefix_byte, feature_name }); + } + } +}; -- cgit v1.2.3 From 3f3b1a6808113fd5f9b2cec1033009cbb17dc969 Mon Sep 17 00:00:00 2001 From: Veikka Tuominen Date: Wed, 3 May 2023 11:49:55 +0300 Subject: std.Build: use Step.* instead of *Step Follow up to 13eb7251d37759bd47403db304c6120c706fe353 --- build.zig | 12 +- lib/init-exe/build.zig | 2 +- lib/std/Build.zig | 150 +++++++++++++------------ lib/std/Build/Step.zig | 67 ++++++++--- lib/std/Build/Step/CheckFile.zig | 12 +- lib/std/Build/Step/CheckObject.zig | 28 ++--- lib/std/Build/Step/Compile.zig | 168 ++++++++++++++-------------- lib/std/Build/Step/ConfigHeader.zig | 26 ++--- lib/std/Build/Step/Fmt.zig | 8 +- lib/std/Build/Step/InstallArtifact.zig | 17 ++- lib/std/Build/Step/InstallFile.zig | 8 +- lib/std/Build/Step/ObjCopy.zig | 17 ++- lib/std/Build/Step/Options.zig | 25 ++--- lib/std/Build/Step/RemoveDir.zig | 8 +- lib/std/Build/Step/Run.zig | 108 +++++++++--------- lib/std/Build/Step/TranslateC.zig | 26 ++--- lib/std/Build/Step/WriteFile.zig | 38 +++---- test/link/macho/dead_strip/build.zig | 2 +- test/link/macho/dead_strip_dylibs/build.zig | 2 +- test/link/macho/headerpad/build.zig | 2 +- test/link/macho/search_strategy/build.zig | 2 +- test/link/macho/unwind_info/build.zig | 2 +- test/link/macho/uuid/build.zig | 3 +- test/src/Cases.zig | 2 +- test/src/StackTrace.zig | 2 +- test/standalone/install_raw_hex/build.zig | 1 - test/tests.zig | 2 +- 27 files changed, 379 insertions(+), 361 deletions(-) (limited to 'lib/std/Build/Step/CheckObject.zig') diff --git a/build.zig b/build.zig index 78345ac9e4..208d06fe1d 100644 --- a/build.zig +++ b/build.zig @@ -533,7 +533,7 @@ fn addCompilerStep( b: *std.Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const exe = b.addExecutable(.{ .name = "zig", .root_source_file = .{ .path = "src/main.zig" }, @@ -561,7 +561,7 @@ const exe_cflags = [_][]const u8{ fn addCmakeCfgOptionsToExe( b: *std.Build, cfg: CMakeConfig, - exe: *std.Build.CompileStep, + exe: *std.Build.Step.Compile, use_zig_libcxx: bool, ) !void { if (exe.target.isDarwin()) { @@ -640,7 +640,7 @@ fn addCmakeCfgOptionsToExe( } } -fn addStaticLlvmOptionsToExe(exe: *std.Build.CompileStep) !void { +fn addStaticLlvmOptionsToExe(exe: *std.Build.Step.Compile) !void { // Adds the Zig C++ sources which both stage1 and stage2 need. // // We need this because otherwise zig_clang_cc1_main.cpp ends up pulling @@ -679,7 +679,7 @@ fn addStaticLlvmOptionsToExe(exe: *std.Build.CompileStep) !void { fn addCxxKnownPath( b: *std.Build, ctx: CMakeConfig, - exe: *std.Build.CompileStep, + exe: *std.Build.Step.Compile, objname: []const u8, errtxt: ?[]const u8, need_cpp_includes: bool, @@ -709,7 +709,7 @@ fn addCxxKnownPath( } } -fn addCMakeLibraryList(exe: *std.Build.CompileStep, list: []const u8) void { +fn addCMakeLibraryList(exe: *std.Build.Step.Compile, list: []const u8) void { var it = mem.tokenize(u8, list, ";"); while (it.next()) |lib| { if (mem.startsWith(u8, lib, "-l")) { @@ -723,7 +723,7 @@ fn addCMakeLibraryList(exe: *std.Build.CompileStep, list: []const u8) void { } const CMakeConfig = struct { - llvm_linkage: std.Build.CompileStep.Linkage, + llvm_linkage: std.Build.Step.Compile.Linkage, cmake_binary_dir: []const u8, cmake_prefix_path: []const u8, cmake_static_library_prefix: []const u8, diff --git a/lib/init-exe/build.zig b/lib/init-exe/build.zig index abf8654f0f..1221984190 100644 --- a/lib/init-exe/build.zig +++ b/lib/init-exe/build.zig @@ -29,7 +29,7 @@ pub fn build(b: *std.Build) void { // step when running `zig build`). b.installArtifact(exe); - // This *creates* a RunStep in the build graph, to be executed when another + // This *creates* a Run step in the build graph, to be executed when another // step is evaluated that depends on it. The next line below will establish // such a dependency. const run_cmd = b.addRunArtifact(exe); diff --git a/lib/std/Build.zig b/lib/std/Build.zig index bda50112b6..ca55d23937 100644 --- a/lib/std/Build.zig +++ b/lib/std/Build.zig @@ -21,27 +21,41 @@ const Build = @This(); pub const Cache = @import("Build/Cache.zig"); -/// deprecated: use `CompileStep`. -pub const LibExeObjStep = CompileStep; +/// deprecated: use `Step.Compile`. +pub const LibExeObjStep = Step.Compile; /// deprecated: use `Build`. pub const Builder = Build; -/// deprecated: use `InstallDirStep.Options` -pub const InstallDirectoryOptions = InstallDirStep.Options; +/// deprecated: use `Step.InstallDir.Options` +pub const InstallDirectoryOptions = Step.InstallDir.Options; pub const Step = @import("Build/Step.zig"); +/// deprecated: use `Step.CheckFile`. pub const CheckFileStep = @import("Build/Step/CheckFile.zig"); +/// deprecated: use `Step.CheckObject`. pub const CheckObjectStep = @import("Build/Step/CheckObject.zig"); +/// deprecated: use `Step.ConfigHeader`. pub const ConfigHeaderStep = @import("Build/Step/ConfigHeader.zig"); +/// deprecated: use `Step.Fmt`. pub const FmtStep = @import("Build/Step/Fmt.zig"); +/// deprecated: use `Step.InstallArtifact`. pub const InstallArtifactStep = @import("Build/Step/InstallArtifact.zig"); +/// deprecated: use `Step.InstallDir`. pub const InstallDirStep = @import("Build/Step/InstallDir.zig"); +/// deprecated: use `Step.InstallFile`. pub const InstallFileStep = @import("Build/Step/InstallFile.zig"); +/// deprecated: use `Step.ObjCopy`. pub const ObjCopyStep = @import("Build/Step/ObjCopy.zig"); +/// deprecated: use `Step.Compile`. pub const CompileStep = @import("Build/Step/Compile.zig"); +/// deprecated: use `Step.Options`. pub const OptionsStep = @import("Build/Step/Options.zig"); +/// deprecated: use `Step.RemoveDir`. pub const RemoveDirStep = @import("Build/Step/RemoveDir.zig"); +/// deprecated: use `Step.Run`. pub const RunStep = @import("Build/Step/Run.zig"); +/// deprecated: use `Step.TranslateC`. pub const TranslateCStep = @import("Build/Step/TranslateC.zig"); +/// deprecated: use `Step.WriteFile`. pub const WriteFileStep = @import("Build/Step/WriteFile.zig"); install_tls: TopLevelStep, @@ -442,8 +456,8 @@ pub fn resolveInstallPrefix(self: *Build, install_prefix: ?[]const u8, dir_list: self.h_dir = self.pathJoin(&h_list); } -pub fn addOptions(self: *Build) *OptionsStep { - return OptionsStep.create(self); +pub fn addOptions(self: *Build) *Step.Options { + return Step.Options.create(self); } pub const ExecutableOptions = struct { @@ -452,7 +466,7 @@ pub const ExecutableOptions = struct { version: ?std.builtin.Version = null, target: CrossTarget = .{}, optimize: std.builtin.Mode = .Debug, - linkage: ?CompileStep.Linkage = null, + linkage: ?Step.Compile.Linkage = null, max_rss: usize = 0, link_libc: ?bool = null, single_threaded: ?bool = null, @@ -460,8 +474,8 @@ pub const ExecutableOptions = struct { use_lld: ?bool = null, }; -pub fn addExecutable(b: *Build, options: ExecutableOptions) *CompileStep { - return CompileStep.create(b, .{ +pub fn addExecutable(b: *Build, options: ExecutableOptions) *Step.Compile { + return Step.Compile.create(b, .{ .name = options.name, .root_source_file = options.root_source_file, .version = options.version, @@ -489,8 +503,8 @@ pub const ObjectOptions = struct { use_lld: ?bool = null, }; -pub fn addObject(b: *Build, options: ObjectOptions) *CompileStep { - return CompileStep.create(b, .{ +pub fn addObject(b: *Build, options: ObjectOptions) *Step.Compile { + return Step.Compile.create(b, .{ .name = options.name, .root_source_file = options.root_source_file, .target = options.target, @@ -517,8 +531,8 @@ pub const SharedLibraryOptions = struct { use_lld: ?bool = null, }; -pub fn addSharedLibrary(b: *Build, options: SharedLibraryOptions) *CompileStep { - return CompileStep.create(b, .{ +pub fn addSharedLibrary(b: *Build, options: SharedLibraryOptions) *Step.Compile { + return Step.Compile.create(b, .{ .name = options.name, .root_source_file = options.root_source_file, .kind = .lib, @@ -547,8 +561,8 @@ pub const StaticLibraryOptions = struct { use_lld: ?bool = null, }; -pub fn addStaticLibrary(b: *Build, options: StaticLibraryOptions) *CompileStep { - return CompileStep.create(b, .{ +pub fn addStaticLibrary(b: *Build, options: StaticLibraryOptions) *Step.Compile { + return Step.Compile.create(b, .{ .name = options.name, .root_source_file = options.root_source_file, .kind = .lib, @@ -579,8 +593,8 @@ pub const TestOptions = struct { use_lld: ?bool = null, }; -pub fn addTest(b: *Build, options: TestOptions) *CompileStep { - return CompileStep.create(b, .{ +pub fn addTest(b: *Build, options: TestOptions) *Step.Compile { + return Step.Compile.create(b, .{ .name = options.name, .kind = .@"test", .root_source_file = options.root_source_file, @@ -604,8 +618,8 @@ pub const AssemblyOptions = struct { max_rss: usize = 0, }; -pub fn addAssembly(b: *Build, options: AssemblyOptions) *CompileStep { - const obj_step = CompileStep.create(b, .{ +pub fn addAssembly(b: *Build, options: AssemblyOptions) *Step.Compile { + const obj_step = Step.Compile.create(b, .{ .name = options.name, .kind = .obj, .root_source_file = null, @@ -657,25 +671,25 @@ fn moduleDependenciesToArrayHashMap(arena: Allocator, deps: []const ModuleDepend return result; } -/// Initializes a RunStep with argv, which must at least have the path to the +/// Initializes a `Step.Run` with argv, which must at least have the path to the /// executable. More command line arguments can be added with `addArg`, /// `addArgs`, and `addArtifactArg`. /// Be careful using this function, as it introduces a system dependency. -/// To run an executable built with zig build, see `CompileStep.run`. -pub fn addSystemCommand(self: *Build, argv: []const []const u8) *RunStep { +/// To run an executable built with zig build, see `Step.Compile.run`. +pub fn addSystemCommand(self: *Build, argv: []const []const u8) *Step.Run { assert(argv.len >= 1); - const run_step = RunStep.create(self, self.fmt("run {s}", .{argv[0]})); + const run_step = Step.Run.create(self, self.fmt("run {s}", .{argv[0]})); run_step.addArgs(argv); return run_step; } -/// Creates a `RunStep` with an executable built with `addExecutable`. -/// Add command line arguments with methods of `RunStep`. -pub fn addRunArtifact(b: *Build, exe: *CompileStep) *RunStep { +/// Creates a `Step.Run` with an executable built with `addExecutable`. +/// Add command line arguments with methods of `Step.Run`. +pub fn addRunArtifact(b: *Build, exe: *Step.Compile) *Step.Run { // It doesn't have to be native. We catch that if you actually try to run it. // Consider that this is declarative; the run step may not be run unless a user // option is supplied. - const run_step = RunStep.create(b, b.fmt("run {s}", .{exe.name})); + const run_step = Step.Run.create(b, b.fmt("run {s}", .{exe.name})); run_step.addArtifactArg(exe); if (exe.kind == .@"test") { @@ -696,14 +710,14 @@ pub fn addRunArtifact(b: *Build, exe: *CompileStep) *RunStep { /// when an option found in the input file is missing from `values`. pub fn addConfigHeader( b: *Build, - options: ConfigHeaderStep.Options, + options: Step.ConfigHeader.Options, values: anytype, -) *ConfigHeaderStep { +) *Step.ConfigHeader { var options_copy = options; if (options_copy.first_ret_addr == null) options_copy.first_ret_addr = @returnAddress(); - const config_header_step = ConfigHeaderStep.create(b, options_copy); + const config_header_step = Step.ConfigHeader.create(b, options_copy); config_header_step.addValues(values); return config_header_step; } @@ -734,28 +748,28 @@ pub fn dupePath(self: *Build, bytes: []const u8) []u8 { return the_copy; } -pub fn addWriteFile(self: *Build, file_path: []const u8, data: []const u8) *WriteFileStep { +pub fn addWriteFile(self: *Build, file_path: []const u8, data: []const u8) *Step.WriteFile { const write_file_step = self.addWriteFiles(); write_file_step.add(file_path, data); return write_file_step; } -pub fn addWriteFiles(b: *Build) *WriteFileStep { - return WriteFileStep.create(b); +pub fn addWriteFiles(b: *Build) *Step.WriteFile { + return Step.WriteFile.create(b); } -pub fn addRemoveDirTree(self: *Build, dir_path: []const u8) *RemoveDirStep { - const remove_dir_step = self.allocator.create(RemoveDirStep) catch @panic("OOM"); - remove_dir_step.* = RemoveDirStep.init(self, dir_path); +pub fn addRemoveDirTree(self: *Build, dir_path: []const u8) *Step.RemoveDir { + const remove_dir_step = self.allocator.create(Step.RemoveDir) catch @panic("OOM"); + remove_dir_step.* = Step.RemoveDir.init(self, dir_path); return remove_dir_step; } -pub fn addFmt(b: *Build, options: FmtStep.Options) *FmtStep { - return FmtStep.create(b, options); +pub fn addFmt(b: *Build, options: Step.Fmt.Options) *Step.Fmt { + return Step.Fmt.create(b, options); } -pub fn addTranslateC(self: *Build, options: TranslateCStep.Options) *TranslateCStep { - return TranslateCStep.create(self, options); +pub fn addTranslateC(self: *Build, options: Step.TranslateC.Options) *Step.TranslateC { + return Step.TranslateC.create(self, options); } pub fn getInstallStep(self: *Build) *Step { @@ -1213,12 +1227,12 @@ fn printCmd(ally: Allocator, cwd: ?[]const u8, argv: []const []const u8) void { std.debug.print("{s}\n", .{text}); } -pub fn installArtifact(self: *Build, artifact: *CompileStep) void { +pub fn installArtifact(self: *Build, artifact: *Step.Compile) void { self.getInstallStep().dependOn(&self.addInstallArtifact(artifact).step); } -pub fn addInstallArtifact(self: *Build, artifact: *CompileStep) *InstallArtifactStep { - return InstallArtifactStep.create(self, artifact); +pub fn addInstallArtifact(self: *Build, artifact: *Step.Compile) *Step.InstallArtifact { + return Step.InstallArtifact.create(self, artifact); } ///`dest_rel_path` is relative to prefix path @@ -1240,26 +1254,26 @@ pub fn installLibFile(self: *Build, src_path: []const u8, dest_rel_path: []const self.getInstallStep().dependOn(&self.addInstallFileWithDir(.{ .path = src_path }, .lib, dest_rel_path).step); } -pub fn addObjCopy(b: *Build, source: FileSource, options: ObjCopyStep.Options) *ObjCopyStep { - return ObjCopyStep.create(b, source, options); +pub fn addObjCopy(b: *Build, source: FileSource, options: Step.ObjCopy.Options) *Step.ObjCopy { + return Step.ObjCopy.create(b, source, options); } ///`dest_rel_path` is relative to install prefix path -pub fn addInstallFile(self: *Build, source: FileSource, dest_rel_path: []const u8) *InstallFileStep { +pub fn addInstallFile(self: *Build, source: FileSource, dest_rel_path: []const u8) *Step.InstallFile { return self.addInstallFileWithDir(source.dupe(self), .prefix, dest_rel_path); } ///`dest_rel_path` is relative to bin path -pub fn addInstallBinFile(self: *Build, source: FileSource, dest_rel_path: []const u8) *InstallFileStep { +pub fn addInstallBinFile(self: *Build, source: FileSource, dest_rel_path: []const u8) *Step.InstallFile { return self.addInstallFileWithDir(source.dupe(self), .bin, dest_rel_path); } ///`dest_rel_path` is relative to lib path -pub fn addInstallLibFile(self: *Build, source: FileSource, dest_rel_path: []const u8) *InstallFileStep { +pub fn addInstallLibFile(self: *Build, source: FileSource, dest_rel_path: []const u8) *Step.InstallFile { return self.addInstallFileWithDir(source.dupe(self), .lib, dest_rel_path); } -pub fn addInstallHeaderFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep { +pub fn addInstallHeaderFile(b: *Build, src_path: []const u8, dest_rel_path: []const u8) *Step.InstallFile { return b.addInstallFileWithDir(.{ .path = src_path }, .header, dest_rel_path); } @@ -1268,22 +1282,22 @@ pub fn addInstallFileWithDir( source: FileSource, install_dir: InstallDir, dest_rel_path: []const u8, -) *InstallFileStep { - return InstallFileStep.create(self, source.dupe(self), install_dir, dest_rel_path); +) *Step.InstallFile { + return Step.InstallFile.create(self, source.dupe(self), install_dir, dest_rel_path); } -pub fn addInstallDirectory(self: *Build, options: InstallDirectoryOptions) *InstallDirStep { - const install_step = self.allocator.create(InstallDirStep) catch @panic("OOM"); - install_step.* = InstallDirStep.init(self, options); +pub fn addInstallDirectory(self: *Build, options: InstallDirectoryOptions) *Step.InstallDir { + const install_step = self.allocator.create(Step.InstallDir) catch @panic("OOM"); + install_step.* = Step.InstallDir.init(self, options); return install_step; } pub fn addCheckFile( b: *Build, file_source: FileSource, - options: CheckFileStep.Options, -) *CheckFileStep { - return CheckFileStep.create(b, file_source, options); + options: Step.CheckFile.Options, +) *Step.CheckFile { + return Step.CheckFile.create(b, file_source, options); } pub fn pushInstalledFile(self: *Build, dir: InstallDir, dest_rel_path: []const u8) void { @@ -1453,10 +1467,10 @@ pub fn getInstallPath(self: *Build, dir: InstallDir, dest_rel_path: []const u8) pub const Dependency = struct { builder: *Build, - pub fn artifact(d: *Dependency, name: []const u8) *CompileStep { - var found: ?*CompileStep = null; + pub fn artifact(d: *Dependency, name: []const u8) *Step.Compile { + var found: ?*Step.Compile = null; for (d.builder.install_tls.step.dependencies.items) |dep_step| { - const inst = dep_step.cast(InstallArtifactStep) orelse continue; + const inst = dep_step.cast(Step.InstallArtifact) orelse continue; if (mem.eql(u8, inst.artifact.name, name)) { if (found != null) panic("artifact name '{s}' is ambiguous", .{name}); found = inst.artifact; @@ -1464,7 +1478,7 @@ pub const Dependency = struct { } return found orelse { for (d.builder.install_tls.step.dependencies.items) |dep_step| { - const inst = dep_step.cast(InstallArtifactStep) orelse continue; + const inst = dep_step.cast(Step.InstallArtifact) orelse continue; log.info("available artifact: '{s}'", .{inst.artifact.name}); } panic("unable to find artifact '{s}'", .{name}); @@ -1808,17 +1822,5 @@ pub fn hex64(x: u64) [16]u8 { } test { - _ = CheckFileStep; - _ = CheckObjectStep; - _ = FmtStep; - _ = InstallArtifactStep; - _ = InstallDirStep; - _ = InstallFileStep; - _ = ObjCopyStep; - _ = CompileStep; - _ = OptionsStep; - _ = RemoveDirStep; - _ = RunStep; - _ = TranslateCStep; - _ = WriteFileStep; + _ = Step; } diff --git a/lib/std/Build/Step.zig b/lib/std/Build/Step.zig index bdb500d99c..40c88df2b9 100644 --- a/lib/std/Build/Step.zig +++ b/lib/std/Build/Step.zig @@ -94,26 +94,41 @@ pub const Id = enum { pub fn Type(comptime id: Id) type { return switch (id) { .top_level => Build.TopLevelStep, - .compile => Build.CompileStep, - .install_artifact => Build.InstallArtifactStep, - .install_file => Build.InstallFileStep, - .install_dir => Build.InstallDirStep, - .remove_dir => Build.RemoveDirStep, - .fmt => Build.FmtStep, - .translate_c => Build.TranslateCStep, - .write_file => Build.WriteFileStep, - .run => Build.RunStep, - .check_file => Build.CheckFileStep, - .check_object => Build.CheckObjectStep, - .config_header => Build.ConfigHeaderStep, - .objcopy => Build.ObjCopyStep, - .options => Build.OptionsStep, + .compile => Compile, + .install_artifact => InstallArtifact, + .install_file => InstallFile, + .install_dir => InstallDir, + .remove_dir => RemoveDir, + .fmt => Fmt, + .translate_c => TranslateC, + .write_file => WriteFile, + .run => Run, + .check_file => CheckFile, + .check_object => CheckObject, + .config_header => ConfigHeader, + .objcopy => ObjCopy, + .options => Options, .custom => @compileError("no type available for custom step"), }; } }; -pub const Options = struct { +pub const CheckFile = @import("Step/CheckFile.zig"); +pub const CheckObject = @import("Step/CheckObject.zig"); +pub const ConfigHeader = @import("Step/ConfigHeader.zig"); +pub const Fmt = @import("Step/Fmt.zig"); +pub const InstallArtifact = @import("Step/InstallArtifact.zig"); +pub const InstallDir = @import("Step/InstallDir.zig"); +pub const InstallFile = @import("Step/InstallFile.zig"); +pub const ObjCopy = @import("Step/ObjCopy.zig"); +pub const Compile = @import("Step/Compile.zig"); +pub const Options = @import("Step/Options.zig"); +pub const RemoveDir = @import("Step/RemoveDir.zig"); +pub const Run = @import("Step/Run.zig"); +pub const TranslateC = @import("Step/TranslateC.zig"); +pub const WriteFile = @import("Step/WriteFile.zig"); + +pub const StepOptions = struct { id: Id, name: []const u8, owner: *Build, @@ -122,7 +137,7 @@ pub const Options = struct { max_rss: usize = 0, }; -pub fn init(options: Options) Step { +pub fn init(options: StepOptions) Step { const arena = options.owner.allocator; var addresses = [1]usize{0} ** n_debug_stack_frames; @@ -387,8 +402,8 @@ pub fn evalZigProcess( s.result_duration_ns = timer.read(); s.result_peak_rss = child.resource_usage_statistics.getMaxRss() orelse 0; - // Special handling for CompileStep that is expecting compile errors. - if (s.cast(Build.CompileStep)) |compile| switch (term) { + // Special handling for Compile step that is expecting compile errors. + if (s.cast(Compile)) |compile| switch (term) { .Exited => { // Note that the exit code may be 0 in this case due to the // compiler server protocol. @@ -535,3 +550,19 @@ pub fn writeManifest(s: *Step, man: *std.Build.Cache.Manifest) !void { }; } } + +test { + _ = CheckFile; + _ = CheckObject; + _ = Fmt; + _ = InstallArtifact; + _ = InstallDir; + _ = InstallFile; + _ = ObjCopy; + _ = Compile; + _ = Options; + _ = RemoveDir; + _ = Run; + _ = TranslateC; + _ = WriteFile; +} diff --git a/lib/std/Build/Step/CheckFile.zig b/lib/std/Build/Step/CheckFile.zig index ad8b1a25f0..dc359b5654 100644 --- a/lib/std/Build/Step/CheckFile.zig +++ b/lib/std/Build/Step/CheckFile.zig @@ -1,8 +1,8 @@ //! Fail the build step if a file does not match certain checks. //! TODO: make this more flexible, supporting more kinds of checks. //! TODO: generalize the code in std.testing.expectEqualStrings and make this -//! CheckFileStep produce those helpful diagnostics when there is not a match. -const CheckFileStep = @This(); +//! CheckFile step produce those helpful diagnostics when there is not a match. +const CheckFile = @This(); const std = @import("std"); const Step = std.Build.Step; const fs = std.fs; @@ -25,8 +25,8 @@ pub fn create( owner: *std.Build, source: std.Build.FileSource, options: Options, -) *CheckFileStep { - const self = owner.allocator.create(CheckFileStep) catch @panic("OOM"); +) *CheckFile { + const self = owner.allocator.create(CheckFile) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = .check_file, @@ -42,14 +42,14 @@ pub fn create( return self; } -pub fn setName(self: *CheckFileStep, name: []const u8) void { +pub fn setName(self: *CheckFile, name: []const u8) void { self.step.name = name; } fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; - const self = @fieldParentPtr(CheckFileStep, "step", step); + const self = @fieldParentPtr(CheckFile, "step", step); const src_path = self.source.getPath(b); const contents = fs.cwd().readFileAlloc(b.allocator, src_path, self.max_bytes) catch |err| { diff --git a/lib/std/Build/Step/CheckObject.zig b/lib/std/Build/Step/CheckObject.zig index 431f74eccc..c77dc3de36 100644 --- a/lib/std/Build/Step/CheckObject.zig +++ b/lib/std/Build/Step/CheckObject.zig @@ -6,7 +6,7 @@ const math = std.math; const mem = std.mem; const testing = std.testing; -const CheckObjectStep = @This(); +const CheckObject = @This(); const Allocator = mem.Allocator; const Step = std.Build.Step; @@ -24,9 +24,9 @@ pub fn create( owner: *std.Build, source: std.Build.FileSource, obj_format: std.Target.ObjectFormat, -) *CheckObjectStep { +) *CheckObject { const gpa = owner.allocator; - const self = gpa.create(CheckObjectStep) catch @panic("OOM"); + const self = gpa.create(CheckObject) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = .check_file, @@ -47,11 +47,11 @@ pub fn create( /// TODO this doesn't actually compare, and there's no apparent reason for it /// to depend on the check object step. I don't see why this function should exist, /// the caller could just add the run step directly. -pub fn runAndCompare(self: *CheckObjectStep) *std.Build.RunStep { +pub fn runAndCompare(self: *CheckObject) *std.Build.Step.Run { const dependencies_len = self.step.dependencies.items.len; assert(dependencies_len > 0); const exe_step = self.step.dependencies.items[dependencies_len - 1]; - const exe = exe_step.cast(std.Build.CompileStep).?; + const exe = exe_step.cast(std.Build.Step.Compile).?; const run = self.step.owner.addRunArtifact(exe); run.skip_foreign_checks = true; run.step.dependOn(&self.step); @@ -274,15 +274,15 @@ const Check = struct { }; /// Creates a new sequence of actions with `phrase` as the first anchor searched phrase. -pub fn checkStart(self: *CheckObjectStep, phrase: []const u8) void { +pub fn checkStart(self: *CheckObject, phrase: []const u8) void { var new_check = Check.create(self.step.owner.allocator); new_check.match(.{ .string = self.step.owner.dupe(phrase) }); self.checks.append(new_check) catch @panic("OOM"); } -/// Adds another searched phrase to the latest created Check with `CheckObjectStep.checkStart(...)`. +/// Adds another searched phrase to the latest created Check with `CheckObject.checkStart(...)`. /// Asserts at least one check already exists. -pub fn checkNext(self: *CheckObjectStep, phrase: []const u8) void { +pub fn checkNext(self: *CheckObject, phrase: []const u8) void { assert(self.checks.items.len > 0); const last = &self.checks.items[self.checks.items.len - 1]; last.match(.{ .string = self.step.owner.dupe(phrase) }); @@ -291,7 +291,7 @@ pub fn checkNext(self: *CheckObjectStep, phrase: []const u8) void { /// Like `checkNext()` but takes an additional argument `FileSource` which will be /// resolved to a full search query in `make()`. pub fn checkNextFileSource( - self: *CheckObjectStep, + self: *CheckObject, phrase: []const u8, file_source: std.Build.FileSource, ) void { @@ -300,10 +300,10 @@ pub fn checkNextFileSource( last.match(.{ .string = self.step.owner.dupe(phrase), .file_source = file_source }); } -/// Adds another searched phrase to the latest created Check with `CheckObjectStep.checkStart(...)` +/// Adds another searched phrase to the latest created Check with `CheckObject.checkStart(...)` /// however ensures there is no matching phrase in the output. /// Asserts at least one check already exists. -pub fn checkNotPresent(self: *CheckObjectStep, phrase: []const u8) void { +pub fn checkNotPresent(self: *CheckObject, phrase: []const u8) void { assert(self.checks.items.len > 0); const last = &self.checks.items[self.checks.items.len - 1]; last.notPresent(.{ .string = self.step.owner.dupe(phrase) }); @@ -312,7 +312,7 @@ pub fn checkNotPresent(self: *CheckObjectStep, phrase: []const u8) void { /// Creates a new check checking specifically symbol table parsed and dumped from the object /// file. /// Issuing this check will force parsing and dumping of the symbol table. -pub fn checkInSymtab(self: *CheckObjectStep) void { +pub fn checkInSymtab(self: *CheckObject) void { self.dump_symtab = true; const symtab_label = switch (self.obj_format) { .macho => MachODumper.symtab_label, @@ -325,7 +325,7 @@ pub fn checkInSymtab(self: *CheckObjectStep) void { /// on the extracted variables. It will then compare the reduced program with the value of /// the expected variable. pub fn checkComputeCompare( - self: *CheckObjectStep, + self: *CheckObject, program: []const u8, expected: ComputeCompareExpected, ) void { @@ -338,7 +338,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; const gpa = b.allocator; - const self = @fieldParentPtr(CheckObjectStep, "step", step); + const self = @fieldParentPtr(CheckObject, "step", step); const src_path = self.source.getPath(b); const contents = fs.cwd().readFileAllocOptions( diff --git a/lib/std/Build/Step/Compile.zig b/lib/std/Build/Step/Compile.zig index 7627c4e6d0..2371f49daf 100644 --- a/lib/std/Build/Step/Compile.zig +++ b/lib/std/Build/Step/Compile.zig @@ -18,14 +18,8 @@ const ExecError = std.Build.ExecError; const Module = std.Build.Module; const VcpkgRoot = std.Build.VcpkgRoot; const InstallDir = std.Build.InstallDir; -const InstallArtifactStep = std.Build.InstallArtifactStep; const GeneratedFile = std.Build.GeneratedFile; -const ObjCopyStep = std.Build.ObjCopyStep; -const CheckObjectStep = std.Build.CheckObjectStep; -const RunStep = std.Build.RunStep; -const OptionsStep = std.Build.OptionsStep; -const ConfigHeaderStep = std.Build.ConfigHeaderStep; -const CompileStep = @This(); +const Compile = @This(); pub const base_id: Step.Id = .compile; @@ -211,8 +205,8 @@ want_lto: ?bool = null, use_llvm: ?bool, use_lld: ?bool, -/// This is an advanced setting that can change the intent of this CompileStep. -/// If this slice has nonzero length, it means that this CompileStep exists to +/// This is an advanced setting that can change the intent of this Compile step. +/// If this slice has nonzero length, it means that this Compile step exists to /// check for compile errors and return *success* if they match, and failure /// otherwise. expect_errors: []const []const u8 = &.{}, @@ -242,7 +236,7 @@ pub const CSourceFile = struct { pub const LinkObject = union(enum) { static_path: FileSource, - other_step: *CompileStep, + other_step: *Compile, system_lib: SystemLib, assembly_file: FileSource, c_source_file: *CSourceFile, @@ -273,8 +267,8 @@ const FrameworkLinkInfo = struct { pub const IncludeDir = union(enum) { raw_path: []const u8, raw_path_system: []const u8, - other_step: *CompileStep, - config_header_step: *ConfigHeaderStep, + other_step: *Compile, + config_header_step: *Step.ConfigHeader, }; pub const Options = struct { @@ -319,7 +313,7 @@ pub const EmitOption = union(enum) { } }; -pub fn create(owner: *std.Build, options: Options) *CompileStep { +pub fn create(owner: *std.Build, options: Options) *Compile { const name = owner.dupe(options.name); const root_src: ?FileSource = if (options.root_source_file) |rsrc| rsrc.dupe(owner) else null; if (mem.indexOf(u8, name, "/") != null or mem.indexOf(u8, name, "\\") != null) { @@ -361,8 +355,8 @@ pub fn create(owner: *std.Build, options: Options) *CompileStep { .version = options.version, }) catch @panic("OOM"); - const self = owner.allocator.create(CompileStep) catch @panic("OOM"); - self.* = CompileStep{ + const self = owner.allocator.create(Compile) catch @panic("OOM"); + self.* = Compile{ .strip = null, .unwind_tables = null, .verbose_link = false, @@ -459,7 +453,7 @@ pub fn create(owner: *std.Build, options: Options) *CompileStep { return self; } -pub fn installHeader(cs: *CompileStep, src_path: []const u8, dest_rel_path: []const u8) void { +pub fn installHeader(cs: *Compile, src_path: []const u8, dest_rel_path: []const u8) void { const b = cs.step.owner; const install_file = b.addInstallHeaderFile(src_path, dest_rel_path); b.getInstallStep().dependOn(&install_file.step); @@ -472,8 +466,8 @@ pub const InstallConfigHeaderOptions = struct { }; pub fn installConfigHeader( - cs: *CompileStep, - config_header: *ConfigHeaderStep, + cs: *Compile, + config_header: *Step.ConfigHeader, options: InstallConfigHeaderOptions, ) void { const dest_rel_path = options.dest_rel_path orelse config_header.include_path; @@ -489,7 +483,7 @@ pub fn installConfigHeader( } pub fn installHeadersDirectory( - a: *CompileStep, + a: *Compile, src_dir_path: []const u8, dest_rel_path: []const u8, ) void { @@ -501,8 +495,8 @@ pub fn installHeadersDirectory( } pub fn installHeadersDirectoryOptions( - cs: *CompileStep, - options: std.Build.InstallDirStep.Options, + cs: *Compile, + options: std.Build.Step.InstallDir.Options, ) void { const b = cs.step.owner; const install_dir = b.addInstallDirectory(options); @@ -510,7 +504,7 @@ pub fn installHeadersDirectoryOptions( cs.installed_headers.append(&install_dir.step) catch @panic("OOM"); } -pub fn installLibraryHeaders(cs: *CompileStep, l: *CompileStep) void { +pub fn installLibraryHeaders(cs: *Compile, l: *Compile) void { assert(l.kind == .lib); const b = cs.step.owner; const install_step = b.getInstallStep(); @@ -533,7 +527,7 @@ pub fn installLibraryHeaders(cs: *CompileStep, l: *CompileStep) void { cs.installed_headers.appendSlice(l.installed_headers.items) catch @panic("OOM"); } -pub fn addObjCopy(cs: *CompileStep, options: ObjCopyStep.Options) *ObjCopyStep { +pub fn addObjCopy(cs: *Compile, options: Step.ObjCopy.Options) *Step.ObjCopy { const b = cs.step.owner; var copy = options; if (copy.basename == null) { @@ -554,34 +548,34 @@ pub const run = @compileError("deprecated; use std.Build.addRunArtifact"); /// which is undesirable when installing an artifact provided by a dependency package. pub const install = @compileError("deprecated; use std.Build.installArtifact"); -pub fn checkObject(self: *CompileStep) *CheckObjectStep { - return CheckObjectStep.create(self.step.owner, self.getOutputSource(), self.target_info.target.ofmt); +pub fn checkObject(self: *Compile) *Step.CheckObject { + return Step.CheckObject.create(self.step.owner, self.getOutputSource(), self.target_info.target.ofmt); } -pub fn setLinkerScriptPath(self: *CompileStep, source: FileSource) void { +pub fn setLinkerScriptPath(self: *Compile, source: FileSource) void { const b = self.step.owner; self.linker_script = source.dupe(b); source.addStepDependencies(&self.step); } -pub fn forceUndefinedSymbol(self: *CompileStep, symbol_name: []const u8) void { +pub fn forceUndefinedSymbol(self: *Compile, symbol_name: []const u8) void { const b = self.step.owner; self.force_undefined_symbols.put(b.dupe(symbol_name), {}) catch @panic("OOM"); } -pub fn linkFramework(self: *CompileStep, framework_name: []const u8) void { +pub fn linkFramework(self: *Compile, framework_name: []const u8) void { const b = self.step.owner; self.frameworks.put(b.dupe(framework_name), .{}) catch @panic("OOM"); } -pub fn linkFrameworkNeeded(self: *CompileStep, framework_name: []const u8) void { +pub fn linkFrameworkNeeded(self: *Compile, framework_name: []const u8) void { const b = self.step.owner; self.frameworks.put(b.dupe(framework_name), .{ .needed = true, }) catch @panic("OOM"); } -pub fn linkFrameworkWeak(self: *CompileStep, framework_name: []const u8) void { +pub fn linkFrameworkWeak(self: *Compile, framework_name: []const u8) void { const b = self.step.owner; self.frameworks.put(b.dupe(framework_name), .{ .weak = true, @@ -589,7 +583,7 @@ pub fn linkFrameworkWeak(self: *CompileStep, framework_name: []const u8) void { } /// Returns whether the library, executable, or object depends on a particular system library. -pub fn dependsOnSystemLibrary(self: CompileStep, name: []const u8) bool { +pub fn dependsOnSystemLibrary(self: Compile, name: []const u8) bool { if (isLibCLibrary(name)) { return self.is_linking_libc; } @@ -605,51 +599,51 @@ pub fn dependsOnSystemLibrary(self: CompileStep, name: []const u8) bool { return false; } -pub fn linkLibrary(self: *CompileStep, lib: *CompileStep) void { +pub fn linkLibrary(self: *Compile, lib: *Compile) void { assert(lib.kind == .lib); self.linkLibraryOrObject(lib); } -pub fn isDynamicLibrary(self: *CompileStep) bool { +pub fn isDynamicLibrary(self: *Compile) bool { return self.kind == .lib and self.linkage == Linkage.dynamic; } -pub fn isStaticLibrary(self: *CompileStep) bool { +pub fn isStaticLibrary(self: *Compile) bool { return self.kind == .lib and self.linkage != Linkage.dynamic; } -pub fn producesPdbFile(self: *CompileStep) bool { +pub fn producesPdbFile(self: *Compile) bool { if (!self.target.isWindows() and !self.target.isUefi()) return false; if (self.target.getObjectFormat() == .c) return false; if (self.strip == true) return false; return self.isDynamicLibrary() or self.kind == .exe or self.kind == .@"test"; } -pub fn linkLibC(self: *CompileStep) void { +pub fn linkLibC(self: *Compile) void { self.is_linking_libc = true; } -pub fn linkLibCpp(self: *CompileStep) void { +pub fn linkLibCpp(self: *Compile) void { self.is_linking_libcpp = true; } /// If the value is omitted, it is set to 1. /// `name` and `value` need not live longer than the function call. -pub fn defineCMacro(self: *CompileStep, name: []const u8, value: ?[]const u8) void { +pub fn defineCMacro(self: *Compile, name: []const u8, value: ?[]const u8) void { const b = self.step.owner; const macro = std.Build.constructCMacro(b.allocator, name, value); self.c_macros.append(macro) catch @panic("OOM"); } /// name_and_value looks like [name]=[value]. If the value is omitted, it is set to 1. -pub fn defineCMacroRaw(self: *CompileStep, name_and_value: []const u8) void { +pub fn defineCMacroRaw(self: *Compile, name_and_value: []const u8) void { const b = self.step.owner; self.c_macros.append(b.dupe(name_and_value)) catch @panic("OOM"); } /// This one has no integration with anything, it just puts -lname on the command line. /// Prefer to use `linkSystemLibrary` instead. -pub fn linkSystemLibraryName(self: *CompileStep, name: []const u8) void { +pub fn linkSystemLibraryName(self: *Compile, name: []const u8) void { const b = self.step.owner; self.link_objects.append(.{ .system_lib = .{ @@ -663,7 +657,7 @@ pub fn linkSystemLibraryName(self: *CompileStep, name: []const u8) void { /// This one has no integration with anything, it just puts -needed-lname on the command line. /// Prefer to use `linkSystemLibraryNeeded` instead. -pub fn linkSystemLibraryNeededName(self: *CompileStep, name: []const u8) void { +pub fn linkSystemLibraryNeededName(self: *Compile, name: []const u8) void { const b = self.step.owner; self.link_objects.append(.{ .system_lib = .{ @@ -677,7 +671,7 @@ pub fn linkSystemLibraryNeededName(self: *CompileStep, name: []const u8) void { /// Darwin-only. This one has no integration with anything, it just puts -weak-lname on the /// command line. Prefer to use `linkSystemLibraryWeak` instead. -pub fn linkSystemLibraryWeakName(self: *CompileStep, name: []const u8) void { +pub fn linkSystemLibraryWeakName(self: *Compile, name: []const u8) void { const b = self.step.owner; self.link_objects.append(.{ .system_lib = .{ @@ -691,7 +685,7 @@ pub fn linkSystemLibraryWeakName(self: *CompileStep, name: []const u8) void { /// This links against a system library, exclusively using pkg-config to find the library. /// Prefer to use `linkSystemLibrary` instead. -pub fn linkSystemLibraryPkgConfigOnly(self: *CompileStep, lib_name: []const u8) void { +pub fn linkSystemLibraryPkgConfigOnly(self: *Compile, lib_name: []const u8) void { const b = self.step.owner; self.link_objects.append(.{ .system_lib = .{ @@ -705,7 +699,7 @@ pub fn linkSystemLibraryPkgConfigOnly(self: *CompileStep, lib_name: []const u8) /// This links against a system library, exclusively using pkg-config to find the library. /// Prefer to use `linkSystemLibraryNeeded` instead. -pub fn linkSystemLibraryNeededPkgConfigOnly(self: *CompileStep, lib_name: []const u8) void { +pub fn linkSystemLibraryNeededPkgConfigOnly(self: *Compile, lib_name: []const u8) void { const b = self.step.owner; self.link_objects.append(.{ .system_lib = .{ @@ -719,7 +713,7 @@ pub fn linkSystemLibraryNeededPkgConfigOnly(self: *CompileStep, lib_name: []cons /// Run pkg-config for the given library name and parse the output, returning the arguments /// that should be passed to zig to link the given library. -fn runPkgConfig(self: *CompileStep, lib_name: []const u8) ![]const []const u8 { +fn runPkgConfig(self: *Compile, lib_name: []const u8) ![]const []const u8 { const b = self.step.owner; const pkg_name = match: { // First we have to map the library name to pkg config name. Unfortunately, @@ -813,19 +807,19 @@ fn runPkgConfig(self: *CompileStep, lib_name: []const u8) ![]const []const u8 { return zig_args.toOwnedSlice(); } -pub fn linkSystemLibrary(self: *CompileStep, name: []const u8) void { +pub fn linkSystemLibrary(self: *Compile, name: []const u8) void { self.linkSystemLibraryInner(name, .{}); } -pub fn linkSystemLibraryNeeded(self: *CompileStep, name: []const u8) void { +pub fn linkSystemLibraryNeeded(self: *Compile, name: []const u8) void { self.linkSystemLibraryInner(name, .{ .needed = true }); } -pub fn linkSystemLibraryWeak(self: *CompileStep, name: []const u8) void { +pub fn linkSystemLibraryWeak(self: *Compile, name: []const u8) void { self.linkSystemLibraryInner(name, .{ .weak = true }); } -fn linkSystemLibraryInner(self: *CompileStep, name: []const u8, opts: struct { +fn linkSystemLibraryInner(self: *Compile, name: []const u8, opts: struct { needed: bool = false, weak: bool = false, }) void { @@ -850,7 +844,7 @@ fn linkSystemLibraryInner(self: *CompileStep, name: []const u8, opts: struct { } /// Handy when you have many C/C++ source files and want them all to have the same flags. -pub fn addCSourceFiles(self: *CompileStep, files: []const []const u8, flags: []const []const u8) void { +pub fn addCSourceFiles(self: *Compile, files: []const []const u8, flags: []const []const u8) void { const b = self.step.owner; const c_source_files = b.allocator.create(CSourceFiles) catch @panic("OOM"); @@ -864,14 +858,14 @@ pub fn addCSourceFiles(self: *CompileStep, files: []const []const u8, flags: []c self.link_objects.append(.{ .c_source_files = c_source_files }) catch @panic("OOM"); } -pub fn addCSourceFile(self: *CompileStep, file: []const u8, flags: []const []const u8) void { +pub fn addCSourceFile(self: *Compile, file: []const u8, flags: []const []const u8) void { self.addCSourceFileSource(.{ .args = flags, .source = .{ .path = file }, }); } -pub fn addCSourceFileSource(self: *CompileStep, source: CSourceFile) void { +pub fn addCSourceFileSource(self: *Compile, source: CSourceFile) void { const b = self.step.owner; const c_source_file = b.allocator.create(CSourceFile) catch @panic("OOM"); c_source_file.* = source.dupe(b); @@ -879,85 +873,85 @@ pub fn addCSourceFileSource(self: *CompileStep, source: CSourceFile) void { source.source.addStepDependencies(&self.step); } -pub fn setVerboseLink(self: *CompileStep, value: bool) void { +pub fn setVerboseLink(self: *Compile, value: bool) void { self.verbose_link = value; } -pub fn setVerboseCC(self: *CompileStep, value: bool) void { +pub fn setVerboseCC(self: *Compile, value: bool) void { self.verbose_cc = value; } -pub fn overrideZigLibDir(self: *CompileStep, dir_path: []const u8) void { +pub fn overrideZigLibDir(self: *Compile, dir_path: []const u8) void { const b = self.step.owner; self.zig_lib_dir = b.dupePath(dir_path); } -pub fn setMainPkgPath(self: *CompileStep, dir_path: []const u8) void { +pub fn setMainPkgPath(self: *Compile, dir_path: []const u8) void { const b = self.step.owner; self.main_pkg_path = b.dupePath(dir_path); } -pub fn setLibCFile(self: *CompileStep, libc_file: ?FileSource) void { +pub fn setLibCFile(self: *Compile, libc_file: ?FileSource) void { const b = self.step.owner; self.libc_file = if (libc_file) |f| f.dupe(b) else null; } /// Returns the generated executable, library or object file. /// To run an executable built with zig build, use `run`, or create an install step and invoke it. -pub fn getOutputSource(self: *CompileStep) FileSource { +pub fn getOutputSource(self: *Compile) FileSource { return .{ .generated = &self.output_path_source }; } -pub fn getOutputDirectorySource(self: *CompileStep) FileSource { +pub fn getOutputDirectorySource(self: *Compile) FileSource { return .{ .generated = &self.output_dirname_source }; } /// Returns the generated import library. This function can only be called for libraries. -pub fn getOutputLibSource(self: *CompileStep) FileSource { +pub fn getOutputLibSource(self: *Compile) FileSource { assert(self.kind == .lib); return .{ .generated = &self.output_lib_path_source }; } /// Returns the generated header file. /// This function can only be called for libraries or object files which have `emit_h` set. -pub fn getOutputHSource(self: *CompileStep) FileSource { +pub fn getOutputHSource(self: *Compile) FileSource { assert(self.kind != .exe and self.kind != .@"test"); assert(self.emit_h); return .{ .generated = &self.output_h_path_source }; } /// Returns the generated PDB file. This function can only be called for Windows and UEFI. -pub fn getOutputPdbSource(self: *CompileStep) FileSource { +pub fn getOutputPdbSource(self: *Compile) FileSource { // TODO: Is this right? Isn't PDB for *any* PE/COFF file? assert(self.target.isWindows() or self.target.isUefi()); return .{ .generated = &self.output_pdb_path_source }; } -pub fn addAssemblyFile(self: *CompileStep, path: []const u8) void { +pub fn addAssemblyFile(self: *Compile, path: []const u8) void { const b = self.step.owner; self.link_objects.append(.{ .assembly_file = .{ .path = b.dupe(path) }, }) catch @panic("OOM"); } -pub fn addAssemblyFileSource(self: *CompileStep, source: FileSource) void { +pub fn addAssemblyFileSource(self: *Compile, source: FileSource) void { const b = self.step.owner; const source_duped = source.dupe(b); self.link_objects.append(.{ .assembly_file = source_duped }) catch @panic("OOM"); source_duped.addStepDependencies(&self.step); } -pub fn addObjectFile(self: *CompileStep, source_file: []const u8) void { +pub fn addObjectFile(self: *Compile, source_file: []const u8) void { self.addObjectFileSource(.{ .path = source_file }); } -pub fn addObjectFileSource(self: *CompileStep, source: FileSource) void { +pub fn addObjectFileSource(self: *Compile, source: FileSource) void { const b = self.step.owner; self.link_objects.append(.{ .static_path = source.dupe(b) }) catch @panic("OOM"); source.addStepDependencies(&self.step); } -pub fn addObject(self: *CompileStep, obj: *CompileStep) void { +pub fn addObject(self: *Compile, obj: *Compile) void { assert(obj.kind == .obj); self.linkLibraryOrObject(obj); } @@ -967,54 +961,54 @@ pub const addIncludeDir = @compileError("deprecated; use addIncludePath"); pub const addLibPath = @compileError("deprecated, use addLibraryPath"); pub const addFrameworkDir = @compileError("deprecated, use addFrameworkPath"); -pub fn addSystemIncludePath(self: *CompileStep, path: []const u8) void { +pub fn addSystemIncludePath(self: *Compile, path: []const u8) void { const b = self.step.owner; self.include_dirs.append(IncludeDir{ .raw_path_system = b.dupe(path) }) catch @panic("OOM"); } -pub fn addIncludePath(self: *CompileStep, path: []const u8) void { +pub fn addIncludePath(self: *Compile, path: []const u8) void { const b = self.step.owner; self.include_dirs.append(IncludeDir{ .raw_path = b.dupe(path) }) catch @panic("OOM"); } -pub fn addConfigHeader(self: *CompileStep, config_header: *ConfigHeaderStep) void { +pub fn addConfigHeader(self: *Compile, config_header: *Step.ConfigHeader) void { self.step.dependOn(&config_header.step); self.include_dirs.append(.{ .config_header_step = config_header }) catch @panic("OOM"); } -pub fn addLibraryPath(self: *CompileStep, path: []const u8) void { +pub fn addLibraryPath(self: *Compile, path: []const u8) void { const b = self.step.owner; self.lib_paths.append(.{ .path = b.dupe(path) }) catch @panic("OOM"); } -pub fn addLibraryPathDirectorySource(self: *CompileStep, directory_source: FileSource) void { +pub fn addLibraryPathDirectorySource(self: *Compile, directory_source: FileSource) void { self.lib_paths.append(directory_source) catch @panic("OOM"); directory_source.addStepDependencies(&self.step); } -pub fn addRPath(self: *CompileStep, path: []const u8) void { +pub fn addRPath(self: *Compile, path: []const u8) void { const b = self.step.owner; self.rpaths.append(.{ .path = b.dupe(path) }) catch @panic("OOM"); } -pub fn addRPathDirectorySource(self: *CompileStep, directory_source: FileSource) void { +pub fn addRPathDirectorySource(self: *Compile, directory_source: FileSource) void { self.rpaths.append(directory_source) catch @panic("OOM"); directory_source.addStepDependencies(&self.step); } -pub fn addFrameworkPath(self: *CompileStep, dir_path: []const u8) void { +pub fn addFrameworkPath(self: *Compile, dir_path: []const u8) void { const b = self.step.owner; self.framework_dirs.append(.{ .path = b.dupe(dir_path) }) catch @panic("OOM"); } -pub fn addFrameworkPathDirectorySource(self: *CompileStep, directory_source: FileSource) void { +pub fn addFrameworkPathDirectorySource(self: *Compile, directory_source: FileSource) void { self.framework_dirs.append(directory_source) catch @panic("OOM"); directory_source.addStepDependencies(&self.step); } /// Adds a module to be used with `@import` and exposing it in the current /// package's module table using `name`. -pub fn addModule(cs: *CompileStep, name: []const u8, module: *Module) void { +pub fn addModule(cs: *Compile, name: []const u8, module: *Module) void { const b = cs.step.owner; cs.modules.put(b.dupe(name), module) catch @panic("OOM"); @@ -1025,17 +1019,17 @@ pub fn addModule(cs: *CompileStep, name: []const u8, module: *Module) void { /// Adds a module to be used with `@import` without exposing it in the current /// package's module table. -pub fn addAnonymousModule(cs: *CompileStep, name: []const u8, options: std.Build.CreateModuleOptions) void { +pub fn addAnonymousModule(cs: *Compile, name: []const u8, options: std.Build.CreateModuleOptions) void { const b = cs.step.owner; const module = b.createModule(options); return addModule(cs, name, module); } -pub fn addOptions(cs: *CompileStep, module_name: []const u8, options: *OptionsStep) void { +pub fn addOptions(cs: *Compile, module_name: []const u8, options: *Step.Options) void { addModule(cs, module_name, options.createModule()); } -fn addRecursiveBuildDeps(cs: *CompileStep, module: *Module, done: *std.AutoHashMap(*Module, void)) !void { +fn addRecursiveBuildDeps(cs: *Compile, module: *Module, done: *std.AutoHashMap(*Module, void)) !void { if (done.contains(module)) return; try done.put(module, {}); module.source_file.addStepDependencies(&cs.step); @@ -1046,7 +1040,7 @@ fn addRecursiveBuildDeps(cs: *CompileStep, module: *Module, done: *std.AutoHashM /// If Vcpkg was found on the system, it will be added to include and lib /// paths for the specified target. -pub fn addVcpkgPaths(self: *CompileStep, linkage: CompileStep.Linkage) !void { +pub fn addVcpkgPaths(self: *Compile, linkage: Compile.Linkage) !void { const b = self.step.owner; // Ideally in the Unattempted case we would call the function recursively // after findVcpkgRoot and have only one switch statement, but the compiler @@ -1082,7 +1076,7 @@ pub fn addVcpkgPaths(self: *CompileStep, linkage: CompileStep.Linkage) !void { } } -pub fn setExecCmd(self: *CompileStep, args: []const ?[]const u8) void { +pub fn setExecCmd(self: *Compile, args: []const ?[]const u8) void { const b = self.step.owner; assert(self.kind == .@"test"); const duped_args = b.allocator.alloc(?[]u8, args.len) catch @panic("OOM"); @@ -1092,7 +1086,7 @@ pub fn setExecCmd(self: *CompileStep, args: []const ?[]const u8) void { self.exec_cmd_args = duped_args; } -fn linkLibraryOrObject(self: *CompileStep, other: *CompileStep) void { +fn linkLibraryOrObject(self: *Compile, other: *Compile) void { self.step.dependOn(&other.step); self.link_objects.append(.{ .other_step = other }) catch @panic("OOM"); self.include_dirs.append(.{ .other_step = other }) catch @panic("OOM"); @@ -1103,7 +1097,7 @@ fn linkLibraryOrObject(self: *CompileStep, other: *CompileStep) void { } fn appendModuleArgs( - cs: *CompileStep, + cs: *Compile, zig_args: *ArrayList([]const u8), ) error{OutOfMemory}!void { const b = cs.step.owner; @@ -1214,7 +1208,7 @@ fn constructDepString( fn make(step: *Step, prog_node: *std.Progress.Node) !void { const b = step.owner; - const self = @fieldParentPtr(CompileStep, "step", step); + const self = @fieldParentPtr(Compile, "step", step); if (self.root_src == null and self.link_objects.items.len == 0) { return step.fail("the linker needs one or more objects to link", .{}); @@ -2088,7 +2082,7 @@ const TransitiveDeps = struct { } } - fn addInner(td: *TransitiveDeps, other: *CompileStep, dyn: bool) !void { + fn addInner(td: *TransitiveDeps, other: *Compile, dyn: bool) !void { // Inherit dependency on libc and libc++ td.is_linking_libcpp = td.is_linking_libcpp or other.is_linking_libcpp; td.is_linking_libc = td.is_linking_libc or other.is_linking_libc; @@ -2128,7 +2122,7 @@ const TransitiveDeps = struct { } }; -fn checkCompileErrors(self: *CompileStep) !void { +fn checkCompileErrors(self: *Compile) !void { // Clear this field so that it does not get printed by the build runner. const actual_eb = self.step.result_error_bundle; self.step.result_error_bundle = std.zig.ErrorBundle.empty; diff --git a/lib/std/Build/Step/ConfigHeader.zig b/lib/std/Build/Step/ConfigHeader.zig index 6bfe28ae62..a17784c96a 100644 --- a/lib/std/Build/Step/ConfigHeader.zig +++ b/lib/std/Build/Step/ConfigHeader.zig @@ -1,5 +1,5 @@ const std = @import("std"); -const ConfigHeaderStep = @This(); +const ConfigHeader = @This(); const Step = std.Build.Step; pub const Style = union(enum) { @@ -48,8 +48,8 @@ pub const Options = struct { first_ret_addr: ?usize = null, }; -pub fn create(owner: *std.Build, options: Options) *ConfigHeaderStep { - const self = owner.allocator.create(ConfigHeaderStep) catch @panic("OOM"); +pub fn create(owner: *std.Build, options: Options) *ConfigHeader { + const self = owner.allocator.create(ConfigHeader) catch @panic("OOM"); var include_path: []const u8 = "config.h"; @@ -93,21 +93,21 @@ pub fn create(owner: *std.Build, options: Options) *ConfigHeaderStep { return self; } -pub fn addValues(self: *ConfigHeaderStep, values: anytype) void { +pub fn addValues(self: *ConfigHeader, values: anytype) void { return addValuesInner(self, values) catch @panic("OOM"); } -pub fn getFileSource(self: *ConfigHeaderStep) std.Build.FileSource { +pub fn getFileSource(self: *ConfigHeader) std.Build.FileSource { return .{ .generated = &self.output_file }; } -fn addValuesInner(self: *ConfigHeaderStep, values: anytype) !void { +fn addValuesInner(self: *ConfigHeader, values: anytype) !void { inline for (@typeInfo(@TypeOf(values)).Struct.fields) |field| { try putValue(self, field.name, field.type, @field(values, field.name)); } } -fn putValue(self: *ConfigHeaderStep, field_name: []const u8, comptime T: type, v: T) !void { +fn putValue(self: *ConfigHeader, field_name: []const u8, comptime T: type, v: T) !void { switch (@typeInfo(T)) { .Null => { try self.values.put(field_name, .undef); @@ -151,31 +151,31 @@ fn putValue(self: *ConfigHeaderStep, field_name: []const u8, comptime T: type, v else => {}, } - @compileError("unsupported ConfigHeaderStep value type: " ++ @typeName(T)); + @compileError("unsupported ConfigHeader value type: " ++ @typeName(T)); }, - else => @compileError("unsupported ConfigHeaderStep value type: " ++ @typeName(T)), + else => @compileError("unsupported ConfigHeader value type: " ++ @typeName(T)), } } fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; - const self = @fieldParentPtr(ConfigHeaderStep, "step", step); + const self = @fieldParentPtr(ConfigHeader, "step", step); const gpa = b.allocator; const arena = b.allocator; var man = b.cache.obtain(); defer man.deinit(); - // Random bytes to make ConfigHeaderStep unique. Refresh this with new - // random bytes when ConfigHeaderStep implementation is modified in a + // Random bytes to make ConfigHeader unique. Refresh this with new + // random bytes when ConfigHeader implementation is modified in a // non-backwards-compatible way. man.hash.add(@as(u32, 0xdef08d23)); var output = std.ArrayList(u8).init(gpa); defer output.deinit(); - const header_text = "This file was generated by ConfigHeaderStep using the Zig Build System."; + const header_text = "This file was generated by ConfigHeader using the Zig Build System."; const c_generated_line = "/* " ++ header_text ++ " */\n"; const asm_generated_line = "; " ++ header_text ++ "\n"; diff --git a/lib/std/Build/Step/Fmt.zig b/lib/std/Build/Step/Fmt.zig index 23d5d9e3ff..8e8cc51c0d 100644 --- a/lib/std/Build/Step/Fmt.zig +++ b/lib/std/Build/Step/Fmt.zig @@ -3,7 +3,7 @@ //! * Check mode: fail the step if a non-conforming file is found. const std = @import("std"); const Step = std.Build.Step; -const FmtStep = @This(); +const Fmt = @This(); step: Step, paths: []const []const u8, @@ -19,8 +19,8 @@ pub const Options = struct { check: bool = false, }; -pub fn create(owner: *std.Build, options: Options) *FmtStep { - const self = owner.allocator.create(FmtStep) catch @panic("OOM"); +pub fn create(owner: *std.Build, options: Options) *Fmt { + const self = owner.allocator.create(Fmt) catch @panic("OOM"); const name = if (options.check) "zig fmt --check" else "zig fmt"; self.* = .{ .step = Step.init(.{ @@ -47,7 +47,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { const b = step.owner; const arena = b.allocator; - const self = @fieldParentPtr(FmtStep, "step", step); + const self = @fieldParentPtr(Fmt, "step", step); var argv: std.ArrayListUnmanaged([]const u8) = .{}; try argv.ensureUnusedCapacity(arena, 2 + 1 + self.paths.len + 2 * self.exclude_paths.len); diff --git a/lib/std/Build/Step/InstallArtifact.zig b/lib/std/Build/Step/InstallArtifact.zig index fa357a9ae9..9552a44440 100644 --- a/lib/std/Build/Step/InstallArtifact.zig +++ b/lib/std/Build/Step/InstallArtifact.zig @@ -1,24 +1,23 @@ const std = @import("std"); const Step = std.Build.Step; -const CompileStep = std.Build.CompileStep; const InstallDir = std.Build.InstallDir; -const InstallArtifactStep = @This(); +const InstallArtifact = @This(); const fs = std.fs; pub const base_id = .install_artifact; step: Step, -artifact: *CompileStep, +artifact: *Step.Compile, dest_dir: InstallDir, pdb_dir: ?InstallDir, h_dir: ?InstallDir, /// If non-null, adds additional path components relative to dest_dir, and -/// overrides the basename of the CompileStep. +/// overrides the basename of the Compile step. dest_sub_path: ?[]const u8, -pub fn create(owner: *std.Build, artifact: *CompileStep) *InstallArtifactStep { - const self = owner.allocator.create(InstallArtifactStep) catch @panic("OOM"); - self.* = InstallArtifactStep{ +pub fn create(owner: *std.Build, artifact: *Step.Compile) *InstallArtifact { + const self = owner.allocator.create(InstallArtifact) catch @panic("OOM"); + self.* = InstallArtifact{ .step = Step.init(.{ .id = base_id, .name = owner.fmt("install {s}", .{artifact.name}), @@ -66,7 +65,7 @@ pub fn create(owner: *std.Build, artifact: *CompileStep) *InstallArtifactStep { fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; - const self = @fieldParentPtr(InstallArtifactStep, "step", step); + const self = @fieldParentPtr(InstallArtifact, "step", step); const src_builder = self.artifact.step.owner; const dest_builder = step.owner; @@ -90,7 +89,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { self.artifact.version != null and self.artifact.target.wantSharedLibSymLinks()) { - try CompileStep.doAtomicSymLinks(step, full_dest_path, self.artifact.major_only_filename.?, self.artifact.name_only_filename.?); + try Step.Compile.doAtomicSymLinks(step, full_dest_path, self.artifact.major_only_filename.?, self.artifact.name_only_filename.?); } if (self.artifact.isDynamicLibrary() and self.artifact.target.isWindows() and diff --git a/lib/std/Build/Step/InstallFile.zig b/lib/std/Build/Step/InstallFile.zig index b6b66fd1e0..784685dc3a 100644 --- a/lib/std/Build/Step/InstallFile.zig +++ b/lib/std/Build/Step/InstallFile.zig @@ -2,7 +2,7 @@ const std = @import("std"); const Step = std.Build.Step; const FileSource = std.Build.FileSource; const InstallDir = std.Build.InstallDir; -const InstallFileStep = @This(); +const InstallFile = @This(); const assert = std.debug.assert; pub const base_id = .install_file; @@ -20,10 +20,10 @@ pub fn create( source: FileSource, dir: InstallDir, dest_rel_path: []const u8, -) *InstallFileStep { +) *InstallFile { assert(dest_rel_path.len != 0); owner.pushInstalledFile(dir, dest_rel_path); - const self = owner.allocator.create(InstallFileStep) catch @panic("OOM"); + const self = owner.allocator.create(InstallFile) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = base_id, @@ -43,7 +43,7 @@ pub fn create( fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const src_builder = step.owner; - const self = @fieldParentPtr(InstallFileStep, "step", step); + const self = @fieldParentPtr(InstallFile, "step", step); const dest_builder = self.dest_builder; const full_src_path = self.source.getPath2(src_builder, step); const full_dest_path = dest_builder.getInstallPath(self.dir, self.dest_rel_path); diff --git a/lib/std/Build/Step/ObjCopy.zig b/lib/std/Build/Step/ObjCopy.zig index 608c56591f..a8a0dafaef 100644 --- a/lib/std/Build/Step/ObjCopy.zig +++ b/lib/std/Build/Step/ObjCopy.zig @@ -1,12 +1,11 @@ const std = @import("std"); -const ObjCopyStep = @This(); +const ObjCopy = @This(); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayListUnmanaged = std.ArrayListUnmanaged; const File = std.fs.File; const InstallDir = std.Build.InstallDir; -const CompileStep = std.Build.CompileStep; const Step = std.Build.Step; const elf = std.elf; const fs = std.fs; @@ -40,9 +39,9 @@ pub fn create( owner: *std.Build, file_source: std.Build.FileSource, options: Options, -) *ObjCopyStep { - const self = owner.allocator.create(ObjCopyStep) catch @panic("OOM"); - self.* = ObjCopyStep{ +) *ObjCopy { + const self = owner.allocator.create(ObjCopy) catch @panic("OOM"); + self.* = ObjCopy{ .step = Step.init(.{ .id = base_id, .name = owner.fmt("objcopy {s}", .{file_source.getDisplayName()}), @@ -61,19 +60,19 @@ pub fn create( return self; } -pub fn getOutputSource(self: *const ObjCopyStep) std.Build.FileSource { +pub fn getOutputSource(self: *const ObjCopy) std.Build.FileSource { return .{ .generated = &self.output_file }; } fn make(step: *Step, prog_node: *std.Progress.Node) !void { const b = step.owner; - const self = @fieldParentPtr(ObjCopyStep, "step", step); + const self = @fieldParentPtr(ObjCopy, "step", step); var man = b.cache.obtain(); defer man.deinit(); - // Random bytes to make ObjCopyStep unique. Refresh this with new random - // bytes when ObjCopyStep implementation is modified incompatibly. + // Random bytes to make ObjCopy unique. Refresh this with new random + // bytes when ObjCopy implementation is modified incompatibly. man.hash.add(@as(u32, 0xe18b7baf)); const full_src_path = self.file_source.getPath(b); diff --git a/lib/std/Build/Step/Options.zig b/lib/std/Build/Step/Options.zig index 101c284cf0..cc7152a81e 100644 --- a/lib/std/Build/Step/Options.zig +++ b/lib/std/Build/Step/Options.zig @@ -3,10 +3,9 @@ const builtin = @import("builtin"); const fs = std.fs; const Step = std.Build.Step; const GeneratedFile = std.Build.GeneratedFile; -const CompileStep = std.Build.CompileStep; const FileSource = std.Build.FileSource; -const OptionsStep = @This(); +const Options = @This(); pub const base_id = .options; @@ -17,8 +16,8 @@ contents: std.ArrayList(u8), artifact_args: std.ArrayList(OptionArtifactArg), file_source_args: std.ArrayList(OptionFileSourceArg), -pub fn create(owner: *std.Build) *OptionsStep { - const self = owner.allocator.create(OptionsStep) catch @panic("OOM"); +pub fn create(owner: *std.Build) *Options { + const self = owner.allocator.create(Options) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = base_id, @@ -36,11 +35,11 @@ pub fn create(owner: *std.Build) *OptionsStep { return self; } -pub fn addOption(self: *OptionsStep, comptime T: type, name: []const u8, value: T) void { +pub fn addOption(self: *Options, comptime T: type, name: []const u8, value: T) void { return addOptionFallible(self, T, name, value) catch @panic("unhandled error"); } -fn addOptionFallible(self: *OptionsStep, comptime T: type, name: []const u8, value: T) !void { +fn addOptionFallible(self: *Options, comptime T: type, name: []const u8, value: T) !void { const out = self.contents.writer(); switch (T) { []const []const u8 => { @@ -189,7 +188,7 @@ fn printLiteral(out: anytype, val: anytype, indent: u8) !void { /// The value is the path in the cache dir. /// Adds a dependency automatically. pub fn addOptionFileSource( - self: *OptionsStep, + self: *Options, name: []const u8, source: FileSource, ) void { @@ -202,19 +201,19 @@ pub fn addOptionFileSource( /// The value is the path in the cache dir. /// Adds a dependency automatically. -pub fn addOptionArtifact(self: *OptionsStep, name: []const u8, artifact: *CompileStep) void { +pub fn addOptionArtifact(self: *Options, name: []const u8, artifact: *Step.Compile) void { self.artifact_args.append(.{ .name = self.step.owner.dupe(name), .artifact = artifact }) catch @panic("OOM"); self.step.dependOn(&artifact.step); } -pub fn createModule(self: *OptionsStep) *std.Build.Module { +pub fn createModule(self: *Options) *std.Build.Module { return self.step.owner.createModule(.{ .source_file = self.getSource(), .dependencies = &.{}, }); } -pub fn getSource(self: *OptionsStep) FileSource { +pub fn getSource(self: *Options) FileSource { return .{ .generated = &self.generated_file }; } @@ -223,7 +222,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; - const self = @fieldParentPtr(OptionsStep, "step", step); + const self = @fieldParentPtr(Options, "step", step); for (self.artifact_args.items) |item| { self.addOption( @@ -314,7 +313,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { const OptionArtifactArg = struct { name: []const u8, - artifact: *CompileStep, + artifact: *Step.Compile, }; const OptionFileSourceArg = struct { @@ -322,7 +321,7 @@ const OptionFileSourceArg = struct { source: FileSource, }; -test "OptionsStep" { +test Options { if (builtin.os.tag == .wasi) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); diff --git a/lib/std/Build/Step/RemoveDir.zig b/lib/std/Build/Step/RemoveDir.zig index 59025a7e91..7666dd2a7d 100644 --- a/lib/std/Build/Step/RemoveDir.zig +++ b/lib/std/Build/Step/RemoveDir.zig @@ -1,15 +1,15 @@ const std = @import("std"); const fs = std.fs; const Step = std.Build.Step; -const RemoveDirStep = @This(); +const RemoveDir = @This(); pub const base_id = .remove_dir; step: Step, dir_path: []const u8, -pub fn init(owner: *std.Build, dir_path: []const u8) RemoveDirStep { - return RemoveDirStep{ +pub fn init(owner: *std.Build, dir_path: []const u8) RemoveDir { + return RemoveDir{ .step = Step.init(.{ .id = .remove_dir, .name = owner.fmt("RemoveDir {s}", .{dir_path}), @@ -26,7 +26,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; - const self = @fieldParentPtr(RemoveDirStep, "step", step); + const self = @fieldParentPtr(RemoveDir, "step", step); b.build_root.handle.deleteTree(self.dir_path) catch |err| { if (b.build_root.path) |base| { diff --git a/lib/std/Build/Step/Run.zig b/lib/std/Build/Step/Run.zig index 4e973cfd98..c506e23f90 100644 --- a/lib/std/Build/Step/Run.zig +++ b/lib/std/Build/Step/Run.zig @@ -1,8 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); const Step = std.Build.Step; -const CompileStep = std.Build.CompileStep; -const WriteFileStep = std.Build.WriteFileStep; const fs = std.fs; const mem = std.mem; const process = std.process; @@ -12,7 +10,7 @@ const Allocator = mem.Allocator; const ExecError = std.Build.ExecError; const assert = std.debug.assert; -const RunStep = @This(); +const Run = @This(); pub const base_id: Step.Id = .run; @@ -29,12 +27,12 @@ cwd: ?[]const u8, /// Override this field to modify the environment, or use setEnvironmentVariable env_map: ?*EnvMap, -/// Configures whether the RunStep is considered to have side-effects, and also -/// whether the RunStep will inherit stdio streams, forwarding them to the +/// Configures whether the Run step is considered to have side-effects, and also +/// whether the Run step will inherit stdio streams, forwarding them to the /// parent process, in which case will require a global lock to prevent other /// steps from interfering with stdio while the subprocess associated with this -/// RunStep is running. -/// If the RunStep is determined to not have side-effects, then execution will +/// Run step is running. +/// If the Run step is determined to not have side-effects, then execution will /// be skipped if all output files are up-to-date and input files are /// unchanged. stdio: StdIo = .infer_from_args, @@ -42,9 +40,9 @@ stdio: StdIo = .infer_from_args, stdin: ?[]const u8 = null, /// Additional file paths relative to build.zig that, when modified, indicate -/// that the RunStep should be re-executed. -/// If the RunStep is determined to have side-effects, this field is ignored -/// and the RunStep is always executed when it appears in the build graph. +/// that the Run step should be re-executed. +/// If the Run step is determined to have side-effects, this field is ignored +/// and the Run step is always executed when it appears in the build graph. extra_file_dependencies: []const []const u8 = &.{}, /// After adding an output argument, this step will by default rename itself @@ -52,14 +50,14 @@ extra_file_dependencies: []const []const u8 = &.{}, /// This can be disabled by setting this to false. rename_step_with_output_arg: bool = true, -/// If this is true, a RunStep which is configured to check the output of the +/// If this is true, a Run step which is configured to check the output of the /// executed binary will not fail the build if the binary cannot be executed /// due to being for a foreign binary to the host system which is running the /// build graph. /// Command-line arguments such as -fqemu and -fwasmtime may affect whether a /// binary is detected as foreign, as well as system configuration such as /// Rosetta (macOS) and binfmt_misc (Linux). -/// If this RunStep is considered to have side-effects, then this flag does +/// If this Run step is considered to have side-effects, then this flag does /// nothing. skip_foreign_checks: bool = false, @@ -73,18 +71,18 @@ captured_stderr: ?*Output = null, has_side_effects: bool = false, pub const StdIo = union(enum) { - /// Whether the RunStep has side-effects will be determined by whether or not one + /// Whether the Run step has side-effects will be determined by whether or not one /// of the args is an output file (added with `addOutputFileArg`). - /// If the RunStep is determined to have side-effects, this is the same as `inherit`. + /// If the Run step is determined to have side-effects, this is the same as `inherit`. /// The step will fail if the subprocess crashes or returns a non-zero exit code. infer_from_args, - /// Causes the RunStep to be considered to have side-effects, and therefore + /// Causes the Run step to be considered to have side-effects, and therefore /// always execute when it appears in the build graph. /// It also means that this step will obtain a global lock to prevent other /// steps from running in the meantime. /// The step will fail if the subprocess crashes or returns a non-zero exit code. inherit, - /// Causes the RunStep to be considered to *not* have side-effects. The + /// Causes the Run step to be considered to *not* have side-effects. The /// process will be re-executed if any of the input dependencies are /// modified. The exit code and standard I/O streams will be checked for /// certain conditions, and the step will succeed or fail based on these @@ -92,7 +90,7 @@ pub const StdIo = union(enum) { /// Note that an explicit check for exit code 0 needs to be added to this /// list if such a check is desirable. check: std.ArrayList(Check), - /// This RunStep is running a zig unit test binary and will communicate + /// This Run step is running a zig unit test binary and will communicate /// extra metadata over the IPC protocol. zig_test, @@ -106,7 +104,7 @@ pub const StdIo = union(enum) { }; pub const Arg = union(enum) { - artifact: *CompileStep, + artifact: *Step.Compile, file_source: std.Build.FileSource, directory_source: std.Build.FileSource, bytes: []u8, @@ -119,8 +117,8 @@ pub const Output = struct { basename: []const u8, }; -pub fn create(owner: *std.Build, name: []const u8) *RunStep { - const self = owner.allocator.create(RunStep) catch @panic("OOM"); +pub fn create(owner: *std.Build, name: []const u8) *Run { + const self = owner.allocator.create(Run) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = base_id, @@ -135,17 +133,17 @@ pub fn create(owner: *std.Build, name: []const u8) *RunStep { return self; } -pub fn setName(self: *RunStep, name: []const u8) void { +pub fn setName(self: *Run, name: []const u8) void { self.step.name = name; self.rename_step_with_output_arg = false; } -pub fn enableTestRunnerMode(rs: *RunStep) void { +pub fn enableTestRunnerMode(rs: *Run) void { rs.stdio = .zig_test; rs.addArgs(&.{"--listen=-"}); } -pub fn addArtifactArg(self: *RunStep, artifact: *CompileStep) void { +pub fn addArtifactArg(self: *Run, artifact: *Step.Compile) void { self.argv.append(Arg{ .artifact = artifact }) catch @panic("OOM"); self.step.dependOn(&artifact.step); } @@ -153,12 +151,12 @@ pub fn addArtifactArg(self: *RunStep, artifact: *CompileStep) void { /// This provides file path as a command line argument to the command being /// run, and returns a FileSource which can be used as inputs to other APIs /// throughout the build system. -pub fn addOutputFileArg(rs: *RunStep, basename: []const u8) std.Build.FileSource { +pub fn addOutputFileArg(rs: *Run, basename: []const u8) std.Build.FileSource { return addPrefixedOutputFileArg(rs, "", basename); } pub fn addPrefixedOutputFileArg( - rs: *RunStep, + rs: *Run, prefix: []const u8, basename: []const u8, ) std.Build.FileSource { @@ -179,38 +177,38 @@ pub fn addPrefixedOutputFileArg( return .{ .generated = &output.generated_file }; } -pub fn addFileSourceArg(self: *RunStep, file_source: std.Build.FileSource) void { +pub fn addFileSourceArg(self: *Run, file_source: std.Build.FileSource) void { self.argv.append(.{ .file_source = file_source.dupe(self.step.owner), }) catch @panic("OOM"); file_source.addStepDependencies(&self.step); } -pub fn addDirectorySourceArg(self: *RunStep, directory_source: std.Build.FileSource) void { +pub fn addDirectorySourceArg(self: *Run, directory_source: std.Build.FileSource) void { self.argv.append(.{ .directory_source = directory_source.dupe(self.step.owner), }) catch @panic("OOM"); directory_source.addStepDependencies(&self.step); } -pub fn addArg(self: *RunStep, arg: []const u8) void { +pub fn addArg(self: *Run, arg: []const u8) void { self.argv.append(.{ .bytes = self.step.owner.dupe(arg) }) catch @panic("OOM"); } -pub fn addArgs(self: *RunStep, args: []const []const u8) void { +pub fn addArgs(self: *Run, args: []const []const u8) void { for (args) |arg| { self.addArg(arg); } } -pub fn clearEnvironment(self: *RunStep) void { +pub fn clearEnvironment(self: *Run) void { const b = self.step.owner; const new_env_map = b.allocator.create(EnvMap) catch @panic("OOM"); new_env_map.* = EnvMap.init(b.allocator); self.env_map = new_env_map; } -pub fn addPathDir(self: *RunStep, search_path: []const u8) void { +pub fn addPathDir(self: *Run, search_path: []const u8) void { const b = self.step.owner; const env_map = getEnvMapInternal(self); @@ -225,11 +223,11 @@ pub fn addPathDir(self: *RunStep, search_path: []const u8) void { } } -pub fn getEnvMap(self: *RunStep) *EnvMap { +pub fn getEnvMap(self: *Run) *EnvMap { return getEnvMapInternal(self); } -fn getEnvMapInternal(self: *RunStep) *EnvMap { +fn getEnvMapInternal(self: *Run) *EnvMap { const arena = self.step.owner.allocator; return self.env_map orelse { const env_map = arena.create(EnvMap) catch @panic("OOM"); @@ -239,25 +237,25 @@ fn getEnvMapInternal(self: *RunStep) *EnvMap { }; } -pub fn setEnvironmentVariable(self: *RunStep, key: []const u8, value: []const u8) void { +pub fn setEnvironmentVariable(self: *Run, key: []const u8, value: []const u8) void { const b = self.step.owner; const env_map = self.getEnvMap(); env_map.put(b.dupe(key), b.dupe(value)) catch @panic("unhandled error"); } -pub fn removeEnvironmentVariable(self: *RunStep, key: []const u8) void { +pub fn removeEnvironmentVariable(self: *Run, key: []const u8) void { self.getEnvMap().remove(key); } /// Adds a check for exact stderr match. Does not add any other checks. -pub fn expectStdErrEqual(self: *RunStep, bytes: []const u8) void { +pub fn expectStdErrEqual(self: *Run, bytes: []const u8) void { const new_check: StdIo.Check = .{ .expect_stderr_exact = self.step.owner.dupe(bytes) }; self.addCheck(new_check); } /// Adds a check for exact stdout match as well as a check for exit code 0, if /// there is not already an expected termination check. -pub fn expectStdOutEqual(self: *RunStep, bytes: []const u8) void { +pub fn expectStdOutEqual(self: *Run, bytes: []const u8) void { const new_check: StdIo.Check = .{ .expect_stdout_exact = self.step.owner.dupe(bytes) }; self.addCheck(new_check); if (!self.hasTermCheck()) { @@ -265,12 +263,12 @@ pub fn expectStdOutEqual(self: *RunStep, bytes: []const u8) void { } } -pub fn expectExitCode(self: *RunStep, code: u8) void { +pub fn expectExitCode(self: *Run, code: u8) void { const new_check: StdIo.Check = .{ .expect_term = .{ .Exited = code } }; self.addCheck(new_check); } -pub fn hasTermCheck(self: RunStep) bool { +pub fn hasTermCheck(self: Run) bool { for (self.stdio.check.items) |check| switch (check) { .expect_term => return true, else => continue, @@ -278,18 +276,18 @@ pub fn hasTermCheck(self: RunStep) bool { return false; } -pub fn addCheck(self: *RunStep, new_check: StdIo.Check) void { +pub fn addCheck(self: *Run, new_check: StdIo.Check) void { switch (self.stdio) { .infer_from_args => { self.stdio = .{ .check = std.ArrayList(StdIo.Check).init(self.step.owner.allocator) }; self.stdio.check.append(new_check) catch @panic("OOM"); }, .check => |*checks| checks.append(new_check) catch @panic("OOM"), - else => @panic("illegal call to addCheck: conflicting helper method calls. Suggest to directly set stdio field of RunStep instead"), + else => @panic("illegal call to addCheck: conflicting helper method calls. Suggest to directly set stdio field of Run instead"), } } -pub fn captureStdErr(self: *RunStep) std.Build.FileSource { +pub fn captureStdErr(self: *Run) std.Build.FileSource { assert(self.stdio != .inherit); if (self.captured_stderr) |output| return .{ .generated = &output.generated_file }; @@ -304,7 +302,7 @@ pub fn captureStdErr(self: *RunStep) std.Build.FileSource { return .{ .generated = &output.generated_file }; } -pub fn captureStdOut(self: *RunStep) std.Build.FileSource { +pub fn captureStdOut(self: *Run) std.Build.FileSource { assert(self.stdio != .inherit); if (self.captured_stdout) |output| return .{ .generated = &output.generated_file }; @@ -319,8 +317,8 @@ pub fn captureStdOut(self: *RunStep) std.Build.FileSource { return .{ .generated = &output.generated_file }; } -/// Returns whether the RunStep has side effects *other than* updating the output arguments. -fn hasSideEffects(self: RunStep) bool { +/// Returns whether the Run step has side effects *other than* updating the output arguments. +fn hasSideEffects(self: Run) bool { if (self.has_side_effects) return true; return switch (self.stdio) { .infer_from_args => !self.hasAnyOutputArgs(), @@ -330,7 +328,7 @@ fn hasSideEffects(self: RunStep) bool { }; } -fn hasAnyOutputArgs(self: RunStep) bool { +fn hasAnyOutputArgs(self: Run) bool { if (self.captured_stdout != null) return true; if (self.captured_stderr != null) return true; for (self.argv.items) |arg| switch (arg) { @@ -371,7 +369,7 @@ fn checksContainStderr(checks: []const StdIo.Check) bool { fn make(step: *Step, prog_node: *std.Progress.Node) !void { const b = step.owner; const arena = b.allocator; - const self = @fieldParentPtr(RunStep, "step", step); + const self = @fieldParentPtr(Run, "step", step); const has_side_effects = self.hasSideEffects(); var argv_list = ArrayList([]const u8).init(arena); @@ -541,7 +539,7 @@ fn termMatches(expected: ?std.process.Child.Term, actual: std.process.Child.Term } fn runCommand( - self: *RunStep, + self: *Run, argv: []const []const u8, has_side_effects: bool, digest: ?*const [std.Build.Cache.hex_digest_len]u8, @@ -567,7 +565,7 @@ fn runCommand( // FileNotFound: can happen with a wrong dynamic linker path if (err == error.InvalidExe or err == error.FileNotFound) interpret: { // TODO: learn the target from the binary directly rather than from - // relying on it being a CompileStep. This will make this logic + // relying on it being a Compile step. This will make this logic // work even for the edge case that the binary was produced by a // third party. const exe = switch (self.argv.items[0]) { @@ -862,7 +860,7 @@ const ChildProcResult = struct { }; fn spawnChildAndCollect( - self: *RunStep, + self: *Run, argv: []const []const u8, has_side_effects: bool, prog_node: *std.Progress.Node, @@ -936,7 +934,7 @@ const StdIoResult = struct { }; fn evalZigTest( - self: *RunStep, + self: *Run, child: *std.process.Child, prog_node: *std.Progress.Node, ) !StdIoResult { @@ -1121,7 +1119,7 @@ fn sendRunTestMessage(file: std.fs.File, index: u32) !void { try file.writeAll(full_msg); } -fn evalGeneric(self: *RunStep, child: *std.process.Child) !StdIoResult { +fn evalGeneric(self: *Run, child: *std.process.Child) !StdIoResult { const arena = self.step.owner.allocator; if (self.stdin) |stdin| { @@ -1188,7 +1186,7 @@ fn evalGeneric(self: *RunStep, child: *std.process.Child) !StdIoResult { }; } -fn addPathForDynLibs(self: *RunStep, artifact: *CompileStep) void { +fn addPathForDynLibs(self: *Run, artifact: *Step.Compile) void { const b = self.step.owner; for (artifact.link_objects.items) |link_object| { switch (link_object) { @@ -1204,10 +1202,10 @@ fn addPathForDynLibs(self: *RunStep, artifact: *CompileStep) void { } fn failForeign( - self: *RunStep, + self: *Run, suggested_flag: []const u8, argv0: []const u8, - exe: *CompileStep, + exe: *Step.Compile, ) error{ MakeFailed, MakeSkipped, OutOfMemory } { switch (self.stdio) { .check, .zig_test => { diff --git a/lib/std/Build/Step/TranslateC.zig b/lib/std/Build/Step/TranslateC.zig index 86727ea2f0..0c7ddc4720 100644 --- a/lib/std/Build/Step/TranslateC.zig +++ b/lib/std/Build/Step/TranslateC.zig @@ -1,12 +1,10 @@ const std = @import("std"); const Step = std.Build.Step; -const CompileStep = std.Build.CompileStep; -const CheckFileStep = std.Build.CheckFileStep; const fs = std.fs; const mem = std.mem; const CrossTarget = std.zig.CrossTarget; -const TranslateCStep = @This(); +const TranslateC = @This(); pub const base_id = .translate_c; @@ -25,10 +23,10 @@ pub const Options = struct { optimize: std.builtin.OptimizeMode, }; -pub fn create(owner: *std.Build, options: Options) *TranslateCStep { - const self = owner.allocator.create(TranslateCStep) catch @panic("OOM"); +pub fn create(owner: *std.Build, options: Options) *TranslateC { + const self = owner.allocator.create(TranslateC) catch @panic("OOM"); const source = options.source_file.dupe(owner); - self.* = TranslateCStep{ + self.* = TranslateC{ .step = Step.init(.{ .id = .translate_c, .name = "translate-c", @@ -52,11 +50,11 @@ pub const AddExecutableOptions = struct { version: ?std.builtin.Version = null, target: ?CrossTarget = null, optimize: ?std.builtin.Mode = null, - linkage: ?CompileStep.Linkage = null, + linkage: ?Step.Compile.Linkage = null, }; /// Creates a step to build an executable from the translated source. -pub fn addExecutable(self: *TranslateCStep, options: AddExecutableOptions) *CompileStep { +pub fn addExecutable(self: *TranslateC, options: AddExecutableOptions) *Step.Compile { return self.step.owner.addExecutable(.{ .root_source_file = .{ .generated = &self.output_file }, .name = options.name orelse "translated_c", @@ -67,12 +65,12 @@ pub fn addExecutable(self: *TranslateCStep, options: AddExecutableOptions) *Comp }); } -pub fn addIncludeDir(self: *TranslateCStep, include_dir: []const u8) void { +pub fn addIncludeDir(self: *TranslateC, include_dir: []const u8) void { self.include_dirs.append(self.step.owner.dupePath(include_dir)) catch @panic("OOM"); } -pub fn addCheckFile(self: *TranslateCStep, expected_matches: []const []const u8) *CheckFileStep { - return CheckFileStep.create( +pub fn addCheckFile(self: *TranslateC, expected_matches: []const []const u8) *Step.CheckFile { + return Step.CheckFile.create( self.step.owner, .{ .generated = &self.output_file }, .{ .expected_matches = expected_matches }, @@ -81,19 +79,19 @@ pub fn addCheckFile(self: *TranslateCStep, expected_matches: []const []const u8) /// If the value is omitted, it is set to 1. /// `name` and `value` need not live longer than the function call. -pub fn defineCMacro(self: *TranslateCStep, name: []const u8, value: ?[]const u8) void { +pub fn defineCMacro(self: *TranslateC, name: []const u8, value: ?[]const u8) void { const macro = std.Build.constructCMacro(self.step.owner.allocator, name, value); self.c_macros.append(macro) catch @panic("OOM"); } /// name_and_value looks like [name]=[value]. If the value is omitted, it is set to 1. -pub fn defineCMacroRaw(self: *TranslateCStep, name_and_value: []const u8) void { +pub fn defineCMacroRaw(self: *TranslateC, name_and_value: []const u8) void { self.c_macros.append(self.step.owner.dupe(name_and_value)) catch @panic("OOM"); } fn make(step: *Step, prog_node: *std.Progress.Node) !void { const b = step.owner; - const self = @fieldParentPtr(TranslateCStep, "step", step); + const self = @fieldParentPtr(TranslateC, "step", step); var argv_list = std.ArrayList([]const u8).init(b.allocator); try argv_list.append(b.zig_exe); diff --git a/lib/std/Build/Step/WriteFile.zig b/lib/std/Build/Step/WriteFile.zig index 68f7c37c6c..0d817e7430 100644 --- a/lib/std/Build/Step/WriteFile.zig +++ b/lib/std/Build/Step/WriteFile.zig @@ -1,4 +1,4 @@ -//! WriteFileStep is primarily used to create a directory in an appropriate +//! WriteFile is primarily used to create a directory in an appropriate //! location inside the local cache which has a set of files that have either //! been generated during the build, or are copied from the source package. //! @@ -12,7 +12,7 @@ const std = @import("std"); const Step = std.Build.Step; const fs = std.fs; const ArrayList = std.ArrayList; -const WriteFileStep = @This(); +const WriteFile = @This(); step: Step, /// The elements here are pointers because we need stable pointers for the @@ -39,8 +39,8 @@ pub const Contents = union(enum) { copy: std.Build.FileSource, }; -pub fn create(owner: *std.Build) *WriteFileStep { - const wf = owner.allocator.create(WriteFileStep) catch @panic("OOM"); +pub fn create(owner: *std.Build) *WriteFile { + const wf = owner.allocator.create(WriteFile) catch @panic("OOM"); wf.* = .{ .step = Step.init(.{ .id = .write_file, @@ -55,7 +55,7 @@ pub fn create(owner: *std.Build) *WriteFileStep { return wf; } -pub fn add(wf: *WriteFileStep, sub_path: []const u8, bytes: []const u8) void { +pub fn add(wf: *WriteFile, sub_path: []const u8, bytes: []const u8) void { const b = wf.step.owner; const gpa = b.allocator; const file = gpa.create(File) catch @panic("OOM"); @@ -72,11 +72,11 @@ pub fn add(wf: *WriteFileStep, sub_path: []const u8, bytes: []const u8) void { /// Place the file into the generated directory within the local cache, /// along with all the rest of the files added to this step. The parameter /// here is the destination path relative to the local cache directory -/// associated with this WriteFileStep. It may be a basename, or it may +/// associated with this WriteFile. It may be a basename, or it may /// include sub-directories, in which case this step will ensure the /// required sub-path exists. /// This is the option expected to be used most commonly with `addCopyFile`. -pub fn addCopyFile(wf: *WriteFileStep, source: std.Build.FileSource, sub_path: []const u8) void { +pub fn addCopyFile(wf: *WriteFile, source: std.Build.FileSource, sub_path: []const u8) void { const b = wf.step.owner; const gpa = b.allocator; const file = gpa.create(File) catch @panic("OOM"); @@ -97,7 +97,7 @@ pub fn addCopyFile(wf: *WriteFileStep, source: std.Build.FileSource, sub_path: [ /// run by a developer with intent to modify source files and then commit /// those changes to version control. /// A file added this way is not available with `getFileSource`. -pub fn addCopyFileToSource(wf: *WriteFileStep, source: std.Build.FileSource, sub_path: []const u8) void { +pub fn addCopyFileToSource(wf: *WriteFile, source: std.Build.FileSource, sub_path: []const u8) void { const b = wf.step.owner; wf.output_source_files.append(b.allocator, .{ .contents = .{ .copy = source }, @@ -112,7 +112,7 @@ pub fn addCopyFileToSource(wf: *WriteFileStep, source: std.Build.FileSource, sub /// run by a developer with intent to modify source files and then commit /// those changes to version control. /// A file added this way is not available with `getFileSource`. -pub fn addBytesToSource(wf: *WriteFileStep, bytes: []const u8, sub_path: []const u8) void { +pub fn addBytesToSource(wf: *WriteFile, bytes: []const u8, sub_path: []const u8) void { const b = wf.step.owner; wf.output_source_files.append(b.allocator, .{ .contents = .{ .bytes = bytes }, @@ -121,7 +121,7 @@ pub fn addBytesToSource(wf: *WriteFileStep, bytes: []const u8, sub_path: []const } /// Gets a file source for the given sub_path. If the file does not exist, returns `null`. -pub fn getFileSource(wf: *WriteFileStep, sub_path: []const u8) ?std.Build.FileSource { +pub fn getFileSource(wf: *WriteFile, sub_path: []const u8) ?std.Build.FileSource { for (wf.files.items) |file| { if (std.mem.eql(u8, file.sub_path, sub_path)) { return .{ .generated = &file.generated_file }; @@ -131,12 +131,12 @@ pub fn getFileSource(wf: *WriteFileStep, sub_path: []const u8) ?std.Build.FileSo } /// Returns a `FileSource` representing the base directory that contains all the -/// files from this `WriteFileStep`. -pub fn getDirectorySource(wf: *WriteFileStep) std.Build.FileSource { +/// files from this `WriteFile`. +pub fn getDirectorySource(wf: *WriteFile) std.Build.FileSource { return .{ .generated = &wf.generated_directory }; } -fn maybeUpdateName(wf: *WriteFileStep) void { +fn maybeUpdateName(wf: *WriteFile) void { if (wf.files.items.len == 1) { // First time adding a file; update name. if (std.mem.eql(u8, wf.step.name, "WriteFile")) { @@ -148,10 +148,10 @@ fn maybeUpdateName(wf: *WriteFileStep) void { fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; - const wf = @fieldParentPtr(WriteFileStep, "step", step); + const wf = @fieldParentPtr(WriteFile, "step", step); // Writing to source files is kind of an extra capability of this - // WriteFileStep - arguably it should be a different step. But anyway here + // WriteFile - arguably it should be a different step. But anyway here // it is, it happens unconditionally and does not interact with the other // files here. var any_miss = false; @@ -194,14 +194,14 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { // the data to a file would probably be very fast - but as a way to find a canonical // location to put build artifacts. - // If, for example, a hard-coded path was used as the location to put WriteFileStep - // files, then two WriteFileSteps executing in parallel might clobber each other. + // If, for example, a hard-coded path was used as the location to put WriteFile + // files, then two WriteFiles executing in parallel might clobber each other. var man = b.cache.obtain(); defer man.deinit(); - // Random bytes to make WriteFileStep unique. Refresh this with - // new random bytes when WriteFileStep implementation is modified + // Random bytes to make WriteFile unique. Refresh this with + // new random bytes when WriteFile implementation is modified // in a non-backwards-compatible way. man.hash.add(@as(u32, 0xd767ee59)); diff --git a/test/link/macho/dead_strip/build.zig b/test/link/macho/dead_strip/build.zig index 4c739b3d8c..9d00bad9e0 100644 --- a/test/link/macho/dead_strip/build.zig +++ b/test/link/macho/dead_strip/build.zig @@ -42,7 +42,7 @@ fn createScenario( optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, name: []const u8, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const exe = b.addExecutable(.{ .name = name, .optimize = optimize, diff --git a/test/link/macho/dead_strip_dylibs/build.zig b/test/link/macho/dead_strip_dylibs/build.zig index 47e53f853e..ec073e183a 100644 --- a/test/link/macho/dead_strip_dylibs/build.zig +++ b/test/link/macho/dead_strip_dylibs/build.zig @@ -46,7 +46,7 @@ fn createScenario( b: *std.Build, optimize: std.builtin.OptimizeMode, name: []const u8, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const exe = b.addExecutable(.{ .name = name, .optimize = optimize, diff --git a/test/link/macho/headerpad/build.zig b/test/link/macho/headerpad/build.zig index 22cfcc90ec..99edfe72fa 100644 --- a/test/link/macho/headerpad/build.zig +++ b/test/link/macho/headerpad/build.zig @@ -104,7 +104,7 @@ fn simpleExe( b: *std.Build, optimize: std.builtin.OptimizeMode, name: []const u8, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const exe = b.addExecutable(.{ .name = name, .optimize = optimize, diff --git a/test/link/macho/search_strategy/build.zig b/test/link/macho/search_strategy/build.zig index 4777629c8b..853c471969 100644 --- a/test/link/macho/search_strategy/build.zig +++ b/test/link/macho/search_strategy/build.zig @@ -46,7 +46,7 @@ fn createScenario( optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, name: []const u8, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const static = b.addStaticLibrary(.{ .name = name, .optimize = optimize, diff --git a/test/link/macho/unwind_info/build.zig b/test/link/macho/unwind_info/build.zig index 4ace2a4e96..96b5f6cacc 100644 --- a/test/link/macho/unwind_info/build.zig +++ b/test/link/macho/unwind_info/build.zig @@ -65,7 +65,7 @@ fn createScenario( optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, name: []const u8, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const exe = b.addExecutable(.{ .name = name, .optimize = optimize, diff --git a/test/link/macho/uuid/build.zig b/test/link/macho/uuid/build.zig index df58aeacb7..0072825f46 100644 --- a/test/link/macho/uuid/build.zig +++ b/test/link/macho/uuid/build.zig @@ -1,5 +1,4 @@ const std = @import("std"); -const CompileStep = std.Build.CompileStep; const FileSource = std.Build.FileSource; const Step = std.Build.Step; @@ -60,7 +59,7 @@ fn simpleDylib( b: *std.Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, -) *std.Build.CompileStep { +) *std.Build.Step.Compile { const dylib = b.addSharedLibrary(.{ .name = "test", .version = .{ .major = 1, .minor = 0 }, diff --git a/test/src/Cases.zig b/test/src/Cases.zig index 4b023f45b0..0451079a0e 100644 --- a/test/src/Cases.zig +++ b/test/src/Cases.zig @@ -465,7 +465,7 @@ pub fn lowerToBuildSteps( parent_step: *std.Build.Step, opt_test_filter: ?[]const u8, cases_dir_path: []const u8, - incremental_exe: *std.Build.CompileStep, + incremental_exe: *std.Build.Step.Compile, ) void { for (self.incremental_cases.items) |incr_case| { if (opt_test_filter) |test_filter| { diff --git a/test/src/StackTrace.zig b/test/src/StackTrace.zig index c32720a210..0d0b7155e6 100644 --- a/test/src/StackTrace.zig +++ b/test/src/StackTrace.zig @@ -3,7 +3,7 @@ step: *Step, test_index: usize, test_filter: ?[]const u8, optimize_modes: []const OptimizeMode, -check_exe: *std.Build.CompileStep, +check_exe: *std.Build.Step.Compile, const Expect = [@typeInfo(OptimizeMode).Enum.fields.len][]const u8; diff --git a/test/standalone/install_raw_hex/build.zig b/test/standalone/install_raw_hex/build.zig index b34bb01378..c05490a3e5 100644 --- a/test/standalone/install_raw_hex/build.zig +++ b/test/standalone/install_raw_hex/build.zig @@ -1,6 +1,5 @@ const builtin = @import("builtin"); const std = @import("std"); -const CheckFileStep = std.Build.CheckFileStep; pub fn build(b: *std.Build) void { const test_step = b.step("test", "Test it"); diff --git a/test/tests.zig b/test/tests.zig index 7ec1aaaa65..641914aabe 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -1132,7 +1132,7 @@ pub fn addCases( b: *std.Build, parent_step: *Step, opt_test_filter: ?[]const u8, - check_case_exe: *std.Build.CompileStep, + check_case_exe: *std.Build.Step.Compile, ) !void { const arena = b.allocator; const gpa = b.allocator; -- cgit v1.2.3 From 815e53b147a321d0bdb47dc008aa8181f57175ac Mon Sep 17 00:00:00 2001 From: Ryan Liptak Date: Thu, 4 May 2023 18:05:40 -0700 Subject: Update all std.mem.tokenize calls to their appropriate function Everywhere that can now use `tokenizeScalar` should get a nice little performance boost. --- build.zig | 8 ++++---- lib/std/Build.zig | 2 +- lib/std/Build/Cache.zig | 4 ++-- lib/std/Build/Step/CheckObject.zig | 8 ++++---- lib/std/Build/Step/Compile.zig | 6 +++--- lib/std/Build/Step/ConfigHeader.zig | 4 ++-- lib/std/child_process.zig | 4 ++-- lib/std/fs.zig | 2 +- lib/std/fs/path.zig | 26 ++++++++++++------------ lib/std/http/Client.zig | 4 ++-- lib/std/http/Server.zig | 4 ++-- lib/std/net.zig | 6 +++--- lib/std/os.zig | 2 +- lib/std/process.zig | 2 +- lib/std/zig/system/NativePaths.zig | 10 ++++----- lib/std/zig/system/NativeTargetInfo.zig | 4 ++-- src/arch/x86_64/CodeGen.zig | 6 +++--- src/glibc.zig | 2 +- src/libc_installation.zig | 8 ++++---- src/link/Plan9.zig | 2 +- src/print_zir.zig | 2 +- test/behavior/bugs/6456.zig | 2 +- test/src/Cases.zig | 4 ++-- tools/generate_linux_syscalls.zig | 36 ++++++++++++++++----------------- 24 files changed, 79 insertions(+), 79 deletions(-) (limited to 'lib/std/Build/Step/CheckObject.zig') diff --git a/build.zig b/build.zig index 208d06fe1d..21b323df56 100644 --- a/build.zig +++ b/build.zig @@ -284,7 +284,7 @@ pub fn build(b: *std.Build) !void { // That means we also have to rely on stage1 compiled c++ files. We parse config.h to find // the information passed on to us from cmake. if (cfg.cmake_prefix_path.len > 0) { - var it = mem.tokenize(u8, cfg.cmake_prefix_path, ";"); + var it = mem.tokenizeScalar(u8, cfg.cmake_prefix_path, ';'); while (it.next()) |path| { b.addSearchPrefix(path); } @@ -687,7 +687,7 @@ fn addCxxKnownPath( if (!std.process.can_spawn) return error.RequiredLibraryNotFound; const path_padded = b.exec(&.{ ctx.cxx_compiler, b.fmt("-print-file-name={s}", .{objname}) }); - var tokenizer = mem.tokenize(u8, path_padded, "\r\n"); + var tokenizer = mem.tokenizeAny(u8, path_padded, "\r\n"); const path_unpadded = tokenizer.next().?; if (mem.eql(u8, path_unpadded, objname)) { if (errtxt) |msg| { @@ -710,7 +710,7 @@ fn addCxxKnownPath( } fn addCMakeLibraryList(exe: *std.Build.Step.Compile, list: []const u8) void { - var it = mem.tokenize(u8, list, ";"); + var it = mem.tokenizeScalar(u8, list, ';'); while (it.next()) |lib| { if (mem.startsWith(u8, lib, "-l")) { exe.linkSystemLibrary(lib["-l".len..]); @@ -855,7 +855,7 @@ fn parseConfigH(b: *std.Build, config_h_text: []const u8) ?CMakeConfig { // .prefix = ZIG_LLVM_LINK_MODE parsed manually below }; - var lines_it = mem.tokenize(u8, config_h_text, "\r\n"); + var lines_it = mem.tokenizeAny(u8, config_h_text, "\r\n"); while (lines_it.next()) |line| { inline for (mappings) |mapping| { if (mem.startsWith(u8, line, mapping.prefix)) { diff --git a/lib/std/Build.zig b/lib/std/Build.zig index ca55d23937..4ab5db5c70 100644 --- a/lib/std/Build.zig +++ b/lib/std/Build.zig @@ -1358,7 +1358,7 @@ pub fn findProgram(self: *Build, names: []const []const u8, paths: []const []con if (fs.path.isAbsolute(name)) { return name; } - var it = mem.tokenize(u8, PATH, &[_]u8{fs.path.delimiter}); + var it = mem.tokenizeScalar(u8, PATH, fs.path.delimiter); while (it.next()) |path| { const full_path = self.pathJoin(&.{ path, diff --git a/lib/std/Build/Cache.zig b/lib/std/Build/Cache.zig index 17429c0370..7709e5e26c 100644 --- a/lib/std/Build/Cache.zig +++ b/lib/std/Build/Cache.zig @@ -434,7 +434,7 @@ pub const Manifest = struct { const input_file_count = self.files.items.len; var any_file_changed = false; - var line_iter = mem.tokenize(u8, file_contents, "\n"); + var line_iter = mem.tokenizeScalar(u8, file_contents, '\n'); var idx: usize = 0; if (if (line_iter.next()) |line| !std.mem.eql(u8, line, manifest_header) else true) { if (try self.upgradeToExclusiveLock()) continue; @@ -463,7 +463,7 @@ pub const Manifest = struct { break :blk new; }; - var iter = mem.tokenize(u8, line, " "); + var iter = mem.tokenizeScalar(u8, line, ' '); const size = iter.next() orelse return error.InvalidFormat; const inode = iter.next() orelse return error.InvalidFormat; const mtime_nsec_str = iter.next() orelse return error.InvalidFormat; diff --git a/lib/std/Build/Step/CheckObject.zig b/lib/std/Build/Step/CheckObject.zig index c77dc3de36..24ebfef388 100644 --- a/lib/std/Build/Step/CheckObject.zig +++ b/lib/std/Build/Step/CheckObject.zig @@ -103,8 +103,8 @@ const Action = struct { assert(act.tag == .match or act.tag == .not_present); const phrase = act.phrase.resolve(b, step); var candidate_var: ?struct { name: []const u8, value: u64 } = null; - var hay_it = mem.tokenize(u8, mem.trim(u8, haystack, " "), " "); - var needle_it = mem.tokenize(u8, mem.trim(u8, phrase, " "), " "); + var hay_it = mem.tokenizeScalar(u8, mem.trim(u8, haystack, " "), ' '); + var needle_it = mem.tokenizeScalar(u8, mem.trim(u8, phrase, " "), ' '); while (needle_it.next()) |needle_tok| { const hay_tok = hay_it.next() orelse return false; @@ -155,7 +155,7 @@ const Action = struct { var op_stack = std.ArrayList(enum { add, sub, mod, mul }).init(gpa); var values = std.ArrayList(u64).init(gpa); - var it = mem.tokenize(u8, phrase, " "); + var it = mem.tokenizeScalar(u8, phrase, ' '); while (it.next()) |next| { if (mem.eql(u8, next, "+")) { try op_stack.append(.add); @@ -365,7 +365,7 @@ fn make(step: *Step, prog_node: *std.Progress.Node) !void { var vars = std.StringHashMap(u64).init(gpa); for (self.checks.items) |chk| { - var it = mem.tokenize(u8, output, "\r\n"); + var it = mem.tokenizeAny(u8, output, "\r\n"); for (chk.actions.items) |act| { switch (act.tag) { .match => { diff --git a/lib/std/Build/Step/Compile.zig b/lib/std/Build/Step/Compile.zig index 2371f49daf..6a05adc1a6 100644 --- a/lib/std/Build/Step/Compile.zig +++ b/lib/std/Build/Step/Compile.zig @@ -777,7 +777,7 @@ fn runPkgConfig(self: *Compile, lib_name: []const u8) ![]const []const u8 { var zig_args = ArrayList([]const u8).init(b.allocator); defer zig_args.deinit(); - var it = mem.tokenize(u8, stdout, " \r\n\t"); + var it = mem.tokenizeAny(u8, stdout, " \r\n\t"); while (it.next()) |tok| { if (mem.eql(u8, tok, "-I")) { const dir = it.next() orelse return error.PkgConfigInvalidOutput; @@ -2017,10 +2017,10 @@ fn execPkgConfigList(self: *std.Build, out_code: *u8) (PkgConfigError || ExecErr const stdout = try self.execAllowFail(&[_][]const u8{ "pkg-config", "--list-all" }, out_code, .Ignore); var list = ArrayList(PkgConfigPkg).init(self.allocator); errdefer list.deinit(); - var line_it = mem.tokenize(u8, stdout, "\r\n"); + var line_it = mem.tokenizeAny(u8, stdout, "\r\n"); while (line_it.next()) |line| { if (mem.trim(u8, line, " \t").len == 0) continue; - var tok_it = mem.tokenize(u8, line, " \t"); + var tok_it = mem.tokenizeAny(u8, line, " \t"); try list.append(PkgConfigPkg{ .name = tok_it.next() orelse return error.PkgConfigInvalidOutput, .desc = tok_it.rest(), diff --git a/lib/std/Build/Step/ConfigHeader.zig b/lib/std/Build/Step/ConfigHeader.zig index f6939e0e38..cd97367218 100644 --- a/lib/std/Build/Step/ConfigHeader.zig +++ b/lib/std/Build/Step/ConfigHeader.zig @@ -257,7 +257,7 @@ fn render_autoconf( try output.appendSlice("\n"); continue; } - var it = std.mem.tokenize(u8, line[1..], " \t\r"); + var it = std.mem.tokenizeAny(u8, line[1..], " \t\r"); const undef = it.next().?; if (!std.mem.eql(u8, undef, "undef")) { try output.appendSlice(line); @@ -304,7 +304,7 @@ fn render_cmake( try output.appendSlice("\n"); continue; } - var it = std.mem.tokenize(u8, line[1..], " \t\r"); + var it = std.mem.tokenizeAny(u8, line[1..], " \t\r"); const cmakedefine = it.next().?; if (!std.mem.eql(u8, cmakedefine, "cmakedefine") and !std.mem.eql(u8, cmakedefine, "cmakedefine01")) diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig index daaa1689bc..d94f5ea000 100644 --- a/lib/std/child_process.zig +++ b/lib/std/child_process.zig @@ -850,7 +850,7 @@ pub const ChildProcess = struct { return original_err; } - var it = mem.tokenize(u16, PATH, &[_]u16{';'}); + var it = mem.tokenizeScalar(u16, PATH, ';'); while (it.next()) |search_path| { dir_buf.clearRetainingCapacity(); try dir_buf.appendSlice(self.allocator, search_path); @@ -1067,7 +1067,7 @@ fn windowsCreateProcessPathExt( // Now we know that at least *a* file matching the wildcard exists, we can loop // through PATHEXT in order and exec any that exist - var ext_it = mem.tokenize(u16, pathext, &[_]u16{';'}); + var ext_it = mem.tokenizeScalar(u16, pathext, ';'); while (ext_it.next()) |ext| { if (!windowsCreateProcessSupportsExtension(ext)) continue; diff --git a/lib/std/fs.zig b/lib/std/fs.zig index 7327a3a913..5aeea8a4aa 100644 --- a/lib/std/fs.zig +++ b/lib/std/fs.zig @@ -3021,7 +3021,7 @@ pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8 { } else if (argv0.len != 0) { // argv[0] is not empty (and not a path): search it inside PATH const PATH = std.os.getenvZ("PATH") orelse return error.FileNotFound; - var path_it = mem.tokenize(u8, PATH, &[_]u8{path.delimiter}); + var path_it = mem.tokenizeScalar(u8, PATH, path.delimiter); while (path_it.next()) |a_path| { var resolved_path_buf: [MAX_PATH_BYTES - 1:0]u8 = undefined; const resolved_path = std.fmt.bufPrintZ(&resolved_path_buf, "{s}/{s}", .{ diff --git a/lib/std/fs/path.zig b/lib/std/fs/path.zig index 4c320ae5cf..e7a28a7615 100644 --- a/lib/std/fs/path.zig +++ b/lib/std/fs/path.zig @@ -358,7 +358,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { return relative_path; } - var it = mem.tokenize(u8, path, &[_]u8{this_sep}); + var it = mem.tokenizeScalar(u8, path, this_sep); _ = (it.next() orelse return relative_path); _ = (it.next() orelse return relative_path); return WindowsPath{ @@ -420,8 +420,8 @@ fn networkShareServersEql(ns1: []const u8, ns2: []const u8) bool { const sep1 = ns1[0]; const sep2 = ns2[0]; - var it1 = mem.tokenize(u8, ns1, &[_]u8{sep1}); - var it2 = mem.tokenize(u8, ns2, &[_]u8{sep2}); + var it1 = mem.tokenizeScalar(u8, ns1, sep1); + var it2 = mem.tokenizeScalar(u8, ns2, sep2); // TODO ASCII is wrong, we actually need full unicode support to compare paths. return ascii.eqlIgnoreCase(it1.next().?, it2.next().?); @@ -441,8 +441,8 @@ fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8 const sep1 = p1[0]; const sep2 = p2[0]; - var it1 = mem.tokenize(u8, p1, &[_]u8{sep1}); - var it2 = mem.tokenize(u8, p2, &[_]u8{sep2}); + var it1 = mem.tokenizeScalar(u8, p1, sep1); + var it2 = mem.tokenizeScalar(u8, p2, sep2); // TODO ASCII is wrong, we actually need full unicode support to compare paths. return ascii.eqlIgnoreCase(it1.next().?, it2.next().?) and ascii.eqlIgnoreCase(it1.next().?, it2.next().?); @@ -535,7 +535,7 @@ pub fn resolveWindows(allocator: Allocator, paths: []const []const u8) ![]u8 { break :l disk_designator.len; }, .NetworkShare => { - var it = mem.tokenize(u8, paths[first_index], "/\\"); + var it = mem.tokenizeAny(u8, paths[first_index], "/\\"); const server_name = it.next().?; const other_name = it.next().?; @@ -570,7 +570,7 @@ pub fn resolveWindows(allocator: Allocator, paths: []const []const u8) ![]u8 { if (!correct_disk_designator) { continue; } - var it = mem.tokenize(u8, p[parsed.disk_designator.len..], "/\\"); + var it = mem.tokenizeAny(u8, p[parsed.disk_designator.len..], "/\\"); while (it.next()) |component| { if (mem.eql(u8, component, ".")) { continue; @@ -657,7 +657,7 @@ pub fn resolvePosix(allocator: Allocator, paths: []const []const u8) Allocator.E negative_count = 0; result.clearRetainingCapacity(); } - var it = mem.tokenize(u8, p, "/"); + var it = mem.tokenizeScalar(u8, p, '/'); while (it.next()) |component| { if (mem.eql(u8, component, ".")) { continue; @@ -1078,8 +1078,8 @@ pub fn relativeWindows(allocator: Allocator, from: []const u8, to: []const u8) ! return resolved_to; } - var from_it = mem.tokenize(u8, resolved_from, "/\\"); - var to_it = mem.tokenize(u8, resolved_to, "/\\"); + var from_it = mem.tokenizeAny(u8, resolved_from, "/\\"); + var to_it = mem.tokenizeAny(u8, resolved_to, "/\\"); while (true) { const from_component = from_it.next() orelse return allocator.dupe(u8, to_it.rest()); const to_rest = to_it.rest(); @@ -1102,7 +1102,7 @@ pub fn relativeWindows(allocator: Allocator, from: []const u8, to: []const u8) ! result_index += 3; } - var rest_it = mem.tokenize(u8, to_rest, "/\\"); + var rest_it = mem.tokenizeAny(u8, to_rest, "/\\"); while (rest_it.next()) |to_component| { result[result_index] = '\\'; result_index += 1; @@ -1124,8 +1124,8 @@ pub fn relativePosix(allocator: Allocator, from: []const u8, to: []const u8) ![] const resolved_to = try resolvePosix(allocator, &[_][]const u8{ cwd, to }); defer allocator.free(resolved_to); - var from_it = mem.tokenize(u8, resolved_from, "/"); - var to_it = mem.tokenize(u8, resolved_to, "/"); + var from_it = mem.tokenizeScalar(u8, resolved_from, '/'); + var to_it = mem.tokenizeScalar(u8, resolved_to, '/'); while (true) { const from_component = from_it.next() orelse return allocator.dupe(u8, to_it.rest()); const to_rest = to_it.rest(); diff --git a/lib/std/http/Client.zig b/lib/std/http/Client.zig index 023bdd28bc..5626864ceb 100644 --- a/lib/std/http/Client.zig +++ b/lib/std/http/Client.zig @@ -386,7 +386,7 @@ pub const Response = struct { }; pub fn parse(res: *Response, bytes: []const u8, trailing: bool) ParseError!void { - var it = mem.tokenize(u8, bytes[0 .. bytes.len - 4], "\r\n"); + var it = mem.tokenizeAny(u8, bytes[0 .. bytes.len - 4], "\r\n"); const first_line = it.next() orelse return error.HttpHeadersInvalid; if (first_line.len < 12) @@ -412,7 +412,7 @@ pub const Response = struct { else => {}, } - var line_it = mem.tokenize(u8, line, ": "); + var line_it = mem.tokenizeAny(u8, line, ": "); const header_name = line_it.next() orelse return error.HttpHeadersInvalid; const header_value = line_it.rest(); diff --git a/lib/std/http/Server.zig b/lib/std/http/Server.zig index 6b5db6725f..51ab6c086b 100644 --- a/lib/std/http/Server.zig +++ b/lib/std/http/Server.zig @@ -231,7 +231,7 @@ pub const Request = struct { }; pub fn parse(req: *Request, bytes: []const u8) ParseError!void { - var it = mem.tokenize(u8, bytes[0 .. bytes.len - 4], "\r\n"); + var it = mem.tokenizeAny(u8, bytes[0 .. bytes.len - 4], "\r\n"); const first_line = it.next() orelse return error.HttpHeadersInvalid; if (first_line.len < 10) @@ -265,7 +265,7 @@ pub const Request = struct { else => {}, } - var line_it = mem.tokenize(u8, line, ": "); + var line_it = mem.tokenizeAny(u8, line, ": "); const header_name = line_it.next() orelse return error.HttpHeadersInvalid; const header_value = line_it.rest(); diff --git a/lib/std/net.zig b/lib/std/net.zig index 57e50a7349..4360cc29f4 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -1266,7 +1266,7 @@ fn linuxLookupNameFromHosts( var split_it = mem.split(u8, line, "#"); const no_comment_line = split_it.first(); - var line_it = mem.tokenize(u8, no_comment_line, " \t"); + var line_it = mem.tokenizeAny(u8, no_comment_line, " \t"); const ip_text = line_it.next() orelse continue; var first_name_text: ?[]const u8 = null; while (line_it.next()) |name_text| { @@ -1346,7 +1346,7 @@ fn linuxLookupNameFromDnsSearch( @memcpy(canon.items, canon_name); try canon.append('.'); - var tok_it = mem.tokenize(u8, search, " \t"); + var tok_it = mem.tokenizeAny(u8, search, " \t"); while (tok_it.next()) |tok| { canon.shrinkRetainingCapacity(canon_name.len + 1); try canon.appendSlice(tok); @@ -1468,7 +1468,7 @@ fn getResolvConf(allocator: mem.Allocator, rc: *ResolvConf) !void { var split = mem.split(u8, line, "#"); break :no_comment_line split.first(); }; - var line_it = mem.tokenize(u8, no_comment_line, " \t"); + var line_it = mem.tokenizeAny(u8, no_comment_line, " \t"); const token = line_it.next() orelse continue; if (mem.eql(u8, token, "options")) { diff --git a/lib/std/os.zig b/lib/std/os.zig index 779e913230..eac79690b5 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -1878,7 +1878,7 @@ pub fn execvpeZ_expandArg0( // Use of MAX_PATH_BYTES here is valid as the path_buf will be passed // directly to the operating system in execveZ. var path_buf: [MAX_PATH_BYTES]u8 = undefined; - var it = mem.tokenize(u8, PATH, ":"); + var it = mem.tokenizeScalar(u8, PATH, ':'); var seen_eacces = false; var err: ExecveError = error.FileNotFound; diff --git a/lib/std/process.zig b/lib/std/process.zig index 504f9075eb..c33fd92db6 100644 --- a/lib/std/process.zig +++ b/lib/std/process.zig @@ -1200,7 +1200,7 @@ fn totalSystemMemoryLinux() !usize { var buf: [50]u8 = undefined; const amt = try file.read(&buf); if (amt != 50) return error.Unexpected; - var it = std.mem.tokenize(u8, buf[0..amt], " \n"); + var it = std.mem.tokenizeAny(u8, buf[0..amt], " \n"); const label = it.next().?; if (!std.mem.eql(u8, label, "MemTotal:")) return error.Unexpected; const int_text = it.next() orelse return error.Unexpected; diff --git a/lib/std/zig/system/NativePaths.zig b/lib/std/zig/system/NativePaths.zig index 70c795b0cf..368e3e062d 100644 --- a/lib/std/zig/system/NativePaths.zig +++ b/lib/std/zig/system/NativePaths.zig @@ -31,7 +31,7 @@ pub fn detect(allocator: Allocator, native_info: NativeTargetInfo) !NativePaths defer allocator.free(nix_cflags_compile); is_nix = true; - var it = mem.tokenize(u8, nix_cflags_compile, " "); + var it = mem.tokenizeScalar(u8, nix_cflags_compile, ' '); while (true) { const word = it.next() orelse break; if (mem.eql(u8, word, "-isystem")) { @@ -62,7 +62,7 @@ pub fn detect(allocator: Allocator, native_info: NativeTargetInfo) !NativePaths defer allocator.free(nix_ldflags); is_nix = true; - var it = mem.tokenize(u8, nix_ldflags, " "); + var it = mem.tokenizeScalar(u8, nix_ldflags, ' '); while (true) { const word = it.next() orelse break; if (mem.eql(u8, word, "-rpath")) { @@ -147,21 +147,21 @@ pub fn detect(allocator: Allocator, native_info: NativeTargetInfo) !NativePaths // We use os.getenv here since this part won't be executed on // windows, to get rid of unnecessary error handling. if (std.os.getenv("C_INCLUDE_PATH")) |c_include_path| { - var it = mem.tokenize(u8, c_include_path, ":"); + var it = mem.tokenizeScalar(u8, c_include_path, ':'); while (it.next()) |dir| { try self.addIncludeDir(dir); } } if (std.os.getenv("CPLUS_INCLUDE_PATH")) |cplus_include_path| { - var it = mem.tokenize(u8, cplus_include_path, ":"); + var it = mem.tokenizeScalar(u8, cplus_include_path, ':'); while (it.next()) |dir| { try self.addIncludeDir(dir); } } if (std.os.getenv("LIBRARY_PATH")) |library_path| { - var it = mem.tokenize(u8, library_path, ":"); + var it = mem.tokenizeScalar(u8, library_path, ':'); while (it.next()) |dir| { try self.addLibDir(dir); } diff --git a/lib/std/zig/system/NativeTargetInfo.zig b/lib/std/zig/system/NativeTargetInfo.zig index 539ad96365..808a1bda8d 100644 --- a/lib/std/zig/system/NativeTargetInfo.zig +++ b/lib/std/zig/system/NativeTargetInfo.zig @@ -354,7 +354,7 @@ fn detectAbiAndDynamicLinker( const newline = mem.indexOfScalar(u8, buffer[0..len], '\n') orelse break :blk file; const line = buffer[0..newline]; if (!mem.startsWith(u8, line, "#!")) break :blk file; - var it = mem.tokenize(u8, line[2..], " "); + var it = mem.tokenizeScalar(u8, line[2..], ' '); file_name = it.next() orelse return defaultAbiAndDynamicLinker(cpu, os, cross_target); file.close(); } @@ -811,7 +811,7 @@ pub fn abiAndDynamicLinkerFromFile( const strtab = strtab_buf[0..strtab_read_len]; const rpath_list = mem.sliceTo(strtab, 0); - var it = mem.tokenize(u8, rpath_list, ":"); + var it = mem.tokenizeScalar(u8, rpath_list, ':'); while (it.next()) |rpath| { if (glibcVerFromRPath(rpath)) |ver| { result.target.os.version_range.linux.glibc = ver; diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig index 2dc1cc8ee4..be09a33bde 100644 --- a/src/arch/x86_64/CodeGen.zig +++ b/src/arch/x86_64/CodeGen.zig @@ -8409,9 +8409,9 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void { } const asm_source = mem.sliceAsBytes(self.air.extra[extra_i..])[0..extra.data.source_len]; - var line_it = mem.tokenize(u8, asm_source, "\n\r;"); + var line_it = mem.tokenizeAny(u8, asm_source, "\n\r;"); while (line_it.next()) |line| { - var mnem_it = mem.tokenize(u8, line, " \t"); + var mnem_it = mem.tokenizeAny(u8, line, " \t"); const mnem_str = mnem_it.next() orelse continue; if (mem.startsWith(u8, mnem_str, "#")) continue; @@ -8435,7 +8435,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void { return self.fail("Invalid mnemonic: '{s}'", .{mnem_str}); } }; - var op_it = mem.tokenize(u8, mnem_it.rest(), ","); + var op_it = mem.tokenizeScalar(u8, mnem_it.rest(), ','); var ops = [1]encoder.Instruction.Operand{.none} ** 4; for (&ops) |*op| { const op_str = mem.trim(u8, op_it.next() orelse break, " \t"); diff --git a/src/glibc.zig b/src/glibc.zig index 327e4f4bb9..00787381f4 100644 --- a/src/glibc.zig +++ b/src/glibc.zig @@ -109,7 +109,7 @@ pub fn loadMetaData(gpa: Allocator, contents: []const u8) LoadMetaDataError!*ABI const target_name = mem.sliceTo(contents[index..], 0); index += target_name.len + 1; - var component_it = mem.tokenize(u8, target_name, "-"); + var component_it = mem.tokenizeScalar(u8, target_name, '-'); const arch_name = component_it.next() orelse { log.err("abilists: expected arch name", .{}); return error.ZigInstallationCorrupt; diff --git a/src/libc_installation.zig b/src/libc_installation.zig index da877e1291..a62da6b9c7 100644 --- a/src/libc_installation.zig +++ b/src/libc_installation.zig @@ -60,7 +60,7 @@ pub const LibCInstallation = struct { const contents = try std.fs.cwd().readFileAlloc(allocator, libc_file, std.math.maxInt(usize)); defer allocator.free(contents); - var it = std.mem.tokenize(u8, contents, "\n"); + var it = std.mem.tokenizeScalar(u8, contents, '\n'); while (it.next()) |line| { if (line.len == 0 or line[0] == '#') continue; var line_it = std.mem.split(u8, line, "="); @@ -293,7 +293,7 @@ pub const LibCInstallation = struct { }, } - var it = std.mem.tokenize(u8, exec_res.stderr, "\n\r"); + var it = std.mem.tokenizeAny(u8, exec_res.stderr, "\n\r"); var search_paths = std.ArrayList([]const u8).init(allocator); defer search_paths.deinit(); while (it.next()) |line| { @@ -613,7 +613,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 { }, } - var it = std.mem.tokenize(u8, exec_res.stdout, "\n\r"); + var it = std.mem.tokenizeAny(u8, exec_res.stdout, "\n\r"); const line = it.next() orelse return error.LibCRuntimeNotFound; // When this command fails, it returns exit code 0 and duplicates the input file name. // So we detect failure by checking if the output matches exactly the input. @@ -692,7 +692,7 @@ fn appendCcExe(args: *std.ArrayList([]const u8), skip_cc_env_var: bool) !void { return; }; // Respect space-separated flags to the C compiler. - var it = std.mem.tokenize(u8, cc_env_var, " "); + var it = std.mem.tokenizeScalar(u8, cc_env_var, ' '); while (it.next()) |arg| { try args.append(arg); } diff --git a/src/link/Plan9.zig b/src/link/Plan9.zig index bef06d1c87..f8ac4e09c1 100644 --- a/src/link/Plan9.zig +++ b/src/link/Plan9.zig @@ -264,7 +264,7 @@ fn putFn(self: *Plan9, decl_index: Module.Decl.Index, out: FnDeclOutput) !void { fn addPathComponents(self: *Plan9, path: []const u8, a: *std.ArrayList(u8)) !void { const sep = std.fs.path.sep; - var it = std.mem.tokenize(u8, path, &.{sep}); + var it = std.mem.tokenizeScalar(u8, path, sep); while (it.next()) |component| { if (self.file_segments.get(component)) |num| { try a.writer().writeIntBig(u16, num); diff --git a/src/print_zir.zig b/src/print_zir.zig index f5e84fcf5b..6ded52ae9f 100644 --- a/src/print_zir.zig +++ b/src/print_zir.zig @@ -2581,7 +2581,7 @@ const Writer = struct { fn writeDocComment(self: *Writer, stream: anytype, doc_comment_index: u32) !void { if (doc_comment_index != 0) { const doc_comment = self.code.nullTerminatedString(doc_comment_index); - var it = std.mem.tokenize(u8, doc_comment, "\n"); + var it = std.mem.tokenizeScalar(u8, doc_comment, '\n'); while (it.next()) |doc_line| { try stream.writeByteNTimes(' ', self.indent); try stream.print("///{s}\n", .{doc_line}); diff --git a/test/behavior/bugs/6456.zig b/test/behavior/bugs/6456.zig index 1eef9c7f75..297c9c7423 100644 --- a/test/behavior/bugs/6456.zig +++ b/test/behavior/bugs/6456.zig @@ -18,7 +18,7 @@ test "issue 6456" { comptime { var fields: []const StructField = &[0]StructField{}; - var it = std.mem.tokenize(u8, text, "\n"); + var it = std.mem.tokenizeScalar(u8, text, '\n'); while (it.next()) |name| { fields = fields ++ &[_]StructField{StructField{ .alignment = 0, diff --git a/test/src/Cases.zig b/test/src/Cases.zig index 68ecebc7bd..aa5369af93 100644 --- a/test/src/Cases.zig +++ b/test/src/Cases.zig @@ -846,7 +846,7 @@ const TestManifest = struct { const actual_start = start orelse return error.MissingTestManifest; const manifest_bytes = bytes[actual_start..end]; - var it = std.mem.tokenize(u8, manifest_bytes, "\r\n"); + var it = std.mem.tokenizeAny(u8, manifest_bytes, "\r\n"); // First line is the test type const tt: Type = blk: { @@ -923,7 +923,7 @@ const TestManifest = struct { fn trailing(self: TestManifest) TrailingIterator { return .{ - .inner = std.mem.tokenize(u8, self.trailing_bytes, "\r\n"), + .inner = std.mem.tokenizeAny(u8, self.trailing_bytes, "\r\n"), }; } diff --git a/tools/generate_linux_syscalls.zig b/tools/generate_linux_syscalls.zig index 11b18ae3bf..32e287b434 100644 --- a/tools/generate_linux_syscalls.zig +++ b/tools/generate_linux_syscalls.zig @@ -51,11 +51,11 @@ pub fn main() !void { try writer.writeAll("pub const X86 = enum(usize) {\n"); const table = try linux_dir.readFile("arch/x86/entry/syscalls/syscall_32.tbl", buf); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; // abi is always i386 _ = fields.next() orelse return error.Incomplete; @@ -70,11 +70,11 @@ pub fn main() !void { try writer.writeAll("pub const X64 = enum(usize) {\n"); const table = try linux_dir.readFile("arch/x86/entry/syscalls/syscall_64.tbl", buf); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; // The x32 abi syscalls are always at the end. @@ -96,11 +96,11 @@ pub fn main() !void { ); const table = try linux_dir.readFile("arch/arm/tools/syscall.tbl", buf); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; if (mem.eql(u8, abi, "oabi")) continue; @@ -127,11 +127,11 @@ pub fn main() !void { { try writer.writeAll("pub const Sparc64 = enum(usize) {\n"); const table = try linux_dir.readFile("arch/sparc/kernel/syscalls/syscall.tbl", buf); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; if (mem.eql(u8, abi, "32")) continue; @@ -151,11 +151,11 @@ pub fn main() !void { ); const table = try linux_dir.readFile("arch/mips/kernel/syscalls/syscall_o32.tbl", buf); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; // abi is always o32 _ = fields.next() orelse return error.Incomplete; @@ -176,11 +176,11 @@ pub fn main() !void { ); const table = try linux_dir.readFile("arch/mips/kernel/syscalls/syscall_n64.tbl", buf); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; // abi is always n64 _ = fields.next() orelse return error.Incomplete; @@ -197,11 +197,11 @@ pub fn main() !void { const table = try linux_dir.readFile("arch/powerpc/kernel/syscalls/syscall.tbl", buf); var list_64 = std.ArrayList(u8).init(allocator); - var lines = mem.tokenize(u8, table, "\n"); + var lines = mem.tokenizeScalar(u8, table, '\n'); while (lines.next()) |line| { if (line[0] == '#') continue; - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; const name = fields.next() orelse return error.Incomplete; @@ -277,9 +277,9 @@ pub fn main() !void { }, }; - var lines = mem.tokenize(u8, defines, "\n"); + var lines = mem.tokenizeScalar(u8, defines, '\n'); loop: while (lines.next()) |line| { - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const cmd = fields.next() orelse return error.Incomplete; if (!mem.eql(u8, cmd, "#define")) continue; const define = fields.next() orelse return error.Incomplete; @@ -339,9 +339,9 @@ pub fn main() !void { }, }; - var lines = mem.tokenize(u8, defines, "\n"); + var lines = mem.tokenizeScalar(u8, defines, '\n'); loop: while (lines.next()) |line| { - var fields = mem.tokenize(u8, line, " \t"); + var fields = mem.tokenizeAny(u8, line, " \t"); const cmd = fields.next() orelse return error.Incomplete; if (!mem.eql(u8, cmd, "#define")) continue; const define = fields.next() orelse return error.Incomplete; -- cgit v1.2.3 From c76ce25a6165e96015b11d506e3c968c6c8dca2c Mon Sep 17 00:00:00 2001 From: Zapolsky Anton Date: Tue, 13 Jun 2023 21:09:24 +0300 Subject: Remove CheckObjectStep.runAndCompare (#15973) Closes #14969 --- lib/std/Build/Step/CheckObject.zig | 16 ---------------- test/link/macho/dead_strip/build.zig | 14 ++++++++------ test/link/macho/dylib/build.zig | 3 ++- test/link/macho/entry/build.zig | 3 ++- test/link/macho/entry_in_dylib/build.zig | 3 ++- test/link/macho/needed_library/build.zig | 7 ++++--- test/link/macho/search_strategy/build.zig | 3 ++- test/link/macho/stack_size/build.zig | 3 ++- test/link/macho/strict_validation/build.zig | 3 ++- test/link/macho/unwind_info/build.zig | 7 ++++--- test/link/macho/weak_library/build.zig | 7 ++++--- 11 files changed, 32 insertions(+), 37 deletions(-) (limited to 'lib/std/Build/Step/CheckObject.zig') diff --git a/lib/std/Build/Step/CheckObject.zig b/lib/std/Build/Step/CheckObject.zig index 24ebfef388..1c2d86e4e3 100644 --- a/lib/std/Build/Step/CheckObject.zig +++ b/lib/std/Build/Step/CheckObject.zig @@ -42,22 +42,6 @@ pub fn create( return self; } -/// Runs and (optionally) compares the output of a binary. -/// Asserts `self` was generated from an executable step. -/// TODO this doesn't actually compare, and there's no apparent reason for it -/// to depend on the check object step. I don't see why this function should exist, -/// the caller could just add the run step directly. -pub fn runAndCompare(self: *CheckObject) *std.Build.Step.Run { - const dependencies_len = self.step.dependencies.items.len; - assert(dependencies_len > 0); - const exe_step = self.step.dependencies.items[dependencies_len - 1]; - const exe = exe_step.cast(std.Build.Step.Compile).?; - const run = self.step.owner.addRunArtifact(exe); - run.skip_foreign_checks = true; - run.step.dependOn(&self.step); - return run; -} - const SearchPhrase = struct { string: []const u8, file_source: ?std.Build.FileSource = null, diff --git a/test/link/macho/dead_strip/build.zig b/test/link/macho/dead_strip/build.zig index 9d00bad9e0..5ca3e5f89f 100644 --- a/test/link/macho/dead_strip/build.zig +++ b/test/link/macho/dead_strip/build.zig @@ -17,9 +17,10 @@ pub fn build(b: *std.Build) void { check.checkInSymtab(); check.checkNext("{*} (__TEXT,__text) external _iAmUnused"); - const run_cmd = check.runAndCompare(); - run_cmd.expectStdOutEqual("Hello!\n"); - test_step.dependOn(&run_cmd.step); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; + run.expectStdOutEqual("Hello!\n"); + test_step.dependOn(&run.step); } { @@ -31,9 +32,10 @@ pub fn build(b: *std.Build) void { check.checkInSymtab(); check.checkNotPresent("{*} (__TEXT,__text) external _iAmUnused"); - const run_cmd = check.runAndCompare(); - run_cmd.expectStdOutEqual("Hello!\n"); - test_step.dependOn(&run_cmd.step); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; + run.expectStdOutEqual("Hello!\n"); + test_step.dependOn(&run.step); } } diff --git a/test/link/macho/dylib/build.zig b/test/link/macho/dylib/build.zig index a4085b51e6..fe294f3333 100644 --- a/test/link/macho/dylib/build.zig +++ b/test/link/macho/dylib/build.zig @@ -54,7 +54,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize check_exe.checkStart("cmd RPATH"); check_exe.checkNextFileSource("path", dylib.getOutputDirectorySource()); - const run = check_exe.runAndCompare(); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; run.expectStdOutEqual("Hello world"); test_step.dependOn(&run.step); } diff --git a/test/link/macho/entry/build.zig b/test/link/macho/entry/build.zig index e983bc9391..454956ad41 100644 --- a/test/link/macho/entry/build.zig +++ b/test/link/macho/entry/build.zig @@ -35,7 +35,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize check_exe.checkComputeCompare("vmaddr entryoff +", .{ .op = .eq, .value = .{ .variable = "n_value" } }); - const run = check_exe.runAndCompare(); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; run.expectStdOutEqual("42"); test_step.dependOn(&run.step); } diff --git a/test/link/macho/entry_in_dylib/build.zig b/test/link/macho/entry_in_dylib/build.zig index 135661872d..acb26efceb 100644 --- a/test/link/macho/entry_in_dylib/build.zig +++ b/test/link/macho/entry_in_dylib/build.zig @@ -48,7 +48,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize .value = .{ .variable = "stubs_vmaddr" }, // The entrypoint should be a synthetic stub }); - const run = check_exe.runAndCompare(); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; run.expectStdOutEqual("Hello!\n"); test_step.dependOn(&run.step); } diff --git a/test/link/macho/needed_library/build.zig b/test/link/macho/needed_library/build.zig index cb9ea38d4b..7b56572cc3 100644 --- a/test/link/macho/needed_library/build.zig +++ b/test/link/macho/needed_library/build.zig @@ -42,7 +42,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize check.checkStart("cmd LOAD_DYLIB"); check.checkNext("name @rpath/liba.dylib"); - const run_cmd = check.runAndCompare(); - run_cmd.expectStdOutEqual(""); - test_step.dependOn(&run_cmd.step); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; + run.expectStdOutEqual(""); + test_step.dependOn(&run.step); } diff --git a/test/link/macho/search_strategy/build.zig b/test/link/macho/search_strategy/build.zig index 853c471969..4b52d9aa0a 100644 --- a/test/link/macho/search_strategy/build.zig +++ b/test/link/macho/search_strategy/build.zig @@ -24,7 +24,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize check.checkStart("cmd LOAD_DYLIB"); check.checkNext("name @rpath/libsearch_dylibs_first.dylib"); - const run = check.runAndCompare(); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; run.expectStdOutEqual("Hello world"); test_step.dependOn(&run.step); } diff --git a/test/link/macho/stack_size/build.zig b/test/link/macho/stack_size/build.zig index c7d308d004..219d65cdb8 100644 --- a/test/link/macho/stack_size/build.zig +++ b/test/link/macho/stack_size/build.zig @@ -28,7 +28,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize check_exe.checkStart("cmd MAIN"); check_exe.checkNext("stacksize 100000000"); - const run = check_exe.runAndCompare(); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; run.expectStdOutEqual(""); test_step.dependOn(&run.step); } diff --git a/test/link/macho/strict_validation/build.zig b/test/link/macho/strict_validation/build.zig index 34a0cd73fc..d75b4c5820 100644 --- a/test/link/macho/strict_validation/build.zig +++ b/test/link/macho/strict_validation/build.zig @@ -122,7 +122,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize else => unreachable, } - const run = check_exe.runAndCompare(); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; run.expectStdOutEqual("Hello!\n"); test_step.dependOn(&run.step); } diff --git a/test/link/macho/unwind_info/build.zig b/test/link/macho/unwind_info/build.zig index 96b5f6cacc..6f19acef38 100644 --- a/test/link/macho/unwind_info/build.zig +++ b/test/link/macho/unwind_info/build.zig @@ -47,8 +47,9 @@ fn testUnwindInfo( check.checkInSymtab(); check.checkNext("{*} (__TEXT,__text) external ___gxx_personality_v0"); - const run_cmd = check.runAndCompare(); - run_cmd.expectStdOutEqual( + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; + run.expectStdOutEqual( \\Constructed: a \\Constructed: b \\About to destroy: b @@ -57,7 +58,7 @@ fn testUnwindInfo( \\ ); - test_step.dependOn(&run_cmd.step); + test_step.dependOn(&run.step); } fn createScenario( diff --git a/test/link/macho/weak_library/build.zig b/test/link/macho/weak_library/build.zig index 88d72ad487..81a694be9b 100644 --- a/test/link/macho/weak_library/build.zig +++ b/test/link/macho/weak_library/build.zig @@ -46,7 +46,8 @@ fn add(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.Optimize check.checkInSymtab(); check.checkNext("(undefined) weak external _asStr (from liba)"); - const run_cmd = check.runAndCompare(); - run_cmd.expectStdOutEqual("42 42"); - test_step.dependOn(&run_cmd.step); + const run = b.addRunArtifact(exe); + run.skip_foreign_checks = true; + run.expectStdOutEqual("42 42"); + test_step.dependOn(&run.step); } -- cgit v1.2.3