authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-03 18:50:16-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-07 22:43:52-07:00
log9c8aef55b4e287197b552ef18e7dd008e3a527bc
tree0bbe77c197c55f57a22ab7e2657ce75fac24a80d
parent30c2921eb87c3157d52edd7d8ee874209a0f7538

std.fmt.format: use {t} for tag name rather than {s}

prevents footgun when formatted type changes from string to enum

12 files changed, 39 insertions(+), 29 deletions(-)

lib/std/fmt.zig+3
......@@ -67,6 +67,9 @@ pub const Options = struct {
6767/// - `s`:
6868/// - for pointer-to-many and C pointers of u8, print as a C-string using zero-termination
6969/// - for slices of u8, print the entire slice as a string without zero-termination
70/// - `t`:
71/// - for enums and tagged unions: prints the tag name
72/// - for error sets: prints the error name
7073/// - `b64`: output string as standard base64
7174/// - `e`: output floating point value in scientific notation
7275/// - `d`: output numeric value in decimal notation
lib/std/io/Writer.zig+3-3
......@@ -851,12 +851,12 @@ pub fn printValue(
851851 }
852852 },
853853 .error_set => {
854 if (fmt.len == 1 and fmt[0] == 's') return w.writeAll(@errorName(value));
854 if (fmt.len == 1 and fmt[0] == 't') return w.writeAll(@errorName(value));
855855 if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
856856 try printErrorSet(w, value);
857857 },
858858 .@"enum" => {
859 if (fmt.len == 1 and fmt[0] == 's') {
859 if (fmt.len == 1 and fmt[0] == 't') {
860860 try w.writeAll(@tagName(value));
861861 return;
862862 }
......@@ -881,7 +881,7 @@ pub fn printValue(
881881 return;
882882 },
883883 .@"union" => |info| {
884 if (fmt.len == 1 and fmt[0] == 's') {
884 if (fmt.len == 1 and fmt[0] == 't') {
885885 try w.writeAll(@tagName(value));
886886 return;
887887 }
lib/std/zig/llvm/Builder.zig+5-5
......@@ -1265,7 +1265,7 @@ pub const Attribute = union(Kind) {
12651265 try w.writeByte(')');
12661266 },
12671267 .alignstack => |alignment| {
1268 try w.print(" {s}", .{attribute});
1268 try w.print(" {t}", .{attribute});
12691269 const alignment_bytes = alignment.toByteUnits() orelse return;
12701270 if (data.flags.pound) {
12711271 try w.print("={d}", .{alignment_bytes});
......@@ -1274,7 +1274,7 @@ pub const Attribute = union(Kind) {
12741274 }
12751275 },
12761276 .allockind => |allockind| {
1277 try w.print(" {s}(\"", .{@tagName(attribute)});
1277 try w.print(" {t}(\"", .{attribute});
12781278 var any = false;
12791279 inline for (@typeInfo(AllocKind).@"struct".fields) |field| {
12801280 if (comptime std.mem.eql(u8, field.name, "_")) continue;
......@@ -1289,13 +1289,13 @@ pub const Attribute = union(Kind) {
12891289 try w.writeAll("\")");
12901290 },
12911291 .allocsize => |allocsize| {
1292 try w.print(" {s}({d}", .{ @tagName(attribute), allocsize.elem_size });
1292 try w.print(" {t}({d}", .{ attribute, allocsize.elem_size });
12931293 if (allocsize.num_elems != AllocSize.none)
12941294 try w.print(",{d}", .{allocsize.num_elems});
12951295 try w.writeByte(')');
12961296 },
12971297 .memory => |memory| {
1298 try w.print(" {s}(", .{@tagName(attribute)});
1298 try w.print(" {t}(", .{attribute});
12991299 var any = memory.other != .none or
13001300 (memory.argmem == .none and memory.inaccessiblemem == .none);
13011301 if (any) try w.writeAll(@tagName(memory.other));
......@@ -8445,7 +8445,7 @@ pub const Metadata = enum(u32) {
84458445 }
84468446 fmt_str = fmt_str ++ "(";
84478447 inline for (fields[2..], names) |*field, name| {
8448 fmt_str = fmt_str ++ "{[" ++ name ++ "]fS}";
8448 fmt_str = fmt_str ++ "{[" ++ name ++ "]f}";
84498449 field.* = .{
84508450 .name = name,
84518451 .type = std.fmt.Formatter(FormatData, format),
src/InternPool.zig+1-1
......@@ -11406,7 +11406,7 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
1140611406 var it = instances.iterator();
1140711407 while (it.next()) |entry| {
1140811408 const generic_fn_owner_nav = ip.getNav(ip.funcDeclInfo(entry.key_ptr.*).owner_nav);
11409 try stderr_bw.print("{f} ({f}): \n", .{ generic_fn_owner_nav.name.fmt(ip), entry.value_ptr.items.len });
11409 try stderr_bw.print("{f} ({d}): \n", .{ generic_fn_owner_nav.name.fmt(ip), entry.value_ptr.items.len });
1141011410 for (entry.value_ptr.items) |index| {
1141111411 const unwrapped_index = index.unwrap(ip);
1141211412 const func = ip.extraFuncInstance(unwrapped_index.tid, unwrapped_index.getExtra(ip), unwrapped_index.getData(ip));
src/Sema.zig+13-6
......@@ -20465,7 +20465,7 @@ fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2046520465 const is_vector = operand_ty.zigTypeTag(zcu) == .vector;
2046620466 const operand_scalar_ty = operand_ty.scalarType(zcu);
2046720467 if (operand_scalar_ty.toIntern() != .bool_type) {
20468 return sema.fail(block, src, "expected 'bool', found '{s}'", .{operand_scalar_ty.zigTypeTag(zcu)});
20468 return sema.fail(block, src, "expected 'bool', found '{t}'", .{operand_scalar_ty.zigTypeTag(zcu)});
2046920469 }
2047020470 const len = if (is_vector) operand_ty.vectorLen(zcu) else undefined;
2047120471 const dest_ty: Type = if (is_vector) try pt.vectorType(.{ .child = .u1_type, .len = len }) else .u1;
......@@ -23576,7 +23576,7 @@ fn checkNumericType(
2357623576 .comptime_float, .float, .comptime_int, .int => {},
2357723577 .vector => switch (ty.childType(zcu).zigTypeTag(zcu)) {
2357823578 .comptime_float, .float, .comptime_int, .int => {},
23579 else => |t| return sema.fail(block, ty_src, "expected number, found '{s}'", .{t}),
23579 else => |t| return sema.fail(block, ty_src, "expected number, found '{t}'", .{t}),
2358023580 },
2358123581 else => return sema.fail(block, ty_src, "expected number, found '{f}'", .{ty.fmt(pt)}),
2358223582 }
......@@ -37176,7 +37176,14 @@ fn explainWhyValueContainsReferenceToComptimeVar(sema: *Sema, msg: *Zcu.ErrorMsg
3717637176 }
3717737177}
3717837178
37179fn notePathToComptimeAllocPtr(sema: *Sema, msg: *Zcu.ErrorMsg, src: LazySrcLoc, val: Value, intermediate_value_count: u32, start_value_name: InternPool.NullTerminatedString) Allocator.Error!union(enum) {
37179fn notePathToComptimeAllocPtr(
37180 sema: *Sema,
37181 msg: *Zcu.ErrorMsg,
37182 src: LazySrcLoc,
37183 val: Value,
37184 intermediate_value_count: u32,
37185 start_value_name: InternPool.NullTerminatedString,
37186) Allocator.Error!union(enum) {
3718037187 done,
3718137188 new_val: Value,
3718237189} {
......@@ -37187,7 +37194,7 @@ fn notePathToComptimeAllocPtr(sema: *Sema, msg: *Zcu.ErrorMsg, src: LazySrcLoc,
3718737194
3718837195 var first_path: std.ArrayListUnmanaged(u8) = .empty;
3718937196 if (intermediate_value_count == 0) {
37190 try first_path.print(arena, "{fi}", .{start_value_name.fmt(ip)});
37197 try first_path.print(arena, "{f}", .{start_value_name.fmt(ip)});
3719137198 } else {
3719237199 try first_path.print(arena, "v{d}", .{intermediate_value_count - 1});
3719337200 }
......@@ -37283,7 +37290,7 @@ fn notePathToComptimeAllocPtrInner(sema: *Sema, val: Value, path: *std.ArrayList
3728337290 const backing_enum = union_ty.unionTagTypeHypothetical(zcu);
3728437291 const field_idx = backing_enum.enumTagFieldIndex(.fromInterned(un.tag), zcu).?;
3728537292 const field_name = backing_enum.enumFieldName(field_idx, zcu);
37286 try path.print(arena, ".{fi}", .{field_name.fmt(ip)});
37293 try path.print(arena, ".{f}", .{field_name.fmt(ip)});
3728737294 return sema.notePathToComptimeAllocPtrInner(.fromInterned(un.val), path);
3728837295 },
3728937296 .aggregate => |agg| {
......@@ -37308,7 +37315,7 @@ fn notePathToComptimeAllocPtrInner(sema: *Sema, val: Value, path: *std.ArrayList
3730837315 try path.print(arena, "[{d}]", .{elem_idx});
3730937316 } else {
3731037317 const name = agg_ty.structFieldName(elem_idx, zcu).unwrap().?;
37311 try path.print(arena, ".{fi}", .{name.fmt(ip)});
37318 try path.print(arena, ".{f}", .{name.fmt(ip)});
3731237319 },
3731337320 else => unreachable,
3731437321 }
src/arch/sparc64/CodeGen.zig+1-1
......@@ -723,7 +723,7 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
723723
724724 if (std.debug.runtime_safety) {
725725 if (self.air_bookkeeping < old_air_bookkeeping + 1) {
726 std.debug.panic("in codegen.zig, handling of AIR instruction %{d} ('{s}') did not do proper bookkeeping. Look for a missing call to finishAir.", .{ inst, air_tags[@intFromEnum(inst)] });
726 std.debug.panic("in codegen.zig, handling of AIR instruction %{d} ('{t}') did not do proper bookkeeping. Look for a missing call to finishAir.", .{ inst, air_tags[@intFromEnum(inst)] });
727727 }
728728 }
729729 }
src/arch/wasm/CodeGen.zig+2-2
......@@ -2046,7 +2046,7 @@ fn genBody(cg: *CodeGen, body: []const Air.Inst.Index) InnerError!void {
20462046 try cg.genInst(inst);
20472047
20482048 if (std.debug.runtime_safety and cg.air_bookkeeping < old_bookkeeping_value + 1) {
2049 std.debug.panic("Missing call to `finishAir` in AIR instruction %{d} ('{s}')", .{
2049 std.debug.panic("Missing call to `finishAir` in AIR instruction %{d} ('{t}')", .{
20502050 inst,
20512051 cg.air.instructions.items(.tag)[@intFromEnum(inst)],
20522052 });
......@@ -3326,7 +3326,7 @@ fn emitUndefined(cg: *CodeGen, ty: Type) InnerError!WValue {
33263326 },
33273327 else => unreachable,
33283328 },
3329 else => return cg.fail("Wasm TODO: emitUndefined for type: {s}\n", .{ty.zigTypeTag(zcu)}),
3329 else => return cg.fail("Wasm TODO: emitUndefined for type: {t}\n", .{ty.zigTypeTag(zcu)}),
33303330 }
33313331}
33323332
src/codegen/c.zig+1-1
......@@ -1680,7 +1680,7 @@ pub const DeclGen = struct {
16801680 try w.writeAll("{(");
16811681 const ptr_ty = ty.slicePtrFieldType(zcu);
16821682 try dg.renderType(w, ptr_ty);
1683 return w.print("){f}, {0fx}}}", .{
1683 return w.print("){f}, {0f}}}", .{
16841684 try dg.fmtIntLiteralHex(.undef_usize, .Other),
16851685 });
16861686 },
src/link/Lld.zig+1-1
......@@ -437,7 +437,7 @@ fn coffLink(lld: *Lld, arena: Allocator) !void {
437437 try argv.append(try allocPrint(arena, "-PDBALTPATH:{s}", .{out_pdb_basename}));
438438 }
439439 if (comp.version) |version| {
440 try argv.append(try allocPrint(arena, "-VERSION:{f}.{f}", .{ version.major, version.minor }));
440 try argv.append(try allocPrint(arena, "-VERSION:{d}.{d}", .{ version.major, version.minor }));
441441 }
442442
443443 if (target_util.llvmMachineAbi(target)) |mabi| {
src/main.zig+2-2
......@@ -3336,8 +3336,8 @@ fn buildOutputType(
33363336 var hasher = file_writer.interface.hashed(Cache.Hasher.init("0123456789abcdef"), &buffer);
33373337 var stdin_reader = fs.File.stdin().readerStreaming(&.{});
33383338 _ = hasher.writer.sendFileAll(&stdin_reader, .unlimited) catch |err| switch (err) {
3339 error.WriteFailed => fatal("failed to write {s}: {s}", .{ dump_path, file_writer.err.? }),
3340 else => fatal("failed to pipe stdin to {s}: {s}", .{ dump_path, err }),
3339 error.WriteFailed => fatal("failed to write {s}: {t}", .{ dump_path, file_writer.err.? }),
3340 else => fatal("failed to pipe stdin to {s}: {t}", .{ dump_path, err }),
33413341 };
33423342 try hasher.writer.flush();
33433343
src/print_value.zig+4-4
......@@ -102,7 +102,7 @@ pub fn print(
102102 .enum_tag => |enum_tag| {
103103 const enum_type = ip.loadEnumType(val.typeOf(zcu).toIntern());
104104 if (enum_type.tagValueIndex(ip, val.toIntern())) |tag_index| {
105 return writer.print(".{fi}", .{enum_type.names.get(ip)[tag_index].fmt(ip)});
105 return writer.print(".{f}", .{enum_type.names.get(ip)[tag_index].fmt(ip)});
106106 }
107107 if (level == 0) {
108108 return writer.writeAll("@enumFromInt(...)");
......@@ -207,7 +207,7 @@ fn printAggregate(
207207 for (0..max_len) |i| {
208208 if (i != 0) try writer.writeAll(", ");
209209 const field_name = ty.structFieldName(@intCast(i), zcu).unwrap().?;
210 try writer.print(".{fi} = ", .{field_name.fmt(ip)});
210 try writer.print(".{f} = ", .{field_name.fmt(ip)});
211211 try print(try val.fieldValue(pt, i), writer, level - 1, pt, opt_sema);
212212 }
213213 try writer.writeAll(" }");
......@@ -392,14 +392,14 @@ pub fn printPtrDerivation(
392392 const agg_ty = (try field.parent.ptrType(pt)).childType(zcu);
393393 switch (agg_ty.zigTypeTag(zcu)) {
394394 .@"struct" => if (agg_ty.structFieldName(field.field_idx, zcu).unwrap()) |field_name| {
395 try writer.print(".{fi}", .{field_name.fmt(ip)});
395 try writer.print(".{f}", .{field_name.fmt(ip)});
396396 } else {
397397 try writer.print("[{d}]", .{field.field_idx});
398398 },
399399 .@"union" => {
400400 const tag_ty = agg_ty.unionTagTypeHypothetical(zcu);
401401 const field_name = tag_ty.enumFieldName(field.field_idx, zcu);
402 try writer.print(".{fi}", .{field_name.fmt(ip)});
402 try writer.print(".{f}", .{field_name.fmt(ip)});
403403 },
404404 .pointer => switch (field.field_idx) {
405405 Value.slice_ptr_index => try writer.writeAll(".ptr"),
src/register_manager.zig+3-3
......@@ -238,7 +238,7 @@ pub fn RegisterManager(
238238 if (i < count) return null;
239239
240240 for (regs, insts) |reg, inst| {
241 log.debug("tryAllocReg {} for inst {f}", .{ reg, inst });
241 log.debug("tryAllocReg {} for inst {?f}", .{ reg, inst });
242242 self.markRegAllocated(reg);
243243
244244 if (inst) |tracked_inst| {
......@@ -317,7 +317,7 @@ pub fn RegisterManager(
317317 tracked_index: TrackedIndex,
318318 inst: ?Air.Inst.Index,
319319 ) AllocationError!void {
320 log.debug("getReg {} for inst {f}", .{ regAtTrackedIndex(tracked_index), inst });
320 log.debug("getReg {} for inst {?f}", .{ regAtTrackedIndex(tracked_index), inst });
321321 if (!self.isRegIndexFree(tracked_index)) {
322322 // Move the instruction that was previously there to a
323323 // stack allocation.
......@@ -349,7 +349,7 @@ pub fn RegisterManager(
349349 tracked_index: TrackedIndex,
350350 inst: ?Air.Inst.Index,
351351 ) void {
352 log.debug("getRegAssumeFree {} for inst {f}", .{ regAtTrackedIndex(tracked_index), inst });
352 log.debug("getRegAssumeFree {} for inst {?f}", .{ regAtTrackedIndex(tracked_index), inst });
353353 self.markRegIndexAllocated(tracked_index);
354354
355355 assert(self.isRegIndexFree(tracked_index));