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 {
574574 var optional_value: ?[]const u8 = null;
575575 assert(optional_value == null);
576576
577 print("\noptional 1\ntype: {s}\nvalue: {?s}\n", .{
577 print("\noptional 1\ntype: {s}\nvalue: {s}\n", .{
578578 @typeName(@TypeOf(optional_value)),
579579 optional_value,
580580 });
......@@ -582,7 +582,7 @@ pub fn main() void {
582582 optional_value = "hi";
583583 assert(optional_value != null);
584584
585 print("\noptional 2\ntype: {s}\nvalue: {?s}\n", .{
585 print("\noptional 2\ntype: {s}\nvalue: {s}\n", .{
586586 @typeName(@TypeOf(optional_value)),
587587 optional_value,
588588 });
......@@ -590,14 +590,14 @@ pub fn main() void {
590590 // error union
591591 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", .{
594594 @typeName(@TypeOf(number_or_error)),
595595 number_or_error,
596596 });
597597
598598 number_or_error = 1234;
599599
600 print("\nerror union 2\ntype: {s}\nvalue: {!}\n", .{
600 print("\nerror union 2\ntype: {s}\nvalue: {}\n", .{
601601 @typeName(@TypeOf(number_or_error)),
602602 number_or_error,
603603 });
lib/std/build.zig+2-2
......@@ -750,7 +750,7 @@ pub const Builder = struct {
750750 \\Available CPU features for architecture '{s}':
751751 \\
752752 , .{
753 diags.unknown_feature_name.?,
753 diags.unknown_feature_name,
754754 @tagName(diags.arch.?),
755755 });
756756 for (diags.arch.?.allFeaturesList()) |feature| {
......@@ -764,7 +764,7 @@ pub const Builder = struct {
764764 \\Unknown OS: '{s}'
765765 \\Available operating systems:
766766 \\
767 , .{diags.os_name.?});
767 , .{diags.os_name});
768768 inline for (std.meta.fields(std.Target.Os.Tag)) |field| {
769769 log.err(" {s}", .{field.name});
770770 }
lib/std/crypto/phc_encoding.zig+1-1
......@@ -216,7 +216,7 @@ fn serializeTo(params: anytype, out: anytype) !void {
216216
217217 var has_params = false;
218218 inline for (comptime meta.fields(HashResult)) |p| {
219 if (comptime !(mem.eql(u8, p.name, "alg_id") or
219 if (!(mem.eql(u8, p.name, "alg_id") or
220220 mem.eql(u8, p.name, "alg_version") or
221221 mem.eql(u8, p.name, "hash") or
222222 mem.eql(u8, p.name, "salt")))
lib/std/fmt.zig+11-33
......@@ -60,10 +60,8 @@ pub const FormatOptions = struct {
6060/// - `o`: output integer value in octal notation
6161/// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max.
6262/// - `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.
6563/// - `*`: 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
6765///
6866/// If a formatted user type contains a function of the type
6967/// ```
......@@ -440,20 +438,12 @@ fn defaultSpec(comptime T: type) [:0]const u8 {
440438 .Many, .C => return "*",
441439 .Slice => return ANY,
442440 },
443 .Optional => |info| return "?" ++ defaultSpec(info.child),
444 .ErrorUnion => |info| return "!" ++ defaultSpec(info.payload),
441 .Optional => |info| return defaultSpec(info.child),
445442 else => {},
446443 }
447444 return "";
448445}
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
457447pub fn formatType(
458448 value: anytype,
459449 comptime fmt: []const u8,
......@@ -461,18 +451,12 @@ pub fn formatType(
461451 writer: anytype,
462452 max_depth: usize,
463453) @TypeOf(writer).Error!void {
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
454 const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY)) defaultSpec(@TypeOf(value)) else fmt;
472455 if (comptime std.mem.eql(u8, actual_fmt, "*")) {
473456 return formatAddress(value, options, writer);
474457 }
475458
459 const T = @TypeOf(value);
476460 if (comptime std.meta.trait.hasFn("format")(T)) {
477461 return try value.format(actual_fmt, options, writer);
478462 }
......@@ -488,23 +472,17 @@ pub fn formatType(
488472 return formatBuf(if (value) "true" else "false", options, writer);
489473 },
490474 .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);
494475 if (value) |payload| {
495 return formatType(payload, remaining_fmt, options, writer, max_depth);
476 return formatType(payload, actual_fmt, options, writer, max_depth);
496477 } else {
497478 return formatBuf("null", options, writer);
498479 }
499480 },
500481 .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);
504482 if (value) |payload| {
505 return formatType(payload, remaining_fmt, options, writer, max_depth);
483 return formatType(payload, actual_fmt, options, writer, max_depth);
506484 } else |err| {
507 return formatType(err, remaining_fmt, options, writer, max_depth);
485 return formatType(err, actual_fmt, options, writer, max_depth);
508486 }
509487 },
510488 .ErrorSet => {
......@@ -1999,11 +1977,11 @@ test "escaped braces" {
19991977test "optional" {
20001978 {
20011979 const value: ?i32 = 1234;
2002 try expectFmt("optional: 1234\n", "optional: {?}\n", .{value});
1980 try expectFmt("optional: 1234\n", "optional: {}\n", .{value});
20031981 }
20041982 {
20051983 const value: ?i32 = null;
2006 try expectFmt("optional: null\n", "optional: {?}\n", .{value});
1984 try expectFmt("optional: null\n", "optional: {}\n", .{value});
20071985 }
20081986 {
20091987 const value = @intToPtr(?*i32, 0xf000d000);
......@@ -2014,11 +1992,11 @@ test "optional" {
20141992test "error" {
20151993 {
20161994 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});
20181996 }
20191997 {
20201998 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});
20222000 }
20232001}
20242002
lib/std/x/os/net.zig+1-1
......@@ -544,7 +544,7 @@ test "ip: convert to and from ipv6" {
544544 try testing.expect(IPv4.localhost.mapToIPv6().mapsToIPv4());
545545
546546 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()});
548548}
549549
550550test "ipv4: parse & format" {
src/Cache.zig+1-1
......@@ -747,7 +747,7 @@ pub const Manifest = struct {
747747 file.stat.inode,
748748 file.stat.mtime,
749749 &encoded_digest,
750 file.path.?,
750 file.path,
751751 });
752752 }
753753
src/Compilation.zig+1-1
......@@ -1465,7 +1465,7 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {
14651465 .handle = artifact_dir,
14661466 .path = try options.local_cache_directory.join(arena, &[_][]const u8{artifact_sub_dir}),
14671467 };
1468 log.debug("zig_cache_artifact_directory='{?s}' use_stage1={}", .{
1468 log.debug("zig_cache_artifact_directory='{s}' use_stage1={}", .{
14691469 zig_cache_artifact_directory.path, use_stage1,
14701470 });
14711471
src/link/MachO.zig+1-1
......@@ -363,7 +363,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO {
363363
364364 // Create dSYM bundle.
365365 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
368368 const d_sym_path = try fmt.allocPrint(
369369 allocator,
src/link/Wasm.zig+1-1
......@@ -1629,7 +1629,7 @@ fn setupMemory(self: *Wasm) !void {
16291629 return error.MemoryTooBig;
16301630 }
16311631 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});
16331633 }
16341634}
16351635
src/link/Wasm/Object.zig+1-1
......@@ -548,7 +548,7 @@ fn Parser(comptime ReaderType: type) type {
548548 .index = try leb.readULEB128(u32, reader),
549549 .addend = if (rel_type_enum.addendIsPresent()) try leb.readULEB128(u32, reader) else null,
550550 };
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})", .{
552552 @tagName(relocation.relocation_type),
553553 relocation.offset,
554554 relocation.index,
src/main.zig+3-5
......@@ -3168,7 +3168,7 @@ fn parseCrossTargetOrReportFatalError(
31683168 @tagName(diags.arch.?), help_text.items,
31693169 });
31703170 }
3171 fatal("Unknown CPU feature: '{s}'", .{diags.unknown_feature_name.?});
3171 fatal("Unknown CPU feature: '{s}'", .{diags.unknown_feature_name});
31723172 },
31733173 else => |e| return e,
31743174 };
......@@ -3496,8 +3496,7 @@ fn cmdTranslateC(comp: *Compilation, arena: Allocator, enable_cache: bool, stage
34963496 } else {
34973497 const out_zig_path = try fs.path.join(arena, &[_][]const u8{ "o", &digest, translated_zig_basename });
34983498 const zig_file = comp.local_cache_directory.handle.openFile(out_zig_path, .{}) catch |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) });
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) });
35013500 };
35023501 defer zig_file.close();
35033502 try io.getStdOut().writeFileAll(zig_file, .{});
......@@ -3627,8 +3626,7 @@ pub fn cmdInit(
36273626 .Exe => "init-exe",
36283627 };
36293628 var template_dir = zig_lib_directory.handle.openDir(template_sub_path, .{}) catch |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) });
3629 fatal("unable to open zig project template directory '{s}{s}{s}': {s}", .{ zig_lib_directory.path, s, template_sub_path, @errorName(err) });
36323630 };
36333631 defer template_dir.close();
36343632
src/register_manager.zig+1-1
......@@ -301,7 +301,7 @@ pub fn RegisterManager(
301301 /// register.
302302 pub fn getReg(self: *Self, reg: Register, inst: ?Air.Inst.Index) AllocateRegistersError!void {
303303 const index = indexOfRegIntoTracked(reg) orelse return;
304 log.debug("getReg {} for inst {?}", .{ reg, inst });
304 log.debug("getReg {} for inst {}", .{ reg, inst });
305305 self.markRegAllocated(reg);
306306
307307 if (inst) |tracked_inst|
src/translate_c.zig+6-7
......@@ -2765,7 +2765,7 @@ fn transInitListExpr(
27652765 qual_type,
27662766 ));
27672767 } else {
2768 const type_name = try c.str(qual_type.getTypeClassName());
2768 const type_name = c.str(qual_type.getTypeClassName());
27692769 return fail(c, error.UnsupportedType, source_loc, "unsupported initlist type: '{s}'", .{type_name});
27702770 }
27712771}
......@@ -4812,11 +4812,11 @@ fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clan
48124812 });
48134813 },
48144814 .BitInt, .ExtVector => {
4815 const type_name = try c.str(ty.getTypeClassName());
4815 const type_name = c.str(ty.getTypeClassName());
48164816 return fail(c, error.UnsupportedType, source_loc, "TODO implement translation of type: '{s}'", .{type_name});
48174817 },
48184818 else => {
4819 const type_name = try c.str(ty.getTypeClassName());
4819 const type_name = c.str(ty.getTypeClassName());
48204820 return fail(c, error.UnsupportedType, source_loc, "unsupported type: '{s}'", .{type_name});
48214821 },
48224822 }
......@@ -5052,8 +5052,8 @@ fn finishTransFnProto(
50525052}
50535053
50545054fn warn(c: *Context, scope: *Scope, loc: clang.SourceLocation, comptime format: []const u8, args: anytype) !void {
5055 const str = try c.locStr(loc);
5056 const value = try std.fmt.allocPrint(c.arena, "// {s}: warning: " ++ format, .{str} ++ args);
5055 const args_prefix = .{c.locStr(loc)};
5056 const value = try std.fmt.allocPrint(c.arena, "// {s}: warning: " ++ format, args_prefix ++ args);
50575057 try scope.appendNode(try Tag.warning.create(c.arena, value));
50585058}
50595059
......@@ -5073,8 +5073,7 @@ pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, compti
50735073 // pub const name = @compileError(msg);
50745074 const fail_msg = try std.fmt.allocPrint(c.arena, format, args);
50755075 try addTopLevelDecl(c, name, try Tag.fail_decl.create(c.arena, .{ .actual = name, .mangled = fail_msg }));
5076 const str = try c.locStr(loc);
5077 const location_comment = try std.fmt.allocPrint(c.arena, "// {s}", .{str});
5076 const location_comment = try std.fmt.allocPrint(c.arena, "// {s}", .{c.locStr(loc)});
50785077 try c.global_scope.nodes.append(try Tag.warning.create(c.arena, location_comment));
50795078}
50805079