From 8b2622cdd58cec697d9d1f8f49717b6ce7ee3e2e Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 8 Dec 2019 22:53:51 -0500 Subject: [PATCH 1/7] std.fmt.format: tuple parameter instead of var args --- build.zig | 10 +- lib/std/atomic/queue.zig | 19 +- lib/std/atomic/stack.zig | 7 +- lib/std/buffer.zig | 8 +- lib/std/build.zig | 186 ++++++++++-------- lib/std/builtin.zig | 4 +- lib/std/crypto/benchmark.zig | 2 +- lib/std/debug.zig | 91 +++++---- lib/std/event/channel.zig | 4 +- lib/std/fifo.zig | 4 +- lib/std/fmt.zig | 220 +++++++++++----------- lib/std/hash/benchmark.zig | 2 +- lib/std/http/headers.zig | 2 +- lib/std/io.zig | 2 +- lib/std/io/out_stream.zig | 2 +- lib/std/io/test.zig | 8 +- lib/std/json/write_stream.zig | 8 +- lib/std/math/big/int.zig | 4 +- lib/std/net.zig | 22 +-- lib/std/net/test.zig | 6 +- lib/std/os.zig | 4 +- lib/std/os/windows.zig | 4 +- lib/std/os/zen.zig | 260 -------------------------- lib/std/priority_queue.zig | 16 +- lib/std/progress.zig | 22 +-- lib/std/special/build_runner.zig | 33 ++-- lib/std/special/init-exe/src/main.zig | 2 +- lib/std/special/start.zig | 4 +- lib/std/special/test_runner.zig | 14 +- lib/std/target.zig | 18 +- lib/std/testing.zig | 41 ++-- lib/std/unicode.zig | 2 +- lib/std/unicode/throughput_test.zig | 8 +- lib/std/valgrind.zig | 14 -- lib/std/zig/ast.zig | 24 ++- lib/std/zig/parser_test.zig | 46 ++--- lib/std/zig/render.zig | 6 +- lib/std/zig/tokenizer.zig | 4 +- src-self-hosted/arg.zig | 12 +- src-self-hosted/dep_tokenizer.zig | 30 +-- src-self-hosted/stage1.zig | 12 +- src-self-hosted/translate_c.zig | 79 +++++--- src/ir.cpp | 16 +- test/cli.zig | 22 +-- test/compile_errors.zig | 6 +- test/standalone/cat/main.zig | 10 +- test/standalone/guess_number/main.zig | 2 +- test/tests.zig | 160 +++++++++------- 48 files changed, 643 insertions(+), 839 deletions(-) delete mode 100644 lib/std/os/zen.zig diff --git a/build.zig b/build.zig index 707094d36b..0788e2e762 100644 --- a/build.zig +++ b/build.zig @@ -154,7 +154,7 @@ fn dependOnLib(b: *Builder, lib_exe_obj: var, dep: LibraryDep) void { const static_bare_name = if (mem.eql(u8, lib, "curses")) @as([]const u8, "libncurses.a") else - b.fmt("lib{}.a", lib); + b.fmt("lib{}.a", .{lib}); const static_lib_name = fs.path.join( b.allocator, &[_][]const u8{ lib_dir, static_bare_name }, @@ -186,7 +186,7 @@ fn addCppLib(b: *Builder, lib_exe_obj: var, cmake_binary_dir: []const u8, lib_na lib_exe_obj.addObjectFile(fs.path.join(b.allocator, &[_][]const u8{ cmake_binary_dir, "zig_cpp", - b.fmt("{}{}{}", lib_exe_obj.target.libPrefix(), lib_name, lib_exe_obj.target.staticLibSuffix()), + b.fmt("{}{}{}", .{ lib_exe_obj.target.libPrefix(), lib_name, lib_exe_obj.target.staticLibSuffix() }), }) catch unreachable); } @@ -343,14 +343,14 @@ fn addCxxKnownPath( ) !void { const path_padded = try b.exec(&[_][]const u8{ ctx.cxx_compiler, - b.fmt("-print-file-name={}", objname), + b.fmt("-print-file-name={}", .{objname}), }); const path_unpadded = mem.tokenize(path_padded, "\r\n").next().?; if (mem.eql(u8, path_unpadded, objname)) { if (errtxt) |msg| { - warn("{}", msg); + warn("{}", .{msg}); } else { - warn("Unable to determine path to {}\n", objname); + warn("Unable to determine path to {}\n", .{objname}); } return error.RequiredLibraryNotFound; } diff --git a/lib/std/atomic/queue.zig b/lib/std/atomic/queue.zig index 53f1d99f13..63bacb4fb5 100644 --- a/lib/std/atomic/queue.zig +++ b/lib/std/atomic/queue.zig @@ -116,19 +116,19 @@ pub fn Queue(comptime T: type) type { fn dumpRecursive(s: *std.io.OutStream(Error), optional_node: ?*Node, indent: usize) Error!void { try s.writeByteNTimes(' ', indent); if (optional_node) |node| { - try s.print("0x{x}={}\n", @ptrToInt(node), node.data); + try s.print("0x{x}={}\n", .{ @ptrToInt(node), node.data }); try dumpRecursive(s, node.next, indent + 1); } else { - try s.print("(null)\n"); + try s.print("(null)\n", .{}); } } }; const held = self.mutex.acquire(); defer held.release(); - try stream.print("head: "); + try stream.print("head: ", .{}); try S.dumpRecursive(stream, self.head, 0); - try stream.print("tail: "); + try stream.print("tail: ", .{}); try S.dumpRecursive(stream, self.tail, 0); } }; @@ -207,16 +207,15 @@ test "std.atomic.Queue" { } if (context.put_sum != context.get_sum) { - std.debug.panic("failure\nput_sum:{} != get_sum:{}", context.put_sum, context.get_sum); + std.debug.panic("failure\nput_sum:{} != get_sum:{}", .{ context.put_sum, context.get_sum }); } if (context.get_count != puts_per_thread * put_thread_count) { - std.debug.panic( - "failure\nget_count:{} != puts_per_thread:{} * put_thread_count:{}", + std.debug.panic("failure\nget_count:{} != puts_per_thread:{} * put_thread_count:{}", .{ context.get_count, @as(u32, puts_per_thread), @as(u32, put_thread_count), - ); + }); } } @@ -351,7 +350,7 @@ test "std.atomic.Queue dump" { \\tail: 0x{x}=1 \\ (null) \\ - , @ptrToInt(queue.head), @ptrToInt(queue.tail)); + , .{ @ptrToInt(queue.head), @ptrToInt(queue.tail) }); expect(mem.eql(u8, buffer[0..sos.pos], expected)); // Test a stream with two elements @@ -372,6 +371,6 @@ test "std.atomic.Queue dump" { \\tail: 0x{x}=2 \\ (null) \\ - , @ptrToInt(queue.head), @ptrToInt(queue.head.?.next), @ptrToInt(queue.tail)); + , .{ @ptrToInt(queue.head), @ptrToInt(queue.head.?.next), @ptrToInt(queue.tail) }); expect(mem.eql(u8, buffer[0..sos.pos], expected)); } diff --git a/lib/std/atomic/stack.zig b/lib/std/atomic/stack.zig index 2636b20528..9de8e36f87 100644 --- a/lib/std/atomic/stack.zig +++ b/lib/std/atomic/stack.zig @@ -134,16 +134,15 @@ test "std.atomic.stack" { } if (context.put_sum != context.get_sum) { - std.debug.panic("failure\nput_sum:{} != get_sum:{}", context.put_sum, context.get_sum); + std.debug.panic("failure\nput_sum:{} != get_sum:{}", .{ context.put_sum, context.get_sum }); } if (context.get_count != puts_per_thread * put_thread_count) { - std.debug.panic( - "failure\nget_count:{} != puts_per_thread:{} * put_thread_count:{}", + std.debug.panic("failure\nget_count:{} != puts_per_thread:{} * put_thread_count:{}", .{ context.get_count, @as(u32, puts_per_thread), @as(u32, put_thread_count), - ); + }); } } diff --git a/lib/std/buffer.zig b/lib/std/buffer.zig index 46c55a32b8..55a5a890d6 100644 --- a/lib/std/buffer.zig +++ b/lib/std/buffer.zig @@ -16,7 +16,7 @@ pub const Buffer = struct { mem.copy(u8, self.list.items, m); return self; } - + /// Initialize memory to size bytes of undefined values. /// Must deinitialize with deinit. pub fn initSize(allocator: *Allocator, size: usize) !Buffer { @@ -24,7 +24,7 @@ pub const Buffer = struct { try self.resize(size); return self; } - + /// Initialize with capacity to hold at least num bytes. /// Must deinitialize with deinit. pub fn initCapacity(allocator: *Allocator, num: usize) !Buffer { @@ -64,7 +64,7 @@ pub const Buffer = struct { return result; } - pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: ...) !Buffer { + pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer { const countSize = struct { fn countSize(size: *usize, bytes: []const u8) (error{}!void) { size.* += bytes.len; @@ -107,7 +107,7 @@ pub const Buffer = struct { pub fn len(self: Buffer) usize { return self.list.len - 1; } - + pub fn capacity(self: Buffer) usize { return if (self.list.items.len > 0) self.list.items.len - 1 diff --git a/lib/std/build.zig b/lib/std/build.zig index bfde2f52d7..82681e3069 100644 --- a/lib/std/build.zig +++ b/lib/std/build.zig @@ -232,7 +232,7 @@ pub const Builder = struct { /// To run an executable built with zig build, see `LibExeObjStep.run`. pub fn addSystemCommand(self: *Builder, argv: []const []const u8) *RunStep { assert(argv.len >= 1); - const run_step = RunStep.create(self, self.fmt("run {}", argv[0])); + const run_step = RunStep.create(self, self.fmt("run {}", .{argv[0]})); run_step.addArgs(argv); return run_step; } @@ -258,7 +258,7 @@ pub const Builder = struct { return write_file_step; } - pub fn addLog(self: *Builder, comptime format: []const u8, args: ...) *LogStep { + pub fn addLog(self: *Builder, comptime format: []const u8, args: var) *LogStep { const data = self.fmt(format, args); const log_step = self.allocator.create(LogStep) catch unreachable; log_step.* = LogStep.init(self, data); @@ -330,7 +330,7 @@ pub const Builder = struct { for (self.installed_files.toSliceConst()) |installed_file| { const full_path = self.getInstallPath(installed_file.dir, installed_file.path); if (self.verbose) { - warn("rm {}\n", full_path); + warn("rm {}\n", .{full_path}); } fs.deleteTree(full_path) catch {}; } @@ -340,7 +340,7 @@ pub const Builder = struct { fn makeOneStep(self: *Builder, s: *Step) anyerror!void { if (s.loop_flag) { - warn("Dependency loop detected:\n {}\n", s.name); + warn("Dependency loop detected:\n {}\n", .{s.name}); return error.DependencyLoopDetected; } s.loop_flag = true; @@ -348,7 +348,7 @@ pub const Builder = struct { for (s.dependencies.toSlice()) |dep| { self.makeOneStep(dep) catch |err| { if (err == error.DependencyLoopDetected) { - warn(" {}\n", s.name); + warn(" {}\n", .{s.name}); } return err; }; @@ -365,7 +365,7 @@ pub const Builder = struct { return &top_level_step.step; } } - warn("Cannot run step '{}' because it does not exist\n", name); + warn("Cannot run step '{}' because it does not exist\n", .{name}); return error.InvalidStepName; } @@ -378,12 +378,12 @@ pub const Builder = struct { const word = it.next() orelse break; if (mem.eql(u8, word, "-isystem")) { const include_path = it.next() orelse { - warn("Expected argument after -isystem in NIX_CFLAGS_COMPILE\n"); + warn("Expected argument after -isystem in NIX_CFLAGS_COMPILE\n", .{}); break; }; self.addNativeSystemIncludeDir(include_path); } else { - warn("Unrecognized C flag from NIX_CFLAGS_COMPILE: {}\n", word); + warn("Unrecognized C flag from NIX_CFLAGS_COMPILE: {}\n", .{word}); break; } } @@ -397,7 +397,7 @@ pub const Builder = struct { const word = it.next() orelse break; if (mem.eql(u8, word, "-rpath")) { const rpath = it.next() orelse { - warn("Expected argument after -rpath in NIX_LDFLAGS\n"); + warn("Expected argument after -rpath in NIX_LDFLAGS\n", .{}); break; }; self.addNativeSystemRPath(rpath); @@ -405,7 +405,7 @@ pub const Builder = struct { const lib_path = word[2..]; self.addNativeSystemLibPath(lib_path); } else { - warn("Unrecognized C flag from NIX_LDFLAGS: {}\n", word); + warn("Unrecognized C flag from NIX_LDFLAGS: {}\n", .{word}); break; } } @@ -431,8 +431,8 @@ pub const Builder = struct { self.addNativeSystemIncludeDir("/usr/local/include"); self.addNativeSystemLibPath("/usr/local/lib"); - self.addNativeSystemIncludeDir(self.fmt("/usr/include/{}", triple)); - self.addNativeSystemLibPath(self.fmt("/usr/lib/{}", triple)); + self.addNativeSystemIncludeDir(self.fmt("/usr/include/{}", .{triple})); + self.addNativeSystemLibPath(self.fmt("/usr/lib/{}", .{triple})); self.addNativeSystemIncludeDir("/usr/include"); self.addNativeSystemLibPath("/usr/lib"); @@ -440,7 +440,7 @@ pub const Builder = struct { // example: on a 64-bit debian-based linux distro, with zlib installed from apt: // zlib.h is in /usr/include (added above) // libz.so.1 is in /lib/x86_64-linux-gnu (added here) - self.addNativeSystemLibPath(self.fmt("/lib/{}", triple)); + self.addNativeSystemLibPath(self.fmt("/lib/{}", .{triple})); }, } } @@ -453,7 +453,7 @@ pub const Builder = struct { .description = description, }; if ((self.available_options_map.put(name, available_option) catch unreachable) != null) { - panic("Option '{}' declared twice", name); + panic("Option '{}' declared twice", .{name}); } self.available_options_list.append(available_option) catch unreachable; @@ -468,33 +468,33 @@ pub const Builder = struct { } else if (mem.eql(u8, s, "false")) { return false; } else { - warn("Expected -D{} to be a boolean, but received '{}'\n", name, s); + warn("Expected -D{} to be a boolean, but received '{}'\n", .{ name, s }); self.markInvalidUserInput(); return null; } }, UserValue.List => { - warn("Expected -D{} to be a boolean, but received a list.\n", name); + warn("Expected -D{} to be a boolean, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, }, - TypeId.Int => panic("TODO integer options to build script"), - TypeId.Float => panic("TODO float options to build script"), + TypeId.Int => panic("TODO integer options to build script", .{}), + TypeId.Float => panic("TODO float options to build script", .{}), TypeId.String => switch (entry.value.value) { UserValue.Flag => { - warn("Expected -D{} to be a string, but received a boolean.\n", name); + warn("Expected -D{} to be a string, but received a boolean.\n", .{name}); self.markInvalidUserInput(); return null; }, UserValue.List => { - warn("Expected -D{} to be a string, but received a list.\n", name); + warn("Expected -D{} to be a string, but received a list.\n", .{name}); self.markInvalidUserInput(); return null; }, UserValue.Scalar => |s| return s, }, - TypeId.List => panic("TODO list options to build script"), + TypeId.List => panic("TODO list options to build script", .{}), } } @@ -513,7 +513,7 @@ pub const Builder = struct { if (self.release_mode != null) { @panic("setPreferredReleaseMode must be called before standardReleaseOptions and may not be called twice"); } - const description = self.fmt("create a release build ({})", @tagName(mode)); + const description = self.fmt("create a release build ({})", .{@tagName(mode)}); self.is_release = self.option(bool, "release", description) orelse false; self.release_mode = if (self.is_release) mode else builtin.Mode.Debug; } @@ -536,7 +536,7 @@ pub const Builder = struct { else if (!release_fast and !release_safe and !release_small) builtin.Mode.Debug else x: { - warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)"); + warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)", .{}); self.markInvalidUserInput(); break :x builtin.Mode.Debug; }; @@ -599,7 +599,7 @@ pub const Builder = struct { }) catch unreachable; }, UserValue.Flag => { - warn("Option '-D{}={}' conflicts with flag '-D{}'.\n", name, value, name); + warn("Option '-D{}={}' conflicts with flag '-D{}'.\n", .{ name, value, name }); return true; }, } @@ -620,11 +620,11 @@ pub const Builder = struct { // option already exists switch (gop.kv.value.value) { UserValue.Scalar => |s| { - warn("Flag '-D{}' conflicts with option '-D{}={}'.\n", name, name, s); + warn("Flag '-D{}' conflicts with option '-D{}={}'.\n", .{ name, name, s }); return true; }, UserValue.List => { - warn("Flag '-D{}' conflicts with multiple options of the same name.\n", name); + warn("Flag '-D{}' conflicts with multiple options of the same name.\n", .{name}); return true; }, UserValue.Flag => {}, @@ -665,7 +665,7 @@ pub const Builder = struct { while (true) { const entry = it.next() orelse break; if (!entry.value.used) { - warn("Invalid option: -D{}\n\n", entry.key); + warn("Invalid option: -D{}\n\n", .{entry.key}); self.markInvalidUserInput(); } } @@ -678,11 +678,11 @@ pub const Builder = struct { } fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void { - if (cwd) |yes_cwd| warn("cd {} && ", yes_cwd); + if (cwd) |yes_cwd| warn("cd {} && ", .{yes_cwd}); for (argv) |arg| { - warn("{} ", arg); + warn("{} ", .{arg}); } - warn("\n"); + warn("\n", .{}); } fn spawnChildEnvMap(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) !void { @@ -697,20 +697,20 @@ pub const Builder = struct { child.env_map = env_map; const term = child.spawnAndWait() catch |err| { - warn("Unable to spawn {}: {}\n", argv[0], @errorName(err)); + warn("Unable to spawn {}: {}\n", .{ argv[0], @errorName(err) }); return err; }; switch (term) { .Exited => |code| { if (code != 0) { - warn("The following command exited with error code {}:\n", code); + warn("The following command exited with error code {}:\n", .{code}); printCmd(cwd, argv); return error.UncleanExit; } }, else => { - warn("The following command terminated unexpectedly:\n"); + warn("The following command terminated unexpectedly:\n", .{}); printCmd(cwd, argv); return error.UncleanExit; @@ -720,7 +720,7 @@ pub const Builder = struct { pub fn makePath(self: *Builder, path: []const u8) !void { fs.makePath(self.allocator, self.pathFromRoot(path)) catch |err| { - warn("Unable to create path {}: {}\n", path, @errorName(err)); + warn("Unable to create path {}: {}\n", .{ path, @errorName(err) }); return err; }; } @@ -793,12 +793,12 @@ pub const Builder = struct { fn updateFile(self: *Builder, source_path: []const u8, dest_path: []const u8) !void { if (self.verbose) { - warn("cp {} {} ", source_path, dest_path); + warn("cp {} {} ", .{ source_path, dest_path }); } const prev_status = try fs.updateFile(source_path, dest_path); if (self.verbose) switch (prev_status) { - .stale => warn("# installed\n"), - .fresh => warn("# up-to-date\n"), + .stale => warn("# installed\n", .{}), + .fresh => warn("# up-to-date\n", .{}), }; } @@ -806,7 +806,7 @@ pub const Builder = struct { return fs.path.resolve(self.allocator, &[_][]const u8{ self.build_root, rel_path }) catch unreachable; } - pub fn fmt(self: *Builder, comptime format: []const u8, args: ...) []u8 { + pub fn fmt(self: *Builder, comptime format: []const u8, args: var) []u8 { return fmt_lib.allocPrint(self.allocator, format, args) catch unreachable; } @@ -818,7 +818,11 @@ pub const Builder = struct { if (fs.path.isAbsolute(name)) { return name; } - const full_path = try fs.path.join(self.allocator, &[_][]const u8{ search_prefix, "bin", self.fmt("{}{}", name, exe_extension) }); + const full_path = try fs.path.join(self.allocator, &[_][]const u8{ + search_prefix, + "bin", + self.fmt("{}{}", .{ name, exe_extension }), + }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } } @@ -829,7 +833,10 @@ pub const Builder = struct { } var it = mem.tokenize(PATH, &[_]u8{fs.path.delimiter}); while (it.next()) |path| { - const full_path = try fs.path.join(self.allocator, &[_][]const u8{ path, self.fmt("{}{}", name, exe_extension) }); + const full_path = try fs.path.join(self.allocator, &[_][]const u8{ + path, + self.fmt("{}{}", .{ name, exe_extension }), + }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } } @@ -839,7 +846,10 @@ pub const Builder = struct { return name; } for (paths) |path| { - const full_path = try fs.path.join(self.allocator, &[_][]const u8{ path, self.fmt("{}{}", name, exe_extension) }); + const full_path = try fs.path.join(self.allocator, &[_][]const u8{ + path, + self.fmt("{}{}", .{ name, exe_extension }), + }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } } @@ -896,17 +906,17 @@ pub const Builder = struct { var code: u8 = undefined; return self.execAllowFail(argv, &code, .Inherit) catch |err| switch (err) { error.FileNotFound => { - warn("Unable to spawn the following command: file not found\n"); + warn("Unable to spawn the following command: file not found\n", .{}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, error.ExitCodeFailure => { - warn("The following command exited with error code {}:\n", code); + warn("The following command exited with error code {}:\n", .{code}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, error.ProcessTerminated => { - warn("The following command terminated unexpectedly:\n"); + warn("The following command terminated unexpectedly:\n", .{}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, @@ -1133,7 +1143,7 @@ pub const LibExeObjStep = struct { fn initExtraArgs(builder: *Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, is_dynamic: bool, ver: Version) LibExeObjStep { if (mem.indexOf(u8, name, "/") != null or mem.indexOf(u8, name, "\\") != null) { - panic("invalid name: '{}'. It looks like a file path, but it is supposed to be the library or application name.", name); + panic("invalid name: '{}'. It looks like a file path, but it is supposed to be the library or application name.", .{name}); } var self = LibExeObjStep{ .strip = false, @@ -1150,9 +1160,9 @@ pub const LibExeObjStep = struct { .step = Step.init(name, builder.allocator, make), .version = ver, .out_filename = undefined, - .out_h_filename = builder.fmt("{}.h", name), + .out_h_filename = builder.fmt("{}.h", .{name}), .out_lib_filename = undefined, - .out_pdb_filename = builder.fmt("{}.pdb", name), + .out_pdb_filename = builder.fmt("{}.pdb", .{name}), .major_only_filename = undefined, .name_only_filename = undefined, .packages = ArrayList(Pkg).init(builder.allocator), @@ -1186,36 +1196,48 @@ pub const LibExeObjStep = struct { fn computeOutFileNames(self: *LibExeObjStep) void { switch (self.kind) { .Obj => { - self.out_filename = self.builder.fmt("{}{}", self.name, self.target.oFileExt()); + self.out_filename = self.builder.fmt("{}{}", .{ self.name, self.target.oFileExt() }); }, .Exe => { - self.out_filename = self.builder.fmt("{}{}", self.name, self.target.exeFileExt()); + self.out_filename = self.builder.fmt("{}{}", .{ self.name, self.target.exeFileExt() }); }, .Test => { - self.out_filename = self.builder.fmt("test{}", self.target.exeFileExt()); + self.out_filename = self.builder.fmt("test{}", .{self.target.exeFileExt()}); }, .Lib => { if (!self.is_dynamic) { - self.out_filename = self.builder.fmt( - "{}{}{}", + self.out_filename = self.builder.fmt("{}{}{}", .{ self.target.libPrefix(), self.name, self.target.staticLibSuffix(), - ); + }); self.out_lib_filename = self.out_filename; } else { if (self.target.isDarwin()) { - self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", self.name, self.version.major, self.version.minor, self.version.patch); - self.major_only_filename = self.builder.fmt("lib{}.{d}.dylib", self.name, self.version.major); - self.name_only_filename = self.builder.fmt("lib{}.dylib", self.name); + self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", .{ + self.name, + self.version.major, + self.version.minor, + self.version.patch, + }); + self.major_only_filename = self.builder.fmt("lib{}.{d}.dylib", .{ + self.name, + self.version.major, + }); + self.name_only_filename = self.builder.fmt("lib{}.dylib", .{self.name}); self.out_lib_filename = self.out_filename; } else if (self.target.isWindows()) { - self.out_filename = self.builder.fmt("{}.dll", self.name); - self.out_lib_filename = self.builder.fmt("{}.lib", self.name); + self.out_filename = self.builder.fmt("{}.dll", .{self.name}); + self.out_lib_filename = self.builder.fmt("{}.lib", .{self.name}); } else { - self.out_filename = self.builder.fmt("lib{}.so.{d}.{d}.{d}", self.name, self.version.major, self.version.minor, self.version.patch); - self.major_only_filename = self.builder.fmt("lib{}.so.{d}", self.name, self.version.major); - self.name_only_filename = self.builder.fmt("lib{}.so", self.name); + self.out_filename = self.builder.fmt("lib{}.so.{d}.{d}.{d}", .{ + self.name, + self.version.major, + self.version.minor, + self.version.patch, + }); + self.major_only_filename = self.builder.fmt("lib{}.so.{d}", .{ self.name, self.version.major }); + self.name_only_filename = self.builder.fmt("lib{}.so", .{self.name}); self.out_lib_filename = self.out_filename; } } @@ -1268,7 +1290,7 @@ pub const LibExeObjStep = struct { // 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(exe.builder, exe.builder.fmt("run {}", exe.step.name)); + const run_step = RunStep.create(exe.builder, exe.builder.fmt("run {}", .{exe.step.name})); run_step.addArtifactArg(exe); if (exe.vcpkg_bin_path) |path| { @@ -1420,7 +1442,7 @@ pub const LibExeObjStep = struct { } else if (mem.eql(u8, tok, "-pthread")) { self.linkLibC(); } else if (self.builder.verbose) { - warn("Ignoring pkg-config flag '{}'\n", tok); + warn("Ignoring pkg-config flag '{}'\n", .{tok}); } } } @@ -1653,7 +1675,7 @@ pub const LibExeObjStep = struct { const builder = self.builder; if (self.root_src == null and self.link_objects.len == 0) { - warn("{}: linker needs 1 or more objects to link\n", self.step.name); + warn("{}: linker needs 1 or more objects to link\n", .{self.step.name}); return error.NeedAnObject; } @@ -1725,7 +1747,7 @@ pub const LibExeObjStep = struct { if (self.build_options_contents.len() > 0) { const build_options_file = try fs.path.join( builder.allocator, - &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", self.name) }, + &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) }, ); try std.io.writeFile(build_options_file, self.build_options_contents.toSliceConst()); try zig_args.append("--pkg-begin"); @@ -1780,13 +1802,13 @@ pub const LibExeObjStep = struct { if (self.kind == Kind.Lib and self.is_dynamic) { zig_args.append("--ver-major") catch unreachable; - zig_args.append(builder.fmt("{}", self.version.major)) catch unreachable; + zig_args.append(builder.fmt("{}", .{self.version.major})) catch unreachable; zig_args.append("--ver-minor") catch unreachable; - zig_args.append(builder.fmt("{}", self.version.minor)) catch unreachable; + zig_args.append(builder.fmt("{}", .{self.version.minor})) catch unreachable; zig_args.append("--ver-patch") catch unreachable; - zig_args.append(builder.fmt("{}", self.version.patch)) catch unreachable; + zig_args.append(builder.fmt("{}", .{self.version.patch})) catch unreachable; } if (self.is_dynamic) { try zig_args.append("-dynamic"); @@ -1811,7 +1833,7 @@ pub const LibExeObjStep = struct { if (self.target_glibc) |ver| { try zig_args.append("-target-glibc"); - try zig_args.append(builder.fmt("{}.{}.{}", ver.major, ver.minor, ver.patch)); + try zig_args.append(builder.fmt("{}.{}.{}", .{ ver.major, ver.minor, ver.patch })); } if (self.linker_script) |linker_script| { @@ -2079,7 +2101,7 @@ pub const RunStep = struct { } if (prev_path) |pp| { - const new_path = self.builder.fmt("{}" ++ [1]u8{fs.path.delimiter} ++ "{}", pp, search_path); + const new_path = self.builder.fmt("{}" ++ [1]u8{fs.path.delimiter} ++ "{}", .{ pp, search_path }); env_map.set(key, new_path) catch unreachable; } else { env_map.set(key, search_path) catch unreachable; @@ -2153,7 +2175,7 @@ const InstallArtifactStep = struct { const self = builder.allocator.create(Self) catch unreachable; self.* = Self{ .builder = builder, - .step = Step.init(builder.fmt("install {}", artifact.step.name), builder.allocator, make), + .step = Step.init(builder.fmt("install {}", .{artifact.step.name}), builder.allocator, make), .artifact = artifact, .dest_dir = switch (artifact.kind) { .Obj => unreachable, @@ -2219,7 +2241,7 @@ pub const InstallFileStep = struct { builder.pushInstalledFile(dir, dest_rel_path); return InstallFileStep{ .builder = builder, - .step = Step.init(builder.fmt("install {}", src_path), builder.allocator, make), + .step = Step.init(builder.fmt("install {}", .{src_path}), builder.allocator, make), .src_path = src_path, .dir = dir, .dest_rel_path = dest_rel_path, @@ -2253,7 +2275,7 @@ pub const InstallDirStep = struct { builder.pushInstalledFile(options.install_dir, options.install_subdir); return InstallDirStep{ .builder = builder, - .step = Step.init(builder.fmt("install {}/", options.source_dir), builder.allocator, make), + .step = Step.init(builder.fmt("install {}/", .{options.source_dir}), builder.allocator, make), .options = options, }; } @@ -2290,7 +2312,7 @@ pub const WriteFileStep = struct { pub fn init(builder: *Builder, file_path: []const u8, data: []const u8) WriteFileStep { return WriteFileStep{ .builder = builder, - .step = Step.init(builder.fmt("writefile {}", file_path), builder.allocator, make), + .step = Step.init(builder.fmt("writefile {}", .{file_path}), builder.allocator, make), .file_path = file_path, .data = data, }; @@ -2301,11 +2323,11 @@ pub const WriteFileStep = struct { const full_path = self.builder.pathFromRoot(self.file_path); const full_path_dir = fs.path.dirname(full_path) orelse "."; fs.makePath(self.builder.allocator, full_path_dir) catch |err| { - warn("unable to make path {}: {}\n", full_path_dir, @errorName(err)); + warn("unable to make path {}: {}\n", .{ full_path_dir, @errorName(err) }); return err; }; io.writeFile(full_path, self.data) catch |err| { - warn("unable to write {}: {}\n", full_path, @errorName(err)); + warn("unable to write {}: {}\n", .{ full_path, @errorName(err) }); return err; }; } @@ -2319,14 +2341,14 @@ pub const LogStep = struct { pub fn init(builder: *Builder, data: []const u8) LogStep { return LogStep{ .builder = builder, - .step = Step.init(builder.fmt("log {}", data), builder.allocator, make), + .step = Step.init(builder.fmt("log {}", .{data}), builder.allocator, make), .data = data, }; } fn make(step: *Step) anyerror!void { const self = @fieldParentPtr(LogStep, "step", step); - warn("{}", self.data); + warn("{}", .{self.data}); } }; @@ -2338,7 +2360,7 @@ pub const RemoveDirStep = struct { pub fn init(builder: *Builder, dir_path: []const u8) RemoveDirStep { return RemoveDirStep{ .builder = builder, - .step = Step.init(builder.fmt("RemoveDir {}", dir_path), builder.allocator, make), + .step = Step.init(builder.fmt("RemoveDir {}", .{dir_path}), builder.allocator, make), .dir_path = dir_path, }; } @@ -2348,7 +2370,7 @@ pub const RemoveDirStep = struct { const full_path = self.builder.pathFromRoot(self.dir_path); fs.deleteTree(full_path) catch |err| { - warn("Unable to remove {}: {}\n", full_path, @errorName(err)); + warn("Unable to remove {}: {}\n", .{ full_path, @errorName(err) }); return err; }; } @@ -2397,7 +2419,7 @@ fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_maj &[_][]const u8{ out_dir, filename_major_only }, ) catch unreachable; fs.atomicSymLink(allocator, out_basename, major_only_path) catch |err| { - warn("Unable to symlink {} -> {}\n", major_only_path, out_basename); + warn("Unable to symlink {} -> {}\n", .{ major_only_path, out_basename }); return err; }; // sym link for libfoo.so to libfoo.so.1 @@ -2406,7 +2428,7 @@ fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_maj &[_][]const u8{ out_dir, filename_name_only }, ) catch unreachable; fs.atomicSymLink(allocator, filename_major_only, name_only_path) catch |err| { - warn("Unable to symlink {} -> {}\n", name_only_path, filename_major_only); + warn("Unable to symlink {} -> {}\n", .{ name_only_path, filename_major_only }); return err; }; } diff --git a/lib/std/builtin.zig b/lib/std/builtin.zig index 35188b61e3..b3a80dc317 100644 --- a/lib/std/builtin.zig +++ b/lib/std/builtin.zig @@ -429,7 +429,7 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn } }, .wasi => { - std.debug.warn("{}", msg); + std.debug.warn("{}", .{msg}); _ = std.os.wasi.proc_raise(std.os.wasi.SIGABRT); unreachable; }, @@ -439,7 +439,7 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn }, else => { const first_trace_addr = @returnAddress(); - std.debug.panicExtra(error_return_trace, first_trace_addr, "{}", msg); + std.debug.panicExtra(error_return_trace, first_trace_addr, "{}", .{msg}); }, } } diff --git a/lib/std/crypto/benchmark.zig b/lib/std/crypto/benchmark.zig index 80615fd5c5..95761b7ba6 100644 --- a/lib/std/crypto/benchmark.zig +++ b/lib/std/crypto/benchmark.zig @@ -114,7 +114,7 @@ fn usage() void { \\ --seed [int] \\ --help \\ - ); + , .{}); } fn mode(comptime x: comptime_int) comptime_int { diff --git a/lib/std/debug.zig b/lib/std/debug.zig index e31f847d79..d93138fd4e 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -46,7 +46,7 @@ var stderr_file_out_stream: File.OutStream = undefined; var stderr_stream: ?*io.OutStream(File.WriteError) = null; var stderr_mutex = std.Mutex.init(); -pub fn warn(comptime fmt: []const u8, args: ...) void { +pub fn warn(comptime fmt: []const u8, args: var) void { const held = stderr_mutex.acquire(); defer held.release(); const stderr = getStderrStream(); @@ -92,15 +92,15 @@ fn wantTtyColor() bool { pub fn dumpCurrentStackTrace(start_addr: ?usize) void { const stderr = getStderrStream(); if (builtin.strip_debug_info) { - stderr.print("Unable to dump stack trace: debug info stripped\n") catch return; + stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return; + stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; return; }; writeCurrentStackTrace(stderr, debug_info, wantTtyColor(), start_addr) catch |err| { - stderr.print("Unable to dump stack trace: {}\n", @errorName(err)) catch return; + stderr.print("Unable to dump stack trace: {}\n", .{@errorName(err)}) catch return; return; }; } @@ -111,11 +111,11 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void { pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void { const stderr = getStderrStream(); if (builtin.strip_debug_info) { - stderr.print("Unable to dump stack trace: debug info stripped\n") catch return; + stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return; + stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; return; }; const tty_color = wantTtyColor(); @@ -184,15 +184,15 @@ pub fn captureStackTrace(first_address: ?usize, stack_trace: *builtin.StackTrace pub fn dumpStackTrace(stack_trace: builtin.StackTrace) void { const stderr = getStderrStream(); if (builtin.strip_debug_info) { - stderr.print("Unable to dump stack trace: debug info stripped\n") catch return; + stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return; + stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; return; }; writeStackTrace(stack_trace, stderr, getDebugInfoAllocator(), debug_info, wantTtyColor()) catch |err| { - stderr.print("Unable to dump stack trace: {}\n", @errorName(err)) catch return; + stderr.print("Unable to dump stack trace: {}\n", .{@errorName(err)}) catch return; return; }; } @@ -211,7 +211,7 @@ pub fn assert(ok: bool) void { if (!ok) unreachable; // assertion failure } -pub fn panic(comptime format: []const u8, args: ...) noreturn { +pub fn panic(comptime format: []const u8, args: var) noreturn { @setCold(true); // TODO: remove conditional once wasi / LLVM defines __builtin_return_address const first_trace_addr = if (builtin.os == .wasi) null else @returnAddress(); @@ -221,7 +221,7 @@ pub fn panic(comptime format: []const u8, args: ...) noreturn { /// TODO multithreaded awareness var panicking: u8 = 0; // TODO make this a bool -pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn { +pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: var) noreturn { @setCold(true); if (enable_segfault_handler) { @@ -376,13 +376,13 @@ fn printSourceAtAddressWindows(di: *DebugInfo, out_stream: var, relocated_addres } else { // we have no information to add to the address if (tty_color) { - try out_stream.print("???:?:?: "); + try out_stream.print("???:?:?: ", .{}); setTtyColor(TtyColor.Dim); - try out_stream.print("0x{x} in ??? (???)", relocated_address); + try out_stream.print("0x{x} in ??? (???)", .{relocated_address}); setTtyColor(TtyColor.Reset); - try out_stream.print("\n\n\n"); + try out_stream.print("\n\n\n", .{}); } else { - try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", relocated_address); + try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", .{relocated_address}); } return; }; @@ -509,18 +509,18 @@ fn printSourceAtAddressWindows(di: *DebugInfo, out_stream: var, relocated_addres if (tty_color) { setTtyColor(TtyColor.White); if (opt_line_info) |li| { - try out_stream.print("{}:{}:{}", li.file_name, li.line, li.column); + try out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column }); } else { - try out_stream.print("???:?:?"); + try out_stream.print("???:?:?", .{}); } setTtyColor(TtyColor.Reset); - try out_stream.print(": "); + try out_stream.print(": ", .{}); setTtyColor(TtyColor.Dim); - try out_stream.print("0x{x} in {} ({})", relocated_address, symbol_name, obj_basename); + try out_stream.print("0x{x} in {} ({})", .{ relocated_address, symbol_name, obj_basename }); setTtyColor(TtyColor.Reset); if (opt_line_info) |line_info| { - try out_stream.print("\n"); + try out_stream.print("\n", .{}); if (printLineFromFileAnyOs(out_stream, line_info)) { if (line_info.column == 0) { try out_stream.write("\n"); @@ -546,13 +546,24 @@ fn printSourceAtAddressWindows(di: *DebugInfo, out_stream: var, relocated_addres else => return err, } } else { - try out_stream.print("\n\n\n"); + try out_stream.print("\n\n\n", .{}); } } else { if (opt_line_info) |li| { - try out_stream.print("{}:{}:{}: 0x{x} in {} ({})\n\n\n", li.file_name, li.line, li.column, relocated_address, symbol_name, obj_basename); + try out_stream.print("{}:{}:{}: 0x{x} in {} ({})\n\n\n", .{ + li.file_name, + li.line, + li.column, + relocated_address, + symbol_name, + obj_basename, + }); } else { - try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", relocated_address, symbol_name, obj_basename); + try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", .{ + relocated_address, + symbol_name, + obj_basename, + }); } } } @@ -697,9 +708,9 @@ fn printSourceAtAddressMacOs(di: *DebugInfo, out_stream: var, address: usize, tt const symbol = machoSearchSymbols(di.symbols, adjusted_addr) orelse { if (tty_color) { - try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", address); + try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", .{address}); } else { - try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", address); + try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", .{address}); } return; }; @@ -723,9 +734,11 @@ fn printSourceAtAddressMacOs(di: *DebugInfo, out_stream: var, address: usize, tt } else |err| switch (err) { error.MissingDebugInfo, error.InvalidDebugInfo => { if (tty_color) { - try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n\n\n", address, symbol_name, compile_unit_name); + try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n\n\n", .{ + address, symbol_name, compile_unit_name, + }); } else { - try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", address, symbol_name, compile_unit_name); + try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", .{ address, symbol_name, compile_unit_name }); } }, else => return err, @@ -746,15 +759,14 @@ fn printLineInfo( comptime printLineFromFile: var, ) !void { if (tty_color) { - try out_stream.print( - WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n", + try out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n", .{ line_info.file_name, line_info.line, line_info.column, address, symbol_name, compile_unit_name, - ); + }); if (printLineFromFile(out_stream, line_info)) { if (line_info.column == 0) { try out_stream.write("\n"); @@ -772,15 +784,14 @@ fn printLineInfo( else => return err, } } else { - try out_stream.print( - "{}:{}:{}: 0x{x} in {} ({})\n", + try out_stream.print("{}:{}:{}: 0x{x} in {} ({})\n", .{ line_info.file_name, line_info.line, line_info.column, address, symbol_name, compile_unit_name, - ); + }); } } @@ -1226,9 +1237,9 @@ pub const DwarfInfo = struct { ) !void { const compile_unit = self.findCompileUnit(address) catch { if (tty_color) { - try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", address); + try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", .{address}); } else { - try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", address); + try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", .{address}); } return; }; @@ -1248,9 +1259,11 @@ pub const DwarfInfo = struct { } else |err| switch (err) { error.MissingDebugInfo, error.InvalidDebugInfo => { if (tty_color) { - try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n\n\n", address, compile_unit_name); + try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n\n\n", .{ + address, compile_unit_name, + }); } else { - try out_stream.print("???:?:?: 0x{x} in ??? ({})\n\n\n", address, compile_unit_name); + try out_stream.print("???:?:?: 0x{x} in ??? ({})\n\n\n", .{ address, compile_unit_name }); } }, else => return err, @@ -2416,7 +2429,7 @@ extern fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *con resetSegfaultHandler(); const addr = @ptrToInt(info.fields.sigfault.addr); - std.debug.warn("Segmentation fault at address 0x{x}\n", addr); + std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr}); switch (builtin.arch) { .i386 => { @@ -2468,7 +2481,7 @@ pub fn dumpStackPointerAddr(prefix: []const u8) void { const sp = asm ("" : [argc] "={rsp}" (-> usize) ); - std.debug.warn("{} sp = 0x{x}\n", prefix, sp); + std.debug.warn("{} sp = 0x{x}\n", .{ prefix, sp }); } // Reference everything so it gets tested. diff --git a/lib/std/event/channel.zig b/lib/std/event/channel.zig index 96cfd706be..2bcf6a4c50 100644 --- a/lib/std/event/channel.zig +++ b/lib/std/event/channel.zig @@ -294,14 +294,14 @@ test "std.event.Channel wraparound" { const channel_size = 2; - var buf : [channel_size]i32 = undefined; + var buf: [channel_size]i32 = undefined; var channel: Channel(i32) = undefined; channel.init(&buf); defer channel.deinit(); // add items to channel and pull them out until // the buffer wraps around, make sure it doesn't crash. - var result : i32 = undefined; + var result: i32 = undefined; channel.put(5); testing.expectEqual(@as(i32, 5), channel.get()); channel.put(6); diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index fdd746dfcc..7870979abb 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -293,7 +293,7 @@ pub fn LinearFifo( pub usingnamespace if (T == u8) struct { - pub fn print(self: *Self, comptime format: []const u8, args: ...) !void { + pub fn print(self: *Self, comptime format: []const u8, args: var) !void { return std.fmt.format(self, error{OutOfMemory}, Self.write, format, args); } } @@ -407,7 +407,7 @@ test "LinearFifo(u8, .Dynamic)" { fifo.shrink(0); { - try fifo.print("{}, {}!", "Hello", "World"); + try fifo.print("{}, {}!", .{ "Hello", "World" }); var result: [30]u8 = undefined; testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]); testing.expectEqual(@as(usize, 0), fifo.readableLength()); diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index da0cfd4318..a0871d52a6 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -91,10 +91,12 @@ pub fn format( comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, - args: ..., + args: var, ) Errors!void { const ArgSetType = @IntType(false, 32); - if (args.len > ArgSetType.bit_count) { + const args_fields = std.meta.fields(@typeOf(args)); + const args_len = args_fields.len; + if (args_len > ArgSetType.bit_count) { @compileError("32 arguments max are supported per format call"); } @@ -158,14 +160,14 @@ pub fn format( maybe_pos_arg.? += c - '0'; specifier_start = i + 1; - if (maybe_pos_arg.? >= args.len) { + if (maybe_pos_arg.? >= args_len) { @compileError("Positional value refers to non-existent argument"); } }, '}' => { const arg_to_print = comptime nextArg(&used_pos_args, maybe_pos_arg, &next_arg); - if (arg_to_print >= args.len) { + if (arg_to_print >= args_len) { @compileError("Too few arguments"); } @@ -302,7 +304,7 @@ pub fn format( used_pos_args |= 1 << i; } - if (@popCount(ArgSetType, used_pos_args) != args.len) { + if (@popCount(ArgSetType, used_pos_args) != args_len) { @compileError("Unused arguments"); } if (state != State.Start) { @@ -389,7 +391,7 @@ pub fn formatType( } try output(context, " }"); } else { - try format(context, Errors, output, "@{x}", @ptrToInt(&value)); + try format(context, Errors, output, "@{x}", .{@ptrToInt(&value)}); } }, .Struct => { @@ -421,12 +423,12 @@ pub fn formatType( if (info.child == u8) { return formatText(value, fmt, options, context, Errors, output); } - return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)); + return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }); }, builtin.TypeId.Enum, builtin.TypeId.Union, builtin.TypeId.Struct => { return formatType(value.*, fmt, options, context, Errors, output, max_depth); }, - else => return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)), + else => return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }), }, .Many => { if (ptr_info.child == u8) { @@ -435,7 +437,7 @@ pub fn formatType( return formatText(value[0..len], fmt, options, context, Errors, output); } } - return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)); + return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }); }, .Slice => { if (fmt.len > 0 and ((fmt[0] == 'x') or (fmt[0] == 'X'))) { @@ -444,10 +446,10 @@ pub fn formatType( if (ptr_info.child == u8) { return formatText(value, fmt, options, context, Errors, output); } - return format(context, Errors, output, "{}@{x}", @typeName(ptr_info.child), @ptrToInt(value.ptr)); + return format(context, Errors, output, "{}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value.ptr) }); }, .C => { - return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)); + return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }); }, }, .Array => |info| { @@ -465,7 +467,7 @@ pub fn formatType( return formatType(@as(Slice, &value), fmt, options, context, Errors, output, max_depth); }, .Fn => { - return format(context, Errors, output, "{}@{x}", @typeName(T), @ptrToInt(value)); + return format(context, Errors, output, "{}@{x}", .{ @typeName(T), @ptrToInt(value) }); }, else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"), } @@ -1113,7 +1115,7 @@ pub const BufPrintError = error{ /// As much as possible was written to the buffer, but it was too small to fit all the printed bytes. BufferTooSmall, }; -pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) BufPrintError![]u8 { +pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![]u8 { var context = BufPrintContext{ .remaining = buf }; try format(&context, BufPrintError, bufPrintWrite, fmt, args); return buf[0 .. buf.len - context.remaining.len]; @@ -1121,7 +1123,7 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) BufPrintError![] pub const AllocPrintError = error{OutOfMemory}; -pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: ...) AllocPrintError![]u8 { +pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 { var size: usize = 0; format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {}; const buf = try allocator.alloc(u8, size); @@ -1173,46 +1175,46 @@ test "parse unsigned comptime" { test "optional" { { const value: ?i32 = 1234; - try testFmt("optional: 1234\n", "optional: {}\n", value); + try testFmt("optional: 1234\n", "optional: {}\n", .{value}); } { const value: ?i32 = null; - try testFmt("optional: null\n", "optional: {}\n", value); + try testFmt("optional: null\n", "optional: {}\n", .{value}); } } test "error" { { const value: anyerror!i32 = 1234; - try testFmt("error union: 1234\n", "error union: {}\n", value); + try testFmt("error union: 1234\n", "error union: {}\n", .{value}); } { const value: anyerror!i32 = error.InvalidChar; - try testFmt("error union: error.InvalidChar\n", "error union: {}\n", value); + try testFmt("error union: error.InvalidChar\n", "error union: {}\n", .{value}); } } test "int.small" { { const value: u3 = 0b101; - try testFmt("u3: 5\n", "u3: {}\n", value); + try testFmt("u3: 5\n", "u3: {}\n", .{value}); } } test "int.specifier" { { const value: u8 = 'a'; - try testFmt("u8: a\n", "u8: {c}\n", value); + try testFmt("u8: a\n", "u8: {c}\n", .{value}); } { const value: u8 = 0b1100; - try testFmt("u8: 0b1100\n", "u8: 0b{b}\n", value); + try testFmt("u8: 0b1100\n", "u8: 0b{b}\n", .{value}); } } test "int.padded" { - try testFmt("u8: ' 1'", "u8: '{:4}'", @as(u8, 1)); - try testFmt("u8: 'xxx1'", "u8: '{:x<4}'", @as(u8, 1)); + try testFmt("u8: ' 1'", "u8: '{:4}'", .{@as(u8, 1)}); + try testFmt("u8: 'xxx1'", "u8: '{:x<4}'", .{@as(u8, 1)}); } test "buffer" { @@ -1238,14 +1240,14 @@ test "buffer" { test "array" { { const value: [3]u8 = "abc".*; - try testFmt("array: abc\n", "array: {}\n", value); - try testFmt("array: abc\n", "array: {}\n", &value); + try testFmt("array: abc\n", "array: {}\n", .{value}); + try testFmt("array: abc\n", "array: {}\n", .{&value}); var buf: [100]u8 = undefined; try testFmt( - try bufPrint(buf[0..], "array: [3]u8@{x}\n", @ptrToInt(&value)), + try bufPrint(buf[0..], "array: [3]u8@{x}\n", .{@ptrToInt(&value)}), "array: {*}\n", - &value, + .{&value}, ); } } @@ -1253,36 +1255,36 @@ test "array" { test "slice" { { const value: []const u8 = "abc"; - try testFmt("slice: abc\n", "slice: {}\n", value); + try testFmt("slice: abc\n", "slice: {}\n", .{value}); } { const value = @intToPtr([*]const []const u8, 0xdeadbeef)[0..0]; - try testFmt("slice: []const u8@deadbeef\n", "slice: {}\n", value); + try testFmt("slice: []const u8@deadbeef\n", "slice: {}\n", .{value}); } - try testFmt("buf: Test \n", "buf: {s:5}\n", "Test"); - try testFmt("buf: Test\n Other text", "buf: {s}\n Other text", "Test"); + try testFmt("buf: Test \n", "buf: {s:5}\n", .{"Test"}); + try testFmt("buf: Test\n Other text", "buf: {s}\n Other text", .{"Test"}); } test "pointer" { { const value = @intToPtr(*i32, 0xdeadbeef); - try testFmt("pointer: i32@deadbeef\n", "pointer: {}\n", value); - try testFmt("pointer: i32@deadbeef\n", "pointer: {*}\n", value); + try testFmt("pointer: i32@deadbeef\n", "pointer: {}\n", .{value}); + try testFmt("pointer: i32@deadbeef\n", "pointer: {*}\n", .{value}); } { const value = @intToPtr(fn () void, 0xdeadbeef); - try testFmt("pointer: fn() void@deadbeef\n", "pointer: {}\n", value); + try testFmt("pointer: fn() void@deadbeef\n", "pointer: {}\n", .{value}); } { const value = @intToPtr(fn () void, 0xdeadbeef); - try testFmt("pointer: fn() void@deadbeef\n", "pointer: {}\n", value); + try testFmt("pointer: fn() void@deadbeef\n", "pointer: {}\n", .{value}); } } test "cstr" { - try testFmt("cstr: Test C\n", "cstr: {s}\n", "Test C"); - try testFmt("cstr: Test C \n", "cstr: {s:10}\n", "Test C"); + try testFmt("cstr: Test C\n", "cstr: {s}\n", .{"Test C"}); + try testFmt("cstr: Test C \n", "cstr: {s:10}\n", .{"Test C"}); } test "filesize" { @@ -1290,8 +1292,8 @@ test "filesize" { // TODO https://github.com/ziglang/zig/issues/3289 return error.SkipZigTest; } - try testFmt("file size: 63MiB\n", "file size: {Bi}\n", @as(usize, 63 * 1024 * 1024)); - try testFmt("file size: 66.06MB\n", "file size: {B:.2}\n", @as(usize, 63 * 1024 * 1024)); + try testFmt("file size: 63MiB\n", "file size: {Bi}\n", .{@as(usize, 63 * 1024 * 1024)}); + try testFmt("file size: 66.06MB\n", "file size: {B:.2}\n", .{@as(usize, 63 * 1024 * 1024)}); } test "struct" { @@ -1300,8 +1302,8 @@ test "struct" { field: u8, }; const value = Struct{ .field = 42 }; - try testFmt("struct: Struct{ .field = 42 }\n", "struct: {}\n", value); - try testFmt("struct: Struct{ .field = 42 }\n", "struct: {}\n", &value); + try testFmt("struct: Struct{ .field = 42 }\n", "struct: {}\n", .{value}); + try testFmt("struct: Struct{ .field = 42 }\n", "struct: {}\n", .{&value}); } { const Struct = struct { @@ -1309,7 +1311,7 @@ test "struct" { b: u1, }; const value = Struct{ .a = 0, .b = 1 }; - try testFmt("struct: Struct{ .a = 0, .b = 1 }\n", "struct: {}\n", value); + try testFmt("struct: Struct{ .a = 0, .b = 1 }\n", "struct: {}\n", .{value}); } } @@ -1319,8 +1321,8 @@ test "enum" { Two, }; const value = Enum.Two; - try testFmt("enum: Enum.Two\n", "enum: {}\n", value); - try testFmt("enum: Enum.Two\n", "enum: {}\n", &value); + try testFmt("enum: Enum.Two\n", "enum: {}\n", .{value}); + try testFmt("enum: Enum.Two\n", "enum: {}\n", .{&value}); } test "float.scientific" { @@ -1328,10 +1330,10 @@ test "float.scientific" { // TODO https://github.com/ziglang/zig/issues/3289 return error.SkipZigTest; } - try testFmt("f32: 1.34000003e+00", "f32: {e}", @as(f32, 1.34)); - try testFmt("f32: 1.23400001e+01", "f32: {e}", @as(f32, 12.34)); - try testFmt("f64: -1.234e+11", "f64: {e}", @as(f64, -12.34e10)); - try testFmt("f64: 9.99996e-40", "f64: {e}", @as(f64, 9.999960e-40)); + try testFmt("f32: 1.34000003e+00", "f32: {e}", .{@as(f32, 1.34)}); + try testFmt("f32: 1.23400001e+01", "f32: {e}", .{@as(f32, 12.34)}); + try testFmt("f64: -1.234e+11", "f64: {e}", .{@as(f64, -12.34e10)}); + try testFmt("f64: 9.99996e-40", "f64: {e}", .{@as(f64, 9.999960e-40)}); } test "float.scientific.precision" { @@ -1339,12 +1341,12 @@ test "float.scientific.precision" { // TODO https://github.com/ziglang/zig/issues/3289 return error.SkipZigTest; } - try testFmt("f64: 1.40971e-42", "f64: {e:.5}", @as(f64, 1.409706e-42)); - try testFmt("f64: 1.00000e-09", "f64: {e:.5}", @as(f64, @bitCast(f32, @as(u32, 814313563)))); - try testFmt("f64: 7.81250e-03", "f64: {e:.5}", @as(f64, @bitCast(f32, @as(u32, 1006632960)))); + try testFmt("f64: 1.40971e-42", "f64: {e:.5}", .{@as(f64, 1.409706e-42)}); + try testFmt("f64: 1.00000e-09", "f64: {e:.5}", .{@as(f64, @bitCast(f32, @as(u32, 814313563)))}); + try testFmt("f64: 7.81250e-03", "f64: {e:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1006632960)))}); // libc rounds 1.000005e+05 to 1.00000e+05 but zig does 1.00001e+05. // In fact, libc doesn't round a lot of 5 cases up when one past the precision point. - try testFmt("f64: 1.00001e+05", "f64: {e:.5}", @as(f64, @bitCast(f32, @as(u32, 1203982400)))); + try testFmt("f64: 1.00001e+05", "f64: {e:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1203982400)))}); } test "float.special" { @@ -1352,14 +1354,14 @@ test "float.special" { // TODO https://github.com/ziglang/zig/issues/3289 return error.SkipZigTest; } - try testFmt("f64: nan", "f64: {}", math.nan_f64); + try testFmt("f64: nan", "f64: {}", .{math.nan_f64}); // negative nan is not defined by IEE 754, // and ARM thus normalizes it to positive nan if (builtin.arch != builtin.Arch.arm) { - try testFmt("f64: -nan", "f64: {}", -math.nan_f64); + try testFmt("f64: -nan", "f64: {}", .{-math.nan_f64}); } - try testFmt("f64: inf", "f64: {}", math.inf_f64); - try testFmt("f64: -inf", "f64: {}", -math.inf_f64); + try testFmt("f64: inf", "f64: {}", .{math.inf_f64}); + try testFmt("f64: -inf", "f64: {}", .{-math.inf_f64}); } test "float.decimal" { @@ -1367,21 +1369,21 @@ test "float.decimal" { // TODO https://github.com/ziglang/zig/issues/3289 return error.SkipZigTest; } - try testFmt("f64: 152314000000000000000000000000", "f64: {d}", @as(f64, 1.52314e+29)); - try testFmt("f32: 1.1", "f32: {d:.1}", @as(f32, 1.1234)); - try testFmt("f32: 1234.57", "f32: {d:.2}", @as(f32, 1234.567)); + try testFmt("f64: 152314000000000000000000000000", "f64: {d}", .{@as(f64, 1.52314e+29)}); + try testFmt("f32: 1.1", "f32: {d:.1}", .{@as(f32, 1.1234)}); + try testFmt("f32: 1234.57", "f32: {d:.2}", .{@as(f32, 1234.567)}); // -11.1234 is converted to f64 -11.12339... internally (errol3() function takes f64). // -11.12339... is rounded back up to -11.1234 - try testFmt("f32: -11.1234", "f32: {d:.4}", @as(f32, -11.1234)); - try testFmt("f32: 91.12345", "f32: {d:.5}", @as(f32, 91.12345)); - try testFmt("f64: 91.1234567890", "f64: {d:.10}", @as(f64, 91.12345678901235)); - try testFmt("f64: 0.00000", "f64: {d:.5}", @as(f64, 0.0)); - try testFmt("f64: 6", "f64: {d:.0}", @as(f64, 5.700)); - try testFmt("f64: 10.0", "f64: {d:.1}", @as(f64, 9.999)); - try testFmt("f64: 1.000", "f64: {d:.3}", @as(f64, 1.0)); - try testFmt("f64: 0.00030000", "f64: {d:.8}", @as(f64, 0.0003)); - try testFmt("f64: 0.00000", "f64: {d:.5}", @as(f64, 1.40130e-45)); - try testFmt("f64: 0.00000", "f64: {d:.5}", @as(f64, 9.999960e-40)); + try testFmt("f32: -11.1234", "f32: {d:.4}", .{@as(f32, -11.1234)}); + try testFmt("f32: 91.12345", "f32: {d:.5}", .{@as(f32, 91.12345)}); + try testFmt("f64: 91.1234567890", "f64: {d:.10}", .{@as(f64, 91.12345678901235)}); + try testFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 0.0)}); + try testFmt("f64: 6", "f64: {d:.0}", .{@as(f64, 5.700)}); + try testFmt("f64: 10.0", "f64: {d:.1}", .{@as(f64, 9.999)}); + try testFmt("f64: 1.000", "f64: {d:.3}", .{@as(f64, 1.0)}); + try testFmt("f64: 0.00030000", "f64: {d:.8}", .{@as(f64, 0.0003)}); + try testFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 1.40130e-45)}); + try testFmt("f64: 0.00000", "f64: {d:.5}", .{@as(f64, 9.999960e-40)}); } test "float.libc.sanity" { @@ -1389,22 +1391,22 @@ test "float.libc.sanity" { // TODO https://github.com/ziglang/zig/issues/3289 return error.SkipZigTest; } - try testFmt("f64: 0.00001", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 916964781)))); - try testFmt("f64: 0.00001", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 925353389)))); - try testFmt("f64: 0.10000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1036831278)))); - try testFmt("f64: 1.00000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1065353133)))); - try testFmt("f64: 10.00000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1092616192)))); + try testFmt("f64: 0.00001", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 916964781)))}); + try testFmt("f64: 0.00001", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 925353389)))}); + try testFmt("f64: 0.10000", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1036831278)))}); + try testFmt("f64: 1.00000", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1065353133)))}); + try testFmt("f64: 10.00000", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1092616192)))}); // libc differences // // This is 0.015625 exactly according to gdb. We thus round down, // however glibc rounds up for some reason. This occurs for all // floats of the form x.yyyy25 on a precision point. - try testFmt("f64: 0.01563", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1015021568)))); + try testFmt("f64: 0.01563", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1015021568)))}); // errol3 rounds to ... 630 but libc rounds to ...632. Grisu3 // also rounds to 630 so I'm inclined to believe libc is not // optimal here. - try testFmt("f64: 18014400656965630.00000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1518338049)))); + try testFmt("f64: 18014400656965630.00000", "f64: {d:.5}", .{@as(f64, @bitCast(f32, @as(u32, 1518338049)))}); } test "custom" { @@ -1422,9 +1424,9 @@ test "custom" { output: fn (@typeOf(context), []const u8) Errors!void, ) Errors!void { if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "p")) { - return std.fmt.format(context, Errors, output, "({d:.3},{d:.3})", self.x, self.y); + return std.fmt.format(context, Errors, output, "({d:.3},{d:.3})", .{ self.x, self.y }); } else if (comptime std.mem.eql(u8, fmt, "d")) { - return std.fmt.format(context, Errors, output, "{d:.3}x{d:.3}", self.x, self.y); + return std.fmt.format(context, Errors, output, "{d:.3}x{d:.3}", .{ self.x, self.y }); } else { @compileError("Unknown format character: '" ++ fmt ++ "'"); } @@ -1436,12 +1438,12 @@ test "custom" { .x = 10.2, .y = 2.22, }; - try testFmt("point: (10.200,2.220)\n", "point: {}\n", &value); - try testFmt("dim: 10.200x2.220\n", "dim: {d}\n", &value); + try testFmt("point: (10.200,2.220)\n", "point: {}\n", .{&value}); + try testFmt("dim: 10.200x2.220\n", "dim: {d}\n", .{&value}); // same thing but not passing a pointer - try testFmt("point: (10.200,2.220)\n", "point: {}\n", value); - try testFmt("dim: 10.200x2.220\n", "dim: {d}\n", value); + try testFmt("point: (10.200,2.220)\n", "point: {}\n", .{value}); + try testFmt("dim: 10.200x2.220\n", "dim: {d}\n", .{value}); } test "struct" { @@ -1455,7 +1457,7 @@ test "struct" { .b = error.Unused, }; - try testFmt("S{ .a = 456, .b = error.Unused }", "{}", inst); + try testFmt("S{ .a = 456, .b = error.Unused }", "{}", .{inst}); } test "union" { @@ -1478,13 +1480,13 @@ test "union" { const uu_inst = UU{ .int = 456 }; const eu_inst = EU{ .float = 321.123 }; - try testFmt("TU{ .int = 123 }", "{}", tu_inst); + try testFmt("TU{ .int = 123 }", "{}", .{tu_inst}); var buf: [100]u8 = undefined; - const uu_result = try bufPrint(buf[0..], "{}", uu_inst); + const uu_result = try bufPrint(buf[0..], "{}", .{uu_inst}); std.testing.expect(mem.eql(u8, uu_result[0..3], "UU@")); - const eu_result = try bufPrint(buf[0..], "{}", eu_inst); + const eu_result = try bufPrint(buf[0..], "{}", .{eu_inst}); std.testing.expect(mem.eql(u8, uu_result[0..3], "EU@")); } @@ -1497,7 +1499,7 @@ test "enum" { const inst = E.Two; - try testFmt("E.Two", "{}", inst); + try testFmt("E.Two", "{}", .{inst}); } test "struct.self-referential" { @@ -1511,7 +1513,7 @@ test "struct.self-referential" { }; inst.a = &inst; - try testFmt("S{ .a = S{ .a = S{ .a = S{ ... } } } }", "{}", inst); + try testFmt("S{ .a = S{ .a = S{ .a = S{ ... } } } }", "{}", .{inst}); } test "struct.zero-size" { @@ -1526,30 +1528,30 @@ test "struct.zero-size" { const a = A{}; const b = B{ .a = a, .c = 0 }; - try testFmt("B{ .a = A{ }, .c = 0 }", "{}", b); + try testFmt("B{ .a = A{ }, .c = 0 }", "{}", .{b}); } test "bytes.hex" { const some_bytes = "\xCA\xFE\xBA\xBE"; - try testFmt("lowercase: cafebabe\n", "lowercase: {x}\n", some_bytes); - try testFmt("uppercase: CAFEBABE\n", "uppercase: {X}\n", some_bytes); + try testFmt("lowercase: cafebabe\n", "lowercase: {x}\n", .{some_bytes}); + try testFmt("uppercase: CAFEBABE\n", "uppercase: {X}\n", .{some_bytes}); //Test Slices - try testFmt("uppercase: CAFE\n", "uppercase: {X}\n", some_bytes[0..2]); - try testFmt("lowercase: babe\n", "lowercase: {x}\n", some_bytes[2..]); + try testFmt("uppercase: CAFE\n", "uppercase: {X}\n", .{some_bytes[0..2]}); + try testFmt("lowercase: babe\n", "lowercase: {x}\n", .{some_bytes[2..]}); const bytes_with_zeros = "\x00\x0E\xBA\xBE"; - try testFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", bytes_with_zeros); + try testFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{bytes_with_zeros}); } -fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void { +fn testFmt(expected: []const u8, comptime template: []const u8, args: var) !void { var buf: [100]u8 = undefined; const result = try bufPrint(buf[0..], template, args); if (mem.eql(u8, result, expected)) return; - std.debug.warn("\n====== expected this output: =========\n"); - std.debug.warn("{}", expected); - std.debug.warn("\n======== instead found this: =========\n"); - std.debug.warn("{}", result); - std.debug.warn("\n======================================\n"); + std.debug.warn("\n====== expected this output: =========\n", .{}); + std.debug.warn("{}", .{expected}); + std.debug.warn("\n======== instead found this: =========\n", .{}); + std.debug.warn("{}", .{result}); + std.debug.warn("\n======================================\n", .{}); return error.TestFailed; } @@ -1602,7 +1604,7 @@ test "hexToBytes" { const test_hex_str = "909A312BB12ED1F819B3521AC4C1E896F2160507FFC1C8381E3B07BB16BD1706"; var pb: [32]u8 = undefined; try hexToBytes(pb[0..], test_hex_str); - try testFmt(test_hex_str, "{X}", pb); + try testFmt(test_hex_str, "{X}", .{pb}); } test "formatIntValue with comptime_int" { @@ -1628,7 +1630,7 @@ test "formatType max_depth" { output: fn (@typeOf(context), []const u8) Errors!void, ) Errors!void { if (fmt.len == 0) { - return std.fmt.format(context, Errors, output, "({d:.3},{d:.3})", self.x, self.y); + return std.fmt.format(context, Errors, output, "({d:.3},{d:.3})", .{ self.x, self.y }); } else { @compileError("Unknown format string: '" ++ fmt ++ "'"); } @@ -1680,17 +1682,17 @@ test "formatType max_depth" { } test "positional" { - try testFmt("2 1 0", "{2} {1} {0}", @as(usize, 0), @as(usize, 1), @as(usize, 2)); - try testFmt("2 1 0", "{2} {1} {}", @as(usize, 0), @as(usize, 1), @as(usize, 2)); - try testFmt("0 0", "{0} {0}", @as(usize, 0)); - try testFmt("0 1", "{} {1}", @as(usize, 0), @as(usize, 1)); - try testFmt("1 0 0 1", "{1} {} {0} {}", @as(usize, 0), @as(usize, 1)); + try testFmt("2 1 0", "{2} {1} {0}", .{ @as(usize, 0), @as(usize, 1), @as(usize, 2) }); + try testFmt("2 1 0", "{2} {1} {}", .{ @as(usize, 0), @as(usize, 1), @as(usize, 2) }); + try testFmt("0 0", "{0} {0}", .{@as(usize, 0)}); + try testFmt("0 1", "{} {1}", .{ @as(usize, 0), @as(usize, 1) }); + try testFmt("1 0 0 1", "{1} {} {0} {}", .{ @as(usize, 0), @as(usize, 1) }); } test "positional with specifier" { - try testFmt("10.0", "{0d:.1}", @as(f64, 9.999)); + try testFmt("10.0", "{0d:.1}", .{@as(f64, 9.999)}); } test "positional/alignment/width/precision" { - try testFmt("10.0", "{0d: >3.1}", @as(f64, 9.999)); + try testFmt("10.0", "{0d: >3.1}", .{@as(f64, 9.999)}); } diff --git a/lib/std/hash/benchmark.zig b/lib/std/hash/benchmark.zig index 4553d928ec..f1b39bff64 100644 --- a/lib/std/hash/benchmark.zig +++ b/lib/std/hash/benchmark.zig @@ -164,7 +164,7 @@ fn usage() void { \\ --iterative-only \\ --help \\ - ); + , .{}); } fn mode(comptime x: comptime_int) comptime_int { diff --git a/lib/std/http/headers.zig b/lib/std/http/headers.zig index 1d573aebc0..7cac6648de 100644 --- a/lib/std/http/headers.zig +++ b/lib/std/http/headers.zig @@ -610,5 +610,5 @@ test "Headers.format" { \\foo: bar \\cookie: somevalue \\ - , try std.fmt.bufPrint(buf[0..], "{}", h)); + , try std.fmt.bufPrint(buf[0..], "{}", .{h})); } diff --git a/lib/std/io.zig b/lib/std/io.zig index 238f7eb0f0..68c147a33c 100644 --- a/lib/std/io.zig +++ b/lib/std/io.zig @@ -492,7 +492,7 @@ test "io.SliceOutStream" { var slice_stream = SliceOutStream.init(buf[0..]); const stream = &slice_stream.stream; - try stream.print("{}{}!", "Hello", "World"); + try stream.print("{}{}!", .{ "Hello", "World" }); testing.expectEqualSlices(u8, "HelloWorld!", slice_stream.getWritten()); } diff --git a/lib/std/io/out_stream.zig b/lib/std/io/out_stream.zig index 77698b333c..b8f5db6fff 100644 --- a/lib/std/io/out_stream.zig +++ b/lib/std/io/out_stream.zig @@ -35,7 +35,7 @@ pub fn OutStream(comptime WriteError: type) type { } } - pub fn print(self: *Self, comptime format: []const u8, args: ...) Error!void { + pub fn print(self: *Self, comptime format: []const u8, args: var) Error!void { return std.fmt.format(self, Error, self.writeFn, format, args); } diff --git a/lib/std/io/test.zig b/lib/std/io/test.zig index 5b189cbe5a..92259fd6e9 100644 --- a/lib/std/io/test.zig +++ b/lib/std/io/test.zig @@ -27,9 +27,9 @@ test "write a file, read it, then delete it" { var file_out_stream = file.outStream(); var buf_stream = io.BufferedOutStream(File.WriteError).init(&file_out_stream.stream); const st = &buf_stream.stream; - try st.print("begin"); + try st.print("begin", .{}); try st.write(data[0..]); - try st.print("end"); + try st.print("end", .{}); try buf_stream.flush(); } @@ -72,7 +72,7 @@ test "BufferOutStream" { const x: i32 = 42; const y: i32 = 1234; - try buf_stream.print("x: {}\ny: {}\n", x, y); + try buf_stream.print("x: {}\ny: {}\n", .{ x, y }); expect(mem.eql(u8, buffer.toSlice(), "x: 42\ny: 1234\n")); } @@ -605,7 +605,7 @@ test "c out stream" { } const out_stream = &io.COutStream.init(out_file).stream; - try out_stream.print("hi: {}\n", @as(i32, 123)); + try out_stream.print("hi: {}\n", .{@as(i32, 123)}); } test "File seek ops" { diff --git a/lib/std/json/write_stream.zig b/lib/std/json/write_stream.zig index fbf860965f..7cff613dad 100644 --- a/lib/std/json/write_stream.zig +++ b/lib/std/json/write_stream.zig @@ -158,24 +158,24 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { switch (@typeInfo(@typeOf(value))) { .Int => |info| { if (info.bits < 53) { - try self.stream.print("{}", value); + try self.stream.print("{}", .{value}); self.popState(); return; } if (value < 4503599627370496 and (!info.is_signed or value > -4503599627370496)) { - try self.stream.print("{}", value); + try self.stream.print("{}", .{value}); self.popState(); return; } }, .Float => if (@floatCast(f64, value) == value) { - try self.stream.print("{}", value); + try self.stream.print("{}", .{value}); self.popState(); return; }, else => {}, } - try self.stream.print("\"{}\"", value); + try self.stream.print("\"{}\"", .{value}); self.popState(); } diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index 5c84dc462b..0d0b186332 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -180,9 +180,9 @@ pub const Int = struct { pub fn dump(self: Int) void { for (self.limbs) |limb| { - debug.warn("{x} ", limb); + debug.warn("{x} ", .{limb}); } - debug.warn("\n"); + debug.warn("\n", .{}); } /// Negate the sign of an Int. diff --git a/lib/std/net.zig b/lib/std/net.zig index 6091564a93..4484821f99 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -277,32 +277,24 @@ pub const Address = extern union { os.AF_INET => { const port = mem.bigToNative(u16, self.in.port); const bytes = @ptrCast(*const [4]u8, &self.in.addr); - try std.fmt.format( - context, - Errors, - output, - "{}.{}.{}.{}:{}", + try std.fmt.format(context, Errors, output, "{}.{}.{}.{}:{}", .{ bytes[0], bytes[1], bytes[2], bytes[3], port, - ); + }); }, os.AF_INET6 => { const port = mem.bigToNative(u16, self.in6.port); if (mem.eql(u8, self.in6.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) { - try std.fmt.format( - context, - Errors, - output, - "[::ffff:{}.{}.{}.{}]:{}", + try std.fmt.format(context, Errors, output, "[::ffff:{}.{}.{}.{}]:{}", .{ self.in6.addr[12], self.in6.addr[13], self.in6.addr[14], self.in6.addr[15], port, - ); + }); return; } const big_endian_parts = @ptrCast(*align(1) const [8]u16, &self.in6.addr); @@ -327,19 +319,19 @@ pub const Address = extern union { } continue; } - try std.fmt.format(context, Errors, output, "{x}", native_endian_parts[i]); + try std.fmt.format(context, Errors, output, "{x}", .{native_endian_parts[i]}); if (i != native_endian_parts.len - 1) { try output(context, ":"); } } - try std.fmt.format(context, Errors, output, "]:{}", port); + try std.fmt.format(context, Errors, output, "]:{}", .{port}); }, os.AF_UNIX => { if (!has_unix_sockets) { unreachable; } - try std.fmt.format(context, Errors, output, "{}", &self.un.path); + try std.fmt.format(context, Errors, output, "{}", .{&self.un.path}); }, else => unreachable, } diff --git a/lib/std/net/test.zig b/lib/std/net/test.zig index 6400b022c6..2dd11b391e 100644 --- a/lib/std/net/test.zig +++ b/lib/std/net/test.zig @@ -29,7 +29,7 @@ test "parse and render IPv6 addresses" { }; for (ips) |ip, i| { var addr = net.Address.parseIp6(ip, 0) catch unreachable; - var newIp = std.fmt.bufPrint(buffer[0..], "{}", addr) catch unreachable; + var newIp = std.fmt.bufPrint(buffer[0..], "{}", .{addr}) catch unreachable; std.testing.expect(std.mem.eql(u8, printed[i], newIp[1 .. newIp.len - 3])); } @@ -51,7 +51,7 @@ test "parse and render IPv4 addresses" { "127.0.0.1", }) |ip| { var addr = net.Address.parseIp4(ip, 0) catch unreachable; - var newIp = std.fmt.bufPrint(buffer[0..], "{}", addr) catch unreachable; + var newIp = std.fmt.bufPrint(buffer[0..], "{}", .{addr}) catch unreachable; std.testing.expect(std.mem.eql(u8, ip, newIp[0 .. newIp.len - 2])); } @@ -118,5 +118,5 @@ fn testServer(server: *net.StreamServer) anyerror!void { var client = try server.accept(); const stream = &client.file.outStream().stream; - try stream.print("hello from server\n"); + try stream.print("hello from server\n", .{}); } diff --git a/lib/std/os.zig b/lib/std/os.zig index 5d3bb705a9..8d6c7dd05e 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -2603,7 +2603,7 @@ pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP defer close(fd); var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined; - const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", fd) catch unreachable; + const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", .{fd}) catch unreachable; return readlinkC(@ptrCast([*:0]const u8, proc_path.ptr), out_buffer); } @@ -2832,7 +2832,7 @@ pub const UnexpectedError = error{ /// and you get an unexpected error. pub fn unexpectedErrno(err: usize) UnexpectedError { if (unexpected_error_tracing) { - std.debug.warn("unexpected errno: {}\n", err); + std.debug.warn("unexpected errno: {}\n", .{err}); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index e832f66254..81855a992a 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -1039,7 +1039,7 @@ pub fn unexpectedError(err: DWORD) std.os.UnexpectedError { var buf_u8: [614]u8 = undefined; var len = kernel32.FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, err, MAKELANGID(LANG.NEUTRAL, SUBLANG.DEFAULT), buf_u16[0..].ptr, buf_u16.len / @sizeOf(TCHAR), null); _ = std.unicode.utf16leToUtf8(&buf_u8, buf_u16[0..len]) catch unreachable; - std.debug.warn("error.Unexpected: GetLastError({}): {}\n", err, buf_u8[0..len]); + std.debug.warn("error.Unexpected: GetLastError({}): {}\n", .{ err, buf_u8[0..len] }); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; @@ -1053,7 +1053,7 @@ pub fn unexpectedWSAError(err: c_int) std.os.UnexpectedError { /// and you get an unexpected status. pub fn unexpectedStatus(status: NTSTATUS) std.os.UnexpectedError { if (std.os.unexpected_error_tracing) { - std.debug.warn("error.Unexpected NTSTATUS=0x{x}\n", status); + std.debug.warn("error.Unexpected NTSTATUS=0x{x}\n", .{status}); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; diff --git a/lib/std/os/zen.zig b/lib/std/os/zen.zig deleted file mode 100644 index 190b7ffe08..0000000000 --- a/lib/std/os/zen.zig +++ /dev/null @@ -1,260 +0,0 @@ -const std = @import("../std.zig"); -const assert = std.debug.assert; - -////////////////////////// -//// IPC structures //// -////////////////////////// - -pub const Message = struct { - sender: MailboxId, - receiver: MailboxId, - code: usize, - args: [5]usize, - payload: ?[]const u8, - - pub fn from(mailbox_id: MailboxId) Message { - return Message{ - .sender = MailboxId.Undefined, - .receiver = mailbox_id, - .code = undefined, - .args = undefined, - .payload = null, - }; - } - - pub fn to(mailbox_id: MailboxId, msg_code: usize, args: ...) Message { - var message = Message{ - .sender = MailboxId.This, - .receiver = mailbox_id, - .code = msg_code, - .args = undefined, - .payload = null, - }; - - assert(args.len <= message.args.len); - comptime var i = 0; - inline while (i < args.len) : (i += 1) { - message.args[i] = args[i]; - } - - return message; - } - - pub fn as(self: Message, sender: MailboxId) Message { - var message = self; - message.sender = sender; - return message; - } - - pub fn withPayload(self: Message, payload: []const u8) Message { - var message = self; - message.payload = payload; - return message; - } -}; - -pub const MailboxId = union(enum) { - Undefined, - This, - Kernel, - Port: u16, - Thread: u16, -}; - -////////////////////////////////////// -//// Ports reserved for servers //// -////////////////////////////////////// - -pub const Server = struct { - pub const Keyboard = MailboxId{ .Port = 0 }; - pub const Terminal = MailboxId{ .Port = 1 }; -}; - -//////////////////////// -//// POSIX things //// -//////////////////////// - -// Standard streams. -pub const STDIN_FILENO = 0; -pub const STDOUT_FILENO = 1; -pub const STDERR_FILENO = 2; - -// FIXME: let's borrow Linux's error numbers for now. -usingnamespace @import("bits/linux/errno-generic.zig"); -// Get the errno from a syscall return value, or 0 for no error. -pub fn getErrno(r: usize) usize { - const signed_r = @bitCast(isize, r); - return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; -} - -// TODO: implement this correctly. -pub fn read(fd: i32, buf: [*]u8, count: usize) usize { - switch (fd) { - STDIN_FILENO => { - var i: usize = 0; - while (i < count) : (i += 1) { - send(&Message.to(Server.Keyboard, 0)); - - // FIXME: we should be certain that we are receiving from Keyboard. - var message = Message.from(MailboxId.This); - receive(&message); - - buf[i] = @intCast(u8, message.args[0]); - } - }, - else => unreachable, - } - return count; -} - -// TODO: implement this correctly. -pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { - switch (fd) { - STDOUT_FILENO, STDERR_FILENO => { - send(&Message.to(Server.Terminal, 1).withPayload(buf[0..count])); - }, - else => unreachable, - } - return count; -} - -/////////////////////////// -//// Syscall numbers //// -/////////////////////////// - -pub const Syscall = enum(usize) { - exit = 0, - send = 1, - receive = 2, - subscribeIRQ = 3, - inb = 4, - outb = 5, - map = 6, - createThread = 7, -}; - -//////////////////// -//// Syscalls //// -//////////////////// - -pub fn exit(status: i32) noreturn { - _ = syscall1(Syscall.exit, @bitCast(usize, @as(isize, status))); - unreachable; -} - -pub fn send(message: *const Message) void { - _ = syscall1(Syscall.send, @ptrToInt(message)); -} - -pub fn receive(destination: *Message) void { - _ = syscall1(Syscall.receive, @ptrToInt(destination)); -} - -pub fn subscribeIRQ(irq: u8, mailbox_id: *const MailboxId) void { - _ = syscall2(Syscall.subscribeIRQ, irq, @ptrToInt(mailbox_id)); -} - -pub fn inb(port: u16) u8 { - return @intCast(u8, syscall1(Syscall.inb, port)); -} - -pub fn outb(port: u16, value: u8) void { - _ = syscall2(Syscall.outb, port, value); -} - -pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool { - return syscall4(Syscall.map, v_addr, p_addr, size, @boolToInt(writable)) != 0; -} - -pub fn createThread(function: fn () void) u16 { - return @as(u16, syscall1(Syscall.createThread, @ptrToInt(function))); -} - -///////////////////////// -//// Syscall stubs //// -///////////////////////// - -inline fn syscall0(number: Syscall) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number) - ); -} - -inline fn syscall1(number: Syscall, arg1: usize) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1) - ); -} - -inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2) - ); -} - -inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3) - ); -} - -inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4) - ); -} - -inline fn syscall5( - number: Syscall, - arg1: usize, - arg2: usize, - arg3: usize, - arg4: usize, - arg5: usize, -) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4), - [arg5] "{edi}" (arg5) - ); -} - -inline fn syscall6( - number: Syscall, - arg1: usize, - arg2: usize, - arg3: usize, - arg4: usize, - arg5: usize, - arg6: usize, -) usize { - return asm volatile ("int $0x80" - : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4), - [arg5] "{edi}" (arg5), - [arg6] "{ebp}" (arg6) - ); -} diff --git a/lib/std/priority_queue.zig b/lib/std/priority_queue.zig index 3351ac994b..77c76e4a70 100644 --- a/lib/std/priority_queue.zig +++ b/lib/std/priority_queue.zig @@ -199,19 +199,19 @@ pub fn PriorityQueue(comptime T: type) type { } fn dump(self: *Self) void { - warn("{{ "); - warn("items: "); + warn("{{ ", .{}); + warn("items: ", .{}); for (self.items) |e, i| { if (i >= self.len) break; - warn("{}, ", e); + warn("{}, ", .{e}); } - warn("array: "); + warn("array: ", .{}); for (self.items) |e, i| { - warn("{}, ", e); + warn("{}, ", .{e}); } - warn("len: {} ", self.len); - warn("capacity: {}", self.capacity()); - warn(" }}\n"); + warn("len: {} ", .{self.len}); + warn("capacity: {}", .{self.capacity()}); + warn(" }}\n", .{}); } }; } diff --git a/lib/std/progress.zig b/lib/std/progress.zig index 034d7ade26..1c5ecd261a 100644 --- a/lib/std/progress.zig +++ b/lib/std/progress.zig @@ -130,11 +130,11 @@ pub const Progress = struct { var end: usize = 0; if (self.columns_written > 0) { // restore cursor position - end += (std.fmt.bufPrint(self.output_buffer[end..], "\x1b[{}D", self.columns_written) catch unreachable).len; + end += (std.fmt.bufPrint(self.output_buffer[end..], "\x1b[{}D", .{self.columns_written}) catch unreachable).len; self.columns_written = 0; // clear rest of line - end += (std.fmt.bufPrint(self.output_buffer[end..], "\x1b[0K") catch unreachable).len; + end += (std.fmt.bufPrint(self.output_buffer[end..], "\x1b[0K", .{}) catch unreachable).len; } if (!self.done) { @@ -142,28 +142,28 @@ pub const Progress = struct { var maybe_node: ?*Node = &self.root; while (maybe_node) |node| { if (need_ellipse) { - self.bufWrite(&end, "..."); + self.bufWrite(&end, "...", .{}); } need_ellipse = false; if (node.name.len != 0 or node.estimated_total_items != null) { if (node.name.len != 0) { - self.bufWrite(&end, "{}", node.name); + self.bufWrite(&end, "{}", .{node.name}); need_ellipse = true; } if (node.estimated_total_items) |total| { - if (need_ellipse) self.bufWrite(&end, " "); - self.bufWrite(&end, "[{}/{}] ", node.completed_items + 1, total); + if (need_ellipse) self.bufWrite(&end, " ", .{}); + self.bufWrite(&end, "[{}/{}] ", .{ node.completed_items + 1, total }); need_ellipse = false; } else if (node.completed_items != 0) { - if (need_ellipse) self.bufWrite(&end, " "); - self.bufWrite(&end, "[{}] ", node.completed_items + 1); + if (need_ellipse) self.bufWrite(&end, " ", .{}); + self.bufWrite(&end, "[{}] ", .{node.completed_items + 1}); need_ellipse = false; } } maybe_node = node.recently_updated_child; } if (need_ellipse) { - self.bufWrite(&end, "..."); + self.bufWrite(&end, "...", .{}); } } @@ -174,7 +174,7 @@ pub const Progress = struct { self.prev_refresh_timestamp = self.timer.read(); } - pub fn log(self: *Progress, comptime format: []const u8, args: ...) void { + pub fn log(self: *Progress, comptime format: []const u8, args: var) void { const file = self.terminal orelse return; self.refresh(); file.outStream().stream.print(format, args) catch { @@ -184,7 +184,7 @@ pub const Progress = struct { self.columns_written = 0; } - fn bufWrite(self: *Progress, end: *usize, comptime format: []const u8, args: ...) void { + fn bufWrite(self: *Progress, end: *usize, comptime format: []const u8, args: var) void { if (std.fmt.bufPrint(self.output_buffer[end.*..], format, args)) |written| { const amt = written.len; end.* += amt; diff --git a/lib/std/special/build_runner.zig b/lib/std/special/build_runner.zig index 27d3283a3c..03d1e8fe1d 100644 --- a/lib/std/special/build_runner.zig +++ b/lib/std/special/build_runner.zig @@ -26,15 +26,15 @@ pub fn main() !void { _ = arg_it.skip(); const zig_exe = try unwrapArg(arg_it.next(allocator) orelse { - warn("Expected first argument to be path to zig compiler\n"); + warn("Expected first argument to be path to zig compiler\n", .{}); return error.InvalidArgs; }); const build_root = try unwrapArg(arg_it.next(allocator) orelse { - warn("Expected second argument to be build root directory path\n"); + warn("Expected second argument to be build root directory path\n", .{}); return error.InvalidArgs; }); const cache_root = try unwrapArg(arg_it.next(allocator) orelse { - warn("Expected third argument to be cache root directory path\n"); + warn("Expected third argument to be cache root directory path\n", .{}); return error.InvalidArgs; }); @@ -51,7 +51,7 @@ pub fn main() !void { if (mem.startsWith(u8, arg, "-D")) { const option_contents = arg[2..]; if (option_contents.len == 0) { - warn("Expected option name after '-D'\n\n"); + warn("Expected option name after '-D'\n\n", .{}); return usageAndErr(builder, false, stderr_stream); } if (mem.indexOfScalar(u8, option_contents, '=')) |name_end| { @@ -70,18 +70,18 @@ pub fn main() !void { return usage(builder, false, stdout_stream); } else if (mem.eql(u8, arg, "--prefix")) { builder.install_prefix = try unwrapArg(arg_it.next(allocator) orelse { - warn("Expected argument after --prefix\n\n"); + warn("Expected argument after --prefix\n\n", .{}); return usageAndErr(builder, false, stderr_stream); }); } else if (mem.eql(u8, arg, "--search-prefix")) { const search_prefix = try unwrapArg(arg_it.next(allocator) orelse { - warn("Expected argument after --search-prefix\n\n"); + warn("Expected argument after --search-prefix\n\n", .{}); return usageAndErr(builder, false, stderr_stream); }); builder.addSearchPrefix(search_prefix); } else if (mem.eql(u8, arg, "--override-lib-dir")) { builder.override_lib_dir = try unwrapArg(arg_it.next(allocator) orelse { - warn("Expected argument after --override-lib-dir\n\n"); + warn("Expected argument after --override-lib-dir\n\n", .{}); return usageAndErr(builder, false, stderr_stream); }); } else if (mem.eql(u8, arg, "--verbose-tokenize")) { @@ -99,7 +99,7 @@ pub fn main() !void { } else if (mem.eql(u8, arg, "--verbose-cc")) { builder.verbose_cc = true; } else { - warn("Unrecognized argument: {}\n\n", arg); + warn("Unrecognized argument: {}\n\n", .{arg}); return usageAndErr(builder, false, stderr_stream); } } else { @@ -145,15 +145,15 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void { \\ \\Steps: \\ - , builder.zig_exe); + , .{builder.zig_exe}); const allocator = builder.allocator; for (builder.top_level_steps.toSliceConst()) |top_level_step| { const name = if (&top_level_step.step == builder.default_step) - try fmt.allocPrint(allocator, "{} (default)", top_level_step.step.name) + try fmt.allocPrint(allocator, "{} (default)", .{top_level_step.step.name}) else top_level_step.step.name; - try out_stream.print(" {s:22} {}\n", name, top_level_step.description); + try out_stream.print(" {s:22} {}\n", .{ name, top_level_step.description }); } try out_stream.write( @@ -169,12 +169,15 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void { ); if (builder.available_options_list.len == 0) { - try out_stream.print(" (none)\n"); + try out_stream.print(" (none)\n", .{}); } else { for (builder.available_options_list.toSliceConst()) |option| { - const name = try fmt.allocPrint(allocator, " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id)); + const name = try fmt.allocPrint(allocator, " -D{}=[{}]", .{ + option.name, + Builder.typeIdName(option.type_id), + }); defer allocator.free(name); - try out_stream.print("{s:24} {}\n", name, option.description); + try out_stream.print("{s:24} {}\n", .{ name, option.description }); } } @@ -204,7 +207,7 @@ const UnwrapArgError = error{OutOfMemory}; fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 { return arg catch |err| { - warn("Unable to parse command line: {}\n", err); + warn("Unable to parse command line: {}\n", .{err}); return err; }; } diff --git a/lib/std/special/init-exe/src/main.zig b/lib/std/special/init-exe/src/main.zig index 128820d3ee..5f35540dc0 100644 --- a/lib/std/special/init-exe/src/main.zig +++ b/lib/std/special/init-exe/src/main.zig @@ -1,5 +1,5 @@ const std = @import("std"); pub fn main() anyerror!void { - std.debug.warn("All your base are belong to us.\n"); + std.debug.warn("All your base are belong to us.\n", .{}); } diff --git a/lib/std/special/start.zig b/lib/std/special/start.zig index d6c6350ff4..b5e4e2edab 100644 --- a/lib/std/special/start.zig +++ b/lib/std/special/start.zig @@ -217,7 +217,7 @@ inline fn initEventLoopAndCallMain() u8 { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { - std.debug.warn("error: {}\n", @errorName(err)); + std.debug.warn("error: {}\n", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -264,7 +264,7 @@ fn callMain() u8 { }, .ErrorUnion => { const result = root.main() catch |err| { - std.debug.warn("error: {}\n", @errorName(err)); + std.debug.warn("error: {}\n", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } diff --git a/lib/std/special/test_runner.zig b/lib/std/special/test_runner.zig index 4dc8be0fec..7bb53774d3 100644 --- a/lib/std/special/test_runner.zig +++ b/lib/std/special/test_runner.zig @@ -16,28 +16,28 @@ pub fn main() anyerror!void { var test_node = root_node.start(test_fn.name, null); test_node.activate(); progress.refresh(); - if (progress.terminal == null) std.debug.warn("{}/{} {}...", i + 1, test_fn_list.len, test_fn.name); + if (progress.terminal == null) std.debug.warn("{}/{} {}...", .{ i + 1, test_fn_list.len, test_fn.name }); if (test_fn.func()) |_| { ok_count += 1; test_node.end(); - if (progress.terminal == null) std.debug.warn("OK\n"); + if (progress.terminal == null) std.debug.warn("OK\n", .{}); } else |err| switch (err) { error.SkipZigTest => { skip_count += 1; test_node.end(); - progress.log("{}...SKIP\n", test_fn.name); - if (progress.terminal == null) std.debug.warn("SKIP\n"); + progress.log("{}...SKIP\n", .{test_fn.name}); + if (progress.terminal == null) std.debug.warn("SKIP\n", .{}); }, else => { - progress.log(""); + progress.log("", .{}); return err; }, } } root_node.end(); if (ok_count == test_fn_list.len) { - std.debug.warn("All {} tests passed.\n", ok_count); + std.debug.warn("All {} tests passed.\n", .{ok_count}); } else { - std.debug.warn("{} passed; {} skipped.\n", ok_count, skip_count); + std.debug.warn("{} passed; {} skipped.\n", .{ ok_count, skip_count }); } } diff --git a/lib/std/target.zig b/lib/std/target.zig index e4beea4552..aaa19ad609 100644 --- a/lib/std/target.zig +++ b/lib/std/target.zig @@ -321,14 +321,12 @@ pub const Target = union(enum) { pub const stack_align = 16; pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 { - return std.fmt.allocPrint( - allocator, - "{}{}-{}-{}", + return std.fmt.allocPrint(allocator, "{}{}-{}-{}", .{ @tagName(self.getArch()), Target.archSubArchName(self.getArch()), @tagName(self.getOs()), @tagName(self.getAbi()), - ); + }); } /// Returned slice must be freed by the caller. @@ -372,23 +370,19 @@ pub const Target = union(enum) { } pub fn zigTripleNoSubArch(self: Target, allocator: *mem.Allocator) ![]u8 { - return std.fmt.allocPrint( - allocator, - "{}-{}-{}", + return std.fmt.allocPrint(allocator, "{}-{}-{}", .{ @tagName(self.getArch()), @tagName(self.getOs()), @tagName(self.getAbi()), - ); + }); } pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 { - return std.fmt.allocPrint( - allocator, - "{}-{}-{}", + return std.fmt.allocPrint(allocator, "{}-{}-{}", .{ @tagName(self.getArch()), @tagName(self.getOs()), @tagName(self.getAbi()), - ); + }); } pub fn parse(text: []const u8) !Target { diff --git a/lib/std/testing.zig b/lib/std/testing.zig index 2ed6c66fe6..e808930b60 100644 --- a/lib/std/testing.zig +++ b/lib/std/testing.zig @@ -8,13 +8,19 @@ pub fn expectError(expected_error: anyerror, actual_error_union: var) void { if (actual_error_union) |actual_payload| { // TODO remove workaround here for https://github.com/ziglang/zig/issues/557 if (@sizeOf(@typeOf(actual_payload)) == 0) { - std.debug.panic("expected error.{}, found {} value", @errorName(expected_error), @typeName(@typeOf(actual_payload))); + std.debug.panic("expected error.{}, found {} value", .{ + @errorName(expected_error), + @typeName(@typeOf(actual_payload)), + }); } else { - std.debug.panic("expected error.{}, found {}", @errorName(expected_error), actual_payload); + std.debug.panic("expected error.{}, found {}", .{ @errorName(expected_error), actual_payload }); } } else |actual_error| { if (expected_error != actual_error) { - std.debug.panic("expected error.{}, found error.{}", @errorName(expected_error), @errorName(actual_error)); + std.debug.panic("expected error.{}, found error.{}", .{ + @errorName(expected_error), + @errorName(actual_error), + }); } } } @@ -51,7 +57,7 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void { .ErrorSet, => { if (actual != expected) { - std.debug.panic("expected {}, found {}", expected, actual); + std.debug.panic("expected {}, found {}", .{ expected, actual }); } }, @@ -62,16 +68,16 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void { builtin.TypeInfo.Pointer.Size.C, => { if (actual != expected) { - std.debug.panic("expected {*}, found {*}", expected, actual); + std.debug.panic("expected {*}, found {*}", .{ expected, actual }); } }, builtin.TypeInfo.Pointer.Size.Slice => { if (actual.ptr != expected.ptr) { - std.debug.panic("expected slice ptr {}, found {}", expected.ptr, actual.ptr); + std.debug.panic("expected slice ptr {}, found {}", .{ expected.ptr, actual.ptr }); } if (actual.len != expected.len) { - std.debug.panic("expected slice len {}, found {}", expected.len, actual.len); + std.debug.panic("expected slice len {}, found {}", .{ expected.len, actual.len }); } }, } @@ -106,7 +112,7 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void { } // we iterate over *all* union fields - // => we should never get here as the loop above is + // => we should never get here as the loop above is // including all possible values. unreachable; }, @@ -116,11 +122,11 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void { if (actual) |actual_payload| { expectEqual(expected_payload, actual_payload); } else { - std.debug.panic("expected {}, found null", expected_payload); + std.debug.panic("expected {}, found null", .{expected_payload}); } } else { if (actual) |actual_payload| { - std.debug.panic("expected null, found {}", actual_payload); + std.debug.panic("expected null, found {}", .{actual_payload}); } } }, @@ -130,11 +136,11 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void { if (actual) |actual_payload| { expectEqual(expected_payload, actual_payload); } else |actual_err| { - std.debug.panic("expected {}, found {}", expected_payload, actual_err); + std.debug.panic("expected {}, found {}", .{ expected_payload, actual_err }); } } else |expected_err| { if (actual) |actual_payload| { - std.debug.panic("expected {}, found {}", expected_err, actual_payload); + std.debug.panic("expected {}, found {}", .{ expected_err, actual_payload }); } else |actual_err| { expectEqual(expected_err, actual_err); } @@ -143,15 +149,14 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void { } } -test "expectEqual.union(enum)" -{ +test "expectEqual.union(enum)" { const T = union(enum) { a: i32, b: f32, }; - const a10 = T { .a = 10 }; - const a20 = T { .a = 20 }; + const a10 = T{ .a = 10 }; + const a20 = T{ .a = 20 }; expectEqual(a10, a10); } @@ -165,12 +170,12 @@ pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const // If the child type is u8 and no weird bytes, we could print it as strings // Even for the length difference, it would be useful to see the values of the slices probably. if (expected.len != actual.len) { - std.debug.panic("slice lengths differ. expected {}, found {}", expected.len, actual.len); + std.debug.panic("slice lengths differ. expected {}, found {}", .{ expected.len, actual.len }); } var i: usize = 0; while (i < expected.len) : (i += 1) { if (expected[i] != actual[i]) { - std.debug.panic("index {} incorrect. expected {}, found {}", i, expected[i], actual[i]); + std.debug.panic("index {} incorrect. expected {}, found {}", .{ i, expected[i], actual[i] }); } } } diff --git a/lib/std/unicode.zig b/lib/std/unicode.zig index 4af1b63a69..0352c91f60 100644 --- a/lib/std/unicode.zig +++ b/lib/std/unicode.zig @@ -170,7 +170,7 @@ pub fn utf8ValidateSlice(s: []const u8) bool { /// ``` /// var utf8 = (try std.unicode.Utf8View.init("hi there")).iterator(); /// while (utf8.nextCodepointSlice()) |codepoint| { -/// std.debug.warn("got codepoint {}\n", codepoint); +/// std.debug.warn("got codepoint {}\n", .{codepoint}); /// } /// ``` pub const Utf8View = struct { diff --git a/lib/std/unicode/throughput_test.zig b/lib/std/unicode/throughput_test.zig index f76f14b3ac..a9a211d24a 100644 --- a/lib/std/unicode/throughput_test.zig +++ b/lib/std/unicode/throughput_test.zig @@ -24,8 +24,12 @@ pub fn main() !void { const elapsed_ns_better = timer.lap(); @fence(.SeqCst); - std.debug.warn("original utf8ToUtf16Le: elapsed: {} ns ({} ms)\n", elapsed_ns_orig, elapsed_ns_orig / 1000000); - std.debug.warn("new utf8ToUtf16Le: elapsed: {} ns ({} ms)\n", elapsed_ns_better, elapsed_ns_better / 1000000); + std.debug.warn("original utf8ToUtf16Le: elapsed: {} ns ({} ms)\n", .{ + elapsed_ns_orig, elapsed_ns_orig / 1000000, + }); + std.debug.warn("new utf8ToUtf16Le: elapsed: {} ns ({} ms)\n", .{ + elapsed_ns_better, elapsed_ns_better / 1000000, + }); asm volatile ("nop" : : [a] "r" (&buffer1), diff --git a/lib/std/valgrind.zig b/lib/std/valgrind.zig index ffdce1b729..fe1eb65b7a 100644 --- a/lib/std/valgrind.zig +++ b/lib/std/valgrind.zig @@ -114,20 +114,6 @@ pub fn innerThreads(qzz: [*]u8) void { doClientRequestStmt(.InnerThreads, qzz, 0, 0, 0, 0); } -//pub fn printf(format: [*]const u8, args: ...) usize { -// return doClientRequestExpr(0, -// .PrintfValistByRef, -// @ptrToInt(format), @ptrToInt(args), -// 0, 0, 0); -//} - -//pub fn printfBacktrace(format: [*]const u8, args: ...) usize { -// return doClientRequestExpr(0, -// .PrintfBacktraceValistByRef, -// @ptrToInt(format), @ptrToInt(args), -// 0, 0, 0); -//} - pub fn nonSIMDCall0(func: fn (usize) usize) usize { return doClientRequestExpr(0, .ClientCall0, @ptrToInt(func), 0, 0, 0, 0); } diff --git a/lib/std/zig/ast.zig b/lib/std/zig/ast.zig index bedb980463..5fa519aa90 100644 --- a/lib/std/zig/ast.zig +++ b/lib/std/zig/ast.zig @@ -301,7 +301,9 @@ pub const Error = union(enum) { node: *Node, pub fn render(self: *const ExpectedCall, tokens: *Tree.TokenList, stream: var) !void { - return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", @tagName(self.node.id)); + return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", .{ + @tagName(self.node.id), + }); } }; @@ -309,7 +311,8 @@ pub const Error = union(enum) { node: *Node, pub fn render(self: *const ExpectedCallOrFnProto, tokens: *Tree.TokenList, stream: var) !void { - return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id)); + return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ + @tagName(Node.Id.FnProto) ++ ", found {}", .{@tagName(self.node.id)}); } }; @@ -321,14 +324,14 @@ pub const Error = union(enum) { const found_token = tokens.at(self.token); switch (found_token.id) { .Invalid_ampersands => { - return stream.print("`&&` is invalid. Note that `and` is boolean AND."); + return stream.print("`&&` is invalid. Note that `and` is boolean AND.", .{}); }, .Invalid => { - return stream.print("expected '{}', found invalid bytes", self.expected_id.symbol()); + return stream.print("expected '{}', found invalid bytes", .{self.expected_id.symbol()}); }, else => { const token_name = found_token.id.symbol(); - return stream.print("expected '{}', found '{}'", self.expected_id.symbol(), token_name); + return stream.print("expected '{}', found '{}'", .{ self.expected_id.symbol(), token_name }); }, } } @@ -340,7 +343,10 @@ pub const Error = union(enum) { pub fn render(self: *const ExpectedCommaOrEnd, tokens: *Tree.TokenList, stream: var) !void { const actual_token = tokens.at(self.token); - return stream.print("expected ',' or '{}', found '{}'", self.end_id.symbol(), actual_token.id.symbol()); + return stream.print("expected ',' or '{}', found '{}'", .{ + self.end_id.symbol(), + actual_token.id.symbol(), + }); } }; @@ -352,7 +358,7 @@ pub const Error = union(enum) { pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void { const actual_token = tokens.at(self.token); - return stream.print(msg, actual_token.id.symbol()); + return stream.print(msg, .{actual_token.id.symbol()}); } }; } @@ -563,10 +569,10 @@ pub const Node = struct { { var i: usize = 0; while (i < indent) : (i += 1) { - std.debug.warn(" "); + std.debug.warn(" ", .{}); } } - std.debug.warn("{}\n", @tagName(self.id)); + std.debug.warn("{}\n", .{@tagName(self.id)}); var child_i: usize = 0; while (self.iterate(child_i)) |child| : (child_i += 1) { diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index 7f3cc3694a..a47e2bdc7e 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -642,15 +642,6 @@ test "zig fmt: fn decl with trailing comma" { ); } -test "zig fmt: var_args with trailing comma" { - try testCanonical( - \\pub fn add( - \\ a: ..., - \\) void {} - \\ - ); -} - test "zig fmt: enum decl with no trailing comma" { try testTransform( \\const StrLitKind = enum {Normal, C}; @@ -1750,13 +1741,6 @@ test "zig fmt: call expression" { ); } -test "zig fmt: var args" { - try testCanonical( - \\fn print(args: ...) void {} - \\ - ); -} - test "zig fmt: var type" { try testCanonical( \\fn print(args: var) var {} @@ -2705,9 +2689,9 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b while (error_it.next()) |parse_error| { const token = tree.tokens.at(parse_error.loc()); const loc = tree.tokenLocation(0, parse_error.loc()); - try stderr.print("(memory buffer):{}:{}: error: ", loc.line + 1, loc.column + 1); + try stderr.print("(memory buffer):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 }); try tree.renderError(parse_error, stderr); - try stderr.print("\n{}\n", source[loc.line_start..loc.line_end]); + try stderr.print("\n{}\n", .{source[loc.line_start..loc.line_end]}); { var i: usize = 0; while (i < loc.column) : (i += 1) { @@ -2743,16 +2727,16 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { var anything_changed: bool = undefined; const result_source = try testParse(source, &failing_allocator.allocator, &anything_changed); if (!mem.eql(u8, result_source, expected_source)) { - warn("\n====== expected this output: =========\n"); - warn("{}", expected_source); - warn("\n======== instead found this: =========\n"); - warn("{}", result_source); - warn("\n======================================\n"); + warn("\n====== expected this output: =========\n", .{}); + warn("{}", .{expected_source}); + warn("\n======== instead found this: =========\n", .{}); + warn("{}", .{result_source}); + warn("\n======================================\n", .{}); return error.TestFailed; } const changes_expected = source.ptr != expected_source.ptr; if (anything_changed != changes_expected) { - warn("std.zig.render returned {} instead of {}\n", anything_changed, changes_expected); + warn("std.zig.render returned {} instead of {}\n", .{ anything_changed, changes_expected }); return error.TestFailed; } std.testing.expect(anything_changed == changes_expected); @@ -2772,12 +2756,14 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { if (failing_allocator.allocated_bytes != failing_allocator.freed_bytes) { warn( "\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n", - fail_index, - needed_alloc_count, - failing_allocator.allocated_bytes, - failing_allocator.freed_bytes, - failing_allocator.allocations, - failing_allocator.deallocations, + .{ + fail_index, + needed_alloc_count, + failing_allocator.allocated_bytes, + failing_allocator.freed_bytes, + failing_allocator.allocations, + failing_allocator.deallocations, + }, ); return error.MemoryLeakDetected; } diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 8b0ce7ee1a..09482b5109 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -76,7 +76,7 @@ fn renderRoot( // render all the line comments at the beginning of the file while (tok_it.next()) |token| { if (token.id != .LineComment) break; - try stream.print("{}\n", mem.trimRight(u8, tree.tokenSlicePtr(token), " ")); + try stream.print("{}\n", .{mem.trimRight(u8, tree.tokenSlicePtr(token), " ")}); if (tok_it.peek()) |next_token| { const loc = tree.tokenLocationPtr(token.end, next_token); if (loc.line >= 2) { @@ -1226,7 +1226,7 @@ fn renderExpression( var skip_first_indent = true; if (tree.tokens.at(multiline_str_literal.firstToken() - 1).id != .LineComment) { - try stream.print("\n"); + try stream.print("\n", .{}); skip_first_indent = false; } @@ -2129,7 +2129,7 @@ fn renderTokenOffset( var loc = tree.tokenLocationPtr(token.end, next_token); if (loc.line == 0) { - try stream.print(" {}", mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ")); + try stream.print(" {}", .{mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ")}); offset = 2; token = next_token; next_token = tree.tokens.at(token_index + offset); diff --git a/lib/std/zig/tokenizer.zig b/lib/std/zig/tokenizer.zig index e7d2b41784..93fbfa18a7 100644 --- a/lib/std/zig/tokenizer.zig +++ b/lib/std/zig/tokenizer.zig @@ -330,7 +330,7 @@ pub const Tokenizer = struct { /// For debugging purposes pub fn dump(self: *Tokenizer, token: *const Token) void { - std.debug.warn("{} \"{}\"\n", @tagName(token.id), self.buffer[token.start..token.end]); + std.debug.warn("{} \"{}\"\n", .{ @tagName(token.id), self.buffer[token.start..token.end] }); } pub fn init(buffer: []const u8) Tokenizer { @@ -1576,7 +1576,7 @@ fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void { for (expected_tokens) |expected_token_id| { const token = tokenizer.next(); if (token.id != expected_token_id) { - std.debug.panic("expected {}, found {}\n", @tagName(expected_token_id), @tagName(token.id)); + std.debug.panic("expected {}, found {}\n", .{ @tagName(expected_token_id), @tagName(token.id) }); } } const last_token = tokenizer.next(); diff --git a/src-self-hosted/arg.zig b/src-self-hosted/arg.zig index 3d12bb3e83..066080f9ef 100644 --- a/src-self-hosted/arg.zig +++ b/src-self-hosted/arg.zig @@ -98,15 +98,15 @@ pub const Args = struct { const flag_args = readFlagArguments(allocator, args, flag.required, flag.allowed_set, &i) catch |err| { switch (err) { error.ArgumentNotInAllowedSet => { - std.debug.warn("argument '{}' is invalid for flag '{}'\n", args[i], arg); - std.debug.warn("allowed options are "); + std.debug.warn("argument '{}' is invalid for flag '{}'\n", .{ args[i], arg }); + std.debug.warn("allowed options are ", .{}); for (flag.allowed_set.?) |possible| { - std.debug.warn("'{}' ", possible); + std.debug.warn("'{}' ", .{possible}); } - std.debug.warn("\n"); + std.debug.warn("\n", .{}); }, error.MissingFlagArguments => { - std.debug.warn("missing argument for flag: {}\n", arg); + std.debug.warn("missing argument for flag: {}\n", .{arg}); }, else => {}, } @@ -134,7 +134,7 @@ pub const Args = struct { } // TODO: Better errors with context, global error state and return is sufficient. - std.debug.warn("could not match flag: {}\n", arg); + std.debug.warn("could not match flag: {}\n", .{arg}); return error.UnknownFlag; } else { try parsed.positionals.append(arg); diff --git a/src-self-hosted/dep_tokenizer.zig b/src-self-hosted/dep_tokenizer.zig index 9509aab702..b4e46bc1ad 100644 --- a/src-self-hosted/dep_tokenizer.zig +++ b/src-self-hosted/dep_tokenizer.zig @@ -38,7 +38,7 @@ pub const Tokenizer = struct { }, .target => |*target| switch (char) { '\t', '\n', '\r', ' ' => { - return self.errorIllegalChar(self.index, char, "invalid target"); + return self.errorIllegalChar(self.index, char, "invalid target", .{}); }, '$' => { self.state = State{ .target_dollar_sign = target.* }; @@ -59,7 +59,7 @@ pub const Tokenizer = struct { }, .target_reverse_solidus => |*target| switch (char) { '\t', '\n', '\r' => { - return self.errorIllegalChar(self.index, char, "bad target escape"); + return self.errorIllegalChar(self.index, char, "bad target escape", .{}); }, ' ', '#', '\\' => { try target.appendByte(char); @@ -84,7 +84,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - return self.errorIllegalChar(self.index, char, "expecting '$'"); + return self.errorIllegalChar(self.index, char, "expecting '$'", .{}); }, }, .target_colon => |*target| switch (char) { @@ -161,7 +161,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - return self.errorIllegalChar(self.index, char, "continuation expecting end-of-line"); + return self.errorIllegalChar(self.index, char, "continuation expecting end-of-line", .{}); }, }, .rhs_continuation_linefeed => switch (char) { @@ -170,7 +170,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - return self.errorIllegalChar(self.index, char, "continuation expecting end-of-line"); + return self.errorIllegalChar(self.index, char, "continuation expecting end-of-line", .{}); }, }, .prereq_quote => |*prereq| switch (char) { @@ -231,7 +231,7 @@ pub const Tokenizer = struct { return Token{ .id = .prereq, .bytes = bytes }; }, else => { - return self.errorIllegalChar(self.index, char, "continuation expecting end-of-line"); + return self.errorIllegalChar(self.index, char, "continuation expecting end-of-line", .{}); }, }, } @@ -249,13 +249,13 @@ pub const Tokenizer = struct { .rhs_continuation_linefeed, => {}, .target => |target| { - return self.errorPosition(idx, target.toSlice(), "incomplete target"); + return self.errorPosition(idx, target.toSlice(), "incomplete target", .{}); }, .target_reverse_solidus, .target_dollar_sign, => { const index = self.index - 1; - return self.errorIllegalChar(idx, self.bytes[idx], "incomplete escape"); + return self.errorIllegalChar(idx, self.bytes[idx], "incomplete escape", .{}); }, .target_colon => |target| { const bytes = target.toSlice(); @@ -278,7 +278,7 @@ pub const Tokenizer = struct { self.state = State{ .lhs = {} }; }, .prereq_quote => |prereq| { - return self.errorPosition(idx, prereq.toSlice(), "incomplete quoted prerequisite"); + return self.errorPosition(idx, prereq.toSlice(), "incomplete quoted prerequisite", .{}); }, .prereq => |prereq| { const bytes = prereq.toSlice(); @@ -299,29 +299,29 @@ pub const Tokenizer = struct { return null; } - fn errorf(self: *Tokenizer, comptime fmt: []const u8, args: ...) Error { + fn errorf(self: *Tokenizer, comptime fmt: []const u8, args: var) Error { self.error_text = (try std.Buffer.allocPrint(&self.arena.allocator, fmt, args)).toSlice(); return Error.InvalidInput; } - fn errorPosition(self: *Tokenizer, position: usize, bytes: []const u8, comptime fmt: []const u8, args: ...) Error { + fn errorPosition(self: *Tokenizer, position: usize, bytes: []const u8, comptime fmt: []const u8, args: var) Error { var buffer = try std.Buffer.initSize(&self.arena.allocator, 0); std.fmt.format(&buffer, anyerror, std.Buffer.append, fmt, args) catch {}; try buffer.append(" '"); var out = makeOutput(std.Buffer.append, &buffer); try printCharValues(&out, bytes); try buffer.append("'"); - std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", position - (bytes.len - 1)) catch {}; + std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", .{position - (bytes.len - 1)}) catch {}; self.error_text = buffer.toSlice(); return Error.InvalidInput; } - fn errorIllegalChar(self: *Tokenizer, position: usize, char: u8, comptime fmt: []const u8, args: ...) Error { + fn errorIllegalChar(self: *Tokenizer, position: usize, char: u8, comptime fmt: []const u8, args: var) Error { var buffer = try std.Buffer.initSize(&self.arena.allocator, 0); try buffer.append("illegal char "); var out = makeOutput(std.Buffer.append, &buffer); try printUnderstandableChar(&out, char); - std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", position) catch {}; + std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", .{position}) catch {}; if (fmt.len != 0) std.fmt.format(&buffer, anyerror, std.Buffer.append, ": " ++ fmt, args) catch {}; self.error_text = buffer.toSlice(); return Error.InvalidInput; @@ -998,7 +998,7 @@ fn printCharValues(out: var, bytes: []const u8) !void { fn printUnderstandableChar(out: var, char: u8) !void { if (!std.ascii.isPrint(char) or char == ' ') { - std.fmt.format(out.context, anyerror, out.output, "\\x{X:2}", char) catch {}; + std.fmt.format(out.context, anyerror, out.output, "\\x{X:2}", .{char}) catch {}; } else { try out.write("'"); try out.write(&[_]u8{printable_char_tab[char]}); diff --git a/src-self-hosted/stage1.zig b/src-self-hosted/stage1.zig index a0fd689a36..3b6d137df5 100644 --- a/src-self-hosted/stage1.zig +++ b/src-self-hosted/stage1.zig @@ -205,7 +205,7 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void { defer allocator.free(source_code); const tree = std.zig.parse(allocator, source_code) catch |err| { - try stderr.print("error parsing stdin: {}\n", err); + try stderr.print("error parsing stdin: {}\n", .{err}); process.exit(1); }; defer tree.deinit(); @@ -294,7 +294,7 @@ fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void }, else => { // TODO lock stderr printing - try stderr.print("unable to open '{}': {}\n", file_path, err); + try stderr.print("unable to open '{}': {}\n", .{ file_path, err }); fmt.any_error = true; return; }, @@ -302,7 +302,7 @@ fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void defer fmt.allocator.free(source_code); const tree = std.zig.parse(fmt.allocator, source_code) catch |err| { - try stderr.print("error parsing file '{}': {}\n", file_path, err); + try stderr.print("error parsing file '{}': {}\n", .{ file_path, err }); fmt.any_error = true; return; }; @@ -320,7 +320,7 @@ fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void if (check_mode) { const anything_changed = try std.zig.render(fmt.allocator, io.null_out_stream, tree); if (anything_changed) { - try stderr.print("{}\n", file_path); + try stderr.print("{}\n", .{file_path}); fmt.any_error = true; } } else { @@ -329,7 +329,7 @@ fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void const anything_changed = try std.zig.render(fmt.allocator, baf.stream(), tree); if (anything_changed) { - try stderr.print("{}\n", file_path); + try stderr.print("{}\n", .{file_path}); try baf.finish(); } } @@ -374,7 +374,7 @@ fn printErrMsgToFile( const text = text_buf.toOwnedSlice(); const stream = &file.outStream().stream; - try stream.print("{}:{}:{}: error: {}\n", path, start_loc.line + 1, start_loc.column + 1, text); + try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text }); if (!color_on) return; diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index 0470ab92dc..134e0b7672 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -125,7 +125,7 @@ const Context = struct { const line = ZigClangSourceManager_getSpellingLineNumber(c.source_manager, spelling_loc); const column = ZigClangSourceManager_getSpellingColumnNumber(c.source_manager, spelling_loc); - return std.fmt.allocPrint(c.a(), "{}:{}:{}", filename, line, column); + return std.fmt.allocPrint(c.a(), "{}:{}:{}", .{ filename, line, column }); } }; @@ -228,20 +228,20 @@ fn declVisitor(c: *Context, decl: *const ZigClangDecl) Error!void { return visitFnDecl(c, @ptrCast(*const ZigClangFunctionDecl, decl)); }, .Typedef => { - try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for typedefs"); + try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for typedefs", .{}); }, .Enum => { - try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for enums"); + try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for enums", .{}); }, .Record => { - try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for structs"); + try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for structs", .{}); }, .Var => { - try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for variables"); + try emitWarning(c, ZigClangDecl_getLocation(decl), "TODO implement translate-c for variables", .{}); }, else => { const decl_name = try c.str(ZigClangDecl_getDeclKindName(decl)); - try emitWarning(c, ZigClangDecl_getLocation(decl), "ignoring {} declaration", decl_name); + try emitWarning(c, ZigClangDecl_getLocation(decl), "ignoring {} declaration", .{decl_name}); }, } } @@ -264,7 +264,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const ZigClangFunctionDecl) Error!void { .is_export = switch (storage_class) { .None => has_body and c.mode != .import, .Extern, .Static => false, - .PrivateExtern => return failDecl(c, fn_decl_loc, fn_name, "unsupported storage class: private extern"), + .PrivateExtern => return failDecl(c, fn_decl_loc, fn_name, "unsupported storage class: private extern", .{}), .Auto => unreachable, // Not legal on functions .Register => unreachable, // Not legal on functions }, @@ -274,7 +274,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const ZigClangFunctionDecl) Error!void { const fn_proto_type = @ptrCast(*const ZigClangFunctionProtoType, fn_type); break :blk transFnProto(rp, fn_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) { error.UnsupportedType => { - return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function"); + return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function", .{}); }, error.OutOfMemory => |e| return e, }; @@ -283,7 +283,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const ZigClangFunctionDecl) Error!void { const fn_no_proto_type = @ptrCast(*const ZigClangFunctionType, fn_type); break :blk transFnNoProto(rp, fn_no_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) { error.UnsupportedType => { - return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function"); + return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function", .{}); }, error.OutOfMemory => |e| return e, }; @@ -302,7 +302,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const ZigClangFunctionDecl) Error!void { error.OutOfMemory => |e| return e, error.UnsupportedTranslation, error.UnsupportedType, - => return failDecl(c, fn_decl_loc, fn_name, "unable to translate function"), + => return failDecl(c, fn_decl_loc, fn_name, "unable to translate function", .{}), }; assert(result.node.id == ast.Node.Id.Block); proto_node.body_node = result.node; @@ -344,7 +344,7 @@ fn transStmt( error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(stmt), "TODO implement translation of stmt class {}", - @tagName(sc), + .{@tagName(sc)}, ); }, } @@ -364,7 +364,7 @@ fn transBinaryOperator( error.UnsupportedTranslation, ZigClangBinaryOperator_getBeginLoc(stmt), "TODO: handle more C binary operators: {}", - op, + .{op}, ), .Assign => return TransResult{ .node = &(try transCreateNodeAssign(rp, scope, result_used, ZigClangBinaryOperator_getLHS(stmt), ZigClangBinaryOperator_getRHS(stmt))).base, @@ -415,7 +415,7 @@ fn transBinaryOperator( error.UnsupportedTranslation, ZigClangBinaryOperator_getBeginLoc(stmt), "TODO: handle more C binary operators: {}", - op, + .{op}, ), .MulAssign, .DivAssign, @@ -567,7 +567,7 @@ fn transDeclStmt(rp: RestorePoint, parent_scope: *Scope, stmt: *const ZigClangDe error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, stmt)), "TODO implement translation of DeclStmt kind {}", - @tagName(kind), + .{@tagName(kind)}, ), } } @@ -636,7 +636,7 @@ fn transImplicitCastExpr( error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, expr)), "TODO implement translation of CastKind {}", - @tagName(kind), + .{@tagName(kind)}, ), } } @@ -650,7 +650,7 @@ fn transIntegerLiteral( var eval_result: ZigClangExprEvalResult = undefined; if (!ZigClangIntegerLiteral_EvaluateAsInt(expr, &eval_result, rp.c.clang_context)) { const loc = ZigClangIntegerLiteral_getBeginLoc(expr); - return revertAndWarn(rp, error.UnsupportedTranslation, loc, "invalid integer literal"); + return revertAndWarn(rp, error.UnsupportedTranslation, loc, "invalid integer literal", .{}); } const node = try transCreateNodeAPInt(rp.c, ZigClangAPValue_getInt(&eval_result.Val)); const res = TransResult{ @@ -719,7 +719,7 @@ fn transStringLiteral( error.UnsupportedTranslation, ZigClangStmt_getBeginLoc(@ptrCast(*const ZigClangStmt, stmt)), "TODO: support string literal kind {}", - kind, + .{kind}, ), } } @@ -751,7 +751,7 @@ fn escapeChar(c: u8, char_buf: *[4]u8) []const u8 { '\n' => return "\\n"[0..], '\r' => return "\\r"[0..], '\t' => return "\\t"[0..], - else => return std.fmt.bufPrint(char_buf[0..], "\\x{x:2}", c) catch unreachable, + else => return std.fmt.bufPrint(char_buf[0..], "\\x{x:2}", .{c}) catch unreachable, }; std.mem.copy(u8, char_buf, escaped); return char_buf[0..escaped.len]; @@ -1016,7 +1016,13 @@ fn transCreateNodeAssign( // zig: lhs = _tmp; // zig: break :x _tmp // zig: }) - return revertAndWarn(rp, error.UnsupportedTranslation, ZigClangExpr_getBeginLoc(lhs), "TODO: worst case assign op expr"); + return revertAndWarn( + rp, + error.UnsupportedTranslation, + ZigClangExpr_getBeginLoc(lhs), + "TODO: worst case assign op expr", + .{}, + ); } fn transCreateNodeBuiltinFnCall(c: *Context, name: []const u8) !*ast.Node.BuiltinCall { @@ -1211,7 +1217,7 @@ fn transType(rp: RestorePoint, ty: *const ZigClangType, source_loc: ZigClangSour .Float128 => return appendIdentifier(rp.c, "f128"), .Float16 => return appendIdentifier(rp.c, "f16"), .LongDouble => return appendIdentifier(rp.c, "c_longdouble"), - else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported builtin type"), + else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported builtin type", .{}), } }, .FunctionProto => { @@ -1253,7 +1259,7 @@ fn transType(rp: RestorePoint, ty: *const ZigClangType, source_loc: ZigClangSour }, else => { const type_name = rp.c.str(ZigClangType_getTypeClassName(ty)); - return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported type: '{}'", type_name); + return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported type: '{}'", .{type_name}); }, } } @@ -1275,7 +1281,13 @@ fn transCC( switch (clang_cc) { .C => return CallingConvention.C, .X86StdCall => return CallingConvention.Stdcall, - else => return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported calling convention: {}", @tagName(clang_cc)), + else => return revertAndWarn( + rp, + error.UnsupportedType, + source_loc, + "unsupported calling convention: {}", + .{@tagName(clang_cc)}, + ), } } @@ -1292,7 +1304,13 @@ fn transFnProto( const param_count: usize = ZigClangFunctionProtoType_getNumParams(fn_proto_ty); var i: usize = 0; while (i < param_count) : (i += 1) { - return revertAndWarn(rp, error.UnsupportedType, source_loc, "TODO: implement parameters for FunctionProto in transType"); + return revertAndWarn( + rp, + error.UnsupportedType, + source_loc, + "TODO: implement parameters for FunctionProto in transType", + .{}, + ); } return finishTransFnProto(rp, fn_ty, source_loc, fn_decl_context, is_var_args, cc, is_pub); @@ -1350,7 +1368,7 @@ fn finishTransFnProto( } else { break :blk transQualType(rp, return_qt, source_loc) catch |err| switch (err) { error.UnsupportedType => { - try emitWarning(rp.c, source_loc, "unsupported function proto return type"); + try emitWarning(rp.c, source_loc, "unsupported function proto return type", .{}); return err; }, error.OutOfMemory => |e| return e, @@ -1397,18 +1415,19 @@ fn revertAndWarn( err: var, source_loc: ZigClangSourceLocation, comptime format: []const u8, - args: ..., + args: var, ) (@typeOf(err) || error{OutOfMemory}) { rp.activate(); try emitWarning(rp.c, source_loc, format, args); return err; } -fn emitWarning(c: *Context, loc: ZigClangSourceLocation, comptime format: []const u8, args: ...) !void { - _ = try appendTokenFmt(c, .LineComment, "// {}: warning: " ++ format, c.locStr(loc), args); +fn emitWarning(c: *Context, loc: ZigClangSourceLocation, comptime format: []const u8, args: var) !void { + const args_prefix = .{c.locStr(loc)}; + _ = try appendTokenFmt(c, .LineComment, "// {}: warning: " ++ format, args_prefix ++ args); } -fn failDecl(c: *Context, loc: ZigClangSourceLocation, name: []const u8, comptime format: []const u8, args: ...) !void { +fn failDecl(c: *Context, loc: ZigClangSourceLocation, name: []const u8, comptime format: []const u8, args: var) !void { // const name = @compileError(msg); const const_tok = try appendToken(c, .Keyword_const, "const"); const name_tok = try appendToken(c, .Identifier, name); @@ -1456,10 +1475,10 @@ fn failDecl(c: *Context, loc: ZigClangSourceLocation, name: []const u8, comptime } fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenIndex { - return appendTokenFmt(c, token_id, "{}", bytes); + return appendTokenFmt(c, token_id, "{}", .{bytes}); } -fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: ...) !ast.TokenIndex { +fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex { const S = struct { fn callback(context: *Context, bytes: []const u8) error{OutOfMemory}!void { return context.source_buffer.append(bytes); diff --git a/src/ir.cpp b/src/ir.cpp index 09e0b70928..0f66965a80 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -17025,7 +17025,7 @@ static IrInstruction *ir_resolve_result(IrAnalyze *ira, IrInstruction *suspend_s { result_loc_pass1 = no_result_loc(); } - bool was_written = result_loc_pass1->written; + bool was_already_resolved = result_loc_pass1->resolved_loc != nullptr; IrInstruction *result_loc = ir_resolve_result_raw(ira, suspend_source_instr, result_loc_pass1, value_type, value, force_runtime, non_null_comptime, allow_discard); if (result_loc == nullptr || (instr_is_unreachable(result_loc) || type_is_invalid(result_loc->value->type))) @@ -17038,7 +17038,7 @@ static IrInstruction *ir_resolve_result(IrAnalyze *ira, IrInstruction *suspend_s } InferredStructField *isf = result_loc->value->type->data.pointer.inferred_struct_field; - if (!was_written && isf != nullptr) { + if (!was_already_resolved && isf != nullptr) { // Now it's time to add the field to the struct type. uint32_t old_field_count = isf->inferred_struct_type->data.structure.src_field_count; uint32_t new_field_count = old_field_count + 1; @@ -18077,7 +18077,11 @@ static IrInstruction *ir_analyze_fn_call(IrAnalyze *ira, IrInstruction *source_i if (type_is_invalid(result_loc->value->type) || instr_is_unreachable(result_loc)) { return result_loc; } - if (!handle_is_ptr(result_loc->value->type->data.pointer.child_type)) { + ZigType *res_child_type = result_loc->value->type->data.pointer.child_type; + if (res_child_type == ira->codegen->builtin_types.entry_var) { + res_child_type = impl_fn_type_id->return_type; + } + if (!handle_is_ptr(res_child_type)) { ir_reset_result(call_result_loc); result_loc = nullptr; } @@ -18240,7 +18244,11 @@ static IrInstruction *ir_analyze_fn_call(IrAnalyze *ira, IrInstruction *source_i if (type_is_invalid(result_loc->value->type) || instr_is_unreachable(result_loc)) { return result_loc; } - if (!handle_is_ptr(result_loc->value->type->data.pointer.child_type)) { + ZigType *res_child_type = result_loc->value->type->data.pointer.child_type; + if (res_child_type == ira->codegen->builtin_types.entry_var) { + res_child_type = return_type; + } + if (!handle_is_ptr(res_child_type)) { ir_reset_result(call_result_loc); result_loc = nullptr; } diff --git a/test/cli.zig b/test/cli.zig index b36742566a..0527b5c923 100644 --- a/test/cli.zig +++ b/test/cli.zig @@ -19,11 +19,11 @@ pub fn main() !void { a = &arena.allocator; const zig_exe_rel = try (arg_it.next(a) orelse { - std.debug.warn("Expected first argument to be path to zig compiler\n"); + std.debug.warn("Expected first argument to be path to zig compiler\n", .{}); return error.InvalidArgs; }); const cache_root = try (arg_it.next(a) orelse { - std.debug.warn("Expected second argument to be cache root directory path\n"); + std.debug.warn("Expected second argument to be cache root directory path\n", .{}); return error.InvalidArgs; }); const zig_exe = try fs.path.resolve(a, &[_][]const u8{zig_exe_rel}); @@ -45,39 +45,39 @@ pub fn main() !void { fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 { return arg catch |err| { - warn("Unable to parse command line: {}\n", err); + warn("Unable to parse command line: {}\n", .{err}); return err; }; } fn printCmd(cwd: []const u8, argv: []const []const u8) void { - std.debug.warn("cd {} && ", cwd); + std.debug.warn("cd {} && ", .{cwd}); for (argv) |arg| { - std.debug.warn("{} ", arg); + std.debug.warn("{} ", .{arg}); } - std.debug.warn("\n"); + std.debug.warn("\n", .{}); } fn exec(cwd: []const u8, argv: []const []const u8) !ChildProcess.ExecResult { const max_output_size = 100 * 1024; const result = ChildProcess.exec(a, argv, cwd, null, max_output_size) catch |err| { - std.debug.warn("The following command failed:\n"); + std.debug.warn("The following command failed:\n", .{}); printCmd(cwd, argv); return err; }; switch (result.term) { .Exited => |code| { if (code != 0) { - std.debug.warn("The following command exited with error code {}:\n", code); + std.debug.warn("The following command exited with error code {}:\n", .{code}); printCmd(cwd, argv); - std.debug.warn("stderr:\n{}\n", result.stderr); + std.debug.warn("stderr:\n{}\n", .{result.stderr}); return error.CommandFailed; } }, else => { - std.debug.warn("The following command terminated unexpectedly:\n"); + std.debug.warn("The following command terminated unexpectedly:\n", .{}); printCmd(cwd, argv); - std.debug.warn("stderr:\n{}\n", result.stderr); + std.debug.warn("stderr:\n{}\n", .{result.stderr}); return error.CommandFailed; }, } diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 3cdf8723ac..ebc57d264d 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -2598,14 +2598,12 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\fn a(b: fn (*const u8) void) void { \\ b('a'); \\} - \\fn c(d: u8) void { - \\ @import("std").debug.warn("{c}\n", d); - \\} + \\fn c(d: u8) void {} \\export fn entry() void { \\ a(c); \\} , - "tmp.zig:8:7: error: expected type 'fn(*const u8) void', found 'fn(u8) void'", + "tmp.zig:6:7: error: expected type 'fn(*const u8) void', found 'fn(u8) void'", ); cases.add( diff --git a/test/standalone/cat/main.zig b/test/standalone/cat/main.zig index f22329050c..f0cd9728ab 100644 --- a/test/standalone/cat/main.zig +++ b/test/standalone/cat/main.zig @@ -23,7 +23,7 @@ pub fn main() !void { return usage(exe); } else { const file = cwd.openFile(arg, .{}) catch |err| { - warn("Unable to open file: {}\n", @errorName(err)); + warn("Unable to open file: {}\n", .{@errorName(err)}); return err; }; defer file.close(); @@ -38,7 +38,7 @@ pub fn main() !void { } fn usage(exe: []const u8) !void { - warn("Usage: {} [FILE]...\n", exe); + warn("Usage: {} [FILE]...\n", .{exe}); return error.Invalid; } @@ -47,7 +47,7 @@ fn cat_file(stdout: fs.File, file: fs.File) !void { while (true) { const bytes_read = file.read(buf[0..]) catch |err| { - warn("Unable to read from stream: {}\n", @errorName(err)); + warn("Unable to read from stream: {}\n", .{@errorName(err)}); return err; }; @@ -56,7 +56,7 @@ fn cat_file(stdout: fs.File, file: fs.File) !void { } stdout.write(buf[0..bytes_read]) catch |err| { - warn("Unable to write to stdout: {}\n", @errorName(err)); + warn("Unable to write to stdout: {}\n", .{@errorName(err)}); return err; }; } @@ -64,7 +64,7 @@ fn cat_file(stdout: fs.File, file: fs.File) !void { fn unwrapArg(arg: anyerror![]u8) ![]u8 { return arg catch |err| { - warn("Unable to parse command line: {}\n", err); + warn("Unable to parse command line: {}\n", .{err}); return err; }; } diff --git a/test/standalone/guess_number/main.zig b/test/standalone/guess_number/main.zig index 8119b70d7e..588a4ddcbd 100644 --- a/test/standalone/guess_number/main.zig +++ b/test/standalone/guess_number/main.zig @@ -10,7 +10,7 @@ pub fn main() !void { var seed_bytes: [@sizeOf(u64)]u8 = undefined; std.crypto.randomBytes(seed_bytes[0..]) catch |err| { - std.debug.warn("unable to seed random number generator: {}", err); + std.debug.warn("unable to seed random number generator: {}", .{err}); return err; }; const seed = std.mem.readIntNative(u64, &seed_bytes); diff --git a/test/tests.zig b/test/tests.zig index f908b889f2..7548be6c4b 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -411,7 +411,7 @@ pub fn addPkgTests( is_qemu_enabled: bool, glibc_dir: ?[]const u8, ) *build.Step { - const step = b.step(b.fmt("test-{}", name), desc); + const step = b.step(b.fmt("test-{}", .{name}), desc); for (test_targets) |test_target| { if (skip_non_native and test_target.target != .Native) @@ -454,14 +454,14 @@ pub fn addPkgTests( test_target.target.zigTripleNoSubArch(b.allocator) catch unreachable; const these_tests = b.addTest(root_src); - these_tests.setNamePrefix(b.fmt( - "{}-{}-{}-{}-{} ", + const single_threaded_txt = if (test_target.single_threaded) "single" else "multi"; + these_tests.setNamePrefix(b.fmt("{}-{}-{}-{}-{} ", .{ name, triple_prefix, @tagName(test_target.mode), libc_prefix, - if (test_target.single_threaded) "single" else "multi", - )); + single_threaded_txt, + })); these_tests.single_threaded = test_target.single_threaded; these_tests.setFilter(test_filter); these_tests.setBuildMode(test_target.mode); @@ -562,7 +562,7 @@ pub const CompareOutputContext = struct { args.append(arg) catch unreachable; } - warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); + warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); const child = std.ChildProcess.init(args.toSliceConst(), b.allocator) catch unreachable; defer child.deinit(); @@ -572,7 +572,7 @@ pub const CompareOutputContext = struct { child.stderr_behavior = .Pipe; child.env_map = b.env_map; - child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err)); + child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); var stdout = Buffer.initNull(b.allocator); var stderr = Buffer.initNull(b.allocator); @@ -584,18 +584,18 @@ pub const CompareOutputContext = struct { stderr_file_in_stream.stream.readAllBuffer(&stderr, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err)); + debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); }; switch (term) { .Exited => |code| { if (code != 0) { - warn("Process {} exited with error code {}\n", full_exe_path, code); + warn("Process {} exited with error code {}\n", .{ full_exe_path, code }); printInvocation(args.toSliceConst()); return error.TestFailed; } }, else => { - warn("Process {} terminated unexpectedly\n", full_exe_path); + warn("Process {} terminated unexpectedly\n", .{full_exe_path}); printInvocation(args.toSliceConst()); return error.TestFailed; }, @@ -609,10 +609,10 @@ pub const CompareOutputContext = struct { \\========= But found: ==================== \\{} \\ - , self.expected_output, stdout.toSliceConst()); + , .{ self.expected_output, stdout.toSliceConst() }); return error.TestFailed; } - warn("OK\n"); + warn("OK\n", .{}); } }; @@ -644,7 +644,7 @@ pub const CompareOutputContext = struct { const full_exe_path = self.exe.getOutputPath(); - warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); + warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); const child = std.ChildProcess.init(&[_][]const u8{full_exe_path}, b.allocator) catch unreachable; defer child.deinit(); @@ -655,28 +655,34 @@ pub const CompareOutputContext = struct { child.stderr_behavior = .Ignore; const term = child.spawnAndWait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err)); + debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); }; const expected_exit_code: u32 = 126; switch (term) { .Exited => |code| { if (code != expected_exit_code) { - warn("\nProgram expected to exit with code {} " ++ "but exited with code {}\n", expected_exit_code, code); + warn("\nProgram expected to exit with code {} but exited with code {}\n", .{ + expected_exit_code, code, + }); return error.TestFailed; } }, .Signal => |sig| { - warn("\nProgram expected to exit with code {} " ++ "but instead signaled {}\n", expected_exit_code, sig); + warn("\nProgram expected to exit with code {} but instead signaled {}\n", .{ + expected_exit_code, sig, + }); return error.TestFailed; }, else => { - warn("\nProgram expected to exit with code {}" ++ " but exited in an unexpected way\n", expected_exit_code); + warn("\nProgram expected to exit with code {} but exited in an unexpected way\n", .{ + expected_exit_code, + }); return error.TestFailed; }, } - warn("OK\n"); + warn("OK\n", .{}); } }; @@ -729,7 +735,9 @@ pub const CompareOutputContext = struct { switch (case.special) { Special.Asm => { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {}", case.name) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {}", .{ + case.name, + }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -758,7 +766,11 @@ pub const CompareOutputContext = struct { }, Special.None => { for (self.modes) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", "compare-output", case.name, @tagName(mode)) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{ + "compare-output", + case.name, + @tagName(mode), + }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } @@ -790,7 +802,7 @@ pub const CompareOutputContext = struct { } }, Special.RuntimeSafety => { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {}", case.name) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {}", .{case.name}) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -843,7 +855,11 @@ pub const StackTracesContext = struct { const expect_for_mode = expect[@enumToInt(mode)]; if (expect_for_mode.len == 0) continue; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", "stack-trace", name, @tagName(mode)) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{ + "stack-trace", + name, + @tagName(mode), + }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } @@ -907,7 +923,7 @@ pub const StackTracesContext = struct { defer args.deinit(); args.append(full_exe_path) catch unreachable; - warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); + warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); const child = std.ChildProcess.init(args.toSliceConst(), b.allocator) catch unreachable; defer child.deinit(); @@ -917,7 +933,7 @@ pub const StackTracesContext = struct { child.stderr_behavior = .Pipe; child.env_map = b.env_map; - child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err)); + child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); var stdout = Buffer.initNull(b.allocator); var stderr = Buffer.initNull(b.allocator); @@ -929,30 +945,34 @@ pub const StackTracesContext = struct { stderr_file_in_stream.stream.readAllBuffer(&stderr, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err)); + debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); }; switch (term) { .Exited => |code| { const expect_code: u32 = 1; if (code != expect_code) { - warn("Process {} exited with error code {} but expected code {}\n", full_exe_path, code, expect_code); + warn("Process {} exited with error code {} but expected code {}\n", .{ + full_exe_path, + code, + expect_code, + }); printInvocation(args.toSliceConst()); return error.TestFailed; } }, .Signal => |signum| { - warn("Process {} terminated on signal {}\n", full_exe_path, signum); + warn("Process {} terminated on signal {}\n", .{ full_exe_path, signum }); printInvocation(args.toSliceConst()); return error.TestFailed; }, .Stopped => |signum| { - warn("Process {} stopped on signal {}\n", full_exe_path, signum); + warn("Process {} stopped on signal {}\n", .{ full_exe_path, signum }); printInvocation(args.toSliceConst()); return error.TestFailed; }, .Unknown => |code| { - warn("Process {} terminated unexpectedly with error code {}\n", full_exe_path, code); + warn("Process {} terminated unexpectedly with error code {}\n", .{ full_exe_path, code }); printInvocation(args.toSliceConst()); return error.TestFailed; }, @@ -1003,10 +1023,10 @@ pub const StackTracesContext = struct { \\================================================ \\{} \\ - , self.expect_output, got); + , .{ self.expect_output, got }); return error.TestFailed; } - warn("OK\n"); + warn("OK\n", .{}); } }; }; @@ -1129,7 +1149,7 @@ pub const CompileErrorContext = struct { Mode.ReleaseSmall => zig_args.append("--release-small") catch unreachable, } - warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); + warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); if (b.verbose) { printInvocation(zig_args.toSliceConst()); @@ -1143,7 +1163,7 @@ pub const CompileErrorContext = struct { child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; - child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", zig_args.items[0], @errorName(err)); + child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) }); var stdout_buf = Buffer.initNull(b.allocator); var stderr_buf = Buffer.initNull(b.allocator); @@ -1155,7 +1175,7 @@ pub const CompileErrorContext = struct { stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", zig_args.items[0], @errorName(err)); + debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) }); }; switch (term) { .Exited => |code| { @@ -1165,7 +1185,7 @@ pub const CompileErrorContext = struct { } }, else => { - warn("Process {} terminated unexpectedly\n", b.zig_exe); + warn("Process {} terminated unexpectedly\n", .{b.zig_exe}); printInvocation(zig_args.toSliceConst()); return error.TestFailed; }, @@ -1182,7 +1202,7 @@ pub const CompileErrorContext = struct { \\{} \\================================================ \\ - , stdout); + , .{stdout}); return error.TestFailed; } @@ -1200,9 +1220,9 @@ pub const CompileErrorContext = struct { ok = ok and i == self.case.expected_errors.len; if (!ok) { - warn("\n======== Expected these compile errors: ========\n"); + warn("\n======== Expected these compile errors: ========\n", .{}); for (self.case.expected_errors.toSliceConst()) |expected| { - warn("{}\n", expected); + warn("{}\n", .{expected}); } } } else { @@ -1213,7 +1233,7 @@ pub const CompileErrorContext = struct { \\=========== Expected compile error: ============ \\{} \\ - , expected); + , .{expected}); ok = false; break; } @@ -1225,11 +1245,11 @@ pub const CompileErrorContext = struct { \\================= Full output: ================= \\{} \\ - , stderr); + , .{stderr}); return error.TestFailed; } - warn("OK\n"); + warn("OK\n", .{}); } }; @@ -1279,7 +1299,9 @@ pub const CompileErrorContext = struct { pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void { const b = self.b; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {}", case.name) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {}", .{ + case.name, + }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -1316,7 +1338,7 @@ pub const StandaloneContext = struct { pub fn addBuildFile(self: *StandaloneContext, build_file: []const u8) void { const b = self.b; - const annotated_case_name = b.fmt("build {} (Debug)", build_file); + const annotated_case_name = b.fmt("build {} (Debug)", .{build_file}); if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -1337,7 +1359,7 @@ pub const StandaloneContext = struct { const run_cmd = b.addSystemCommand(zig_args.toSliceConst()); - const log_step = b.addLog("PASS {}\n", annotated_case_name); + const log_step = b.addLog("PASS {}\n", .{annotated_case_name}); log_step.step.dependOn(&run_cmd.step); self.step.dependOn(&log_step.step); @@ -1347,7 +1369,10 @@ pub const StandaloneContext = struct { const b = self.b; for (self.modes) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {} ({})", root_src, @tagName(mode)) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {} ({})", .{ + root_src, + @tagName(mode), + }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } @@ -1358,7 +1383,7 @@ pub const StandaloneContext = struct { exe.linkSystemLibrary("c"); } - const log_step = b.addLog("PASS {}\n", annotated_case_name); + const log_step = b.addLog("PASS {}\n", .{annotated_case_name}); log_step.step.dependOn(&exe.step); self.step.dependOn(&log_step.step); @@ -1434,7 +1459,7 @@ pub const TranslateCContext = struct { zig_args.append(translate_c_cmd) catch unreachable; zig_args.append(b.pathFromRoot(root_src)) catch unreachable; - warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); + warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); if (b.verbose) { printInvocation(zig_args.toSliceConst()); @@ -1448,7 +1473,10 @@ pub const TranslateCContext = struct { child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; - child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", zig_args.toSliceConst()[0], @errorName(err)); + child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ + zig_args.toSliceConst()[0], + @errorName(err), + }); var stdout_buf = Buffer.initNull(b.allocator); var stderr_buf = Buffer.initNull(b.allocator); @@ -1460,23 +1488,23 @@ pub const TranslateCContext = struct { stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", zig_args.toSliceConst()[0], @errorName(err)); + debug.panic("Unable to spawn {}: {}\n", .{ zig_args.toSliceConst()[0], @errorName(err) }); }; switch (term) { .Exited => |code| { if (code != 0) { - warn("Compilation failed with exit code {}\n", code); + warn("Compilation failed with exit code {}\n", .{code}); printInvocation(zig_args.toSliceConst()); return error.TestFailed; } }, .Signal => |code| { - warn("Compilation failed with signal {}\n", code); + warn("Compilation failed with signal {}\n", .{code}); printInvocation(zig_args.toSliceConst()); return error.TestFailed; }, else => { - warn("Compilation terminated unexpectedly\n"); + warn("Compilation terminated unexpectedly\n", .{}); printInvocation(zig_args.toSliceConst()); return error.TestFailed; }, @@ -1491,7 +1519,7 @@ pub const TranslateCContext = struct { \\{} \\============================================ \\ - , stderr); + , .{stderr}); printInvocation(zig_args.toSliceConst()); return error.TestFailed; } @@ -1505,20 +1533,20 @@ pub const TranslateCContext = struct { \\========= But found: =========================== \\{} \\ - , expected_line, stdout); + , .{ expected_line, stdout }); printInvocation(zig_args.toSliceConst()); return error.TestFailed; } } - warn("OK\n"); + warn("OK\n", .{}); } }; fn printInvocation(args: []const []const u8) void { for (args) |arg| { - warn("{} ", arg); + warn("{} ", .{arg}); } - warn("\n"); + warn("\n", .{}); } pub fn create(self: *TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) *TestCase { @@ -1586,7 +1614,7 @@ pub const TranslateCContext = struct { const b = self.b; const translate_c_cmd = if (case.stage2) "translate-c-2" else "translate-c"; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {}", translate_c_cmd, case.name) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {}", .{ translate_c_cmd, case.name }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -1666,7 +1694,7 @@ pub const GenHContext = struct { const self = @fieldParentPtr(GenHCmpOutputStep, "step", step); const b = self.context.b; - warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); + warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); const full_h_path = self.obj.getOutputHPath(); const actual_h = try io.readFileAlloc(b.allocator, full_h_path); @@ -1680,19 +1708,19 @@ pub const GenHContext = struct { \\========= But found: =========================== \\{} \\ - , expected_line, actual_h); + , .{ expected_line, actual_h }); return error.TestFailed; } } - warn("OK\n"); + warn("OK\n", .{}); } }; fn printInvocation(args: []const []const u8) void { for (args) |arg| { - warn("{} ", arg); + warn("{} ", .{arg}); } - warn("\n"); + warn("\n", .{}); } pub fn create(self: *GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) *TestCase { @@ -1724,7 +1752,7 @@ pub const GenHContext = struct { ) catch unreachable; const mode = builtin.Mode.Debug; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {} ({})", case.name, @tagName(mode)) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {} ({})", .{ case.name, @tagName(mode) }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -1749,7 +1777,7 @@ pub const GenHContext = struct { fn printInvocation(args: []const []const u8) void { for (args) |arg| { - warn("{} ", arg); + warn("{} ", .{arg}); } - warn("\n"); + warn("\n", .{}); } From fe4963412f939d4f72eb5f0153a253116206749b Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 8 Dec 2019 23:17:03 -0500 Subject: [PATCH 2/7] update self-hosted compiler to new format API --- src-self-hosted/codegen.zig | 14 +++-- src-self-hosted/compilation.zig | 27 +++++----- src-self-hosted/errmsg.zig | 12 ++--- src-self-hosted/introspect.zig | 2 +- src-self-hosted/ir.zig | 78 +++++++++++++-------------- src-self-hosted/libc_installation.zig | 28 +++++----- src-self-hosted/link.zig | 33 +++++++----- src-self-hosted/main.zig | 49 +++++++++-------- src-self-hosted/type.zig | 26 ++++----- src-self-hosted/util.zig | 4 +- src-self-hosted/value.zig | 2 +- 11 files changed, 133 insertions(+), 142 deletions(-) diff --git a/src-self-hosted/codegen.zig b/src-self-hosted/codegen.zig index 030112985a..702f2c2883 100644 --- a/src-self-hosted/codegen.zig +++ b/src-self-hosted/codegen.zig @@ -45,13 +45,11 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) // Don't use ZIG_VERSION_STRING here. LLVM misparses it when it includes // the git revision. - const producer = try std.Buffer.allocPrint( - &code.arena.allocator, - "zig {}.{}.{}", + const producer = try std.Buffer.allocPrint(&code.arena.allocator, "zig {}.{}.{}", .{ @as(u32, c.ZIG_VERSION_MAJOR), @as(u32, c.ZIG_VERSION_MINOR), @as(u32, c.ZIG_VERSION_PATCH), - ); + }); const flags = ""; const runtime_version = 0; const compile_unit_file = llvm.CreateFile( @@ -93,7 +91,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) llvm.DIBuilderFinalize(dibuilder); if (comp.verbose_llvm_ir) { - std.debug.warn("raw module:\n"); + std.debug.warn("raw module:\n", .{}); llvm.DumpModule(ofile.module); } @@ -120,18 +118,18 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) is_small, )) { if (std.debug.runtime_safety) { - std.debug.panic("unable to write object file {}: {s}\n", output_path.toSliceConst(), err_msg); + std.debug.panic("unable to write object file {}: {s}\n", .{ output_path.toSliceConst(), err_msg }); } return error.WritingObjectFileFailed; } //validate_inline_fns(g); TODO fn_val.containing_object = output_path; if (comp.verbose_llvm_ir) { - std.debug.warn("optimized module:\n"); + std.debug.warn("optimized module:\n", .{}); llvm.DumpModule(ofile.module); } if (comp.verbose_link) { - std.debug.warn("created {}\n", output_path.toSliceConst()); + std.debug.warn("created {}\n", .{output_path.toSliceConst()}); } } diff --git a/src-self-hosted/compilation.zig b/src-self-hosted/compilation.zig index a825ba3903..47ea595cad 100644 --- a/src-self-hosted/compilation.zig +++ b/src-self-hosted/compilation.zig @@ -807,7 +807,7 @@ pub const Compilation = struct { root_scope.realpath, max_src_size, ) catch |err| { - try self.addCompileErrorCli(root_scope.realpath, "unable to open: {}", @errorName(err)); + try self.addCompileErrorCli(root_scope.realpath, "unable to open: {}", .{@errorName(err)}); return; }; errdefer self.gpa().free(source_code); @@ -878,7 +878,7 @@ pub const Compilation = struct { try self.addCompileError(tree_scope, Span{ .first = fn_proto.fn_token, .last = fn_proto.fn_token + 1, - }, "missing function name"); + }, "missing function name", .{}); continue; }; @@ -942,7 +942,7 @@ pub const Compilation = struct { const root_scope = blk: { // TODO async/await std.fs.realpath const root_src_real_path = std.fs.realpathAlloc(self.gpa(), root_src_path) catch |err| { - try self.addCompileErrorCli(root_src_path, "unable to open: {}", @errorName(err)); + try self.addCompileErrorCli(root_src_path, "unable to open: {}", .{@errorName(err)}); return; }; errdefer self.gpa().free(root_src_real_path); @@ -991,7 +991,7 @@ pub const Compilation = struct { defer unanalyzed_code.destroy(comp.gpa()); if (comp.verbose_ir) { - std.debug.warn("unanalyzed:\n"); + std.debug.warn("unanalyzed:\n", .{}); unanalyzed_code.dump(); } @@ -1003,7 +1003,7 @@ pub const Compilation = struct { errdefer analyzed_code.destroy(comp.gpa()); if (comp.verbose_ir) { - std.debug.warn("analyzed:\n"); + std.debug.warn("analyzed:\n", .{}); analyzed_code.dump(); } @@ -1048,14 +1048,14 @@ pub const Compilation = struct { const gop = try locked_table.getOrPut(decl.name); if (gop.found_existing) { - try self.addCompileError(decl.tree_scope, decl.getSpan(), "redefinition of '{}'", decl.name); + try self.addCompileError(decl.tree_scope, decl.getSpan(), "redefinition of '{}'", .{decl.name}); // TODO note: other definition here } else { gop.kv.value = decl; } } - fn addCompileError(self: *Compilation, tree_scope: *Scope.AstTree, span: Span, comptime fmt: []const u8, args: ...) !void { + fn addCompileError(self: *Compilation, tree_scope: *Scope.AstTree, span: Span, comptime fmt: []const u8, args: var) !void { const text = try std.fmt.allocPrint(self.gpa(), fmt, args); errdefer self.gpa().free(text); @@ -1065,7 +1065,7 @@ pub const Compilation = struct { try self.prelink_group.call(addCompileErrorAsync, self, msg); } - fn addCompileErrorCli(self: *Compilation, realpath: []const u8, comptime fmt: []const u8, args: ...) !void { + fn addCompileErrorCli(self: *Compilation, realpath: []const u8, comptime fmt: []const u8, args: var) !void { const text = try std.fmt.allocPrint(self.gpa(), fmt, args); errdefer self.gpa().free(text); @@ -1092,12 +1092,9 @@ pub const Compilation = struct { defer exported_symbol_names.release(); if (try exported_symbol_names.value.put(decl.name, decl)) |other_decl| { - try self.addCompileError( - decl.tree_scope, - decl.getSpan(), - "exported symbol collision: '{}'", + try self.addCompileError(decl.tree_scope, decl.getSpan(), "exported symbol collision: '{}'", .{ decl.name, - ); + }); // TODO add error note showing location of other symbol } } @@ -1162,7 +1159,7 @@ pub const Compilation = struct { const tmp_dir = try self.getTmpDir(); const file_prefix = self.getRandomFileName(); - const file_name = try std.fmt.allocPrint(self.gpa(), "{}{}", file_prefix[0..], suffix); + const file_name = try std.fmt.allocPrint(self.gpa(), "{}{}", .{ file_prefix[0..], suffix }); defer self.gpa().free(file_name); const full_path = try std.fs.path.join(self.gpa(), &[_][]const u8{ tmp_dir, file_name[0..] }); @@ -1303,7 +1300,7 @@ fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void { try comp.addCompileError(tree_scope, Span{ .first = param_decl.firstToken(), .last = param_decl.type_node.firstToken(), - }, "missing parameter name"); + }, "missing parameter name", .{}); return error.SemanticAnalysisFailed; }; const param_name = tree_scope.tree.tokenSlice(name_token); diff --git a/src-self-hosted/errmsg.zig b/src-self-hosted/errmsg.zig index 9782fdda1c..c1ebf0058e 100644 --- a/src-self-hosted/errmsg.zig +++ b/src-self-hosted/errmsg.zig @@ -231,7 +231,7 @@ pub const Msg = struct { pub fn printToStream(msg: *const Msg, stream: var, color_on: bool) !void { switch (msg.data) { .Cli => { - try stream.print("{}:-:-: error: {}\n", msg.realpath, msg.text); + try stream.print("{}:-:-: error: {}\n", .{ msg.realpath, msg.text }); return; }, else => {}, @@ -254,24 +254,22 @@ pub const Msg = struct { const start_loc = tree.tokenLocationPtr(0, first_token); const end_loc = tree.tokenLocationPtr(first_token.end, last_token); if (!color_on) { - try stream.print( - "{}:{}:{}: error: {}\n", + try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, msg.text, - ); + }); return; } - try stream.print( - "{}:{}:{}: error: {}\n{}\n", + try stream.print("{}:{}:{}: error: {}\n{}\n", .{ path, start_loc.line + 1, start_loc.column + 1, msg.text, tree.source[start_loc.line_start..start_loc.line_end], - ); + }); try stream.writeByteNTimes(' ', start_loc.column); try stream.writeByteNTimes('~', last_token.end - first_token.start); try stream.write("\n"); diff --git a/src-self-hosted/introspect.zig b/src-self-hosted/introspect.zig index 8f822c79df..67181b40a8 100644 --- a/src-self-hosted/introspect.zig +++ b/src-self-hosted/introspect.zig @@ -48,7 +48,7 @@ pub fn resolveZigLibDir(allocator: *mem.Allocator) ![]u8 { \\Unable to find zig lib directory: {}. \\Reinstall Zig or use --zig-install-prefix. \\ - , @errorName(err)); + , .{@errorName(err)}); return error.ZigLibDirNotFound; }; diff --git a/src-self-hosted/ir.zig b/src-self-hosted/ir.zig index 1d11d7969d..741dbb6e3d 100644 --- a/src-self-hosted/ir.zig +++ b/src-self-hosted/ir.zig @@ -32,16 +32,16 @@ pub const IrVal = union(enum) { pub fn dump(self: IrVal) void { switch (self) { - .Unknown => std.debug.warn("Unknown"), + .Unknown => std.debug.warn("Unknown", .{}), .KnownType => |typ| { - std.debug.warn("KnownType("); + std.debug.warn("KnownType(", .{}); typ.dump(); - std.debug.warn(")"); + std.debug.warn(")", .{}); }, .KnownValue => |value| { - std.debug.warn("KnownValue("); + std.debug.warn("KnownValue(", .{}); value.dump(); - std.debug.warn(")"); + std.debug.warn(")", .{}); }, } } @@ -90,9 +90,9 @@ pub const Inst = struct { inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Inst, @memberName(Id, i)); - std.debug.warn("#{} = {}(", base.debug_id, @tagName(base.id)); + std.debug.warn("#{} = {}(", .{ base.debug_id, @tagName(base.id) }); @fieldParentPtr(T, "base", base).dump(); - std.debug.warn(")"); + std.debug.warn(")", .{}); return; } } @@ -173,7 +173,7 @@ pub const Inst = struct { if (self.isCompTime()) { return self.val.KnownValue; } else { - try ira.addCompileError(self.span, "unable to evaluate constant expression"); + try ira.addCompileError(self.span, "unable to evaluate constant expression", .{}); return error.SemanticAnalysisFailed; } } @@ -269,11 +269,11 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.Unknown; pub fn dump(self: *const Call) void { - std.debug.warn("#{}(", self.params.fn_ref.debug_id); + std.debug.warn("#{}(", .{self.params.fn_ref.debug_id}); for (self.params.args) |arg| { - std.debug.warn("#{},", arg.debug_id); + std.debug.warn("#{},", .{arg.debug_id}); } - std.debug.warn(")"); + std.debug.warn(")", .{}); } pub fn hasSideEffects(self: *const Call) bool { @@ -284,19 +284,17 @@ pub const Inst = struct { const fn_ref = try self.params.fn_ref.getAsParam(); const fn_ref_type = fn_ref.getKnownType(); const fn_type = fn_ref_type.cast(Type.Fn) orelse { - try ira.addCompileError(fn_ref.span, "type '{}' not a function", fn_ref_type.name); + try ira.addCompileError(fn_ref.span, "type '{}' not a function", .{fn_ref_type.name}); return error.SemanticAnalysisFailed; }; const fn_type_param_count = fn_type.paramCount(); if (fn_type_param_count != self.params.args.len) { - try ira.addCompileError( - self.base.span, - "expected {} arguments, found {}", + try ira.addCompileError(self.base.span, "expected {} arguments, found {}", .{ fn_type_param_count, self.params.args.len, - ); + }); return error.SemanticAnalysisFailed; } @@ -375,7 +373,7 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.NoReturn; pub fn dump(self: *const Return) void { - std.debug.warn("#{}", self.params.return_value.debug_id); + std.debug.warn("#{}", .{self.params.return_value.debug_id}); } pub fn hasSideEffects(self: *const Return) bool { @@ -509,7 +507,7 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.Unknown; pub fn dump(inst: *const VarPtr) void { - std.debug.warn("{}", inst.params.var_scope.name); + std.debug.warn("{}", .{inst.params.var_scope.name}); } pub fn hasSideEffects(inst: *const VarPtr) bool { @@ -567,7 +565,7 @@ pub const Inst = struct { const target = try self.params.target.getAsParam(); const target_type = target.getKnownType(); if (target_type.id != .Pointer) { - try ira.addCompileError(self.base.span, "dereference of non pointer type '{}'", target_type.name); + try ira.addCompileError(self.base.span, "dereference of non pointer type '{}'", .{target_type.name}); return error.SemanticAnalysisFailed; } const ptr_type = @fieldParentPtr(Type.Pointer, "base", target_type); @@ -705,7 +703,7 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.Unknown; pub fn dump(self: *const CheckVoidStmt) void { - std.debug.warn("#{}", self.params.target.debug_id); + std.debug.warn("#{}", .{self.params.target.debug_id}); } pub fn hasSideEffects(inst: *const CheckVoidStmt) bool { @@ -715,7 +713,7 @@ pub const Inst = struct { pub fn analyze(self: *const CheckVoidStmt, ira: *Analyze) !*Inst { const target = try self.params.target.getAsParam(); if (target.getKnownType().id != .Void) { - try ira.addCompileError(self.base.span, "expression value is ignored"); + try ira.addCompileError(self.base.span, "expression value is ignored", .{}); return error.SemanticAnalysisFailed; } return ira.irb.buildConstVoid(self.base.scope, self.base.span, true); @@ -801,7 +799,7 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.Unknown; pub fn dump(inst: *const AddImplicitReturnType) void { - std.debug.warn("#{}", inst.params.target.debug_id); + std.debug.warn("#{}", .{inst.params.target.debug_id}); } pub fn hasSideEffects(inst: *const AddImplicitReturnType) bool { @@ -826,7 +824,7 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.Unknown; pub fn dump(inst: *const TestErr) void { - std.debug.warn("#{}", inst.params.target.debug_id); + std.debug.warn("#{}", .{inst.params.target.debug_id}); } pub fn hasSideEffects(inst: *const TestErr) bool { @@ -888,7 +886,7 @@ pub const Inst = struct { const ir_val_init = IrVal.Init.Unknown; pub fn dump(inst: *const TestCompTime) void { - std.debug.warn("#{}", inst.params.target.debug_id); + std.debug.warn("#{}", .{inst.params.target.debug_id}); } pub fn hasSideEffects(inst: *const TestCompTime) bool { @@ -971,11 +969,11 @@ pub const Code = struct { pub fn dump(self: *Code) void { var bb_i: usize = 0; for (self.basic_block_list.toSliceConst()) |bb| { - std.debug.warn("{s}_{}:\n", bb.name_hint, bb.debug_id); + std.debug.warn("{s}_{}:\n", .{ bb.name_hint, bb.debug_id }); for (bb.instruction_list.toSliceConst()) |instr| { - std.debug.warn(" "); + std.debug.warn(" ", .{}); instr.dump(); - std.debug.warn("\n"); + std.debug.warn("\n", .{}); } } } @@ -993,6 +991,7 @@ pub const Code = struct { self.tree_scope, ret_value.span, "unable to evaluate constant expression", + .{}, ); return error.SemanticAnalysisFailed; } else if (inst.hasSideEffects()) { @@ -1000,6 +999,7 @@ pub const Code = struct { self.tree_scope, inst.span, "unable to evaluate constant expression", + .{}, ); return error.SemanticAnalysisFailed; } @@ -1359,7 +1359,7 @@ pub const Builder = struct { irb.code.tree_scope, src_span, "invalid character in string literal: '{c}'", - str_token[bad_index], + .{str_token[bad_index]}, ); return error.SemanticAnalysisFailed; }, @@ -1523,6 +1523,7 @@ pub const Builder = struct { irb.code.tree_scope, src_span, "return expression outside function definition", + .{}, ); return error.SemanticAnalysisFailed; } @@ -1533,6 +1534,7 @@ pub const Builder = struct { irb.code.tree_scope, src_span, "cannot return from defer expression", + .{}, ); scope_defer_expr.reported_err = true; } @@ -1629,7 +1631,7 @@ pub const Builder = struct { } } else |err| switch (err) { error.Overflow => { - try irb.comp.addCompileError(irb.code.tree_scope, src_span, "integer too large"); + try irb.comp.addCompileError(irb.code.tree_scope, src_span, "integer too large", .{}); return error.SemanticAnalysisFailed; }, error.OutOfMemory => return error.OutOfMemory, @@ -1663,7 +1665,7 @@ pub const Builder = struct { // TODO put a variable of same name with invalid type in global scope // so that future references to this same name will find a variable with an invalid type - try irb.comp.addCompileError(irb.code.tree_scope, src_span, "unknown identifier '{}'", name); + try irb.comp.addCompileError(irb.code.tree_scope, src_span, "unknown identifier '{}'", .{name}); return error.SemanticAnalysisFailed; } @@ -2008,7 +2010,7 @@ const Analyze = struct { const next_instruction = ira.parent_basic_block.instruction_list.at(ira.instruction_index); if (!next_instruction.is_generated) { - try ira.addCompileError(next_instruction.span, "unreachable code"); + try ira.addCompileError(next_instruction.span, "unreachable code", .{}); break; } ira.instruction_index += 1; @@ -2041,7 +2043,7 @@ const Analyze = struct { } } - fn addCompileError(self: *Analyze, span: Span, comptime fmt: []const u8, args: ...) !void { + fn addCompileError(self: *Analyze, span: Span, comptime fmt: []const u8, args: var) !void { return self.irb.comp.addCompileError(self.irb.code.tree_scope, span, fmt, args); } @@ -2330,12 +2332,10 @@ const Analyze = struct { break :cast; }; if (!fits) { - try ira.addCompileError( - source_instr.span, - "integer value '{}' cannot be stored in type '{}'", + try ira.addCompileError(source_instr.span, "integer value '{}' cannot be stored in type '{}'", .{ from_int, dest_type.name, - ); + }); return error.SemanticAnalysisFailed; } @@ -2498,12 +2498,10 @@ const Analyze = struct { // } //} - try ira.addCompileError( - source_instr.span, - "expected type '{}', found '{}'", + try ira.addCompileError(source_instr.span, "expected type '{}', found '{}'", .{ dest_type.name, from_type.name, - ); + }); //ErrorMsg *parent_msg = ir_add_error_node(ira, source_instr->source_node, // buf_sprintf("expected type '%s', found '%s'", // buf_ptr(&wanted_type->name), diff --git a/src-self-hosted/libc_installation.zig b/src-self-hosted/libc_installation.zig index b339a07c90..970fc97823 100644 --- a/src-self-hosted/libc_installation.zig +++ b/src-self-hosted/libc_installation.zig @@ -65,7 +65,7 @@ pub const LibCInstallation = struct { if (line.len == 0 or line[0] == '#') continue; var line_it = std.mem.separate(line, "="); const name = line_it.next() orelse { - try stderr.print("missing equal sign after field name\n"); + try stderr.print("missing equal sign after field name\n", .{}); return error.ParseError; }; const value = line_it.rest(); @@ -83,7 +83,7 @@ pub const LibCInstallation = struct { }, else => { if (value.len == 0) { - try stderr.print("field cannot be empty: {}\n", key); + try stderr.print("field cannot be empty: {}\n", .{key}); return error.ParseError; } const dupe = try std.mem.dupe(allocator, u8, value); @@ -97,7 +97,7 @@ pub const LibCInstallation = struct { } for (found_keys) |found_key, i| { if (!found_key.found) { - try stderr.print("missing field: {}\n", keys[i]); + try stderr.print("missing field: {}\n", .{keys[i]}); return error.ParseError; } } @@ -105,6 +105,11 @@ pub const LibCInstallation = struct { pub fn render(self: *const LibCInstallation, out: *std.io.OutStream(fs.File.WriteError)) !void { @setEvalBranchQuota(4000); + const lib_dir = self.lib_dir orelse ""; + const static_lib_dir = self.static_lib_dir orelse ""; + const msvc_lib_dir = self.msvc_lib_dir orelse ""; + const kernel32_lib_dir = self.kernel32_lib_dir orelse ""; + const dynamic_linker_path = self.dynamic_linker_path orelse util.getDynamicLinkerPath(Target{ .Native = {} }); try out.print( \\# The directory that contains `stdlib.h`. \\# On Linux, can be found with: `cc -E -Wp,-v -xc /dev/null` @@ -132,14 +137,7 @@ pub const LibCInstallation = struct { \\# Only needed when targeting Linux. \\dynamic_linker_path={} \\ - , - self.include_dir, - self.lib_dir orelse "", - self.static_lib_dir orelse "", - self.msvc_lib_dir orelse "", - self.kernel32_lib_dir orelse "", - self.dynamic_linker_path orelse util.getDynamicLinkerPath(Target{ .Native = {} }), - ); + , .{ self.include_dir, lib_dir, static_lib_dir, msvc_lib_dir, kernel32_lib_dir, dynamic_linker_path }); } /// Finds the default, native libc. @@ -255,7 +253,7 @@ pub const LibCInstallation = struct { for (searches) |search| { result_buf.shrink(0); const stream = &std.io.BufferOutStream.init(&result_buf).stream; - try stream.print("{}\\Include\\{}\\ucrt", search.path, search.version); + try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version }); const stdlib_path = try fs.path.join( allocator, @@ -282,7 +280,7 @@ pub const LibCInstallation = struct { for (searches) |search| { result_buf.shrink(0); const stream = &std.io.BufferOutStream.init(&result_buf).stream; - try stream.print("{}\\Lib\\{}\\ucrt\\", search.path, search.version); + try stream.print("{}\\Lib\\{}\\ucrt\\", .{ search.path, search.version }); switch (builtin.arch) { .i386 => try stream.write("x86"), .x86_64 => try stream.write("x64"), @@ -360,7 +358,7 @@ pub const LibCInstallation = struct { for (searches) |search| { result_buf.shrink(0); const stream = &std.io.BufferOutStream.init(&result_buf).stream; - try stream.print("{}\\Lib\\{}\\um\\", search.path, search.version); + try stream.print("{}\\Lib\\{}\\um\\", .{ search.path, search.version }); switch (builtin.arch) { .i386 => try stream.write("x86\\"), .x86_64 => try stream.write("x64\\"), @@ -395,7 +393,7 @@ pub const LibCInstallation = struct { /// caller owns returned memory fn ccPrintFileName(allocator: *Allocator, o_file: []const u8, want_dirname: bool) ![]u8 { const cc_exe = std.os.getenv("CC") orelse "cc"; - const arg1 = try std.fmt.allocPrint(allocator, "-print-file-name={}", o_file); + const arg1 = try std.fmt.allocPrint(allocator, "-print-file-name={}", .{o_file}); defer allocator.free(arg1); const argv = [_][]const u8{ cc_exe, arg1 }; diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index 339acfd3ef..935b2f2937 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -75,9 +75,9 @@ pub fn link(comp: *Compilation) !void { if (comp.verbose_link) { for (ctx.args.toSliceConst()) |arg, i| { const space = if (i == 0) "" else " "; - std.debug.warn("{}{s}", space, arg); + std.debug.warn("{}{s}", .{ space, arg }); } - std.debug.warn("\n"); + std.debug.warn("\n", .{}); } const extern_ofmt = toExternObjectFormatType(util.getObjectFormat(comp.target)); @@ -94,7 +94,7 @@ pub fn link(comp: *Compilation) !void { // TODO capture these messages and pass them through the system, reporting them through the // event system instead of printing them directly here. // perhaps try to parse and understand them. - std.debug.warn("{}\n", ctx.link_msg.toSliceConst()); + std.debug.warn("{}\n", .{ctx.link_msg.toSliceConst()}); } return error.LinkFailed; } @@ -334,13 +334,13 @@ fn constructLinkerArgsCoff(ctx: *Context) !void { const is_library = ctx.comp.kind == .Lib; - const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", ctx.out_file_path.toSliceConst()); + const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", .{ctx.out_file_path.toSliceConst()}); try ctx.args.append(@ptrCast([*:0]const u8, out_arg.ptr)); if (ctx.comp.haveLibC()) { - try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.msvc_lib_dir.?)).ptr)); - try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.kernel32_lib_dir.?)).ptr)); - try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.lib_dir.?)).ptr)); + try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", .{ctx.libc.msvc_lib_dir.?})).ptr)); + try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", .{ctx.libc.kernel32_lib_dir.?})).ptr)); + try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", .{ctx.libc.lib_dir.?})).ptr)); } if (ctx.link_in_crt) { @@ -348,17 +348,20 @@ fn constructLinkerArgsCoff(ctx: *Context) !void { const d_str = if (ctx.comp.build_mode == .Debug) "d" else ""; if (ctx.comp.is_static) { - const cmt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "libcmt{}.lib\x00", d_str); + const cmt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "libcmt{}.lib\x00", .{d_str}); try ctx.args.append(@ptrCast([*:0]const u8, cmt_lib_name.ptr)); } else { - const msvcrt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "msvcrt{}.lib\x00", d_str); + const msvcrt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "msvcrt{}.lib\x00", .{d_str}); try ctx.args.append(@ptrCast([*:0]const u8, msvcrt_lib_name.ptr)); } - const vcruntime_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "{}vcruntime{}.lib\x00", lib_str, d_str); + const vcruntime_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "{}vcruntime{}.lib\x00", .{ + lib_str, + d_str, + }); try ctx.args.append(@ptrCast([*:0]const u8, vcruntime_lib_name.ptr)); - const crt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "{}ucrt{}.lib\x00", lib_str, d_str); + const crt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "{}ucrt{}.lib\x00", .{ lib_str, d_str }); try ctx.args.append(@ptrCast([*:0]const u8, crt_lib_name.ptr)); // Visual C++ 2015 Conformance Changes @@ -508,7 +511,11 @@ fn constructLinkerArgsMachO(ctx: *Context) !void { .IPhoneOS => try ctx.args.append("-iphoneos_version_min"), .IPhoneOSSimulator => try ctx.args.append("-ios_simulator_version_min"), } - const ver_str = try std.fmt.allocPrint(&ctx.arena.allocator, "{}.{}.{}\x00", platform.major, platform.minor, platform.micro); + const ver_str = try std.fmt.allocPrint(&ctx.arena.allocator, "{}.{}.{}\x00", .{ + platform.major, + platform.minor, + platform.micro, + }); try ctx.args.append(@ptrCast([*:0]const u8, ver_str.ptr)); if (ctx.comp.kind == .Exe) { @@ -584,7 +591,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void { try ctx.args.append("-lSystem"); } else { if (mem.indexOfScalar(u8, lib.name, '/') == null) { - const arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-l{}\x00", lib.name); + const arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-l{}\x00", .{lib.name}); try ctx.args.append(@ptrCast([*:0]const u8, arg.ptr)); } else { const arg = try std.cstr.addNullByte(&ctx.arena.allocator, lib.name); diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index 01319e62ce..e5371ce25d 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -128,7 +128,7 @@ pub fn main() !void { } } - try stderr.print("unknown command: {}\n\n", args[1]); + try stderr.print("unknown command: {}\n\n", .{args[1]}); try stderr.write(usage); process.argsFree(allocator, args); process.exit(1); @@ -329,14 +329,14 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co if (cur_pkg.parent) |parent| { cur_pkg = parent; } else { - try stderr.print("encountered --pkg-end with no matching --pkg-begin\n"); + try stderr.print("encountered --pkg-end with no matching --pkg-begin\n", .{}); process.exit(1); } } } if (cur_pkg.parent != null) { - try stderr.print("unmatched --pkg-begin\n"); + try stderr.print("unmatched --pkg-begin\n", .{}); process.exit(1); } @@ -345,7 +345,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co 0 => null, 1 => flags.positionals.at(0), else => { - try stderr.print("unexpected extra parameter: {}\n", flags.positionals.at(1)); + try stderr.print("unexpected extra parameter: {}\n", .{flags.positionals.at(1)}); process.exit(1); }, }; @@ -477,13 +477,13 @@ fn processBuildEvents(comp: *Compilation, color: errmsg.Color) void { switch (build_event) { .Ok => { - stderr.print("Build {} succeeded\n", count) catch process.exit(1); + stderr.print("Build {} succeeded\n", .{count}) catch process.exit(1); }, .Error => |err| { - stderr.print("Build {} failed: {}\n", count, @errorName(err)) catch process.exit(1); + stderr.print("Build {} failed: {}\n", .{ count, @errorName(err) }) catch process.exit(1); }, .Fail => |msgs| { - stderr.print("Build {} compile errors:\n", count) catch process.exit(1); + stderr.print("Build {} compile errors:\n", .{count}) catch process.exit(1); for (msgs) |msg| { defer msg.destroy(); msg.printToFile(stderr_file, color) catch process.exit(1); @@ -544,12 +544,11 @@ const Fmt = struct { fn parseLibcPaths(allocator: *Allocator, libc: *LibCInstallation, libc_paths_file: []const u8) void { libc.parse(allocator, libc_paths_file, stderr) catch |err| { - stderr.print( - "Unable to parse libc path file '{}': {}.\n" ++ - "Try running `zig libc` to see an example for the native target.\n", + stderr.print("Unable to parse libc path file '{}': {}.\n" ++ + "Try running `zig libc` to see an example for the native target.\n", .{ libc_paths_file, @errorName(err), - ) catch {}; + }) catch {}; process.exit(1); }; } @@ -563,7 +562,7 @@ fn cmdLibC(allocator: *Allocator, args: []const []const u8) !void { return; }, else => { - try stderr.print("unexpected extra parameter: {}\n", args[1]); + try stderr.print("unexpected extra parameter: {}\n", .{args[1]}); process.exit(1); }, } @@ -572,7 +571,7 @@ fn cmdLibC(allocator: *Allocator, args: []const []const u8) !void { defer zig_compiler.deinit(); const libc = zig_compiler.getNativeLibC() catch |err| { - stderr.print("unable to find libc: {}\n", @errorName(err)) catch {}; + stderr.print("unable to find libc: {}\n", .{@errorName(err)}) catch {}; process.exit(1); }; libc.render(stdout) catch process.exit(1); @@ -614,7 +613,7 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void { defer allocator.free(source_code); const tree = std.zig.parse(allocator, source_code) catch |err| { - try stderr.print("error parsing stdin: {}\n", err); + try stderr.print("error parsing stdin: {}\n", .{err}); process.exit(1); }; defer tree.deinit(); @@ -718,7 +717,7 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro }, else => { // TODO lock stderr printing - try stderr.print("unable to open '{}': {}\n", file_path, err); + try stderr.print("unable to open '{}': {}\n", .{ file_path, err }); fmt.any_error = true; return; }, @@ -726,7 +725,7 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro defer fmt.allocator.free(source_code); const tree = std.zig.parse(fmt.allocator, source_code) catch |err| { - try stderr.print("error parsing file '{}': {}\n", file_path, err); + try stderr.print("error parsing file '{}': {}\n", .{ file_path, err }); fmt.any_error = true; return; }; @@ -747,7 +746,7 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro if (check_mode) { const anything_changed = try std.zig.render(fmt.allocator, io.null_out_stream, tree); if (anything_changed) { - try stderr.print("{}\n", file_path); + try stderr.print("{}\n", .{file_path}); fmt.any_error = true; } } else { @@ -757,7 +756,7 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro const anything_changed = try std.zig.render(fmt.allocator, baf.stream(), tree); if (anything_changed) { - try stderr.print("{}\n", file_path); + try stderr.print("{}\n", .{file_path}); try baf.finish(); } } @@ -774,7 +773,7 @@ fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void { // NOTE: Cannot use empty string, see #918. comptime const native_str = if (comptime mem.eql(u8, arch_tag, @tagName(builtin.arch))) " (native)\n" else "\n"; - try stdout.print(" {}{}", arch_tag, native_str); + try stdout.print(" {}{}", .{ arch_tag, native_str }); } } try stdout.write("\n"); @@ -787,7 +786,7 @@ fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void { // NOTE: Cannot use empty string, see #918. comptime const native_str = if (comptime mem.eql(u8, os_tag, @tagName(builtin.os))) " (native)\n" else "\n"; - try stdout.print(" {}{}", os_tag, native_str); + try stdout.print(" {}{}", .{ os_tag, native_str }); } } try stdout.write("\n"); @@ -800,13 +799,13 @@ fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void { // NOTE: Cannot use empty string, see #918. comptime const native_str = if (comptime mem.eql(u8, abi_tag, @tagName(builtin.abi))) " (native)\n" else "\n"; - try stdout.print(" {}{}", abi_tag, native_str); + try stdout.print(" {}{}", .{ abi_tag, native_str }); } } } fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void { - try stdout.print("{}\n", std.mem.toSliceConst(u8, c.ZIG_VERSION_STRING)); + try stdout.print("{}\n", .{std.mem.toSliceConst(u8, c.ZIG_VERSION_STRING)}); } const args_test_spec = [_]Flag{Flag.Bool("--help")}; @@ -865,7 +864,7 @@ fn cmdInternal(allocator: *Allocator, args: []const []const u8) !void { } } - try stderr.print("unknown sub command: {}\n\n", args[0]); + try stderr.print("unknown sub command: {}\n\n", .{args[0]}); try stderr.write(usage_internal); } @@ -878,14 +877,14 @@ fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void { \\ZIG_LLVM_CONFIG_EXE {} \\ZIG_DIA_GUIDS_LIB {} \\ - , + , .{ std.mem.toSliceConst(u8, c.ZIG_CMAKE_BINARY_DIR), std.mem.toSliceConst(u8, c.ZIG_CXX_COMPILER), std.mem.toSliceConst(u8, c.ZIG_LLD_INCLUDE_PATH), std.mem.toSliceConst(u8, c.ZIG_LLD_LIBRARIES), std.mem.toSliceConst(u8, c.ZIG_LLVM_CONFIG_EXE), std.mem.toSliceConst(u8, c.ZIG_DIA_GUIDS_LIB), - ); + }); } const CliPkg = struct { diff --git a/src-self-hosted/type.zig b/src-self-hosted/type.zig index 8b068150b6..fa8e133b69 100644 --- a/src-self-hosted/type.zig +++ b/src-self-hosted/type.zig @@ -399,7 +399,7 @@ pub const Type = struct { .Generic => |generic| { self.non_key = NonKey{ .Generic = {} }; const cc_str = ccFnTypeStr(generic.cc); - try name_stream.print("{}fn(", cc_str); + try name_stream.print("{}fn(", .{cc_str}); var param_i: usize = 0; while (param_i < generic.param_count) : (param_i += 1) { const arg = if (param_i == 0) "var" else ", var"; @@ -407,7 +407,7 @@ pub const Type = struct { } try name_stream.write(")"); if (key.alignment) |alignment| { - try name_stream.print(" align({})", alignment); + try name_stream.print(" align({})", .{alignment}); } try name_stream.write(" var"); }, @@ -416,7 +416,7 @@ pub const Type = struct { .Normal = NonKey.Normal{ .variable_list = std.ArrayList(*Scope.Var).init(comp.gpa()) }, }; const cc_str = ccFnTypeStr(normal.cc); - try name_stream.print("{}fn(", cc_str); + try name_stream.print("{}fn(", .{cc_str}); for (normal.params) |param, i| { if (i != 0) try name_stream.write(", "); if (param.is_noalias) try name_stream.write("noalias "); @@ -428,9 +428,9 @@ pub const Type = struct { } try name_stream.write(")"); if (key.alignment) |alignment| { - try name_stream.print(" align({})", alignment); + try name_stream.print(" align({})", .{alignment}); } - try name_stream.print(" {}", normal.return_type.name); + try name_stream.print(" {}", .{normal.return_type.name}); }, } @@ -584,7 +584,7 @@ pub const Type = struct { errdefer comp.gpa().destroy(self); const u_or_i = "ui"[@boolToInt(key.is_signed)]; - const name = try std.fmt.allocPrint(comp.gpa(), "{c}{}", u_or_i, key.bit_count); + const name = try std.fmt.allocPrint(comp.gpa(), "{c}{}", .{ u_or_i, key.bit_count }); errdefer comp.gpa().free(name); self.base.init(comp, .Int, name); @@ -767,23 +767,19 @@ pub const Type = struct { .Non => "", }; const name = switch (self.key.alignment) { - .Abi => try std.fmt.allocPrint( - comp.gpa(), - "{}{}{}{}", + .Abi => try std.fmt.allocPrint(comp.gpa(), "{}{}{}{}", .{ size_str, mut_str, vol_str, self.key.child_type.name, - ), - .Override => |alignment| try std.fmt.allocPrint( - comp.gpa(), - "{}align<{}> {}{}{}", + }), + .Override => |alignment| try std.fmt.allocPrint(comp.gpa(), "{}align<{}> {}{}{}", .{ size_str, alignment, mut_str, vol_str, self.key.child_type.name, - ), + }), }; errdefer comp.gpa().free(name); @@ -852,7 +848,7 @@ pub const Type = struct { }; errdefer comp.gpa().destroy(self); - const name = try std.fmt.allocPrint(comp.gpa(), "[{}]{}", key.len, key.elem_type.name); + const name = try std.fmt.allocPrint(comp.gpa(), "[{}]{}", .{ key.len, key.elem_type.name }); errdefer comp.gpa().free(name); self.base.init(comp, .Array, name); diff --git a/src-self-hosted/util.zig b/src-self-hosted/util.zig index 070ba9ba87..85e2fc0e73 100644 --- a/src-self-hosted/util.zig +++ b/src-self-hosted/util.zig @@ -175,7 +175,7 @@ pub fn llvmTargetFromTriple(triple: std.Buffer) !*llvm.Target { var result: *llvm.Target = undefined; var err_msg: [*:0]u8 = undefined; if (llvm.GetTargetFromTriple(triple.toSlice(), &result, &err_msg) != 0) { - std.debug.warn("triple: {s} error: {s}\n", triple.toSlice(), err_msg); + std.debug.warn("triple: {s} error: {s}\n", .{ triple.toSlice(), err_msg }); return error.UnsupportedTarget; } return result; @@ -206,7 +206,7 @@ pub fn getTriple(allocator: *std.mem.Allocator, self: std.Target) !std.Buffer { const env_name = if (self.isWasm()) "wasm" else @tagName(self.getAbi()); var out = &std.io.BufferOutStream.init(&result).stream; - try out.print("{}-unknown-{}-{}", @tagName(self.getArch()), @tagName(self.getOs()), env_name); + try out.print("{}-unknown-{}-{}", .{ @tagName(self.getArch()), @tagName(self.getOs()), env_name }); return result; } diff --git a/src-self-hosted/value.zig b/src-self-hosted/value.zig index accd70d9cc..03c0db0c3c 100644 --- a/src-self-hosted/value.zig +++ b/src-self-hosted/value.zig @@ -53,7 +53,7 @@ pub const Value = struct { } pub fn dump(base: *const Value) void { - std.debug.warn("{}", @tagName(base.id)); + std.debug.warn("{}", .{@tagName(base.id)}); } pub fn getLlvmConst(base: *Value, ofile: *ObjectFile) (error{OutOfMemory}!?*llvm.Value) { From 7a4f7042583e0d19e41e3add77b011416b537405 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 8 Dec 2019 23:26:19 -0500 Subject: [PATCH 3/7] windows-specific fixes --- lib/std/debug.zig | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/std/debug.zig b/lib/std/debug.zig index d93138fd4e..04a83c39f3 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -2469,10 +2469,10 @@ extern fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *con stdcallcc fn handleSegfaultWindows(info: *windows.EXCEPTION_POINTERS) c_long { const exception_address = @ptrToInt(info.ExceptionRecord.ExceptionAddress); switch (info.ExceptionRecord.ExceptionCode) { - windows.EXCEPTION_DATATYPE_MISALIGNMENT => panicExtra(null, exception_address, "Unaligned Memory Access"), - windows.EXCEPTION_ACCESS_VIOLATION => panicExtra(null, exception_address, "Segmentation fault at address 0x{x}", info.ExceptionRecord.ExceptionInformation[1]), - windows.EXCEPTION_ILLEGAL_INSTRUCTION => panicExtra(null, exception_address, "Illegal Instruction"), - windows.EXCEPTION_STACK_OVERFLOW => panicExtra(null, exception_address, "Stack Overflow"), + windows.EXCEPTION_DATATYPE_MISALIGNMENT => panicExtra(null, exception_address, "Unaligned Memory Access", .{}), + windows.EXCEPTION_ACCESS_VIOLATION => panicExtra(null, exception_address, "Segmentation fault at address 0x{x}", .{info.ExceptionRecord.ExceptionInformation[1]}), + windows.EXCEPTION_ILLEGAL_INSTRUCTION => panicExtra(null, exception_address, "Illegal Instruction", .{}), + windows.EXCEPTION_STACK_OVERFLOW => panicExtra(null, exception_address, "Stack Overflow", .{}), else => return windows.EXCEPTION_CONTINUE_SEARCH, } } From 5f9467d78f678932ec14946fc83ba50ad7fc2454 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 8 Dec 2019 23:39:30 -0500 Subject: [PATCH 4/7] update formatted printing when linking libc --- lib/std/net.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/std/net.zig b/lib/std/net.zig index 4484821f99..a3f9c1c6d1 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -437,7 +437,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !* const name_c = try std.cstr.addNullByte(allocator, name); defer allocator.free(name_c); - const port_c = try std.fmt.allocPrint(allocator, "{}\x00", port); + const port_c = try std.fmt.allocPrint(allocator, "{}\x00", .{port}); defer allocator.free(port_c); const hints = os.addrinfo{ From 03396b3caac1ab76dae5f672800aafb176d46cad Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 8 Dec 2019 23:46:50 -0500 Subject: [PATCH 5/7] update docs to new fmt API --- doc/langref.html.in | 152 ++++++++++++++++++++----------------- lib/std/os/windows.zig | 2 +- src-self-hosted/stage1.zig | 2 +- 3 files changed, 84 insertions(+), 72 deletions(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index 64c039d533..48ec5e39fe 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -205,7 +205,7 @@ const std = @import("std"); pub fn main() !void { const stdout = &std.io.getStdOut().outStream().stream; - try stdout.print("Hello, {}!\n", "world"); + try stdout.print("Hello, {}!\n", .{"world"}); } {#code_end#}

