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) {
164164 return @bitCast(self);
165165 }
166166
167 pub fn format(language: Language, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
168 comptime assert(fmt.len == 0);
167 pub fn format(language: Language, w: *std.io.Writer) std.io.Writer.Error!void {
169168 const language_id = language.asInt();
170169 const language_name = language_name: {
171170 if (std.enums.fromInt(lang.LanguageId, language_id)) |lang_enum_val| {
......@@ -440,8 +439,7 @@ pub const NameOrOrdinal = union(enum) {
440439 }
441440 }
442441
443 pub fn format(self: NameOrOrdinal, w: *std.io.Writer, comptime fmt: []const u8) !void {
444 comptime assert(fmt.len == 0);
442 pub fn format(self: NameOrOrdinal, w: *std.io.Writer) !void {
445443 switch (self) {
446444 .name => |name| {
447445 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 {
5656 self.* = undefined;
5757}
5858
59pub fn format(self: Directory, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
60 comptime assert(f.len == 0);
59pub fn format(self: Directory, writer: *std.io.Writer) std.io.Writer.Error!void {
6160 if (self.path) |p| {
6261 try writer.writeAll(p);
6362 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 {
147147 return std.fmt.allocPrintSentinel(allocator, "{f}", .{p}, 0);
148148}
149149
150pub fn format(self: Path, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
151 if (f.len == 1) {
152 // Quote-escape the string.
153 const zigEscape = switch (f[0]) {
154 'q' => std.zig.stringEscape,
155 '\'' => std.zig.charEscape,
156 else => @compileError("unsupported format string: " ++ f),
157 };
158 if (self.root_dir.path) |p| {
159 try zigEscape(p, writer);
160 if (self.sub_path.len > 0) try zigEscape(fs.path.sep_str, writer);
161 }
162 if (self.sub_path.len > 0) {
163 try zigEscape(self.sub_path, writer);
164 }
165 return;
150pub fn fmtEscapeString(path: Path) std.fmt.Formatter(Path, formatEscapeString) {
151 return .{ .data = path };
152}
153
154pub fn formatEscapeString(path: Path, writer: *std.io.Writer) std.io.Writer.Error!void {
155 if (path.root_dir.path) |p| {
156 try std.zig.stringEscape(p, writer);
157 if (path.sub_path.len > 0) try std.zig.stringEscape(fs.path.sep_str, writer);
158 }
159 if (path.sub_path.len > 0) {
160 try std.zig.stringEscape(path.sub_path, writer);
166161 }
167 if (f.len > 0)
168 std.fmt.invalidFmtError(f, self);
162}
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 {
169179 if (std.fs.path.isAbsolute(self.sub_path)) {
170180 try writer.writeAll(self.sub_path);
171181 return;
lib/std/SemanticVersion.zig+1-2
......@@ -150,8 +150,7 @@ fn parseNum(text: []const u8) error{ InvalidVersion, Overflow }!usize {
150150 };
151151}
152152
153pub fn format(self: Version, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
154 if (fmt.len != 0) std.fmt.invalidFmtError(fmt, self);
153pub fn format(self: Version, w: *std.io.Writer) std.io.Writer.Error!void {
155154 try w.print("{d}.{d}.{d}", .{ self.major, self.minor, self.patch });
156155 if (self.pre) |pre| try w.print("-{s}", .{pre});
157156 if (self.build) |build| try w.print("+{s}", .{build});
lib/std/Uri.zig+117-89
......@@ -1,6 +1,10 @@
11//! Uniform Resource Identifier (URI) parsing roughly adhering to <https://tools.ietf.org/html/rfc3986>.
22//! 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
48scheme: []const u8,
59user: ?Component = null,
610password: ?Component = null,
......@@ -34,21 +38,14 @@ pub const Component = union(enum) {
3438 return switch (component) {
3539 .raw => |raw| raw,
3640 .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)})
3842 else
3943 percent_encoded,
4044 };
4145 }
4246
43 pub fn format(component: Component, w: *std.io.Writer, comptime fmt_str: []const u8) std.io.Writer.Error!void {
44 if (fmt_str.len == 0) {
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) {
47 pub fn formatRaw(component: Component, w: *std.io.Writer) std.io.Writer.Error!void {
48 switch (component) {
5249 .raw => |raw| try w.writeAll(raw),
5350 .percent_encoded => |percent_encoded| {
5451 var start: usize = 0;
......@@ -67,28 +64,56 @@ pub const Component = union(enum) {
6764 }
6865 try w.writeAll(percent_encoded[start..]);
6966 },
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) {
7172 .raw => |raw| try percentEncode(w, raw, isUnreserved),
7273 .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) {
7479 .raw => |raw| try percentEncode(w, raw, isUserChar),
7580 .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) {
7786 .raw => |raw| try percentEncode(w, raw, isPasswordChar),
7887 .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) {
8093 .raw => |raw| try percentEncode(w, raw, isHostChar),
8194 .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) {
83100 .raw => |raw| try percentEncode(w, raw, isPathChar),
84101 .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) {
86107 .raw => |raw| try percentEncode(w, raw, isQueryChar),
87108 .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) {
89114 .raw => |raw| try percentEncode(w, raw, isFragmentChar),
90115 .percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
91 } else @compileError("invalid format string '" ++ fmt_str ++ "'");
116 }
92117 }
93118
94119 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 {
215240 return uri;
216241}
217242
218pub const WriteToStreamOptions = struct {
219 /// When true, include the scheme part of the URI.
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) {
243pub fn writeToStream(uri: *const Uri, writer: *std.io.Writer, flags: Format.Flags) std.io.Writer.Error!void {
244 if (flags.scheme) {
243245 try writer.print("{s}:", .{uri.scheme});
244 if (options.authority and uri.host != null) {
246 if (flags.authority and uri.host != null) {
245247 try writer.writeAll("//");
246248 }
247249 }
248 if (options.authority) {
249 if (options.authentication and uri.host != null) {
250 if (flags.authority) {
251 if (flags.authentication and uri.host != null) {
250252 if (uri.user) |user| {
251 try writer.print("{fuser}", .{user});
253 try user.formatUser(writer);
252254 if (uri.password) |password| {
253 try writer.print(":{fpassword}", .{password});
255 try writer.writeByte(':');
256 try password.formatPassword(writer);
254257 }
255258 try writer.writeByte('@');
256259 }
257260 }
258261 if (uri.host) |host| {
259 try writer.print("{fhost}", .{host});
260 if (options.port) {
262 try host.formatHost(writer);
263 if (flags.port) {
261264 if (uri.port) |port| try writer.print(":{d}", .{port});
262265 }
263266 }
264267 }
265 if (options.path) {
266 try writer.print("{fpath}", .{
267 if (uri.path.isEmpty()) Uri.Component{ .percent_encoded = "/" } else uri.path,
268 });
269 if (options.query) {
270 if (uri.query) |query| try writer.print("?{fquery}", .{query});
268 if (flags.path) {
269 const uri_path: Component = if (uri.path.isEmpty()) .{ .percent_encoded = "/" } else uri.path;
270 try uri_path.formatPath(writer);
271 if (flags.query) {
272 if (uri.query) |query| {
273 try writer.writeByte('?');
274 try query.formatQuery(writer);
275 }
271276 }
272 if (options.fragment) {
273 if (uri.fragment) |fragment| try writer.print("#{ffragment}", .{fragment});
277 if (flags.fragment) {
278 if (uri.fragment) |fragment| {
279 try writer.writeByte('#');
280 try fragment.formatFragment(writer);
281 }
274282 }
275283 }
276284}
277285
278pub fn format(uri: Uri, writer: *std.io.Writer, comptime fmt_str: []const u8) std.io.Writer.Error!void {
279 const scheme = comptime std.mem.indexOfScalar(u8, fmt_str, ';') != null or fmt_str.len == 0;
280 const authentication = comptime std.mem.indexOfScalar(u8, fmt_str, '@') != null or fmt_str.len == 0;
281 const authority = comptime std.mem.indexOfScalar(u8, fmt_str, '+') != null or fmt_str.len == 0;
282 const path = comptime std.mem.indexOfScalar(u8, fmt_str, '/') != null or fmt_str.len == 0;
283 const query = comptime std.mem.indexOfScalar(u8, fmt_str, '?') != null or fmt_str.len == 0;
284 const fragment = comptime std.mem.indexOfScalar(u8, fmt_str, '#') != null or fmt_str.len == 0;
286pub const Format = struct {
287 uri: *const Uri,
288 flags: Flags = .{},
289
290 pub const Flags = struct {
291 /// When true, include the scheme part of the URI.
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, .{
287 .scheme = scheme,
288 .authentication = authentication,
289 .authority = authority,
290 .path = path,
291 .query = query,
292 .fragment = fragment,
293 });
312pub fn fmt(uri: *const Uri, flags: Format.Flags) std.fmt.Formatter(Format, Format.default) {
313 return .{ .data = .{ .uri = uri, .flags = flags } };
294314}
295315
296316/// Parses the URI or returns an error.
......@@ -427,14 +447,13 @@ test remove_dot_segments {
427447
428448/// 5.2.3. Merge Paths
429449fn 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.*);
431451 if (!base.isEmpty()) {
432 try aux.writer().print("{fpath}", .{base});
433 aux.pos = std.mem.lastIndexOfScalar(u8, aux.getWritten(), '/') orelse
434 return remove_dot_segments(new);
452 base.formatPath(&aux) catch return error.NoSpaceLeft;
453 aux.end = std.mem.lastIndexOfScalar(u8, aux.buffered(), '/') orelse return remove_dot_segments(new);
435454 }
436 try aux.writer().print("/{s}", .{new});
437 const merged_path = remove_dot_segments(aux.getWritten());
455 aux.print("/{s}", .{new}) catch return error.NoSpaceLeft;
456 const merged_path = remove_dot_segments(aux.buffered());
438457 aux_buf.* = aux_buf.*[merged_path.percent_encoded.len..];
439458 return merged_path;
440459}
......@@ -794,8 +813,11 @@ test "Special test" {
794813test "URI percent encoding" {
795814 try std.testing.expectFmt(
796815 "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad",
797 "{f%}",
798 .{Component{ .raw = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad" }},
816 "{f}",
817 .{std.fmt.alt(
818 @as(Component, .{ .raw = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad" }),
819 .formatEscaped,
820 )},
799821 );
800822}
801823
......@@ -804,7 +826,10 @@ test "URI percent decoding" {
804826 const expected = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad";
805827 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
809834 var output: [expected.len]u8 = undefined;
810835 try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);
......@@ -816,7 +841,10 @@ test "URI percent decoding" {
816841 const expected = "/abc%";
817842 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
821849 var output: [expected.len]u8 = undefined;
822850 try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);
......@@ -830,7 +858,9 @@ test "URI query encoding" {
830858 const parsed = try Uri.parse(address);
831859
832860 // 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 });
834864}
835865
836866test "format" {
......@@ -844,7 +874,9 @@ test "format" {
844874 .query = null,
845875 .fragment = null,
846876 };
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 });
848880}
849881
850882test "URI malformed input" {
......@@ -852,7 +884,3 @@ test "URI malformed input" {
852884 try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://]@["));
853885 try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://lo]s\x85hc@[/8\x10?0Q"));
854886}
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 {
3434 index: usize,
3535 instruction_addresses: []usize,
3636
37 pub fn format(self: StackTrace, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
38 if (fmt.len != 0) unreachable;
39
37 pub fn format(self: StackTrace, writer: *std.io.Writer) std.io.Writer.Error!void {
4038 // TODO: re-evaluate whether to use format() methods at all.
4139 // Until then, avoid an error when using GeneralPurposeAllocator with WebAssembly
4240 // where it tries to call detectTTYConfig here.
lib/std/fmt.zig+37-49
......@@ -24,6 +24,8 @@ pub const Alignment = enum {
2424 right,
2525};
2626
27pub const Case = enum { lower, upper };
28
2729const default_alignment = .right;
2830const default_fill_char = ' ';
2931
......@@ -84,13 +86,7 @@ pub const Options = struct {
8486/// - `!`: 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.
8587/// - `*`: output the address of the value instead of the value itself.
8688/// - `any`: output a value of any type using its default format.
87///
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.
89/// - `f`: delegates to a method on the type named "format" with the signature `fn (*Writer, args: anytype) Writer.Error!void`.
9490///
9591/// A user type may be a `struct`, `vector`, `union` or `enum` type.
9692///
......@@ -406,8 +402,6 @@ pub const ArgState = struct {
406402 }
407403};
408404
409pub const Case = enum { lower, upper };
410
411405/// Asserts the rendered integer value fits in `buffer`.
412406/// Returns the end index within `buffer`.
413407pub fn printInt(buffer: []u8, value: anytype, base: u8, case: Case, options: Options) usize {
......@@ -425,26 +419,49 @@ pub fn digits2(value: u8) [2]u8 {
425419 }
426420}
427421
428pub const ParseIntError = error{
429 /// The result cannot fit in the type specified.
430 Overflow,
431 /// The input was empty or contained an invalid character.
432 InvalidCharacter,
433};
422/// Deprecated in favor of `Alt`.
423pub const Formatter = Alt;
434424
435pub fn Formatter(
425/// Creates a type suitable for instantiating and passing to a "{f}" placeholder.
426pub fn Alt(
436427 comptime Data: type,
437428 comptime formatFn: fn (data: Data, writer: *Writer) Writer.Error!void,
438429) type {
439430 return struct {
440431 data: Data,
441 pub fn format(self: @This(), writer: *Writer, comptime fmt: []const u8) Writer.Error!void {
442 comptime assert(fmt.len == 0);
432 pub inline fn format(self: @This(), writer: *Writer) Writer.Error!void {
443433 try formatFn(self.data, writer);
444434 }
445435 };
446436}
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
448465/// Parses the string `buf` as signed or unsigned representation in the
449466/// specified base of an integral value of type `T`.
450467///
......@@ -1005,7 +1022,7 @@ test "slice" {
10051022 const S2 = struct {
10061023 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 {
10091026 try writer.print("S2({})", .{s.x});
10101027 }
10111028 };
......@@ -1249,35 +1266,6 @@ test "float.libc.sanity" {
12491266 try expectFmt("f64: 18014400656965630.00000", "f64: {d:.5}", .{@as(f64, @as(f32, @bitCast(@as(u32, 1518338049))))});
12501267}
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
12811269test "union" {
12821270 const TU = union(enum) {
12831271 float: f32,
......@@ -1516,7 +1504,7 @@ test "recursive format function" {
15161504 Leaf: i32,
15171505 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 {
15201508 return switch (self) {
15211509 .Leaf => |n| std.fmt.format(writer, "Leaf({})", .{n}),
15221510 .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) {
4242 return x;
4343 }
4444
45 pub fn format(self: Method, w: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
46 comptime assert(f.len == 0);
45 pub fn format(self: Method, w: *std.io.Writer) std.io.Writer.Error!void {
4746 const bytes: []const u8 = @ptrCast(&@intFromEnum(self));
4847 const str = std.mem.sliceTo(bytes, 0);
4948 try w.writeAll(str);
lib/std/http/Client.zig+20-14
......@@ -832,7 +832,7 @@ pub const Request = struct {
832832 }
833833
834834 fn sendAdapted(req: *Request, connection: *Connection, w: *std.io.Writer) !void {
835 try req.method.format(w, "");
835 try req.method.format(w);
836836 try w.writeByte(' ');
837837
838838 if (req.method == .CONNECT) {
......@@ -1290,26 +1290,32 @@ pub const basic_authorization = struct {
12901290 }
12911291
12921292 pub fn valueLengthFromUri(uri: Uri) usize {
1293 var stream = std.io.countingWriter(std.io.null_writer);
1294 try stream.writer().print("{fuser}", .{uri.user orelse Uri.Component.empty});
1295 const user_len = stream.bytes_written;
1296 stream.bytes_written = 0;
1297 try stream.writer().print("{fpassword}", .{uri.password orelse Uri.Component.empty});
1298 const password_len = stream.bytes_written;
1293 const user: Uri.Component = uri.user orelse .empty;
1294 const password: Uri.Component = uri.password orelse .empty;
1295
1296 var w: std.io.Writer = .discarding(&.{});
1297 user.formatUser(&w) catch unreachable; // discarding
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
12991304 return valueLength(@intCast(user_len), @intCast(password_len));
13001305 }
13011306
13021307 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
13031311 var buf: [max_user_len + ":".len + max_password_len]u8 = undefined;
1304 var stream = std.io.fixedBufferStream(&buf);
1305 stream.writer().print("{fuser}", .{uri.user orelse Uri.Component.empty}) catch
1306 unreachable;
1307 assert(stream.pos <= max_user_len);
1308 stream.writer().print(":{fpassword}", .{uri.password orelse Uri.Component.empty}) catch
1309 unreachable;
1312 var w: std.io.Writer = .fixed(&buf);
1313 user.formatUser(&w) catch unreachable; // fixed
1314 assert(w.count <= max_user_len);
1315 password.formatPassword(&w) catch unreachable; // fixed
13101316
13111317 @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());
13131319 return out[0 .. prefix.len + base64.len];
13141320 }
13151321};
lib/std/io/Writer.zig+7-8
......@@ -804,8 +804,11 @@ pub fn printValue(
804804) Error!void {
805805 const T = @TypeOf(value);
806806
807 if (comptime std.mem.eql(u8, fmt, "*")) return w.printAddress(value);
808 if (fmt.len > 0 and fmt[0] == 'f') return value.format(w, fmt[1..]);
807 if (fmt.len == 1) switch (fmt[0]) {
808 '*' => return w.printAddress(value),
809 'f' => return value.format(w),
810 else => {},
811 };
809812
810813 const is_any = comptime std.mem.eql(u8, fmt, ANY);
811814 if (!is_any and std.meta.hasMethod(T, "format") and fmt.len == 0) {
......@@ -1568,12 +1571,8 @@ test "printValue max_depth" {
15681571 x: f32,
15691572 y: f32,
15701573
1571 pub fn format(self: SelfType, w: *Writer, comptime fmt: []const u8) Error!void {
1572 if (fmt.len == 0) {
1573 return w.print("({d:.3},{d:.3})", .{ self.x, self.y });
1574 } else {
1575 @compileError("unknown format string: '" ++ fmt ++ "'");
1576 }
1574 pub fn format(self: SelfType, w: *Writer) Error!void {
1575 return w.print("({d:.3},{d:.3})", .{ self.x, self.y });
15771576 }
15781577 };
15791578 const E = enum {
lib/std/json/fmt.zig+1-2
......@@ -15,8 +15,7 @@ pub fn Formatter(comptime T: type) type {
1515 value: T,
1616 options: StringifyOptions,
1717
18 pub fn format(self: @This(), writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
19 comptime assert(f.len == 0);
18 pub fn format(self: @This(), writer: *std.io.Writer) std.io.Writer.Error!void {
2019 try stringify(self.value, self.options, writer);
2120 }
2221 };
lib/std/math/big/int.zig+23-25
......@@ -2317,46 +2317,40 @@ pub const Const = struct {
23172317 return .{ normalized_res.reconstruct(if (self.positive) .positive else .negative), exactness };
23182318 }
23192319
2320 /// To allow `std.fmt.format` to work with this type.
23212320 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,
23222321 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
23232322 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
23242323 /// 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 {
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
2324 pub fn print(self: Const, w: *std.io.Writer, base: u8, case: std.fmt.Case) std.io.Writer.Error!void {
23452325 const available_len = 64;
23462326 if (self.limbs.len > available_len)
23472327 return w.writeAll("(BigInt)");
23482328
2349 var limbs: [calcToStringLimbsBufferLen(available_len, base)]Limb = undefined;
2329 var limbs: [calcToStringLimbsBufferLen(available_len, 10)]Limb = undefined;
23502330
23512331 const biggest: Const = .{
23522332 .limbs = &([1]Limb{comptime math.maxInt(Limb)} ** available_len),
23532333 .positive = false,
23542334 };
2355 var buf: [biggest.sizeInBaseUpperBound(base)]u8 = undefined;
2335 var buf: [biggest.sizeInBaseUpperBound(2)]u8 = undefined;
23562336 const len = self.toString(&buf, base, case, &limbs);
23572337 return w.writeAll(buf[0..len]);
23582338 }
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
23602354 /// Converts self to a string in the requested base.
23612355 /// Caller owns returned memory.
23622356 /// Asserts that `base` is in the range [2, 36].
......@@ -2924,12 +2918,16 @@ pub const Managed = struct {
29242918 }
29252919
29262920 /// 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
29272925 /// If the absolute value of integer is greater than or equal to `pow(2, 64 * @sizeOf(usize) * 8)`,
29282926 /// this function will fail to print the string, printing "(BigInt)" instead of a number.
29292927 /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory.
29302928 /// 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 {
2932 return self.toConst().format(w, f);
2929 pub fn fmt(self: Managed, base: u8, case: std.fmt.Case) std.fmt.Formatter(Const.Format, Const.Format.default) {
2930 return .{ .data = .{ .int = self.toConst(), .base = base, .case = case } };
29332931 }
29342932
29352933 /// 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" {
38133813 try a.pow(&a, 64 * @sizeOf(Limb) * 8);
38143814 try b.sub(&a, &c);
38153815
3816 const a_fmt = try std.fmt.allocPrintSentinel(testing.allocator, "{fd}", .{a}, 0);
3817 defer testing.allocator.free(a_fmt);
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)"));
3816 try testing.expectFmt("(BigInt)", "{f}", .{a.fmt(10, .lower)});
3817 try testing.expectFmt("1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335", "{f}", .{b.fmt(10, .lower)});
38243818}
38253819
38263820test "(BigInt) negative" {
......@@ -3838,10 +3832,10 @@ test "(BigInt) negative" {
38383832 a.negate();
38393833 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)});
38423836 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)});
38453839 defer testing.allocator.free(b_fmt);
38463840
38473841 try testing.expect(mem.eql(u8, a_fmt, "(BigInt)"));
lib/std/net.zig+5-8
......@@ -161,11 +161,10 @@ pub const Address = extern union {
161161 }
162162 }
163163
164 pub fn format(self: Address, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
165 comptime assert(fmt.len == 0);
164 pub fn format(self: Address, w: *std.io.Writer) std.io.Writer.Error!void {
166165 switch (self.any.family) {
167 posix.AF.INET => try self.in.format(w, fmt),
168 posix.AF.INET6 => try self.in6.format(w, fmt),
166 posix.AF.INET => try self.in.format(w),
167 posix.AF.INET6 => try self.in6.format(w),
169168 posix.AF.UNIX => {
170169 if (!has_unix_sockets) unreachable;
171170 try w.writeAll(std.mem.sliceTo(&self.un.path, 0));
......@@ -341,8 +340,7 @@ pub const Ip4Address = extern struct {
341340 self.sa.port = mem.nativeToBig(u16, port);
342341 }
343342
344 pub fn format(self: Ip4Address, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
345 comptime assert(fmt.len == 0);
343 pub fn format(self: Ip4Address, w: *std.io.Writer) std.io.Writer.Error!void {
346344 const bytes: *const [4]u8 = @ptrCast(&self.sa.addr);
347345 try w.print("{d}.{d}.{d}.{d}:{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3], self.getPort() });
348346 }
......@@ -633,8 +631,7 @@ pub const Ip6Address = extern struct {
633631 self.sa.port = mem.nativeToBig(u16, port);
634632 }
635633
636 pub fn format(self: Ip6Address, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
637 comptime assert(fmt.len == 0);
634 pub fn format(self: Ip6Address, w: *std.io.Writer) std.io.Writer.Error!void {
638635 const port = mem.bigToNative(u16, self.sa.port);
639636 if (mem.eql(u8, self.sa.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {
640637 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 {
6060 node: [6]u8,
6161
6262 /// 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 {
64 comptime assert(f.len == 0);
65
63 pub fn format(self: @This(), writer: *std.io.Writer) std.io.Writer.Error!void {
6664 const time_low = @byteSwap(self.time_low);
6765 const time_mid = @byteSwap(self.time_mid);
6866 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) {
17961796 extern_weak = 7,
17971797 external = 0,
17981798
1799 pub fn format(self: Linkage, w: *Writer, comptime f: []const u8) Writer.Error!void {
1800 comptime assert(f.len == 0);
1799 pub fn format(self: Linkage, w: *Writer) Writer.Error!void {
18011800 if (self != .external) try w.print(" {s}", .{@tagName(self)});
18021801 }
18031802
......@@ -1814,8 +1813,7 @@ pub const Preemption = enum {
18141813 dso_local,
18151814 implicit_dso_local,
18161815
1817 pub fn format(self: Preemption, w: *Writer, comptime f: []const u8) Writer.Error!void {
1818 comptime assert(f.len == 0);
1816 pub fn format(self: Preemption, w: *Writer) Writer.Error!void {
18191817 if (self == .dso_local) try w.print(" {s}", .{@tagName(self)});
18201818 }
18211819};
......@@ -1833,8 +1831,7 @@ pub const Visibility = enum(u2) {
18331831 };
18341832 }
18351833
1836 pub fn format(self: Visibility, writer: *Writer, comptime f: []const u8) Writer.Error!void {
1837 comptime assert(f.len == 0);
1834 pub fn format(self: Visibility, writer: *Writer) Writer.Error!void {
18381835 if (self != .default) try writer.print(" {s}", .{@tagName(self)});
18391836 }
18401837};
......@@ -1844,8 +1841,7 @@ pub const DllStorageClass = enum(u2) {
18441841 dllimport = 1,
18451842 dllexport = 2,
18461843
1847 pub fn format(self: DllStorageClass, w: *Writer, comptime f: []const u8) Writer.Error!void {
1848 comptime assert(f.len == 0);
1844 pub fn format(self: DllStorageClass, w: *Writer) Writer.Error!void {
18491845 if (self != .default) try w.print(" {s}", .{@tagName(self)});
18501846 }
18511847};
......@@ -1871,8 +1867,7 @@ pub const UnnamedAddr = enum(u2) {
18711867 unnamed_addr = 1,
18721868 local_unnamed_addr = 2,
18731869
1874 pub fn format(self: UnnamedAddr, w: *Writer, comptime f: []const u8) Writer.Error!void {
1875 comptime assert(f.len == 0);
1870 pub fn format(self: UnnamedAddr, w: *Writer) Writer.Error!void {
18761871 if (self != .default) try w.print(" {s}", .{@tagName(self)});
18771872 }
18781873};
......@@ -1975,8 +1970,7 @@ pub const ExternallyInitialized = enum {
19751970 default,
19761971 externally_initialized,
19771972
1978 pub fn format(self: ExternallyInitialized, w: *Writer, comptime f: []const u8) Writer.Error!void {
1979 comptime assert(f.len == 0);
1973 pub fn format(self: ExternallyInitialized, w: *Writer) Writer.Error!void {
19801974 if (self != .default) try w.print(" {s}", .{@tagName(self)});
19811975 }
19821976};
......@@ -2074,8 +2068,7 @@ pub const CallConv = enum(u10) {
20742068
20752069 pub const default = CallConv.ccc;
20762070
2077 pub fn format(self: CallConv, w: *Writer, comptime f: []const u8) Writer.Error!void {
2078 comptime assert(f.len == 0);
2071 pub fn format(self: CallConv, w: *Writer) Writer.Error!void {
20792072 switch (self) {
20802073 default => {},
20812074 .fastcc,
......@@ -7969,8 +7962,7 @@ pub const Metadata = enum(u32) {
79697962 AllCallsDescribed: bool = false,
79707963 Unused: u2 = 0,
79717964
7972 pub fn format(self: DIFlags, w: *Writer, comptime f: []const u8) Writer.Error!void {
7973 comptime assert(f.len == 0);
7965 pub fn format(self: DIFlags, w: *Writer) Writer.Error!void {
79747966 var need_pipe = false;
79757967 inline for (@typeInfo(DIFlags).@"struct".fields) |field| {
79767968 switch (@typeInfo(field.type)) {
......@@ -8027,8 +8019,7 @@ pub const Metadata = enum(u32) {
80278019 ObjCDirect: bool = false,
80288020 Unused: u20 = 0,
80298021
8030 pub fn format(self: DISPFlags, w: *Writer, comptime f: []const u8) Writer.Error!void {
8031 comptime assert(f.len == 0);
8022 pub fn format(self: DISPFlags, w: *Writer) Writer.Error!void {
80328023 var need_pipe = false;
80338024 inline for (@typeInfo(DISPFlags).@"struct".fields) |field| {
80348025 switch (@typeInfo(field.type)) {
lib/std/zon/parse.zig+1-2
......@@ -226,8 +226,7 @@ pub const Diagnostics = struct {
226226 return .{ .diag = self };
227227 }
228228
229 pub fn format(self: *const @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
230 comptime assert(fmt.len == 0);
229 pub fn format(self: *const @This(), w: *std.io.Writer) std.io.Writer.Error!void {
231230 var errors = self.iterateErrors();
232231 while (errors.next()) |err| {
233232 const loc = err.getLocation(self);
lib/ubsan_rt.zig+1-3
......@@ -119,9 +119,7 @@ const Value = extern struct {
119119 }
120120 }
121121
122 pub fn format(value: Value, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
123 comptime assert(fmt.len == 0);
124
122 pub fn format(value: Value, writer: *std.io.Writer) std.io.Writer.Error!void {
125123 // Work around x86_64 backend limitation.
126124 if (builtin.zig_backend == .stage2_x86_64 and builtin.os.tag == .windows) {
127125 try writer.writeAll("(unknown)");
src/Air.zig+1-2
......@@ -957,8 +957,7 @@ pub const Inst = struct {
957957 return index.unwrap().target;
958958 }
959959
960 pub fn format(index: Index, w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
961 comptime assert(fmt.len == 0);
960 pub fn format(index: Index, w: *std.io.Writer) std.io.Writer.Error!void {
962961 try w.writeByte('%');
963962 switch (index.unwrap()) {
964963 .ref => {},
src/Air/Liveness.zig+2-4
......@@ -2036,8 +2036,7 @@ fn fmtInstSet(set: *const std.AutoHashMapUnmanaged(Air.Inst.Index, void)) FmtIns
20362036const FmtInstSet = struct {
20372037 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 {
2040 comptime assert(f.len == 0);
2039 pub fn format(val: FmtInstSet, w: *std.io.Writer) std.io.Writer.Error!void {
20412040 if (val.set.count() == 0) {
20422041 try w.writeAll("[no instructions]");
20432042 return;
......@@ -2057,8 +2056,7 @@ fn fmtInstList(list: []const Air.Inst.Index) FmtInstList {
20572056const FmtInstList = struct {
20582057 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 {
2061 comptime assert(f.len == 0);
2059 pub fn format(val: FmtInstList, w: *std.io.Writer) std.io.Writer.Error!void {
20622060 if (val.list.len == 0) {
20632061 try w.writeAll("[no instructions]");
20642062 return;
src/Compilation.zig+1-2
......@@ -399,8 +399,7 @@ pub const Path = struct {
399399 const Formatter = struct {
400400 p: Path,
401401 comp: *Compilation,
402 pub fn format(f: Formatter, w: *std.io.Writer, comptime unused_fmt: []const u8) std.io.Writer.Error!void {
403 comptime assert(unused_fmt.len == 0);
402 pub fn format(f: Formatter, w: *std.io.Writer) std.io.Writer.Error!void {
404403 const root_path: []const u8 = switch (f.p.root) {
405404 .zig_lib => f.comp.dirs.zig_lib.path orelse ".",
406405 .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) {
119119 } else error.InvalidOid;
120120 }
121121
122 pub fn format(oid: Oid, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
123 comptime assert(fmt.len == 0);
122 pub fn format(oid: Oid, writer: *std.io.Writer) std.io.Writer.Error!void {
124123 try writer.print("{x}", .{oid.slice()});
125124 }
126125
src/Sema.zig+2-4
......@@ -9448,8 +9448,7 @@ fn callConvSupportsVarArgs(cc: std.builtin.CallingConvention.Tag) bool {
94489448fn checkCallConvSupportsVarArgs(sema: *Sema, block: *Block, src: LazySrcLoc, cc: std.builtin.CallingConvention.Tag) CompileError!void {
94499449 const CallingConventionsSupportingVarArgsList = struct {
94509450 arch: std.Target.Cpu.Arch,
9451 pub fn format(ctx: @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
9452 comptime assert(fmt.len == 0);
9451 pub fn format(ctx: @This(), w: *std.io.Writer) std.io.Writer.Error!void {
94539452 var first = true;
94549453 for (calling_conventions_supporting_var_args) |cc_inner| {
94559454 for (std.Target.Cpu.Arch.fromCallingConvention(cc_inner)) |supported_arch| {
......@@ -9894,8 +9893,7 @@ fn finishFunc(
98949893 .bad_arch => |allowed_archs| {
98959894 const ArchListFormatter = struct {
98969895 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 {
9898 comptime assert(fmt.len == 0);
9896 pub fn format(formatter: @This(), w: *std.io.Writer) std.io.Writer.Error!void {
98999897 for (formatter.archs, 0..) |arch, i| {
99009898 if (i != 0)
99019899 try w.writeAll(", ");
src/Type.zig+1-2
......@@ -121,9 +121,8 @@ pub fn eql(a: Type, b: Type, zcu: *const Zcu) bool {
121121 return a.toIntern() == b.toIntern();
122122}
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 {
125125 _ = ty;
126 _ = unused_fmt_string;
127126 _ = writer;
128127 @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");
129128}
src/Value.zig+1-2
......@@ -15,10 +15,9 @@ const Value = @This();
1515
1616ip_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 {
1919 _ = val;
2020 _ = writer;
21 _ = fmt;
2221 @compileError("do not use format values directly; use either fmtDebug or fmtValue");
2322}
2423
src/arch/riscv64/CodeGen.zig+1-2
......@@ -566,8 +566,7 @@ const InstTracking = struct {
566566 }
567567 }
568568
569 pub fn format(inst_tracking: InstTracking, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
570 comptime assert(f.len == 0);
569 pub fn format(inst_tracking: InstTracking, writer: *std.io.Writer) std.io.Writer.Error!void {
571570 if (!std.meta.eql(inst_tracking.long, inst_tracking.short)) try writer.print("|{}| ", .{inst_tracking.long});
572571 try writer.print("{}", .{inst_tracking.short});
573572 }
src/arch/riscv64/Mir.zig+1-2
......@@ -92,8 +92,7 @@ pub const Inst = struct {
9292 },
9393 };
9494
95 pub fn format(inst: Inst, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
96 assert(fmt.len == 0);
95 pub fn format(inst: Inst, writer: *std.io.Writer) std.io.Writer.Error!void {
9796 try writer.print("Tag: {s}, Data: {s}", .{ @tagName(inst.tag), @tagName(inst.data) });
9897 }
9998};
src/arch/riscv64/bits.zig-18
......@@ -249,24 +249,6 @@ pub const FrameIndex = enum(u32) {
249249 spill_frame,
250250 /// Other indices are used for local variable stack slots
251251 _,
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 }
270252};
271253
272254/// 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) {
525525 };
526526 }
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 {
529529 switch (mcv) {
530530 .none, .unreach, .dead, .undef => try bw.print("({s})", .{@tagName(mcv)}),
531531 .immediate => |pl| try bw.print("0x{x}", .{pl}),
......@@ -812,7 +812,7 @@ const InstTracking = struct {
812812 }
813813 }
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 {
816816 if (!std.meta.eql(tracking.long, tracking.short)) try bw.print("|{f}| ", .{tracking.long});
817817 try bw.print("{f}", .{tracking.short});
818818 }
src/arch/x86_64/Encoding.zig+1-2
......@@ -158,8 +158,7 @@ pub fn modRmExt(encoding: Encoding) u3 {
158158 };
159159}
160160
161pub fn format(encoding: Encoding, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
162 comptime assert(fmt.len == 0);
161pub fn format(encoding: Encoding, writer: *std.io.Writer) std.io.Writer.Error!void {
163162 var opc = encoding.opcode();
164163 if (encoding.data.mode.isVex()) {
165164 try writer.writeAll("VEX.");
src/arch/x86_64/bits.zig+2-22
......@@ -721,24 +721,6 @@ pub const FrameIndex = enum(u32) {
721721 call_frame,
722722 // Other indices are used for local variable stack slots
723723 _,
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 }
742724};
743725
744726pub const FrameAddr = struct { index: FrameIndex, off: i32 = 0 };
......@@ -839,8 +821,7 @@ pub const Memory = struct {
839821 };
840822 }
841823
842 pub fn format(s: Size, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
843 comptime assert(f.len == 0);
824 pub fn format(s: Size, writer: *std.io.Writer) std.io.Writer.Error!void {
844825 if (s == .none) return;
845826 try writer.writeAll(@tagName(s));
846827 switch (s) {
......@@ -905,8 +886,7 @@ pub const Immediate = union(enum) {
905886 return .{ .signed = x };
906887 }
907888
908 pub fn format(imm: Immediate, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
909 comptime assert(f.len == 0);
889 pub fn format(imm: Immediate, writer: *std.io.Writer) std.io.Writer.Error!void {
910890 switch (imm) {
911891 inline else => |int| try writer.print("{d}", .{int}),
912892 .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 {
353353 return inst;
354354 }
355355
356 pub fn format(inst: Instruction, w: *Writer, comptime unused_format_string: []const u8) Writer.Error!void {
357 comptime assert(unused_format_string.len == 0);
356 pub fn format(inst: Instruction, w: *Writer) Writer.Error!void {
358357 switch (inst.prefix) {
359358 .none, .directive => {},
360359 else => try w.print("{s} ", .{@tagName(inst.prefix)}),
src/codegen/c.zig+1-2
......@@ -2471,8 +2471,7 @@ const RenderCTypeTrailing = enum {
24712471 no_space,
24722472 maybe_space,
24732473
2474 pub fn format(self: @This(), w: *Writer, comptime fmt: []const u8) Writer.Error!void {
2475 comptime assert(fmt.len == 0);
2474 pub fn format(self: @This(), w: *Writer) Writer.Error!void {
24762475 switch (self) {
24772476 .no_space => {},
24782477 .maybe_space => try w.writeByte(' '),
src/codegen/spirv/spec.zig+1-2
......@@ -19,8 +19,7 @@ pub const IdResult = enum(Word) {
1919 none,
2020 _,
2121
22 pub fn format(self: IdResult, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
23 comptime assert(f.len == 0);
22 pub fn format(self: IdResult, writer: *std.io.Writer) std.io.Writer.Error!void {
2423 switch (self) {
2524 .none => try writer.writeAll("(none)"),
2625 else => try writer.print("%{d}", .{@intFromEnum(self)}),
src/link/Elf.zig+1-2
......@@ -4192,8 +4192,7 @@ pub const Ref = struct {
41924192 return ref.index == other.index and ref.file == other.file;
41934193 }
41944194
4195 pub fn format(ref: Ref, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
4196 comptime assert(f.len == 0);
4195 pub fn format(ref: Ref, writer: *std.io.Writer) std.io.Writer.Error!void {
41974196 try writer.print("ref({d},{d})", .{ ref.index, ref.file });
41984197 }
41994198};
src/link/Elf/Archive.zig+1-2
......@@ -260,8 +260,7 @@ pub const ArStrtab = struct {
260260 try writer.writeAll(ar.buffer.items);
261261 }
262262
263 pub fn format(ar: ArStrtab, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
264 comptime assert(fmt.len == 0);
263 pub fn format(ar: ArStrtab, writer: *std.io.Writer) std.io.Writer.Error!void {
265264 try writer.print("{f}", .{std.ascii.hexEscape(ar.buffer.items, .lower)});
266265 }
267266};
src/link/Elf/gc.zig+1-2
......@@ -185,8 +185,7 @@ const Level = struct {
185185 self.value += 1;
186186 }
187187
188 pub fn format(self: *const @This(), w: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
189 comptime assert(fmt.len == 0);
188 pub fn format(self: *const @This(), w: *std.io.Writer) std.io.Writer.Error!void {
190189 try w.splatByteAll(' ', self.value);
191190 }
192191};
src/link/MachO.zig+1-2
......@@ -4472,8 +4472,7 @@ pub const Ref = struct {
44724472 };
44734473 }
44744474
4475 pub fn format(ref: Ref, bw: *Writer, comptime unused_fmt_string: []const u8) Writer.Error!void {
4476 comptime assert(unused_fmt_string.len == 0);
4475 pub fn format(ref: Ref, bw: *Writer) Writer.Error!void {
44774476 try bw.print("%{d} in file({d})", .{ ref.index, ref.file });
44784477 }
44794478};
src/link/MachO/UnwindInfo.zig+1-2
......@@ -455,8 +455,7 @@ pub const Encoding = extern struct {
455455 return enc.enc == other.enc;
456456 }
457457
458 pub fn format(enc: Encoding, w: *Writer, comptime unused_fmt_string: []const u8) Writer.Error!void {
459 comptime assert(unused_fmt_string.len == 0);
458 pub fn format(enc: Encoding, w: *Writer) Writer.Error!void {
460459 try w.print("0x{x:0>8}", .{enc.enc});
461460 }
462461};
src/link/MachO/dead_strip.zig+2-3
......@@ -196,9 +196,8 @@ const Level = struct {
196196 self.value += 1;
197197 }
198198
199 pub fn format(self: *const @This(), bw: *Writer, comptime unused_fmt_string: []const u8) Writer.Error!void {
200 _ = unused_fmt_string;
201 try bw.splatByteAll(' ', self.value);
199 pub fn format(self: *const @This(), w: *Writer) Writer.Error!void {
200 try w.splatByteAll(' ', self.value);
202201 }
203202};
204203
src/link/Wasm.zig+2-4
......@@ -2126,8 +2126,7 @@ pub const FunctionType = extern struct {
21262126 wasm: *const Wasm,
21272127 ft: FunctionType,
21282128
2129 pub fn format(self: Formatter, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
2130 comptime assert(f.len == 0);
2129 pub fn format(self: Formatter, writer: *std.io.Writer) std.io.Writer.Error!void {
21312130 const params = self.ft.params.slice(self.wasm);
21322131 const returns = self.ft.returns.slice(self.wasm);
21332132
......@@ -2906,8 +2905,7 @@ pub const Feature = packed struct(u8) {
29062905 @"=",
29072906 };
29082907
2909 pub fn format(feature: Feature, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
2910 comptime assert(fmt.len == 0);
2908 pub fn format(feature: Feature, writer: *std.io.Writer) std.io.Writer.Error!void {
29112909 try writer.print("{s} {s}", .{ @tagName(feature.prefix), @tagName(feature.tag) });
29122910 }
29132911
src/link/table_section.zig+1-2
......@@ -39,8 +39,7 @@ pub fn TableSection(comptime Entry: type) type {
3939 return self.entries.items.len;
4040 }
4141
42 pub fn format(self: Self, writer: *std.io.Writer, comptime f: []const u8) std.io.Writer.Error!void {
43 comptime assert(f.len == 0);
42 pub fn format(self: Self, writer: *std.io.Writer) std.io.Writer.Error!void {
4443 try writer.writeAll("TableSection:\n");
4544 for (self.entries.items, 0..) |entry, i| {
4645 try writer.print(" {d} => {}\n", .{ i, entry });
src/link/tapi/parse.zig+6-10
......@@ -57,9 +57,9 @@ pub const Node = struct {
5757 }
5858 }
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 {
6161 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),
6363 }
6464 }
6565
......@@ -81,8 +81,7 @@ pub const Node = struct {
8181 }
8282 }
8383
84 pub fn format(self: *const Doc, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
85 comptime assert(fmt.len == 0);
84 pub fn format(self: *const Doc, writer: *std.io.Writer) std.io.Writer.Error!void {
8685 if (self.directive) |id| {
8786 try std.fmt.format(writer, "{{ ", .{});
8887 const directive = self.base.tree.getRaw(id, id);
......@@ -122,8 +121,7 @@ pub const Node = struct {
122121 self.values.deinit(allocator);
123122 }
124123
125 pub fn format(self: *const Map, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
126 comptime assert(fmt.len == 0);
124 pub fn format(self: *const Map, writer: *std.io.Writer) std.io.Writer.Error!void {
127125 try std.fmt.format(writer, "{{ ", .{});
128126 for (self.values.items) |entry| {
129127 const key = self.base.tree.getRaw(entry.key, entry.key);
......@@ -155,8 +153,7 @@ pub const Node = struct {
155153 self.values.deinit(allocator);
156154 }
157155
158 pub fn format(self: *const List, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
159 comptime assert(fmt.len == 0);
156 pub fn format(self: *const List, writer: *std.io.Writer) std.io.Writer.Error!void {
160157 try std.fmt.format(writer, "[ ", .{});
161158 for (self.values.items) |node| {
162159 try std.fmt.format(writer, "{}, ", .{node});
......@@ -180,8 +177,7 @@ pub const Node = struct {
180177 self.string_value.deinit(allocator);
181178 }
182179
183 pub fn format(self: *const Value, writer: *std.io.Writer, comptime fmt: []const u8) std.io.Writer.Error!void {
184 comptime assert(fmt.len == 0);
180 pub fn format(self: *const Value, writer: *std.io.Writer) std.io.Writer.Error!void {
185181 const raw = self.base.tree.getRaw(self.base.start, self.base.end);
186182 return std.fmt.format(writer, "{s}", .{raw});
187183 }