authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-07-24 11:50:10-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-07-24 11:50:10-07:00
log934573fc5db1307caf559cc485e0e557a7c655e2
tree2e62419f306e5f77c7787a88dbc2c56c46f0f14e
parenta08b0fa706f79a506b219d59a0b58a6d5761dcd7

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

This reverts commit 7cbd586ace46a8e8cebab660ebca3cfc049305d9. This is causing a fail to build from source: ``` ./lib/std/fmt.zig:492:17: error: cannot format optional without a specifier (i.e. {?} or {any}) @compileError("cannot format optional without a specifier (i.e. {?} or {any})"); ^ ./src/link/MachO/Atom.zig:544:26: note: called from here log.debug(" RELA({s}) @ {x} => %{d} in object({d})", .{ ^ ``` I looked at the code to fix it but none of those args are optionals.

13 files changed, 34 insertions(+), 59 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 (comptime !(mem.eql(u8, p.name, "alg_id") or219 if (!(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+11-33
...@@ -60,10 +60,8 @@ pub const FormatOptions = struct {...@@ -60,10 +60,8 @@ 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.
65/// - `*`: output the address of the value instead of the value itself.63/// - `*`: output the address of the value instead of the value itself.
66/// - `any`: output a value of any type using its default format.64/// - `any`: output a value of any type using its default format
67///65///
68/// If a formatted user type contains a function of the type66/// If a formatted user type contains a function of the type
69/// ```67/// ```
...@@ -440,20 +438,12 @@ fn defaultSpec(comptime T: type) [:0]const u8 {...@@ -440,20 +438,12 @@ fn defaultSpec(comptime T: type) [:0]const u8 {
440 .Many, .C => return "*",438 .Many, .C => return "*",
441 .Slice => return ANY,439 .Slice => return ANY,
442 },440 },
443 .Optional => |info| return "?" ++ defaultSpec(info.child),441 .Optional => |info| return defaultSpec(info.child),
444 .ErrorUnion => |info| return "!" ++ defaultSpec(info.payload),
445 else => {},442 else => {},
446 }443 }
447 return "";444 return "";
448}445}
449446
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
457pub fn formatType(447pub fn formatType(
458 value: anytype,448 value: anytype,
459 comptime fmt: []const u8,449 comptime fmt: []const u8,
...@@ -461,18 +451,12 @@ pub fn formatType(...@@ -461,18 +451,12 @@ pub fn formatType(
461 writer: anytype,451 writer: anytype,
462 max_depth: usize,452 max_depth: usize,
463) @TypeOf(writer).Error!void {453) @TypeOf(writer).Error!void {
464 const T = @TypeOf(value);454 const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY)) defaultSpec(@TypeOf(value)) else fmt;
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
472 if (comptime std.mem.eql(u8, actual_fmt, "*")) {455 if (comptime std.mem.eql(u8, actual_fmt, "*")) {
473 return formatAddress(value, options, writer);456 return formatAddress(value, options, writer);
474 }457 }
475458
459 const T = @TypeOf(value);
476 if (comptime std.meta.trait.hasFn("format")(T)) {460 if (comptime std.meta.trait.hasFn("format")(T)) {
477 return try value.format(actual_fmt, options, writer);461 return try value.format(actual_fmt, options, writer);
478 }462 }
...@@ -488,23 +472,17 @@ pub fn formatType(...@@ -488,23 +472,17 @@ pub fn formatType(
488 return formatBuf(if (value) "true" else "false", options, writer);472 return formatBuf(if (value) "true" else "false", options, writer);
489 },473 },
490 .Optional => {474 .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);
494 if (value) |payload| {475 if (value) |payload| {
495 return formatType(payload, remaining_fmt, options, writer, max_depth);476 return formatType(payload, actual_fmt, options, writer, max_depth);
496 } else {477 } else {
497 return formatBuf("null", options, writer);478 return formatBuf("null", options, writer);
498 }479 }
499 },480 },
500 .ErrorUnion => {481 .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);
504 if (value) |payload| {482 if (value) |payload| {
505 return formatType(payload, remaining_fmt, options, writer, max_depth);483 return formatType(payload, actual_fmt, options, writer, max_depth);
506 } else |err| {484 } else |err| {
507 return formatType(err, remaining_fmt, options, writer, max_depth);485 return formatType(err, actual_fmt, options, writer, max_depth);
508 }486 }
509 },487 },
510 .ErrorSet => {488 .ErrorSet => {
...@@ -1999,11 +1977,11 @@ test "escaped braces" {...@@ -1999,11 +1977,11 @@ test "escaped braces" {
1999test "optional" {1977test "optional" {
2000 {1978 {
2001 const value: ?i32 = 1234;1979 const value: ?i32 = 1234;
2002 try expectFmt("optional: 1234\n", "optional: {?}\n", .{value});1980 try expectFmt("optional: 1234\n", "optional: {}\n", .{value});
2003 }1981 }
2004 {1982 {
2005 const value: ?i32 = null;1983 const value: ?i32 = null;
2006 try expectFmt("optional: null\n", "optional: {?}\n", .{value});1984 try expectFmt("optional: null\n", "optional: {}\n", .{value});
2007 }1985 }
2008 {1986 {
2009 const value = @intToPtr(?*i32, 0xf000d000);1987 const value = @intToPtr(?*i32, 0xf000d000);
...@@ -2014,11 +1992,11 @@ test "optional" {...@@ -2014,11 +1992,11 @@ test "optional" {
2014test "error" {1992test "error" {
2015 {1993 {
2016 const value: anyerror!i32 = 1234;1994 const value: anyerror!i32 = 1234;
2017 try expectFmt("error union: 1234\n", "error union: {!}\n", .{value});1995 try expectFmt("error union: 1234\n", "error union: {}\n", .{value});
2018 }1996 }
2019 {1997 {
2020 const value: anyerror!i32 = error.InvalidChar;1998 const value: anyerror!i32 = error.InvalidChar;
2021 try expectFmt("error union: error.InvalidChar\n", "error union: {!}\n", .{value});1999 try expectFmt("error union: error.InvalidChar\n", "error union: {}\n", .{value});
2022 }2000 }
2023}2001}
20242002
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+3-5
...@@ -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,8 +3496,7 @@ fn cmdTranslateC(comp: *Compilation, arena: Allocator, enable_cache: bool, stage...@@ -3496,8 +3496,7 @@ 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 const path = comp.local_cache_directory.path orelse ".";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) });
3500 fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ path, fs.path.sep_str, out_zig_path, @errorName(err) });
3501 };3500 };
3502 defer zig_file.close();3501 defer zig_file.close();
3503 try io.getStdOut().writeFileAll(zig_file, .{});3502 try io.getStdOut().writeFileAll(zig_file, .{});
...@@ -3627,8 +3626,7 @@ pub fn cmdInit(...@@ -3627,8 +3626,7 @@ pub fn cmdInit(
3627 .Exe => "init-exe",3626 .Exe => "init-exe",
3628 };3627 };
3629 var template_dir = zig_lib_directory.handle.openDir(template_sub_path, .{}) catch |err| {3628 var template_dir = zig_lib_directory.handle.openDir(template_sub_path, .{}) catch |err| {
3630 const path = zig_lib_directory.path orelse ".";3629 fatal("unable to open zig project template directory '{s}{s}{s}': {s}", .{ zig_lib_directory.path, s, template_sub_path, @errorName(err) });
3631 fatal("unable to open zig project template directory '{s}{s}{s}': {s}", .{ path, s, template_sub_path, @errorName(err) });
3632 };3630 };
3633 defer template_dir.close();3631 defer template_dir.close();
36343632
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+6-7
...@@ -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 = try c.str(qual_type.getTypeClassName());2768 const type_name = 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 = try c.str(ty.getTypeClassName());4815 const type_name = 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 = try c.str(ty.getTypeClassName());4819 const type_name = 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 str = try c.locStr(loc);5055 const args_prefix = .{c.locStr(loc)};
5056 const value = try std.fmt.allocPrint(c.arena, "// {s}: warning: " ++ format, .{str} ++ args);5056 const value = try std.fmt.allocPrint(c.arena, "// {s}: warning: " ++ format, args_prefix ++ 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,8 +5073,7 @@ pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, compti...@@ -5073,8 +5073,7 @@ 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 str = try c.locStr(loc);5076 const location_comment = try std.fmt.allocPrint(c.arena, "// {s}", .{c.locStr(loc)});
5077 const location_comment = try std.fmt.allocPrint(c.arena, "// {s}", .{str});
5078 try c.global_scope.nodes.append(try Tag.warning.create(c.arena, location_comment));5077 try c.global_scope.nodes.append(try Tag.warning.create(c.arena, location_comment));
5079}5078}
50805079