@@ -217,7 +217,7 @@ pub fn main() !void { const warn = @import("std").debug.warn; pub fn main() void { - warn("Hello, world!\n"); + warn("Hello, world!\n", .{}); } {#code_end#}

@@ -289,41 +289,50 @@ const assert = std.debug.assert; pub fn main() void { // integers const one_plus_one: i32 = 1 + 1; - warn("1 + 1 = {}\n", one_plus_one); + warn("1 + 1 = {}\n", .{one_plus_one}); // floats const seven_div_three: f32 = 7.0 / 3.0; - warn("7.0 / 3.0 = {}\n", seven_div_three); + warn("7.0 / 3.0 = {}\n", .{seven_div_three}); // boolean - warn("{}\n{}\n{}\n", + warn("{}\n{}\n{}\n", .{ true and false, true or false, - !true); + !true, + }); // optional var optional_value: ?[]const u8 = null; assert(optional_value == null); - warn("\noptional 1\ntype: {}\nvalue: {}\n", - @typeName(@typeOf(optional_value)), optional_value); + warn("\noptional 1\ntype: {}\nvalue: {}\n", .{ + @typeName(@typeOf(optional_value)), + optional_value, + }); optional_value = "hi"; assert(optional_value != null); - warn("\noptional 2\ntype: {}\nvalue: {}\n", - @typeName(@typeOf(optional_value)), optional_value); + warn("\noptional 2\ntype: {}\nvalue: {}\n", .{ + @typeName(@typeOf(optional_value)), + optional_value, + }); // error union var number_or_error: anyerror!i32 = error.ArgNotFound; - warn("\nerror union 1\ntype: {}\nvalue: {}\n", - @typeName(@typeOf(number_or_error)), number_or_error); + warn("\nerror union 1\ntype: {}\nvalue: {}\n", .{ + @typeName(@typeOf(number_or_error)), + number_or_error, + }); number_or_error = 1234; - warn("\nerror union 2\ntype: {}\nvalue: {}\n", - @typeName(@typeOf(number_or_error)), number_or_error); + warn("\nerror union 2\ntype: {}\nvalue: {}\n", .{ + @typeName(@typeOf(number_or_error)), + number_or_error, + }); } {#code_end#} {#header_open|Primitive Types#} @@ -954,8 +963,8 @@ extern fn foo_optimized(x: f64) f64; pub fn main() void { const x = 0.001; - warn("optimized = {}\n", foo_optimized(x)); - warn("strict = {}\n", foo_strict(x)); + warn("optimized = {}\n", .{foo_optimized(x)}); + warn("strict = {}\n", .{foo_strict(x)}); } {#code_end#} {#see_also|@setFloatMode|Division by Zero#} @@ -2182,7 +2191,7 @@ test "using slices for strings" { // You can use slice syntax on an array to convert an array into a slice. const all_together_slice = all_together[0..]; // String concatenation example. - const hello_world = try fmt.bufPrint(all_together_slice, "{} {}", hello, world); + const hello_world = try fmt.bufPrint(all_together_slice, "{} {}", .{hello, world}); // Generally, you can use UTF-8 and not worry about whether something is a // string. If you don't need to deal with individual characters, no need @@ -2623,9 +2632,9 @@ const std = @import("std"); pub fn main() void { const Foo = struct {}; - std.debug.warn("variable: {}\n", @typeName(Foo)); - std.debug.warn("anonymous: {}\n", @typeName(struct {})); - std.debug.warn("function: {}\n", @typeName(List(i32))); + std.debug.warn("variable: {}\n", .{@typeName(Foo)}); + std.debug.warn("anonymous: {}\n", .{@typeName(struct {})}); + std.debug.warn("function: {}\n", .{@typeName(List(i32))}); } fn List(comptime T: type) type { @@ -3806,18 +3815,18 @@ test "defer basics" { // If multiple defer statements are specified, they will be executed in // the reverse order they were run. fn deferUnwindExample() void { - warn("\n"); + warn("\n", .{}); defer { - warn("1 "); + warn("1 ", .{}); } defer { - warn("2 "); + warn("2 ", .{}); } if (false) { // defers are not run if they are never executed. defer { - warn("3 "); + warn("3 ", .{}); } } } @@ -3832,15 +3841,15 @@ test "defer unwinding" { // This is especially useful in allowing a function to clean up properly // on error, and replaces goto error handling tactics as seen in c. fn deferErrorExample(is_error: bool) !void { - warn("\nstart of function\n"); + warn("\nstart of function\n", .{}); // This will always be executed on exit defer { - warn("end of function\n"); + warn("end of function\n", .{}); } errdefer { - warn("encountered an error!\n"); + warn("encountered an error!\n", .{}); } if (is_error) { @@ -5843,7 +5852,7 @@ const a_number: i32 = 1234; const a_string = "foobar"; pub fn main() void { - warn("here is a string: '{}' here is a number: {}\n", a_string, a_number); + warn("here is a string: '{}' here is a number: {}\n", .{a_string, a_number}); } {#code_end#} @@ -5960,8 +5969,11 @@ const a_number: i32 = 1234; const a_string = "foobar"; test "printf too many arguments" { - warn("here is a string: '{}' here is a number: {}\n", - a_string, a_number, a_number); + warn("here is a string: '{}' here is a number: {}\n", .{ + a_string, + a_number, + a_number, + }); } {#code_end#}

@@ -5979,7 +5991,7 @@ const a_string = "foobar"; const fmt = "here is a string: '{}' here is a number: {}\n"; pub fn main() void { - warn(fmt, a_string, a_number); + warn(fmt, .{a_string, a_number}); } {#code_end#}

@@ -6417,7 +6429,7 @@ pub fn main() void { fn amainWrap() void { amain() catch |e| { - std.debug.warn("{}\n", e); + std.debug.warn("{}\n", .{e}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -6447,8 +6459,8 @@ fn amain() !void { const download_text = try await download_frame; defer allocator.free(download_text); - std.debug.warn("download_text: {}\n", download_text); - std.debug.warn("file_text: {}\n", file_text); + std.debug.warn("download_text: {}\n", .{download_text}); + std.debug.warn("file_text: {}\n", .{file_text}); } var global_download_frame: anyframe = undefined; @@ -6458,7 +6470,7 @@ fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 { suspend { global_download_frame = @frame(); } - std.debug.warn("fetchUrl returning\n"); + std.debug.warn("fetchUrl returning\n", .{}); return result; } @@ -6469,7 +6481,7 @@ fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 { suspend { global_file_frame = @frame(); } - std.debug.warn("readFile returning\n"); + std.debug.warn("readFile returning\n", .{}); return result; } {#code_end#} @@ -6487,7 +6499,7 @@ pub fn main() void { fn amainWrap() void { amain() catch |e| { - std.debug.warn("{}\n", e); + std.debug.warn("{}\n", .{e}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -6517,21 +6529,21 @@ fn amain() !void { const download_text = try await download_frame; defer allocator.free(download_text); - std.debug.warn("download_text: {}\n", download_text); - std.debug.warn("file_text: {}\n", file_text); + std.debug.warn("download_text: {}\n", .{download_text}); + std.debug.warn("file_text: {}\n", .{file_text}); } fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 { const result = try std.mem.dupe(allocator, u8, "this is the downloaded url contents"); errdefer allocator.free(result); - std.debug.warn("fetchUrl returning\n"); + std.debug.warn("fetchUrl returning\n", .{}); return result; } fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 { const result = try std.mem.dupe(allocator, u8, "this is the file contents"); errdefer allocator.free(result); - std.debug.warn("readFile returning\n"); + std.debug.warn("readFile returning\n", .{}); return result; } {#code_end#} @@ -7103,7 +7115,7 @@ const num1 = blk: { test "main" { @compileLog("comptime in main"); - warn("Runtime in main, num1 = {}.\n", num1); + warn("Runtime in main, num1 = {}.\n", .{num1}); } {#code_end#}

@@ -7124,7 +7136,7 @@ const num1 = blk: { }; test "main" { - warn("Runtime in main, num1 = {}.\n", num1); + warn("Runtime in main, num1 = {}.\n", .{num1}); } {#code_end#} {#header_close#} @@ -8706,7 +8718,7 @@ const std = @import("std"); pub fn main() void { var value: i32 = -1; var unsigned = @intCast(u32, value); - std.debug.warn("value: {}\n", unsigned); + std.debug.warn("value: {}\n", .{unsigned}); } {#code_end#}

@@ -8728,7 +8740,7 @@ const std = @import("std"); pub fn main() void { var spartan_count: u16 = 300; const byte = @intCast(u8, spartan_count); - std.debug.warn("value: {}\n", byte); + std.debug.warn("value: {}\n", .{byte}); } {#code_end#}

@@ -8762,7 +8774,7 @@ const std = @import("std"); pub fn main() void { var byte: u8 = 255; byte += 1; - std.debug.warn("value: {}\n", byte); + std.debug.warn("value: {}\n", .{byte}); } {#code_end#} {#header_close#} @@ -8785,11 +8797,11 @@ pub fn main() !void { var byte: u8 = 255; byte = if (math.add(u8, byte, 1)) |result| result else |err| { - warn("unable to add one: {}\n", @errorName(err)); + warn("unable to add one: {}\n", .{@errorName(err)}); return err; }; - warn("result: {}\n", byte); + warn("result: {}\n", .{byte}); } {#code_end#} {#header_close#} @@ -8814,9 +8826,9 @@ pub fn main() void { var result: u8 = undefined; if (@addWithOverflow(u8, byte, 10, &result)) { - warn("overflowed result: {}\n", result); + warn("overflowed result: {}\n", .{result}); } else { - warn("result: {}\n", result); + warn("result: {}\n", .{result}); } } {#code_end#} @@ -8861,7 +8873,7 @@ const std = @import("std"); pub fn main() void { var x: u8 = 0b01010101; var y = @shlExact(x, 2); - std.debug.warn("value: {}\n", y); + std.debug.warn("value: {}\n", .{y}); } {#code_end#} {#header_close#} @@ -8879,7 +8891,7 @@ const std = @import("std"); pub fn main() void { var x: u8 = 0b10101010; var y = @shrExact(x, 2); - std.debug.warn("value: {}\n", y); + std.debug.warn("value: {}\n", .{y}); } {#code_end#} {#header_close#} @@ -8900,7 +8912,7 @@ pub fn main() void { var a: u32 = 1; var b: u32 = 0; var c = a / b; - std.debug.warn("value: {}\n", c); + std.debug.warn("value: {}\n", .{c}); } {#code_end#} {#header_close#} @@ -8921,7 +8933,7 @@ pub fn main() void { var a: u32 = 10; var b: u32 = 0; var c = a % b; - std.debug.warn("value: {}\n", c); + std.debug.warn("value: {}\n", .{c}); } {#code_end#} {#header_close#} @@ -8942,7 +8954,7 @@ pub fn main() void { var a: u32 = 10; var b: u32 = 3; var c = @divExact(a, b); - std.debug.warn("value: {}\n", c); + std.debug.warn("value: {}\n", .{c}); } {#code_end#} {#header_close#} @@ -8961,7 +8973,7 @@ const std = @import("std"); pub fn main() void { var bytes = [5]u8{ 1, 2, 3, 4, 5 }; var slice = @bytesToSlice(u32, bytes[0..]); - std.debug.warn("value: {}\n", slice[0]); + std.debug.warn("value: {}\n", .{slice[0]}); } {#code_end#} {#header_close#} @@ -8980,7 +8992,7 @@ const std = @import("std"); pub fn main() void { var optional_number: ?i32 = null; var number = optional_number.?; - std.debug.warn("value: {}\n", number); + std.debug.warn("value: {}\n", .{number}); } {#code_end#}

One way to avoid this crash is to test for null instead of assuming non-null, with @@ -8991,9 +9003,9 @@ pub fn main() void { const optional_number: ?i32 = null; if (optional_number) |number| { - warn("got number: {}\n", number); + warn("got number: {}\n", .{number}); } else { - warn("it's null\n"); + warn("it's null\n", .{}); } } {#code_end#} @@ -9016,7 +9028,7 @@ const std = @import("std"); pub fn main() void { const number = getNumberOrFail() catch unreachable; - std.debug.warn("value: {}\n", number); + std.debug.warn("value: {}\n", .{number}); } fn getNumberOrFail() !i32 { @@ -9032,9 +9044,9 @@ pub fn main() void { const result = getNumberOrFail(); if (result) |number| { - warn("got number: {}\n", number); + warn("got number: {}\n", .{number}); } else |err| { - warn("got error: {}\n", @errorName(err)); + warn("got error: {}\n", .{@errorName(err)}); } } @@ -9061,7 +9073,7 @@ pub fn main() void { var err = error.AnError; var number = @errorToInt(err) + 500; var invalid_err = @intToError(number); - std.debug.warn("value: {}\n", number); + std.debug.warn("value: {}\n", .{number}); } {#code_end#} {#header_close#} @@ -9091,7 +9103,7 @@ const Foo = enum { pub fn main() void { var a: u2 = 3; var b = @intToEnum(Foo, a); - std.debug.warn("value: {}\n", @tagName(b)); + std.debug.warn("value: {}\n", .{@tagName(b)}); } {#code_end#} {#header_close#} @@ -9128,7 +9140,7 @@ pub fn main() void { } fn foo(set1: Set1) void { const x = @errSetCast(Set2, set1); - std.debug.warn("value: {}\n", x); + std.debug.warn("value: {}\n", .{x}); } {#code_end#} {#header_close#} @@ -9184,7 +9196,7 @@ pub fn main() void { fn bar(f: *Foo) void { f.float = 12.34; - std.debug.warn("value: {}\n", f.float); + std.debug.warn("value: {}\n", .{f.float}); } {#code_end#}

@@ -9208,7 +9220,7 @@ pub fn main() void { fn bar(f: *Foo) void { f.* = Foo{ .float = 12.34 }; - std.debug.warn("value: {}\n", f.float); + std.debug.warn("value: {}\n", .{f.float}); } {#code_end#}

@@ -9227,7 +9239,7 @@ pub fn main() void { var f = Foo{ .int = 42 }; f = Foo{ .float = undefined }; bar(&f); - std.debug.warn("value: {}\n", f.float); + std.debug.warn("value: {}\n", .{f.float}); } fn bar(f: *Foo) void { @@ -9348,7 +9360,7 @@ pub fn main() !void { const allocator = &arena.allocator; const ptr = try allocator.create(i32); - std.debug.warn("ptr={*}\n", ptr); + std.debug.warn("ptr={*}\n", .{ptr}); } {#code_end#} When using this kind of allocator, there is no need to free anything manually. Everything @@ -9881,7 +9893,7 @@ pub fn main() !void { defer std.process.argsFree(std.heap.page_allocator, args); for (args) |arg, i| { - std.debug.warn("{}: {}\n", i, arg); + std.debug.warn("{}: {}\n", .{i, arg}); } } {#code_end#} diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index 81855a992a..b7b1edeb89 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -323,7 +323,7 @@ pub fn GetQueuedCompletionStatus( ERROR.HANDLE_EOF => return GetQueuedCompletionStatusResult.EOF, else => |err| { if (std.debug.runtime_safety) { - std.debug.panic("unexpected error: {}\n", err); + std.debug.panic("unexpected error: {}\n", .{err}); } }, } diff --git a/src-self-hosted/stage1.zig b/src-self-hosted/stage1.zig index 3b6d137df5..909572bee0 100644 --- a/src-self-hosted/stage1.zig +++ b/src-self-hosted/stage1.zig @@ -149,7 +149,7 @@ export fn stage2_fmt(argc: c_int, argv: [*]const [*:0]const u8) c_int { fmtMain(argc, argv) catch unreachable; } else { fmtMain(argc, argv) catch |e| { - std.debug.warn("{}\n", @errorName(e)); + std.debug.warn("{}\n", .{@errorName(e)}); return -1; }; } From d571fad20eac23cadf6116742ad4abab5ed281e5 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 9 Dec 2019 00:03:08 -0500 Subject: [PATCH 6/7] update tests to new format API --- .../special/compiler_rt/truncXfYf2_test.zig | 2 +- test/compare_output.zig | 66 +++++++++---------- test/standalone/guess_number/main.zig | 14 ++-- 3 files changed, 41 insertions(+), 41 deletions(-) diff --git a/lib/std/special/compiler_rt/truncXfYf2_test.zig b/lib/std/special/compiler_rt/truncXfYf2_test.zig index d1dd837ddc..baec2a4450 100644 --- a/lib/std/special/compiler_rt/truncXfYf2_test.zig +++ b/lib/std/special/compiler_rt/truncXfYf2_test.zig @@ -217,7 +217,7 @@ fn test__truncdfsf2(a: f64, expected: u32) void { } } - @import("std").debug.warn("got 0x{x} wanted 0x{x}\n", rep, expected); + @import("std").debug.warn("got 0x{x} wanted 0x{x}\n", .{ rep, expected }); @panic("__trunctfsf2 test failure"); } diff --git a/test/compare_output.zig b/test/compare_output.zig index 35687b6a6c..80bac9b1f7 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -20,7 +20,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\pub fn main() void { \\ privateFunction(); \\ const stdout = &getStdOut().outStream().stream; - \\ stdout.print("OK 2\n") catch unreachable; + \\ stdout.print("OK 2\n", .{}) catch unreachable; \\} \\ \\fn privateFunction() void { @@ -35,7 +35,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\// but it's private so it should be OK \\fn privateFunction() void { \\ const stdout = &getStdOut().outStream().stream; - \\ stdout.print("OK 1\n") catch unreachable; + \\ stdout.print("OK 1\n", .{}) catch unreachable; \\} \\ \\pub fn printText() void { @@ -61,7 +61,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\usingnamespace @import("std").io; \\pub fn foo_function() void { \\ const stdout = &getStdOut().outStream().stream; - \\ stdout.print("OK\n") catch unreachable; + \\ stdout.print("OK\n", .{}) catch unreachable; \\} ); @@ -72,7 +72,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\pub fn bar_function() void { \\ if (foo_function()) { \\ const stdout = &getStdOut().outStream().stream; - \\ stdout.print("OK\n") catch unreachable; + \\ stdout.print("OK\n", .{}) catch unreachable; \\ } \\} ); @@ -104,7 +104,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ \\pub fn ok() void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print(b_text) catch unreachable; + \\ stdout.print(b_text, .{}) catch unreachable; \\} ); @@ -122,7 +122,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ \\pub fn main() void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print("Hello, world!\n{d:4} {x:3} {c}\n", @as(u32, 12), @as(u16, 0x12), @as(u8, 'a')) catch unreachable; + \\ stdout.print("Hello, world!\n{d:4} {x:3} {c}\n", .{@as(u32, 12), @as(u16, 0x12), @as(u8, 'a')}) catch unreachable; \\} , "Hello, world!\n 12 12 a\n"); @@ -265,7 +265,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\} \\fn print_ok(val: @typeOf(x)) @typeOf(foo) { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print("OK\n") catch unreachable; + \\ stdout.print("OK\n", .{}) catch unreachable; \\ return 0; \\} \\const foo : i32 = 0; @@ -348,12 +348,12 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ const foo = Foo {.field1 = bar,}; \\ const stdout = &io.getStdOut().outStream().stream; \\ if (!foo.method()) { - \\ stdout.print("BAD\n") catch unreachable; + \\ stdout.print("BAD\n", .{}) catch unreachable; \\ } \\ if (!bar.method()) { - \\ stdout.print("BAD\n") catch unreachable; + \\ stdout.print("BAD\n", .{}) catch unreachable; \\ } - \\ stdout.print("OK\n") catch unreachable; + \\ stdout.print("OK\n", .{}) catch unreachable; \\} , "OK\n"); @@ -361,11 +361,11 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\const io = @import("std").io; \\pub fn main() void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print("before\n") catch unreachable; - \\ defer stdout.print("defer1\n") catch unreachable; - \\ defer stdout.print("defer2\n") catch unreachable; - \\ defer stdout.print("defer3\n") catch unreachable; - \\ stdout.print("after\n") catch unreachable; + \\ stdout.print("before\n", .{}) catch unreachable; + \\ defer stdout.print("defer1\n", .{}) catch unreachable; + \\ defer stdout.print("defer2\n", .{}) catch unreachable; + \\ defer stdout.print("defer3\n", .{}) catch unreachable; + \\ stdout.print("after\n", .{}) catch unreachable; \\} , "before\nafter\ndefer3\ndefer2\ndefer1\n"); @@ -374,13 +374,13 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\const os = @import("std").os; \\pub fn main() void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print("before\n") catch unreachable; - \\ defer stdout.print("defer1\n") catch unreachable; - \\ defer stdout.print("defer2\n") catch unreachable; + \\ stdout.print("before\n", .{}) catch unreachable; + \\ defer stdout.print("defer1\n", .{}) catch unreachable; + \\ defer stdout.print("defer2\n", .{}) catch unreachable; \\ var args_it = @import("std").process.args(); \\ if (args_it.skip() and !args_it.skip()) return; - \\ defer stdout.print("defer3\n") catch unreachable; - \\ stdout.print("after\n") catch unreachable; + \\ defer stdout.print("defer3\n", .{}) catch unreachable; + \\ stdout.print("after\n", .{}) catch unreachable; \\} , "before\ndefer2\ndefer1\n"); @@ -391,12 +391,12 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\} \\fn do_test() !void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print("before\n") catch unreachable; - \\ defer stdout.print("defer1\n") catch unreachable; - \\ errdefer stdout.print("deferErr\n") catch unreachable; + \\ stdout.print("before\n", .{}) catch unreachable; + \\ defer stdout.print("defer1\n", .{}) catch unreachable; + \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable; \\ try its_gonna_fail(); - \\ defer stdout.print("defer3\n") catch unreachable; - \\ stdout.print("after\n") catch unreachable; + \\ defer stdout.print("defer3\n", .{}) catch unreachable; + \\ stdout.print("after\n", .{}) catch unreachable; \\} \\fn its_gonna_fail() !void { \\ return error.IToldYouItWouldFail; @@ -410,12 +410,12 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\} \\fn do_test() !void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print("before\n") catch unreachable; - \\ defer stdout.print("defer1\n") catch unreachable; - \\ errdefer stdout.print("deferErr\n") catch unreachable; + \\ stdout.print("before\n", .{}) catch unreachable; + \\ defer stdout.print("defer1\n", .{}) catch unreachable; + \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable; \\ try its_gonna_pass(); - \\ defer stdout.print("defer3\n") catch unreachable; - \\ stdout.print("after\n") catch unreachable; + \\ defer stdout.print("defer3\n", .{}) catch unreachable; + \\ stdout.print("after\n", .{}) catch unreachable; \\} \\fn its_gonna_pass() anyerror!void { } , "before\nafter\ndefer3\ndefer1\n"); @@ -427,7 +427,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ \\pub fn main() void { \\ const stdout = &io.getStdOut().outStream().stream; - \\ stdout.print(foo_txt) catch unreachable; + \\ stdout.print(foo_txt, .{}) catch unreachable; \\} , "1234\nabcd\n"); @@ -452,7 +452,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ _ = args_it.skip(); \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) { \\ const arg = try arg_or_err; - \\ try stdout.print("{}: {}\n", index, arg); + \\ try stdout.print("{}: {}\n", .{index, arg}); \\ } \\} , @@ -493,7 +493,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ _ = args_it.skip(); \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) { \\ const arg = try arg_or_err; - \\ try stdout.print("{}: {}\n", index, arg); + \\ try stdout.print("{}: {}\n", .{index, arg}); \\ } \\} , diff --git a/test/standalone/guess_number/main.zig b/test/standalone/guess_number/main.zig index 588a4ddcbd..ce7d58ac17 100644 --- a/test/standalone/guess_number/main.zig +++ b/test/standalone/guess_number/main.zig @@ -6,7 +6,7 @@ const fmt = std.fmt; pub fn main() !void { const stdout = &io.getStdOut().outStream().stream; - try stdout.print("Welcome to the Guess Number Game in Zig.\n"); + try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{}); var seed_bytes: [@sizeOf(u64)]u8 = undefined; std.crypto.randomBytes(seed_bytes[0..]) catch |err| { @@ -19,27 +19,27 @@ pub fn main() !void { const answer = prng.random.range(u8, 0, 100) + 1; while (true) { - try stdout.print("\nGuess a number between 1 and 100: "); + try stdout.print("\nGuess a number between 1 and 100: ", .{}); var line_buf: [20]u8 = undefined; const line = io.readLineSlice(line_buf[0..]) catch |err| switch (err) { error.OutOfMemory => { - try stdout.print("Input too long.\n"); + try stdout.print("Input too long.\n", .{}); continue; }, else => return err, }; const guess = fmt.parseUnsigned(u8, line, 10) catch { - try stdout.print("Invalid number.\n"); + try stdout.print("Invalid number.\n", .{}); continue; }; if (guess > answer) { - try stdout.print("Guess lower.\n"); + try stdout.print("Guess lower.\n", .{}); } else if (guess < answer) { - try stdout.print("Guess higher.\n"); + try stdout.print("Guess higher.\n", .{}); } else { - try stdout.print("You win!\n"); + try stdout.print("You win!\n", .{}); return; } } From 8b3c0bbeeef080b77d0cb7999682abc52de437e3 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 9 Dec 2019 00:18:01 -0500 Subject: [PATCH 7/7] update docgen to new format API --- doc/docgen.zig | 281 +++++++++++++++++++++++++------------------------ 1 file changed, 146 insertions(+), 135 deletions(-) diff --git a/doc/docgen.zig b/doc/docgen.zig index 430d6eb1e2..6fb9b93e1d 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -215,32 +215,33 @@ const Tokenizer = struct { } }; -fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, args: ...) anyerror { +fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, args: var) anyerror { const loc = tokenizer.getTokenLocation(token); - warn("{}:{}:{}: error: " ++ fmt ++ "\n", tokenizer.source_file_name, loc.line + 1, loc.column + 1, args); + const args_prefix = .{ tokenizer.source_file_name, loc.line + 1, loc.column + 1 }; + warn("{}:{}:{}: error: " ++ fmt ++ "\n", args_prefix ++ args); if (loc.line_start <= loc.line_end) { - warn("{}\n", tokenizer.buffer[loc.line_start..loc.line_end]); + warn("{}\n", .{tokenizer.buffer[loc.line_start..loc.line_end]}); { var i: usize = 0; while (i < loc.column) : (i += 1) { - warn(" "); + warn(" ", .{}); } } { const caret_count = token.end - token.start; var i: usize = 0; while (i < caret_count) : (i += 1) { - warn("~"); + warn("~", .{}); } } - warn("\n"); + warn("\n", .{}); } return error.ParseError; } fn assertToken(tokenizer: *Tokenizer, token: Token, id: Token.Id) !void { if (token.id != id) { - return parseError(tokenizer, token, "expected {}, found {}", @tagName(id), @tagName(token.id)); + return parseError(tokenizer, token, "expected {}, found {}", .{ @tagName(id), @tagName(token.id) }); } } @@ -339,7 +340,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { switch (token.id) { Token.Id.Eof => { if (header_stack_size != 0) { - return parseError(tokenizer, token, "unbalanced headers"); + return parseError(tokenizer, token, "unbalanced headers", .{}); } try toc.write(" \n"); break; @@ -373,10 +374,15 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { if (mem.eql(u8, param, "3col")) { columns = 3; } else { - return parseError(tokenizer, bracket_tok, "unrecognized header_open param: {}", param); + return parseError( + tokenizer, + bracket_tok, + "unrecognized header_open param: {}", + .{param}, + ); } }, - else => return parseError(tokenizer, bracket_tok, "invalid header_open token"), + else => return parseError(tokenizer, bracket_tok, "invalid header_open token", .{}), } } @@ -391,15 +397,15 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { }, }); if (try urls.put(urlized, tag_token)) |entry| { - parseError(tokenizer, tag_token, "duplicate header url: #{}", urlized) catch {}; - parseError(tokenizer, entry.value, "other tag here") catch {}; + parseError(tokenizer, tag_token, "duplicate header url: #{}", .{urlized}) catch {}; + parseError(tokenizer, entry.value, "other tag here", .{}) catch {}; return error.ParseError; } if (last_action == Action.Open) { try toc.writeByte('\n'); try toc.writeByteNTimes(' ', header_stack_size * 4); if (last_columns) |n| { - try toc.print("

    \n", n); + try toc.print("
      \n", .{n}); } else { try toc.write("
        \n"); } @@ -408,10 +414,10 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { } last_columns = columns; try toc.writeByteNTimes(' ', 4 + header_stack_size * 4); - try toc.print("
      • {}", urlized, urlized, content); + try toc.print("
      • {}", .{ urlized, urlized, content }); } else if (mem.eql(u8, tag_name, "header_close")) { if (header_stack_size == 0) { - return parseError(tokenizer, tag_token, "unbalanced close header"); + return parseError(tokenizer, tag_token, "unbalanced close header", .{}); } header_stack_size -= 1; _ = try eatToken(tokenizer, Token.Id.BracketClose); @@ -442,7 +448,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { try nodes.append(Node{ .SeeAlso = list.toOwnedSlice() }); break; }, - else => return parseError(tokenizer, see_also_tok, "invalid see_also token"), + else => return parseError(tokenizer, see_also_tok, "invalid see_also token", .{}), } } } else if (mem.eql(u8, tag_name, "link")) { @@ -459,7 +465,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { _ = try eatToken(tokenizer, Token.Id.BracketClose); break :blk tokenizer.buffer[explicit_text.start..explicit_text.end]; }, - else => return parseError(tokenizer, tok, "invalid link token"), + else => return parseError(tokenizer, tok, "invalid link token", .{}), } }; @@ -482,7 +488,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { _ = try eatToken(tokenizer, Token.Id.BracketClose); }, Token.Id.BracketClose => {}, - else => return parseError(tokenizer, token, "invalid token"), + else => return parseError(tokenizer, token, "invalid token", .{}), } const code_kind_str = tokenizer.buffer[code_kind_tok.start..code_kind_tok.end]; var code_kind_id: Code.Id = undefined; @@ -512,7 +518,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { code_kind_id = Code.Id{ .Obj = null }; is_inline = true; } else { - return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {}", code_kind_str); + return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {}", .{code_kind_str}); } var mode = builtin.Mode.Debug; @@ -550,7 +556,12 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { _ = try eatToken(tokenizer, Token.Id.BracketClose); break content_tok; } else { - return parseError(tokenizer, end_code_tag, "invalid token inside code_begin: {}", end_tag_name); + return parseError( + tokenizer, + end_code_tag, + "invalid token inside code_begin: {}", + .{end_tag_name}, + ); } _ = try eatToken(tokenizer, Token.Id.BracketClose); } else @@ -575,15 +586,20 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { const end_syntax_tag = try eatToken(tokenizer, Token.Id.TagContent); const end_tag_name = tokenizer.buffer[end_syntax_tag.start..end_syntax_tag.end]; if (!mem.eql(u8, end_tag_name, "endsyntax")) { - return parseError(tokenizer, end_syntax_tag, "invalid token inside syntax: {}", end_tag_name); + return parseError( + tokenizer, + end_syntax_tag, + "invalid token inside syntax: {}", + .{end_tag_name}, + ); } _ = try eatToken(tokenizer, Token.Id.BracketClose); try nodes.append(Node{ .Syntax = content_tok }); } else { - return parseError(tokenizer, tag_token, "unrecognized tag name: {}", tag_name); + return parseError(tokenizer, tag_token, "unrecognized tag name: {}", .{tag_name}); } }, - else => return parseError(tokenizer, token, "invalid token"), + else => return parseError(tokenizer, token, "invalid token", .{}), } } @@ -729,7 +745,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 { try out.write(""); } if (first_number != 0 or second_number != 0) { - try out.print("", first_number, second_number); + try out.print("", .{ first_number, second_number }); open_span_count += 1; } }, @@ -960,6 +976,7 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok docgen_tokenizer, source_token, "syntax error", + .{}, ), } index = token.end; @@ -987,9 +1004,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, Node.Link => |info| { if (!toc.urls.contains(info.url)) { - return parseError(tokenizer, info.token, "url not found: {}", info.url); + return parseError(tokenizer, info.token, "url not found: {}", .{info.url}); } - try out.print("{}", info.url, info.name); + try out.print("{}", .{ info.url, info.name }); }, Node.Nav => { try out.write(toc.toc); @@ -1002,12 +1019,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var Node.HeaderOpen => |info| { try out.print( "{} ยง\n", - info.n, - info.url, - info.url, - info.name, - info.url, - info.n, + .{ info.n, info.url, info.url, info.name, info.url, info.n }, ); }, Node.SeeAlso => |items| { @@ -1015,9 +1027,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var for (items) |item| { const url = try urlize(allocator, item.name); if (!toc.urls.contains(url)) { - return parseError(tokenizer, item.token, "url not found: {}", url); + return parseError(tokenizer, item.token, "url not found: {}", .{url}); } - try out.print("
      • {}
      • \n", url, item.name); + try out.print("
      • {}
      • \n", .{ url, item.name }); } try out.write("
      \n"); }, @@ -1026,17 +1038,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, Node.Code => |code| { code_progress_index += 1; - warn("docgen example code {}/{}...", code_progress_index, tokenizer.code_node_count); + warn("docgen example code {}/{}...", .{ code_progress_index, tokenizer.code_node_count }); const raw_source = tokenizer.buffer[code.source_token.start..code.source_token.end]; const trimmed_raw_source = mem.trim(u8, raw_source, " \n"); if (!code.is_inline) { - try out.print("

      {}.zig

      ", code.name); + try out.print("

      {}.zig

      ", .{code.name}); } try out.write("
      ");
                       try tokenizeAndPrint(tokenizer, out, code.source_token);
                       try out.write("
      "); - const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", code.name); + const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", .{code.name}); const tmp_source_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_ext }, @@ -1045,7 +1057,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var switch (code.id) { Code.Id.Exe => |expected_outcome| code_block: { - const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{}{}", code.name, exe_ext); + const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, exe_ext }); var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); try build_args.appendSlice(&[_][]const u8{ @@ -1059,40 +1071,40 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var "--cache", "on", }); - try out.print("
      $ zig build-exe {}.zig", code.name);
      +                        try out.print("
      $ zig build-exe {}.zig", .{code.name});
                               switch (code.mode) {
                                   builtin.Mode.Debug => {},
                                   builtin.Mode.ReleaseSafe => {
                                       try build_args.append("--release-safe");
      -                                try out.print(" --release-safe");
      +                                try out.print(" --release-safe", .{});
                                   },
                                   builtin.Mode.ReleaseFast => {
                                       try build_args.append("--release-fast");
      -                                try out.print(" --release-fast");
      +                                try out.print(" --release-fast", .{});
                                   },
                                   builtin.Mode.ReleaseSmall => {
                                       try build_args.append("--release-small");
      -                                try out.print(" --release-small");
      +                                try out.print(" --release-small", .{});
                                   },
                               }
                               for (code.link_objects) |link_object| {
      -                            const name_with_ext = try std.fmt.allocPrint(allocator, "{}{}", link_object, obj_ext);
      +                            const name_with_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ link_object, obj_ext });
                                   const full_path_object = try fs.path.join(
                                       allocator,
                                       &[_][]const u8{ tmp_dir_name, name_with_ext },
                                   );
                                   try build_args.append("--object");
                                   try build_args.append(full_path_object);
      -                            try out.print(" --object {}", name_with_ext);
      +                            try out.print(" --object {}", .{name_with_ext});
                               }
                               if (code.link_libc) {
                                   try build_args.append("-lc");
      -                            try out.print(" -lc");
      +                            try out.print(" -lc", .{});
                               }
                               if (code.target_str) |triple| {
                                   try build_args.appendSlice(&[_][]const u8{ "-target", triple });
                                   if (!code.is_inline) {
      -                                try out.print(" -target {}", triple);
      +                                try out.print(" -target {}", .{triple});
                                   }
                               }
                               if (expected_outcome == .BuildFail) {
      @@ -1106,29 +1118,29 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
                                   switch (result.term) {
                                       .Exited => |exit_code| {
                                           if (exit_code == 0) {
      -                                        warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
      +                                        warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
                                               for (build_args.toSliceConst()) |arg|
      -                                            warn("{} ", arg)
      +                                            warn("{} ", .{arg})
                                               else
      -                                            warn("\n");
      -                                        return parseError(tokenizer, code.source_token, "example incorrectly compiled");
      +                                            warn("\n", .{});
      +                                        return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{});
                                           }
                                       },
                                       else => {
      -                                    warn("{}\nThe following command crashed:\n", result.stderr);
      +                                    warn("{}\nThe following command crashed:\n", .{result.stderr});
                                           for (build_args.toSliceConst()) |arg|
      -                                        warn("{} ", arg)
      +                                        warn("{} ", .{arg})
                                           else
      -                                        warn("\n");
      -                                    return parseError(tokenizer, code.source_token, "example compile crashed");
      +                                        warn("\n", .{});
      +                                    return parseError(tokenizer, code.source_token, "example compile crashed", .{});
                                       },
                                   }
                                   const escaped_stderr = try escapeHtml(allocator, result.stderr);
                                   const colored_stderr = try termColor(allocator, escaped_stderr);
      -                            try out.print("\n{}
      \n", colored_stderr); + try out.print("\n{}
      \n", .{colored_stderr}); break :code_block; } - const exec_result = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile"); + const exec_result = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{}); if (code.target_str) |triple| { if (mem.startsWith(u8, triple, "wasm32") or @@ -1137,7 +1149,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var (builtin.os != .linux or builtin.arch != .x86_64)) { // skip execution - try out.print("\n"); + try out.print("\n", .{}); break :code_block; } } @@ -1152,12 +1164,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { - warn("{}\nThe following command incorrectly succeeded:\n", result.stderr); + warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); for (run_args) |arg| - warn("{} ", arg) + warn("{} ", .{arg}) else - warn("\n"); - return parseError(tokenizer, code.source_token, "example incorrectly compiled"); + warn("\n", .{}); + return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{}); } }, .Signal => exited_with_signal = true, @@ -1165,7 +1177,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var } break :blk result; } else blk: { - break :blk exec(allocator, &env_map, run_args) catch return parseError(tokenizer, code.source_token, "example crashed"); + break :blk exec(allocator, &env_map, run_args) catch return parseError(tokenizer, code.source_token, "example crashed", .{}); }; const escaped_stderr = try escapeHtml(allocator, result.stderr); @@ -1174,11 +1186,11 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var const colored_stderr = try termColor(allocator, escaped_stderr); const colored_stdout = try termColor(allocator, escaped_stdout); - try out.print("\n$ ./{}\n{}{}", code.name, colored_stdout, colored_stderr); + try out.print("\n$ ./{}\n{}{}", .{ code.name, colored_stdout, colored_stderr }); if (exited_with_signal) { - try out.print("(process terminated by signal)"); + try out.print("(process terminated by signal)", .{}); } - try out.print("\n"); + try out.print("\n", .{}); }, Code.Id.Test => { var test_args = std.ArrayList([]const u8).init(allocator); @@ -1191,34 +1203,34 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var "--cache", "on", }); - try out.print("
      $ zig test {}.zig", code.name);
      +                        try out.print("
      $ zig test {}.zig", .{code.name});
                               switch (code.mode) {
                                   builtin.Mode.Debug => {},
                                   builtin.Mode.ReleaseSafe => {
                                       try test_args.append("--release-safe");
      -                                try out.print(" --release-safe");
      +                                try out.print(" --release-safe", .{});
                                   },
                                   builtin.Mode.ReleaseFast => {
                                       try test_args.append("--release-fast");
      -                                try out.print(" --release-fast");
      +                                try out.print(" --release-fast", .{});
                                   },
                                   builtin.Mode.ReleaseSmall => {
                                       try test_args.append("--release-small");
      -                                try out.print(" --release-small");
      +                                try out.print(" --release-small", .{});
                                   },
                               }
                               if (code.link_libc) {
                                   try test_args.append("-lc");
      -                            try out.print(" -lc");
      +                            try out.print(" -lc", .{});
                               }
                               if (code.target_str) |triple| {
                                   try test_args.appendSlice(&[_][]const u8{ "-target", triple });
      -                            try out.print(" -target {}", triple);
      +                            try out.print(" -target {}", .{triple});
                               }
      -                        const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed");
      +                        const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed", .{});
                               const escaped_stderr = try escapeHtml(allocator, result.stderr);
                               const escaped_stdout = try escapeHtml(allocator, result.stdout);
      -                        try out.print("\n{}{}
      \n", escaped_stderr, escaped_stdout); + try out.print("\n{}{}
      \n", .{ escaped_stderr, escaped_stdout }); }, Code.Id.TestError => |error_match| { var test_args = std.ArrayList([]const u8).init(allocator); @@ -1233,50 +1245,50 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var "--output-dir", tmp_dir_name, }); - try out.print("
      $ zig test {}.zig", code.name);
      +                        try out.print("
      $ zig test {}.zig", .{code.name});
                               switch (code.mode) {
                                   builtin.Mode.Debug => {},
                                   builtin.Mode.ReleaseSafe => {
                                       try test_args.append("--release-safe");
      -                                try out.print(" --release-safe");
      +                                try out.print(" --release-safe", .{});
                                   },
                                   builtin.Mode.ReleaseFast => {
                                       try test_args.append("--release-fast");
      -                                try out.print(" --release-fast");
      +                                try out.print(" --release-fast", .{});
                                   },
                                   builtin.Mode.ReleaseSmall => {
                                       try test_args.append("--release-small");
      -                                try out.print(" --release-small");
      +                                try out.print(" --release-small", .{});
                                   },
                               }
                               const result = try ChildProcess.exec(allocator, test_args.toSliceConst(), null, &env_map, max_doc_file_size);
                               switch (result.term) {
                                   .Exited => |exit_code| {
                                       if (exit_code == 0) {
      -                                    warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
      +                                    warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
                                           for (test_args.toSliceConst()) |arg|
      -                                        warn("{} ", arg)
      +                                        warn("{} ", .{arg})
                                           else
      -                                        warn("\n");
      -                                    return parseError(tokenizer, code.source_token, "example incorrectly compiled");
      +                                        warn("\n", .{});
      +                                    return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{});
                                       }
                                   },
                                   else => {
      -                                warn("{}\nThe following command crashed:\n", result.stderr);
      +                                warn("{}\nThe following command crashed:\n", .{result.stderr});
                                       for (test_args.toSliceConst()) |arg|
      -                                    warn("{} ", arg)
      +                                    warn("{} ", .{arg})
                                       else
      -                                    warn("\n");
      -                                return parseError(tokenizer, code.source_token, "example compile crashed");
      +                                    warn("\n", .{});
      +                                return parseError(tokenizer, code.source_token, "example compile crashed", .{});
                                   },
                               }
                               if (mem.indexOf(u8, result.stderr, error_match) == null) {
      -                            warn("{}\nExpected to find '{}' in stderr", result.stderr, error_match);
      -                            return parseError(tokenizer, code.source_token, "example did not have expected compile error");
      +                            warn("{}\nExpected to find '{}' in stderr", .{ result.stderr, error_match });
      +                            return parseError(tokenizer, code.source_token, "example did not have expected compile error", .{});
                               }
                               const escaped_stderr = try escapeHtml(allocator, result.stderr);
                               const colored_stderr = try termColor(allocator, escaped_stderr);
      -                        try out.print("\n{}
      \n", colored_stderr); + try out.print("\n{}
      \n", .{colored_stderr}); }, Code.Id.TestSafety => |error_match| { @@ -1311,38 +1323,37 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { - warn("{}\nThe following command incorrectly succeeded:\n", result.stderr); + warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); for (test_args.toSliceConst()) |arg| - warn("{} ", arg) + warn("{} ", .{arg}) else - warn("\n"); - return parseError(tokenizer, code.source_token, "example test incorrectly succeeded"); + warn("\n", .{}); + return parseError(tokenizer, code.source_token, "example test incorrectly succeeded", .{}); } }, else => { - warn("{}\nThe following command crashed:\n", result.stderr); + warn("{}\nThe following command crashed:\n", .{result.stderr}); for (test_args.toSliceConst()) |arg| - warn("{} ", arg) + warn("{} ", .{arg}) else - warn("\n"); - return parseError(tokenizer, code.source_token, "example compile crashed"); + warn("\n", .{}); + return parseError(tokenizer, code.source_token, "example compile crashed", .{}); }, } if (mem.indexOf(u8, result.stderr, error_match) == null) { - warn("{}\nExpected to find '{}' in stderr", result.stderr, error_match); - return parseError(tokenizer, code.source_token, "example did not have expected runtime safety error message"); + warn("{}\nExpected to find '{}' in stderr", .{ result.stderr, error_match }); + return parseError(tokenizer, code.source_token, "example did not have expected runtime safety error message", .{}); } const escaped_stderr = try escapeHtml(allocator, result.stderr); const colored_stderr = try termColor(allocator, escaped_stderr); - try out.print( - "
      $ zig test {}.zig{}\n{}
      \n", + try out.print("
      $ zig test {}.zig{}\n{}
      \n", .{ code.name, mode_arg, colored_stderr, - ); + }); }, Code.Id.Obj => |maybe_error_match| { - const name_plus_obj_ext = try std.fmt.allocPrint(allocator, "{}{}", code.name, obj_ext); + const name_plus_obj_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, obj_ext }); const tmp_obj_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_obj_ext }, @@ -1350,7 +1361,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); - const name_plus_h_ext = try std.fmt.allocPrint(allocator, "{}.h", code.name); + const name_plus_h_ext = try std.fmt.allocPrint(allocator, "{}.h", .{code.name}); const output_h_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_h_ext }, @@ -1369,7 +1380,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }); if (!code.is_inline) { - try out.print("
      $ zig build-obj {}.zig", code.name);
      +                            try out.print("
      $ zig build-obj {}.zig", .{code.name});
                               }
       
                               switch (code.mode) {
      @@ -1377,26 +1388,26 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
                                   builtin.Mode.ReleaseSafe => {
                                       try build_args.append("--release-safe");
                                       if (!code.is_inline) {
      -                                    try out.print(" --release-safe");
      +                                    try out.print(" --release-safe", .{});
                                       }
                                   },
                                   builtin.Mode.ReleaseFast => {
                                       try build_args.append("--release-fast");
                                       if (!code.is_inline) {
      -                                    try out.print(" --release-fast");
      +                                    try out.print(" --release-fast", .{});
                                       }
                                   },
                                   builtin.Mode.ReleaseSmall => {
                                       try build_args.append("--release-small");
                                       if (!code.is_inline) {
      -                                    try out.print(" --release-small");
      +                                    try out.print(" --release-small", .{});
                                       }
                                   },
                               }
       
                               if (code.target_str) |triple| {
                                   try build_args.appendSlice(&[_][]const u8{ "-target", triple });
      -                            try out.print(" -target {}", triple);
      +                            try out.print(" -target {}", .{triple});
                               }
       
                               if (maybe_error_match) |error_match| {
      @@ -1404,35 +1415,35 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
                                   switch (result.term) {
                                       .Exited => |exit_code| {
                                           if (exit_code == 0) {
      -                                        warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
      +                                        warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
                                               for (build_args.toSliceConst()) |arg|
      -                                            warn("{} ", arg)
      +                                            warn("{} ", .{arg})
                                               else
      -                                            warn("\n");
      -                                        return parseError(tokenizer, code.source_token, "example build incorrectly succeeded");
      +                                            warn("\n", .{});
      +                                        return parseError(tokenizer, code.source_token, "example build incorrectly succeeded", .{});
                                           }
                                       },
                                       else => {
      -                                    warn("{}\nThe following command crashed:\n", result.stderr);
      +                                    warn("{}\nThe following command crashed:\n", .{result.stderr});
                                           for (build_args.toSliceConst()) |arg|
      -                                        warn("{} ", arg)
      +                                        warn("{} ", .{arg})
                                           else
      -                                        warn("\n");
      -                                    return parseError(tokenizer, code.source_token, "example compile crashed");
      +                                        warn("\n", .{});
      +                                    return parseError(tokenizer, code.source_token, "example compile crashed", .{});
                                       },
                                   }
                                   if (mem.indexOf(u8, result.stderr, error_match) == null) {
      -                                warn("{}\nExpected to find '{}' in stderr", result.stderr, error_match);
      -                                return parseError(tokenizer, code.source_token, "example did not have expected compile error message");
      +                                warn("{}\nExpected to find '{}' in stderr", .{ result.stderr, error_match });
      +                                return parseError(tokenizer, code.source_token, "example did not have expected compile error message", .{});
                                   }
                                   const escaped_stderr = try escapeHtml(allocator, result.stderr);
                                   const colored_stderr = try termColor(allocator, escaped_stderr);
      -                            try out.print("\n{}", colored_stderr);
      +                            try out.print("\n{}", .{colored_stderr});
                               } else {
      -                            _ = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile");
      +                            _ = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{});
                               }
                               if (!code.is_inline) {
      -                            try out.print("
      \n"); + try out.print("
      \n", .{}); } }, Code.Id.Lib => { @@ -1446,33 +1457,33 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var "--output-dir", tmp_dir_name, }); - try out.print("
      $ zig build-lib {}.zig", code.name);
      +                        try out.print("
      $ zig build-lib {}.zig", .{code.name});
                               switch (code.mode) {
                                   builtin.Mode.Debug => {},
                                   builtin.Mode.ReleaseSafe => {
                                       try test_args.append("--release-safe");
      -                                try out.print(" --release-safe");
      +                                try out.print(" --release-safe", .{});
                                   },
                                   builtin.Mode.ReleaseFast => {
                                       try test_args.append("--release-fast");
      -                                try out.print(" --release-fast");
      +                                try out.print(" --release-fast", .{});
                                   },
                                   builtin.Mode.ReleaseSmall => {
                                       try test_args.append("--release-small");
      -                                try out.print(" --release-small");
      +                                try out.print(" --release-small", .{});
                                   },
                               }
                               if (code.target_str) |triple| {
                                   try test_args.appendSlice(&[_][]const u8{ "-target", triple });
      -                            try out.print(" -target {}", triple);
      +                            try out.print(" -target {}", .{triple});
                               }
      -                        const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed");
      +                        const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed", .{});
                               const escaped_stderr = try escapeHtml(allocator, result.stderr);
                               const escaped_stdout = try escapeHtml(allocator, result.stdout);
      -                        try out.print("\n{}{}
      \n", escaped_stderr, escaped_stdout); + try out.print("\n{}{}
      \n", .{ escaped_stderr, escaped_stdout }); }, } - warn("OK\n"); + warn("OK\n", .{}); }, } } @@ -1483,20 +1494,20 @@ fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u switch (result.term) { .Exited => |exit_code| { if (exit_code != 0) { - warn("{}\nThe following command exited with code {}:\n", result.stderr, exit_code); + warn("{}\nThe following command exited with code {}:\n", .{ result.stderr, exit_code }); for (args) |arg| - warn("{} ", arg) + warn("{} ", .{arg}) else - warn("\n"); + warn("\n", .{}); return error.ChildExitError; } }, else => { - warn("{}\nThe following command crashed:\n", result.stderr); + warn("{}\nThe following command crashed:\n", .{result.stderr}); for (args) |arg| - warn("{} ", arg) + warn("{} ", .{arg}) else - warn("\n"); + warn("\n", .{}); return error.ChildCrashed; }, }