From 540b52931aeeee7c72c73361118d07ab986cf048 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Tue, 8 Jun 2021 20:42:29 -0700 Subject: [PATCH] Improve error message when std.fmt.format is missing arguments Use fmt in fmt so the number in the error message is fmt'd --- doc/langref.html.in | 2 +- lib/std/fmt.zig | 7 ++++++- test/compile_errors.zig | 8 ++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index c84885074e..2378d0f0ba 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -6262,7 +6262,7 @@ pub fn printValue(self: *Writer, value: anytype) !void {

And now, what happens if we give too many arguments to {#syntax#}printf{#endsyntax#}?

- {#code_begin|test_err|Unused arguments#} + {#code_begin|test_err|Unused argument in "here is a string: '{s}' here is a number: {}#} const print = @import("std").debug.print; const a_number: i32 = 1234; diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index 07c076a248..81b505c952 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -359,7 +359,12 @@ pub fn format( } if (comptime arg_state.hasUnusedArgs()) { - @compileError("Unused arguments"); + const missing_count = arg_state.args_len - @popCount(ArgSetType, arg_state.used_args); + switch (missing_count) { + 0 => unreachable, + 1 => @compileError("Unused argument in \"" ++ fmt ++ "\""), + else => @compileError((comptime comptimePrint("{d}", .{missing_count})) ++ " unused arguments in \"" ++ fmt ++ "\""), + } } } diff --git a/test/compile_errors.zig b/test/compile_errors.zig index f0ab776eb6..65c7de6dec 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -2,6 +2,14 @@ const tests = @import("tests.zig"); const std = @import("std"); pub fn addCases(cases: *tests.CompileErrorContext) void { + cases.add("std.fmt error for unused arguments", + \\pub fn main() !void { + \\ @import("std").debug.print("{d} {d} {d} {d} {d}", .{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}); + \\} + , &.{ + \\error: 10 unused arguments in "{d} {d} {d} {d} {d}" + }); + cases.add("lazy pointer with undefined element type", \\export fn foo() void { \\ comptime var T: type = undefined;