authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-05 10:43:14-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-07 22:43:53-07:00
log5378fdb153bc76990105e3640e7725e434e8cdee
tree9791e08538c10c521f5634ed79e3b369fcd004df
parent4ccc6f2b5777afd06f0fddbea4e0e0d0c92b007d

std.fmt: fully remove format string from format methods

Introduces `std.fmt.alt` which is a helper for calling alternate format methods besides one named "format".

43 files changed, 295 insertions(+), 363 deletions(-)

lib/compiler/resinator/res.zig+2-4
...@@ -164,8 +164,7 @@ pub const Language = packed struct(u16) {...@@ -164,8 +164,7 @@ pub const Language = packed struct(u16) {
164 return @bitCast(self);164 return @bitCast(self);
165 }165 }
166166
167 pub fn format(language: Language, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {167 pub fn format(language: Language, w: *std.io.Writer) std.io.Writer.Error!void {
168 comptime assert(fmt.len == 0);
169 const language_id = language.asInt();168 const language_id = language.asInt();
170 const language_name = language_name: {169 const language_name = language_name: {
171 if (std.enums.fromInt(lang.LanguageId, language_id)) |lang_enum_val| {170 if (std.enums.fromInt(lang.LanguageId, language_id)) |lang_enum_val| {
...@@ -440,8 +439,7 @@ pub const NameOrOrdinal = union(enum) {...@@ -440,8 +439,7 @@ pub const NameOrOrdinal = union(enum) {
440 }439 }
441 }440 }
442441
443 pub fn format(self: NameOrOrdinal, w: *std.io.Writer, comptime fmt: []const u8) !void {442 pub fn format(self: NameOrOrdinal, w: *std.io.Writer) !void {
444 comptime assert(fmt.len == 0);
445 switch (self) {443 switch (self) {
446 .name => |name| {444 .name => |name| {
447 try w.print("{s}", .{std.unicode.fmtUtf16Le(name)});445 try w.print("{s}", .{std.unicode.fmtUtf16Le(name)});
lib/std/Build/Cache/Directory.zig+1-2
...@@ -56,8 +56,7 @@ pub fn closeAndFree(self: *Directory, gpa: Allocator) void {...@@ -56,8 +56,7 @@ pub fn closeAndFree(self: *Directory, gpa: Allocator) void {
56 self.* = undefined;56 self.* = undefined;
57}57}
5858
59pub fn format(self: Directory, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {59pub fn format(self: Directory, writer: *std.io.Writer) std.io.Writer.Error!void {
60 comptime assert(f.len == 0);
61 if (self.path) |p| {60 if (self.path) |p| {
62 try writer.writeAll(p);61 try writer.writeAll(p);
63 try writer.writeAll(fs.path.sep_str);62 try writer.writeAll(fs.path.sep_str);
lib/std/Build/Cache/Path.zig+28-18
...@@ -147,25 +147,35 @@ pub fn toStringZ(p: Path, allocator: Allocator) Allocator.Error![:0]u8 {...@@ -147,25 +147,35 @@ pub fn toStringZ(p: Path, allocator: Allocator) Allocator.Error![:0]u8 {
147 return std.fmt.allocPrintSentinel(allocator, "{f}", .{p}, 0);147 return std.fmt.allocPrintSentinel(allocator, "{f}", .{p}, 0);
148}148}
149149
150pub fn format(self: Path, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {150pub fn fmtEscapeString(path: Path) std.fmt.Formatter(Path, formatEscapeString) {
151 if (f.len == 1) {151 return .{ .data = path };
152 // Quote-escape the string.152}
153 const zigEscape = switch (f[0]) {153
154 'q' => std.zig.stringEscape,154pub fn formatEscapeString(path: Path, writer: *std.io.Writer) std.io.Writer.Error!void {
155 '\'' => std.zig.charEscape,155 if (path.root_dir.path) |p| {
156 else => @compileError("unsupported format string: " ++ f),156 try std.zig.stringEscape(p, writer);
157 };157 if (path.sub_path.len > 0) try std.zig.stringEscape(fs.path.sep_str, writer);
158 if (self.root_dir.path) |p| {158 }
159 try zigEscape(p, writer);159 if (path.sub_path.len > 0) {
160 if (self.sub_path.len > 0) try zigEscape(fs.path.sep_str, writer);160 try std.zig.stringEscape(path.sub_path, writer);
161 }
162 if (self.sub_path.len > 0) {
163 try zigEscape(self.sub_path, writer);
164 }
165 return;
166 }161 }
167 if (f.len > 0)162}
168 std.fmt.invalidFmtError(f, self);163
164pub fn fmtEscapeChar(path: Path) std.fmt.Formatter(Path, formatEscapeChar) {
165 return .{ .data = path };
166}
167
168pub fn formatEscapeChar(path: Path, writer: *std.io.Writer) std.io.Writer.Error!void {
169 if (path.root_dir.path) |p| {
170 try std.zig.charEscape(p, writer);
171 if (path.sub_path.len > 0) try std.zig.charEscape(fs.path.sep_str, writer);
172 }
173 if (path.sub_path.len > 0) {
174 try std.zig.charEscape(path.sub_path, writer);
175 }
176}
177
178pub fn format(self: Path, writer: *std.io.Writer) std.io.Writer.Error!void {
169 if (std.fs.path.isAbsolute(self.sub_path)) {179 if (std.fs.path.isAbsolute(self.sub_path)) {
170 try writer.writeAll(self.sub_path);180 try writer.writeAll(self.sub_path);
171 return;181 return;
lib/std/SemanticVersion.zig+1-2
...@@ -150,8 +150,7 @@ fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize {...@@ -150,8 +150,7 @@ fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize {
150 };150 };
151}151}
152152
153pub fn format(self: Version, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {153pub fn format(self: Version, w: *std.io.Writer) std.io.Writer.Error!void {
154 if (fmt.len != 0) std.fmt.invalidFmtError(fmt, self);
155 try w.print("{d}.{d}.{d}", .{ self.major, self.minor, self.patch });154 try w.print("{d}.{d}.{d}", .{ self.major, self.minor, self.patch });
156 if (self.pre) |pre| try w.print("-{s}", .{pre});155 if (self.pre) |pre| try w.print("-{s}", .{pre});
157 if (self.build) |build| try w.print("+{s}", .{build});156 if (self.build) |build| try w.print("+{s}", .{build});
lib/std/Uri.zig+117-89
...@@ -1,6 +1,10 @@...@@ -1,6 +1,10 @@
1//! Uniform Resource Identifier (URI) parsing roughly adhering to <https://tools.ietf.org/html/rfc3986>.1//! Uniform Resource Identifier (URI) parsing roughly adhering to <https://tools.ietf.org/html/rfc3986>.
2//! Does not do perfect grammar and character class checking, but should be robust against URIs in the wild.2//! Does not do perfect grammar and character class checking, but should be robust against URIs in the wild.
33
4const std = @import("std.zig");
5const testing = std.testing;
6const Uri = @This();
7
4scheme: []const u8,8scheme: []const u8,
5user: ?Component = null,9user: ?Component = null,
6password: ?Component = null,10password: ?Component = null,
...@@ -34,21 +38,14 @@ pub const Component = union(enum) {...@@ -34,21 +38,14 @@ pub const Component = union(enum) {
34 return switch (component) {38 return switch (component) {
35 .raw => |raw| raw,39 .raw => |raw| raw,
36 .percent_encoded => |percent_encoded| if (std.mem.indexOfScalar(u8, percent_encoded, '%')) |_|40 .percent_encoded => |percent_encoded| if (std.mem.indexOfScalar(u8, percent_encoded, '%')) |_|
37 try std.fmt.allocPrint(arena, "{fraw}", .{component})41 try std.fmt.allocPrint(arena, "{f}", .{std.fmt.alt(component, .formatRaw)})
38 else42 else
39 percent_encoded,43 percent_encoded,
40 };44 };
41 }45 }
4246
43 pub fn format(component: Component, w: *std.io.Writer, comptime fmt_str: []const u8) std.io.Writer.Error!void {47 pub fn formatRaw(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
44 if (fmt_str.len == 0) {48 switch (component) {
45 try w.print("std.Uri.Component{{ .{s} = \"{f}\" }}", .{
46 @tagName(component),
47 std.zig.fmtString(switch (component) {
48 .raw, .percent_encoded => |string| string,
49 }),
50 });
51 } else if (comptime std.mem.eql(u8, fmt_str, "raw")) switch (component) {
52 .raw => |raw| try w.writeAll(raw),49 .raw => |raw| try w.writeAll(raw),
53 .percent_encoded => |percent_encoded| {50 .percent_encoded => |percent_encoded| {
54 var start: usize = 0;51 var start: usize = 0;
...@@ -67,28 +64,56 @@ pub const Component = union(enum) {...@@ -67,28 +64,56 @@ pub const Component = union(enum) {
67 }64 }
68 try w.writeAll(percent_encoded[start..]);65 try w.writeAll(percent_encoded[start..]);
69 },66 },
70 } else if (comptime std.mem.eql(u8, fmt_str, "%")) switch (component) {67 }
68 }
69
70 pub fn formatEscaped(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
71 switch (component) {
71 .raw => |raw| try percentEncode(w, raw, isUnreserved),72 .raw => |raw| try percentEncode(w, raw, isUnreserved),
72 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),73 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
73 } else if (comptime std.mem.eql(u8, fmt_str, "user")) switch (component) {74 }
75 }
76
77 pub fn formatUser(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
78 switch (component) {
74 .raw => |raw| try percentEncode(w, raw, isUserChar),79 .raw => |raw| try percentEncode(w, raw, isUserChar),
75 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),80 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
76 } else if (comptime std.mem.eql(u8, fmt_str, "password")) switch (component) {81 }
82 }
83
84 pub fn formatPassword(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
85 switch (component) {
77 .raw => |raw| try percentEncode(w, raw, isPasswordChar),86 .raw => |raw| try percentEncode(w, raw, isPasswordChar),
78 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),87 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
79 } else if (comptime std.mem.eql(u8, fmt_str, "host")) switch (component) {88 }
89 }
90
91 pub fn formatHost(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
92 switch (component) {
80 .raw => |raw| try percentEncode(w, raw, isHostChar),93 .raw => |raw| try percentEncode(w, raw, isHostChar),
81 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),94 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
82 } else if (comptime std.mem.eql(u8, fmt_str, "path")) switch (component) {95 }
96 }
97
98 pub fn formatPath(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
99 switch (component) {
83 .raw => |raw| try percentEncode(w, raw, isPathChar),100 .raw => |raw| try percentEncode(w, raw, isPathChar),
84 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),101 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
85 } else if (comptime std.mem.eql(u8, fmt_str, "query")) switch (component) {102 }
103 }
104
105 pub fn formatQuery(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
106 switch (component) {
86 .raw => |raw| try percentEncode(w, raw, isQueryChar),107 .raw => |raw| try percentEncode(w, raw, isQueryChar),
87 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),108 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
88 } else if (comptime std.mem.eql(u8, fmt_str, "fragment")) switch (component) {109 }
110 }
111
112 pub fn formatFragment(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
113 switch (component) {
89 .raw => |raw| try percentEncode(w, raw, isFragmentChar),114 .raw => |raw| try percentEncode(w, raw, isFragmentChar),
90 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),115 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
91 } else @compileError("invalid format string '" ++ fmt_str ++ "'");116 }
92 }117 }
93118
94 pub fn percentEncode(w: *std.io.Writer, raw: []const u8, comptime isValidChar: fn (u8) bool) std.io.Writer.Error!void {119 pub fn percentEncode(w: *std.io.Writer, raw: []const u8, comptime isValidChar: fn (u8) bool) std.io.Writer.Error!void {
...@@ -215,82 +240,77 @@ pub fn parseAfterScheme(scheme: []const u8, text: []const u8) ParseError!Uri {...@@ -215,82 +240,77 @@ pub fn parseAfterScheme(scheme: []const u8, text: []const u8) ParseError!Uri {
215 return uri;240 return uri;
216}241}
217242
218pub const WriteToStreamOptions = struct {243pub fn writeToStream(uri: *const Uri, writer: *std.io.Writer, flags: Format.Flags) std.io.Writer.Error!void {
219 /// When true, include the scheme part of the URI.244 if (flags.scheme) {
220 scheme: bool = false,
221
222 /// When true, include the user and password part of the URI. Ignored if `authority` is false.
223 authentication: bool = false,
224
225 /// When true, include the authority part of the URI.
226 authority: bool = false,
227
228 /// When true, include the path part of the URI.
229 path: bool = false,
230
231 /// When true, include the query part of the URI. Ignored when `path` is false.
232 query: bool = false,
233
234 /// When true, include the fragment part of the URI. Ignored when `path` is false.
235 fragment: bool = false,
236
237 /// When true, include the port part of the URI. Ignored when `port` is null.
238 port: bool = true,
239};
240
241pub fn writeToStream(uri: Uri, writer: *std.io.Writer, options: WriteToStreamOptions) std.io.Writer.Error!void {
242 if (options.scheme) {
243 try writer.print("{s}:", .{uri.scheme});245 try writer.print("{s}:", .{uri.scheme});
244 if (options.authority and uri.host != null) {246 if (flags.authority and uri.host != null) {
245 try writer.writeAll("//");247 try writer.writeAll("//");
246 }248 }
247 }249 }
248 if (options.authority) {250 if (flags.authority) {
249 if (options.authentication and uri.host != null) {251 if (flags.authentication and uri.host != null) {
250 if (uri.user) |user| {252 if (uri.user) |user| {
251 try writer.print("{fuser}", .{user});253 try user.formatUser(writer);
252 if (uri.password) |password| {254 if (uri.password) |password| {
253 try writer.print(":{fpassword}", .{password});255 try writer.writeByte(':');
256 try password.formatPassword(writer);
254 }257 }
255 try writer.writeByte('@');258 try writer.writeByte('@');
256 }259 }
257 }260 }
258 if (uri.host) |host| {261 if (uri.host) |host| {
259 try writer.print("{fhost}", .{host});262 try host.formatHost(writer);
260 if (options.port) {263 if (flags.port) {
261 if (uri.port) |port| try writer.print(":{d}", .{port});264 if (uri.port) |port| try writer.print(":{d}", .{port});
262 }265 }
263 }266 }
264 }267 }
265 if (options.path) {268 if (flags.path) {
266 try writer.print("{fpath}", .{269 const uri_path: Component = if (uri.path.isEmpty()) .{ .percent_encoded = "/" } else uri.path;
267 if (uri.path.isEmpty()) Uri.Component{ .percent_encoded = "/" } else uri.path,270 try uri_path.formatPath(writer);
268 });271 if (flags.query) {
269 if (options.query) {272 if (uri.query) |query| {
270 if (uri.query) |query| try writer.print("?{fquery}", .{query});273 try writer.writeByte('?');
274 try query.formatQuery(writer);
275 }
271 }276 }
272 if (options.fragment) {277 if (flags.fragment) {
273 if (uri.fragment) |fragment| try writer.print("#{ffragment}", .{fragment});278 if (uri.fragment) |fragment| {
279 try writer.writeByte('#');
280 try fragment.formatFragment(writer);
281 }
274 }282 }
275 }283 }
276}284}
277285
278pub fn format(uri: Uri, writer: *std.io.Writer, comptime fmt_str: []const u8) std.io.Writer.Error!void {286pub const Format = struct {
279 const scheme = comptime std.mem.indexOfScalar(u8, fmt_str, ';') != null or fmt_str.len == 0;287 uri: *const Uri,
280 const authentication = comptime std.mem.indexOfScalar(u8, fmt_str, '@') != null or fmt_str.len == 0;288 flags: Flags = .{},
281 const authority = comptime std.mem.indexOfScalar(u8, fmt_str, '+') != null or fmt_str.len == 0;289
282 const path = comptime std.mem.indexOfScalar(u8, fmt_str, '/') != null or fmt_str.len == 0;290 pub const Flags = struct {
283 const query = comptime std.mem.indexOfScalar(u8, fmt_str, '?') != null or fmt_str.len == 0;291 /// When true, include the scheme part of the URI.
284 const fragment = comptime std.mem.indexOfScalar(u8, fmt_str, '#') != null or fmt_str.len == 0;292 scheme: bool = false,
293 /// When true, include the user and password part of the URI. Ignored if `authority` is false.
294 authentication: bool = false,
295 /// When true, include the authority part of the URI.
296 authority: bool = false,
297 /// When true, include the path part of the URI.
298 path: bool = false,
299 /// When true, include the query part of the URI. Ignored when `path` is false.
300 query: bool = false,
301 /// When true, include the fragment part of the URI. Ignored when `path` is false.
302 fragment: bool = false,
303 /// When true, include the port part of the URI. Ignored when `port` is null.
304 port: bool = true,
305 };
306
307 pub fn default(f: Format, writer: *std.io.Writer) std.io.Writer.Error!void {
308 return writeToStream(f.uri, writer, f.flags);
309 }
310};
285311
286 return writeToStream(uri, writer, .{312pub fn fmt(uri: *const Uri, flags: Format.Flags) std.fmt.Formatter(Format, Format.default) {
287 .scheme = scheme,313 return .{ .data = .{ .uri = uri, .flags = flags } };
288 .authentication = authentication,
289 .authority = authority,
290 .path = path,
291 .query = query,
292 .fragment = fragment,
293 });
294}314}
295315
296/// Parses the URI or returns an error.316/// Parses the URI or returns an error.
...@@ -427,14 +447,13 @@ test remove_dot_segments {...@@ -427,14 +447,13 @@ test remove_dot_segments {
427447
428/// 5.2.3. Merge Paths448/// 5.2.3. Merge Paths
429fn merge_paths(base: Component, new: []u8, aux_buf: *[]u8) error{NoSpaceLeft}!Component {449fn merge_paths(base: Component, new: []u8, aux_buf: *[]u8) error{NoSpaceLeft}!Component {
430 var aux = std.io.fixedBufferStream(aux_buf.*);450 var aux: std.io.Writer = .fixed(aux_buf.*);
431 if (!base.isEmpty()) {451 if (!base.isEmpty()) {
432 try aux.writer().print("{fpath}", .{base});452 base.formatPath(&aux) catch return error.NoSpaceLeft;
433 aux.pos = std.mem.lastIndexOfScalar(u8, aux.getWritten(), '/') orelse453 aux.end = std.mem.lastIndexOfScalar(u8, aux.buffered(), '/') orelse return remove_dot_segments(new);
434 return remove_dot_segments(new);
435 }454 }
436 try aux.writer().print("/{s}", .{new});455 aux.print("/{s}", .{new}) catch return error.NoSpaceLeft;
437 const merged_path = remove_dot_segments(aux.getWritten());456 const merged_path = remove_dot_segments(aux.buffered());
438 aux_buf.* = aux_buf.*[merged_path.percent_encoded.len..];457 aux_buf.* = aux_buf.*[merged_path.percent_encoded.len..];
439 return merged_path;458 return merged_path;
440}459}
...@@ -794,8 +813,11 @@ test "Special test" {...@@ -794,8 +813,11 @@ test "Special test" {
794test "URI percent encoding" {813test "URI percent encoding" {
795 try std.testing.expectFmt(814 try std.testing.expectFmt(
796 "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad",815 "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad",
797 "{f%}",816 "{f}",
798 .{Component{ .raw = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad" }},817 .{std.fmt.alt(
818 @as(Component, .{ .raw = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad" }),
819 .formatEscaped,
820 )},
799 );821 );
800}822}
801823
...@@ -804,7 +826,10 @@ test "URI percent decoding" {...@@ -804,7 +826,10 @@ test "URI percent decoding" {
804 const expected = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad";826 const expected = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad";
805 var input = "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad".*;827 var input = "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad".*;
806828
807 try std.testing.expectFmt(expected, "{fraw}", .{Component{ .percent_encoded = &input }});829 try std.testing.expectFmt(expected, "{f}", .{std.fmt.alt(
830 @as(Component, .{ .percent_encoded = &input }),
831 .formatRaw,
832 )});
808833
809 var output: [expected.len]u8 = undefined;834 var output: [expected.len]u8 = undefined;
810 try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);835 try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);
...@@ -816,7 +841,10 @@ test "URI percent decoding" {...@@ -816,7 +841,10 @@ test "URI percent decoding" {
816 const expected = "/abc%";841 const expected = "/abc%";
817 var input = expected.*;842 var input = expected.*;
818843
819 try std.testing.expectFmt(expected, "{fraw}", .{Component{ .percent_encoded = &input }});844 try std.testing.expectFmt(expected, "{f}", .{std.fmt.alt(
845 @as(Component, .{ .percent_encoded = &input }),
846 .formatRaw,
847 )});
820848
821 var output: [expected.len]u8 = undefined;849 var output: [expected.len]u8 = undefined;
822 try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);850 try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);
...@@ -830,7 +858,9 @@ test "URI query encoding" {...@@ -830,7 +858,9 @@ test "URI query encoding" {
830 const parsed = try Uri.parse(address);858 const parsed = try Uri.parse(address);
831859
832 // format the URI to percent encode it860 // format the URI to percent encode it
833 try std.testing.expectFmt("/?response-content-type=application%2Foctet-stream", "{f/?}", .{parsed});861 try std.testing.expectFmt("/?response-content-type=application%2Foctet-stream", "{f}", .{
862 parsed.fmt(.{ .path = true, .query = true }),
863 });
834}864}
835865
836test "format" {866test "format" {
...@@ -844,7 +874,9 @@ test "format" {...@@ -844,7 +874,9 @@ test "format" {
844 .query = null,874 .query = null,
845 .fragment = null,875 .fragment = null,
846 };876 };
847 try std.testing.expectFmt("file:/foo/bar/baz", "{f;/?#}", .{uri});877 try std.testing.expectFmt("file:/foo/bar/baz", "{f}", .{
878 uri.fmt(.{ .scheme = true, .path = true, .query = true, .fragment = true }),
879 });
848}880}
849881
850test "URI malformed input" {882test "URI malformed input" {
...@@ -852,7 +884,3 @@ test "URI malformed input" {...@@ -852,7 +884,3 @@ test "URI malformed input" {
852 try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://]@["));884 try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://]@["));
853 try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://lo]s\x85hc@[/8\x10?0Q"));885 try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://lo]s\x85hc@[/8\x10?0Q"));
854}886}
855
856const std = @import("std.zig");
857const testing = std.testing;
858const Uri = @This();
lib/std/builtin.zig+1-3
...@@ -34,9 +34,7 @@ pub const StackTrace = struct {...@@ -34,9 +34,7 @@ pub const StackTrace = struct {
34 index: usize,34 index: usize,
35 instruction_addresses: []usize,35 instruction_addresses: []usize,
3636
37 pub fn format(self: StackTrace, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {37 pub fn format(self: StackTrace, writer: *std.io.Writer) std.io.Writer.Error!void {
38 if (fmt.len != 0) unreachable;
39
40 // TODO: re-evaluate whether to use format() methods at all.38 // TODO: re-evaluate whether to use format() methods at all.
41 // Until then, avoid an error when using GeneralPurposeAllocator with WebAssembly39 // Until then, avoid an error when using GeneralPurposeAllocator with WebAssembly
42 // where it tries to call detectTTYConfig here.40 // where it tries to call detectTTYConfig here.
lib/std/fmt.zig+37-49
...@@ -24,6 +24,8 @@ pub const Alignment = enum {...@@ -24,6 +24,8 @@ pub const Alignment = enum {
24 right,24 right,
25};25};
2626
27pub const Case = enum { lower, upper };
28
27const default_alignment = .right;29const default_alignment = .right;
28const default_fill_char = ' ';30const default_fill_char = ' ';
2931
...@@ -84,13 +86,7 @@ pub const Options = struct {...@@ -84,13 +86,7 @@ pub const Options = struct {
84/// - `!`: output error union value as either the unwrapped value, or the formatted error value; may be followed by a format specifier for the underlying value.86/// - `!`: output error union value as either the unwrapped value, or the formatted error value; may be followed by a format specifier for the underlying value.
85/// - `*`: output the address of the value instead of the value itself.87/// - `*`: output the address of the value instead of the value itself.
86/// - `any`: output a value of any type using its default format.88/// - `any`: output a value of any type using its default format.
87///89/// - `f`: delegates to a method on the type named "format" with the signature `fn (*Writer, args: anytype) Writer.Error!void`.
88/// If a formatted user type contains a function of the type
89/// ```
90/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.Options, writer: anytype) !void
91/// ```
92/// with `?` being the type formatted, this function will be called instead of the default implementation.
93/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.
94///90///
95/// A user type may be a `struct`, `vector`, `union` or `enum` type.91/// A user type may be a `struct`, `vector`, `union` or `enum` type.
96///92///
...@@ -406,8 +402,6 @@ pub const ArgState = struct {...@@ -406,8 +402,6 @@ pub const ArgState = struct {
406 }402 }
407};403};
408404
409pub const Case = enum { lower, upper };
410
411/// Asserts the rendered integer value fits in `buffer`.405/// Asserts the rendered integer value fits in `buffer`.
412/// Returns the end index within `buffer`.406/// Returns the end index within `buffer`.
413pub fn printInt(buffer: []u8, value: anytype, base: u8, case: Case, options: Options) usize {407pub fn printInt(buffer: []u8, value: anytype, base: u8, case: Case, options: Options) usize {
...@@ -425,26 +419,49 @@ pub fn digits2(value: u8) [2]u8 {...@@ -425,26 +419,49 @@ pub fn digits2(value: u8) [2]u8 {
425 }419 }
426}420}
427421
428pub const ParseIntError = error{422/// Deprecated in favor of `Alt`.
429 /// The result cannot fit in the type specified.423pub const Formatter = Alt;
430 Overflow,
431 /// The input was empty or contained an invalid character.
432 InvalidCharacter,
433};
434424
435pub fn Formatter(425/// Creates a type suitable for instantiating and passing to a "{f}" placeholder.
426pub fn Alt(
436 comptime Data: type,427 comptime Data: type,
437 comptime formatFn: fn (data: Data, writer: *Writer) Writer.Error!void,428 comptime formatFn: fn (data: Data, writer: *Writer) Writer.Error!void,
438) type {429) type {
439 return struct {430 return struct {
440 data: Data,431 data: Data,
441 pub fn format(self: @This(), writer: *Writer, comptime fmt: []const u8) Writer.Error!void {432 pub inline fn format(self: @This(), writer: *Writer) Writer.Error!void {
442 comptime assert(fmt.len == 0);
443 try formatFn(self.data, writer);433 try formatFn(self.data, writer);
444 }434 }
445 };435 };
446}436}
447437
438/// Helper for calling alternate format methods besides one named "format".
439pub fn alt(
440 context: anytype,
441 comptime func_name: @TypeOf(.enum_literal),
442) Formatter(@TypeOf(context), @field(@TypeOf(context), @tagName(func_name))) {
443 return .{ .data = context };
444}
445
446test alt {
447 const Example = struct {
448 number: u8,
449
450 pub fn other(ex: @This(), w: *Writer) Writer.Error!void {
451 try w.writeByte(ex.number);
452 }
453 };
454 const ex: Example = .{ .number = 'a' };
455 try expectFmt("a", "{f}", .{alt(ex, .other)});
456}
457
458pub const ParseIntError = error{
459 /// The result cannot fit in the type specified.
460 Overflow,
461 /// The input was empty or contained an invalid character.
462 InvalidCharacter,
463};
464
448/// Parses the string `buf` as signed or unsigned representation in the465/// Parses the string `buf` as signed or unsigned representation in the
449/// specified base of an integral value of type `T`.466/// specified base of an integral value of type `T`.
450///467///
...@@ -1005,7 +1022,7 @@ test "slice" {...@@ -1005,7 +1022,7 @@ test "slice" {
1005 const S2 = struct {1022 const S2 = struct {
1006 x: u8,1023 x: u8,
10071024
1008 pub fn format(s: @This(), writer: *Writer, comptime _: []const u8) Writer.Error!void {1025 pub fn format(s: @This(), writer: *Writer) Writer.Error!void {
1009 try writer.print("S2({})", .{s.x});1026 try writer.print("S2({})", .{s.x});
1010 }1027 }
1011 };1028 };
...@@ -1249,35 +1266,6 @@ test "float.libc.sanity" {...@@ -1249,35 +1266,6 @@ test "float.libc.sanity" {
1249 try expectFmt("f64: 18014400656965630.00000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1518338049))))});1266 try expectFmt("f64: 18014400656965630.00000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1518338049))))});
1250}1267}
12511268
1252test "custom" {
1253 const Vec2 = struct {
1254 const SelfType = @This();
1255 x: f32,
1256 y: f32,
1257
1258 pub fn format(self: SelfType, writer: *Writer, comptime fmt: []const u8) Writer.Error!void {
1259 if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "p")) {
1260 return std.fmt.format(writer, "({d:.3},{d:.3})", .{ self.x, self.y });
1261 } else if (comptime std.mem.eql(u8, fmt, "d")) {
1262 return std.fmt.format(writer, "{d:.3}x{d:.3}", .{ self.x, self.y });
1263 } else {
1264 @compileError("unknown format character: '" ++ fmt ++ "'");
1265 }
1266 }
1267 };
1268
1269 var value: Vec2 = .{
1270 .x = 10.2,
1271 .y = 2.22,
1272 };
1273 try expectFmt("point: (10.200,2.220)\n", "point: {f}\n", .{&value});
1274 try expectFmt("dim: 10.200x2.220\n", "dim: {fd}\n", .{&value});
1275
1276 // same thing but not passing a pointer
1277 try expectFmt("point: (10.200,2.220)\n", "point: {f}\n", .{value});
1278 try expectFmt("dim: 10.200x2.220\n", "dim: {fd}\n", .{value});
1279}
1280
1281test "union" {1269test "union" {
1282 const TU = union(enum) {1270 const TU = union(enum) {
1283 float: f32,1271 float: f32,
...@@ -1516,7 +1504,7 @@ test "recursive format function" {...@@ -1516,7 +1504,7 @@ test "recursive format function" {
1516 Leaf: i32,1504 Leaf: i32,
1517 Branch: struct { left: *const R, right: *const R },1505 Branch: struct { left: *const R, right: *const R },
15181506
1519 pub fn format(self: R, writer: *Writer, comptime _: []const u8) Writer.Error!void {1507 pub fn format(self: R, writer: *Writer) Writer.Error!void {
1520 return switch (self) {1508 return switch (self) {
1521 .Leaf => |n| std.fmt.format(writer, "Leaf({})", .{n}),1509 .Leaf => |n| std.fmt.format(writer, "Leaf({})", .{n}),
1522 .Branch => |b| std.fmt.format(writer, "Branch({f}, {f})", .{ b.left, b.right }),1510 .Branch => |b| std.fmt.format(writer, "Branch({f}, {f})", .{ b.left, b.right }),
lib/std/http.zig+1-2
...@@ -42,8 +42,7 @@ pub const Method = enum(u64) {...@@ -42,8 +42,7 @@ pub const Method = enum(u64) {
42 return x;42 return x;
43 }43 }
4444
45 pub fn format(self: Method, w: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {45 pub fn format(self: Method, w: *std.io.Writer) std.io.Writer.Error!void {
46 comptime assert(f.len == 0);
47 const bytes: []const u8 = @ptrCast(&@intFromEnum(self));46 const bytes: []const u8 = @ptrCast(&@intFromEnum(self));
48 const str = std.mem.sliceTo(bytes, 0);47 const str = std.mem.sliceTo(bytes, 0);
49 try w.writeAll(str);48 try w.writeAll(str);
lib/std/http/Client.zig+20-14
...@@ -832,7 +832,7 @@ pub const Request = struct {...@@ -832,7 +832,7 @@ pub const Request = struct {
832 }832 }
833833
834 fn sendAdapted(req: *Request, connection: *Connection, w: *std.io.Writer) !void {834 fn sendAdapted(req: *Request, connection: *Connection, w: *std.io.Writer) !void {
835 try req.method.format(w, "");835 try req.method.format(w);
836 try w.writeByte(' ');836 try w.writeByte(' ');
837837
838 if (req.method == .CONNECT) {838 if (req.method == .CONNECT) {
...@@ -1290,26 +1290,32 @@ pub const basic_authorization = struct {...@@ -1290,26 +1290,32 @@ pub const basic_authorization = struct {
1290 }1290 }
12911291
1292 pub fn valueLengthFromUri(uri: Uri) usize {1292 pub fn valueLengthFromUri(uri: Uri) usize {
1293 var stream = std.io.countingWriter(std.io.null_writer);1293 const user: Uri.Component = uri.user orelse .empty;
1294 try stream.writer().print("{fuser}", .{uri.user orelse Uri.Component.empty});1294 const password: Uri.Component = uri.password orelse .empty;
1295 const user_len = stream.bytes_written;1295
1296 stream.bytes_written = 0;1296 var w: std.io.Writer = .discarding(&.{});
1297 try stream.writer().print("{fpassword}", .{uri.password orelse Uri.Component.empty});1297 user.formatUser(&w) catch unreachable; // discarding
1298 const password_len = stream.bytes_written;1298 const user_len = w.count;
1299
1300 w.count = 0;
1301 password.formatPassword(&w) catch unreachable; // discarding
1302 const password_len = w.count;
1303
1299 return valueLength(@intCast(user_len), @intCast(password_len));1304 return valueLength(@intCast(user_len), @intCast(password_len));
1300 }1305 }
13011306
1302 pub fn value(uri: Uri, out: []u8) []u8 {1307 pub fn value(uri: Uri, out: []u8) []u8 {
1308 const user: Uri.Component = uri.user orelse .empty;
1309 const password: Uri.Component = uri.password orelse .empty;
1310
1303 var buf: [max_user_len + ":".len + max_password_len]u8 = undefined;1311 var buf: [max_user_len + ":".len + max_password_len]u8 = undefined;
1304 var stream = std.io.fixedBufferStream(&buf);1312 var w: std.io.Writer = .fixed(&buf);
1305 stream.writer().print("{fuser}", .{uri.user orelse Uri.Component.empty}) catch1313 user.formatUser(&w) catch unreachable; // fixed
1306 unreachable;1314 assert(w.count <= max_user_len);
1307 assert(stream.pos <= max_user_len);1315 password.formatPassword(&w) catch unreachable; // fixed
1308 stream.writer().print(":{fpassword}", .{uri.password orelse Uri.Component.empty}) catch
1309 unreachable;
13101316
1311 @memcpy(out[0..prefix.len], prefix);1317 @memcpy(out[0..prefix.len], prefix);
1312 const base64 = std.base64.standard.Encoder.encode(out[prefix.len..], stream.getWritten());1318 const base64 = std.base64.standard.Encoder.encode(out[prefix.len..], w.buffered());
1313 return out[0 .. prefix.len + base64.len];1319 return out[0 .. prefix.len + base64.len];
1314 }1320 }
1315};1321};
lib/std/io/Writer.zig+7-8
...@@ -804,8 +804,11 @@ pub fn printValue(...@@ -804,8 +804,11 @@ pub fn printValue(
804) Error!void {804) Error!void {
805 const T = @TypeOf(value);805 const T = @TypeOf(value);
806806
807 if (comptime std.mem.eql(u8, fmt, "*")) return w.printAddress(value);807 if (fmt.len == 1) switch (fmt[0]) {
808 if (fmt.len > 0 and fmt[0] == 'f') return value.format(w, fmt[1..]);808 '*' => return w.printAddress(value),
809 'f' => return value.format(w),
810 else => {},
811 };
809812
810 const is_any = comptime std.mem.eql(u8, fmt, ANY);813 const is_any = comptime std.mem.eql(u8, fmt, ANY);
811 if (!is_any and std.meta.hasMethod(T, "format") and fmt.len == 0) {814 if (!is_any and std.meta.hasMethod(T, "format") and fmt.len == 0) {
...@@ -1568,12 +1571,8 @@ test "printValue max_depth" {...@@ -1568,12 +1571,8 @@ test "printValue max_depth" {
1568 x: f32,1571 x: f32,
1569 y: f32,1572 y: f32,
15701573
1571 pub fn format(self: SelfType, w: *Writer, comptime fmt: []const u8) Error!void {1574 pub fn format(self: SelfType, w: *Writer) Error!void {
1572 if (fmt.len == 0) {1575 return w.print("({d:.3},{d:.3})", .{ self.x, self.y });
1573 return w.print("({d:.3},{d:.3})", .{ self.x, self.y });
1574 } else {
1575 @compileError("unknown format string: '" ++ fmt ++ "'");
1576 }
1577 }1576 }
1578 };1577 };
1579 const E = enum {1578 const E = enum {
lib/std/json/fmt.zig+1-2
...@@ -15,8 +15,7 @@ pub fn Formatter(comptime T: type) type {...@@ -15,8 +15,7 @@ pub fn Formatter(comptime T: type) type {
15 value: T,15 value: T,
16 options: StringifyOptions,16 options: StringifyOptions,
1717
18 pub fn format(self: @This(), writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {18 pub fn format(self: @This(), writer: *std.io.Writer) std.io.Writer.Error!void {
19 comptime assert(f.len == 0);
20 try stringify(self.value, self.options, writer);19 try stringify(self.value, self.options, writer);
21 }20 }
22 };21 };
lib/std/math/big/int.zig+23-25
...@@ -2317,46 +2317,40 @@ pub const Const = struct {...@@ -2317,46 +2317,40 @@ pub const Const = struct {
2317 return .{ normalized_res.reconstruct(if (self.positive) .positive else .negative), exactness };2317 return .{ normalized_res.reconstruct(if (self.positive) .positive else .negative), exactness };
2318 }2318 }
23192319
2320 /// To allow `std.fmt.format` to work with this type.
2321 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,2320 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,
2322 /// this function will fail to print the string, printing "(BigInt)" instead of a number.2321 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
2323 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.2322 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
2324 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.2323 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.
2325 pub fn format(self: Const, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {2324 pub fn print(self: Const, w: *std.io.Writer, base: u8, case: std.fmt.Case) std.io.Writer.Error!void {
2326 comptime var base = 10;
2327 comptime var case: std.fmt.Case = .lower;
2328
2329 if (fmt.len == 0 or comptime mem.eql(u8, fmt, "d")) {
2330 base = 10;
2331 case = .lower;
2332 } else if (comptime mem.eql(u8, fmt, "b")) {
2333 base = 2;
2334 case = .lower;
2335 } else if (comptime mem.eql(u8, fmt, "x")) {
2336 base = 16;
2337 case = .lower;
2338 } else if (comptime mem.eql(u8, fmt, "X")) {
2339 base = 16;
2340 case = .upper;
2341 } else {
2342 std.fmt.invalidFmtError(fmt, self);
2343 }
2344
2345 const available_len = 64;2325 const available_len = 64;
2346 if (self.limbs.len > available_len)2326 if (self.limbs.len > available_len)
2347 return w.writeAll("(BigInt)");2327 return w.writeAll("(BigInt)");
23482328
2349 var limbs: [calcToStringLimbsBufferLen(available_len, base)]Limb = undefined;2329 var limbs: [calcToStringLimbsBufferLen(available_len, 10)]Limb = undefined;
23502330
2351 const biggest: Const = .{2331 const biggest: Const = .{
2352 .limbs = &([1]Limb{comptime math.maxInt(Limb)} ** available_len),2332 .limbs = &([1]Limb{comptime math.maxInt(Limb)} ** available_len),
2353 .positive = false,2333 .positive = false,
2354 };2334 };
2355 var buf: [biggest.sizeInBaseUpperBound(base)]u8 = undefined;2335 var buf: [biggest.sizeInBaseUpperBound(2)]u8 = undefined;
2356 const len = self.toString(&buf, base, case, &limbs);2336 const len = self.toString(&buf, base, case, &limbs);
2357 return w.writeAll(buf[0..len]);2337 return w.writeAll(buf[0..len]);
2358 }2338 }
23592339
2340 const Format = struct {
2341 int: Const,
2342 base: u8,
2343 case: std.fmt.Case,
2344
2345 pub fn default(f: Format, w: *std.io.Writer) std.io.Writer.Error!void {
2346 return print(f.int, w, f.base, f.case);
2347 }
2348 };
2349
2350 pub fn fmt(self: Const, base: u8, case: std.fmt.Case) std.fmt.Formatter(Format, Format.default) {
2351 return .{ .data = .{ .int = self, .base = base, .case = case } };
2352 }
2353
2360 /// Converts self to a string in the requested base.2354 /// Converts self to a string in the requested base.
2361 /// Caller owns returned memory.2355 /// Caller owns returned memory.
2362 /// Asserts that `base` is in the range [2, 36].2356 /// Asserts that `base` is in the range [2, 36].
...@@ -2924,12 +2918,16 @@ pub const Managed = struct {...@@ -2924,12 +2918,16 @@ pub const Managed = struct {
2924 }2918 }
29252919
2926 /// To allow `std.fmt.format` to work with `Managed`.2920 /// To allow `std.fmt.format` to work with `Managed`.
2921 pub fn format(self: Managed, w: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
2922 return self.toConst().format(w, f);
2923 }
2924
2927 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,2925 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,
2928 /// this function will fail to print the string, printing "(BigInt)" instead of a number.2926 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
2929 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.2927 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
2930 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.2928 /// See `toString` and `toStringAlloc` for a way to print big integers without failure.
2931 pub fn format(self: Managed, w: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {2929 pub fn fmt(self: Managed, base: u8, case: std.fmt.Case) std.fmt.Formatter(Const.Format, Const.Format.default) {
2932 return self.toConst().format(w, f);2930 return .{ .data = .{ .int = self.toConst(), .base = base, .case = case } };
2933 }2931 }
29342932
2935 /// Returns math.Order.lt, math.Order.eq, math.Order.gt if |a| < |b|, |a| ==2933 /// Returns math.Order.lt, math.Order.eq, math.Order.gt if |a| < |b|, |a| ==
lib/std/math/big/int_test.zig+4-10
...@@ -3813,14 +3813,8 @@ test "(BigInt) positive" {...@@ -3813,14 +3813,8 @@ test "(BigInt) positive" {
3813 try a.pow(&a, 64 * @sizeOf(Limb) * 8);3813 try a.pow(&a, 64 * @sizeOf(Limb) * 8);
3814 try b.sub(&a, &c);3814 try b.sub(&a, &c);
38153815
3816 const a_fmt = try std.fmt.allocPrintSentinel(testing.allocator, "{fd}", .{a}, 0);3816 try testing.expectFmt("(BigInt)", "{f}", .{a.fmt(10, .lower)});
3817 defer testing.allocator.free(a_fmt);3817 try testing.expectFmt("1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335", "{f}", .{b.fmt(10, .lower)});
3818
3819 const b_fmt = try std.fmt.allocPrintSentinel(testing.allocator, "{fd}", .{b}, 0);
3820 defer testing.allocator.free(b_fmt);
3821
3822 try testing.expect(mem.eql(u8, a_fmt, "(BigInt)"));
3823 try testing.expect(!mem.eql(u8, b_fmt, "(BigInt)"));
3824}3818}
38253819
3826test "(BigInt) negative" {3820test "(BigInt) negative" {
...@@ -3838,10 +3832,10 @@ test "(BigInt) negative" {...@@ -3838,10 +3832,10 @@ test "(BigInt) negative" {
3838 a.negate();3832 a.negate();
3839 try b.add(&a, &c);3833 try b.add(&a, &c);
38403834
3841 const a_fmt = try std.fmt.allocPrintSentinel(testing.allocator, "{fd}", .{a}, 0);3835 const a_fmt = try std.fmt.allocPrint(testing.allocator, "{f}", .{a.fmt(10, .lower)});
3842 defer testing.allocator.free(a_fmt);3836 defer testing.allocator.free(a_fmt);
38433837
3844 const b_fmt = try std.fmt.allocPrintSentinel(testing.allocator, "{fd}", .{b}, 0);3838 const b_fmt = try std.fmt.allocPrint(testing.allocator, "{f}", .{b.fmt(10, .lower)});
3845 defer testing.allocator.free(b_fmt);3839 defer testing.allocator.free(b_fmt);
38463840
3847 try testing.expect(mem.eql(u8, a_fmt, "(BigInt)"));3841 try testing.expect(mem.eql(u8, a_fmt, "(BigInt)"));
lib/std/net.zig+5-8
...@@ -161,11 +161,10 @@ pub const Address = extern union {...@@ -161,11 +161,10 @@ pub const Address = extern union {
161 }161 }
162 }162 }
163163
164 pub fn format(self: Address, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {164 pub fn format(self: Address, w: *std.io.Writer) std.io.Writer.Error!void {
165 comptime assert(fmt.len == 0);
166 switch (self.any.family) {165 switch (self.any.family) {
167 posix.AF.INET => try self.in.format(w, fmt),166 posix.AF.INET => try self.in.format(w),
168 posix.AF.INET6 => try self.in6.format(w, fmt),167 posix.AF.INET6 => try self.in6.format(w),
169 posix.AF.UNIX => {168 posix.AF.UNIX => {
170 if (!has_unix_sockets) unreachable;169 if (!has_unix_sockets) unreachable;
171 try w.writeAll(std.mem.sliceTo(&self.un.path, 0));170 try w.writeAll(std.mem.sliceTo(&self.un.path, 0));
...@@ -341,8 +340,7 @@ pub const Ip4Address = extern struct {...@@ -341,8 +340,7 @@ pub const Ip4Address = extern struct {
341 self.sa.port = mem.nativeToBig(u16, port);340 self.sa.port = mem.nativeToBig(u16, port);
342 }341 }
343342
344 pub fn format(self: Ip4Address, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {343 pub fn format(self: Ip4Address, w: *std.io.Writer) std.io.Writer.Error!void {
345 comptime assert(fmt.len == 0);
346 const bytes: *const [4]u8 = @ptrCast(&self.sa.addr);344 const bytes: *const [4]u8 = @ptrCast(&self.sa.addr);
347 try w.print("{d}.{d}.{d}.{d}:{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3], self.getPort() });345 try w.print("{d}.{d}.{d}.{d}:{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3], self.getPort() });
348 }346 }
...@@ -633,8 +631,7 @@ pub const Ip6Address = extern struct {...@@ -633,8 +631,7 @@ pub const Ip6Address = extern struct {
633 self.sa.port = mem.nativeToBig(u16, port);631 self.sa.port = mem.nativeToBig(u16, port);
634 }632 }
635633
636 pub fn format(self: Ip6Address, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {634 pub fn format(self: Ip6Address, w: *std.io.Writer) std.io.Writer.Error!void {
637 comptime assert(fmt.len == 0);
638 const port = mem.bigToNative(u16, self.sa.port);635 const port = mem.bigToNative(u16, self.sa.port);
639 if (mem.eql(u8, self.sa.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {636 if (mem.eql(u8, self.sa.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {
640 try w.print("[::ffff:{d}.{d}.{d}.{d}]:{d}", .{637 try w.print("[::ffff:{d}.{d}.{d}.{d}]:{d}", .{
lib/std/os/uefi.zig+1-3
...@@ -60,9 +60,7 @@ pub const Guid = extern struct {...@@ -60,9 +60,7 @@ pub const Guid = extern struct {
60 node: [6]u8,60 node: [6]u8,
6161
62 /// Format GUID into hexadecimal lowercase xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format62 /// Format GUID into hexadecimal lowercase xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format
63 pub fn format(self: @This(), writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {63 pub fn format(self: @This(), writer: *std.io.Writer) std.io.Writer.Error!void {
64 comptime assert(f.len == 0);
65
66 const time_low = @byteSwap(self.time_low);64 const time_low = @byteSwap(self.time_low);
67 const time_mid = @byteSwap(self.time_mid);65 const time_mid = @byteSwap(self.time_mid);
68 const time_high_and_version = @byteSwap(self.time_high_and_version);66 const time_high_and_version = @byteSwap(self.time_high_and_version);
lib/std/zig/llvm/Builder.zig+9-18
...@@ -1796,8 +1796,7 @@ pub const Linkage = enum(u4) {...@@ -1796,8 +1796,7 @@ pub const Linkage = enum(u4) {
1796 extern_weak = 7,1796 extern_weak = 7,
1797 external = 0,1797 external = 0,
17981798
1799 pub fn format(self: Linkage, w: *Writer, comptime f: []const u8) Writer.Error!void {1799 pub fn format(self: Linkage, w: *Writer) Writer.Error!void {
1800 comptime assert(f.len == 0);
1801 if (self != .external) try w.print(" {s}", .{@tagName(self)});1800 if (self != .external) try w.print(" {s}", .{@tagName(self)});
1802 }1801 }
18031802
...@@ -1814,8 +1813,7 @@ pub const Preemption = enum {...@@ -1814,8 +1813,7 @@ pub const Preemption = enum {
1814 dso_local,1813 dso_local,
1815 implicit_dso_local,1814 implicit_dso_local,
18161815
1817 pub fn format(self: Preemption, w: *Writer, comptime f: []const u8) Writer.Error!void {1816 pub fn format(self: Preemption, w: *Writer) Writer.Error!void {
1818 comptime assert(f.len == 0);
1819 if (self == .dso_local) try w.print(" {s}", .{@tagName(self)});1817 if (self == .dso_local) try w.print(" {s}", .{@tagName(self)});
1820 }1818 }
1821};1819};
...@@ -1833,8 +1831,7 @@ pub const Visibility = enum(u2) {...@@ -1833,8 +1831,7 @@ pub const Visibility = enum(u2) {
1833 };1831 };
1834 }1832 }
18351833
1836 pub fn format(self: Visibility, writer: *Writer, comptime f: []const u8) Writer.Error!void {1834 pub fn format(self: Visibility, writer: *Writer) Writer.Error!void {
1837 comptime assert(f.len == 0);
1838 if (self != .default) try writer.print(" {s}", .{@tagName(self)});1835 if (self != .default) try writer.print(" {s}", .{@tagName(self)});
1839 }1836 }
1840};1837};
...@@ -1844,8 +1841,7 @@ pub const DllStorageClass = enum(u2) {...@@ -1844,8 +1841,7 @@ pub const DllStorageClass = enum(u2) {
1844 dllimport = 1,1841 dllimport = 1,
1845 dllexport = 2,1842 dllexport = 2,
18461843
1847 pub fn format(self: DllStorageClass, w: *Writer, comptime f: []const u8) Writer.Error!void {1844 pub fn format(self: DllStorageClass, w: *Writer) Writer.Error!void {
1848 comptime assert(f.len == 0);
1849 if (self != .default) try w.print(" {s}", .{@tagName(self)});1845 if (self != .default) try w.print(" {s}", .{@tagName(self)});
1850 }1846 }
1851};1847};
...@@ -1871,8 +1867,7 @@ pub const UnnamedAddr = enum(u2) {...@@ -1871,8 +1867,7 @@ pub const UnnamedAddr = enum(u2) {
1871 unnamed_addr = 1,1867 unnamed_addr = 1,
1872 local_unnamed_addr = 2,1868 local_unnamed_addr = 2,
18731869
1874 pub fn format(self: UnnamedAddr, w: *Writer, comptime f: []const u8) Writer.Error!void {1870 pub fn format(self: UnnamedAddr, w: *Writer) Writer.Error!void {
1875 comptime assert(f.len == 0);
1876 if (self != .default) try w.print(" {s}", .{@tagName(self)});1871 if (self != .default) try w.print(" {s}", .{@tagName(self)});
1877 }1872 }
1878};1873};
...@@ -1975,8 +1970,7 @@ pub const ExternallyInitialized = enum {...@@ -1975,8 +1970,7 @@ pub const ExternallyInitialized = enum {
1975 default,1970 default,
1976 externally_initialized,1971 externally_initialized,
19771972
1978 pub fn format(self: ExternallyInitialized, w: *Writer, comptime f: []const u8) Writer.Error!void {1973 pub fn format(self: ExternallyInitialized, w: *Writer) Writer.Error!void {
1979 comptime assert(f.len == 0);
1980 if (self != .default) try w.print(" {s}", .{@tagName(self)});1974 if (self != .default) try w.print(" {s}", .{@tagName(self)});
1981 }1975 }
1982};1976};
...@@ -2074,8 +2068,7 @@ pub const CallConv = enum(u10) {...@@ -2074,8 +2068,7 @@ pub const CallConv = enum(u10) {
20742068
2075 pub const default = CallConv.ccc;2069 pub const default = CallConv.ccc;
20762070
2077 pub fn format(self: CallConv, w: *Writer, comptime f: []const u8) Writer.Error!void {2071 pub fn format(self: CallConv, w: *Writer) Writer.Error!void {
2078 comptime assert(f.len == 0);
2079 switch (self) {2072 switch (self) {
2080 default => {},2073 default => {},
2081 .fastcc,2074 .fastcc,
...@@ -7969,8 +7962,7 @@ pub const Metadata = enum(u32) {...@@ -7969,8 +7962,7 @@ pub const Metadata = enum(u32) {
7969 AllCallsDescribed: bool = false,7962 AllCallsDescribed: bool = false,
7970 Unused: u2 = 0,7963 Unused: u2 = 0,
79717964
7972 pub fn format(self: DIFlags, w: *Writer, comptime f: []const u8) Writer.Error!void {7965 pub fn format(self: DIFlags, w: *Writer) Writer.Error!void {
7973 comptime assert(f.len == 0);
7974 var need_pipe = false;7966 var need_pipe = false;
7975 inline for (@typeInfo(DIFlags).@"struct".fields) |field| {7967 inline for (@typeInfo(DIFlags).@"struct".fields) |field| {
7976 switch (@typeInfo(field.type)) {7968 switch (@typeInfo(field.type)) {
...@@ -8027,8 +8019,7 @@ pub const Metadata = enum(u32) {...@@ -8027,8 +8019,7 @@ pub const Metadata = enum(u32) {
8027 ObjCDirect: bool = false,8019 ObjCDirect: bool = false,
8028 Unused: u20 = 0,8020 Unused: u20 = 0,
80298021
8030 pub fn format(self: DISPFlags, w: *Writer, comptime f: []const u8) Writer.Error!void {8022 pub fn format(self: DISPFlags, w: *Writer) Writer.Error!void {
8031 comptime assert(f.len == 0);
8032 var need_pipe = false;8023 var need_pipe = false;
8033 inline for (@typeInfo(DISPFlags).@"struct".fields) |field| {8024 inline for (@typeInfo(DISPFlags).@"struct".fields) |field| {
8034 switch (@typeInfo(field.type)) {8025 switch (@typeInfo(field.type)) {
lib/std/zon/parse.zig+1-2
...@@ -226,8 +226,7 @@ pub const Diagnostics = struct {...@@ -226,8 +226,7 @@ pub const Diagnostics = struct {
226 return .{ .diag = self };226 return .{ .diag = self };
227 }227 }
228228
229 pub fn format(self: *const @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {229 pub fn format(self: *const @This(), w: *std.io.Writer) std.io.Writer.Error!void {
230 comptime assert(fmt.len == 0);
231 var errors = self.iterateErrors();230 var errors = self.iterateErrors();
232 while (errors.next()) |err| {231 while (errors.next()) |err| {
233 const loc = err.getLocation(self);232 const loc = err.getLocation(self);
lib/ubsan_rt.zig+1-3
...@@ -119,9 +119,7 @@ const Value = extern struct {...@@ -119,9 +119,7 @@ const Value = extern struct {
119 }119 }
120 }120 }
121121
122 pub fn format(value: Value, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {122 pub fn format(value: Value, writer: *std.io.Writer) std.io.Writer.Error!void {
123 comptime assert(fmt.len == 0);
124
125 // Work around x86_64 backend limitation.123 // Work around x86_64 backend limitation.
126 if (builtin.zig_backend == .stage2_x86_64 and builtin.os.tag == .windows) {124 if (builtin.zig_backend == .stage2_x86_64 and builtin.os.tag == .windows) {
127 try writer.writeAll("(unknown)");125 try writer.writeAll("(unknown)");
src/Air.zig+1-2
...@@ -957,8 +957,7 @@ pub const Inst = struct {...@@ -957,8 +957,7 @@ pub const Inst = struct {
957 return index.unwrap().target;957 return index.unwrap().target;
958 }958 }
959959
960 pub fn format(index: Index, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {960 pub fn format(index: Index, w: *std.io.Writer) std.io.Writer.Error!void {
961 comptime assert(fmt.len == 0);
962 try w.writeByte('%');961 try w.writeByte('%');
963 switch (index.unwrap()) {962 switch (index.unwrap()) {
964 .ref => {},963 .ref => {},
src/Air/Liveness.zig+2-4
...@@ -2036,8 +2036,7 @@ fn fmtInstSet(set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void)) FmtIns...@@ -2036,8 +2036,7 @@ fn fmtInstSet(set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void)) FmtIns
2036const FmtInstSet = struct {2036const FmtInstSet = struct {
2037 set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void),2037 set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void),
20382038
2039 pub fn format(val: FmtInstSet, w: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {2039 pub fn format(val: FmtInstSet, w: *std.io.Writer) std.io.Writer.Error!void {
2040 comptime assert(f.len == 0);
2041 if (val.set.count() == 0) {2040 if (val.set.count() == 0) {
2042 try w.writeAll("[no instructions]");2041 try w.writeAll("[no instructions]");
2043 return;2042 return;
...@@ -2057,8 +2056,7 @@ fn fmtInstList(list: []const Air.Inst.Index) FmtInstList {...@@ -2057,8 +2056,7 @@ fn fmtInstList(list: []const Air.Inst.Index) FmtInstList {
2057const FmtInstList = struct {2056const FmtInstList = struct {
2058 list: []const Air.Inst.Index,2057 list: []const Air.Inst.Index,
20592058
2060 pub fn format(val: FmtInstList, w: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {2059 pub fn format(val: FmtInstList, w: *std.io.Writer) std.io.Writer.Error!void {
2061 comptime assert(f.len == 0);
2062 if (val.list.len == 0) {2060 if (val.list.len == 0) {
2063 try w.writeAll("[no instructions]");2061 try w.writeAll("[no instructions]");
2064 return;2062 return;
src/Compilation.zig+1-2
...@@ -399,8 +399,7 @@ pub const Path = struct {...@@ -399,8 +399,7 @@ pub const Path = struct {
399 const Formatter = struct {399 const Formatter = struct {
400 p: Path,400 p: Path,
401 comp: *Compilation,401 comp: *Compilation,
402 pub fn format(f: Formatter, w: *std.io.Writer, comptime unused_fmt: []const u8) std.io.Writer.Error!void {402 pub fn format(f: Formatter, w: *std.io.Writer) std.io.Writer.Error!void {
403 comptime assert(unused_fmt.len == 0);
404 const root_path: []const u8 = switch (f.p.root) {403 const root_path: []const u8 = switch (f.p.root) {
405 .zig_lib => f.comp.dirs.zig_lib.path orelse ".",404 .zig_lib => f.comp.dirs.zig_lib.path orelse ".",
406 .global_cache => f.comp.dirs.global_cache.path orelse ".",405 .global_cache => f.comp.dirs.global_cache.path orelse ".",
src/Package/Fetch/git.zig+1-2
...@@ -119,8 +119,7 @@ pub const Oid = union(Format) {...@@ -119,8 +119,7 @@ pub const Oid = union(Format) {
119 } else error.InvalidOid;119 } else error.InvalidOid;
120 }120 }
121121
122 pub fn format(oid: Oid, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {122 pub fn format(oid: Oid, writer: *std.io.Writer) std.io.Writer.Error!void {
123 comptime assert(fmt.len == 0);
124 try writer.print("{x}", .{oid.slice()});123 try writer.print("{x}", .{oid.slice()});
125 }124 }
126125
src/Sema.zig+2-4
...@@ -9448,8 +9448,7 @@ fn callConvSupportsVarArgs(cc: std.builtin.CallingConvention.Tag) bool {...@@ -9448,8 +9448,7 @@ fn callConvSupportsVarArgs(cc: std.builtin.CallingConvention.Tag) bool {
9448fn checkCallConvSupportsVarArgs(sema: *Sema, block: *Block, src: LazySrcLoc, cc: std.builtin.CallingConvention.Tag) CompileError!void {9448fn checkCallConvSupportsVarArgs(sema: *Sema, block: *Block, src: LazySrcLoc, cc: std.builtin.CallingConvention.Tag) CompileError!void {
9449 const CallingConventionsSupportingVarArgsList = struct {9449 const CallingConventionsSupportingVarArgsList = struct {
9450 arch: std.Target.Cpu.Arch,9450 arch: std.Target.Cpu.Arch,
9451 pub fn format(ctx: @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {9451 pub fn format(ctx: @This(), w: *std.io.Writer) std.io.Writer.Error!void {
9452 comptime assert(fmt.len == 0);
9453 var first = true;9452 var first = true;
9454 for (calling_conventions_supporting_var_args) |cc_inner| {9453 for (calling_conventions_supporting_var_args) |cc_inner| {
9455 for (std.Target.Cpu.Arch.fromCallingConvention(cc_inner)) |supported_arch| {9454 for (std.Target.Cpu.Arch.fromCallingConvention(cc_inner)) |supported_arch| {
...@@ -9894,8 +9893,7 @@ fn finishFunc(...@@ -9894,8 +9893,7 @@ fn finishFunc(
9894 .bad_arch => |allowed_archs| {9893 .bad_arch => |allowed_archs| {
9895 const ArchListFormatter = struct {9894 const ArchListFormatter = struct {
9896 archs: []const std.Target.Cpu.Arch,9895 archs: []const std.Target.Cpu.Arch,
9897 pub fn format(formatter: @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {9896 pub fn format(formatter: @This(), w: *std.io.Writer) std.io.Writer.Error!void {
9898 comptime assert(fmt.len == 0);
9899 for (formatter.archs, 0..) |arch, i| {9897 for (formatter.archs, 0..) |arch, i| {
9900 if (i != 0)9898 if (i != 0)
9901 try w.writeAll(", ");9899 try w.writeAll(", ");
src/Type.zig+1-2
...@@ -121,9 +121,8 @@ pub fn eql(a: Type, b: Type, zcu: *const Zcu) bool {...@@ -121,9 +121,8 @@ pub fn eql(a: Type, b: Type, zcu: *const Zcu) bool {
121 return a.toIntern() == b.toIntern();121 return a.toIntern() == b.toIntern();
122}122}
123123
124pub fn format(ty: Type, writer: *std.io.Writer, comptime unused_fmt_string: []const u8) !void {124pub fn format(ty: Type, writer: *std.io.Writer) !void {
125 _ = ty;125 _ = ty;
126 _ = unused_fmt_string;
127 _ = writer;126 _ = writer;
128 @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");127 @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");
129}128}
src/Value.zig+1-2
...@@ -15,10 +15,9 @@ const Value = @This();...@@ -15,10 +15,9 @@ const Value = @This();
1515
16ip_index: InternPool.Index,16ip_index: InternPool.Index,
1717
18pub fn format(val: Value, writer: *std.io.Writer, comptime fmt: []const u8) !void {18pub fn format(val: Value, writer: *std.io.Writer) !void {
19 _ = val;19 _ = val;
20 _ = writer;20 _ = writer;
21 _ = fmt;
22 @compileError("do not use format values directly; use either fmtDebug or fmtValue");21 @compileError("do not use format values directly; use either fmtDebug or fmtValue");
23}22}
2423
src/arch/riscv64/CodeGen.zig+1-2
...@@ -566,8 +566,7 @@ const InstTracking = struct {...@@ -566,8 +566,7 @@ const InstTracking = struct {
566 }566 }
567 }567 }
568568
569 pub fn format(inst_tracking: InstTracking, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {569 pub fn format(inst_tracking: InstTracking, writer: *std.io.Writer) std.io.Writer.Error!void {
570 comptime assert(f.len == 0);
571 if (!std.meta.eql(inst_tracking.long, inst_tracking.short)) try writer.print("|{}| ", .{inst_tracking.long});570 if (!std.meta.eql(inst_tracking.long, inst_tracking.short)) try writer.print("|{}| ", .{inst_tracking.long});
572 try writer.print("{}", .{inst_tracking.short});571 try writer.print("{}", .{inst_tracking.short});
573 }572 }
src/arch/riscv64/Mir.zig+1-2
...@@ -92,8 +92,7 @@ pub const Inst = struct {...@@ -92,8 +92,7 @@ pub const Inst = struct {
92 },92 },
93 };93 };
9494
95 pub fn format(inst: Inst, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {95 pub fn format(inst: Inst, writer: *std.io.Writer) std.io.Writer.Error!void {
96 assert(fmt.len == 0);
97 try writer.print("Tag: {s}, Data: {s}", .{ @tagName(inst.tag), @tagName(inst.data) });96 try writer.print("Tag: {s}, Data: {s}", .{ @tagName(inst.tag), @tagName(inst.data) });
98 }97 }
99};98};
src/arch/riscv64/bits.zig-18
...@@ -249,24 +249,6 @@ pub const FrameIndex = enum(u32) {...@@ -249,24 +249,6 @@ pub const FrameIndex = enum(u32) {
249 spill_frame,249 spill_frame,
250 /// Other indices are used for local variable stack slots250 /// Other indices are used for local variable stack slots
251 _,251 _,
252
253 pub const named_count = @typeInfo(FrameIndex).@"enum".fields.len;
254
255 pub fn isNamed(fi: FrameIndex) bool {
256 return @intFromEnum(fi) < named_count;
257 }
258
259 pub fn format(fi: FrameIndex, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
260 try writer.writeAll("FrameIndex");
261 if (fi.isNamed()) {
262 try writer.writeByte('.');
263 try writer.writeAll(@tagName(fi));
264 } else {
265 try writer.writeByte('(');
266 try writer.printInt(fmt, .{}, @intFromEnum(fi));
267 try writer.writeByte(')');
268 }
269 }
270};252};
271253
272/// A linker symbol not yet allocated in VM.254/// A linker symbol not yet allocated in VM.
src/arch/x86_64/CodeGen.zig+2-2
...@@ -525,7 +525,7 @@ pub const MCValue = union(enum) {...@@ -525,7 +525,7 @@ pub const MCValue = union(enum) {
525 };525 };
526 }526 }
527527
528 pub fn format(mcv: MCValue, bw: *Writer, comptime _: []const u8) Writer.Error!void {528 pub fn format(mcv: MCValue, bw: *Writer) Writer.Error!void {
529 switch (mcv) {529 switch (mcv) {
530 .none, .unreach, .dead, .undef => try bw.print("({s})", .{@tagName(mcv)}),530 .none, .unreach, .dead, .undef => try bw.print("({s})", .{@tagName(mcv)}),
531 .immediate => |pl| try bw.print("0x{x}", .{pl}),531 .immediate => |pl| try bw.print("0x{x}", .{pl}),
...@@ -812,7 +812,7 @@ const InstTracking = struct {...@@ -812,7 +812,7 @@ const InstTracking = struct {
812 }812 }
813 }813 }
814814
815 pub fn format(tracking: InstTracking, bw: *Writer, comptime _: []const u8) Writer.Error!void {815 pub fn format(tracking: InstTracking, bw: *Writer) Writer.Error!void {
816 if (!std.meta.eql(tracking.long, tracking.short)) try bw.print("|{f}| ", .{tracking.long});816 if (!std.meta.eql(tracking.long, tracking.short)) try bw.print("|{f}| ", .{tracking.long});
817 try bw.print("{f}", .{tracking.short});817 try bw.print("{f}", .{tracking.short});
818 }818 }
src/arch/x86_64/Encoding.zig+1-2
...@@ -158,8 +158,7 @@ pub fn modRmExt(encoding: Encoding) u3 {...@@ -158,8 +158,7 @@ pub fn modRmExt(encoding: Encoding) u3 {
158 };158 };
159}159}
160160
161pub fn format(encoding: Encoding, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {161pub fn format(encoding: Encoding, writer: *std.io.Writer) std.io.Writer.Error!void {
162 comptime assert(fmt.len == 0);
163 var opc = encoding.opcode();162 var opc = encoding.opcode();
164 if (encoding.data.mode.isVex()) {163 if (encoding.data.mode.isVex()) {
165 try writer.writeAll("VEX.");164 try writer.writeAll("VEX.");
src/arch/x86_64/bits.zig+2-22
...@@ -721,24 +721,6 @@ pub const FrameIndex = enum(u32) {...@@ -721,24 +721,6 @@ pub const FrameIndex = enum(u32) {
721 call_frame,721 call_frame,
722 // Other indices are used for local variable stack slots722 // Other indices are used for local variable stack slots
723 _,723 _,
724
725 pub const named_count = @typeInfo(FrameIndex).@"enum".fields.len;
726
727 pub fn isNamed(fi: FrameIndex) bool {
728 return @intFromEnum(fi) < named_count;
729 }
730
731 pub fn format(fi: FrameIndex, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
732 try writer.writeAll("FrameIndex");
733 if (fi.isNamed()) {
734 try writer.writeByte('.');
735 try writer.writeAll(@tagName(fi));
736 } else {
737 try writer.writeByte('(');
738 try writer.printInt(fmt, .{}, @intFromEnum(fi));
739 try writer.writeByte(')');
740 }
741 }
742};724};
743725
744pub const FrameAddr = struct { index: FrameIndex, off: i32 = 0 };726pub const FrameAddr = struct { index: FrameIndex, off: i32 = 0 };
...@@ -839,8 +821,7 @@ pub const Memory = struct {...@@ -839,8 +821,7 @@ pub const Memory = struct {
839 };821 };
840 }822 }
841823
842 pub fn format(s: Size, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {824 pub fn format(s: Size, writer: *std.io.Writer) std.io.Writer.Error!void {
843 comptime assert(f.len == 0);
844 if (s == .none) return;825 if (s == .none) return;
845 try writer.writeAll(@tagName(s));826 try writer.writeAll(@tagName(s));
846 switch (s) {827 switch (s) {
...@@ -905,8 +886,7 @@ pub const Immediate = union(enum) {...@@ -905,8 +886,7 @@ pub const Immediate = union(enum) {
905 return .{ .signed = x };886 return .{ .signed = x };
906 }887 }
907888
908 pub fn format(imm: Immediate, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {889 pub fn format(imm: Immediate, writer: *std.io.Writer) std.io.Writer.Error!void {
909 comptime assert(f.len == 0);
910 switch (imm) {890 switch (imm) {
911 inline else => |int| try writer.print("{d}", .{int}),891 inline else => |int| try writer.print("{d}", .{int}),
912 .nav => |nav_off| try writer.print("Nav({d}) + {d}", .{ @intFromEnum(nav_off.nav), nav_off.off }),892 .nav => |nav_off| try writer.print("Nav({d}) + {d}", .{ @intFromEnum(nav_off.nav), nav_off.off }),
src/arch/x86_64/encoder.zig+1-2
...@@ -353,8 +353,7 @@ pub const Instruction = struct {...@@ -353,8 +353,7 @@ pub const Instruction = struct {
353 return inst;353 return inst;
354 }354 }
355355
356 pub fn format(inst: Instruction, w: *Writer, comptime unused_format_string: []const u8) Writer.Error!void {356 pub fn format(inst: Instruction, w: *Writer) Writer.Error!void {
357 comptime assert(unused_format_string.len == 0);
358 switch (inst.prefix) {357 switch (inst.prefix) {
359 .none, .directive => {},358 .none, .directive => {},
360 else => try w.print("{s} ", .{@tagName(inst.prefix)}),359 else => try w.print("{s} ", .{@tagName(inst.prefix)}),
src/codegen/c.zig+1-2
...@@ -2471,8 +2471,7 @@ const RenderCTypeTrailing = enum {...@@ -2471,8 +2471,7 @@ const RenderCTypeTrailing = enum {
2471 no_space,2471 no_space,
2472 maybe_space,2472 maybe_space,
24732473
2474 pub fn format(self: @This(), w: *Writer, comptime fmt: []const u8) Writer.Error!void {2474 pub fn format(self: @This(), w: *Writer) Writer.Error!void {
2475 comptime assert(fmt.len == 0);
2476 switch (self) {2475 switch (self) {
2477 .no_space => {},2476 .no_space => {},
2478 .maybe_space => try w.writeByte(' '),2477 .maybe_space => try w.writeByte(' '),
src/codegen/spirv/spec.zig+1-2
...@@ -19,8 +19,7 @@ pub const IdResult = enum(Word) {...@@ -19,8 +19,7 @@ pub const IdResult = enum(Word) {
19 none,19 none,
20 _,20 _,
2121
22 pub fn format(self: IdResult, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {22 pub fn format(self: IdResult, writer: *std.io.Writer) std.io.Writer.Error!void {
23 comptime assert(f.len == 0);
24 switch (self) {23 switch (self) {
25 .none => try writer.writeAll("(none)"),24 .none => try writer.writeAll("(none)"),
26 else => try writer.print("%{d}", .{@intFromEnum(self)}),25 else => try writer.print("%{d}", .{@intFromEnum(self)}),
src/link/Elf.zig+1-2
...@@ -4192,8 +4192,7 @@ pub const Ref = struct {...@@ -4192,8 +4192,7 @@ pub const Ref = struct {
4192 return ref.index == other.index and ref.file == other.file;4192 return ref.index == other.index and ref.file == other.file;
4193 }4193 }
41944194
4195 pub fn format(ref: Ref, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {4195 pub fn format(ref: Ref, writer: *std.io.Writer) std.io.Writer.Error!void {
4196 comptime assert(f.len == 0);
4197 try writer.print("ref({d},{d})", .{ ref.index, ref.file });4196 try writer.print("ref({d},{d})", .{ ref.index, ref.file });
4198 }4197 }
4199};4198};
src/link/Elf/Archive.zig+1-2
...@@ -260,8 +260,7 @@ pub const ArStrtab = struct {...@@ -260,8 +260,7 @@ pub const ArStrtab = struct {
260 try writer.writeAll(ar.buffer.items);260 try writer.writeAll(ar.buffer.items);
261 }261 }
262262
263 pub fn format(ar: ArStrtab, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {263 pub fn format(ar: ArStrtab, writer: *std.io.Writer) std.io.Writer.Error!void {
264 comptime assert(fmt.len == 0);
265 try writer.print("{f}", .{std.ascii.hexEscape(ar.buffer.items, .lower)});264 try writer.print("{f}", .{std.ascii.hexEscape(ar.buffer.items, .lower)});
266 }265 }
267};266};
src/link/Elf/gc.zig+1-2
...@@ -185,8 +185,7 @@ const Level = struct {...@@ -185,8 +185,7 @@ const Level = struct {
185 self.value += 1;185 self.value += 1;
186 }186 }
187187
188 pub fn format(self: *const @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {188 pub fn format(self: *const @This(), w: *std.io.Writer) std.io.Writer.Error!void {
189 comptime assert(fmt.len == 0);
190 try w.splatByteAll(' ', self.value);189 try w.splatByteAll(' ', self.value);
191 }190 }
192};191};
src/link/MachO.zig+1-2
...@@ -4472,8 +4472,7 @@ pub const Ref = struct {...@@ -4472,8 +4472,7 @@ pub const Ref = struct {
4472 };4472 };
4473 }4473 }
44744474
4475 pub fn format(ref: Ref, bw: *Writer, comptime unused_fmt_string: []const u8) Writer.Error!void {4475 pub fn format(ref: Ref, bw: *Writer) Writer.Error!void {
4476 comptime assert(unused_fmt_string.len == 0);
4477 try bw.print("%{d} in file({d})", .{ ref.index, ref.file });4476 try bw.print("%{d} in file({d})", .{ ref.index, ref.file });
4478 }4477 }
4479};4478};
src/link/MachO/UnwindInfo.zig+1-2
...@@ -455,8 +455,7 @@ pub const Encoding = extern struct {...@@ -455,8 +455,7 @@ pub const Encoding = extern struct {
455 return enc.enc == other.enc;455 return enc.enc == other.enc;
456 }456 }
457457
458 pub fn format(enc: Encoding, w: *Writer, comptime unused_fmt_string: []const u8) Writer.Error!void {458 pub fn format(enc: Encoding, w: *Writer) Writer.Error!void {
459 comptime assert(unused_fmt_string.len == 0);
460 try w.print("0x{x:0>8}", .{enc.enc});459 try w.print("0x{x:0>8}", .{enc.enc});
461 }460 }
462};461};
src/link/MachO/dead_strip.zig+2-3
...@@ -196,9 +196,8 @@ const Level = struct {...@@ -196,9 +196,8 @@ const Level = struct {
196 self.value += 1;196 self.value += 1;
197 }197 }
198198
199 pub fn format(self: *const @This(), bw: *Writer, comptime unused_fmt_string: []const u8) Writer.Error!void {199 pub fn format(self: *const @This(), w: *Writer) Writer.Error!void {
200 _ = unused_fmt_string;200 try w.splatByteAll(' ', self.value);
201 try bw.splatByteAll(' ', self.value);
202 }201 }
203};202};
204203
src/link/Wasm.zig+2-4
...@@ -2126,8 +2126,7 @@ pub const FunctionType = extern struct {...@@ -2126,8 +2126,7 @@ pub const FunctionType = extern struct {
2126 wasm: *const Wasm,2126 wasm: *const Wasm,
2127 ft: FunctionType,2127 ft: FunctionType,
21282128
2129 pub fn format(self: Formatter, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {2129 pub fn format(self: Formatter, writer: *std.io.Writer) std.io.Writer.Error!void {
2130 comptime assert(f.len == 0);
2131 const params = self.ft.params.slice(self.wasm);2130 const params = self.ft.params.slice(self.wasm);
2132 const returns = self.ft.returns.slice(self.wasm);2131 const returns = self.ft.returns.slice(self.wasm);
21332132
...@@ -2906,8 +2905,7 @@ pub const Feature = packed struct(u8) {...@@ -2906,8 +2905,7 @@ pub const Feature = packed struct(u8) {
2906 @"=",2905 @"=",
2907 };2906 };
29082907
2909 pub fn format(feature: Feature, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {2908 pub fn format(feature: Feature, writer: *std.io.Writer) std.io.Writer.Error!void {
2910 comptime assert(fmt.len == 0);
2911 try writer.print("{s} {s}", .{ @tagName(feature.prefix), @tagName(feature.tag) });2909 try writer.print("{s} {s}", .{ @tagName(feature.prefix), @tagName(feature.tag) });
2912 }2910 }
29132911
src/link/table_section.zig+1-2
...@@ -39,8 +39,7 @@ pub fn TableSection(comptime Entry: type) type {...@@ -39,8 +39,7 @@ pub fn TableSection(comptime Entry: type) type {
39 return self.entries.items.len;39 return self.entries.items.len;
40 }40 }
4141
42 pub fn format(self: Self, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {42 pub fn format(self: Self, writer: *std.io.Writer) std.io.Writer.Error!void {
43 comptime assert(f.len == 0);
44 try writer.writeAll("TableSection:\n");43 try writer.writeAll("TableSection:\n");
45 for (self.entries.items, 0..) |entry, i| {44 for (self.entries.items, 0..) |entry, i| {
46 try writer.print(" {d} => {}\n", .{ i, entry });45 try writer.print(" {d} => {}\n", .{ i, entry });
src/link/tapi/parse.zig+6-10
...@@ -57,9 +57,9 @@ pub const Node = struct {...@@ -57,9 +57,9 @@ pub const Node = struct {
57 }57 }
58 }58 }
5959
60 pub fn format(self: *const Node, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {60 pub fn format(self: *const Node, writer: *std.io.Writer) std.io.Writer.Error!void {
61 switch (self.tag) {61 switch (self.tag) {
62 inline else => |tag| return @as(*tag.Type(), @fieldParentPtr("base", self)).format(writer, fmt),62 inline else => |tag| return @as(*tag.Type(), @fieldParentPtr("base", self)).format(writer),
63 }63 }
64 }64 }
6565
...@@ -81,8 +81,7 @@ pub const Node = struct {...@@ -81,8 +81,7 @@ pub const Node = struct {
81 }81 }
82 }82 }
8383
84 pub fn format(self: *const Doc, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {84 pub fn format(self: *const Doc, writer: *std.io.Writer) std.io.Writer.Error!void {
85 comptime assert(fmt.len == 0);
86 if (self.directive) |id| {85 if (self.directive) |id| {
87 try std.fmt.format(writer, "{{ ", .{});86 try std.fmt.format(writer, "{{ ", .{});
88 const directive = self.base.tree.getRaw(id, id);87 const directive = self.base.tree.getRaw(id, id);
...@@ -122,8 +121,7 @@ pub const Node = struct {...@@ -122,8 +121,7 @@ pub const Node = struct {
122 self.values.deinit(allocator);121 self.values.deinit(allocator);
123 }122 }
124123
125 pub fn format(self: *const Map, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {124 pub fn format(self: *const Map, writer: *std.io.Writer) std.io.Writer.Error!void {
126 comptime assert(fmt.len == 0);
127 try std.fmt.format(writer, "{{ ", .{});125 try std.fmt.format(writer, "{{ ", .{});
128 for (self.values.items) |entry| {126 for (self.values.items) |entry| {
129 const key = self.base.tree.getRaw(entry.key, entry.key);127 const key = self.base.tree.getRaw(entry.key, entry.key);
...@@ -155,8 +153,7 @@ pub const Node = struct {...@@ -155,8 +153,7 @@ pub const Node = struct {
155 self.values.deinit(allocator);153 self.values.deinit(allocator);
156 }154 }
157155
158 pub fn format(self: *const List, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {156 pub fn format(self: *const List, writer: *std.io.Writer) std.io.Writer.Error!void {
159 comptime assert(fmt.len == 0);
160 try std.fmt.format(writer, "[ ", .{});157 try std.fmt.format(writer, "[ ", .{});
161 for (self.values.items) |node| {158 for (self.values.items) |node| {
162 try std.fmt.format(writer, "{}, ", .{node});159 try std.fmt.format(writer, "{}, ", .{node});
...@@ -180,8 +177,7 @@ pub const Node = struct {...@@ -180,8 +177,7 @@ pub const Node = struct {
180 self.string_value.deinit(allocator);177 self.string_value.deinit(allocator);
181 }178 }
182179
183 pub fn format(self: *const Value, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {180 pub fn format(self: *const Value, writer: *std.io.Writer) std.io.Writer.Error!void {
184 comptime assert(fmt.len == 0);
185 const raw = self.base.tree.getRaw(self.base.start, self.base.end);181 const raw = self.base.tree.getRaw(self.base.start, self.base.end);
186 return std.fmt.format(writer, "{s}", .{raw});182 return std.fmt.format(writer, "{s}", .{raw});
187 }183 }