authorgravatar for 59504965+InKryption@users.noreply.github.comInKryption <59504965+InKryption@users.noreply.github.com> 2022-07-24 11:01:56+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-07-24 12:01:56+03:00
log7cbd586ace46a8e8cebab660ebca3cfc049305d9
tree10514a09063847aaed2a8dcc9b0f2196f0cc3ef4
parent0b4a3ec9501b31e7b31e81b83e5974e6c6d72757
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std.fmt: require specifier for unwrapping ?T and E!T.

Co-authored-by: Veikka Tuominen <git@vexu.eu>

13 files changed, 59 insertions(+), 34 deletions(-)

doc/langref.html.in+4-4
...@@ -574,7 +574,7 @@ pub fn main() void {...@@ -574,7 +574,7 @@ pub fn main() void {
574 var optional_value: ?[]const u8 = null;574 var optional_value: ?[]const u8 = null;
575 assert(optional_value == null);575 assert(optional_value == null);
576576
577 print("\noptional 1\ntype: {s}\nvalue: {s}\n", .{577 print("\noptional 1\ntype: {s}\nvalue: {?s}\n", .{
578 @typeName(@TypeOf(optional_value)),578 @typeName(@TypeOf(optional_value)),
579 optional_value,579 optional_value,
580 });580 });
...@@ -582,7 +582,7 @@ pub fn main() void {...@@ -582,7 +582,7 @@ pub fn main() void {
582 optional_value = "hi";582 optional_value = "hi";
583 assert(optional_value != null);583 assert(optional_value != null);
584584
585 print("\noptional 2\ntype: {s}\nvalue: {s}\n", .{585 print("\noptional 2\ntype: {s}\nvalue: {?s}\n", .{
586 @typeName(@TypeOf(optional_value)),586 @typeName(@TypeOf(optional_value)),
587 optional_value,587 optional_value,
588 });588 });
...@@ -590,14 +590,14 @@ pub fn main() void {...@@ -590,14 +590,14 @@ pub fn main() void {
590 // error union590 // error union
591 var number_or_error: anyerror!i32 = error.ArgNotFound;591 var number_or_error: anyerror!i32 = error.ArgNotFound;
592592
593 print("\nerror union 1\ntype: {s}\nvalue: {}\n", .{593 print("\nerror union 1\ntype: {s}\nvalue: {!}\n", .{
594 @typeName(@TypeOf(number_or_error)),594 @typeName(@TypeOf(number_or_error)),
595 number_or_error,595 number_or_error,
596 });596 });
597597
598 number_or_error = 1234;598 number_or_error = 1234;
599599
600 print("\nerror union 2\ntype: {s}\nvalue: {}\n", .{600 print("\nerror union 2\ntype: {s}\nvalue: {!}\n", .{
601 @typeName(@TypeOf(number_or_error)),601 @typeName(@TypeOf(number_or_error)),
602 number_or_error,602 number_or_error,
603 });603 });
lib/std/build.zig+2-2
...@@ -750,7 +750,7 @@ pub const Builder = struct {...@@ -750,7 +750,7 @@ pub const Builder = struct {
750 \\Available CPU features for architecture '{s}':750 \\Available CPU features for architecture '{s}':
751 \\751 \\
752 , .{752 , .{
753 diags.unknown_feature_name,753 diags.unknown_feature_name.?,
754 @tagName(diags.arch.?),754 @tagName(diags.arch.?),
755 });755 });
756 for (diags.arch.?.allFeaturesList()) |feature| {756 for (diags.arch.?.allFeaturesList()) |feature| {
...@@ -764,7 +764,7 @@ pub const Builder = struct {...@@ -764,7 +764,7 @@ pub const Builder = struct {
764 \\Unknown OS: '{s}'764 \\Unknown OS: '{s}'
765 \\Available operating systems:765 \\Available operating systems:
766 \\766 \\
767 , .{diags.os_name});767 , .{diags.os_name.?});
768 inline for (std.meta.fields(std.Target.Os.Tag)) |field| {768 inline for (std.meta.fields(std.Target.Os.Tag)) |field| {
769 log.err(" {s}", .{field.name});769 log.err(" {s}", .{field.name});
770 }770 }
lib/std/crypto/phc_encoding.zig+1-1
...@@ -216,7 +216,7 @@ fn serializeTo(params: anytype, out: anytype) !void {...@@ -216,7 +216,7 @@ fn serializeTo(params: anytype, out: anytype) !void {
216216
217 var has_params = false;217 var has_params = false;
218 inline for (comptime meta.fields(HashResult)) |p| {218 inline for (comptime meta.fields(HashResult)) |p| {
219 if (!(mem.eql(u8, p.name, "alg_id") or219 if (comptime !(mem.eql(u8, p.name, "alg_id") or
220 mem.eql(u8, p.name, "alg_version") or220 mem.eql(u8, p.name, "alg_version") or
221 mem.eql(u8, p.name, "hash") or221 mem.eql(u8, p.name, "hash") or
222 mem.eql(u8, p.name, "salt")))222 mem.eql(u8, p.name, "salt")))
lib/std/fmt.zig+33-11
...@@ -60,8 +60,10 @@ pub const FormatOptions = struct {...@@ -60,8 +60,10 @@ pub const FormatOptions = struct {
60/// - `o`: output integer value in octal notation60/// - `o`: output integer value in octal notation
61/// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max.61/// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max.
62/// - `u`: output integer as an UTF-8 sequence. Integer type must have 21 bits at max.62/// - `u`: output integer as an UTF-8 sequence. Integer type must have 21 bits at max.
63/// - `?`: output optional value as either the unwrapped value, or `null`; may be followed by a format specifier for the underlying value.
64/// - `!`: 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.
63/// - `*`: output the address of the value instead of the value itself.65/// - `*`: output the address of the value instead of the value itself.
64/// - `any`: output a value of any type using its default format66/// - `any`: output a value of any type using its default format.
65///67///
66/// If a formatted user type contains a function of the type68/// If a formatted user type contains a function of the type
67/// ```69/// ```
...@@ -438,12 +440,20 @@ fn defaultSpec(comptime T: type) [:0]const u8 {...@@ -438,12 +440,20 @@ fn defaultSpec(comptime T: type) [:0]const u8 {
438 .Many, .C => return "*",440 .Many, .C => return "*",
439 .Slice => return ANY,441 .Slice => return ANY,
440 },442 },
441 .Optional => |info| return defaultSpec(info.child),443 .Optional => |info| return "?" ++ defaultSpec(info.child),
444 .ErrorUnion => |info| return "!" ++ defaultSpec(info.payload),
442 else => {},445 else => {},
443 }446 }
444 return "";447 return "";
445}448}
446449
450fn stripOptionalOrErrorUnionSpec(comptime fmt: []const u8) []const u8 {
451 return if (std.mem.eql(u8, fmt[1..], ANY))
452 ANY
453 else
454 fmt[1..];
455}
456
447pub fn formatType(457pub fn formatType(
448 value: anytype,458 value: anytype,
449 comptime fmt: []const u8,459 comptime fmt: []const u8,
...@@ -451,12 +461,18 @@ pub fn formatType(...@@ -451,12 +461,18 @@ pub fn formatType(
451 writer: anytype,461 writer: anytype,
452 max_depth: usize,462 max_depth: usize,
453) @TypeOf(writer).Error!void {463) @TypeOf(writer).Error!void {
454 const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY)) defaultSpec(@TypeOf(value)) else fmt;464 const T = @TypeOf(value);
465 const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY))
466 defaultSpec(@TypeOf(value))
467 else if (fmt.len != 0 and (fmt[0] == '?' or fmt[0] == '!')) switch (@typeInfo(T)) {
468 .Optional, .ErrorUnion => fmt,
469 else => stripOptionalOrErrorUnionSpec(fmt),
470 } else fmt;
471
455 if (comptime std.mem.eql(u8, actual_fmt, "*")) {472 if (comptime std.mem.eql(u8, actual_fmt, "*")) {
456 return formatAddress(value, options, writer);473 return formatAddress(value, options, writer);
457 }474 }
458475
459 const T = @TypeOf(value);
460 if (comptime std.meta.trait.hasFn("format")(T)) {476 if (comptime std.meta.trait.hasFn("format")(T)) {
461 return try value.format(actual_fmt, options, writer);477 return try value.format(actual_fmt, options, writer);
462 }478 }
...@@ -472,17 +488,23 @@ pub fn formatType(...@@ -472,17 +488,23 @@ pub fn formatType(
472 return formatBuf(if (value) "true" else "false", options, writer);488 return formatBuf(if (value) "true" else "false", options, writer);
473 },489 },
474 .Optional => {490 .Optional => {
491 if (actual_fmt.len == 0 or actual_fmt[0] != '?')
492 @compileError("cannot format optional without a specifier (i.e. {?} or {any})");
493 const remaining_fmt = comptime stripOptionalOrErrorUnionSpec(actual_fmt);
475 if (value) |payload| {494 if (value) |payload| {
476 return formatType(payload, actual_fmt, options, writer, max_depth);495 return formatType(payload, remaining_fmt, options, writer, max_depth);
477 } else {496 } else {
478 return formatBuf("null", options, writer);497 return formatBuf("null", options, writer);
479 }498 }
480 },499 },
481 .ErrorUnion => {500 .ErrorUnion => {
501 if (actual_fmt.len == 0 or actual_fmt[0] != '!')
502 @compileError("cannot format error union without a specifier (i.e. {!} or {any})");
503 const remaining_fmt = comptime stripOptionalOrErrorUnionSpec(actual_fmt);
482 if (value) |payload| {504 if (value) |payload| {
483 return formatType(payload, actual_fmt, options, writer, max_depth);505 return formatType(payload, remaining_fmt, options, writer, max_depth);
484 } else |err| {506 } else |err| {
485 return formatType(err, actual_fmt, options, writer, max_depth);507 return formatType(err, remaining_fmt, options, writer, max_depth);
486 }508 }
487 },509 },
488 .ErrorSet => {510 .ErrorSet => {
...@@ -1977,11 +1999,11 @@ test "escaped braces" {...@@ -1977,11 +1999,11 @@ test "escaped braces" {
1977test "optional" {1999test "optional" {
1978 {2000 {
1979 const value: ?i32 = 1234;2001 const value: ?i32 = 1234;
1980 try expectFmt("optional: 1234\n", "optional: {}\n", .{value});2002 try expectFmt("optional: 1234\n", "optional: {?}\n", .{value});
1981 }2003 }
1982 {2004 {
1983 const value: ?i32 = null;2005 const value: ?i32 = null;
1984 try expectFmt("optional: null\n", "optional: {}\n", .{value});2006 try expectFmt("optional: null\n", "optional: {?}\n", .{value});
1985 }2007 }
1986 {2008 {
1987 const value = @intToPtr(?*i32, 0xf000d000);2009 const value = @intToPtr(?*i32, 0xf000d000);
...@@ -1992,11 +2014,11 @@ test "optional" {...@@ -1992,11 +2014,11 @@ test "optional" {
1992test "error" {2014test "error" {
1993 {2015 {
1994 const value: anyerror!i32 = 1234;2016 const value: anyerror!i32 = 1234;
1995 try expectFmt("error union: 1234\n", "error union: {}\n", .{value});2017 try expectFmt("error union: 1234\n", "error union: {!}\n", .{value});
1996 }2018 }
1997 {2019 {
1998 const value: anyerror!i32 = error.InvalidChar;2020 const value: anyerror!i32 = error.InvalidChar;
1999 try expectFmt("error union: error.InvalidChar\n", "error union: {}\n", .{value});2021 try expectFmt("error union: error.InvalidChar\n", "error union: {!}\n", .{value});
2000 }2022 }
2001}2023}
20022024
lib/std/x/os/net.zig+1-1
...@@ -544,7 +544,7 @@ test "ip: convert to and from ipv6" {...@@ -544,7 +544,7 @@ test "ip: convert to and from ipv6" {
544 try testing.expect(IPv4.localhost.mapToIPv6().mapsToIPv4());544 try testing.expect(IPv4.localhost.mapToIPv6().mapsToIPv4());
545545
546 try testing.expect(IPv4.localhost.toIPv6().toIPv4() == null);546 try testing.expect(IPv4.localhost.toIPv6().toIPv4() == null);
547 try testing.expectFmt("127.0.0.1", "{}", .{IPv4.localhost.mapToIPv6().toIPv4()});547 try testing.expectFmt("127.0.0.1", "{?}", .{IPv4.localhost.mapToIPv6().toIPv4()});
548}548}
549549
550test "ipv4: parse & format" {550test "ipv4: parse & format" {
src/Cache.zig+1-1
...@@ -747,7 +747,7 @@ pub const Manifest = struct {...@@ -747,7 +747,7 @@ pub const Manifest = struct {
747 file.stat.inode,747 file.stat.inode,
748 file.stat.mtime,748 file.stat.mtime,
749 &encoded_digest,749 &encoded_digest,
750 file.path,750 file.path.?,
751 });751 });
752 }752 }
753753
src/Compilation.zig+1-1
...@@ -1465,7 +1465,7 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {...@@ -1465,7 +1465,7 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {
1465 .handle = artifact_dir,1465 .handle = artifact_dir,
1466 .path = try options.local_cache_directory.join(arena, &[_][]const u8{artifact_sub_dir}),1466 .path = try options.local_cache_directory.join(arena, &[_][]const u8{artifact_sub_dir}),
1467 };1467 };
1468 log.debug("zig_cache_artifact_directory='{s}' use_stage1={}", .{1468 log.debug("zig_cache_artifact_directory='{?s}' use_stage1={}", .{
1469 zig_cache_artifact_directory.path, use_stage1,1469 zig_cache_artifact_directory.path, use_stage1,
1470 });1470 });
14711471
src/link/MachO.zig+1-1
...@@ -363,7 +363,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO {...@@ -363,7 +363,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO {
363363
364 // Create dSYM bundle.364 // Create dSYM bundle.
365 const dir = options.module.?.zig_cache_artifact_directory;365 const dir = options.module.?.zig_cache_artifact_directory;
366 log.debug("creating {s}.dSYM bundle in {s}", .{ emit.sub_path, dir.path });366 log.debug("creating {s}.dSYM bundle in {?s}", .{ emit.sub_path, dir.path });
367367
368 const d_sym_path = try fmt.allocPrint(368 const d_sym_path = try fmt.allocPrint(
369 allocator,369 allocator,
src/link/Wasm.zig+1-1
...@@ -1629,7 +1629,7 @@ fn setupMemory(self: *Wasm) !void {...@@ -1629,7 +1629,7 @@ fn setupMemory(self: *Wasm) !void {
1629 return error.MemoryTooBig;1629 return error.MemoryTooBig;
1630 }1630 }
1631 self.memories.limits.max = @intCast(u32, max_memory / page_size);1631 self.memories.limits.max = @intCast(u32, max_memory / page_size);
1632 log.debug("Maximum memory pages: {d}", .{self.memories.limits.max});1632 log.debug("Maximum memory pages: {?d}", .{self.memories.limits.max});
1633 }1633 }
1634}1634}
16351635
src/link/Wasm/Object.zig+1-1
...@@ -548,7 +548,7 @@ fn Parser(comptime ReaderType: type) type {...@@ -548,7 +548,7 @@ fn Parser(comptime ReaderType: type) type {
548 .index = try leb.readULEB128(u32, reader),548 .index = try leb.readULEB128(u32, reader),
549 .addend = if (rel_type_enum.addendIsPresent()) try leb.readULEB128(u32, reader) else null,549 .addend = if (rel_type_enum.addendIsPresent()) try leb.readULEB128(u32, reader) else null,
550 };550 };
551 log.debug("Found relocation: type({s}) offset({d}) index({d}) addend({d})", .{551 log.debug("Found relocation: type({s}) offset({d}) index({d}) addend({?d})", .{
552 @tagName(relocation.relocation_type),552 @tagName(relocation.relocation_type),
553 relocation.offset,553 relocation.offset,
554 relocation.index,554 relocation.index,
src/main.zig+5-3
...@@ -3168,7 +3168,7 @@ fn parseCrossTargetOrReportFatalError(...@@ -3168,7 +3168,7 @@ fn parseCrossTargetOrReportFatalError(
3168 @tagName(diags.arch.?), help_text.items,3168 @tagName(diags.arch.?), help_text.items,
3169 });3169 });
3170 }3170 }
3171 fatal("Unknown CPU feature: '{s}'", .{diags.unknown_feature_name});3171 fatal("Unknown CPU feature: '{s}'", .{diags.unknown_feature_name.?});
3172 },3172 },
3173 else => |e| return e,3173 else => |e| return e,
3174 };3174 };
...@@ -3496,7 +3496,8 @@ fn cmdTranslateC(comp: *Compilation, arena: Allocator, enable_cache: bool, stage...@@ -3496,7 +3496,8 @@ fn cmdTranslateC(comp: *Compilation, arena: Allocator, enable_cache: bool, stage
3496 } else {3496 } else {
3497 const out_zig_path = try fs.path.join(arena, &[_][]const u8{ "o", &digest, translated_zig_basename });3497 const out_zig_path = try fs.path.join(arena, &[_][]const u8{ "o", &digest, translated_zig_basename });
3498 const zig_file = comp.local_cache_directory.handle.openFile(out_zig_path, .{}) catch |err| {3498 const zig_file = comp.local_cache_directory.handle.openFile(out_zig_path, .{}) catch |err| {
3499 fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ comp.local_cache_directory.path, fs.path.sep_str, out_zig_path, @errorName(err) });3499 const path = comp.local_cache_directory.path orelse ".";
3500 fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ path, fs.path.sep_str, out_zig_path, @errorName(err) });
3500 };3501 };
3501 defer zig_file.close();3502 defer zig_file.close();
3502 try io.getStdOut().writeFileAll(zig_file, .{});3503 try io.getStdOut().writeFileAll(zig_file, .{});
...@@ -3626,7 +3627,8 @@ pub fn cmdInit(...@@ -3626,7 +3627,8 @@ pub fn cmdInit(
3626 .Exe => "init-exe",3627 .Exe => "init-exe",
3627 };3628 };
3628 var template_dir = zig_lib_directory.handle.openDir(template_sub_path, .{}) catch |err| {3629 var template_dir = zig_lib_directory.handle.openDir(template_sub_path, .{}) catch |err| {
3629 fatal("unable to open zig project template directory '{s}{s}{s}': {s}", .{ zig_lib_directory.path, s, template_sub_path, @errorName(err) });3630 const path = zig_lib_directory.path orelse ".";
3631 fatal("unable to open zig project template directory '{s}{s}{s}': {s}", .{ path, s, template_sub_path, @errorName(err) });
3630 };3632 };
3631 defer template_dir.close();3633 defer template_dir.close();
36323634
src/register_manager.zig+1-1
...@@ -301,7 +301,7 @@ pub fn RegisterManager(...@@ -301,7 +301,7 @@ pub fn RegisterManager(
301 /// register.301 /// register.
302 pub fn getReg(self: *Self, reg: Register, inst: ?Air.Inst.Index) AllocateRegistersError!void {302 pub fn getReg(self: *Self, reg: Register, inst: ?Air.Inst.Index) AllocateRegistersError!void {
303 const index = indexOfRegIntoTracked(reg) orelse return;303 const index = indexOfRegIntoTracked(reg) orelse return;
304 log.debug("getReg {} for inst {}", .{ reg, inst });304 log.debug("getReg {} for inst {?}", .{ reg, inst });
305 self.markRegAllocated(reg);305 self.markRegAllocated(reg);
306306
307 if (inst) |tracked_inst|307 if (inst) |tracked_inst|
src/translate_c.zig+7-6
...@@ -2765,7 +2765,7 @@ fn transInitListExpr(...@@ -2765,7 +2765,7 @@ fn transInitListExpr(
2765 qual_type,2765 qual_type,
2766 ));2766 ));
2767 } else {2767 } else {
2768 const type_name = c.str(qual_type.getTypeClassName());2768 const type_name = try c.str(qual_type.getTypeClassName());
2769 return fail(c, error.UnsupportedType, source_loc, "unsupported initlist type: '{s}'", .{type_name});2769 return fail(c, error.UnsupportedType, source_loc, "unsupported initlist type: '{s}'", .{type_name});
2770 }2770 }
2771}2771}
...@@ -4812,11 +4812,11 @@ fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clan...@@ -4812,11 +4812,11 @@ fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clan
4812 });4812 });
4813 },4813 },
4814 .BitInt, .ExtVector => {4814 .BitInt, .ExtVector => {
4815 const type_name = c.str(ty.getTypeClassName());4815 const type_name = try c.str(ty.getTypeClassName());
4816 return fail(c, error.UnsupportedType, source_loc, "TODO implement translation of type: '{s}'", .{type_name});4816 return fail(c, error.UnsupportedType, source_loc, "TODO implement translation of type: '{s}'", .{type_name});
4817 },4817 },
4818 else => {4818 else => {
4819 const type_name = c.str(ty.getTypeClassName());4819 const type_name = try c.str(ty.getTypeClassName());
4820 return fail(c, error.UnsupportedType, source_loc, "unsupported type: '{s}'", .{type_name});4820 return fail(c, error.UnsupportedType, source_loc, "unsupported type: '{s}'", .{type_name});
4821 },4821 },
4822 }4822 }
...@@ -5052,8 +5052,8 @@ fn finishTransFnProto(...@@ -5052,8 +5052,8 @@ fn finishTransFnProto(
5052}5052}
50535053
5054fn warn(c: *Context, scope: *Scope, loc: clang.SourceLocation, comptime format: []const u8, args: anytype) !void {5054fn warn(c: *Context, scope: *Scope, loc: clang.SourceLocation, comptime format: []const u8, args: anytype) !void {
5055 const args_prefix = .{c.locStr(loc)};5055 const str = try c.locStr(loc);
5056 const value = try std.fmt.allocPrint(c.arena, "// {s}: warning: " ++ format, args_prefix ++ args);5056 const value = try std.fmt.allocPrint(c.arena, "// {s}: warning: " ++ format, .{str} ++ args);
5057 try scope.appendNode(try Tag.warning.create(c.arena, value));5057 try scope.appendNode(try Tag.warning.create(c.arena, value));
5058}5058}
50595059
...@@ -5073,7 +5073,8 @@ pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, compti...@@ -5073,7 +5073,8 @@ pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, compti
5073 // pub const name = @compileError(msg);5073 // pub const name = @compileError(msg);
5074 const fail_msg = try std.fmt.allocPrint(c.arena, format, args);5074 const fail_msg = try std.fmt.allocPrint(c.arena, format, args);
5075 try addTopLevelDecl(c, name, try Tag.fail_decl.create(c.arena, .{ .actual = name, .mangled = fail_msg }));5075 try addTopLevelDecl(c, name, try Tag.fail_decl.create(c.arena, .{ .actual = name, .mangled = fail_msg }));
5076 const location_comment = try std.fmt.allocPrint(c.arena, "// {s}", .{c.locStr(loc)});5076 const str = try c.locStr(loc);
5077 const location_comment = try std.fmt.allocPrint(c.arena, "// {s}", .{str});
5077 try c.global_scope.nodes.append(try Tag.warning.create(c.arena, location_comment));5078 try c.global_scope.nodes.append(try Tag.warning.create(c.arena, location_comment));
5078}5079}
50795080