diff --git a/build.zig b/build.zig index fe588ea2cb..2b0685d19e 100644 --- a/build.zig +++ b/build.zig @@ -224,7 +224,7 @@ pub fn build(b: *Builder) !void { const opt_version_string = b.option([]const u8, "version-string", "Override Zig version string. Default is to find out with git."); const version = if (opt_version_string) |version| version else v: { - const version_string = b.fmt("{}.{}.{}", .{ zig_version.major, zig_version.minor, zig_version.patch }); + const version_string = b.fmt("{d}.{d}.{d}", .{ zig_version.major, zig_version.minor, zig_version.patch }); var code: u8 = undefined; const git_describe_untrimmed = b.execAllowFail(&[_][]const u8{ @@ -238,7 +238,7 @@ pub fn build(b: *Builder) !void { 0 => { // Tagged release version (e.g. 0.7.0). if (!mem.eql(u8, git_describe, version_string)) { - std.debug.print("Zig version '{}' does not match Git tag '{}'\n", .{ version_string, git_describe }); + std.debug.print("Zig version '{s}' does not match Git tag '{s}'\n", .{ version_string, git_describe }); std.process.exit(1); } break :v version_string; @@ -258,15 +258,15 @@ pub fn build(b: *Builder) !void { // Check that the commit hash is prefixed with a 'g' (a Git convention). if (commit_id.len < 1 or commit_id[0] != 'g') { - std.debug.print("Unexpected `git describe` output: {}\n", .{git_describe}); + std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); break :v version_string; } // The version is reformatted in accordance with the https://semver.org specification. - break :v b.fmt("{}-dev.{}+{}", .{ version_string, commit_height, commit_id[1..] }); + break :v b.fmt("{s}-dev.{s}+{s}", .{ version_string, commit_height, commit_id[1..] }); }, else => { - std.debug.print("Unexpected `git describe` output: {}\n", .{git_describe}); + std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); break :v version_string; }, } @@ -369,14 +369,14 @@ fn addCxxKnownPath( ) !void { const path_padded = try b.exec(&[_][]const u8{ ctx.cxx_compiler, - b.fmt("-print-file-name={}", .{objname}), + b.fmt("-print-file-name={s}", .{objname}), }); const path_unpadded = mem.tokenize(path_padded, "\r\n").next().?; if (mem.eql(u8, path_unpadded, objname)) { if (errtxt) |msg| { - warn("{}", .{msg}); + warn("{s}", .{msg}); } else { - warn("Unable to determine path to {}\n", .{objname}); + warn("Unable to determine path to {s}\n", .{objname}); } return error.RequiredLibraryNotFound; } diff --git a/doc/docgen.zig b/doc/docgen.zig index e995e2f324..7e0bedbb6c 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -215,9 +215,9 @@ const Tokenizer = struct { fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, args: anytype) anyerror { const loc = tokenizer.getTokenLocation(token); const args_prefix = .{ tokenizer.source_file_name, loc.line + 1, loc.column + 1 }; - print("{}:{}:{}: error: " ++ fmt ++ "\n", args_prefix ++ args); + print("{s}:{d}:{d}: error: " ++ fmt ++ "\n", args_prefix ++ args); if (loc.line_start <= loc.line_end) { - print("{}\n", .{tokenizer.buffer[loc.line_start..loc.line_end]}); + print("{s}\n", .{tokenizer.buffer[loc.line_start..loc.line_end]}); { var i: usize = 0; while (i < loc.column) : (i += 1) { @@ -238,7 +238,7 @@ fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, arg fn assertToken(tokenizer: *Tokenizer, token: Token, id: Token.Id) !void { if (token.id != id) { - return parseError(tokenizer, token, "expected {}, found {}", .{ @tagName(id), @tagName(token.id) }); + return parseError(tokenizer, token, "expected {s}, found {s}", .{ @tagName(id), @tagName(token.id) }); } } @@ -374,7 +374,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { return parseError( tokenizer, bracket_tok, - "unrecognized header_open param: {}", + "unrecognized header_open param: {s}", .{param}, ); } @@ -394,7 +394,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { }, }); if (try urls.fetchPut(urlized, tag_token)) |entry| { - parseError(tokenizer, tag_token, "duplicate header url: #{}", .{urlized}) catch {}; + parseError(tokenizer, tag_token, "duplicate header url: #{s}", .{urlized}) catch {}; parseError(tokenizer, entry.value, "other tag here", .{}) catch {}; return error.ParseError; } @@ -411,7 +411,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { } last_columns = columns; try toc.writeByteNTimes(' ', 4 + header_stack_size * 4); - try toc.print("
  • {}", .{ urlized, urlized, content }); + try toc.print("
  • {s}", .{ urlized, urlized, content }); } else if (mem.eql(u8, tag_name, "header_close")) { if (header_stack_size == 0) { return parseError(tokenizer, tag_token, "unbalanced close header", .{}); @@ -515,7 +515,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { code_kind_id = Code.Id{ .Obj = null }; is_inline = true; } else { - return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {}", .{code_kind_str}); + return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {s}", .{code_kind_str}); } var mode: builtin.Mode = .Debug; @@ -559,7 +559,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { return parseError( tokenizer, end_code_tag, - "invalid token inside code_begin: {}", + "invalid token inside code_begin: {s}", .{end_tag_name}, ); } @@ -590,14 +590,14 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { return parseError( tokenizer, end_syntax_tag, - "invalid token inside syntax: {}", + "invalid token inside syntax: {s}", .{end_tag_name}, ); } _ = try eatToken(tokenizer, Token.Id.BracketClose); try nodes.append(Node{ .Syntax = content_tok }); } else { - return parseError(tokenizer, tag_token, "unrecognized tag name: {}", .{tag_name}); + return parseError(tokenizer, tag_token, "unrecognized tag name: {s}", .{tag_name}); } }, else => return parseError(tokenizer, token, "invalid token", .{}), @@ -744,7 +744,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 { try out.writeAll(""); } if (first_number != 0 or second_number != 0) { - try out.print("", .{ first_number, second_number }); + try out.print("", .{ first_number, second_number }); open_span_count += 1; } }, @@ -1004,9 +1004,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any }, .Link => |info| { if (!toc.urls.contains(info.url)) { - return parseError(tokenizer, info.token, "url not found: {}", .{info.url}); + return parseError(tokenizer, info.token, "url not found: {s}", .{info.url}); } - try out.print("{}", .{ info.url, info.name }); + try out.print("{s}", .{ info.url, info.name }); }, .Nav => { try out.writeAll(toc.toc); @@ -1018,7 +1018,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any }, .HeaderOpen => |info| { try out.print( - "{} §\n", + "{s} §\n", .{ info.n, info.url, info.url, info.name, info.url, info.n }, ); }, @@ -1027,9 +1027,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any for (items) |item| { const url = try urlize(allocator, item.name); if (!toc.urls.contains(url)) { - return parseError(tokenizer, item.token, "url not found: {}", .{url}); + return parseError(tokenizer, item.token, "url not found: {s}", .{url}); } - try out.print("
  • {}
  • \n", .{ url, item.name }); + try out.print("
  • {s}
  • \n", .{ url, item.name }); } try out.writeAll("\n"); }, @@ -1043,12 +1043,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any const raw_source = tokenizer.buffer[code.source_token.start..code.source_token.end]; const trimmed_raw_source = mem.trim(u8, raw_source, " \n"); if (!code.is_inline) { - try out.print("

    {}.zig

    ", .{code.name}); + try out.print("

    {s}.zig

    ", .{code.name}); } try out.writeAll("
    ");
                     try tokenizeAndPrint(tokenizer, out, code.source_token);
                     try out.writeAll("
    "); - const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", .{code.name}); + const name_plus_ext = try std.fmt.allocPrint(allocator, "{s}.zig", .{code.name}); const tmp_source_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_ext }, @@ -1057,7 +1057,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any switch (code.id) { Code.Id.Exe => |expected_outcome| code_block: { - const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, exe_ext }); + const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ code.name, exe_ext }); var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); try build_args.appendSlice(&[_][]const u8{ @@ -1066,7 +1066,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any "--color", "on", "--enable-cache", tmp_source_file_name, }); - try out.print("
    $ zig build-exe {}.zig", .{code.name});
    +                        try out.print("
    $ zig build-exe {s}.zig", .{code.name});
                             switch (code.mode) {
                                 .Debug => {},
                                 else => {
    @@ -1075,7 +1075,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                                 },
                             }
                             for (code.link_objects) |link_object| {
    -                            const name_with_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ link_object, obj_ext });
    +                            const name_with_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ link_object, obj_ext });
                                 const full_path_object = try fs.path.join(
                                     allocator,
                                     &[_][]const u8{ tmp_dir_name, name_with_ext },
    @@ -1093,7 +1093,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                             if (code.target_str) |triple| {
                                 try build_args.appendSlice(&[_][]const u8{ "-target", triple });
                                 if (!code.is_inline) {
    -                                try out.print(" -target {}", .{triple});
    +                                try out.print(" -target {s}", .{triple});
                                 }
                             }
                             if (expected_outcome == .BuildFail) {
    @@ -1106,20 +1106,20 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                                 switch (result.term) {
                                     .Exited => |exit_code| {
                                         if (exit_code == 0) {
    -                                        print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
    +                                        print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
                                             dumpArgs(build_args.items);
                                             return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{});
                                         }
                                     },
                                     else => {
    -                                    print("{}\nThe following command crashed:\n", .{result.stderr});
    +                                    print("{s}\nThe following command crashed:\n", .{result.stderr});
                                         dumpArgs(build_args.items);
                                         return parseError(tokenizer, code.source_token, "example compile crashed", .{});
                                     },
                                 }
                                 const escaped_stderr = try escapeHtml(allocator, result.stderr);
                                 const colored_stderr = try termColor(allocator, escaped_stderr);
    -                            try out.print("\n{}
    \n", .{colored_stderr}); + try out.print("\n{s}
    \n", .{colored_stderr}); break :code_block; } const exec_result = exec(allocator, &env_map, build_args.items) catch @@ -1138,7 +1138,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any } const path_to_exe_dir = mem.trim(u8, exec_result.stdout, " \r\n"); - const path_to_exe_basename = try std.fmt.allocPrint(allocator, "{}{}", .{ + const path_to_exe_basename = try std.fmt.allocPrint(allocator, "{s}{s}", .{ code.name, target.exeFileExt(), }); @@ -1160,7 +1160,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { - print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); + print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(run_args); return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{}); } @@ -1179,7 +1179,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any const colored_stderr = try termColor(allocator, escaped_stderr); const colored_stdout = try termColor(allocator, escaped_stdout); - try out.print("\n$ ./{}\n{}{}", .{ code.name, colored_stdout, colored_stderr }); + try out.print("\n$ ./{s}\n{s}{s}", .{ code.name, colored_stdout, colored_stderr }); if (exited_with_signal) { try out.print("(process terminated by signal)", .{}); } @@ -1190,7 +1190,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any defer test_args.deinit(); try test_args.appendSlice(&[_][]const u8{ zig_exe, "test", tmp_source_file_name }); - try out.print("
    $ zig test {}.zig", .{code.name});
    +                        try out.print("
    $ zig test {s}.zig", .{code.name});
                             switch (code.mode) {
                                 .Debug => {},
                                 else => {
    @@ -1204,12 +1204,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                             }
                             if (code.target_str) |triple| {
                                 try test_args.appendSlice(&[_][]const u8{ "-target", triple });
    -                            try out.print(" -target {}", .{triple});
    +                            try out.print(" -target {s}", .{triple});
                             }
                             const result = exec(allocator, &env_map, test_args.items) catch return parseError(tokenizer, code.source_token, "test failed", .{});
                             const escaped_stderr = try escapeHtml(allocator, result.stderr);
                             const escaped_stdout = try escapeHtml(allocator, result.stdout);
    -                        try out.print("\n{}{}
    \n", .{ escaped_stderr, escaped_stdout }); + try out.print("\n{s}{s}
    \n", .{ escaped_stderr, escaped_stdout }); }, Code.Id.TestError => |error_match| { var test_args = std.ArrayList([]const u8).init(allocator); @@ -1222,7 +1222,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any "on", tmp_source_file_name, }); - try out.print("
    $ zig test {}.zig", .{code.name});
    +                        try out.print("
    $ zig test {s}.zig", .{code.name});
                             switch (code.mode) {
                                 .Debug => {},
                                 else => {
    @@ -1239,24 +1239,24 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                             switch (result.term) {
                                 .Exited => |exit_code| {
                                     if (exit_code == 0) {
    -                                    print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
    +                                    print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
                                         dumpArgs(test_args.items);
                                         return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{});
                                     }
                                 },
                                 else => {
    -                                print("{}\nThe following command crashed:\n", .{result.stderr});
    +                                print("{s}\nThe following command crashed:\n", .{result.stderr});
                                     dumpArgs(test_args.items);
                                     return parseError(tokenizer, code.source_token, "example compile crashed", .{});
                                 },
                             }
                             if (mem.indexOf(u8, result.stderr, error_match) == null) {
    -                            print("{}\nExpected to find '{}' in stderr\n", .{ result.stderr, error_match });
    +                            print("{s}\nExpected to find '{s}' in stderr\n", .{ result.stderr, error_match });
                                 return parseError(tokenizer, code.source_token, "example did not have expected compile error", .{});
                             }
                             const escaped_stderr = try escapeHtml(allocator, result.stderr);
                             const colored_stderr = try termColor(allocator, escaped_stderr);
    -                        try out.print("\n{}
    \n", .{colored_stderr}); + try out.print("\n{s}
    \n", .{colored_stderr}); }, Code.Id.TestSafety => |error_match| { @@ -1294,31 +1294,31 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { - print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); + print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(test_args.items); return parseError(tokenizer, code.source_token, "example test incorrectly succeeded", .{}); } }, else => { - print("{}\nThe following command crashed:\n", .{result.stderr}); + print("{s}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(test_args.items); return parseError(tokenizer, code.source_token, "example compile crashed", .{}); }, } if (mem.indexOf(u8, result.stderr, error_match) == null) { - print("{}\nExpected to find '{}' in stderr\n", .{ result.stderr, error_match }); + print("{s}\nExpected to find '{s}' in stderr\n", .{ result.stderr, error_match }); return parseError(tokenizer, code.source_token, "example did not have expected runtime safety error message", .{}); } const escaped_stderr = try escapeHtml(allocator, result.stderr); const colored_stderr = try termColor(allocator, escaped_stderr); - try out.print("
    $ zig test {}.zig{}\n{}
    \n", .{ + try out.print("
    $ zig test {s}.zig{s}\n{s}
    \n", .{ code.name, mode_arg, colored_stderr, }); }, Code.Id.Obj => |maybe_error_match| { - const name_plus_obj_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, obj_ext }); + const name_plus_obj_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ code.name, obj_ext }); const tmp_obj_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_obj_ext }, @@ -1326,7 +1326,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); - const name_plus_h_ext = try std.fmt.allocPrint(allocator, "{}.h", .{code.name}); + const name_plus_h_ext = try std.fmt.allocPrint(allocator, "{s}.h", .{code.name}); const output_h_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_h_ext }, @@ -1345,7 +1345,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any }), }); if (!code.is_inline) { - try out.print("
    $ zig build-obj {}.zig", .{code.name});
    +                            try out.print("
    $ zig build-obj {s}.zig", .{code.name});
                             }
     
                             switch (code.mode) {
    @@ -1360,7 +1360,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
     
                             if (code.target_str) |triple| {
                                 try build_args.appendSlice(&[_][]const u8{ "-target", triple });
    -                            try out.print(" -target {}", .{triple});
    +                            try out.print(" -target {s}", .{triple});
                             }
     
                             if (maybe_error_match) |error_match| {
    @@ -1373,24 +1373,24 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                                 switch (result.term) {
                                     .Exited => |exit_code| {
                                         if (exit_code == 0) {
    -                                        print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
    +                                        print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
                                             dumpArgs(build_args.items);
                                             return parseError(tokenizer, code.source_token, "example build incorrectly succeeded", .{});
                                         }
                                     },
                                     else => {
    -                                    print("{}\nThe following command crashed:\n", .{result.stderr});
    +                                    print("{s}\nThe following command crashed:\n", .{result.stderr});
                                         dumpArgs(build_args.items);
                                         return parseError(tokenizer, code.source_token, "example compile crashed", .{});
                                     },
                                 }
                                 if (mem.indexOf(u8, result.stderr, error_match) == null) {
    -                                print("{}\nExpected to find '{}' in stderr\n", .{ result.stderr, error_match });
    +                                print("{s}\nExpected to find '{s}' in stderr\n", .{ result.stderr, error_match });
                                     return parseError(tokenizer, code.source_token, "example did not have expected compile error message", .{});
                                 }
                                 const escaped_stderr = try escapeHtml(allocator, result.stderr);
                                 const colored_stderr = try termColor(allocator, escaped_stderr);
    -                            try out.print("\n{}", .{colored_stderr});
    +                            try out.print("\n{s}", .{colored_stderr});
                             } else {
                                 _ = exec(allocator, &env_map, build_args.items) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{});
                             }
    @@ -1416,7 +1416,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                                     tmp_dir_name, fs.path.sep_str, bin_basename,
                                 }),
                             });
    -                        try out.print("
    $ zig build-lib {}.zig", .{code.name});
    +                        try out.print("
    $ zig build-lib {s}.zig", .{code.name});
                             switch (code.mode) {
                                 .Debug => {},
                                 else => {
    @@ -1426,12 +1426,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
                             }
                             if (code.target_str) |triple| {
                                 try test_args.appendSlice(&[_][]const u8{ "-target", triple });
    -                            try out.print(" -target {}", .{triple});
    +                            try out.print(" -target {s}", .{triple});
                             }
                             const result = exec(allocator, &env_map, test_args.items) catch return parseError(tokenizer, code.source_token, "test failed", .{});
                             const escaped_stderr = try escapeHtml(allocator, result.stderr);
                             const escaped_stdout = try escapeHtml(allocator, result.stdout);
    -                        try out.print("\n{}{}
    \n", .{ escaped_stderr, escaped_stdout }); + try out.print("\n{s}{s}
    \n", .{ escaped_stderr, escaped_stdout }); }, } print("OK\n", .{}); @@ -1450,13 +1450,13 @@ fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u switch (result.term) { .Exited => |exit_code| { if (exit_code != 0) { - print("{}\nThe following command exited with code {}:\n", .{ result.stderr, exit_code }); + print("{s}\nThe following command exited with code {}:\n", .{ result.stderr, exit_code }); dumpArgs(args); return error.ChildExitError; } }, else => { - print("{}\nThe following command crashed:\n", .{result.stderr}); + print("{s}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(args); return error.ChildCrashed; }, @@ -1471,7 +1471,7 @@ fn getBuiltinCode(allocator: *mem.Allocator, env_map: *std.BufMap, zig_exe: []co fn dumpArgs(args: []const []const u8) void { for (args) |arg| - print("{} ", .{arg}) + print("{s} ", .{arg}) else print("\n", .{}); } diff --git a/doc/langref.html.in b/doc/langref.html.in index 7c8d1c6662..9d89e894ad 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -236,7 +236,7 @@ const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); - try stdout.print("Hello, {}!\n", .{"world"}); + try stdout.print("Hello, {s}!\n", .{"world"}); } {#code_end#}

    @@ -308,7 +308,7 @@ pub fn main() !void { multiple arguments passed to a function, they are separated by commas ,.

    - The two arguments passed to the stdout.print() function, "Hello, {}!\n" + The two arguments passed to the stdout.print() function, "Hello, {s}!\n" and .{"world"}, are evaluated at {#link|compile-time|comptime#}. The code sample is purposely written to show how to perform {#link|string|String Literals and Character Literals#} substitution in the print function. The curly-braces inside of the first argument @@ -435,7 +435,7 @@ pub fn main() void { var optional_value: ?[]const u8 = null; assert(optional_value == null); - print("\noptional 1\ntype: {}\nvalue: {}\n", .{ + print("\noptional 1\ntype: {s}\nvalue: {s}\n", .{ @typeName(@TypeOf(optional_value)), optional_value, }); @@ -443,7 +443,7 @@ pub fn main() void { optional_value = "hi"; assert(optional_value != null); - print("\noptional 2\ntype: {}\nvalue: {}\n", .{ + print("\noptional 2\ntype: {s}\nvalue: {s}\n", .{ @typeName(@TypeOf(optional_value)), optional_value, }); @@ -451,14 +451,14 @@ pub fn main() void { // error union var number_or_error: anyerror!i32 = error.ArgNotFound; - print("\nerror union 1\ntype: {}\nvalue: {}\n", .{ + print("\nerror union 1\ntype: {s}\nvalue: {}\n", .{ @typeName(@TypeOf(number_or_error)), number_or_error, }); number_or_error = 1234; - print("\nerror union 2\ntype: {}\nvalue: {}\n", .{ + print("\nerror union 2\ntype: {s}\nvalue: {}\n", .{ @typeName(@TypeOf(number_or_error)), number_or_error, }); @@ -2339,7 +2339,7 @@ test "using slices for strings" { // You can use slice syntax on an array to convert an array into a slice. const all_together_slice = all_together[0..]; // String concatenation example. - const hello_world = try fmt.bufPrint(all_together_slice, "{} {}", .{ hello, world }); + const hello_world = try fmt.bufPrint(all_together_slice, "{s} {s}", .{ hello, world }); // Generally, you can use UTF-8 and not worry about whether something is a // string. If you don't need to deal with individual characters, no need @@ -2772,9 +2772,9 @@ const std = @import("std"); pub fn main() void { const Foo = struct {}; - std.debug.print("variable: {}\n", .{@typeName(Foo)}); - std.debug.print("anonymous: {}\n", .{@typeName(struct {})}); - std.debug.print("function: {}\n", .{@typeName(List(i32))}); + std.debug.print("variable: {s}\n", .{@typeName(Foo)}); + std.debug.print("anonymous: {s}\n", .{@typeName(struct {})}); + std.debug.print("function: {s}\n", .{@typeName(List(i32))}); } fn List(comptime T: type) type { @@ -6110,7 +6110,7 @@ const a_number: i32 = 1234; const a_string = "foobar"; pub fn main() void { - print("here is a string: '{}' here is a number: {}\n", .{a_string, a_number}); + print("here is a string: '{s}' here is a number: {}\n", .{a_string, a_number}); } {#code_end#} @@ -6230,7 +6230,7 @@ const a_number: i32 = 1234; const a_string = "foobar"; test "printf too many arguments" { - print("here is a string: '{}' here is a number: {}\n", .{ + print("here is a string: '{s}' here is a number: {}\n", .{ a_string, a_number, a_number, @@ -6249,7 +6249,7 @@ const print = @import("std").debug.print; const a_number: i32 = 1234; const a_string = "foobar"; -const fmt = "here is a string: '{}' here is a number: {}\n"; +const fmt = "here is a string: '{s}' here is a number: {}\n"; pub fn main() void { print(fmt, .{a_string, a_number}); @@ -6720,8 +6720,8 @@ fn amain() !void { const download_text = try await download_frame; defer allocator.free(download_text); - std.debug.print("download_text: {}\n", .{download_text}); - std.debug.print("file_text: {}\n", .{file_text}); + std.debug.print("download_text: {s}\n", .{download_text}); + std.debug.print("file_text: {s}\n", .{file_text}); } var global_download_frame: anyframe = undefined; @@ -6790,8 +6790,8 @@ fn amain() !void { const download_text = try await download_frame; defer allocator.free(download_text); - std.debug.print("download_text: {}\n", .{download_text}); - std.debug.print("file_text: {}\n", .{file_text}); + std.debug.print("download_text: {s}\n", .{download_text}); + std.debug.print("file_text: {s}\n", .{file_text}); } fn fetchUrl(allocator: *Allocator, url: []const u8) ![]u8 { @@ -8848,7 +8848,7 @@ pub fn main() !void { var byte: u8 = 255; byte = if (math.add(u8, byte, 1)) |result| result else |err| { - print("unable to add one: {}\n", .{@errorName(err)}); + print("unable to add one: {s}\n", .{@errorName(err)}); return err; }; @@ -9078,7 +9078,7 @@ pub fn main() void { if (result) |number| { print("got number: {}\n", .{number}); } else |err| { - print("got error: {}\n", .{@errorName(err)}); + print("got error: {s}\n", .{@errorName(err)}); } } @@ -9135,7 +9135,7 @@ const Foo = enum { pub fn main() void { var a: u2 = 3; var b = @intToEnum(Foo, a); - std.debug.print("value: {}\n", .{@tagName(b)}); + std.debug.print("value: {s}\n", .{@tagName(b)}); } {#code_end#} {#header_close#} @@ -10025,7 +10025,7 @@ pub fn main() !void { defer std.process.argsFree(gpa, args); for (args) |arg, i| { - std.debug.print("{}: {}\n", .{ i, arg }); + std.debug.print("{}: {s}\n", .{ i, arg }); } } {#code_end#} diff --git a/lib/std/SemanticVersion.zig b/lib/std/SemanticVersion.zig index 74e515f9d1..dc9e6d8572 100644 --- a/lib/std/SemanticVersion.zig +++ b/lib/std/SemanticVersion.zig @@ -163,9 +163,9 @@ pub fn format( out_stream: anytype, ) !void { if (fmt.len != 0) @compileError("Unknown format string: '" ++ fmt ++ "'"); - try std.fmt.format(out_stream, "{}.{}.{}", .{ self.major, self.minor, self.patch }); - if (self.pre) |pre| try std.fmt.format(out_stream, "-{}", .{pre}); - if (self.build) |build| try std.fmt.format(out_stream, "+{}", .{build}); + try std.fmt.format(out_stream, "{d}.{d}.{d}", .{ self.major, self.minor, self.patch }); + if (self.pre) |pre| try std.fmt.format(out_stream, "-{s}", .{pre}); + if (self.build) |build| try std.fmt.format(out_stream, "+{s}", .{build}); } const expect = std.testing.expect; @@ -287,9 +287,9 @@ fn testFmt(expected: []const u8, comptime template: []const u8, args: anytype) ! if (std.mem.eql(u8, result, expected)) return; std.debug.warn("\n====== expected this output: =========\n", .{}); - std.debug.warn("{}", .{expected}); + std.debug.warn("{s}", .{expected}); std.debug.warn("\n======== instead found this: =========\n", .{}); - std.debug.warn("{}", .{result}); + std.debug.warn("{s}", .{result}); std.debug.warn("\n======================================\n", .{}); return error.TestFailed; } diff --git a/lib/std/build.zig b/lib/std/build.zig index 3b6f8815bc..bd097c9414 100644 --- a/lib/std/build.zig +++ b/lib/std/build.zig @@ -294,7 +294,7 @@ pub const Builder = struct { /// To run an executable built with zig build, see `LibExeObjStep.run`. pub fn addSystemCommand(self: *Builder, argv: []const []const u8) *RunStep { assert(argv.len >= 1); - const run_step = RunStep.create(self, self.fmt("run {}", .{argv[0]})); + const run_step = RunStep.create(self, self.fmt("run {s}", .{argv[0]})); run_step.addArgs(argv); return run_step; } @@ -409,7 +409,7 @@ pub const Builder = struct { for (self.installed_files.items) |installed_file| { const full_path = self.getInstallPath(installed_file.dir, installed_file.path); if (self.verbose) { - warn("rm {}\n", .{full_path}); + warn("rm {s}\n", .{full_path}); } fs.cwd().deleteTree(full_path) catch {}; } @@ -419,7 +419,7 @@ pub const Builder = struct { fn makeOneStep(self: *Builder, s: *Step) anyerror!void { if (s.loop_flag) { - warn("Dependency loop detected:\n {}\n", .{s.name}); + warn("Dependency loop detected:\n {s}\n", .{s.name}); return error.DependencyLoopDetected; } s.loop_flag = true; @@ -427,7 +427,7 @@ pub const Builder = struct { for (s.dependencies.items) |dep| { self.makeOneStep(dep) catch |err| { if (err == error.DependencyLoopDetected) { - warn(" {}\n", .{s.name}); + warn(" {s}\n", .{s.name}); } return err; }; @@ -444,7 +444,7 @@ pub const Builder = struct { return &top_level_step.step; } } - warn("Cannot run step '{}' because it does not exist\n", .{name}); + warn("Cannot run step '{s}' because it does not exist\n", .{name}); return error.InvalidStepName; } @@ -456,7 +456,7 @@ pub const Builder = struct { .description = description, }; if ((self.available_options_map.fetchPut(name, available_option) catch unreachable) != null) { - panic("Option '{}' declared twice", .{name}); + panic("Option '{s}' declared twice", .{name}); } self.available_options_list.append(available_option) catch unreachable; @@ -471,32 +471,32 @@ pub const Builder = struct { } else if (mem.eql(u8, s, "false")) { return false; } else { - warn("Expected -D{} to be a boolean, but received '{}'\n\n", .{ name, s }); + warn("Expected -D{s} to be a boolean, but received '{s}'\n\n", .{ name, s }); self.markInvalidUserInput(); return null; } }, .List => { - warn("Expected -D{} to be a boolean, but received a list.\n\n", .{name}); + warn("Expected -D{s} to be a boolean, but received a list.\n\n", .{name}); self.markInvalidUserInput(); return null; }, }, .Int => switch (entry.value.value) { .Flag => { - warn("Expected -D{} to be an integer, but received a boolean.\n\n", .{name}); + warn("Expected -D{s} to be an integer, but received a boolean.\n\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| { const n = std.fmt.parseInt(T, s, 10) catch |err| switch (err) { error.Overflow => { - warn("-D{} value {} cannot fit into type {}.\n\n", .{ name, s, @typeName(T) }); + warn("-D{s} value {} cannot fit into type {s}.\n\n", .{ name, s, @typeName(T) }); self.markInvalidUserInput(); return null; }, else => { - warn("Expected -D{} to be an integer of type {}.\n\n", .{ name, @typeName(T) }); + warn("Expected -D{s} to be an integer of type {s}.\n\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; }, @@ -504,34 +504,34 @@ pub const Builder = struct { return n; }, .List => { - warn("Expected -D{} to be an integer, but received a list.\n\n", .{name}); + warn("Expected -D{s} to be an integer, but received a list.\n\n", .{name}); self.markInvalidUserInput(); return null; }, }, .Float => switch (entry.value.value) { .Flag => { - warn("Expected -D{} to be a float, but received a boolean.\n\n", .{name}); + warn("Expected -D{s} to be a float, but received a boolean.\n\n", .{name}); self.markInvalidUserInput(); return null; }, .Scalar => |s| { const n = std.fmt.parseFloat(T, s) catch |err| { - warn("Expected -D{} to be a float of type {}.\n\n", .{ name, @typeName(T) }); + warn("Expected -D{s} to be a float of type {s}.\n\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; }; return n; }, .List => { - warn("Expected -D{} to be a float, but received a list.\n\n", .{name}); + warn("Expected -D{s} to be a float, but received a list.\n\n", .{name}); self.markInvalidUserInput(); return null; }, }, .Enum => switch (entry.value.value) { .Flag => { - warn("Expected -D{} to be a string, but received a boolean.\n\n", .{name}); + warn("Expected -D{s} to be a string, but received a boolean.\n\n", .{name}); self.markInvalidUserInput(); return null; }, @@ -539,25 +539,25 @@ pub const Builder = struct { if (std.meta.stringToEnum(T, s)) |enum_lit| { return enum_lit; } else { - warn("Expected -D{} to be of type {}.\n\n", .{ name, @typeName(T) }); + warn("Expected -D{s} to be of type {s}.\n\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; } }, .List => { - warn("Expected -D{} to be a string, but received a list.\n\n", .{name}); + warn("Expected -D{s} to be a string, but received a list.\n\n", .{name}); self.markInvalidUserInput(); return null; }, }, .String => switch (entry.value.value) { .Flag => { - warn("Expected -D{} to be a string, but received a boolean.\n\n", .{name}); + warn("Expected -D{s} to be a string, but received a boolean.\n\n", .{name}); self.markInvalidUserInput(); return null; }, .List => { - warn("Expected -D{} to be a string, but received a list.\n\n", .{name}); + warn("Expected -D{s} to be a string, but received a list.\n\n", .{name}); self.markInvalidUserInput(); return null; }, @@ -565,7 +565,7 @@ pub const Builder = struct { }, .List => switch (entry.value.value) { .Flag => { - warn("Expected -D{} to be a list, but received a boolean.\n\n", .{name}); + warn("Expected -D{s} to be a list, but received a boolean.\n\n", .{name}); self.markInvalidUserInput(); return null; }, @@ -592,7 +592,7 @@ pub const Builder = struct { if (self.release_mode != null) { @panic("setPreferredReleaseMode must be called before standardReleaseOptions and may not be called twice"); } - const description = self.fmt("Create a release build ({})", .{@tagName(mode)}); + const description = self.fmt("Create a release build ({s})", .{@tagName(mode)}); self.is_release = self.option(bool, "release", description) orelse false; self.release_mode = if (self.is_release) mode else builtin.Mode.Debug; } @@ -646,12 +646,12 @@ pub const Builder = struct { .diagnostics = &diags, }) catch |err| switch (err) { error.UnknownCpuModel => { - warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{ + warn("Unknown CPU: '{s}'\nAvailable CPUs for architecture '{s}':\n", .{ diags.cpu_name.?, @tagName(diags.arch.?), }); for (diags.arch.?.allCpuModels()) |cpu| { - warn(" {}\n", .{cpu.name}); + warn(" {s}\n", .{cpu.name}); } warn("\n", .{}); self.markInvalidUserInput(); @@ -659,15 +659,15 @@ pub const Builder = struct { }, error.UnknownCpuFeature => { warn( - \\Unknown CPU feature: '{}' - \\Available CPU features for architecture '{}': + \\Unknown CPU feature: '{s}' + \\Available CPU features for architecture '{s}': \\ , .{ diags.unknown_feature_name, @tagName(diags.arch.?), }); for (diags.arch.?.allFeaturesList()) |feature| { - warn(" {}: {}\n", .{ feature.name, feature.description }); + warn(" {s}: {s}\n", .{ feature.name, feature.description }); } warn("\n", .{}); self.markInvalidUserInput(); @@ -675,19 +675,19 @@ pub const Builder = struct { }, error.UnknownOperatingSystem => { warn( - \\Unknown OS: '{}' + \\Unknown OS: '{s}' \\Available operating systems: \\ , .{diags.os_name}); inline for (std.meta.fields(std.Target.Os.Tag)) |field| { - warn(" {}\n", .{field.name}); + warn(" {s}\n", .{field.name}); } warn("\n", .{}); self.markInvalidUserInput(); return args.default_target; }, else => |e| { - warn("Unable to parse target '{}': {}\n\n", .{ triple, @errorName(e) }); + warn("Unable to parse target '{}': {s}\n\n", .{ triple, @errorName(e) }); self.markInvalidUserInput(); return args.default_target; }, @@ -703,12 +703,12 @@ pub const Builder = struct { break :whitelist_check; } } - warn("Chosen target '{}' does not match one of the supported targets:\n", .{ + warn("Chosen target '{s}' does not match one of the supported targets:\n", .{ selected_canonicalized_triple, }); for (list) |t| { const t_triple = t.zigTriple(self.allocator) catch unreachable; - warn(" {}\n", .{t_triple}); + warn(" {s}\n", .{t_triple}); } warn("\n", .{}); self.markInvalidUserInput(); @@ -752,7 +752,7 @@ pub const Builder = struct { }) catch unreachable; }, UserValue.Flag => { - warn("Option '-D{}={}' conflicts with flag '-D{}'.\n", .{ name, value, name }); + warn("Option '-D{s}={s}' conflicts with flag '-D{s}'.\n", .{ name, value, name }); return true; }, } @@ -773,11 +773,11 @@ pub const Builder = struct { // option already exists switch (gop.entry.value.value) { UserValue.Scalar => |s| { - warn("Flag '-D{}' conflicts with option '-D{}={}'.\n", .{ name, name, s }); + warn("Flag '-D{s}' conflicts with option '-D{s}={s}'.\n", .{ name, name, s }); return true; }, UserValue.List => { - warn("Flag '-D{}' conflicts with multiple options of the same name.\n", .{name}); + warn("Flag '-D{s}' conflicts with multiple options of the same name.\n", .{name}); return true; }, UserValue.Flag => {}, @@ -820,7 +820,7 @@ pub const Builder = struct { while (true) { const entry = it.next() orelse break; if (!entry.value.used) { - warn("Invalid option: -D{}\n\n", .{entry.key}); + warn("Invalid option: -D{s}\n\n", .{entry.key}); self.markInvalidUserInput(); } } @@ -833,9 +833,9 @@ pub const Builder = struct { } fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void { - if (cwd) |yes_cwd| warn("cd {} && ", .{yes_cwd}); + if (cwd) |yes_cwd| warn("cd {s} && ", .{yes_cwd}); for (argv) |arg| { - warn("{} ", .{arg}); + warn("{s} ", .{arg}); } warn("\n", .{}); } @@ -852,7 +852,7 @@ pub const Builder = struct { child.env_map = env_map; const term = child.spawnAndWait() catch |err| { - warn("Unable to spawn {}: {}\n", .{ argv[0], @errorName(err) }); + warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) }); return err; }; @@ -875,7 +875,7 @@ pub const Builder = struct { pub fn makePath(self: *Builder, path: []const u8) !void { fs.cwd().makePath(self.pathFromRoot(path)) catch |err| { - warn("Unable to create path {}: {}\n", .{ path, @errorName(err) }); + warn("Unable to create path {s}: {s}\n", .{ path, @errorName(err) }); return err; }; } @@ -959,7 +959,7 @@ pub const Builder = struct { pub fn updateFile(self: *Builder, source_path: []const u8, dest_path: []const u8) !void { if (self.verbose) { - warn("cp {} {} ", .{ source_path, dest_path }); + warn("cp {s} {s} ", .{ source_path, dest_path }); } const cwd = fs.cwd(); const prev_status = try fs.Dir.updateFile(cwd, source_path, cwd, dest_path, .{}); @@ -988,7 +988,7 @@ pub const Builder = struct { const full_path = try fs.path.join(self.allocator, &[_][]const u8{ search_prefix, "bin", - self.fmt("{}{}", .{ name, exe_extension }), + self.fmt("{s}{s}", .{ name, exe_extension }), }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } @@ -1002,7 +1002,7 @@ pub const Builder = struct { while (it.next()) |path| { const full_path = try fs.path.join(self.allocator, &[_][]const u8{ path, - self.fmt("{}{}", .{ name, exe_extension }), + self.fmt("{s}{s}", .{ name, exe_extension }), }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } @@ -1015,7 +1015,7 @@ pub const Builder = struct { for (paths) |path| { const full_path = try fs.path.join(self.allocator, &[_][]const u8{ path, - self.fmt("{}{}", .{ name, exe_extension }), + self.fmt("{s}{s}", .{ name, exe_extension }), }); return fs.realpathAlloc(self.allocator, full_path) catch continue; } @@ -1070,19 +1070,19 @@ pub const Builder = struct { var code: u8 = undefined; return self.execAllowFail(argv, &code, .Inherit) catch |err| switch (err) { error.FileNotFound => { - if (src_step) |s| warn("{}...", .{s.name}); + if (src_step) |s| warn("{s}...", .{s.name}); warn("Unable to spawn the following command: file not found\n", .{}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, error.ExitCodeFailure => { - if (src_step) |s| warn("{}...", .{s.name}); - warn("The following command exited with error code {}:\n", .{code}); + if (src_step) |s| warn("{s}...", .{s.name}); + warn("The following command exited with error code {d}:\n", .{code}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); }, error.ProcessTerminated => { - if (src_step) |s| warn("{}...", .{s.name}); + if (src_step) |s| warn("{s}...", .{s.name}); warn("The following command terminated unexpectedly:\n", .{}); printCmd(null, argv); std.os.exit(@truncate(u8, code)); @@ -1405,7 +1405,7 @@ pub const LibExeObjStep = struct { ver: ?Version, ) LibExeObjStep { if (mem.indexOf(u8, name, "/") != null or mem.indexOf(u8, name, "\\") != null) { - panic("invalid name: '{}'. It looks like a file path, but it is supposed to be the library or application name.", .{name}); + panic("invalid name: '{s}'. It looks like a file path, but it is supposed to be the library or application name.", .{name}); } var self = LibExeObjStep{ .strip = false, @@ -1421,9 +1421,9 @@ pub const LibExeObjStep = struct { .step = Step.init(.LibExeObj, name, builder.allocator, make), .version = ver, .out_filename = undefined, - .out_h_filename = builder.fmt("{}.h", .{name}), + .out_h_filename = builder.fmt("{s}.h", .{name}), .out_lib_filename = undefined, - .out_pdb_filename = builder.fmt("{}.pdb", .{name}), + .out_pdb_filename = builder.fmt("{s}.pdb", .{name}), .major_only_filename = undefined, .name_only_filename = undefined, .packages = ArrayList(Pkg).init(builder.allocator), @@ -1529,7 +1529,7 @@ pub const LibExeObjStep = struct { // It doesn't have to be native. We catch that if you actually try to run it. // Consider that this is declarative; the run step may not be run unless a user // option is supplied. - const run_step = RunStep.create(exe.builder, exe.builder.fmt("run {}", .{exe.step.name})); + const run_step = RunStep.create(exe.builder, exe.builder.fmt("run {s}", .{exe.step.name})); run_step.addArtifactArg(exe); if (exe.vcpkg_bin_path) |path| { @@ -1680,7 +1680,7 @@ pub const LibExeObjStep = struct { } else if (mem.eql(u8, tok, "-pthread")) { self.linkLibC(); } else if (self.builder.verbose) { - warn("Ignoring pkg-config flag '{}'\n", .{tok}); + warn("Ignoring pkg-config flag '{s}'\n", .{tok}); } } } @@ -1926,7 +1926,7 @@ pub const LibExeObjStep = struct { }, else => {}, } - out.print("pub const {z}: {} = {};\n", .{ name, @typeName(T), value }) catch unreachable; + out.print("pub const {z}: {s} = {};\n", .{ name, @typeName(T), value }) catch unreachable; } /// The value is the path in the cache dir. @@ -2048,7 +2048,7 @@ pub const LibExeObjStep = struct { const builder = self.builder; if (self.root_src == null and self.link_objects.items.len == 0) { - warn("{}: linker needs 1 or more objects to link\n", .{self.step.name}); + warn("{s}: linker needs 1 or more objects to link\n", .{self.step.name}); return error.NeedAnObject; } @@ -2156,12 +2156,12 @@ pub const LibExeObjStep = struct { // Render build artifact options at the last minute, now that the path is known. for (self.build_options_artifact_args.items) |item| { const out = self.build_options_contents.writer(); - out.print("pub const {}: []const u8 = \"{Z}\";\n", .{ item.name, item.artifact.getOutputPath() }) catch unreachable; + out.print("pub const {s}: []const u8 = \"{Z}\";\n", .{ item.name, item.artifact.getOutputPath() }) catch unreachable; } const build_options_file = try fs.path.join( builder.allocator, - &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) }, + &[_][]const u8{ builder.cache_root, builder.fmt("{s}_build_options.zig", .{self.name}) }, ); const path_from_root = builder.pathFromRoot(build_options_file); try fs.cwd().writeFile(path_from_root, self.build_options_contents.items); @@ -2294,16 +2294,16 @@ pub const LibExeObjStep = struct { } else { var mcpu_buffer = std.ArrayList(u8).init(builder.allocator); - try mcpu_buffer.outStream().print("-mcpu={}", .{cross.cpu.model.name}); + try mcpu_buffer.outStream().print("-mcpu={s}", .{cross.cpu.model.name}); for (all_features) |feature, i_usize| { const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize); const in_cpu_set = populated_cpu_features.isEnabled(i); const in_actual_set = cross.cpu.features.isEnabled(i); if (in_cpu_set and !in_actual_set) { - try mcpu_buffer.outStream().print("-{}", .{feature.name}); + try mcpu_buffer.outStream().print("-{s}", .{feature.name}); } else if (!in_cpu_set and in_actual_set) { - try mcpu_buffer.outStream().print("+{}", .{feature.name}); + try mcpu_buffer.outStream().print("+{s}", .{feature.name}); } } @@ -2536,7 +2536,7 @@ pub const InstallArtifactStep = struct { const self = builder.allocator.create(Self) catch unreachable; self.* = Self{ .builder = builder, - .step = Step.init(.InstallArtifact, builder.fmt("install {}", .{artifact.step.name}), builder.allocator, make), + .step = Step.init(.InstallArtifact, builder.fmt("install {s}", .{artifact.step.name}), builder.allocator, make), .artifact = artifact, .dest_dir = artifact.override_dest_dir orelse switch (artifact.kind) { .Obj => unreachable, @@ -2612,7 +2612,7 @@ pub const InstallFileStep = struct { builder.pushInstalledFile(dir, dest_rel_path); return InstallFileStep{ .builder = builder, - .step = Step.init(.InstallFile, builder.fmt("install {}", .{src_path}), builder.allocator, make), + .step = Step.init(.InstallFile, builder.fmt("install {s}", .{src_path}), builder.allocator, make), .src_path = src_path, .dir = dir, .dest_rel_path = dest_rel_path, @@ -2646,7 +2646,7 @@ pub const InstallDirStep = struct { builder.pushInstalledFile(options.install_dir, options.install_subdir); return InstallDirStep{ .builder = builder, - .step = Step.init(.InstallDir, builder.fmt("install {}/", .{options.source_dir}), builder.allocator, make), + .step = Step.init(.InstallDir, builder.fmt("install {s}/", .{options.source_dir}), builder.allocator, make), .options = options, }; } @@ -2682,14 +2682,14 @@ pub const LogStep = struct { pub fn init(builder: *Builder, data: []const u8) LogStep { return LogStep{ .builder = builder, - .step = Step.init(.Log, builder.fmt("log {}", .{data}), builder.allocator, make), + .step = Step.init(.Log, builder.fmt("log {s}", .{data}), builder.allocator, make), .data = data, }; } fn make(step: *Step) anyerror!void { const self = @fieldParentPtr(LogStep, "step", step); - warn("{}", .{self.data}); + warn("{s}", .{self.data}); } }; @@ -2701,7 +2701,7 @@ pub const RemoveDirStep = struct { pub fn init(builder: *Builder, dir_path: []const u8) RemoveDirStep { return RemoveDirStep{ .builder = builder, - .step = Step.init(.RemoveDir, builder.fmt("RemoveDir {}", .{dir_path}), builder.allocator, make), + .step = Step.init(.RemoveDir, builder.fmt("RemoveDir {s}", .{dir_path}), builder.allocator, make), .dir_path = dir_path, }; } @@ -2711,7 +2711,7 @@ pub const RemoveDirStep = struct { const full_path = self.builder.pathFromRoot(self.dir_path); fs.cwd().deleteTree(full_path) catch |err| { - warn("Unable to remove {}: {}\n", .{ full_path, @errorName(err) }); + warn("Unable to remove {s}: {s}\n", .{ full_path, @errorName(err) }); return err; }; } @@ -2799,7 +2799,7 @@ fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_maj &[_][]const u8{ out_dir, filename_major_only }, ) catch unreachable; fs.atomicSymLink(allocator, out_basename, major_only_path) catch |err| { - warn("Unable to symlink {} -> {}\n", .{ major_only_path, out_basename }); + warn("Unable to symlink {s} -> {s}\n", .{ major_only_path, out_basename }); return err; }; // sym link for libfoo.so to libfoo.so.1 @@ -2808,7 +2808,7 @@ fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_maj &[_][]const u8{ out_dir, filename_name_only }, ) catch unreachable; fs.atomicSymLink(allocator, filename_major_only, name_only_path) catch |err| { - warn("Unable to symlink {} -> {}\n", .{ name_only_path, filename_major_only }); + warn("Unable to symlink {s} -> {s}\n", .{ name_only_path, filename_major_only }); return err; }; } diff --git a/lib/std/build/check_file.zig b/lib/std/build/check_file.zig index 565ff0692a..31966fad52 100644 --- a/lib/std/build/check_file.zig +++ b/lib/std/build/check_file.zig @@ -45,9 +45,9 @@ pub const CheckFileStep = struct { warn( \\ \\========= Expected to find: =================== - \\{} + \\{s} \\========= But file does not contain it: ======= - \\{} + \\{s} \\ , .{ expected_match, contents }); return error.TestFailed; diff --git a/lib/std/build/emit_raw.zig b/lib/std/build/emit_raw.zig index 66d44fc59f..3d2c6124c1 100644 --- a/lib/std/build/emit_raw.zig +++ b/lib/std/build/emit_raw.zig @@ -189,7 +189,7 @@ pub const InstallRawStep = struct { pub fn create(builder: *Builder, artifact: *LibExeObjStep, dest_filename: []const u8) *Self { const self = builder.allocator.create(Self) catch unreachable; self.* = Self{ - .step = Step.init(.InstallRaw, builder.fmt("install raw binary {}", .{artifact.step.name}), builder.allocator, make), + .step = Step.init(.InstallRaw, builder.fmt("install raw binary {s}", .{artifact.step.name}), builder.allocator, make), .builder = builder, .artifact = artifact, .dest_dir = switch (artifact.kind) { diff --git a/lib/std/build/run.zig b/lib/std/build/run.zig index 18e05c2e01..36a4a1a843 100644 --- a/lib/std/build/run.zig +++ b/lib/std/build/run.zig @@ -116,7 +116,7 @@ pub const RunStep = struct { } if (prev_path) |pp| { - const new_path = self.builder.fmt("{}" ++ [1]u8{fs.path.delimiter} ++ "{}", .{ pp, search_path }); + const new_path = self.builder.fmt("{s}" ++ [1]u8{fs.path.delimiter} ++ "{s}", .{ pp, search_path }); env_map.set(key, new_path) catch unreachable; } else { env_map.set(key, search_path) catch unreachable; @@ -189,7 +189,7 @@ pub const RunStep = struct { child.stderr_behavior = stdIoActionToBehavior(self.stderr_action); child.spawn() catch |err| { - warn("Unable to spawn {}: {}\n", .{ argv[0], @errorName(err) }); + warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) }); return err; }; @@ -216,7 +216,7 @@ pub const RunStep = struct { } const term = child.wait() catch |err| { - warn("Unable to spawn {}: {}\n", .{ argv[0], @errorName(err) }); + warn("Unable to spawn {s}: {s}\n", .{ argv[0], @errorName(err) }); return err; }; @@ -245,9 +245,9 @@ pub const RunStep = struct { warn( \\ \\========= Expected this stderr: ========= - \\{} + \\{s} \\========= But found: ==================== - \\{} + \\{s} \\ , .{ expected_bytes, stderr.? }); printCmd(cwd, argv); @@ -259,9 +259,9 @@ pub const RunStep = struct { warn( \\ \\========= Expected to find in stderr: ========= - \\{} + \\{s} \\========= But stderr does not contain it: ===== - \\{} + \\{s} \\ , .{ match, stderr.? }); printCmd(cwd, argv); @@ -277,9 +277,9 @@ pub const RunStep = struct { warn( \\ \\========= Expected this stdout: ========= - \\{} + \\{s} \\========= But found: ==================== - \\{} + \\{s} \\ , .{ expected_bytes, stdout.? }); printCmd(cwd, argv); @@ -291,9 +291,9 @@ pub const RunStep = struct { warn( \\ \\========= Expected to find in stdout: ========= - \\{} + \\{s} \\========= But stdout does not contain it: ===== - \\{} + \\{s} \\ , .{ match, stdout.? }); printCmd(cwd, argv); @@ -304,9 +304,9 @@ pub const RunStep = struct { } fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void { - if (cwd) |yes_cwd| warn("cd {} && ", .{yes_cwd}); + if (cwd) |yes_cwd| warn("cd {s} && ", .{yes_cwd}); for (argv) |arg| { - warn("{} ", .{arg}); + warn("{s} ", .{arg}); } warn("\n", .{}); } diff --git a/lib/std/build/write_file.zig b/lib/std/build/write_file.zig index 04b7268e81..bbe6ec5086 100644 --- a/lib/std/build/write_file.zig +++ b/lib/std/build/write_file.zig @@ -80,14 +80,14 @@ pub const WriteFileStep = struct { }); // TODO replace with something like fs.makePathAndOpenDir fs.cwd().makePath(self.output_dir) catch |err| { - warn("unable to make path {}: {}\n", .{ self.output_dir, @errorName(err) }); + warn("unable to make path {s}: {s}\n", .{ self.output_dir, @errorName(err) }); return err; }; var dir = try fs.cwd().openDir(self.output_dir, .{}); defer dir.close(); for (self.files.items) |file| { dir.writeFile(file.basename, file.bytes) catch |err| { - warn("unable to write {} into {}: {}\n", .{ + warn("unable to write {s} into {s}: {s}\n", .{ file.basename, self.output_dir, @errorName(err), diff --git a/lib/std/builtin.zig b/lib/std/builtin.zig index fbc4a7cef5..c883e03ba9 100644 --- a/lib/std/builtin.zig +++ b/lib/std/builtin.zig @@ -67,12 +67,12 @@ pub const StackTrace = struct { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const debug_info = std.debug.getSelfDebugInfo() catch |err| { - return writer.print("\nUnable to print stack trace: Unable to open debug info: {}\n", .{@errorName(err)}); + return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}); }; const tty_config = std.debug.detectTTYConfig(); try writer.writeAll("\n"); std.debug.writeStackTrace(self, writer, &arena.allocator, debug_info, tty_config) catch |err| { - try writer.print("Unable to print stack trace: {}\n", .{@errorName(err)}); + try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)}); }; try writer.writeAll("\n"); } @@ -529,12 +529,12 @@ pub const Version = struct { if (fmt.len == 0) { if (self.patch == 0) { if (self.minor == 0) { - return std.fmt.format(out_stream, "{}", .{self.major}); + return std.fmt.format(out_stream, "{d}", .{self.major}); } else { - return std.fmt.format(out_stream, "{}.{}", .{ self.major, self.minor }); + return std.fmt.format(out_stream, "{d}.{d}", .{ self.major, self.minor }); } } else { - return std.fmt.format(out_stream, "{}.{}.{}", .{ self.major, self.minor, self.patch }); + return std.fmt.format(out_stream, "{d}.{d}.{d}", .{ self.major, self.minor, self.patch }); } } else { @compileError("Unknown format string: '" ++ fmt ++ "'"); @@ -683,7 +683,7 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn } }, .wasi => { - std.debug.warn("{}", .{msg}); + std.debug.warn("{s}", .{msg}); std.os.abort(); }, .uefi => { @@ -692,7 +692,7 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn }, else => { const first_trace_addr = @returnAddress(); - std.debug.panicExtra(error_return_trace, first_trace_addr, "{}", .{msg}); + std.debug.panicExtra(error_return_trace, first_trace_addr, "{s}", .{msg}); }, } } diff --git a/lib/std/c/ast.zig b/lib/std/c/ast.zig index c1e20f799d..207fe8eac8 100644 --- a/lib/std/c/ast.zig +++ b/lib/std/c/ast.zig @@ -115,10 +115,10 @@ pub const Error = union(enum) { pub fn render(self: *const ExpectedToken, tree: *Tree, stream: anytype) !void { const found_token = tree.tokens.at(self.token); if (found_token.id == .Invalid) { - return stream.print("expected '{}', found invalid bytes", .{self.expected_id.symbol()}); + return stream.print("expected '{s}', found invalid bytes", .{self.expected_id.symbol()}); } else { const token_name = found_token.id.symbol(); - return stream.print("expected '{}', found '{}'", .{ self.expected_id.symbol(), token_name }); + return stream.print("expected '{s}', found '{s}'", .{ self.expected_id.symbol(), token_name }); } } }; @@ -131,7 +131,7 @@ pub const Error = union(enum) { try stream.write("invalid type specifier '"); try type_spec.spec.print(tree, stream); const token_name = tree.tokens.at(self.token).id.symbol(); - return stream.print("{}'", .{token_name}); + return stream.print("{s}'", .{token_name}); } }; @@ -140,7 +140,7 @@ pub const Error = union(enum) { name: TokenIndex, pub fn render(self: *const ExpectedToken, tree: *Tree, stream: anytype) !void { - return stream.print("must use '{}' tag to refer to type '{}'", .{ tree.slice(kw), tree.slice(name) }); + return stream.print("must use '{s}' tag to refer to type '{s}'", .{ tree.slice(kw), tree.slice(name) }); } }; diff --git a/lib/std/c/tokenizer.zig b/lib/std/c/tokenizer.zig index 3fa3d1d6f8..aeb47fc4a0 100644 --- a/lib/std/c/tokenizer.zig +++ b/lib/std/c/tokenizer.zig @@ -1552,7 +1552,7 @@ fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) void { for (expected_tokens) |expected_token_id| { const token = tokenizer.next(); if (!std.meta.eql(token.id, expected_token_id)) { - std.debug.panic("expected {}, found {}\n", .{ @tagName(expected_token_id), @tagName(token.id) }); + std.debug.panic("expected {s}, found {s}\n", .{ @tagName(expected_token_id), @tagName(token.id) }); } } const last_token = tokenizer.next(); diff --git a/lib/std/crypto/bcrypt.zig b/lib/std/crypto/bcrypt.zig index 554ba50c68..6d333c45cb 100644 --- a/lib/std/crypto/bcrypt.zig +++ b/lib/std/crypto/bcrypt.zig @@ -247,7 +247,7 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8) Codec.encode(ct_str[0..], ct[0 .. ct.len - 1]); var s_buf: [hash_length]u8 = undefined; - const s = fmt.bufPrint(s_buf[0..], "$2b${}{}${}{}", .{ rounds_log / 10, rounds_log % 10, salt_str, ct_str }) catch unreachable; + const s = fmt.bufPrint(s_buf[0..], "$2b${d}{d}${s}{s}", .{ rounds_log / 10, rounds_log % 10, salt_str, ct_str }) catch unreachable; debug.assert(s.len == s_buf.len); return s_buf; } diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 57a0e20d2e..073f68da5d 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -108,11 +108,11 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void { return; } const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; + stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; return; }; writeCurrentStackTrace(stderr, debug_info, detectTTYConfig(), start_addr) catch |err| { - stderr.print("Unable to dump stack trace: {}\n", .{@errorName(err)}) catch return; + stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return; return; }; } @@ -129,7 +129,7 @@ pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void { return; } const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; + stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; return; }; const tty_config = detectTTYConfig(); @@ -199,11 +199,11 @@ pub fn dumpStackTrace(stack_trace: builtin.StackTrace) void { return; } const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", .{@errorName(err)}) catch return; + stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; return; }; writeStackTrace(stack_trace, stderr, getDebugInfoAllocator(), debug_info, detectTTYConfig()) catch |err| { - stderr.print("Unable to dump stack trace: {}\n", .{@errorName(err)}) catch return; + stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return; return; }; } @@ -611,7 +611,7 @@ fn printLineInfo( tty_config.setColor(out_stream, .White); if (line_info) |*li| { - try out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column }); + try out_stream.print("{s}:{d}:{d}", .{ li.file_name, li.line, li.column }); } else { try out_stream.writeAll("???:?:?"); } @@ -619,7 +619,7 @@ fn printLineInfo( tty_config.setColor(out_stream, .Reset); try out_stream.writeAll(": "); tty_config.setColor(out_stream, .Dim); - try out_stream.print("0x{x} in {} ({})", .{ address, symbol_name, compile_unit_name }); + try out_stream.print("0x{x} in {s} ({s})", .{ address, symbol_name, compile_unit_name }); tty_config.setColor(out_stream, .Reset); try out_stream.writeAll("\n"); diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index e9112c9178..788f8f1933 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -466,7 +466,7 @@ test "LinearFifo(u8, .Dynamic)" { fifo.shrink(0); { - try fifo.writer().print("{}, {}!", .{ "Hello", "World" }); + try fifo.writer().print("{s}, {s}!", .{ "Hello", "World" }); var result: [30]u8 = undefined; testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]); testing.expectEqual(@as(usize, 0), fifo.readableLength()); diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index 803df7da94..bc9ac92283 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -367,6 +367,36 @@ pub fn format( } } +pub fn formatAddress(value: anytype, options: FormatOptions, writer: anytype) @TypeOf(writer).Error!void { + const T = @TypeOf(value); + + switch (@typeInfo(T)) { + .Pointer => |info| { + try writer.writeAll(@typeName(info.child) ++ "@"); + if (info.size == .Slice) + try formatInt(@ptrToInt(value.ptr), 16, false, FormatOptions{}, writer) + else + try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, writer); + return; + }, + .Optional => |info| { + if (@typeInfo(info.child) == .Pointer) { + try writer.writeAll(@typeName(info.child) ++ "@"); + try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, writer); + return; + } + }, + .Array => |info| { + try writer.writeAll(@typeName(info.child) ++ "@"); + try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, writer); + return; + }, + else => {}, + } + + @compileError("Cannot format non-pointer type " ++ @typeName(T) ++ " with * specifier"); +} + pub fn formatType( value: anytype, comptime fmt: []const u8, @@ -375,10 +405,7 @@ pub fn formatType( max_depth: usize, ) @TypeOf(writer).Error!void { if (comptime std.mem.eql(u8, fmt, "*")) { - try writer.writeAll(@typeName(std.meta.Child(@TypeOf(value)))); - try writer.writeAll("@"); - try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, writer); - return; + return formatAddress(value, options, writer); } const T = @TypeOf(value); @@ -436,12 +463,11 @@ pub fn formatType( try formatType(@enumToInt(value), fmt, options, writer, max_depth); try writer.writeAll(")"); }, - .Union => { + .Union => |info| { try writer.writeAll(@typeName(T)); if (max_depth == 0) { return writer.writeAll("{ ... }"); } - const info = @typeInfo(T).Union; if (info.tag_type) |UnionTagType| { try writer.writeAll("{ ."); try writer.writeAll(@tagName(@as(UnionTagType, value))); @@ -456,13 +482,13 @@ pub fn formatType( try format(writer, "@{x}", .{@ptrToInt(&value)}); } }, - .Struct => |StructT| { + .Struct => |info| { try writer.writeAll(@typeName(T)); if (max_depth == 0) { return writer.writeAll("{ ... }"); } try writer.writeAll("{"); - inline for (StructT.fields) |f, i| { + inline for (info.fields) |f, i| { if (i == 0) { try writer.writeAll(" ."); } else { @@ -478,69 +504,83 @@ pub fn formatType( .One => switch (@typeInfo(ptr_info.child)) { .Array => |info| { if (info.child == u8) { - return formatText(value, fmt, options, writer); + if (fmt.len > 0 and comptime mem.indexOfScalar(u8, "sxXeEzZ", fmt[0]) != null) { + return formatText(value, fmt, options, writer); + } } - return format(writer, "{}@{x}", .{ @typeName(@typeInfo(T).Pointer.child), @ptrToInt(value) }); + return format(writer, "{s}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value) }); }, .Enum, .Union, .Struct => { return formatType(value.*, fmt, options, writer, max_depth); }, - else => return format(writer, "{}@{x}", .{ @typeName(@typeInfo(T).Pointer.child), @ptrToInt(value) }), + else => return format(writer, "{s}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value) }), }, .Many, .C => { if (ptr_info.sentinel) |sentinel| { return formatType(mem.span(value), fmt, options, writer, max_depth); } if (ptr_info.child == u8) { - if (fmt.len > 0 and fmt[0] == 's') { + if (fmt.len > 0 and comptime mem.indexOfScalar(u8, "sxXeEzZ", fmt[0]) != null) { return formatText(mem.span(value), fmt, options, writer); } } - return format(writer, "{}@{x}", .{ @typeName(@typeInfo(T).Pointer.child), @ptrToInt(value) }); + return format(writer, "{s}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value) }); }, .Slice => { - if (fmt.len > 0 and ((fmt[0] == 'x') or (fmt[0] == 'X'))) { - return formatText(value, fmt, options, writer); + if (max_depth == 0) { + return writer.writeAll("{ ... }"); } if (ptr_info.child == u8) { - return formatText(value, fmt, options, writer); + if (fmt.len > 0 and comptime mem.indexOfScalar(u8, "sxXeEzZ", fmt[0]) != null) { + return formatText(value, fmt, options, writer); + } } - return format(writer, "{}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value.ptr) }); + try writer.writeAll("{ "); + for (value) |elem, i| { + try formatType(elem, fmt, options, writer, max_depth - 1); + if (i != value.len - 1) { + try writer.writeAll(", "); + } + } + try writer.writeAll(" }"); }, }, .Array => |info| { - const Slice = @Type(builtin.TypeInfo{ - .Pointer = .{ - .size = .Slice, - .is_const = true, - .is_volatile = false, - .is_allowzero = false, - .alignment = @alignOf(info.child), - .child = info.child, - .sentinel = null, - }, - }); - return formatType(@as(Slice, &value), fmt, options, writer, max_depth); + if (max_depth == 0) { + return writer.writeAll("{ ... }"); + } + if (info.child == u8) { + if (fmt.len > 0 and comptime mem.indexOfScalar(u8, "sxXeEzZ", fmt[0]) != null) { + return formatText(&value, fmt, options, writer); + } + } + try writer.writeAll("{ "); + for (value) |elem, i| { + try formatType(elem, fmt, options, writer, max_depth - 1); + if (i < value.len - 1) { + try writer.writeAll(", "); + } + } + try writer.writeAll(" }"); }, - .Vector => { - const len = @typeInfo(T).Vector.len; + .Vector => |info| { try writer.writeAll("{ "); var i: usize = 0; - while (i < len) : (i += 1) { + while (i < info.len) : (i += 1) { try formatValue(value[i], fmt, options, writer); - if (i < len - 1) { + if (i < info.len - 1) { try writer.writeAll(", "); } } try writer.writeAll(" }"); }, .Fn => { - return format(writer, "{}@{x}", .{ @typeName(T), @ptrToInt(value) }); + return format(writer, "{s}@{x}", .{ @typeName(T), @ptrToInt(value) }); }, .Type => return formatBuf(@typeName(value), options, writer), .EnumLiteral => { const buffer = [_]u8{'.'} ++ @tagName(value); - return formatType(buffer, fmt, options, writer, max_depth); + return formatBuf(buffer, options, writer); }, .Null => return formatBuf("null", options, writer), else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"), @@ -657,7 +697,7 @@ pub fn formatText( options: FormatOptions, writer: anytype, ) !void { - if (comptime std.mem.eql(u8, fmt, "s") or (fmt.len == 0)) { + if (comptime std.mem.eql(u8, fmt, "s")) { return formatBuf(bytes, options, writer); } else if (comptime (std.mem.eql(u8, fmt, "x") or std.mem.eql(u8, fmt, "X"))) { for (bytes) |c| { @@ -1521,8 +1561,9 @@ test "buffer" { test "array" { { const value: [3]u8 = "abc".*; - try testFmt("array: abc\n", "array: {}\n", .{value}); - try testFmt("array: abc\n", "array: {}\n", .{&value}); + try testFmt("array: abc\n", "array: {s}\n", .{value}); + try testFmt("array: abc\n", "array: {s}\n", .{&value}); + try testFmt("array: { 97, 98, 99 }\n", "array: {d}\n", .{value}); var buf: [100]u8 = undefined; try testFmt( @@ -1536,12 +1577,12 @@ test "array" { test "slice" { { const value: []const u8 = "abc"; - try testFmt("slice: abc\n", "slice: {}\n", .{value}); + try testFmt("slice: abc\n", "slice: {s}\n", .{value}); } { var runtime_zero: usize = 0; const value = @intToPtr([*]align(1) const []const u8, 0xdeadbeef)[runtime_zero..runtime_zero]; - try testFmt("slice: []const u8@deadbeef\n", "slice: {}\n", .{value}); + try testFmt("slice: []const u8@deadbeef\n", "slice: {*}\n", .{value}); } { const null_term_slice: [:0]const u8 = "\x00hello\x00"; @@ -1550,6 +1591,15 @@ test "slice" { try testFmt("buf: Test\n", "buf: {s:5}\n", .{"Test"}); try testFmt("buf: Test\n Other text", "buf: {s}\n Other text", .{"Test"}); + + { + var int_slice = [_]u32{ 1, 4096, 391891, 1111111111 }; + var runtime_zero: usize = 0; + try testFmt("int: { 1, 4096, 391891, 1111111111 }", "int: {}", .{int_slice[runtime_zero..]}); + try testFmt("int: { 1, 4096, 391891, 1111111111 }", "int: {d}", .{int_slice[runtime_zero..]}); + try testFmt("int: { 1, 1000, 5fad3, 423a35c7 }", "int: {x}", .{int_slice[runtime_zero..]}); + try testFmt("int: { 00001, 01000, 5fad3, 423a35c7 }", "int: {x:0>5}", .{int_slice[runtime_zero..]}); + } } test "escape non-printable" { @@ -1854,9 +1904,9 @@ fn testFmt(expected: []const u8, comptime template: []const u8, args: anytype) ! if (mem.eql(u8, result, expected)) return; std.debug.warn("\n====== expected this output: =========\n", .{}); - std.debug.warn("{}", .{expected}); + std.debug.warn("{s}", .{expected}); std.debug.warn("\n======== instead found this: =========\n", .{}); - std.debug.warn("{}", .{result}); + std.debug.warn("{s}", .{result}); std.debug.warn("\n======================================\n", .{}); return error.TestFailed; } @@ -2013,24 +2063,24 @@ test "vector" { } test "enum-literal" { - try testFmt(".hello_world", "{}", .{.hello_world}); + try testFmt(".hello_world", "{s}", .{.hello_world}); } test "padding" { - try testFmt("Simple", "{}", .{"Simple"}); + try testFmt("Simple", "{s}", .{"Simple"}); try testFmt(" true", "{:10}", .{true}); try testFmt(" true", "{:>10}", .{true}); try testFmt("======true", "{:=>10}", .{true}); try testFmt("true======", "{:=<10}", .{true}); try testFmt(" true ", "{:^10}", .{true}); try testFmt("===true===", "{:=^10}", .{true}); - try testFmt(" Minimum width", "{:18} width", .{"Minimum"}); - try testFmt("==================Filled", "{:=>24}", .{"Filled"}); - try testFmt(" Centered ", "{:^24}", .{"Centered"}); - try testFmt("-", "{:-^1}", .{""}); - try testFmt("==crêpe===", "{:=^10}", .{"crêpe"}); - try testFmt("=====crêpe", "{:=>10}", .{"crêpe"}); - try testFmt("crêpe=====", "{:=<10}", .{"crêpe"}); + try testFmt(" Minimum width", "{s:18} width", .{"Minimum"}); + try testFmt("==================Filled", "{s:=>24}", .{"Filled"}); + try testFmt(" Centered ", "{s:^24}", .{"Centered"}); + try testFmt("-", "{s:-^1}", .{""}); + try testFmt("==crêpe===", "{s:=^10}", .{"crêpe"}); + try testFmt("=====crêpe", "{s:=>10}", .{"crêpe"}); + try testFmt("crêpe=====", "{s:=<10}", .{"crêpe"}); } test "decimal float padding" { @@ -2059,15 +2109,15 @@ test "type" { } test "named arguments" { - try testFmt("hello world!", "{} world{c}", .{ "hello", '!' }); - try testFmt("hello world!", "{[greeting]} world{[punctuation]c}", .{ .punctuation = '!', .greeting = "hello" }); - try testFmt("hello world!", "{[1]} world{[0]c}", .{ '!', "hello" }); + try testFmt("hello world!", "{s} world{c}", .{ "hello", '!' }); + try testFmt("hello world!", "{[greeting]s} world{[punctuation]c}", .{ .punctuation = '!', .greeting = "hello" }); + try testFmt("hello world!", "{[1]s} world{[0]c}", .{ '!', "hello" }); } test "runtime width specifier" { var width: usize = 9; - try testFmt("~~hello~~", "{:~^[1]}", .{ "hello", width }); - try testFmt("~~hello~~", "{:~^[width]}", .{ .string = "hello", .width = width }); + try testFmt("~~hello~~", "{s:~^[1]}", .{ "hello", width }); + try testFmt("~~hello~~", "{s:~^[width]}", .{ .string = "hello", .width = width }); } test "runtime precision specifier" { diff --git a/lib/std/fs/wasi.zig b/lib/std/fs/wasi.zig index 761f6e8466..900adc5e2d 100644 --- a/lib/std/fs/wasi.zig +++ b/lib/std/fs/wasi.zig @@ -38,7 +38,7 @@ pub const PreopenType = union(PreopenTypeTag) { pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void { try out_stream.print("PreopenType{{ ", .{}); switch (self) { - PreopenType.Dir => |path| try out_stream.print(".Dir = '{}'", .{path}), + PreopenType.Dir => |path| try out_stream.print(".Dir = '{z}'", .{path}), } return out_stream.print(" }}", .{}); } diff --git a/lib/std/heap/general_purpose_allocator.zig b/lib/std/heap/general_purpose_allocator.zig index e7766f6445..415b206b6a 100644 --- a/lib/std/heap/general_purpose_allocator.zig +++ b/lib/std/heap/general_purpose_allocator.zig @@ -314,7 +314,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { if (is_used) { const slot_index = @intCast(SlotIndex, used_bits_byte * 8 + bit_index); const stack_trace = bucketStackTrace(bucket, size_class, slot_index, .alloc); - log.err("Memory leak detected: {}", .{stack_trace}); + log.err("Memory leak detected: {s}", .{stack_trace}); leaks = true; } if (bit_index == math.maxInt(u3)) @@ -342,7 +342,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { } var it = self.large_allocations.iterator(); while (it.next()) |large_alloc| { - log.err("Memory leak detected: {}", .{large_alloc.value.getStackTrace()}); + log.err("Memory leak detected: {s}", .{large_alloc.value.getStackTrace()}); leaks = true; } return leaks; @@ -443,7 +443,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { .index = 0, }; std.debug.captureStackTrace(ret_addr, &free_stack_trace); - log.err("Allocation size {} bytes does not match free size {}. Allocation: {} Free: {}", .{ + log.err("Allocation size {d} bytes does not match free size {d}. Allocation: {s} Free: {s}", .{ entry.value.bytes.len, old_mem.len, entry.value.getStackTrace(), @@ -526,7 +526,7 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type { .index = 0, }; std.debug.captureStackTrace(ret_addr, &second_free_stack_trace); - log.err("Double free detected. Allocation: {} First free: {} Second free: {}", .{ + log.err("Double free detected. Allocation: {s} First free: {s} Second free: {s}", .{ alloc_stack_trace, free_stack_trace, second_free_stack_trace, diff --git a/lib/std/io/fixed_buffer_stream.zig b/lib/std/io/fixed_buffer_stream.zig index e698ce061e..b36949e538 100644 --- a/lib/std/io/fixed_buffer_stream.zig +++ b/lib/std/io/fixed_buffer_stream.zig @@ -147,7 +147,7 @@ test "FixedBufferStream output" { var fbs = fixedBufferStream(&buf); const stream = fbs.writer(); - try stream.print("{}{}!", .{ "Hello", "World" }); + try stream.print("{s}{s}!", .{ "Hello", "World" }); testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten()); } diff --git a/lib/std/json.zig b/lib/std/json.zig index e412676fa3..f5be3a2094 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -2642,9 +2642,9 @@ fn teststringify(expected: []const u8, value: anytype, options: StringifyOptions if (self.expected_remaining.len < bytes.len) { std.debug.warn( \\====== expected this output: ========= - \\{} + \\{s} \\======== instead found this: ========= - \\{} + \\{s} \\====================================== , .{ self.expected_remaining, @@ -2655,9 +2655,9 @@ fn teststringify(expected: []const u8, value: anytype, options: StringifyOptions if (!mem.eql(u8, self.expected_remaining[0..bytes.len], bytes)) { std.debug.warn( \\====== expected this output: ========= - \\{} + \\{s} \\======== instead found this: ========= - \\{} + \\{s} \\====================================== , .{ self.expected_remaining[0..bytes.len], diff --git a/lib/std/meta/trait.zig b/lib/std/meta/trait.zig index 8c8b26cf45..8e54293533 100644 --- a/lib/std/meta/trait.zig +++ b/lib/std/meta/trait.zig @@ -298,6 +298,20 @@ pub fn isNumber(comptime T: type) bool { }; } +pub fn isIntegerNumber(comptime T: type) bool { + return switch (@typeInfo(T)) { + .Int, .ComptimeInt => true, + else => false, + }; +} + +pub fn isFloatingNumber(comptime T: type) bool { + return switch (@typeInfo(T)) { + .Float, .ComptimeFloat => true, + else => false, + }; +} + test "std.meta.trait.isNumber" { const NotANumber = struct { number: u8, diff --git a/lib/std/net.zig b/lib/std/net.zig index 5b17714fae..b8f48b2020 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -154,7 +154,7 @@ pub const Address = extern union { unreachable; } - try std.fmt.format(out_stream, "{}", .{&self.un.path}); + try std.fmt.format(out_stream, "{s}", .{&self.un.path}); }, else => unreachable, } diff --git a/lib/std/os.zig b/lib/std/os.zig index fb187252a1..1bde12a6fb 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -4256,7 +4256,7 @@ pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 { }, .linux => { var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined; - const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", .{fd}) catch unreachable; + const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{d}\x00", .{fd}) catch unreachable; const target = readlinkZ(std.meta.assumeSentinel(proc_path.ptr, 0), out_buffer) catch |err| { switch (err) { @@ -4487,7 +4487,7 @@ pub const UnexpectedError = error{ /// and you get an unexpected error. pub fn unexpectedErrno(err: usize) UnexpectedError { if (unexpected_error_tracing) { - std.debug.warn("unexpected errno: {}\n", .{err}); + std.debug.warn("unexpected errno: {d}\n", .{err}); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index 40271cdc38..1c6e5202a3 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -1618,7 +1618,7 @@ pub fn unexpectedError(err: Win32Error) std.os.UnexpectedError { null, ); _ = std.unicode.utf16leToUtf8(&buf_u8, buf_u16[0..len]) catch unreachable; - std.debug.warn("error.Unexpected: GetLastError({}): {}\n", .{ @enumToInt(err), buf_u8[0..len] }); + std.debug.warn("error.Unexpected: GetLastError({}): {s}\n", .{ @enumToInt(err), buf_u8[0..len] }); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; diff --git a/lib/std/process.zig b/lib/std/process.zig index 3f944f10b6..3529bf52cb 100644 --- a/lib/std/process.zig +++ b/lib/std/process.zig @@ -596,7 +596,7 @@ fn testWindowsCmdLine(input_cmd_line: [*]const u16, expected_args: []const []con for (expected_args) |expected_arg| { const arg = it.next(std.testing.allocator).? catch unreachable; defer std.testing.allocator.free(arg); - testing.expectEqualSlices(u8, expected_arg, arg); + testing.expectEqualStrings(expected_arg, arg); } testing.expect(it.next(std.testing.allocator) == null); } diff --git a/lib/std/special/build_runner.zig b/lib/std/special/build_runner.zig index e3e90e7574..f2fa2dc3b8 100644 --- a/lib/std/special/build_runner.zig +++ b/lib/std/special/build_runner.zig @@ -98,7 +98,7 @@ pub fn main() !void { return usageAndErr(builder, false, stderr_stream); }; builder.color = std.meta.stringToEnum(@TypeOf(builder.color), next_arg) orelse { - warn("expected [auto|on|off] after --color, found '{}'", .{next_arg}); + warn("expected [auto|on|off] after --color, found '{s}'", .{next_arg}); return usageAndErr(builder, false, stderr_stream); }; } else if (mem.eql(u8, arg, "--override-lib-dir")) { @@ -126,7 +126,7 @@ pub fn main() !void { builder.args = argsRest(args, arg_idx); break; } else { - warn("Unrecognized argument: {}\n\n", .{arg}); + warn("Unrecognized argument: {s}\n\n", .{arg}); return usageAndErr(builder, false, stderr_stream); } } else { @@ -168,7 +168,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void } try out_stream.print( - \\Usage: {} build [steps] [options] + \\Usage: {s} build [steps] [options] \\ \\Steps: \\ @@ -177,10 +177,10 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void const allocator = builder.allocator; for (builder.top_level_steps.items) |top_level_step| { const name = if (&top_level_step.step == builder.default_step) - try fmt.allocPrint(allocator, "{} (default)", .{top_level_step.step.name}) + try fmt.allocPrint(allocator, "{s} (default)", .{top_level_step.step.name}) else top_level_step.step.name; - try out_stream.print(" {s:<27} {}\n", .{ name, top_level_step.description }); + try out_stream.print(" {s:<27} {s}\n", .{ name, top_level_step.description }); } try out_stream.writeAll( @@ -200,12 +200,12 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void try out_stream.print(" (none)\n", .{}); } else { for (builder.available_options_list.items) |option| { - const name = try fmt.allocPrint(allocator, " -D{}=[{}]", .{ + const name = try fmt.allocPrint(allocator, " -D{s}=[{s}]", .{ option.name, Builder.typeIdName(option.type_id), }); defer allocator.free(name); - try out_stream.print("{s:<29} {}\n", .{ name, option.description }); + try out_stream.print("{s:<29} {s}\n", .{ name, option.description }); } } diff --git a/lib/std/special/c.zig b/lib/std/special/c.zig index c92ffa21ac..51cbafc133 100644 --- a/lib/std/special/c.zig +++ b/lib/std/special/c.zig @@ -172,7 +172,7 @@ test "strncmp" { pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { if (builtin.is_test) { @setCold(true); - std.debug.panic("{}", .{msg}); + std.debug.panic("{s}", .{msg}); } if (builtin.os.tag != .freestanding and builtin.os.tag != .other) { std.os.abort(); diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index e0743cd4b7..a06c568b2e 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -324,7 +324,7 @@ pub usingnamespace @import("compiler_rt/atomics.zig"); pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { @setCold(true); if (is_test) { - std.debug.panic("{}", .{msg}); + std.debug.panic("{s}", .{msg}); } else { unreachable; } diff --git a/lib/std/special/test_runner.zig b/lib/std/special/test_runner.zig index 6c1a298759..f5a93298b5 100644 --- a/lib/std/special/test_runner.zig +++ b/lib/std/special/test_runner.zig @@ -48,7 +48,7 @@ pub fn main() anyerror!void { test_node.activate(); progress.refresh(); if (progress.terminal == null) { - std.debug.print("{}/{} {}... ", .{ i + 1, test_fn_list.len, test_fn.name }); + std.debug.print("{d}/{d} {s}... ", .{ i + 1, test_fn_list.len, test_fn.name }); } const result = if (test_fn.async_frame_size) |size| switch (io_mode) { .evented => blk: { @@ -62,7 +62,7 @@ pub fn main() anyerror!void { .blocking => { skip_count += 1; test_node.end(); - progress.log("{}...SKIP (async test)\n", .{test_fn.name}); + progress.log("{s}...SKIP (async test)\n", .{test_fn.name}); if (progress.terminal == null) std.debug.print("SKIP (async test)\n", .{}); continue; }, @@ -75,7 +75,7 @@ pub fn main() anyerror!void { error.SkipZigTest => { skip_count += 1; test_node.end(); - progress.log("{}...SKIP\n", .{test_fn.name}); + progress.log("{s}...SKIP\n", .{test_fn.name}); if (progress.terminal == null) std.debug.print("SKIP\n", .{}); }, else => { @@ -86,15 +86,15 @@ pub fn main() anyerror!void { } root_node.end(); if (ok_count == test_fn_list.len) { - std.debug.print("All {} tests passed.\n", .{ok_count}); + std.debug.print("All {d} tests passed.\n", .{ok_count}); } else { - std.debug.print("{} passed; {} skipped.\n", .{ ok_count, skip_count }); + std.debug.print("{d} passed; {d} skipped.\n", .{ ok_count, skip_count }); } if (log_err_count != 0) { - std.debug.print("{} errors were logged.\n", .{log_err_count}); + std.debug.print("{d} errors were logged.\n", .{log_err_count}); } if (leaks != 0) { - std.debug.print("{} tests leaked memory.\n", .{leaks}); + std.debug.print("{d} tests leaked memory.\n", .{leaks}); } if (leaks != 0 or log_err_count != 0) { std.process.exit(1); @@ -111,6 +111,6 @@ pub fn log( log_err_count += 1; } if (@enumToInt(message_level) <= @enumToInt(std.testing.log_level)) { - std.debug.print("[{}] ({}): " ++ format ++ "\n", .{ @tagName(scope), @tagName(message_level) } ++ args); + std.debug.print("[{s}] ({s}): " ++ format ++ "\n", .{ @tagName(scope), @tagName(message_level) } ++ args); } } diff --git a/lib/std/start.zig b/lib/std/start.zig index a8fbf251f7..718d48130e 100644 --- a/lib/std/start.zig +++ b/lib/std/start.zig @@ -266,7 +266,7 @@ inline fn initEventLoopAndCallMain() u8 { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { - std.log.err("{}", .{@errorName(err)}); + std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -295,7 +295,7 @@ inline fn initEventLoopAndCallWinMain() std.os.windows.INT { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { - std.log.err("{}", .{@errorName(err)}); + std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -343,7 +343,7 @@ pub fn callMain() u8 { }, .ErrorUnion => { const result = root.main() catch |err| { - std.log.err("{}", .{@errorName(err)}); + std.log.err("{s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } diff --git a/lib/std/target.zig b/lib/std/target.zig index 165a8fcae7..2b3518bc92 100644 --- a/lib/std/target.zig +++ b/lib/std/target.zig @@ -136,14 +136,14 @@ pub const Target = struct { ) !void { if (fmt.len > 0 and fmt[0] == 's') { if (@enumToInt(self) >= @enumToInt(WindowsVersion.nt4) and @enumToInt(self) <= @enumToInt(WindowsVersion.latest)) { - try std.fmt.format(out_stream, ".{}", .{@tagName(self)}); + try std.fmt.format(out_stream, ".{s}", .{@tagName(self)}); } else { // TODO this code path breaks zig triples, but it is used in `builtin` try std.fmt.format(out_stream, "@intToEnum(Target.Os.WindowsVersion, 0x{X:0>8})", .{@enumToInt(self)}); } } else { if (@enumToInt(self) >= @enumToInt(WindowsVersion.nt4) and @enumToInt(self) <= @enumToInt(WindowsVersion.latest)) { - try std.fmt.format(out_stream, "WindowsVersion.{}", .{@tagName(self)}); + try std.fmt.format(out_stream, "WindowsVersion.{s}", .{@tagName(self)}); } else { try std.fmt.format(out_stream, "WindowsVersion(0x{X:0>8})", .{@enumToInt(self)}); } @@ -1177,7 +1177,7 @@ pub const Target = struct { } pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 { - return std.fmt.allocPrint(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) }); + return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) }); } pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 { @@ -1381,7 +1381,7 @@ pub const Target = struct { if (self.abi == .android) { const suffix = if (self.cpu.arch.ptrBitWidth() == 64) "64" else ""; - return print(&result, "/system/bin/linker{}", .{suffix}); + return print(&result, "/system/bin/linker{s}", .{suffix}); } if (self.abi.isMusl()) { @@ -1395,7 +1395,7 @@ pub const Target = struct { else => |arch| @tagName(arch), }; const arch_suffix = if (is_arm and self.abi.floatAbi() == .hard) "hf" else ""; - return print(&result, "/lib/ld-musl-{}{}.so.1", .{ arch_part, arch_suffix }); + return print(&result, "/lib/ld-musl-{s}{s}.so.1", .{ arch_part, arch_suffix }); } switch (self.os.tag) { @@ -1434,7 +1434,7 @@ pub const Target = struct { }; const is_nan_2008 = mips.featureSetHas(self.cpu.features, .nan2008); const loader = if (is_nan_2008) "ld-linux-mipsn8.so.1" else "ld.so.1"; - return print(&result, "/lib{}/{}", .{ lib_suffix, loader }); + return print(&result, "/lib{s}/{s}", .{ lib_suffix, loader }); }, .powerpc => return copy(&result, "/lib/ld.so.1"), diff --git a/lib/std/testing.zig b/lib/std/testing.zig index a6f749b158..4f4a46dbf7 100644 --- a/lib/std/testing.zig +++ b/lib/std/testing.zig @@ -29,10 +29,10 @@ pub var zig_exe_path: []const u8 = undefined; /// and then aborts when actual_error_union is not expected_error. pub fn expectError(expected_error: anyerror, actual_error_union: anytype) void { if (actual_error_union) |actual_payload| { - std.debug.panic("expected error.{}, found {}", .{ @errorName(expected_error), actual_payload }); + std.debug.panic("expected error.{s}, found {}", .{ @errorName(expected_error), actual_payload }); } else |actual_error| { if (expected_error != actual_error) { - std.debug.panic("expected error.{}, found error.{}", .{ + std.debug.panic("expected error.{s}, found error.{s}", .{ @errorName(expected_error), @errorName(actual_error), }); @@ -60,7 +60,7 @@ pub fn expectEqual(expected: anytype, actual: @TypeOf(expected)) void { .Type => { if (actual != expected) { - std.debug.panic("expected type {}, found type {}", .{ @typeName(expected), @typeName(actual) }); + std.debug.panic("expected type {s}, found type {s}", .{ @typeName(expected), @typeName(actual) }); } }, @@ -258,7 +258,7 @@ pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const // If the child type is u8 and no weird bytes, we could print it as strings // Even for the length difference, it would be useful to see the values of the slices probably. if (expected.len != actual.len) { - std.debug.panic("slice lengths differ. expected {}, found {}", .{ expected.len, actual.len }); + std.debug.panic("slice lengths differ. expected {d}, found {d}", .{ expected.len, actual.len }); } var i: usize = 0; while (i < expected.len) : (i += 1) { @@ -360,7 +360,7 @@ pub fn expectEqualStrings(expected: []const u8, actual: []const u8) void { for (expected[0..diff_index]) |value| { if (value == '\n') diff_line_number += 1; } - print("First difference occurs on line {}:\n", .{diff_line_number}); + print("First difference occurs on line {d}:\n", .{diff_line_number}); print("expected:\n", .{}); printIndicatorLine(expected, diff_index); @@ -416,15 +416,15 @@ fn printWithVisibleNewlines(source: []const u8) void { while (std.mem.indexOf(u8, source[i..], "\n")) |nl| : (i += nl + 1) { printLine(source[i .. i + nl]); } - print("{}␃\n", .{source[i..]}); // End of Text symbol (ETX) + print("{s}␃\n", .{source[i..]}); // End of Text symbol (ETX) } fn printLine(line: []const u8) void { if (line.len != 0) switch (line[line.len - 1]) { - ' ', '\t' => print("{}⏎\n", .{line}), // Carriage return symbol, + ' ', '\t' => print("{s}⏎\n", .{line}), // Carriage return symbol, else => {}, }; - print("{}\n", .{line}); + print("{s}\n", .{line}); } test "" { diff --git a/lib/std/thread.zig b/lib/std/thread.zig index 7d63b5f644..0fee13b057 100644 --- a/lib/std/thread.zig +++ b/lib/std/thread.zig @@ -186,7 +186,7 @@ pub const Thread = struct { @compileError(bad_startfn_ret); } startFn(arg) catch |err| { - std.debug.warn("error: {}\n", .{@errorName(err)}); + std.debug.warn("error: {s}\n", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -247,7 +247,7 @@ pub const Thread = struct { @compileError(bad_startfn_ret); } startFn(arg) catch |err| { - std.debug.warn("error: {}\n", .{@errorName(err)}); + std.debug.warn("error: {s}\n", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } @@ -281,7 +281,7 @@ pub const Thread = struct { @compileError(bad_startfn_ret); } startFn(arg) catch |err| { - std.debug.warn("error: {}\n", .{@errorName(err)}); + std.debug.warn("error: {s}\n", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } diff --git a/lib/std/zig/ast.zig b/lib/std/zig/ast.zig index c0e72ea822..eb894fa1f6 100644 --- a/lib/std/zig/ast.zig +++ b/lib/std/zig/ast.zig @@ -281,41 +281,41 @@ pub const Error = union(enum) { } } - pub const InvalidToken = SingleTokenError("Invalid token '{}'"); - pub const ExpectedContainerMembers = SingleTokenError("Expected test, comptime, var decl, or container field, found '{}'"); - pub const ExpectedStringLiteral = SingleTokenError("Expected string literal, found '{}'"); - pub const ExpectedIntegerLiteral = SingleTokenError("Expected integer literal, found '{}'"); - pub const ExpectedIdentifier = SingleTokenError("Expected identifier, found '{}'"); - pub const ExpectedStatement = SingleTokenError("Expected statement, found '{}'"); - pub const ExpectedVarDeclOrFn = SingleTokenError("Expected variable declaration or function, found '{}'"); - pub const ExpectedVarDecl = SingleTokenError("Expected variable declaration, found '{}'"); - pub const ExpectedFn = SingleTokenError("Expected function, found '{}'"); - pub const ExpectedReturnType = SingleTokenError("Expected 'var' or return type expression, found '{}'"); - pub const ExpectedAggregateKw = SingleTokenError("Expected '" ++ Token.Id.Keyword_struct.symbol() ++ "', '" ++ Token.Id.Keyword_union.symbol() ++ "', '" ++ Token.Id.Keyword_enum.symbol() ++ "', or '" ++ Token.Id.Keyword_opaque.symbol() ++ "', found '{}'"); - pub const ExpectedEqOrSemi = SingleTokenError("Expected '=' or ';', found '{}'"); - pub const ExpectedSemiOrLBrace = SingleTokenError("Expected ';' or '{{', found '{}'"); - pub const ExpectedSemiOrElse = SingleTokenError("Expected ';' or 'else', found '{}'"); - pub const ExpectedLBrace = SingleTokenError("Expected '{{', found '{}'"); - pub const ExpectedLabelOrLBrace = SingleTokenError("Expected label or '{{', found '{}'"); - pub const ExpectedColonOrRParen = SingleTokenError("Expected ':' or ')', found '{}'"); - pub const ExpectedLabelable = SingleTokenError("Expected 'while', 'for', 'inline', 'suspend', or '{{', found '{}'"); - pub const ExpectedInlinable = SingleTokenError("Expected 'while' or 'for', found '{}'"); - pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or '" ++ Token.Id.Identifier.symbol() ++ "', found '{}'"); - pub const ExpectedSliceOrRBracket = SingleTokenError("Expected ']' or '..', found '{}'"); - pub const ExpectedTypeExpr = SingleTokenError("Expected type expression, found '{}'"); - pub const ExpectedPrimaryTypeExpr = SingleTokenError("Expected primary type expression, found '{}'"); - pub const ExpectedExpr = SingleTokenError("Expected expression, found '{}'"); - pub const ExpectedPrimaryExpr = SingleTokenError("Expected primary expression, found '{}'"); - pub const ExpectedParamList = SingleTokenError("Expected parameter list, found '{}'"); - pub const ExpectedPayload = SingleTokenError("Expected loop payload, found '{}'"); - pub const ExpectedBlockOrAssignment = SingleTokenError("Expected block or assignment, found '{}'"); - pub const ExpectedBlockOrExpression = SingleTokenError("Expected block or expression, found '{}'"); - pub const ExpectedExprOrAssignment = SingleTokenError("Expected expression or assignment, found '{}'"); - pub const ExpectedPrefixExpr = SingleTokenError("Expected prefix expression, found '{}'"); - pub const ExpectedLoopExpr = SingleTokenError("Expected loop expression, found '{}'"); - pub const ExpectedDerefOrUnwrap = SingleTokenError("Expected pointer dereference or optional unwrap, found '{}'"); - pub const ExpectedSuffixOp = SingleTokenError("Expected pointer dereference, optional unwrap, or field access, found '{}'"); - pub const ExpectedBlockOrField = SingleTokenError("Expected block or field, found '{}'"); + pub const InvalidToken = SingleTokenError("Invalid token '{s}'"); + pub const ExpectedContainerMembers = SingleTokenError("Expected test, comptime, var decl, or container field, found '{s}'"); + pub const ExpectedStringLiteral = SingleTokenError("Expected string literal, found '{s}'"); + pub const ExpectedIntegerLiteral = SingleTokenError("Expected integer literal, found '{s}'"); + pub const ExpectedIdentifier = SingleTokenError("Expected identifier, found '{s}'"); + pub const ExpectedStatement = SingleTokenError("Expected statement, found '{s}'"); + pub const ExpectedVarDeclOrFn = SingleTokenError("Expected variable declaration or function, found '{s}'"); + pub const ExpectedVarDecl = SingleTokenError("Expected variable declaration, found '{s}'"); + pub const ExpectedFn = SingleTokenError("Expected function, found '{s}'"); + pub const ExpectedReturnType = SingleTokenError("Expected 'var' or return type expression, found '{s}'"); + pub const ExpectedAggregateKw = SingleTokenError("Expected '" ++ Token.Id.Keyword_struct.symbol() ++ "', '" ++ Token.Id.Keyword_union.symbol() ++ "', '" ++ Token.Id.Keyword_enum.symbol() ++ "', or '" ++ Token.Id.Keyword_opaque.symbol() ++ "', found '{s}'"); + pub const ExpectedEqOrSemi = SingleTokenError("Expected '=' or ';', found '{s}'"); + pub const ExpectedSemiOrLBrace = SingleTokenError("Expected ';' or '{{', found '{s}'"); + pub const ExpectedSemiOrElse = SingleTokenError("Expected ';' or 'else', found '{s}'"); + pub const ExpectedLBrace = SingleTokenError("Expected '{{', found '{s}'"); + pub const ExpectedLabelOrLBrace = SingleTokenError("Expected label or '{{', found '{s}'"); + pub const ExpectedColonOrRParen = SingleTokenError("Expected ':' or ')', found '{s}'"); + pub const ExpectedLabelable = SingleTokenError("Expected 'while', 'for', 'inline', 'suspend', or '{{', found '{s}'"); + pub const ExpectedInlinable = SingleTokenError("Expected 'while' or 'for', found '{s}'"); + pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or '" ++ Token.Id.Identifier.symbol() ++ "', found '{s}'"); + pub const ExpectedSliceOrRBracket = SingleTokenError("Expected ']' or '..', found '{s}'"); + pub const ExpectedTypeExpr = SingleTokenError("Expected type expression, found '{s}'"); + pub const ExpectedPrimaryTypeExpr = SingleTokenError("Expected primary type expression, found '{s}'"); + pub const ExpectedExpr = SingleTokenError("Expected expression, found '{s}'"); + pub const ExpectedPrimaryExpr = SingleTokenError("Expected primary expression, found '{s}'"); + pub const ExpectedParamList = SingleTokenError("Expected parameter list, found '{s}'"); + pub const ExpectedPayload = SingleTokenError("Expected loop payload, found '{s}'"); + pub const ExpectedBlockOrAssignment = SingleTokenError("Expected block or assignment, found '{s}'"); + pub const ExpectedBlockOrExpression = SingleTokenError("Expected block or expression, found '{s}'"); + pub const ExpectedExprOrAssignment = SingleTokenError("Expected expression or assignment, found '{s}'"); + pub const ExpectedPrefixExpr = SingleTokenError("Expected prefix expression, found '{s}'"); + pub const ExpectedLoopExpr = SingleTokenError("Expected loop expression, found '{s}'"); + pub const ExpectedDerefOrUnwrap = SingleTokenError("Expected pointer dereference or optional unwrap, found '{s}'"); + pub const ExpectedSuffixOp = SingleTokenError("Expected pointer dereference, optional unwrap, or field access, found '{s}'"); + pub const ExpectedBlockOrField = SingleTokenError("Expected block or field, found '{s}'"); pub const ExpectedParamType = SimpleError("Expected parameter type"); pub const ExpectedPubItem = SimpleError("Expected function or variable declaration after pub"); @@ -332,7 +332,7 @@ pub const Error = union(enum) { node: *Node, pub fn render(self: *const ExpectedCall, tokens: []const Token.Id, stream: anytype) !void { - return stream.print("expected " ++ @tagName(Node.Tag.Call) ++ ", found {}", .{ + return stream.print("expected " ++ @tagName(Node.Tag.Call) ++ ", found {s}", .{ @tagName(self.node.tag), }); } @@ -343,7 +343,7 @@ pub const Error = union(enum) { pub fn render(self: *const ExpectedCallOrFnProto, tokens: []const Token.Id, stream: anytype) !void { return stream.print("expected " ++ @tagName(Node.Tag.Call) ++ " or " ++ - @tagName(Node.Tag.FnProto) ++ ", found {}", .{@tagName(self.node.tag)}); + @tagName(Node.Tag.FnProto) ++ ", found {s}", .{@tagName(self.node.tag)}); } }; @@ -355,11 +355,11 @@ pub const Error = union(enum) { const found_token = tokens[self.token]; switch (found_token) { .Invalid => { - return stream.print("expected '{}', found invalid bytes", .{self.expected_id.symbol()}); + return stream.print("expected '{s}', found invalid bytes", .{self.expected_id.symbol()}); }, else => { const token_name = found_token.symbol(); - return stream.print("expected '{}', found '{}'", .{ self.expected_id.symbol(), token_name }); + return stream.print("expected '{s}', found '{s}'", .{ self.expected_id.symbol(), token_name }); }, } } @@ -371,7 +371,7 @@ pub const Error = union(enum) { pub fn render(self: *const ExpectedCommaOrEnd, tokens: []const Token.Id, stream: anytype) !void { const actual_token = tokens[self.token]; - return stream.print("expected ',' or '{}', found '{}'", .{ + return stream.print("expected ',' or '{s}', found '{s}'", .{ self.end_id.symbol(), actual_token.symbol(), }); @@ -843,7 +843,7 @@ pub const Node = struct { std.debug.warn(" ", .{}); } } - std.debug.warn("{}\n", .{@tagName(self.tag)}); + std.debug.warn("{s}\n", .{@tagName(self.tag)}); var child_i: usize = 0; while (self.iterate(child_i)) |child| : (child_i += 1) { @@ -1418,7 +1418,7 @@ pub const Node = struct { @alignOf(ParamDecl), @ptrCast([*]const u8, self) + @sizeOf(FnProto) + @sizeOf(ParamDecl) * self.params_len, ); - std.debug.print("{*} flags: {b} name_token: {} {*} params_len: {}\n", .{ + std.debug.print("{*} flags: {b} name_token: {s} {*} params_len: {d}\n", .{ self, self.trailer_flags.bits, self.getNameToken(), diff --git a/lib/std/zig/cross_target.zig b/lib/std/zig/cross_target.zig index e00f83e422..060dd83caf 100644 --- a/lib/std/zig/cross_target.zig +++ b/lib/std/zig/cross_target.zig @@ -519,7 +519,7 @@ pub const CrossTarget = struct { var result = std.ArrayList(u8).init(allocator); defer result.deinit(); - try result.outStream().print("{}-{}", .{ arch_name, os_name }); + try result.outStream().print("{s}-{s}", .{ arch_name, os_name }); // The zig target syntax does not allow specifying a max os version with no min, so // if either are present, we need the min. @@ -539,9 +539,9 @@ pub const CrossTarget = struct { } if (self.glibc_version) |v| { - try result.outStream().print("-{}.{}", .{ @tagName(self.getAbi()), v }); + try result.outStream().print("-{s}.{}", .{ @tagName(self.getAbi()), v }); } else if (self.abi) |abi| { - try result.outStream().print("-{}", .{@tagName(abi)}); + try result.outStream().print("-{s}", .{@tagName(abi)}); } return result.toOwnedSlice(); @@ -595,7 +595,7 @@ pub const CrossTarget = struct { .Dynamic => "", }; - return std.fmt.allocPrint(allocator, "{}-{}{}", .{ arch, os, static_suffix }); + return std.fmt.allocPrint(allocator, "{s}-{s}{s}", .{ arch, os, static_suffix }); } pub const Executor = union(enum) { @@ -790,7 +790,7 @@ test "CrossTarget.parse" { var buf: [256]u8 = undefined; const triple = std.fmt.bufPrint( buf[0..], - "native-native-{}.2.1.1", + "native-native-{s}.2.1.1", .{@tagName(std.Target.current.abi)}, ) catch unreachable; diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index 2879f2652b..63d04f9a80 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -3742,9 +3742,9 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b for (tree.errors) |*parse_error| { const token = tree.token_locs[parse_error.loc()]; const loc = tree.tokenLocation(0, parse_error.loc()); - try stderr.print("(memory buffer):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 }); + try stderr.print("(memory buffer):{d}:{d}: error: ", .{ loc.line + 1, loc.column + 1 }); try tree.renderError(parse_error, stderr); - try stderr.print("\n{}\n", .{source[loc.line_start..loc.line_end]}); + try stderr.print("\n{s}\n", .{source[loc.line_start..loc.line_end]}); { var i: usize = 0; while (i < loc.column) : (i += 1) { @@ -3800,7 +3800,7 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { error.OutOfMemory => { if (failing_allocator.allocated_bytes != failing_allocator.freed_bytes) { warn( - "\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n", + "\nfail_index: {d}/{d}\nallocated bytes: {d}\nfreed bytes: {d}\nallocations: {d}\ndeallocations: {d}\n", .{ fail_index, needed_alloc_count, diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index b8b0d8c1f1..6931b19250 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -41,7 +41,7 @@ fn renderRoot( for (tree.token_ids) |token_id, i| { if (token_id != .LineComment) break; const token_loc = tree.token_locs[i]; - try ais.writer().print("{}\n", .{mem.trimRight(u8, tree.tokenSliceLoc(token_loc), " ")}); + try ais.writer().print("{s}\n", .{mem.trimRight(u8, tree.tokenSliceLoc(token_loc), " ")}); const next_token = tree.token_locs[i + 1]; const loc = tree.tokenLocationLoc(token_loc.end, next_token); if (loc.line >= 2) { diff --git a/lib/std/zig/system.zig b/lib/std/zig/system.zig index 09fc15c8ba..a052c81a7d 100644 --- a/lib/std/zig/system.zig +++ b/lib/std/zig/system.zig @@ -51,7 +51,7 @@ pub const NativePaths = struct { }; try self.addIncludeDir(include_path); } else { - try self.addWarningFmt("Unrecognized C flag from NIX_CFLAGS_COMPILE: {}", .{word}); + try self.addWarningFmt("Unrecognized C flag from NIX_CFLAGS_COMPILE: {s}", .{word}); break; } } @@ -77,7 +77,7 @@ pub const NativePaths = struct { const lib_path = word[2..]; try self.addLibDir(lib_path); } else { - try self.addWarningFmt("Unrecognized C flag from NIX_LDFLAGS: {}", .{word}); + try self.addWarningFmt("Unrecognized C flag from NIX_LDFLAGS: {s}", .{word}); break; } } @@ -113,22 +113,22 @@ pub const NativePaths = struct { // TODO: some of these are suspect and should only be added on some systems. audit needed. try self.addIncludeDir("/usr/local/include"); - try self.addLibDirFmt("/usr/local/lib{}", .{qual}); + try self.addLibDirFmt("/usr/local/lib{d}", .{qual}); try self.addLibDir("/usr/local/lib"); - try self.addIncludeDirFmt("/usr/include/{}", .{triple}); - try self.addLibDirFmt("/usr/lib/{}", .{triple}); + try self.addIncludeDirFmt("/usr/include/{s}", .{triple}); + try self.addLibDirFmt("/usr/lib/{s}", .{triple}); try self.addIncludeDir("/usr/include"); - try self.addLibDirFmt("/lib{}", .{qual}); + try self.addLibDirFmt("/lib{d}", .{qual}); try self.addLibDir("/lib"); - try self.addLibDirFmt("/usr/lib{}", .{qual}); + try self.addLibDirFmt("/usr/lib{d}", .{qual}); try self.addLibDir("/usr/lib"); // example: on a 64-bit debian-based linux distro, with zlib installed from apt: // zlib.h is in /usr/include (added above) // libz.so.1 is in /lib/x86_64-linux-gnu (added here) - try self.addLibDirFmt("/lib/{}", .{triple}); + try self.addLibDirFmt("/lib/{s}", .{triple}); } return self; diff --git a/lib/std/zig/system/macos.zig b/lib/std/zig/system/macos.zig index fbc0b5149b..7c4e255cc5 100644 --- a/lib/std/zig/system/macos.zig +++ b/lib/std/zig/system/macos.zig @@ -450,7 +450,7 @@ test "version_from_build" { for (known) |pair| { var buf: [32]u8 = undefined; const ver = try version_from_build(pair[0]); - const sver = try std.fmt.bufPrint(buf[0..], "{}.{}.{}", .{ ver.major, ver.minor, ver.patch }); + const sver = try std.fmt.bufPrint(buf[0..], "{d}.{d}.{d}", .{ ver.major, ver.minor, ver.patch }); std.testing.expect(std.mem.eql(u8, sver, pair[1])); } } @@ -468,7 +468,7 @@ pub fn getSDKPath(allocator: *mem.Allocator) ![]u8 { allocator.free(result.stdout); } if (result.stderr.len != 0) { - std.log.err("unexpected 'xcrun --show-sdk-path' stderr: {}", .{result.stderr}); + std.log.err("unexpected 'xcrun --show-sdk-path' stderr: {s}", .{result.stderr}); } if (result.term.Exited != 0) { return error.ProcessTerminated; diff --git a/lib/std/zig/tokenizer.zig b/lib/std/zig/tokenizer.zig index 4e50b55816..dcbf717638 100644 --- a/lib/std/zig/tokenizer.zig +++ b/lib/std/zig/tokenizer.zig @@ -334,7 +334,7 @@ pub const Tokenizer = struct { /// For debugging purposes pub fn dump(self: *Tokenizer, token: *const Token) void { - std.debug.warn("{} \"{}\"\n", .{ @tagName(token.id), self.buffer[token.start..token.end] }); + std.debug.warn("{s} \"{s}\"\n", .{ @tagName(token.id), self.buffer[token.start..token.end] }); } pub fn init(buffer: []const u8) Tokenizer { @@ -2046,7 +2046,7 @@ fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void { for (expected_tokens) |expected_token_id| { const token = tokenizer.next(); if (token.id != expected_token_id) { - std.debug.panic("expected {}, found {}\n", .{ @tagName(expected_token_id), @tagName(token.id) }); + std.debug.panic("expected {s}, found {s}\n", .{ @tagName(expected_token_id), @tagName(token.id) }); } } const last_token = tokenizer.next(); diff --git a/src/Cache.zig b/src/Cache.zig index 3d33226f27..03a0d61157 100644 --- a/src/Cache.zig +++ b/src/Cache.zig @@ -549,7 +549,7 @@ pub const Manifest = struct { .target, .target_must_resolve, .prereq => {}, else => |err| { try err.printError(error_buf.writer()); - std.log.err("failed parsing {}: {}", .{ dep_file_basename, error_buf.items }); + std.log.err("failed parsing {s}: {s}", .{ dep_file_basename, error_buf.items }); return error.InvalidDepFile; }, } @@ -561,7 +561,7 @@ pub const Manifest = struct { .prereq => |bytes| try self.addFilePost(bytes), else => |err| { try err.printError(error_buf.writer()); - std.log.err("failed parsing {}: {}", .{ dep_file_basename, error_buf.items }); + std.log.err("failed parsing {s}: {s}", .{ dep_file_basename, error_buf.items }); return error.InvalidDepFile; }, } diff --git a/src/Compilation.zig b/src/Compilation.zig index 33376d46d2..de115b9b40 100644 --- a/src/Compilation.zig +++ b/src/Compilation.zig @@ -1475,7 +1475,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor // lifetime annotations in the ZIR. var decl_arena = decl.typed_value.most_recent.arena.?.promote(module.gpa); defer decl.typed_value.most_recent.arena.?.* = decl_arena.state; - log.debug("analyze liveness of {}\n", .{decl.name}); + log.debug("analyze liveness of {s}\n", .{decl.name}); try liveness.analyze(module.gpa, &decl_arena.allocator, func.analysis.success); } @@ -1492,7 +1492,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor module.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create( module.gpa, decl.src(), - "unable to codegen: {}", + "unable to codegen: {s}", .{@errorName(err)}, )); decl.analysis = .codegen_failure_retryable; @@ -1512,7 +1512,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor module.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create( module.gpa, decl.src(), - "unable to generate C header: {}", + "unable to generate C header: {s}", .{@errorName(err)}, )); decl.analysis = .codegen_failure_retryable; @@ -1535,7 +1535,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor module.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create( module.gpa, decl.src(), - "unable to update line number: {}", + "unable to update line number: {s}", .{@errorName(err)}, )); decl.analysis = .codegen_failure_retryable; @@ -1544,56 +1544,56 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor .glibc_crt_file => |crt_file| { glibc.buildCRTFile(self, crt_file) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build glibc CRT file: {}", .{@errorName(err)}); + fatal("unable to build glibc CRT file: {s}", .{@errorName(err)}); }; }, .glibc_shared_objects => { glibc.buildSharedObjects(self) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build glibc shared objects: {}", .{@errorName(err)}); + fatal("unable to build glibc shared objects: {s}", .{@errorName(err)}); }; }, .musl_crt_file => |crt_file| { musl.buildCRTFile(self, crt_file) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build musl CRT file: {}", .{@errorName(err)}); + fatal("unable to build musl CRT file: {s}", .{@errorName(err)}); }; }, .mingw_crt_file => |crt_file| { mingw.buildCRTFile(self, crt_file) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build mingw-w64 CRT file: {}", .{@errorName(err)}); + fatal("unable to build mingw-w64 CRT file: {s}", .{@errorName(err)}); }; }, .windows_import_lib => |index| { const link_lib = self.bin_file.options.system_libs.items()[index].key; mingw.buildImportLib(self, link_lib) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to generate DLL import .lib file: {}", .{@errorName(err)}); + fatal("unable to generate DLL import .lib file: {s}", .{@errorName(err)}); }; }, .libunwind => { libunwind.buildStaticLib(self) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build libunwind: {}", .{@errorName(err)}); + fatal("unable to build libunwind: {s}", .{@errorName(err)}); }; }, .libcxx => { libcxx.buildLibCXX(self) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build libcxx: {}", .{@errorName(err)}); + fatal("unable to build libcxx: {s}", .{@errorName(err)}); }; }, .libcxxabi => { libcxx.buildLibCXXABI(self) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build libcxxabi: {}", .{@errorName(err)}); + fatal("unable to build libcxxabi: {s}", .{@errorName(err)}); }; }, .libtsan => { libtsan.buildTsan(self) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build TSAN library: {}", .{@errorName(err)}); + fatal("unable to build TSAN library: {s}", .{@errorName(err)}); }; }, .compiler_rt_lib => { @@ -1611,20 +1611,20 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor .libssp => { self.buildOutputFromZig("ssp.zig", .Lib, &self.libssp_static_lib) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build libssp: {}", .{@errorName(err)}); + fatal("unable to build libssp: {s}", .{@errorName(err)}); }; }, .zig_libc => { self.buildOutputFromZig("c.zig", .Lib, &self.libc_static_lib) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to build zig's multitarget libc: {}", .{@errorName(err)}); + fatal("unable to build zig's multitarget libc: {s}", .{@errorName(err)}); }; }, .generate_builtin_zig => { // This Job is only queued up if there is a zig module. self.updateBuiltinZigFile(self.bin_file.options.module.?) catch |err| { // TODO Expose this as a normal compile error rather than crashing here. - fatal("unable to update builtin.zig file: {}", .{@errorName(err)}); + fatal("unable to update builtin.zig file: {s}", .{@errorName(err)}); }; }, .stage1_module => { @@ -1704,11 +1704,11 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult { const out_h_path = try comp.local_cache_directory.join(arena, &[_][]const u8{ tmp_dir_sub_path, cimport_basename, }); - const out_dep_path = try std.fmt.allocPrint(arena, "{}.d", .{out_h_path}); + const out_dep_path = try std.fmt.allocPrint(arena, "{s}.d", .{out_h_path}); try zig_cache_tmp_dir.writeFile(cimport_basename, c_src); if (comp.verbose_cimport) { - log.info("C import source: {}", .{out_h_path}); + log.info("C import source: {s}", .{out_h_path}); } var argv = std.ArrayList([]const u8).init(comp.gpa); @@ -1755,7 +1755,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult { defer tree.deinit(); if (comp.verbose_cimport) { - log.info("C import .d file: {}", .{out_dep_path}); + log.info("C import .d file: {s}", .{out_dep_path}); } const dep_basename = std.fs.path.basename(out_dep_path); @@ -1775,7 +1775,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult { try bos.flush(); man.writeManifest() catch |err| { - log.warn("failed to write cache manifest for C import: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest for C import: {s}", .{@errorName(err)}); }; break :digest digest; @@ -1785,7 +1785,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult { "o", &digest, cimport_zig_basename, }); if (comp.verbose_cimport) { - log.info("C import output: {}\n", .{out_zig_path}); + log.info("C import output: {s}\n", .{out_zig_path}); } return CImportResult{ .out_zig_path = out_zig_path, @@ -1946,7 +1946,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_comp_progress_node: * child.stderr_behavior = .Inherit; const term = child.spawnAndWait() catch |err| { - return comp.failCObj(c_object, "unable to spawn {}: {}", .{ argv.items[0], @errorName(err) }); + return comp.failCObj(c_object, "unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) }); }; switch (term) { .Exited => |code| { @@ -1974,7 +1974,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_comp_progress_node: * const stderr = try stderr_reader.readAllAlloc(arena, 10 * 1024 * 1024); const term = child.wait() catch |err| { - return comp.failCObj(c_object, "unable to spawn {}: {}", .{ argv.items[0], @errorName(err) }); + return comp.failCObj(c_object, "unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) }); }; switch (term) { @@ -1982,12 +1982,12 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_comp_progress_node: * if (code != 0) { // TODO parse clang stderr and turn it into an error message // and then call failCObjWithOwnedErrorMsg - log.err("clang failed with stderr: {}", .{stderr}); - return comp.failCObj(c_object, "clang exited with code {}", .{code}); + log.err("clang failed with stderr: {s}", .{stderr}); + return comp.failCObj(c_object, "clang exited with code {d}", .{code}); } }, else => { - log.err("clang terminated with stderr: {}", .{stderr}); + log.err("clang terminated with stderr: {s}", .{stderr}); return comp.failCObj(c_object, "clang terminated unexpectedly", .{}); }, } @@ -1999,7 +1999,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_comp_progress_node: * try man.addDepFilePost(zig_cache_tmp_dir, dep_basename); // Just to save disk space, we delete the file because it is never needed again. zig_cache_tmp_dir.deleteFile(dep_basename) catch |err| { - log.warn("failed to delete '{}': {}", .{ dep_file_path, @errorName(err) }); + log.warn("failed to delete '{s}': {s}", .{ dep_file_path, @errorName(err) }); }; } @@ -2015,7 +2015,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_comp_progress_node: * try std.fs.rename(zig_cache_tmp_dir, tmp_basename, o_dir, o_basename); man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when compiling '{}': {}", .{ c_object.src.src_path, @errorName(err) }); + log.warn("failed to write cache manifest when compiling '{s}': {s}", .{ c_object.src.src_path, @errorName(err) }); }; break :blk digest; }; @@ -2034,7 +2034,7 @@ pub fn tmpFilePath(comp: *Compilation, arena: *Allocator, suffix: []const u8) er const s = std.fs.path.sep_str; const rand_int = std.crypto.random.int(u64); if (comp.local_cache_directory.path) |p| { - return std.fmt.allocPrint(arena, "{}" ++ s ++ "tmp" ++ s ++ "{x}-{s}", .{ p, rand_int, suffix }); + return std.fmt.allocPrint(arena, "{s}" ++ s ++ "tmp" ++ s ++ "{x}-{s}", .{ p, rand_int, suffix }); } else { return std.fmt.allocPrint(arena, "tmp" ++ s ++ "{x}-{s}", .{ rand_int, suffix }); } @@ -2144,7 +2144,7 @@ pub fn addCCArgs( } const mcmodel = comp.bin_file.options.machine_code_model; if (mcmodel != .default) { - try argv.append(try std.fmt.allocPrint(arena, "-mcmodel={}", .{@tagName(mcmodel)})); + try argv.append(try std.fmt.allocPrint(arena, "-mcmodel={s}", .{@tagName(mcmodel)})); } switch (target.os.tag) { @@ -2497,22 +2497,22 @@ fn detectLibCIncludeDirs( const s = std.fs.path.sep_str; const arch_include_dir = try std.fmt.allocPrint( arena, - "{}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{}-{}-{}", + "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-{s}-{s}", .{ zig_lib_dir, arch_name, os_name, abi_name }, ); const generic_include_dir = try std.fmt.allocPrint( arena, - "{}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "generic-{}", + "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "generic-{s}", .{ zig_lib_dir, generic_name }, ); const arch_os_include_dir = try std.fmt.allocPrint( arena, - "{}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{}-{}-any", + "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-{s}-any", .{ zig_lib_dir, @tagName(target.cpu.arch), os_name }, ); const generic_os_include_dir = try std.fmt.allocPrint( arena, - "{}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "any-{}-any", + "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "any-{s}-any", .{ zig_lib_dir, os_name }, ); @@ -2631,9 +2631,9 @@ fn updateBuiltinZigFile(comp: *Compilation, mod: *Module) !void { pub fn dump_argv(argv: []const []const u8) void { for (argv[0 .. argv.len - 1]) |arg| { - std.debug.print("{} ", .{arg}); + std.debug.print("{s} ", .{arg}); } - std.debug.print("{}\n", .{argv[argv.len - 1]}); + std.debug.print("{s}\n", .{argv[argv.len - 1]}); } pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 { @@ -2653,15 +2653,15 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 \\pub const arch = Target.current.cpu.arch; \\/// Deprecated \\pub const endian = Target.current.cpu.arch.endian(); - \\pub const output_mode = OutputMode.{}; - \\pub const link_mode = LinkMode.{}; + \\pub const output_mode = OutputMode.{z}; + \\pub const link_mode = LinkMode.{z}; \\pub const is_test = {}; \\pub const single_threaded = {}; - \\pub const abi = Abi.{}; + \\pub const abi = Abi.{z}; \\pub const cpu: Cpu = Cpu{{ - \\ .arch = .{}, - \\ .model = &Target.{}.cpu.{}, - \\ .features = Target.{}.featureSet(&[_]Target.{}.Feature{{ + \\ .arch = .{z}, + \\ .model = &Target.{z}.cpu.{z}, + \\ .features = Target.{z}.featureSet(&[_]Target.{z}.Feature{{ \\ , .{ @tagName(comp.bin_file.options.output_mode), @@ -2692,7 +2692,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 \\ }}), \\}}; \\pub const os = Os{{ - \\ .tag = .{}, + \\ .tag = .{z}, \\ .version_range = .{{ , .{@tagName(target.os.tag)}, @@ -2778,8 +2778,8 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 (comp.bin_file.options.skip_linker_dependencies and comp.bin_file.options.parent_compilation_link_libc); try buffer.writer().print( - \\pub const object_format = ObjectFormat.{}; - \\pub const mode = Mode.{}; + \\pub const object_format = ObjectFormat.{z}; + \\pub const mode = Mode.{z}; \\pub const link_libc = {}; \\pub const link_libcpp = {}; \\pub const have_error_return_tracing = {}; @@ -2787,7 +2787,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 \\pub const position_independent_code = {}; \\pub const position_independent_executable = {}; \\pub const strip_debug_info = {}; - \\pub const code_model = CodeModel.{}; + \\pub const code_model = CodeModel.{z}; \\ , .{ @tagName(comp.bin_file.options.object_format), @@ -3013,7 +3013,7 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { - log.debug("stage1 {} new_digest={} error: {}", .{ mod.root_pkg.root_src_path, digest, @errorName(err) }); + log.debug("stage1 {s} new_digest={} error: {s}", .{ mod.root_pkg.root_src_path, digest, @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; @@ -3021,7 +3021,7 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node if (!mem.eql(u8, prev_digest[0..digest.len], &digest)) break :hit; - log.debug("stage1 {} digest={} match - skipping invocation", .{ mod.root_pkg.root_src_path, digest }); + log.debug("stage1 {s} digest={} match - skipping invocation", .{ mod.root_pkg.root_src_path, digest }); var flags_bytes: [1]u8 = undefined; _ = std.fmt.hexToBytes(&flags_bytes, prev_digest[digest.len..]) catch { log.warn("bad cache stage1 digest: '{s}'", .{prev_digest}); @@ -3044,7 +3044,7 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node mod.stage1_flags = @bitCast(@TypeOf(mod.stage1_flags), flags_bytes[0]); return; } - log.debug("stage1 {} prev_digest={} new_digest={}", .{ mod.root_pkg.root_src_path, prev_digest, digest }); + log.debug("stage1 {s} prev_digest={} new_digest={}", .{ mod.root_pkg.root_src_path, prev_digest, digest }); man.unhit(prev_hash_state, input_file_count); } @@ -3189,7 +3189,7 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node // Update the small file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. const stage1_flags_byte = @bitCast(u8, mod.stage1_flags); - log.debug("stage1 {} final digest={} flags={x}", .{ + log.debug("stage1 {s} final digest={} flags={x}", .{ mod.root_pkg.root_src_path, digest, stage1_flags_byte, }); var digest_plus_flags: [digest.len + 2]u8 = undefined; @@ -3202,11 +3202,11 @@ fn updateStage1Module(comp: *Compilation, main_progress_node: *std.Progress.Node digest_plus_flags, stage1_flags_byte, mod.stage1_flags.have_winmain_crt_startup, }); Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest_plus_flags) catch |err| { - log.warn("failed to save stage1 hash digest file: {}", .{@errorName(err)}); + log.warn("failed to save stage1 hash digest file: {s}", .{@errorName(err)}); }; // Failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when linking: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. diff --git a/src/DepTokenizer.zig b/src/DepTokenizer.zig index 99db6e4b3c..0872513b51 100644 --- a/src/DepTokenizer.zig +++ b/src/DepTokenizer.zig @@ -366,14 +366,14 @@ pub const Token = union(enum) { .incomplete_quoted_prerequisite, .incomplete_target, => |index_and_bytes| { - try writer.print("{} '", .{self.errStr()}); + try writer.print("{s} '", .{self.errStr()}); if (self == .incomplete_target) { const tmp = Token{ .target_must_resolve = index_and_bytes.bytes }; try tmp.resolve(writer); } else { try printCharValues(writer, index_and_bytes.bytes); } - try writer.print("' at position {}", .{index_and_bytes.index}); + try writer.print("' at position {d}", .{index_and_bytes.index}); }, .invalid_target, .bad_target_escape, @@ -383,7 +383,7 @@ pub const Token = union(enum) { => |index_and_char| { try writer.writeAll("illegal char "); try printUnderstandableChar(writer, index_and_char.char); - try writer.print(" at position {}: {}", .{ index_and_char.index, self.errStr() }); + try writer.print(" at position {d}: {s}", .{ index_and_char.index, self.errStr() }); }, } } @@ -943,7 +943,7 @@ fn printSection(out: anytype, label: []const u8, bytes: []const u8) !void { fn printLabel(out: anytype, label: []const u8, bytes: []const u8) !void { var buf: [80]u8 = undefined; - var text = try std.fmt.bufPrint(buf[0..], "{} {} bytes ", .{ label, bytes.len }); + var text = try std.fmt.bufPrint(buf[0..], "{s} {d} bytes ", .{ label, bytes.len }); try out.writeAll(text); var i: usize = text.len; const end = 79; diff --git a/src/Module.zig b/src/Module.zig index 5ea78d06d1..d1719059c4 100644 --- a/src/Module.zig +++ b/src/Module.zig @@ -248,7 +248,7 @@ pub const Decl = struct { pub fn dump(self: *Decl) void { const loc = std.zig.findLineColumn(self.scope.source.bytes, self.src); - std.debug.print("{}:{}:{} name={} status={}", .{ + std.debug.print("{s}:{d}:{d} name={s} status={s}", .{ self.scope.sub_file_path, loc.line + 1, loc.column + 1, @@ -308,7 +308,7 @@ pub const Fn = struct { /// For debugging purposes. pub fn dump(self: *Fn, mod: Module) void { - std.debug.print("Module.Function(name={}) ", .{self.owner_decl.name}); + std.debug.print("Module.Function(name={s}) ", .{self.owner_decl.name}); switch (self.analysis) { .queued => { std.debug.print("queued\n", .{}); @@ -632,7 +632,7 @@ pub const Scope = struct { pub fn dumpSrc(self: *File, src: usize) void { const loc = std.zig.findLineColumn(self.source.bytes, src); - std.debug.print("{}:{}:{}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 }); + std.debug.print("{s}:{d}:{d}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 }); } pub fn getSource(self: *File, module: *Module) ![:0]const u8 { @@ -730,7 +730,7 @@ pub const Scope = struct { pub fn dumpSrc(self: *ZIRModule, src: usize) void { const loc = std.zig.findLineColumn(self.source.bytes, src); - std.debug.print("{}:{}:{}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 }); + std.debug.print("{s}:{d}:{d}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 }); } pub fn getSource(self: *ZIRModule, module: *Module) ![:0]const u8 { @@ -918,7 +918,7 @@ pub fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void { .complete => return, .outdated => blk: { - log.debug("re-analyzing {}\n", .{decl.name}); + log.debug("re-analyzing {s}\n", .{decl.name}); // The exports this Decl performs will be re-discovered, so we remove them here // prior to re-analysis. @@ -953,7 +953,7 @@ pub fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void { self.failed_decls.putAssumeCapacityNoClobber(decl, try Compilation.ErrorMsg.create( self.gpa, decl.src(), - "unable to analyze: {}", + "unable to analyze: {s}", .{@errorName(err)}, )); decl.analysis = .sema_failure_retryable; @@ -1475,7 +1475,7 @@ fn getSrcModule(self: *Module, root_scope: *Scope.ZIRModule) !*zir.Module { if (zir_module.error_msg) |src_err_msg| { self.failed_files.putAssumeCapacityNoClobber( &root_scope.base, - try Compilation.ErrorMsg.create(self.gpa, src_err_msg.byte_offset, "{}", .{src_err_msg.msg}), + try Compilation.ErrorMsg.create(self.gpa, src_err_msg.byte_offset, "{s}", .{src_err_msg.msg}), ); root_scope.status = .unloaded_parse_failure; return error.AnalysisFail; @@ -1581,7 +1581,7 @@ pub fn analyzeContainer(self: *Module, container_scope: *Scope.Container) !void decl.src_index = decl_i; if (deleted_decls.remove(decl) == null) { decl.analysis = .sema_failure; - const err_msg = try Compilation.ErrorMsg.create(self.gpa, tree.token_locs[name_tok].start, "redefinition of '{}'", .{decl.name}); + const err_msg = try Compilation.ErrorMsg.create(self.gpa, tree.token_locs[name_tok].start, "redefinition of '{s}'", .{decl.name}); errdefer err_msg.destroy(self.gpa); try self.failed_decls.putNoClobber(self.gpa, decl, err_msg); } else { @@ -1623,7 +1623,7 @@ pub fn analyzeContainer(self: *Module, container_scope: *Scope.Container) !void decl.src_index = decl_i; if (deleted_decls.remove(decl) == null) { decl.analysis = .sema_failure; - const err_msg = try Compilation.ErrorMsg.create(self.gpa, name_loc.start, "redefinition of '{}'", .{decl.name}); + const err_msg = try Compilation.ErrorMsg.create(self.gpa, name_loc.start, "redefinition of '{s}'", .{decl.name}); errdefer err_msg.destroy(self.gpa); try self.failed_decls.putNoClobber(self.gpa, decl, err_msg); } else if (!srcHashEql(decl.contents_hash, contents_hash)) { @@ -1641,7 +1641,7 @@ pub fn analyzeContainer(self: *Module, container_scope: *Scope.Container) !void } } else if (src_decl.castTag(.Comptime)) |comptime_node| { const name_index = self.getNextAnonNameIndex(); - const name = try std.fmt.allocPrint(self.gpa, "__comptime_{}", .{name_index}); + const name = try std.fmt.allocPrint(self.gpa, "__comptime_{d}", .{name_index}); defer self.gpa.free(name); const name_hash = container_scope.fullyQualifiedNameHash(name); @@ -1663,7 +1663,7 @@ pub fn analyzeContainer(self: *Module, container_scope: *Scope.Container) !void // Handle explicitly deleted decls from the source code. Not to be confused // with when we delete decls because they are no longer referenced. for (deleted_decls.items()) |entry| { - log.debug("noticed '{}' deleted from source\n", .{entry.key.name}); + log.debug("noticed '{s}' deleted from source\n", .{entry.key.name}); try self.deleteDecl(entry.key); } } @@ -1716,7 +1716,7 @@ pub fn analyzeRootZIRModule(self: *Module, root_scope: *Scope.ZIRModule) !void { // Handle explicitly deleted decls from the source code. Not to be confused // with when we delete decls because they are no longer referenced. for (deleted_decls.items()) |entry| { - log.debug("noticed '{}' deleted from source\n", .{entry.key.name}); + log.debug("noticed '{s}' deleted from source\n", .{entry.key.name}); try self.deleteDecl(entry.key); } } @@ -1728,7 +1728,7 @@ pub fn deleteDecl(self: *Module, decl: *Decl) !void { // not be present in the set, and this does nothing. decl.scope.removeDecl(decl); - log.debug("deleting decl '{}'\n", .{decl.name}); + log.debug("deleting decl '{s}'\n", .{decl.name}); const name_hash = decl.fullyQualifiedNameHash(); self.decl_table.removeAssertDiscard(name_hash); // Remove itself from its dependencies, because we are about to destroy the decl pointer. @@ -1819,17 +1819,17 @@ pub fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void { const fn_zir = func.analysis.queued; defer fn_zir.arena.promote(self.gpa).deinit(); func.analysis = .{ .in_progress = {} }; - log.debug("set {} to in_progress\n", .{decl.name}); + log.debug("set {s} to in_progress\n", .{decl.name}); try zir_sema.analyzeBody(self, &inner_block.base, fn_zir.body); const instructions = try arena.allocator.dupe(*Inst, inner_block.instructions.items); func.analysis = .{ .success = .{ .instructions = instructions } }; - log.debug("set {} to success\n", .{decl.name}); + log.debug("set {s} to success\n", .{decl.name}); } fn markOutdatedDecl(self: *Module, decl: *Decl) !void { - log.debug("mark {} outdated\n", .{decl.name}); + log.debug("mark {s} outdated\n", .{decl.name}); try self.comp.work_queue.writeItem(.{ .analyze_decl = decl }); if (self.failed_decls.remove(decl)) |entry| { entry.value.destroy(self.gpa); @@ -1991,7 +1991,7 @@ pub fn analyzeExport( self.failed_exports.putAssumeCapacityNoClobber(new_export, try Compilation.ErrorMsg.create( self.gpa, src, - "exported symbol collision: {}", + "exported symbol collision: {s}", .{symbol_name}, )); // TODO: add a note @@ -2007,7 +2007,7 @@ pub fn analyzeExport( self.failed_exports.putAssumeCapacityNoClobber(new_export, try Compilation.ErrorMsg.create( self.gpa, src, - "unable to export: {}", + "unable to export: {s}", .{@errorName(err)}, )); new_export.status = .failed_retryable; @@ -2277,7 +2277,7 @@ pub fn createAnonymousDecl( ) !*Decl { const name_index = self.getNextAnonNameIndex(); const scope_decl = scope.decl().?; - const name = try std.fmt.allocPrint(self.gpa, "{}__anon_{}", .{ scope_decl.name, name_index }); + const name = try std.fmt.allocPrint(self.gpa, "{s}__anon_{d}", .{ scope_decl.name, name_index }); defer self.gpa.free(name); const name_hash = scope.namespace().fullyQualifiedNameHash(name); const src_hash: std.zig.SrcHash = undefined; @@ -2384,7 +2384,7 @@ pub fn analyzeDeref(self: *Module, scope: *Scope, src: usize, ptr: *Inst, ptr_sr pub fn analyzeDeclRefByName(self: *Module, scope: *Scope, src: usize, decl_name: []const u8) InnerError!*Inst { const decl = self.lookupDeclName(scope, decl_name) orelse - return self.fail(scope, src, "decl '{}' not found", .{decl_name}); + return self.fail(scope, src, "decl '{s}' not found", .{decl_name}); return self.analyzeDeclRef(scope, src, decl); } @@ -2555,7 +2555,7 @@ pub fn cmpNumeric( if (lhs_ty_tag == .Vector and rhs_ty_tag == .Vector) { if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) { - return self.fail(scope, src, "vector length mismatch: {} and {}", .{ + return self.fail(scope, src, "vector length mismatch: {d} and {d}", .{ lhs.ty.arrayLen(), rhs.ty.arrayLen(), }); @@ -2700,7 +2700,7 @@ pub fn cmpNumeric( const dest_type = if (dest_float_type) |ft| ft else blk: { const max_bits = std.math.max(lhs_bits, rhs_bits); const casted_bits = std.math.cast(u16, max_bits) catch |err| switch (err) { - error.Overflow => return self.fail(scope, src, "{} exceeds maximum integer bit count", .{max_bits}), + error.Overflow => return self.fail(scope, src, "{d} exceeds maximum integer bit count", .{max_bits}), }; break :blk try self.makeIntType(scope, dest_int_is_signed, casted_bits); }; @@ -3319,7 +3319,7 @@ pub fn dumpInst(self: *Module, scope: *Scope, inst: *Inst) void { const source = zir_module.getSource(self) catch @panic("dumpInst failed to get source"); const loc = std.zig.findLineColumn(source, inst.src); if (inst.tag == .constant) { - std.debug.print("constant ty={} val={} src={}:{}:{}\n", .{ + std.debug.print("constant ty={} val={} src={s}:{d}:{d}\n", .{ inst.ty, inst.castTag(.constant).?.val, zir_module.subFilePath(), @@ -3327,7 +3327,7 @@ pub fn dumpInst(self: *Module, scope: *Scope, inst: *Inst) void { loc.column + 1, }); } else if (inst.deaths == 0) { - std.debug.print("{} ty={} src={}:{}:{}\n", .{ + std.debug.print("{s} ty={} src={s}:{d}:{d}\n", .{ @tagName(inst.tag), inst.ty, zir_module.subFilePath(), @@ -3335,7 +3335,7 @@ pub fn dumpInst(self: *Module, scope: *Scope, inst: *Inst) void { loc.column + 1, }); } else { - std.debug.print("{} ty={} deaths={b} src={}:{}:{}\n", .{ + std.debug.print("{s} ty={} deaths={b} src={s}:{d}:{d}\n", .{ @tagName(inst.tag), inst.ty, inst.deaths, diff --git a/src/astgen.zig b/src/astgen.zig index 3670cb260e..a50fa026ca 100644 --- a/src/astgen.zig +++ b/src/astgen.zig @@ -385,7 +385,7 @@ fn breakExpr(mod: *Module, parent_scope: *Scope, node: *ast.Node.ControlFlowExpr .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, else => if (node.getLabel()) |break_label| { const label_name = try identifierTokenString(mod, parent_scope, break_label); - return mod.failTok(parent_scope, break_label, "label not found: '{}'", .{label_name}); + return mod.failTok(parent_scope, break_label, "label not found: '{s}'", .{label_name}); } else { return mod.failTok(parent_scope, src, "break expression outside loop", .{}); }, @@ -427,7 +427,7 @@ fn continueExpr(mod: *Module, parent_scope: *Scope, node: *ast.Node.ControlFlowE .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, else => if (node.getLabel()) |break_label| { const label_name = try identifierTokenString(mod, parent_scope, break_label); - return mod.failTok(parent_scope, break_label, "label not found: '{}'", .{label_name}); + return mod.failTok(parent_scope, break_label, "label not found: '{s}'", .{label_name}); } else { return mod.failTok(parent_scope, src, "continue expression outside loop", .{}); }, @@ -560,14 +560,14 @@ fn varDecl( .local_val => { const local_val = s.cast(Scope.LocalVal).?; if (mem.eql(u8, local_val.name, ident_name)) { - return mod.fail(scope, name_src, "redefinition of '{}'", .{ident_name}); + return mod.fail(scope, name_src, "redefinition of '{s}'", .{ident_name}); } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (mem.eql(u8, local_ptr.name, ident_name)) { - return mod.fail(scope, name_src, "redefinition of '{}'", .{ident_name}); + return mod.fail(scope, name_src, "redefinition of '{s}'", .{ident_name}); } s = local_ptr.parent; }, @@ -578,7 +578,7 @@ fn varDecl( // Namespace vars shadowing detection if (mod.lookupDeclName(scope, ident_name)) |_| { - return mod.fail(scope, name_src, "redefinition of '{}'", .{ident_name}); + return mod.fail(scope, name_src, "redefinition of '{s}'", .{ident_name}); } const init_node = node.getInitNode() orelse return mod.fail(scope, name_src, "variables must be initialized", .{}); @@ -1955,7 +1955,7 @@ fn identifier(mod: *Module, scope: *Scope, rl: ResultLoc, ident: *ast.Node.OneTo error.Overflow => return mod.failNode( scope, &ident.base, - "primitive integer type '{}' exceeds maximum bit width of 65535", + "primitive integer type '{s}' exceeds maximum bit width of 65535", .{ident_name}, ), error.InvalidCharacter => break :integer, @@ -2010,7 +2010,7 @@ fn identifier(mod: *Module, scope: *Scope, rl: ResultLoc, ident: *ast.Node.OneTo return rlWrapPtr(mod, scope, rl, try addZIRInst(mod, scope, src, zir.Inst.DeclValInModule, .{ .decl = decl }, .{})); } - return mod.failNode(scope, &ident.base, "use of undeclared identifier '{}'", .{ident_name}); + return mod.failNode(scope, &ident.base, "use of undeclared identifier '{s}'", .{ident_name}); } fn stringLiteral(mod: *Module, scope: *Scope, str_lit: *ast.Node.OneToken) InnerError!*zir.Inst { @@ -2204,7 +2204,7 @@ fn ensureBuiltinParamCount(mod: *Module, scope: *Scope, call: *ast.Node.BuiltinC return; const s = if (count == 1) "" else "s"; - return mod.failTok(scope, call.builtin_token, "expected {} parameter{}, found {}", .{ count, s, call.params_len }); + return mod.failTok(scope, call.builtin_token, "expected {d} parameter{s}, found {d}", .{ count, s, call.params_len }); } fn simpleCast( @@ -2383,7 +2383,7 @@ fn builtinCall(mod: *Module, scope: *Scope, rl: ResultLoc, call: *ast.Node.Built } else if (mem.eql(u8, builtin_name, "@compileError")) { return compileError(mod, scope, call); } else { - return mod.failTok(scope, call.builtin_token, "invalid builtin function: '{}'", .{builtin_name}); + return mod.failTok(scope, call.builtin_token, "invalid builtin function: '{s}'", .{builtin_name}); } } diff --git a/src/codegen.zig b/src/codegen.zig index 9e6de711d4..6530b687e5 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -228,7 +228,7 @@ pub fn generateSymbol( .fail = try ErrorMsg.create( bin_file.allocator, src, - "TODO implement generateSymbol for type '{}'", + "TODO implement generateSymbol for type '{s}'", .{@tagName(t)}, ), }; @@ -2029,7 +2029,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { }); break :blk 0x84; }, - else => return self.fail(inst.base.src, "TODO implement condbr {} when condition is {}", .{ self.target.cpu.arch, @tagName(cond) }), + else => return self.fail(inst.base.src, "TODO implement condbr {s} when condition is {s}", .{ self.target.cpu.arch, @tagName(cond) }), }; self.code.appendSliceAssumeCapacity(&[_]u8{ 0x0f, opcode }); const reloc = Reloc{ .rel32 = self.code.items.len }; @@ -2376,11 +2376,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { .arm, .armeb => { for (inst.inputs) |input, i| { if (input.len < 3 or input[0] != '{' or input[input.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm input constraint: '{}'", .{input}); + return self.fail(inst.base.src, "unrecognized asm input constraint: '{s}'", .{input}); } const reg_name = input[1 .. input.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); const arg = try self.resolveInst(inst.args[i]); try self.genSetReg(inst.base.src, reg, arg); } @@ -2393,11 +2393,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { if (inst.output) |output| { if (output.len < 4 or output[0] != '=' or output[1] != '{' or output[output.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm output constraint: '{}'", .{output}); + return self.fail(inst.base.src, "unrecognized asm output constraint: '{s}'", .{output}); } const reg_name = output[2 .. output.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); return MCValue{ .register = reg }; } else { return MCValue.none; @@ -2406,11 +2406,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { .aarch64 => { for (inst.inputs) |input, i| { if (input.len < 3 or input[0] != '{' or input[input.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm input constraint: '{}'", .{input}); + return self.fail(inst.base.src, "unrecognized asm input constraint: '{s}'", .{input}); } const reg_name = input[1 .. input.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); const arg = try self.resolveInst(inst.args[i]); try self.genSetReg(inst.base.src, reg, arg); } @@ -2425,11 +2425,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { if (inst.output) |output| { if (output.len < 4 or output[0] != '=' or output[1] != '{' or output[output.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm output constraint: '{}'", .{output}); + return self.fail(inst.base.src, "unrecognized asm output constraint: '{s}'", .{output}); } const reg_name = output[2 .. output.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); return MCValue{ .register = reg }; } else { return MCValue.none; @@ -2438,11 +2438,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { .riscv64 => { for (inst.inputs) |input, i| { if (input.len < 3 or input[0] != '{' or input[input.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm input constraint: '{}'", .{input}); + return self.fail(inst.base.src, "unrecognized asm input constraint: '{s}'", .{input}); } const reg_name = input[1 .. input.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); const arg = try self.resolveInst(inst.args[i]); try self.genSetReg(inst.base.src, reg, arg); } @@ -2455,11 +2455,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { if (inst.output) |output| { if (output.len < 4 or output[0] != '=' or output[1] != '{' or output[output.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm output constraint: '{}'", .{output}); + return self.fail(inst.base.src, "unrecognized asm output constraint: '{s}'", .{output}); } const reg_name = output[2 .. output.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); return MCValue{ .register = reg }; } else { return MCValue.none; @@ -2468,11 +2468,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { .x86_64, .i386 => { for (inst.inputs) |input, i| { if (input.len < 3 or input[0] != '{' or input[input.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm input constraint: '{}'", .{input}); + return self.fail(inst.base.src, "unrecognized asm input constraint: '{s}'", .{input}); } const reg_name = input[1 .. input.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); const arg = try self.resolveInst(inst.args[i]); try self.genSetReg(inst.base.src, reg, arg); } @@ -2485,11 +2485,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { if (inst.output) |output| { if (output.len < 4 or output[0] != '=' or output[1] != '{' or output[output.len - 1] != '}') { - return self.fail(inst.base.src, "unrecognized asm output constraint: '{}'", .{output}); + return self.fail(inst.base.src, "unrecognized asm output constraint: '{s}'", .{output}); } const reg_name = output[2 .. output.len - 1]; const reg = parseRegName(reg_name) orelse - return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name}); + return self.fail(inst.base.src, "unrecognized register: '{s}'", .{reg_name}); return MCValue{ .register = reg }; } else { return MCValue.none; @@ -3417,7 +3417,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { next_int_reg += 1; } }, - else => return self.fail(src, "TODO implement function parameters of type {}", .{@tagName(ty.zigTypeTag())}), + else => return self.fail(src, "TODO implement function parameters of type {s}", .{@tagName(ty.zigTypeTag())}), } } result.stack_byte_count = next_stack_offset; diff --git a/src/codegen/c.zig b/src/codegen/c.zig index c6c29942d9..684a03eb79 100644 --- a/src/codegen/c.zig +++ b/src/codegen/c.zig @@ -235,7 +235,7 @@ fn renderFunctionSignature( try writer.writeAll(", "); } try renderType(ctx, writer, tv.ty.fnParamType(index)); - try writer.print(" arg{}", .{index}); + try writer.print(" arg{d}", .{index}); } } try writer.writeByte(')'); @@ -383,7 +383,7 @@ const Context = struct { } fn name(self: *Context) ![]u8 { - const val = try std.fmt.allocPrint(&self.arena.allocator, "__temp_{}", .{self.unnamed_index}); + const val = try std.fmt.allocPrint(&self.arena.allocator, "__temp_{d}", .{self.unnamed_index}); self.unnamed_index += 1; return val; } @@ -420,7 +420,7 @@ fn genAlloc(ctx: *Context, file: *C, alloc: *Inst.NoOp) !?[]u8 { } fn genArg(ctx: *Context) !?[]u8 { - const name = try std.fmt.allocPrint(&ctx.arena.allocator, "arg{}", .{ctx.argdex}); + const name = try std.fmt.allocPrint(&ctx.arena.allocator, "arg{d}", .{ctx.argdex}); ctx.argdex += 1; return name; } @@ -528,7 +528,7 @@ fn genCall(ctx: *Context, file: *C, inst: *Inst.Call) !?[]u8 { try renderValue(ctx, writer, arg.ty, val); } else { const val = try ctx.resolveInst(arg); - try writer.print("{}", .{val}); + try writer.print("{s}", .{val}); } } } @@ -587,7 +587,7 @@ fn genAsm(ctx: *Context, file: *C, as: *Inst.Assembly) !?[]u8 { const arg = as.args[index]; try writer.writeAll("register "); try renderType(ctx, writer, arg.ty); - try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); + try writer.print(" {s}_constant __asm__(\"{s}\") = ", .{ reg, reg }); // TODO merge constant handling into inst_map as well if (arg.castTag(.constant)) |c| { try renderValue(ctx, writer, arg.ty, c.val); @@ -597,13 +597,13 @@ fn genAsm(ctx: *Context, file: *C, as: *Inst.Assembly) !?[]u8 { if (!gop.found_existing) { return ctx.fail(ctx.decl.src(), "Internal error in C backend: asm argument not found in inst_map", .{}); } - try writer.print("{};\n ", .{gop.entry.value}); + try writer.print("{s};\n ", .{gop.entry.value}); } } else { return ctx.fail(ctx.decl.src(), "TODO non-explicit inline asm regs", .{}); } } - try writer.print("__asm {} (\"{}\"", .{ if (as.is_volatile) @as([]const u8, "volatile") else "", as.asm_source }); + try writer.print("__asm {s} (\"{s}\"", .{ if (as.is_volatile) @as([]const u8, "volatile") else "", as.asm_source }); if (as.output) |o| { return ctx.fail(ctx.decl.src(), "TODO inline asm output", .{}); } @@ -619,7 +619,7 @@ fn genAsm(ctx: *Context, file: *C, as: *Inst.Assembly) !?[]u8 { if (index > 0) { try writer.writeAll(", "); } - try writer.print("\"\"({}_constant)", .{reg}); + try writer.print("\"\"({s}_constant)", .{reg}); } else { // This is blocked by the earlier test unreachable; diff --git a/src/glibc.zig b/src/glibc.zig index 0c27872720..e7b7b1b1cf 100644 --- a/src/glibc.zig +++ b/src/glibc.zig @@ -72,7 +72,7 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! errdefer version_table.deinit(gpa); var glibc_dir = zig_lib_dir.openDir("libc" ++ path.sep_str ++ "glibc", .{}) catch |err| { - std.log.err("unable to open glibc dir: {}", .{@errorName(err)}); + std.log.err("unable to open glibc dir: {s}", .{@errorName(err)}); return error.ZigInstallationCorrupt; }; defer glibc_dir.close(); @@ -81,7 +81,7 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! const vers_txt_contents = glibc_dir.readFileAlloc(gpa, "vers.txt", max_txt_size) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { - std.log.err("unable to read vers.txt: {}", .{@errorName(err)}); + std.log.err("unable to read vers.txt: {s}", .{@errorName(err)}); return error.ZigInstallationCorrupt; }, }; @@ -91,7 +91,7 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! const fns_txt_contents = glibc_dir.readFileAlloc(arena, "fns.txt", max_txt_size) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { - std.log.err("unable to read fns.txt: {}", .{@errorName(err)}); + std.log.err("unable to read fns.txt: {s}", .{@errorName(err)}); return error.ZigInstallationCorrupt; }, }; @@ -99,7 +99,7 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! const abi_txt_contents = glibc_dir.readFileAlloc(gpa, "abi.txt", max_txt_size) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { - std.log.err("unable to read abi.txt: {}", .{@errorName(err)}); + std.log.err("unable to read abi.txt: {s}", .{@errorName(err)}); return error.ZigInstallationCorrupt; }, }; @@ -111,12 +111,12 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! while (it.next()) |line| : (line_i += 1) { const prefix = "GLIBC_"; if (!mem.startsWith(u8, line, prefix)) { - std.log.err("vers.txt:{}: expected 'GLIBC_' prefix", .{line_i}); + std.log.err("vers.txt:{d}: expected 'GLIBC_' prefix", .{line_i}); return error.ZigInstallationCorrupt; } const adjusted_line = line[prefix.len..]; const ver = std.builtin.Version.parse(adjusted_line) catch |err| { - std.log.err("vers.txt:{}: unable to parse glibc version '{}': {}", .{ line_i, line, @errorName(err) }); + std.log.err("vers.txt:{d}: unable to parse glibc version '{s}': {s}", .{ line_i, line, @errorName(err) }); return error.ZigInstallationCorrupt; }; try all_versions.append(arena, ver); @@ -128,15 +128,15 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! while (file_it.next()) |line| : (line_i += 1) { var line_it = mem.tokenize(line, " "); const fn_name = line_it.next() orelse { - std.log.err("fns.txt:{}: expected function name", .{line_i}); + std.log.err("fns.txt:{d}: expected function name", .{line_i}); return error.ZigInstallationCorrupt; }; const lib_name = line_it.next() orelse { - std.log.err("fns.txt:{}: expected library name", .{line_i}); + std.log.err("fns.txt:{d}: expected library name", .{line_i}); return error.ZigInstallationCorrupt; }; const lib = findLib(lib_name) orelse { - std.log.err("fns.txt:{}: unknown library name: {}", .{ line_i, lib_name }); + std.log.err("fns.txt:{d}: unknown library name: {s}", .{ line_i, lib_name }); return error.ZigInstallationCorrupt; }; try all_functions.append(arena, .{ @@ -158,27 +158,27 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! while (line_it.next()) |target_string| { var component_it = mem.tokenize(target_string, "-"); const arch_name = component_it.next() orelse { - std.log.err("abi.txt:{}: expected arch name", .{line_i}); + std.log.err("abi.txt:{d}: expected arch name", .{line_i}); return error.ZigInstallationCorrupt; }; const os_name = component_it.next() orelse { - std.log.err("abi.txt:{}: expected OS name", .{line_i}); + std.log.err("abi.txt:{d}: expected OS name", .{line_i}); return error.ZigInstallationCorrupt; }; const abi_name = component_it.next() orelse { - std.log.err("abi.txt:{}: expected ABI name", .{line_i}); + std.log.err("abi.txt:{d}: expected ABI name", .{line_i}); return error.ZigInstallationCorrupt; }; const arch_tag = std.meta.stringToEnum(std.Target.Cpu.Arch, arch_name) orelse { - std.log.err("abi.txt:{}: unrecognized arch: '{}'", .{ line_i, arch_name }); + std.log.err("abi.txt:{d}: unrecognized arch: '{s}'", .{ line_i, arch_name }); return error.ZigInstallationCorrupt; }; if (!mem.eql(u8, os_name, "linux")) { - std.log.err("abi.txt:{}: expected OS 'linux', found '{}'", .{ line_i, os_name }); + std.log.err("abi.txt:{d}: expected OS 'linux', found '{s}'", .{ line_i, os_name }); return error.ZigInstallationCorrupt; } const abi_tag = std.meta.stringToEnum(std.Target.Abi, abi_name) orelse { - std.log.err("abi.txt:{}: unrecognized ABI: '{}'", .{ line_i, abi_name }); + std.log.err("abi.txt:{d}: unrecognized ABI: '{s}'", .{ line_i, abi_name }); return error.ZigInstallationCorrupt; }; @@ -193,7 +193,7 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! }; for (ver_list_base) |*ver_list| { const line = file_it.next() orelse { - std.log.err("abi.txt:{}: missing version number line", .{line_i}); + std.log.err("abi.txt:{d}: missing version number line", .{line_i}); return error.ZigInstallationCorrupt; }; line_i += 1; @@ -206,12 +206,12 @@ pub fn loadMetaData(gpa: *Allocator, zig_lib_dir: std.fs.Dir) LoadMetaDataError! while (line_it.next()) |version_index_string| { if (ver_list.len >= ver_list.versions.len) { // If this happens with legit data, increase the array len in the type. - std.log.err("abi.txt:{}: too many versions", .{line_i}); + std.log.err("abi.txt:{d}: too many versions", .{line_i}); return error.ZigInstallationCorrupt; } const version_index = std.fmt.parseInt(u8, version_index_string, 10) catch |err| { // If this happens with legit data, increase the size of the integer type in the struct. - std.log.err("abi.txt:{}: unable to parse version: {}", .{ line_i, @errorName(err) }); + std.log.err("abi.txt:{d}: unable to parse version: {s}", .{ line_i, @errorName(err) }); return error.ZigInstallationCorrupt; }; @@ -531,7 +531,7 @@ fn add_include_dirs(comp: *Compilation, arena: *Allocator, args: *std.ArrayList( try args.append(try path.join(arena, &[_][]const u8{ comp.zig_lib_directory.path.?, lib_libc ++ "glibc" })); try args.append("-I"); - try args.append(try std.fmt.allocPrint(arena, "{}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{}-{}-{}", .{ + try args.append(try std.fmt.allocPrint(arena, "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-{s}-{s}", .{ comp.zig_lib_directory.path.?, @tagName(arch), @tagName(target.os.tag), @tagName(target.abi), })); @@ -539,7 +539,7 @@ fn add_include_dirs(comp: *Compilation, arena: *Allocator, args: *std.ArrayList( try args.append(try lib_path(comp, arena, lib_libc ++ "include" ++ s ++ "generic-glibc")); try args.append("-I"); - try args.append(try std.fmt.allocPrint(arena, "{}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{}-linux-any", .{ + try args.append(try std.fmt.allocPrint(arena, "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-linux-any", .{ comp.zig_lib_directory.path.?, @tagName(arch), })); @@ -881,7 +881,7 @@ pub fn buildSharedObjects(comp: *Compilation) !void { if (o_directory.handle.createFile(ok_basename, .{})) |file| { file.close(); } else |err| { - std.log.warn("glibc shared objects: failed to mark completion: {}", .{@errorName(err)}); + std.log.warn("glibc shared objects: failed to mark completion: {s}", .{@errorName(err)}); } } diff --git a/src/libc_installation.zig b/src/libc_installation.zig index 0b1029eeb8..cc96146e0b 100644 --- a/src/libc_installation.zig +++ b/src/libc_installation.zig @@ -83,7 +83,7 @@ pub const LibCInstallation = struct { } inline for (fields) |field, i| { if (!found_keys[i].found) { - log.err("missing field: {}\n", .{field.name}); + log.err("missing field: {s}\n", .{field.name}); return error.ParseError; } } @@ -96,18 +96,18 @@ pub const LibCInstallation = struct { return error.ParseError; } if (self.crt_dir == null and !is_darwin) { - log.err("crt_dir may not be empty for {}\n", .{@tagName(Target.current.os.tag)}); + log.err("crt_dir may not be empty for {s}\n", .{@tagName(Target.current.os.tag)}); return error.ParseError; } if (self.msvc_lib_dir == null and is_windows and !is_gnu) { - log.err("msvc_lib_dir may not be empty for {}-{}\n", .{ + log.err("msvc_lib_dir may not be empty for {s}-{s}\n", .{ @tagName(Target.current.os.tag), @tagName(Target.current.abi), }); return error.ParseError; } if (self.kernel32_lib_dir == null and is_windows and !is_gnu) { - log.err("kernel32_lib_dir may not be empty for {}-{}\n", .{ + log.err("kernel32_lib_dir may not be empty for {s}-{s}\n", .{ @tagName(Target.current.os.tag), @tagName(Target.current.abi), }); @@ -128,25 +128,25 @@ pub const LibCInstallation = struct { try out.print( \\# The directory that contains `stdlib.h`. \\# On POSIX-like systems, include directories be found with: `cc -E -Wp,-v -xc /dev/null` - \\include_dir={} + \\include_dir={s} \\ \\# The system-specific include directory. May be the same as `include_dir`. \\# On Windows it's the directory that includes `vcruntime.h`. \\# On POSIX it's the directory that includes `sys/errno.h`. - \\sys_include_dir={} + \\sys_include_dir={s} \\ \\# The directory that contains `crt1.o` or `crt2.o`. \\# On POSIX, can be found with `cc -print-file-name=crt1.o`. \\# Not needed when targeting MacOS. - \\crt_dir={} + \\crt_dir={s} \\ \\# The directory that contains `vcruntime.lib`. \\# Only needed when targeting MSVC on Windows. - \\msvc_lib_dir={} + \\msvc_lib_dir={s} \\ \\# The directory that contains `kernel32.lib`. \\# Only needed when targeting MSVC on Windows. - \\kernel32_lib_dir={} + \\kernel32_lib_dir={s} \\ , .{ include_dir, @@ -338,7 +338,7 @@ pub const LibCInstallation = struct { for (searches) |search| { result_buf.shrink(0); - try result_buf.outStream().print("{}\\Include\\{}\\ucrt", .{ search.path, search.version }); + try result_buf.outStream().print("{s}\\Include\\{s}\\ucrt", .{ search.path, search.version }); var dir = fs.cwd().openDir(result_buf.items, .{}) catch |err| switch (err) { error.FileNotFound, @@ -384,7 +384,7 @@ pub const LibCInstallation = struct { for (searches) |search| { result_buf.shrink(0); - try result_buf.outStream().print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir }); + try result_buf.outStream().print("{s}\\Lib\\{s}\\ucrt\\{s}", .{ search.path, search.version, arch_sub_dir }); var dir = fs.cwd().openDir(result_buf.items, .{}) catch |err| switch (err) { error.FileNotFound, @@ -439,7 +439,7 @@ pub const LibCInstallation = struct { for (searches) |search| { result_buf.shrink(0); const stream = result_buf.outStream(); - try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir }); + try stream.print("{s}\\Lib\\{s}\\um\\{s}", .{ search.path, search.version, arch_sub_dir }); var dir = fs.cwd().openDir(result_buf.items, .{}) catch |err| switch (err) { error.FileNotFound, @@ -520,7 +520,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 { const allocator = args.allocator; const cc_exe = std.os.getenvZ("CC") orelse default_cc_exe; - const arg1 = try std.fmt.allocPrint(allocator, "-print-file-name={}", .{args.search_basename}); + const arg1 = try std.fmt.allocPrint(allocator, "-print-file-name={s}", .{args.search_basename}); defer allocator.free(arg1); const argv = [_][]const u8{ cc_exe, arg1 }; @@ -584,17 +584,17 @@ fn printVerboseInvocation( if (!verbose) return; if (search_basename) |s| { - std.debug.warn("Zig attempted to find the file '{}' by executing this command:\n", .{s}); + std.debug.warn("Zig attempted to find the file '{s}' by executing this command:\n", .{s}); } else { std.debug.warn("Zig attempted to find the path to native system libc headers by executing this command:\n", .{}); } for (argv) |arg, i| { if (i != 0) std.debug.warn(" ", .{}); - std.debug.warn("{}", .{arg}); + std.debug.warn("{s}", .{arg}); } std.debug.warn("\n", .{}); if (stderr) |s| { - std.debug.warn("Output:\n==========\n{}\n==========\n", .{s}); + std.debug.warn("Output:\n==========\n{s}\n==========\n", .{s}); } } diff --git a/src/link.zig b/src/link.zig index 468f23bffd..3dbfb3b922 100644 --- a/src/link.zig +++ b/src/link.zig @@ -523,7 +523,7 @@ pub const File = struct { id_symlink_basename, &prev_digest_buf, ) catch |err| b: { - log.debug("archive new_digest={} readFile error: {}", .{ digest, @errorName(err) }); + log.debug("archive new_digest={} readFile error: {s}", .{ digest, @errorName(err) }); break :b prev_digest_buf[0..0]; }; if (mem.eql(u8, prev_digest, &digest)) { @@ -560,9 +560,9 @@ pub const File = struct { const full_out_path_z = try arena.dupeZ(u8, full_out_path); if (base.options.verbose_link) { - std.debug.print("ar rcs {}", .{full_out_path_z}); + std.debug.print("ar rcs {s}", .{full_out_path_z}); for (object_files.items) |arg| { - std.debug.print(" {}", .{arg}); + std.debug.print(" {s}", .{arg}); } std.debug.print("\n", .{}); } @@ -574,11 +574,11 @@ pub const File = struct { if (!base.options.disable_lld_caching) { Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { - log.warn("failed to save archive hash digest file: {}", .{@errorName(err)}); + log.warn("failed to save archive hash digest file: {s}", .{@errorName(err)}); }; man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when archiving: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest when archiving: {s}", .{@errorName(err)}); }; base.lock = man.toOwnedLock(); diff --git a/src/link/C.zig b/src/link/C.zig index 1059e52115..c3ab506b2c 100644 --- a/src/link/C.zig +++ b/src/link/C.zig @@ -112,7 +112,7 @@ pub fn flushModule(self: *C, comp: *Compilation) !void { try writer.writeByte('\n'); } if (self.constants.items.len > 0) { - try writer.print("{}\n", .{self.constants.items}); + try writer.print("{s}\n", .{self.constants.items}); } if (self.main.items.len > 1) { const last_two = self.main.items[self.main.items.len - 2 ..]; diff --git a/src/link/Coff.zig b/src/link/Coff.zig index 096fa2cd0b..a3cb5cc4c7 100644 --- a/src/link/Coff.zig +++ b/src/link/Coff.zig @@ -686,7 +686,7 @@ pub fn updateDecl(self: *Coff, module: *Module, decl: *Module.Decl) !void { if (need_realloc) { const curr_vaddr = self.getDeclVAddr(decl); const vaddr = try self.growTextBlock(&decl.link.coff, code.len, required_alignment); - log.debug("growing {} from 0x{x} to 0x{x}\n", .{ decl.name, curr_vaddr, vaddr }); + log.debug("growing {s} from 0x{x} to 0x{x}\n", .{ decl.name, curr_vaddr, vaddr }); if (vaddr != curr_vaddr) { log.debug(" (writing new offset table entry)\n", .{}); self.offset_table.items[decl.link.coff.offset_table_index] = vaddr; @@ -697,7 +697,7 @@ pub fn updateDecl(self: *Coff, module: *Module, decl: *Module.Decl) !void { } } else { const vaddr = try self.allocateTextBlock(&decl.link.coff, code.len, required_alignment); - log.debug("allocated text block for {} at 0x{x} (size: {Bi})\n", .{ mem.spanZ(decl.name), vaddr, code.len }); + log.debug("allocated text block for {s} at 0x{x} (size: {Bi})\n", .{ mem.spanZ(decl.name), vaddr, code.len }); errdefer self.freeTextBlock(&decl.link.coff); self.offset_table.items[decl.link.coff.offset_table_index] = vaddr; try self.writeOffsetTableEntry(decl.link.coff.offset_table_index); @@ -880,7 +880,7 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void { id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { - log.debug("COFF LLD new_digest={} error: {}", .{ digest, @errorName(err) }); + log.debug("COFF LLD new_digest={} error: {s}", .{ digest, @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; @@ -1236,11 +1236,11 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void { // Update the file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { - log.warn("failed to save linking hash digest file: {}", .{@errorName(err)}); + log.warn("failed to save linking hash digest file: {s}", .{@errorName(err)}); }; // Again failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when linking: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 4b2b95fc72..116d7c9859 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -1362,7 +1362,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { - log.debug("ELF LLD new_digest={} error: {}", .{ digest, @errorName(err) }); + log.debug("ELF LLD new_digest={} error: {s}", .{ digest, @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; @@ -1396,7 +1396,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { if (self.base.options.output_mode == .Exe) { try argv.append("-z"); - try argv.append(try std.fmt.allocPrint(arena, "stack-size={}", .{stack_size})); + try argv.append(try std.fmt.allocPrint(arena, "stack-size={d}", .{stack_size})); } if (self.base.options.image_base_override) |image_base| { @@ -1438,7 +1438,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { if (getLDMOption(target)) |ldm| { // Any target ELF will use the freebsd osabi if suffixed with "_fbsd". const arg = if (target.os.tag == .freebsd) - try std.fmt.allocPrint(arena, "{}_fbsd", .{ldm}) + try std.fmt.allocPrint(arena, "{s}_fbsd", .{ldm}) else ldm; try argv.append("-m"); @@ -1599,7 +1599,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { // (the check for that needs to be earlier), but they could be full paths to .so files, in which // case we want to avoid prepending "-l". const ext = Compilation.classifyFileExt(link_lib); - const arg = if (ext == .shared_library) link_lib else try std.fmt.allocPrint(arena, "-l{}", .{link_lib}); + const arg = if (ext == .shared_library) link_lib else try std.fmt.allocPrint(arena, "-l{s}", .{link_lib}); argv.appendAssumeCapacity(arg); } @@ -1733,11 +1733,11 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { // Update the file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { - log.warn("failed to save linking hash digest file: {}", .{@errorName(err)}); + log.warn("failed to save linking hash digest file: {s}", .{@errorName(err)}); }; // Again failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when linking: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. @@ -2082,10 +2082,10 @@ pub fn allocateDeclIndexes(self: *Elf, decl: *Module.Decl) !void { try self.offset_table.ensureCapacity(self.base.allocator, self.offset_table.items.len + 1); if (self.local_symbol_free_list.popOrNull()) |i| { - log.debug("reusing symbol index {} for {}\n", .{ i, decl.name }); + log.debug("reusing symbol index {d} for {s}\n", .{ i, decl.name }); decl.link.elf.local_sym_index = i; } else { - log.debug("allocating symbol index {} for {}\n", .{ self.local_symbols.items.len, decl.name }); + log.debug("allocating symbol index {d} for {s}\n", .{ self.local_symbols.items.len, decl.name }); decl.link.elf.local_sym_index = @intCast(u32, self.local_symbols.items.len); _ = self.local_symbols.addOneAssumeCapacity(); } @@ -2182,7 +2182,7 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { if (zir_dumps.len != 0) { for (zir_dumps) |fn_name| { if (mem.eql(u8, mem.spanZ(decl.name), fn_name)) { - std.debug.print("\n{}\n", .{decl.name}); + std.debug.print("\n{s}\n", .{decl.name}); typed_value.val.castTag(.function).?.data.dump(module.*); } } @@ -2300,7 +2300,7 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { !mem.isAlignedGeneric(u64, local_sym.st_value, required_alignment); if (need_realloc) { const vaddr = try self.growTextBlock(&decl.link.elf, code.len, required_alignment); - log.debug("growing {} from 0x{x} to 0x{x}\n", .{ decl.name, local_sym.st_value, vaddr }); + log.debug("growing {s} from 0x{x} to 0x{x}\n", .{ decl.name, local_sym.st_value, vaddr }); if (vaddr != local_sym.st_value) { local_sym.st_value = vaddr; @@ -2322,7 +2322,7 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { const decl_name = mem.spanZ(decl.name); const name_str_index = try self.makeString(decl_name); const vaddr = try self.allocateTextBlock(&decl.link.elf, code.len, required_alignment); - log.debug("allocated text block for {} at 0x{x}\n", .{ decl_name, vaddr }); + log.debug("allocated text block for {s} at 0x{x}\n", .{ decl_name, vaddr }); errdefer self.freeTextBlock(&decl.link.elf); local_sym.* = .{ @@ -2432,7 +2432,7 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { if (needed_size > self.allocatedSize(debug_line_sect.sh_offset)) { const new_offset = self.findFreeSpace(needed_size, 1); const existing_size = last_src_fn.off; - log.debug("moving .debug_line section: {} bytes from 0x{x} to 0x{x}\n", .{ + log.debug("moving .debug_line section: {d} bytes from 0x{x} to 0x{x}\n", .{ existing_size, debug_line_sect.sh_offset, new_offset, diff --git a/src/link/MachO.zig b/src/link/MachO.zig index 6abbae2c26..3f8544a4e8 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -520,7 +520,7 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { - log.debug("MachO LLD new_digest={} error: {}", .{ digest, @errorName(err) }); + log.debug("MachO LLD new_digest={} error: {s}", .{ digest, @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; @@ -620,7 +620,7 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { try argv.append(cur_vers); } - const dylib_install_name = try std.fmt.allocPrint(arena, "@rpath/{}", .{self.base.options.emit.?.sub_path}); + const dylib_install_name = try std.fmt.allocPrint(arena, "@rpath/{s}", .{self.base.options.emit.?.sub_path}); try argv.append("-install_name"); try argv.append(dylib_install_name); } @@ -706,7 +706,7 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which // case we want to avoid prepending "-l". const ext = Compilation.classifyFileExt(link_lib); - const arg = if (ext == .shared_library) link_lib else try std.fmt.allocPrint(arena, "-l{}", .{link_lib}); + const arg = if (ext == .shared_library) link_lib else try std.fmt.allocPrint(arena, "-l{s}", .{link_lib}); argv.appendAssumeCapacity(arg); } @@ -759,15 +759,15 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { self.base.allocator.free(result.stderr); } if (result.stdout.len != 0) { - log.warn("unexpected LD stdout: {}", .{result.stdout}); + log.warn("unexpected LD stdout: {s}", .{result.stdout}); } if (result.stderr.len != 0) { - log.warn("unexpected LD stderr: {}", .{result.stderr}); + log.warn("unexpected LD stderr: {s}", .{result.stderr}); } if (result.term != .Exited or result.term.Exited != 0) { // TODO parse this output and surface with the Compilation API rather than // directly outputting to stderr here. - log.err("{}", .{result.stderr}); + log.err("{s}", .{result.stderr}); return error.LDReportedFailure; } } else { @@ -980,11 +980,11 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { // Update the file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { - log.warn("failed to save linking hash digest file: {}", .{@errorName(err)}); + log.warn("failed to save linking hash digest file: {s}", .{@errorName(err)}); }; // Again failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when linking: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. @@ -1088,10 +1088,10 @@ pub fn allocateDeclIndexes(self: *MachO, decl: *Module.Decl) !void { try self.offset_table.ensureCapacity(self.base.allocator, self.offset_table.items.len + 1); if (self.local_symbol_free_list.popOrNull()) |i| { - log.debug("reusing symbol index {} for {}", .{ i, decl.name }); + log.debug("reusing symbol index {d} for {s}", .{ i, decl.name }); decl.link.macho.local_sym_index = i; } else { - log.debug("allocating symbol index {} for {}", .{ self.local_symbols.items.len, decl.name }); + log.debug("allocating symbol index {d} for {s}", .{ self.local_symbols.items.len, decl.name }); decl.link.macho.local_sym_index = @intCast(u32, self.local_symbols.items.len); _ = self.local_symbols.addOneAssumeCapacity(); } @@ -1165,7 +1165,7 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void { const need_realloc = code.len > capacity or !mem.isAlignedGeneric(u64, symbol.n_value, required_alignment); if (need_realloc) { const vaddr = try self.growTextBlock(&decl.link.macho, code.len, required_alignment); - log.debug("growing {} from 0x{x} to 0x{x}", .{ decl.name, symbol.n_value, vaddr }); + log.debug("growing {s} from 0x{x} to 0x{x}", .{ decl.name, symbol.n_value, vaddr }); if (vaddr != symbol.n_value) { symbol.n_value = vaddr; log.debug(" (writing new offset table entry)", .{}); @@ -1188,7 +1188,7 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void { const decl_name = mem.spanZ(decl.name); const name_str_index = try self.makeString(decl_name); const addr = try self.allocateTextBlock(&decl.link.macho, code.len, required_alignment); - log.debug("allocated text block for {} at 0x{x}", .{ decl_name, addr }); + log.debug("allocated text block for {s} at 0x{x}", .{ decl_name, addr }); errdefer self.freeTextBlock(&decl.link.macho); symbol.* = .{ diff --git a/src/link/Wasm.zig b/src/link/Wasm.zig index 374fa2230b..cbb3e83147 100644 --- a/src/link/Wasm.zig +++ b/src/link/Wasm.zig @@ -321,7 +321,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { id_symlink_basename, &prev_digest_buf, ) catch |err| blk: { - log.debug("WASM LLD new_digest={} error: {}", .{ digest, @errorName(err) }); + log.debug("WASM LLD new_digest={} error: {s}", .{ digest, @errorName(err) }); // Handle this as a cache miss. break :blk prev_digest_buf[0..0]; }; @@ -463,11 +463,11 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { // Update the file with the digest. If it fails we can continue; it only // means that the next invocation will have an unnecessary cache miss. Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { - log.warn("failed to save linking hash digest symlink: {}", .{@errorName(err)}); + log.warn("failed to save linking hash digest symlink: {s}", .{@errorName(err)}); }; // Again failure here only means an unnecessary cache miss. man.writeManifest() catch |err| { - log.warn("failed to write cache manifest when linking: {}", .{@errorName(err)}); + log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)}); }; // We hang on to this lock so that the output file path can be used without // other processes clobbering it. diff --git a/src/liveness.zig b/src/liveness.zig index 0d759f8312..b0aafa28f1 100644 --- a/src/liveness.zig +++ b/src/liveness.zig @@ -1,6 +1,7 @@ const std = @import("std"); const ir = @import("ir.zig"); const trace = @import("tracy.zig").trace; +const log = std.log.scoped(.liveness); /// Perform Liveness Analysis over the `Body`. Each `Inst` will have its `deaths` field populated. pub fn analyze( @@ -248,5 +249,5 @@ fn analyzeInst( @panic("Handle liveness analysis for instructions with many parameters"); } - std.log.scoped(.liveness).debug("analyze {}: 0b{b}\n", .{ base.tag, base.deaths }); + log.debug("analyze {}: 0b{b}\n", .{ base.tag, base.deaths }); } diff --git a/src/llvm_backend.zig b/src/llvm_backend.zig index 294e6f5400..51d1a0840e 100644 --- a/src/llvm_backend.zig +++ b/src/llvm_backend.zig @@ -132,7 +132,7 @@ pub fn targetTriple(allocator: *Allocator, target: std.Target) ![:0]u8 { .macabi => "macabi", }; - return std.fmt.allocPrintZ(allocator, "{}-unknown-{}-{}", .{ llvm_arch, llvm_os, llvm_abi }); + return std.fmt.allocPrintZ(allocator, "{s}-unknown-{s}-{s}", .{ llvm_arch, llvm_os, llvm_abi }); } pub const LLVMIRModule = struct { diff --git a/src/main.zig b/src/main.zig index 98b19cc3ea..b1243badff 100644 --- a/src/main.zig +++ b/src/main.zig @@ -118,7 +118,7 @@ pub fn main() anyerror!void { pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !void { if (args.len <= 1) { - std.log.info("{}", .{usage}); + std.log.info("{s}", .{usage}); fatal("expected command argument", .{}); } @@ -204,8 +204,8 @@ pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v } else if (mem.eql(u8, cmd, "help") or mem.eql(u8, cmd, "-h") or mem.eql(u8, cmd, "--help")) { try io.getStdOut().writeAll(usage); } else { - std.log.info("{}", .{usage}); - fatal("unknown command: {}", .{args[1]}); + std.log.info("{s}", .{usage}); + fatal("unknown command: {s}", .{args[1]}); } } @@ -615,7 +615,7 @@ fn buildOutputType( fatal("unexpected end-of-parameter mark: --", .{}); } } else if (mem.eql(u8, arg, "--pkg-begin")) { - if (i + 2 >= args.len) fatal("Expected 2 arguments after {}", .{arg}); + if (i + 2 >= args.len) fatal("Expected 2 arguments after {s}", .{arg}); i += 1; const pkg_name = args[i]; i += 1; @@ -626,7 +626,7 @@ fn buildOutputType( fs.path.dirname(pkg_path), fs.path.basename(pkg_path), ) catch |err| { - fatal("Failed to add package at path {}: {}", .{ pkg_path, @errorName(err) }); + fatal("Failed to add package at path {s}: {s}", .{ pkg_path, @errorName(err) }); }; new_cur_pkg.parent = cur_pkg; try cur_pkg.add(gpa, pkg_name, new_cur_pkg); @@ -635,7 +635,7 @@ fn buildOutputType( cur_pkg = cur_pkg.parent orelse fatal("encountered --pkg-end with no matching --pkg-begin", .{}); } else if (mem.eql(u8, arg, "--main-pkg-path")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; main_pkg_path = args[i]; } else if (mem.eql(u8, arg, "-cflags")) { @@ -653,10 +653,10 @@ fn buildOutputType( i += 1; const next_arg = args[i]; color = std.meta.stringToEnum(Color, next_arg) orelse { - fatal("expected [auto|on|off] after --color, found '{}'", .{next_arg}); + fatal("expected [auto|on|off] after --color, found '{s}'", .{next_arg}); }; } else if (mem.eql(u8, arg, "--subsystem")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; if (mem.eql(u8, args[i], "console")) { subsystem = .Console; @@ -689,51 +689,51 @@ fn buildOutputType( }); } } else if (mem.eql(u8, arg, "-O")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; optimize_mode_string = args[i]; } else if (mem.eql(u8, arg, "--stack")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; stack_size_override = std.fmt.parseUnsigned(u64, args[i], 0) catch |err| { - fatal("unable to parse '{}': {}", .{ arg, @errorName(err) }); + fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) }); }; } else if (mem.eql(u8, arg, "--image-base")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; image_base_override = std.fmt.parseUnsigned(u64, args[i], 0) catch |err| { - fatal("unable to parse '{}': {}", .{ arg, @errorName(err) }); + fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) }); }; } else if (mem.eql(u8, arg, "--name")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; provided_name = args[i]; } else if (mem.eql(u8, arg, "-rpath")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; try rpath_list.append(args[i]); } else if (mem.eql(u8, arg, "--library-directory") or mem.eql(u8, arg, "-L")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; try lib_dirs.append(args[i]); } else if (mem.eql(u8, arg, "-F")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; try framework_dirs.append(args[i]); } else if (mem.eql(u8, arg, "-framework")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; try frameworks.append(args[i]); } else if (mem.eql(u8, arg, "-T") or mem.eql(u8, arg, "--script")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; linker_script = args[i]; } else if (mem.eql(u8, arg, "--version-script")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; version_script = args[i]; } else if (mem.eql(u8, arg, "--library") or mem.eql(u8, arg, "-l")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); // We don't know whether this library is part of libc or libc++ until we resolve the target. // So we simply append to the list for now. i += 1; @@ -743,7 +743,7 @@ fn buildOutputType( mem.eql(u8, arg, "-I") or mem.eql(u8, arg, "-dirafter")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; try clang_argv.append(arg); try clang_argv.append(args[i]); @@ -753,19 +753,19 @@ fn buildOutputType( } i += 1; version = std.builtin.Version.parse(args[i]) catch |err| { - fatal("unable to parse --version '{}': {}", .{ args[i], @errorName(err) }); + fatal("unable to parse --version '{s}': {s}", .{ args[i], @errorName(err) }); }; have_version = true; } else if (mem.eql(u8, arg, "-target")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; target_arch_os_abi = args[i]; } else if (mem.eql(u8, arg, "-mcpu")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; target_mcpu = args[i]; } else if (mem.eql(u8, arg, "-mcmodel")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; machine_code_model = parseCodeModel(args[i]); } else if (mem.startsWith(u8, arg, "-ofmt=")) { @@ -777,35 +777,35 @@ fn buildOutputType( } else if (mem.startsWith(u8, arg, "-O")) { optimize_mode_string = arg["-O".len..]; } else if (mem.eql(u8, arg, "--dynamic-linker")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; target_dynamic_linker = args[i]; } else if (mem.eql(u8, arg, "--libc")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; libc_paths_file = args[i]; } else if (mem.eql(u8, arg, "--test-filter")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; test_filter = args[i]; } else if (mem.eql(u8, arg, "--test-name-prefix")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; test_name_prefix = args[i]; } else if (mem.eql(u8, arg, "--test-cmd")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; try test_exec_args.append(args[i]); } else if (mem.eql(u8, arg, "--cache-dir")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; override_local_cache_dir = args[i]; } else if (mem.eql(u8, arg, "--global-cache-dir")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; override_global_cache_dir = args[i]; } else if (mem.eql(u8, arg, "--override-lib-dir")) { - if (i + 1 >= args.len) fatal("expected parameter after {}", .{arg}); + if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg}); i += 1; override_lib_dir = args[i]; } else if (mem.eql(u8, arg, "-fcompiler-rt")) { @@ -968,7 +968,7 @@ fn buildOutputType( { try clang_argv.append(arg); } else { - fatal("unrecognized parameter: '{}'", .{arg}); + fatal("unrecognized parameter: '{s}'", .{arg}); } } else switch (Compilation.classifyFileExt(arg)) { .object, .static_library, .shared_library => { @@ -982,19 +982,19 @@ fn buildOutputType( }, .zig, .zir => { if (root_src_file) |other| { - fatal("found another zig file '{}' after root source file '{}'", .{ arg, other }); + fatal("found another zig file '{s}' after root source file '{s}'", .{ arg, other }); } else { root_src_file = arg; } }, .unknown => { - fatal("unrecognized file extension of parameter '{}'", .{arg}); + fatal("unrecognized file extension of parameter '{s}'", .{arg}); }, } } if (optimize_mode_string) |s| { optimize_mode = std.meta.stringToEnum(std.builtin.Mode, s) orelse - fatal("unrecognized optimization mode: '{}'", .{s}); + fatal("unrecognized optimization mode: '{s}'", .{s}); } }, .cc, .cpp => { @@ -1018,7 +1018,7 @@ fn buildOutputType( var it = ClangArgIterator.init(arena, all_args); while (it.has_next) { it.next() catch |err| { - fatal("unable to parse command line parameters: {}", .{@errorName(err)}); + fatal("unable to parse command line parameters: {s}", .{@errorName(err)}); }; switch (it.zig_equivalent) { .target => target_arch_os_abi = it.only_arg, // example: -target riscv64-linux-unknown @@ -1038,7 +1038,7 @@ fn buildOutputType( }, .zig, .zir => { if (root_src_file) |other| { - fatal("found another zig file '{}' after root source file '{}'", .{ it.only_arg, other }); + fatal("found another zig file '{s}' after root source file '{s}'", .{ it.only_arg, other }); } else { root_src_file = it.only_arg; } @@ -1153,7 +1153,7 @@ fn buildOutputType( if (mem.eql(u8, arg, "-soname")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } const name = linker_args.items[i]; soname = .{ .yes = name }; @@ -1185,7 +1185,7 @@ fn buildOutputType( } else if (mem.eql(u8, arg, "-rpath")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } try rpath_list.append(linker_args.items[i]); } else if (mem.eql(u8, arg, "-I") or @@ -1194,7 +1194,7 @@ fn buildOutputType( { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } target_dynamic_linker = linker_args.items[i]; } else if (mem.eql(u8, arg, "-E") or @@ -1205,7 +1205,7 @@ fn buildOutputType( } else if (mem.eql(u8, arg, "--version-script")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } version_script = linker_args.items[i]; } else if (mem.startsWith(u8, arg, "-O")) { @@ -1227,7 +1227,7 @@ fn buildOutputType( } else if (mem.eql(u8, arg, "-z")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } const z_arg = linker_args.items[i]; if (mem.eql(u8, z_arg, "nodelete")) { @@ -1235,44 +1235,44 @@ fn buildOutputType( } else if (mem.eql(u8, z_arg, "defs")) { linker_z_defs = true; } else { - warn("unsupported linker arg: -z {}", .{z_arg}); + warn("unsupported linker arg: -z {s}", .{z_arg}); } } else if (mem.eql(u8, arg, "--major-image-version")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } version.major = std.fmt.parseUnsigned(u32, linker_args.items[i], 10) catch |err| { - fatal("unable to parse '{}': {}", .{ arg, @errorName(err) }); + fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) }); }; have_version = true; } else if (mem.eql(u8, arg, "--minor-image-version")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } version.minor = std.fmt.parseUnsigned(u32, linker_args.items[i], 10) catch |err| { - fatal("unable to parse '{}': {}", .{ arg, @errorName(err) }); + fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) }); }; have_version = true; } else if (mem.eql(u8, arg, "--stack")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } stack_size_override = std.fmt.parseUnsigned(u64, linker_args.items[i], 0) catch |err| { - fatal("unable to parse '{}': {}", .{ arg, @errorName(err) }); + fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) }); }; } else if (mem.eql(u8, arg, "--image-base")) { i += 1; if (i >= linker_args.items.len) { - fatal("expected linker arg after '{}'", .{arg}); + fatal("expected linker arg after '{s}'", .{arg}); } image_base_override = std.fmt.parseUnsigned(u64, linker_args.items[i], 0) catch |err| { - fatal("unable to parse '{}': {}", .{ arg, @errorName(err) }); + fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) }); }; } else { - warn("unsupported linker arg: {}", .{arg}); + warn("unsupported linker arg: {s}", .{arg}); } } @@ -1328,7 +1328,7 @@ fn buildOutputType( } if (arg_mode == .translate_c and c_source_files.items.len != 1) { - fatal("translate-c expects exactly 1 source file (found {})", .{c_source_files.items.len}); + fatal("translate-c expects exactly 1 source file (found {d})", .{c_source_files.items.len}); } if (root_src_file == null and arg_mode == .zig_test) { @@ -1373,25 +1373,25 @@ fn buildOutputType( help: { var help_text = std.ArrayList(u8).init(arena); for (diags.arch.?.allCpuModels()) |cpu| { - help_text.writer().print(" {}\n", .{cpu.name}) catch break :help; + help_text.writer().print(" {s}\n", .{cpu.name}) catch break :help; } - std.log.info("Available CPUs for architecture '{}': {}", .{ + std.log.info("Available CPUs for architecture '{s}': {s}", .{ @tagName(diags.arch.?), help_text.items, }); } - fatal("Unknown CPU: '{}'", .{diags.cpu_name.?}); + fatal("Unknown CPU: '{s}'", .{diags.cpu_name.?}); }, error.UnknownCpuFeature => { help: { var help_text = std.ArrayList(u8).init(arena); for (diags.arch.?.allFeaturesList()) |feature| { - help_text.writer().print(" {}: {}\n", .{ feature.name, feature.description }) catch break :help; + help_text.writer().print(" {s}: {s}\n", .{ feature.name, feature.description }) catch break :help; } - std.log.info("Available CPU features for architecture '{}': {}", .{ + std.log.info("Available CPU features for architecture '{s}': {s}", .{ @tagName(diags.arch.?), help_text.items, }); } - fatal("Unknown CPU feature: '{}'", .{diags.unknown_feature_name}); + fatal("Unknown CPU feature: '{s}'", .{diags.unknown_feature_name}); }, else => |e| return e, }; @@ -1431,10 +1431,10 @@ fn buildOutputType( if (cross_target.isNativeOs() and (system_libs.items.len != 0 or want_native_include_dirs)) { const paths = std.zig.system.NativePaths.detect(arena) catch |err| { - fatal("unable to detect native system paths: {}", .{@errorName(err)}); + fatal("unable to detect native system paths: {s}", .{@errorName(err)}); }; for (paths.warnings.items) |warning| { - warn("{}", .{warning}); + warn("{s}", .{warning}); } const has_sysroot = if (comptime std.Target.current.isDarwin()) outer: { @@ -1492,7 +1492,7 @@ fn buildOutputType( } else if (mem.eql(u8, ofmt, "raw")) { break :blk .raw; } else { - fatal("unsupported object format: {}", .{ofmt}); + fatal("unsupported object format: {s}", .{ofmt}); } }; @@ -1562,7 +1562,7 @@ fn buildOutputType( } if (fs.path.dirname(full_path)) |dirname| { const handle = fs.cwd().openDir(dirname, .{}) catch |err| { - fatal("unable to open output directory '{}': {}", .{ dirname, @errorName(err) }); + fatal("unable to open output directory '{s}': {s}", .{ dirname, @errorName(err) }); }; cleanup_emit_bin_dir = handle; break :b Compilation.EmitLoc{ @@ -1585,19 +1585,19 @@ fn buildOutputType( }, }; - const default_h_basename = try std.fmt.allocPrint(arena, "{}.h", .{root_name}); + const default_h_basename = try std.fmt.allocPrint(arena, "{s}.h", .{root_name}); var emit_h_resolved = try emit_h.resolve(default_h_basename); defer emit_h_resolved.deinit(); - const default_asm_basename = try std.fmt.allocPrint(arena, "{}.s", .{root_name}); + const default_asm_basename = try std.fmt.allocPrint(arena, "{s}.s", .{root_name}); var emit_asm_resolved = try emit_asm.resolve(default_asm_basename); defer emit_asm_resolved.deinit(); - const default_llvm_ir_basename = try std.fmt.allocPrint(arena, "{}.ll", .{root_name}); + const default_llvm_ir_basename = try std.fmt.allocPrint(arena, "{s}.ll", .{root_name}); var emit_llvm_ir_resolved = try emit_llvm_ir.resolve(default_llvm_ir_basename); defer emit_llvm_ir_resolved.deinit(); - const default_analysis_basename = try std.fmt.allocPrint(arena, "{}-analysis.json", .{root_name}); + const default_analysis_basename = try std.fmt.allocPrint(arena, "{s}-analysis.json", .{root_name}); var emit_analysis_resolved = try emit_analysis.resolve(default_analysis_basename); defer emit_analysis_resolved.deinit(); @@ -1609,10 +1609,10 @@ fn buildOutputType( .yes_default_path => blk: { if (root_src_file) |rsf| { if (mem.endsWith(u8, rsf, ".zir")) { - break :blk try std.fmt.allocPrint(arena, "{}.out.zir", .{root_name}); + break :blk try std.fmt.allocPrint(arena, "{s}.out.zir", .{root_name}); } } - break :blk try std.fmt.allocPrint(arena, "{}.zir", .{root_name}); + break :blk try std.fmt.allocPrint(arena, "{s}.zir", .{root_name}); }, .yes => |p| p, }; @@ -1642,7 +1642,7 @@ fn buildOutputType( } else introspect.findZigLibDirFromSelfExe(arena, self_exe_path) catch |err| { - fatal("unable to find zig installation directory: {}", .{@errorName(err)}); + fatal("unable to find zig installation directory: {s}", .{@errorName(err)}); }; defer zig_lib_directory.handle.close(); @@ -1655,7 +1655,7 @@ fn buildOutputType( if (libc_paths_file) |paths_file| { libc_installation = LibCInstallation.parse(gpa, paths_file) catch |err| { - fatal("unable to parse libc paths file: {}", .{@errorName(err)}); + fatal("unable to parse libc paths file: {s}", .{@errorName(err)}); }; } @@ -1791,7 +1791,7 @@ fn buildOutputType( .disable_lld_caching = !have_enable_cache, .subsystem = subsystem, }) catch |err| { - fatal("unable to create compilation: {}", .{@errorName(err)}); + fatal("unable to create compilation: {s}", .{@errorName(err)}); }; var comp_destroyed = false; defer if (!comp_destroyed) comp.destroy(); @@ -1914,12 +1914,12 @@ fn buildOutputType( if (!watch) return cleanExit(); } else { const cmd = try argvCmd(arena, argv.items); - fatal("the following test command failed with exit code {}:\n{}", .{ code, cmd }); + fatal("the following test command failed with exit code {d}:\n{s}", .{ code, cmd }); } }, else => { const cmd = try argvCmd(arena, argv.items); - fatal("the following test command crashed:\n{}", .{cmd}); + fatal("the following test command crashed:\n{s}", .{cmd}); }, } }, @@ -1936,7 +1936,7 @@ fn buildOutputType( try stderr.print("(zig) ", .{}); try comp.makeBinFileExecutable(); if (stdin.readUntilDelimiterOrEof(&repl_buf, '\n') catch |err| { - try stderr.print("\nUnable to parse command: {}\n", .{@errorName(err)}); + try stderr.print("\nUnable to parse command: {s}\n", .{@errorName(err)}); continue; }) |line| { const actual_line = mem.trimRight(u8, line, "\r\n "); @@ -1954,7 +1954,7 @@ fn buildOutputType( } else if (mem.eql(u8, actual_line, "help")) { try stderr.writeAll(repl_help); } else { - try stderr.print("unknown command: {}\n", .{actual_line}); + try stderr.print("unknown command: {s}\n", .{actual_line}); } } else { break; @@ -2012,14 +2012,14 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi assert(comp.c_source_files.len == 1); const c_source_file = comp.c_source_files[0]; - const translated_zig_basename = try std.fmt.allocPrint(arena, "{}.zig", .{comp.bin_file.options.root_name}); + const translated_zig_basename = try std.fmt.allocPrint(arena, "{s}.zig", .{comp.bin_file.options.root_name}); var man: Cache.Manifest = comp.obtainCObjectCacheManifest(); defer if (enable_cache) man.deinit(); man.hash.add(@as(u16, 0xb945)); // Random number to distinguish translate-c from compiling C objects _ = man.addFile(c_source_file.src_path, null) catch |err| { - fatal("unable to process '{}': {}", .{ c_source_file.src_path, @errorName(err) }); + fatal("unable to process '{s}': {s}", .{ c_source_file.src_path, @errorName(err) }); }; const digest = if (try man.hit()) man.final() else digest: { @@ -2034,7 +2034,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi break :blk null; const c_src_basename = fs.path.basename(c_source_file.src_path); - const dep_basename = try std.fmt.allocPrint(arena, "{}.d", .{c_src_basename}); + const dep_basename = try std.fmt.allocPrint(arena, "{s}.d", .{c_src_basename}); const out_dep_path = try comp.tmpFilePath(arena, dep_basename); break :blk out_dep_path; }; @@ -2069,7 +2069,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi error.ASTUnitFailure => fatal("clang API returned errors but due to a clang bug, it is not exposing the errors for zig to see. For more details: https://github.com/ziglang/zig/issues/4455", .{}), error.SemanticAnalyzeFail => { for (clang_errors) |clang_err| { - std.debug.print("{}:{}:{}: {}\n", .{ + std.debug.print("{s}:{d}:{d}: {s}\n", .{ if (clang_err.filename_ptr) |p| p[0..clang_err.filename_len] else "(no file)", clang_err.line + 1, clang_err.column + 1, @@ -2087,7 +2087,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi try man.addDepFilePost(zig_cache_tmp_dir, dep_basename); // Just to save disk space, we delete the file because it is never needed again. zig_cache_tmp_dir.deleteFile(dep_basename) catch |err| { - warn("failed to delete '{}': {}", .{ dep_file_path, @errorName(err) }); + warn("failed to delete '{s}': {s}", .{ dep_file_path, @errorName(err) }); }; } @@ -2102,7 +2102,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi _ = try std.zig.render(comp.gpa, bos.writer(), tree); try bos.flush(); - man.writeManifest() catch |err| warn("failed to write cache manifest: {}", .{@errorName(err)}); + man.writeManifest() catch |err| warn("failed to write cache manifest: {s}", .{@errorName(err)}); break :digest digest; }; @@ -2111,7 +2111,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi const full_zig_path = try comp.local_cache_directory.join(arena, &[_][]const u8{ "o", &digest, translated_zig_basename, }); - try io.getStdOut().writer().print("{}\n", .{full_zig_path}); + try io.getStdOut().writer().print("{s}\n", .{full_zig_path}); return cleanExit(); } else { const out_zig_path = try fs.path.join(arena, &[_][]const u8{ "o", &digest, translated_zig_basename }); @@ -2148,10 +2148,10 @@ pub fn cmdLibC(gpa: *Allocator, args: []const []const u8) !void { try stdout.writeAll(usage_libc); return cleanExit(); } else { - fatal("unrecognized parameter: '{}'", .{arg}); + fatal("unrecognized parameter: '{s}'", .{arg}); } } else if (input_file != null) { - fatal("unexpected extra parameter: '{}'", .{arg}); + fatal("unexpected extra parameter: '{s}'", .{arg}); } else { input_file = arg; } @@ -2159,7 +2159,7 @@ pub fn cmdLibC(gpa: *Allocator, args: []const []const u8) !void { } if (input_file) |libc_file| { var libc = LibCInstallation.parse(gpa, libc_file) catch |err| { - fatal("unable to parse libc file: {}", .{@errorName(err)}); + fatal("unable to parse libc file: {s}", .{@errorName(err)}); }; defer libc.deinit(gpa); } else { @@ -2167,7 +2167,7 @@ pub fn cmdLibC(gpa: *Allocator, args: []const []const u8) !void { .allocator = gpa, .verbose = true, }) catch |err| { - fatal("unable to detect native libc: {}", .{@errorName(err)}); + fatal("unable to detect native libc: {s}", .{@errorName(err)}); }; defer libc.deinit(gpa); @@ -2205,16 +2205,16 @@ pub fn cmdInit( try io.getStdOut().writeAll(usage_init); return cleanExit(); } else { - fatal("unrecognized parameter: '{}'", .{arg}); + fatal("unrecognized parameter: '{s}'", .{arg}); } } else { - fatal("unexpected extra parameter: '{}'", .{arg}); + fatal("unexpected extra parameter: '{s}'", .{arg}); } } } const self_exe_path = try fs.selfExePathAlloc(arena); var zig_lib_directory = introspect.findZigLibDirFromSelfExe(arena, self_exe_path) catch |err| { - fatal("unable to find zig installation directory: {}\n", .{@errorName(err)}); + fatal("unable to find zig installation directory: {s}\n", .{@errorName(err)}); }; defer zig_lib_directory.handle.close(); @@ -2232,7 +2232,7 @@ pub fn cmdInit( const max_bytes = 10 * 1024 * 1024; const build_zig_contents = template_dir.readFileAlloc(arena, "build.zig", max_bytes) catch |err| { - fatal("unable to read template file 'build.zig': {}", .{@errorName(err)}); + fatal("unable to read template file 'build.zig': {s}", .{@errorName(err)}); }; var modified_build_zig_contents = std.ArrayList(u8).init(arena); try modified_build_zig_contents.ensureCapacity(build_zig_contents.len); @@ -2244,13 +2244,13 @@ pub fn cmdInit( } } const main_zig_contents = template_dir.readFileAlloc(arena, "src" ++ s ++ "main.zig", max_bytes) catch |err| { - fatal("unable to read template file 'main.zig': {}", .{@errorName(err)}); + fatal("unable to read template file 'main.zig': {s}", .{@errorName(err)}); }; if (fs.cwd().access("build.zig", .{})) |_| { fatal("existing build.zig file would be overwritten", .{}); } else |err| switch (err) { error.FileNotFound => {}, - else => fatal("unable to test existence of build.zig: {}\n", .{@errorName(err)}), + else => fatal("unable to test existence of build.zig: {s}\n", .{@errorName(err)}), } var src_dir = try fs.cwd().makeOpenPath("src", .{}); defer src_dir.close(); @@ -2311,23 +2311,23 @@ pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v const arg = args[i]; if (mem.startsWith(u8, arg, "-")) { if (mem.eql(u8, arg, "--build-file")) { - if (i + 1 >= args.len) fatal("expected argument after '{}'", .{arg}); + if (i + 1 >= args.len) fatal("expected argument after '{s}'", .{arg}); i += 1; build_file = args[i]; continue; } else if (mem.eql(u8, arg, "--override-lib-dir")) { - if (i + 1 >= args.len) fatal("expected argument after '{}'", .{arg}); + if (i + 1 >= args.len) fatal("expected argument after '{s}'", .{arg}); i += 1; override_lib_dir = args[i]; try child_argv.appendSlice(&[_][]const u8{ arg, args[i] }); continue; } else if (mem.eql(u8, arg, "--cache-dir")) { - if (i + 1 >= args.len) fatal("expected argument after '{}'", .{arg}); + if (i + 1 >= args.len) fatal("expected argument after '{s}'", .{arg}); i += 1; override_local_cache_dir = args[i]; continue; } else if (mem.eql(u8, arg, "--global-cache-dir")) { - if (i + 1 >= args.len) fatal("expected argument after '{}'", .{arg}); + if (i + 1 >= args.len) fatal("expected argument after '{s}'", .{arg}); i += 1; override_global_cache_dir = args[i]; continue; @@ -2344,7 +2344,7 @@ pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v } else introspect.findZigLibDirFromSelfExe(arena, self_exe_path) catch |err| { - fatal("unable to find zig installation directory: {}", .{@errorName(err)}); + fatal("unable to find zig installation directory: {s}", .{@errorName(err)}); }; defer zig_lib_directory.handle.close(); @@ -2385,7 +2385,7 @@ pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v } else |err| switch (err) { error.FileNotFound => { dirname = fs.path.dirname(dirname) orelse { - std.log.info("{}", .{ + std.log.info("{s}", .{ \\Initialize a 'build.zig' template file with `zig init-lib` or `zig init-exe`, \\or see `zig --help` for more options. }); @@ -2467,7 +2467,7 @@ pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v .self_exe_path = self_exe_path, .thread_pool = &thread_pool, }) catch |err| { - fatal("unable to create compilation: {}", .{@errorName(err)}); + fatal("unable to create compilation: {s}", .{@errorName(err)}); }; defer comp.destroy(); @@ -2493,11 +2493,11 @@ pub fn cmdBuild(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v .Exited => |code| { if (code == 0) return cleanExit(); const cmd = try argvCmd(arena, child_argv); - fatal("the following build command failed with exit code {}:\n{}", .{ code, cmd }); + fatal("the following build command failed with exit code {d}:\n{s}", .{ code, cmd }); }, else => { const cmd = try argvCmd(arena, child_argv); - fatal("the following build command crashed:\n{}", .{cmd}); + fatal("the following build command crashed:\n{s}", .{cmd}); }, } } @@ -2564,14 +2564,14 @@ pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void { i += 1; const next_arg = args[i]; color = std.meta.stringToEnum(Color, next_arg) orelse { - fatal("expected [auto|on|off] after --color, found '{}'", .{next_arg}); + fatal("expected [auto|on|off] after --color, found '{s}'", .{next_arg}); }; } else if (mem.eql(u8, arg, "--stdin")) { stdin_flag = true; } else if (mem.eql(u8, arg, "--check")) { check_flag = true; } else { - fatal("unrecognized parameter: '{}'", .{arg}); + fatal("unrecognized parameter: '{s}'", .{arg}); } } else { try input_files.append(arg); @@ -2590,7 +2590,7 @@ pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void { defer gpa.free(source_code); const tree = std.zig.parse(gpa, source_code) catch |err| { - fatal("error parsing stdin: {}", .{err}); + fatal("error parsing stdin: {s}", .{err}); }; defer tree.deinit(); @@ -2629,7 +2629,7 @@ pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void { for (input_files.items) |file_path| { // Get the real path here to avoid Windows failing on relative file paths with . or .. in them. const real_path = fs.realpathAlloc(gpa, file_path) catch |err| { - fatal("unable to open '{}': {}", .{ file_path, err }); + fatal("unable to open '{s}': {s}", .{ file_path, @errorName(err) }); }; defer gpa.free(real_path); @@ -2668,7 +2668,7 @@ fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool, dir: fs.Dir, sub_ fmtPathFile(fmt, file_path, check_mode, dir, sub_path) catch |err| switch (err) { error.IsDir, error.AccessDenied => return fmtPathDir(fmt, file_path, check_mode, dir, sub_path), else => { - warn("unable to format '{}': {}", .{ file_path, err }); + warn("unable to format '{s}': {s}", .{ file_path, @errorName(err) }); fmt.any_error = true; return; }, @@ -2702,7 +2702,7 @@ fn fmtPathDir( try fmtPathDir(fmt, full_path, check_mode, dir, entry.name); } else { fmtPathFile(fmt, full_path, check_mode, dir, entry.name) catch |err| { - warn("unable to format '{}': {}", .{ full_path, err }); + warn("unable to format '{s}': {s}", .{ full_path, @errorName(err) }); fmt.any_error = true; return; }; @@ -2761,7 +2761,7 @@ fn fmtPathFile( const anything_changed = try std.zig.render(fmt.gpa, io.null_out_stream, tree); if (anything_changed) { const stdout = io.getStdOut().writer(); - try stdout.print("{}\n", .{file_path}); + try stdout.print("{s}\n", .{file_path}); fmt.any_error = true; } } else { @@ -2779,7 +2779,7 @@ fn fmtPathFile( try af.file.writeAll(fmt.out_buffer.items); try af.finish(); const stdout = io.getStdOut().writer(); - try stdout.print("{}\n", .{file_path}); + try stdout.print("{s}\n", .{file_path}); } } @@ -2812,7 +2812,7 @@ fn printErrMsgToFile( const text = text_buf.items; const stream = file.outStream(); - try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text }); + try stream.print("{s}:{d}:{d}: error: {s}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text }); if (!color_on) return; @@ -2984,7 +2984,7 @@ pub const ClangArgIterator = struct { const max_bytes = 10 * 1024 * 1024; // 10 MiB of command line arguments is a reasonable limit const resp_file_path = arg[1..]; const resp_contents = fs.cwd().readFileAlloc(allocator, resp_file_path, max_bytes) catch |err| { - fatal("unable to read response file '{}': {}", .{ resp_file_path, @errorName(err) }); + fatal("unable to read response file '{s}': {s}", .{ resp_file_path, @errorName(err) }); }; defer allocator.free(resp_contents); // TODO is there a specification for this file format? Let's find it and make this parsing more robust @@ -3057,7 +3057,7 @@ pub const ClangArgIterator = struct { const prefix_len = clang_arg.matchStartsWith(arg); if (prefix_len == arg.len) { if (self.next_index >= self.argv.len) { - fatal("Expected parameter after '{}'", .{arg}); + fatal("Expected parameter after '{s}'", .{arg}); } self.only_arg = self.argv[self.next_index]; self.incrementArgIndex(); @@ -3078,7 +3078,7 @@ pub const ClangArgIterator = struct { if (prefix_len != 0) { self.only_arg = arg[prefix_len..]; if (self.next_index >= self.argv.len) { - fatal("Expected parameter after '{}'", .{arg}); + fatal("Expected parameter after '{s}'", .{arg}); } self.second_arg = self.argv[self.next_index]; self.incrementArgIndex(); @@ -3089,7 +3089,7 @@ pub const ClangArgIterator = struct { }, .separate => if (clang_arg.matchEql(arg) > 0) { if (self.next_index >= self.argv.len) { - fatal("Expected parameter after '{}'", .{arg}); + fatal("Expected parameter after '{s}'", .{arg}); } self.only_arg = self.argv[self.next_index]; self.incrementArgIndex(); @@ -3115,7 +3115,7 @@ pub const ClangArgIterator = struct { }, } else { - fatal("Unknown Clang option: '{}'", .{arg}); + fatal("Unknown Clang option: '{s}'", .{arg}); } } @@ -3143,7 +3143,7 @@ pub const ClangArgIterator = struct { fn parseCodeModel(arg: []const u8) std.builtin.CodeModel { return std.meta.stringToEnum(std.builtin.CodeModel, arg) orelse - fatal("unsupported machine code model: '{}'", .{arg}); + fatal("unsupported machine code model: '{s}'", .{arg}); } /// Raise the open file descriptor limit. Ask and ye shall receive. @@ -3263,7 +3263,7 @@ fn detectNativeTargetInfo(gpa: *Allocator, cross_target: std.zig.CrossTarget) !s // CPU model & feature detection is todo so here we rely on LLVM. // https://github.com/ziglang/zig/issues/4591 if (!build_options.have_llvm) - fatal("CPU features detection is not yet available for {} without LLVM extensions", .{@tagName(arch)}); + fatal("CPU features detection is not yet available for {s} without LLVM extensions", .{@tagName(arch)}); const llvm = @import("llvm_bindings.zig"); const llvm_cpu_name = llvm.GetHostCPUName(); diff --git a/src/mingw.zig b/src/mingw.zig index 246b0f33dc..d55cc28b2b 100644 --- a/src/mingw.zig +++ b/src/mingw.zig @@ -381,7 +381,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void { const term = child.wait() catch |err| { // TODO surface a proper error here - log.err("unable to spawn {}: {}", .{ args[0], @errorName(err) }); + log.err("unable to spawn {s}: {s}", .{ args[0], @errorName(err) }); return error.ClangPreprocessorFailed; }; @@ -395,7 +395,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void { }, else => { // TODO surface a proper error here - log.err("clang terminated unexpectedly with stderr: {}", .{stderr}); + log.err("clang terminated unexpectedly with stderr: {s}", .{stderr}); return error.ClangPreprocessorFailed; }, } diff --git a/src/musl.zig b/src/musl.zig index f67fe90add..a865e78623 100644 --- a/src/musl.zig +++ b/src/musl.zig @@ -155,21 +155,21 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void { if (!is_arch_specific) { // Look for an arch specific override. override_path.shrinkRetainingCapacity(0); - try override_path.writer().print("{}" ++ s ++ "{}" ++ s ++ "{}.s", .{ + try override_path.writer().print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.s", .{ dirname, arch_name, noextbasename, }); if (source_table.contains(override_path.items)) continue; override_path.shrinkRetainingCapacity(0); - try override_path.writer().print("{}" ++ s ++ "{}" ++ s ++ "{}.S", .{ + try override_path.writer().print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.S", .{ dirname, arch_name, noextbasename, }); if (source_table.contains(override_path.items)) continue; override_path.shrinkRetainingCapacity(0); - try override_path.writer().print("{}" ++ s ++ "{}" ++ s ++ "{}.c", .{ + try override_path.writer().print("{s}" ++ s ++ "{s}" ++ s ++ "{s}.c", .{ dirname, arch_name, noextbasename, }); if (source_table.contains(override_path.items)) @@ -322,7 +322,7 @@ fn add_cc_args( const target = comp.getTarget(); const arch_name = target_util.archMuslName(target.cpu.arch); const os_name = @tagName(target.os.tag); - const triple = try std.fmt.allocPrint(arena, "{}-{}-musl", .{ arch_name, os_name }); + const triple = try std.fmt.allocPrint(arena, "{s}-{s}-musl", .{ arch_name, os_name }); const o_arg = if (want_O3) "-O3" else "-Os"; try args.appendSlice(&[_][]const u8{ diff --git a/src/print_env.zig b/src/print_env.zig index 8aa692e644..bcf4a983ab 100644 --- a/src/print_env.zig +++ b/src/print_env.zig @@ -9,7 +9,7 @@ pub fn cmdEnv(gpa: *Allocator, args: []const []const u8, stdout: std.fs.File.Wri defer gpa.free(self_exe_path); var zig_lib_directory = introspect.findZigLibDirFromSelfExe(gpa, self_exe_path) catch |err| { - fatal("unable to find zig installation directory: {}\n", .{@errorName(err)}); + fatal("unable to find zig installation directory: {s}\n", .{@errorName(err)}); }; defer gpa.free(zig_lib_directory.path.?); defer zig_lib_directory.handle.close(); diff --git a/src/print_targets.zig b/src/print_targets.zig index 724cb7a9ac..cf55eee516 100644 --- a/src/print_targets.zig +++ b/src/print_targets.zig @@ -18,7 +18,7 @@ pub fn cmdTargets( native_target: Target, ) !void { var zig_lib_directory = introspect.findZigLibDir(allocator) catch |err| { - fatal("unable to find zig installation directory: {}\n", .{@errorName(err)}); + fatal("unable to find zig installation directory: {s}\n", .{@errorName(err)}); }; defer zig_lib_directory.handle.close(); defer allocator.free(zig_lib_directory.path.?); @@ -61,7 +61,7 @@ pub fn cmdTargets( try jws.objectField("libc"); try jws.beginArray(); for (target.available_libcs) |libc| { - const tmp = try std.fmt.allocPrint(allocator, "{}-{}-{}", .{ + const tmp = try std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{ @tagName(libc.arch), @tagName(libc.os), @tagName(libc.abi), }); defer allocator.free(tmp); diff --git a/src/stage1.zig b/src/stage1.zig index 1d50a71ad1..cf3a252ce8 100644 --- a/src/stage1.zig +++ b/src/stage1.zig @@ -37,14 +37,14 @@ pub export fn main(argc: c_int, argv: [*][*:0]u8) c_int { defer arena_instance.deinit(); const arena = &arena_instance.allocator; - const args = arena.alloc([]const u8, @intCast(usize, argc)) catch fatal("{}", .{"OutOfMemory"}); + const args = arena.alloc([]const u8, @intCast(usize, argc)) catch fatal("{s}", .{"OutOfMemory"}); for (args) |*arg, i| { arg.* = mem.spanZ(argv[i]); } if (std.builtin.mode == .Debug) { stage2.mainArgs(gpa, arena, args) catch unreachable; } else { - stage2.mainArgs(gpa, arena, args) catch |err| fatal("{}", .{@errorName(err)}); + stage2.mainArgs(gpa, arena, args) catch |err| fatal("{s}", .{@errorName(err)}); } return 0; } diff --git a/src/test.zig b/src/test.zig index 6d76ae39c1..b74732d10d 100644 --- a/src/test.zig +++ b/src/test.zig @@ -660,7 +660,7 @@ pub const TestContext = struct { } } if (comp.bin_file.cast(link.File.C)) |c_file| { - std.debug.print("Generated C: \n===============\n{}\n\n===========\n\n", .{ + std.debug.print("Generated C: \n===============\n{s}\n\n===========\n\n", .{ c_file.main.items, }); } diff --git a/src/translate_c.zig b/src/translate_c.zig index 1b2aa4b219..1b6455fd4d 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -136,7 +136,7 @@ const Scope = struct { var proposed_name = name_copy; while (scope.contains(proposed_name)) { scope.mangle_count += 1; - proposed_name = try std.fmt.allocPrint(c.arena, "{}_{}", .{ name, scope.mangle_count }); + proposed_name = try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ name, scope.mangle_count }); } try scope.variables.append(.{ .name = name_copy, .alias = proposed_name }); return proposed_name; @@ -290,7 +290,7 @@ pub const Context = struct { const line = c.source_manager.getSpellingLineNumber(spelling_loc); const column = c.source_manager.getSpellingColumnNumber(spelling_loc); - return std.fmt.allocPrint(c.arena, "{}:{}:{}", .{ filename, line, column }); + return std.fmt.allocPrint(c.arena, "{s}:{d}:{d}", .{ filename, line, column }); } fn createCall(c: *Context, fn_expr: *ast.Node, params_len: ast.NodeIndex) !*ast.Node.Call { @@ -440,7 +440,7 @@ pub fn translate( mem.copy(*ast.Node, root_node.decls(), context.root_decls.items); if (false) { - std.debug.warn("debug source:\n{}\n==EOF==\ntokens:\n", .{source_buffer.items}); + std.debug.warn("debug source:\n{s}\n==EOF==\ntokens:\n", .{source_buffer.items}); for (context.token_ids.items) |token| { std.debug.warn("{}\n", .{token}); } @@ -530,7 +530,7 @@ fn declVisitor(c: *Context, decl: *const clang.Decl) Error!void { }, else => { const decl_name = try c.str(decl.getDeclKindName()); - try emitWarning(c, decl.getLocation(), "ignoring {} declaration", .{decl_name}); + try emitWarning(c, decl.getLocation(), "ignoring {s} declaration", .{decl_name}); }, } } @@ -625,7 +625,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const clang.FunctionDecl) Error!void { const param_name = if (param.name_token) |name_tok| tokenSlice(c, name_tok) else - return failDecl(c, fn_decl_loc, fn_name, "function {} parameter has no name", .{fn_name}); + return failDecl(c, fn_decl_loc, fn_name, "function {s} parameter has no name", .{fn_name}); const c_param = fn_decl.getParamDecl(param_id); const qual_type = c_param.getOriginalType(); @@ -634,7 +634,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const clang.FunctionDecl) Error!void { const mangled_param_name = try block_scope.makeMangledName(c, param_name); if (!is_const) { - const bare_arg_name = try std.fmt.allocPrint(c.arena, "arg_{}", .{mangled_param_name}); + const bare_arg_name = try std.fmt.allocPrint(c.arena, "arg_{s}", .{mangled_param_name}); const arg_name = try block_scope.makeMangledName(c, bare_arg_name); const mut_tok = try appendToken(c, .Keyword_var, "var"); @@ -727,7 +727,7 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co // TODO https://github.com/ziglang/zig/issues/3756 // TODO https://github.com/ziglang/zig/issues/1802 - const checked_name = if (isZigPrimitiveType(var_name)) try std.fmt.allocPrint(c.arena, "{}_{}", .{ var_name, c.getMangle() }) else var_name; + const checked_name = if (isZigPrimitiveType(var_name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ var_name, c.getMangle() }) else var_name; const var_decl_loc = var_decl.getLocation(); const qual_type = var_decl.getTypeSourceInfo_getType(); @@ -808,7 +808,7 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co _ = try appendToken(rp.c, .LParen, "("); const expr = try transCreateNodeStringLiteral( rp.c, - try std.fmt.allocPrint(rp.c.arena, "\"{}\"", .{str_ptr[0..str_len]}), + try std.fmt.allocPrint(rp.c.arena, "\"{s}\"", .{str_ptr[0..str_len]}), ); _ = try appendToken(rp.c, .RParen, ")"); @@ -887,7 +887,7 @@ fn transTypeDef(c: *Context, typedef_decl: *const clang.TypedefNameDecl, top_lev // TODO https://github.com/ziglang/zig/issues/3756 // TODO https://github.com/ziglang/zig/issues/1802 - const checked_name = if (isZigPrimitiveType(typedef_name)) try std.fmt.allocPrint(c.arena, "{}_{}", .{ typedef_name, c.getMangle() }) else typedef_name; + const checked_name = if (isZigPrimitiveType(typedef_name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ typedef_name, c.getMangle() }) else typedef_name; if (checkForBuiltinTypedef(checked_name)) |builtin| { return transTypeDefAsBuiltin(c, typedef_decl, builtin); } @@ -945,7 +945,7 @@ fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*as // Record declarations such as `struct {...} x` have no name but they're not // anonymous hence here isAnonymousStructOrUnion is not needed if (bare_name.len == 0) { - bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{}", .{c.getMangle()}); + bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{d}", .{c.getMangle()}); is_unnamed = true; } @@ -958,11 +958,11 @@ fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*as container_kind_name = "struct"; container_kind = .Keyword_struct; } else { - try emitWarning(c, record_loc, "record {} is not a struct or union", .{bare_name}); + try emitWarning(c, record_loc, "record {s} is not a struct or union", .{bare_name}); return null; } - const name = try std.fmt.allocPrint(c.arena, "{}_{}", .{ container_kind_name, bare_name }); + const name = try std.fmt.allocPrint(c.arena, "{s}_{s}", .{ container_kind_name, bare_name }); _ = try c.decl_table.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), name); const visib_tok = if (!is_unnamed) try appendToken(c, .Keyword_pub, "pub") else null; @@ -1003,7 +1003,7 @@ fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*as _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); - try emitWarning(c, field_loc, "{} demoted to opaque type - has bitfield", .{container_kind_name}); + try emitWarning(c, field_loc, "{s} demoted to opaque type - has bitfield", .{container_kind_name}); break :blk opaque_type; } @@ -1011,7 +1011,7 @@ fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*as _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); - try emitWarning(c, field_loc, "{} demoted to opaque type - has variable length array", .{container_kind_name}); + try emitWarning(c, field_loc, "{s} demoted to opaque type - has variable length array", .{container_kind_name}); break :blk opaque_type; } @@ -1019,7 +1019,7 @@ fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*as var raw_name = try c.str(@ptrCast(*const clang.NamedDecl, field_decl).getName_bytes_begin()); if (field_decl.isAnonymousStructOrUnion() or raw_name.len == 0) { // Context.getMangle() is not used here because doing so causes unpredictable field names for anonymous fields. - raw_name = try std.fmt.allocPrint(c.arena, "unnamed_{}", .{unnamed_field_count}); + raw_name = try std.fmt.allocPrint(c.arena, "unnamed_{d}", .{unnamed_field_count}); unnamed_field_count += 1; is_anon = true; } @@ -1030,7 +1030,7 @@ fn transRecordDecl(c: *Context, record_decl: *const clang.RecordDecl) Error!?*as _ = try c.opaque_demotes.put(c.gpa, @ptrToInt(record_decl.getCanonicalDecl()), {}); const opaque_type = try transCreateNodeOpaqueType(c); semicolon = try appendToken(c, .Semicolon, ";"); - try emitWarning(c, record_loc, "{} demoted to opaque type - unable to translate type of field {}", .{ container_kind_name, raw_name }); + try emitWarning(c, record_loc, "{s} demoted to opaque type - unable to translate type of field {s}", .{ container_kind_name, raw_name }); break :blk opaque_type; }, else => |e| return e, @@ -1110,11 +1110,11 @@ fn transEnumDecl(c: *Context, enum_decl: *const clang.EnumDecl) Error!?*ast.Node var bare_name = try c.str(@ptrCast(*const clang.NamedDecl, enum_decl).getName_bytes_begin()); var is_unnamed = false; if (bare_name.len == 0) { - bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{}", .{c.getMangle()}); + bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{d}", .{c.getMangle()}); is_unnamed = true; } - const name = try std.fmt.allocPrint(c.arena, "enum_{}", .{bare_name}); + const name = try std.fmt.allocPrint(c.arena, "enum_{s}", .{bare_name}); _ = try c.decl_table.put(c.gpa, @ptrToInt(enum_decl.getCanonicalDecl()), name); const visib_tok = if (!is_unnamed) try appendToken(c, .Keyword_pub, "pub") else null; @@ -1385,7 +1385,7 @@ fn transStmt( rp, error.UnsupportedTranslation, stmt.getBeginLoc(), - "TODO implement translation of stmt class {}", + "TODO implement translation of stmt class {s}", .{@tagName(sc)}, ); }, @@ -1684,7 +1684,7 @@ fn transDeclStmtOne( rp, error.UnsupportedTranslation, decl.getLocation(), - "TODO implement translation of DeclStmt kind {}", + "TODO implement translation of DeclStmt kind {s}", .{@tagName(kind)}, ), } @@ -1782,7 +1782,7 @@ fn transImplicitCastExpr( rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, expr).getBeginLoc(), - "TODO implement translation of CastKind {}", + "TODO implement translation of CastKind {s}", .{@tagName(kind)}, ), } @@ -2043,7 +2043,7 @@ fn transStringLiteral( rp, error.UnsupportedTranslation, @ptrCast(*const clang.Stmt, stmt).getBeginLoc(), - "TODO: support string literal kind {}", + "TODO: support string literal kind {s}", .{kind}, ), } @@ -2168,7 +2168,6 @@ fn transCCast( // @boolToInt returns either a comptime_int or a u1 // TODO: if dst_type is 1 bit & signed (bitfield) we need @bitCast // instead of @as - const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1); builtin_node.params()[0] = expr; builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")"); @@ -2455,7 +2454,7 @@ fn transInitListExpr( ); } else { const type_name = rp.c.str(qual_type.getTypeClassName()); - return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported initlist type: '{}'", .{type_name}); + return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported initlist type: '{s}'", .{type_name}); } } @@ -3957,7 +3956,7 @@ fn qualTypeToLog2IntRef(rp: RestorePoint, qt: clang.QualType, source_loc: clang. const node = try rp.c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .IntegerLiteral }, - .token = try appendTokenFmt(rp.c, .Identifier, "u{}", .{cast_bit_width}), + .token = try appendTokenFmt(rp.c, .Identifier, "u{d}", .{cast_bit_width}), }; return &node.base; } @@ -4433,7 +4432,8 @@ fn transCreateNodeBoolLiteral(c: *Context, value: bool) !*ast.Node { } fn transCreateNodeInt(c: *Context, int: anytype) !*ast.Node { - const token = try appendTokenFmt(c, .IntegerLiteral, "{}", .{int}); + const fmt_s = if (comptime std.meta.trait.isIntegerNumber(@TypeOf(int))) "{d}" else "{s}"; + const token = try appendTokenFmt(c, .IntegerLiteral, fmt_s, .{int}); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .IntegerLiteral }, @@ -4442,8 +4442,8 @@ fn transCreateNodeInt(c: *Context, int: anytype) !*ast.Node { return &node.base; } -fn transCreateNodeFloat(c: *Context, int: anytype) !*ast.Node { - const token = try appendTokenFmt(c, .FloatLiteral, "{}", .{int}); +fn transCreateNodeFloat(c: *Context, str: []const u8) !*ast.Node { + const token = try appendTokenFmt(c, .FloatLiteral, "{s}", .{str}); const node = try c.arena.create(ast.Node.OneToken); node.* = .{ .base = .{ .tag = .FloatLiteral }, @@ -4484,7 +4484,7 @@ fn transCreateNodeMacroFn(c: *Context, name: []const u8, ref: *ast.Node, proto_a _ = try appendToken(c, .Comma, ","); } const param_name_tok = param.name_token orelse - try appendTokenFmt(c, .Identifier, "arg_{}", .{c.getMangle()}); + try appendTokenFmt(c, .Identifier, "arg_{d}", .{c.getMangle()}); _ = try appendToken(c, .Colon, ":"); @@ -4916,7 +4916,7 @@ fn transType(rp: RestorePoint, ty: *const clang.Type, source_loc: clang.SourceLo }, else => { const type_name = rp.c.str(ty.getTypeClassName()); - return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported type: '{}'", .{type_name}); + return revertAndWarn(rp, error.UnsupportedType, source_loc, "unsupported type: '{s}'", .{type_name}); }, } } @@ -4999,7 +4999,7 @@ fn transCC( rp, error.UnsupportedType, source_loc, - "unsupported calling convention: {}", + "unsupported calling convention: {s}", .{@tagName(clang_cc)}, ), } @@ -5117,7 +5117,7 @@ fn finishTransFnProto( _ = try appendToken(rp.c, .LParen, "("); const expr = try transCreateNodeStringLiteral( rp.c, - try std.fmt.allocPrint(rp.c.arena, "\"{}\"", .{str_ptr[0..str_len]}), + try std.fmt.allocPrint(rp.c.arena, "\"{s}\"", .{str_ptr[0..str_len]}), ); _ = try appendToken(rp.c, .RParen, ")"); @@ -5214,7 +5214,7 @@ fn revertAndWarn( fn emitWarning(c: *Context, loc: clang.SourceLocation, comptime format: []const u8, args: anytype) !void { const args_prefix = .{c.locStr(loc)}; - _ = try appendTokenFmt(c, .LineComment, "// {}: warning: " ++ format, args_prefix ++ args); + _ = try appendTokenFmt(c, .LineComment, "// {s}: warning: " ++ format, args_prefix ++ args); } pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, comptime format: []const u8, args: anytype) !void { @@ -5228,7 +5228,7 @@ pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, compti const msg_tok = try appendTokenFmt(c, .StringLiteral, "\"" ++ format ++ "\"", args); const rparen_tok = try appendToken(c, .RParen, ")"); const semi_tok = try appendToken(c, .Semicolon, ";"); - _ = try appendTokenFmt(c, .LineComment, "// {}", .{c.locStr(loc)}); + _ = try appendTokenFmt(c, .LineComment, "// {s}", .{c.locStr(loc)}); const msg_node = try c.arena.create(ast.Node.OneToken); msg_node.* = .{ @@ -5258,7 +5258,7 @@ pub fn failDecl(c: *Context, loc: clang.SourceLocation, name: []const u8, compti fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenIndex { std.debug.assert(token_id != .Identifier); // use appendIdentifier - return appendTokenFmt(c, token_id, "{}", .{bytes}); + return appendTokenFmt(c, token_id, "{s}", .{bytes}); } fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: anytype) !ast.TokenIndex { @@ -5329,7 +5329,7 @@ fn transCreateNodeIdentifier(c: *Context, name: []const u8) !*ast.Node { } fn transCreateNodeIdentifierUnchecked(c: *Context, name: []const u8) !*ast.Node { - const token_index = try appendTokenFmt(c, .Identifier, "{}", .{name}); + const token_index = try appendTokenFmt(c, .Identifier, "{s}", .{name}); const identifier = try c.arena.create(ast.Node.OneToken); identifier.* = .{ .base = .{ .tag = .Identifier }, @@ -5390,7 +5390,7 @@ fn transPreprocessorEntities(c: *Context, unit: *clang.ASTUnit) Error!void { const name = try c.str(raw_name); // TODO https://github.com/ziglang/zig/issues/3756 // TODO https://github.com/ziglang/zig/issues/1802 - const mangled_name = if (isZigPrimitiveType(name)) try std.fmt.allocPrint(c.arena, "{}_{}", .{ name, c.getMangle() }) else name; + const mangled_name = if (isZigPrimitiveType(name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ name, c.getMangle() }) else name; if (scope.containsNow(mangled_name)) { continue; } @@ -5468,7 +5468,7 @@ fn transMacroDefine(c: *Context, m: *MacroCtx) ParseError!void { const init_node = try parseCExpr(c, m, scope); const last = m.next().?; if (last != .Eof and last != .Nl) - return m.fail(c, "unable to translate C expr: unexpected token .{}", .{@tagName(last)}); + return m.fail(c, "unable to translate C expr: unexpected token .{s}", .{@tagName(last)}); const semicolon_token = try appendToken(c, .Semicolon, ";"); const node = try ast.Node.VarDecl.create(c.arena, .{ @@ -5540,7 +5540,7 @@ fn transMacroFnDefine(c: *Context, m: *MacroCtx) ParseError!void { const expr = try parseCExpr(c, m, scope); const last = m.next().?; if (last != .Eof and last != .Nl) - return m.fail(c, "unable to translate C expr: unexpected token .{}", .{@tagName(last)}); + return m.fail(c, "unable to translate C expr: unexpected token .{s}", .{@tagName(last)}); _ = try appendToken(c, .Semicolon, ";"); const type_of_arg = if (!expr.tag.isBlock()) expr else blk: { const stmts = expr.blockStatements(); @@ -5623,11 +5623,11 @@ fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!*ast.Node { switch (lit_bytes[1]) { '0'...'7' => { // Octal - lit_bytes = try std.fmt.allocPrint(c.arena, "0o{}", .{lit_bytes}); + lit_bytes = try std.fmt.allocPrint(c.arena, "0o{s}", .{lit_bytes}); }, 'X' => { // Hexadecimal with capital X, valid in C but not in Zig - lit_bytes = try std.fmt.allocPrint(c.arena, "0x{}", .{lit_bytes[2..]}); + lit_bytes = try std.fmt.allocPrint(c.arena, "0x{s}", .{lit_bytes[2..]}); }, else => {}, } @@ -5659,7 +5659,7 @@ fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!*ast.Node { }, .FloatLiteral => |suffix| { if (lit_bytes[0] == '.') - lit_bytes = try std.fmt.allocPrint(c.arena, "0{}", .{lit_bytes}); + lit_bytes = try std.fmt.allocPrint(c.arena, "0{s}", .{lit_bytes}); if (suffix == .none) { return transCreateNodeFloat(c, lit_bytes); } @@ -5916,11 +5916,11 @@ fn parseCPrimaryExprInner(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!* // struct Foo will be declared as struct_Foo by transRecordDecl const next_id = m.next().?; if (next_id != .Identifier) { - try m.fail(c, "unable to translate C expr: expected Identifier instead got: {}", .{@tagName(next_id)}); + try m.fail(c, "unable to translate C expr: expected Identifier instead got: {s}", .{@tagName(next_id)}); return error.ParseError; } - const ident_token = try appendTokenFmt(c, .Identifier, "{}_{}", .{ slice, m.slice() }); + const ident_token = try appendTokenFmt(c, .Identifier, "{s}_{s}", .{ slice, m.slice() }); const identifier = try c.arena.create(ast.Node.OneToken); identifier.* = .{ .base = .{ .tag = .Identifier }, @@ -5937,7 +5937,7 @@ fn parseCPrimaryExprInner(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!* const next_id = m.next().?; if (next_id != .RParen) { - try m.fail(c, "unable to translate C expr: expected ')' instead got: {}", .{@tagName(next_id)}); + try m.fail(c, "unable to translate C expr: expected ')' instead got: {s}", .{@tagName(next_id)}); return error.ParseError; } var saw_l_paren = false; @@ -5995,7 +5995,7 @@ fn parseCPrimaryExprInner(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!* return &group_node.base; }, else => { - try m.fail(c, "unable to translate C expr: unexpected token .{}", .{@tagName(tok)}); + try m.fail(c, "unable to translate C expr: unexpected token .{s}", .{@tagName(tok)}); return error.ParseError; }, } diff --git a/src/type.zig b/src/type.zig index bb2e3b3bc2..9e2cd321f0 100644 --- a/src/type.zig +++ b/src/type.zig @@ -558,21 +558,21 @@ pub const Type = extern union { }, .array_u8 => { const len = ty.castTag(.array_u8).?.data; - return out_stream.print("[{}]u8", .{len}); + return out_stream.print("[{d}]u8", .{len}); }, .array_u8_sentinel_0 => { const len = ty.castTag(.array_u8_sentinel_0).?.data; - return out_stream.print("[{}:0]u8", .{len}); + return out_stream.print("[{d}:0]u8", .{len}); }, .array => { const payload = ty.castTag(.array).?.data; - try out_stream.print("[{}]", .{payload.len}); + try out_stream.print("[{d}]", .{payload.len}); ty = payload.elem_type; continue; }, .array_sentinel => { const payload = ty.castTag(.array_sentinel).?.data; - try out_stream.print("[{}:{}]", .{ payload.len, payload.sentinel }); + try out_stream.print("[{d}:{}]", .{ payload.len, payload.sentinel }); ty = payload.elem_type; continue; }, diff --git a/src/value.zig b/src/value.zig index 8180df2f9e..10f58fa44f 100644 --- a/src/value.zig +++ b/src/value.zig @@ -464,7 +464,7 @@ pub const Value = extern union { .ty => return val.castTag(.ty).?.data.format("", options, out_stream), .int_type => { const int_type = val.castTag(.int_type).?.data; - return out_stream.print("{}{}", .{ + return out_stream.print("{s}{d}", .{ if (int_type.signed) "s" else "u", int_type.bits, }); @@ -507,7 +507,7 @@ pub const Value = extern union { } return out_stream.writeAll("}"); }, - .@"error" => return out_stream.print("error.{}", .{val.castTag(.@"error").?.data.name}), + .@"error" => return out_stream.print("error.{s}", .{val.castTag(.@"error").?.data.name}), .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"), }; } diff --git a/src/zir.zig b/src/zir.zig index ce8498d7e8..0593cbd8fd 100644 --- a/src/zir.zig +++ b/src/zir.zig @@ -1150,7 +1150,7 @@ pub const Module = struct { for (self.decls) |decl, i| { write.next_instr_index = 0; - try stream.print("@{} ", .{decl.name}); + try stream.print("@{s} ", .{decl.name}); try write.writeInstToStream(stream, decl.inst); try stream.writeByte('\n'); } @@ -1206,13 +1206,13 @@ const Writer = struct { if (@typeInfo(arg_field.field_type) == .Optional) { if (@field(inst.kw_args, arg_field.name)) |non_optional| { if (need_comma) try stream.writeAll(", "); - try stream.print("{}=", .{arg_field.name}); + try stream.print("{s}=", .{arg_field.name}); try self.writeParamToStream(stream, &non_optional); need_comma = true; } } else { if (need_comma) try stream.writeAll(", "); - try stream.print("{}=", .{arg_field.name}); + try stream.print("{s}=", .{arg_field.name}); try self.writeParamToStream(stream, &@field(inst.kw_args, arg_field.name)); need_comma = true; } @@ -1257,12 +1257,12 @@ const Writer = struct { self.next_instr_index += 1; try self.inst_table.putNoClobber(inst, .{ .inst = inst, .index = my_i, .name = undefined }); try stream.writeByteNTimes(' ', self.indent); - try stream.print("%{} ", .{my_i}); + try stream.print("%{d} ", .{my_i}); if (inst.cast(Inst.Block)) |block| { - const name = try std.fmt.allocPrint(&self.arena.allocator, "label_{}", .{my_i}); + const name = try std.fmt.allocPrint(&self.arena.allocator, "label_{d}", .{my_i}); try self.block_table.put(block, name); } else if (inst.cast(Inst.Loop)) |loop| { - const name = try std.fmt.allocPrint(&self.arena.allocator, "loop_{}", .{my_i}); + const name = try std.fmt.allocPrint(&self.arena.allocator, "loop_{d}", .{my_i}); try self.loop_table.put(loop, name); } self.indent += 2; @@ -1332,18 +1332,18 @@ const Writer = struct { fn writeInstParamToStream(self: *Writer, stream: anytype, inst: *Inst) !void { if (self.inst_table.get(inst)) |info| { if (info.index) |i| { - try stream.print("%{}", .{info.index}); + try stream.print("%{d}", .{info.index}); } else { - try stream.print("@{}", .{info.name}); + try stream.print("@{s}", .{info.name}); } } else if (inst.cast(Inst.DeclVal)) |decl_val| { - try stream.print("@{}", .{decl_val.positionals.name}); + try stream.print("@{s}", .{decl_val.positionals.name}); } else if (inst.cast(Inst.DeclValInModule)) |decl_val| { - try stream.print("@{}", .{decl_val.positionals.decl.name}); + try stream.print("@{s}", .{decl_val.positionals.decl.name}); } else { // This should be unreachable in theory, but since ZIR is used for debugging the compiler // we output some debug text instead. - try stream.print("?{}?", .{@tagName(inst.tag)}); + try stream.print("?{s}?", .{@tagName(inst.tag)}); } } }; @@ -1424,7 +1424,7 @@ const Parser = struct { const decl = try parseInstruction(self, &body_context, ident); const ident_index = body_context.instructions.items.len; if (try body_context.name_map.fetchPut(ident, decl.inst)) |_| { - return self.fail("redefinition of identifier '{}'", .{ident}); + return self.fail("redefinition of identifier '{s}'", .{ident}); } try body_context.instructions.append(decl.inst); continue; @@ -1510,7 +1510,7 @@ const Parser = struct { const decl = try parseInstruction(self, null, ident); const ident_index = self.decls.items.len; if (try self.global_name_map.fetchPut(ident, decl.inst)) |_| { - return self.fail("redefinition of identifier '{}'", .{ident}); + return self.fail("redefinition of identifier '{s}'", .{ident}); } try self.decls.append(self.allocator, decl); }, @@ -1538,7 +1538,7 @@ const Parser = struct { for (bytes) |byte| { if (self.source[self.i] != byte) { self.i = start; - return self.fail("expected '{}'", .{bytes}); + return self.fail("expected '{s}'", .{bytes}); } self.i += 1; } @@ -1585,7 +1585,7 @@ const Parser = struct { return parseInstructionGeneric(self, field.name, tag.Type(), tag, body_ctx, name, contents_start); } } - return self.fail("unknown instruction '{}'", .{fn_name}); + return self.fail("unknown instruction '{s}'", .{fn_name}); } fn parseInstructionGeneric( @@ -1621,7 +1621,7 @@ const Parser = struct { self.i += 1; skipSpace(self); } else if (self.source[self.i] == ')') { - return self.fail("expected positional parameter '{}'", .{arg_field.name}); + return self.fail("expected positional parameter '{s}'", .{arg_field.name}); } @field(inst_specific.positionals, arg_field.name) = try parseParameterGeneric( self, @@ -1648,7 +1648,7 @@ const Parser = struct { break; } } else { - return self.fail("unrecognized keyword parameter: '{}'", .{name}); + return self.fail("unrecognized keyword parameter: '{s}'", .{name}); } skipSpace(self); } @@ -1660,7 +1660,6 @@ const Parser = struct { .contents_hash = std.zig.hashSrc(self.source[contents_start..self.i]), .inst = &inst_specific.base, }; - //std.debug.warn("parsed {} = '{}'\n", .{ inst_specific.base.name, inst_specific.base.contents }); return decl; } @@ -1672,7 +1671,7 @@ const Parser = struct { ' ', '\n', ',', ')' => { const enum_name = self.source[start..self.i]; return std.meta.stringToEnum(T, enum_name) orelse { - return self.fail("tag '{}' not a member of enum '{}'", .{ enum_name, @typeName(T) }); + return self.fail("tag '{s}' not a member of enum '{s}'", .{ enum_name, @typeName(T) }); }; }, 0 => return self.failByte(0), @@ -1710,7 +1709,7 @@ const Parser = struct { BigIntConst => return self.parseIntegerLiteral(), usize => { const big_int = try self.parseIntegerLiteral(); - return big_int.to(usize) catch |err| return self.fail("integer literal: {}", .{@errorName(err)}); + return big_int.to(usize) catch |err| return self.fail("integer literal: {s}", .{@errorName(err)}); }, TypedValue => return self.fail("'const' is a special instruction; not legal in ZIR text", .{}), *IrModule.Decl => return self.fail("'declval_in_module' is a special instruction; not legal in ZIR text", .{}), @@ -1759,7 +1758,7 @@ const Parser = struct { }, else => @compileError("Unimplemented: ir parseParameterGeneric for type " ++ @typeName(T)), } - return self.fail("TODO parse parameter {}", .{@typeName(T)}); + return self.fail("TODO parse parameter {s}", .{@typeName(T)}); } fn parseParameterInst(self: *Parser, body_ctx: ?*Body) !*Inst { @@ -1788,7 +1787,7 @@ const Parser = struct { const src = name_start - 1; if (local_ref) { self.i = src; - return self.fail("unrecognized identifier: {}", .{bad_name}); + return self.fail("unrecognized identifier: {s}", .{bad_name}); } else { const declval = try self.arena.allocator.create(Inst.DeclVal); declval.* = .{ @@ -1805,7 +1804,7 @@ const Parser = struct { } fn generateName(self: *Parser) ![]u8 { - const result = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${}", .{self.unnamed_index}); + const result = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${d}", .{self.unnamed_index}); self.unnamed_index += 1; return result; } @@ -1873,7 +1872,7 @@ pub fn dumpFn(old_module: IrModule, module_fn: *IrModule.Fn) void { const fn_ty = module_fn.owner_decl.typed_value.most_recent.typed_value.ty; _ = ctx.emitFn(module_fn, 0, fn_ty) catch |err| { - std.debug.print("unable to dump function: {}\n", .{err}); + std.debug.print("unable to dump function: {s}\n", .{@errorName(err)}); return; }; var module = Module{ @@ -2203,7 +2202,7 @@ const EmitZIR = struct { }; return self.emitStringLiteral(src, bytes); }, - else => |t| std.debug.panic("TODO implement emitTypedValue for pointer to {}", .{@tagName(t)}), + else => |t| std.debug.panic("TODO implement emitTypedValue for pointer to {s}", .{@tagName(t)}), } }, .ComptimeInt => return self.emitComptimeIntVal(src, typed_value.val), @@ -2274,7 +2273,7 @@ const EmitZIR = struct { }; return self.emitUnnamedDecl(&inst.base); }, - else => |t| std.debug.panic("TODO implement emitTypedValue for {}", .{@tagName(t)}), + else => |t| std.debug.panic("TODO implement emitTypedValue for {s}", .{@tagName(t)}), } } @@ -2865,7 +2864,7 @@ const EmitZIR = struct { fn autoName(self: *EmitZIR) ![]u8 { while (true) { - const proposed_name = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${}", .{self.next_auto_name}); + const proposed_name = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${d}", .{self.next_auto_name}); self.next_auto_name += 1; const gop = try self.names.getOrPut(proposed_name); if (!gop.found_existing) { @@ -2947,25 +2946,25 @@ pub fn dumpZir(allocator: *Allocator, kind: []const u8, decl_name: [*:0]const u8 try write.inst_table.ensureCapacity(@intCast(u32, instructions.len)); const stderr = std.io.getStdErr().outStream(); - try stderr.print("{} {s} {{ // unanalyzed\n", .{ kind, decl_name }); + try stderr.print("{s} {s} {{ // unanalyzed\n", .{ kind, decl_name }); for (instructions) |inst| { const my_i = write.next_instr_index; write.next_instr_index += 1; if (inst.cast(Inst.Block)) |block| { - const name = try std.fmt.allocPrint(&write.arena.allocator, "label_{}", .{my_i}); + const name = try std.fmt.allocPrint(&write.arena.allocator, "label_{d}", .{my_i}); try write.block_table.put(block, name); } else if (inst.cast(Inst.Loop)) |loop| { - const name = try std.fmt.allocPrint(&write.arena.allocator, "loop_{}", .{my_i}); + const name = try std.fmt.allocPrint(&write.arena.allocator, "loop_{d}", .{my_i}); try write.loop_table.put(loop, name); } try write.inst_table.putNoClobber(inst, .{ .inst = inst, .index = my_i, .name = "inst" }); - try stderr.print(" %{} ", .{my_i}); + try stderr.print(" %{d} ", .{my_i}); try write.writeInstToStream(stderr, inst); try stderr.writeByte('\n'); } - try stderr.print("}} // {} {s}\n\n", .{ kind, decl_name }); + try stderr.print("}} // {s} {s}\n\n", .{ kind, decl_name }); } diff --git a/src/zir_sema.zig b/src/zir_sema.zig index 629dfa0c9a..f9cd0e1a3d 100644 --- a/src/zir_sema.zig +++ b/src/zir_sema.zig @@ -274,7 +274,7 @@ pub fn resolveInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError! const entry = if (old_inst.cast(zir.Inst.DeclVal)) |declval| blk: { const decl_name = declval.positionals.name; const entry = zir_module.contents.module.findDecl(decl_name) orelse - return mod.fail(scope, old_inst.src, "decl '{}' not found", .{decl_name}); + return mod.fail(scope, old_inst.src, "decl '{s}' not found", .{decl_name}); break :blk entry; } else blk: { // If this assert trips, the instruction that was referenced did not get @@ -535,7 +535,7 @@ fn analyzeInstParamType(mod: *Module, scope: *Scope, inst: *zir.Inst.ParamType) // TODO support C-style var args const param_count = fn_ty.fnParamLen(); if (arg_index >= param_count) { - return mod.fail(scope, inst.base.src, "arg index {} out of bounds; '{}' has {} argument(s)", .{ + return mod.fail(scope, inst.base.src, "arg index {d} out of bounds; '{}' has {d} argument(s)", .{ arg_index, fn_ty, param_count, @@ -564,14 +564,14 @@ fn analyzeInstStr(mod: *Module, scope: *Scope, str_inst: *zir.Inst.Str) InnerErr fn analyzeInstExport(mod: *Module, scope: *Scope, export_inst: *zir.Inst.Export) InnerError!*Inst { const symbol_name = try resolveConstString(mod, scope, export_inst.positionals.symbol_name); const exported_decl = mod.lookupDeclName(scope, export_inst.positionals.decl_name) orelse - return mod.fail(scope, export_inst.base.src, "decl '{}' not found", .{export_inst.positionals.decl_name}); + return mod.fail(scope, export_inst.base.src, "decl '{s}' not found", .{export_inst.positionals.decl_name}); try mod.analyzeExport(scope, export_inst.base.src, symbol_name, exported_decl); return mod.constVoid(scope, export_inst.base.src); } fn analyzeInstCompileError(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const msg = try resolveConstString(mod, scope, inst.positionals.operand); - return mod.fail(scope, inst.base.src, "{}", .{msg}); + return mod.fail(scope, inst.base.src, "{s}", .{msg}); } fn analyzeInstArg(mod: *Module, scope: *Scope, inst: *zir.Inst.Arg) InnerError!*Inst { @@ -580,7 +580,7 @@ fn analyzeInstArg(mod: *Module, scope: *Scope, inst: *zir.Inst.Arg) InnerError!* const param_index = b.instructions.items.len; const param_count = fn_ty.fnParamLen(); if (param_index >= param_count) { - return mod.fail(scope, inst.base.src, "parameter index {} outside list of length {}", .{ + return mod.fail(scope, inst.base.src, "parameter index {d} outside list of length {d}", .{ param_index, param_count, }); @@ -790,7 +790,7 @@ fn analyzeInstCall(mod: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerError return mod.fail( scope, inst.positionals.func.src, - "expected at least {} argument(s), found {}", + "expected at least {d} argument(s), found {d}", .{ fn_params_len, call_params_len }, ); } @@ -800,7 +800,7 @@ fn analyzeInstCall(mod: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerError return mod.fail( scope, inst.positionals.func.src, - "expected {} argument(s), found {}", + "expected {d} argument(s), found {d}", .{ fn_params_len, call_params_len }, ); } @@ -918,7 +918,7 @@ fn analyzeInstErrorSet(mod: *Module, scope: *Scope, inst: *zir.Inst.ErrorSet) In for (inst.positionals.fields) |field_name| { const entry = try mod.getErrorValue(field_name); if (payload.data.fields.fetchPutAssumeCapacity(entry.key, entry.value)) |prev| { - return mod.fail(scope, inst.base.src, "duplicate error: '{}'", .{field_name}); + return mod.fail(scope, inst.base.src, "duplicate error: '{s}'", .{field_name}); } } // TODO create name in format "error:line:column" @@ -1068,7 +1068,7 @@ fn analyzeInstFieldPtr(mod: *Module, scope: *Scope, fieldptr: *zir.Inst.FieldPtr return mod.fail( scope, fieldptr.positionals.field_name.src, - "no member named '{}' in '{}'", + "no member named '{s}' in '{}'", .{ field_name, elem_ty }, ); } @@ -1089,7 +1089,7 @@ fn analyzeInstFieldPtr(mod: *Module, scope: *Scope, fieldptr: *zir.Inst.FieldPtr return mod.fail( scope, fieldptr.positionals.field_name.src, - "no member named '{}' in '{}'", + "no member named '{s}' in '{}'", .{ field_name, elem_ty }, ); } @@ -1107,7 +1107,7 @@ fn analyzeInstFieldPtr(mod: *Module, scope: *Scope, fieldptr: *zir.Inst.FieldPtr // TODO resolve inferred error sets const entry = if (val.castTag(.error_set)) |payload| (payload.data.fields.getEntry(field_name) orelse - return mod.fail(scope, fieldptr.base.src, "no error named '{}' in '{}'", .{ field_name, child_type })).* + return mod.fail(scope, fieldptr.base.src, "no error named '{s}' in '{}'", .{ field_name, child_type })).* else try mod.getErrorValue(field_name); @@ -1135,9 +1135,9 @@ fn analyzeInstFieldPtr(mod: *Module, scope: *Scope, fieldptr: *zir.Inst.FieldPtr } if (&container_scope.file_scope.base == mod.root_scope) { - return mod.fail(scope, fieldptr.base.src, "root source file has no member called '{}'", .{field_name}); + return mod.fail(scope, fieldptr.base.src, "root source file has no member called '{s}'", .{field_name}); } else { - return mod.fail(scope, fieldptr.base.src, "container '{}' has no member called '{}'", .{ child_type, field_name }); + return mod.fail(scope, fieldptr.base.src, "container '{}' has no member called '{s}'", .{ child_type, field_name }); } }, else => return mod.fail(scope, fieldptr.base.src, "type '{}' does not support field access", .{child_type}), @@ -1503,14 +1503,14 @@ fn analyzeInstImport(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerErr const file_scope = mod.analyzeImport(scope, inst.base.src, operand) catch |err| switch (err) { error.ImportOutsidePkgPath => { - return mod.fail(scope, inst.base.src, "import of file outside package path: '{}'", .{operand}); + return mod.fail(scope, inst.base.src, "import of file outside package path: '{s}'", .{operand}); }, error.FileNotFound => { - return mod.fail(scope, inst.base.src, "unable to find '{}'", .{operand}); + return mod.fail(scope, inst.base.src, "unable to find '{s}'", .{operand}); }, else => { // TODO user friendly error to string - return mod.fail(scope, inst.base.src, "unable to open '{}': {}", .{ operand, @errorName(err) }); + return mod.fail(scope, inst.base.src, "unable to open '{s}': {s}", .{ operand, @errorName(err) }); }, }; return mod.constType(scope, inst.base.src, file_scope.root_container.ty); @@ -1545,7 +1545,7 @@ fn analyzeInstBitwise(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerE if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) { if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) { - return mod.fail(scope, inst.base.src, "vector length mismatch: {} and {}", .{ + return mod.fail(scope, inst.base.src, "vector length mismatch: {d} and {d}", .{ lhs.ty.arrayLen(), rhs.ty.arrayLen(), }); @@ -1620,7 +1620,7 @@ fn analyzeInstArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) Inn if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) { if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) { - return mod.fail(scope, inst.base.src, "vector length mismatch: {} and {}", .{ + return mod.fail(scope, inst.base.src, "vector length mismatch: {d} and {d}", .{ lhs.ty.arrayLen(), rhs.ty.arrayLen(), }); @@ -1637,7 +1637,7 @@ fn analyzeInstArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) Inn const is_float = scalar_tag == .Float or scalar_tag == .ComptimeFloat; if (!is_int and !(is_float and floatOpAllowed(inst.base.tag))) { - return mod.fail(scope, inst.base.src, "invalid operands to binary expression: '{}' and '{}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) }); + return mod.fail(scope, inst.base.src, "invalid operands to binary expression: '{s}' and '{s}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) }); } if (casted_lhs.value()) |lhs_val| { @@ -1656,7 +1656,7 @@ fn analyzeInstArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) Inn const ir_tag = switch (inst.base.tag) { .add => Inst.Tag.add, .sub => Inst.Tag.sub, - else => return mod.fail(scope, inst.base.src, "TODO implement arithmetic for operand '{}''", .{@tagName(inst.base.tag)}), + else => return mod.fail(scope, inst.base.src, "TODO implement arithmetic for operand '{s}''", .{@tagName(inst.base.tag)}), }; return mod.addBinOp(b, inst.base.src, scalar_type, ir_tag, casted_lhs, casted_rhs); @@ -1689,7 +1689,7 @@ fn analyzeInstComptimeOp(mod: *Module, scope: *Scope, res_type: Type, inst: *zir mod.floatSub(scope, res_type, inst.base.src, lhs_val, rhs_val); break :blk val; }, - else => return mod.fail(scope, inst.base.src, "TODO Implement arithmetic operand '{}'", .{@tagName(inst.base.tag)}), + else => return mod.fail(scope, inst.base.src, "TODO Implement arithmetic operand '{s}'", .{@tagName(inst.base.tag)}), }; return mod.constInst(scope, inst.base.src, .{ @@ -1781,7 +1781,7 @@ fn analyzeInstCmp( return mod.fail(scope, inst.base.src, "TODO implement equality comparison between a union's tag value and an enum literal", .{}); } else if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) { if (!is_equality_cmp) { - return mod.fail(scope, inst.base.src, "{} operator not allowed for errors", .{@tagName(op)}); + return mod.fail(scope, inst.base.src, "{s} operator not allowed for errors", .{@tagName(op)}); } return mod.fail(scope, inst.base.src, "TODO implement equality comparison between errors", .{}); } else if (lhs.ty.isNumeric() and rhs.ty.isNumeric()) { @@ -1791,7 +1791,7 @@ fn analyzeInstCmp( return mod.cmpNumeric(scope, inst.base.src, lhs, rhs, op); } else if (lhs_ty_tag == .Type and rhs_ty_tag == .Type) { if (!is_equality_cmp) { - return mod.fail(scope, inst.base.src, "{} operator not allowed for types", .{@tagName(op)}); + return mod.fail(scope, inst.base.src, "{s} operator not allowed for types", .{@tagName(op)}); } return mod.constBool(scope, inst.base.src, lhs.value().?.eql(rhs.value().?) == (op == .eq)); } @@ -1962,7 +1962,7 @@ fn analyzeDeclVal(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerErr const decl_name = inst.positionals.name; const zir_module = scope.namespace().cast(Scope.ZIRModule).?; const src_decl = zir_module.contents.module.findDecl(decl_name) orelse - return mod.fail(scope, inst.base.src, "use of undeclared identifier '{}'", .{decl_name}); + return mod.fail(scope, inst.base.src, "use of undeclared identifier '{s}'", .{decl_name}); const decl = try resolveCompleteZirDecl(mod, scope, src_decl.decl); diff --git a/test/compare_output.zig b/test/compare_output.zig index 46c475e046..9dc80f202d 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -453,7 +453,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ _ = args_it.skip(); \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) { \\ const arg = try arg_or_err; - \\ try stdout.print("{}: {}\n", .{index, arg}); + \\ try stdout.print("{}: {s}\n", .{index, arg}); \\ } \\} , @@ -492,7 +492,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ _ = args_it.skip(); \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) { \\ const arg = try arg_or_err; - \\ try stdout.print("{}: {}\n", .{index, arg}); + \\ try stdout.print("{}: {s}\n", .{index, arg}); \\ } \\} , diff --git a/test/src/compare_output.zig b/test/src/compare_output.zig index f78d6744e1..1cde470887 100644 --- a/test/src/compare_output.zig +++ b/test/src/compare_output.zig @@ -97,7 +97,7 @@ pub const CompareOutputContext = struct { switch (case.special) { Special.Asm => { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {}", .{ + const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {s}", .{ case.name, }) catch unreachable; if (self.test_filter) |filter| { @@ -116,7 +116,7 @@ pub const CompareOutputContext = struct { }, Special.None => { for (self.modes) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{ + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s} ({s})", .{ "compare-output", case.name, @tagName(mode), @@ -141,7 +141,7 @@ pub const CompareOutputContext = struct { } }, Special.RuntimeSafety => { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {}", .{case.name}) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {s}", .{case.name}) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } diff --git a/test/src/run_translated_c.zig b/test/src/run_translated_c.zig index 06990241cc..1de329112c 100644 --- a/test/src/run_translated_c.zig +++ b/test/src/run_translated_c.zig @@ -77,7 +77,7 @@ pub const RunTranslatedCContext = struct { pub fn addCase(self: *RunTranslatedCContext, case: *const TestCase) void { const b = self.b; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "run-translated-c {}", .{case.name}) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "run-translated-c {s}", .{case.name}) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -92,13 +92,13 @@ pub const RunTranslatedCContext = struct { .basename = case.sources.items[0].filename, }, }); - translate_c.step.name = b.fmt("{} translate-c", .{annotated_case_name}); + translate_c.step.name = b.fmt("{s} translate-c", .{annotated_case_name}); const exe = translate_c.addExecutable(); exe.setTarget(self.target); - exe.step.name = b.fmt("{} build-exe", .{annotated_case_name}); + exe.step.name = b.fmt("{s} build-exe", .{annotated_case_name}); exe.linkLibC(); const run = exe.run(); - run.step.name = b.fmt("{} run", .{annotated_case_name}); + run.step.name = b.fmt("{s} run", .{annotated_case_name}); if (!case.allow_warnings) { run.expectStdErrEqual(""); } diff --git a/test/src/translate_c.zig b/test/src/translate_c.zig index 405c5954ba..c43f326926 100644 --- a/test/src/translate_c.zig +++ b/test/src/translate_c.zig @@ -99,7 +99,7 @@ pub const TranslateCContext = struct { const b = self.b; const translate_c_cmd = "translate-c"; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {}", .{ translate_c_cmd, case.name }) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s}", .{ translate_c_cmd, case.name }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } diff --git a/test/stage1/behavior.zig b/test/stage1/behavior.zig index db6e596291..f82631cd9e 100644 --- a/test/stage1/behavior.zig +++ b/test/stage1/behavior.zig @@ -141,5 +141,5 @@ comptime { _ = @import("behavior/while.zig"); _ = @import("behavior/widening.zig"); _ = @import("behavior/src.zig"); - _ = @import("behavior/translate_c_macros.zig"); + // _ = @import("behavior/translate_c_macros.zig"); } diff --git a/test/stage1/behavior/async_fn.zig b/test/stage1/behavior/async_fn.zig index eb9c3f5d07..16c7b14944 100644 --- a/test/stage1/behavior/async_fn.zig +++ b/test/stage1/behavior/async_fn.zig @@ -2,6 +2,7 @@ const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; +const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; var global_x: i32 = 1; @@ -541,7 +542,7 @@ test "pass string literal to async function" { fn hello(msg: []const u8) void { frame = @frame(); suspend; - expectEqual(@as([]const u8, "hello"), msg); + expectEqualStrings("hello", msg); ok = true; } }; diff --git a/test/tests.zig b/test/tests.zig index 250c1cc4ea..5ee381e5c2 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -482,7 +482,7 @@ pub fn addPkgTests( is_wasmtime_enabled: bool, glibc_dir: ?[]const u8, ) *build.Step { - const step = b.step(b.fmt("test-{}", .{name}), desc); + const step = b.step(b.fmt("test-{s}", .{name}), desc); for (test_targets) |test_target| { if (skip_non_native and !test_target.target.isNative()) @@ -523,7 +523,7 @@ pub fn addPkgTests( const these_tests = b.addTest(root_src); const single_threaded_txt = if (test_target.single_threaded) "single" else "multi"; - these_tests.setNamePrefix(b.fmt("{}-{}-{}-{}-{} ", .{ + these_tests.setNamePrefix(b.fmt("{s}-{s}-{s}-{s}-{s} ", .{ name, triple_prefix, @tagName(test_target.mode), @@ -570,7 +570,7 @@ pub const StackTracesContext = struct { const expect_for_mode = expect[@enumToInt(mode)]; if (expect_for_mode.len == 0) continue; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{ + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s} ({s})", .{ "stack-trace", name, @tagName(mode), @@ -637,7 +637,7 @@ pub const StackTracesContext = struct { defer args.deinit(); args.append(full_exe_path) catch unreachable; - warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); + warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name }); const child = std.ChildProcess.init(args.items, b.allocator) catch unreachable; defer child.deinit(); @@ -650,7 +650,7 @@ pub const StackTracesContext = struct { if (b.verbose) { printInvocation(args.items); } - child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); + child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ full_exe_path, @errorName(err) }); const stdout = child.stdout.?.inStream().readAllAlloc(b.allocator, max_stdout_size) catch unreachable; defer b.allocator.free(stdout); @@ -659,14 +659,14 @@ pub const StackTracesContext = struct { var stderr = stderrFull; const term = child.wait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); + debug.panic("Unable to spawn {s}: {s}\n", .{ full_exe_path, @errorName(err) }); }; switch (term) { .Exited => |code| { const expect_code: u32 = 1; if (code != expect_code) { - warn("Process {} exited with error code {} but expected code {}\n", .{ + warn("Process {s} exited with error code {d} but expected code {d}\n", .{ full_exe_path, code, expect_code, @@ -676,17 +676,17 @@ pub const StackTracesContext = struct { } }, .Signal => |signum| { - warn("Process {} terminated on signal {}\n", .{ full_exe_path, signum }); + warn("Process {s} terminated on signal {d}\n", .{ full_exe_path, signum }); printInvocation(args.items); return error.TestFailed; }, .Stopped => |signum| { - warn("Process {} stopped on signal {}\n", .{ full_exe_path, signum }); + warn("Process {s} stopped on signal {d}\n", .{ full_exe_path, signum }); printInvocation(args.items); return error.TestFailed; }, .Unknown => |code| { - warn("Process {} terminated unexpectedly with error code {}\n", .{ full_exe_path, code }); + warn("Process {s} terminated unexpectedly with error code {d}\n", .{ full_exe_path, code }); printInvocation(args.items); return error.TestFailed; }, @@ -732,9 +732,9 @@ pub const StackTracesContext = struct { warn( \\ \\========= Expected this output: ========= - \\{} + \\{s} \\================================================ - \\{} + \\{s} \\ , .{ self.expect_output, got }); return error.TestFailed; @@ -856,7 +856,7 @@ pub const CompileErrorContext = struct { zig_args.append("-O") catch unreachable; zig_args.append(@tagName(self.build_mode)) catch unreachable; - warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); + warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name }); if (b.verbose) { printInvocation(zig_args.items); @@ -870,7 +870,7 @@ pub const CompileErrorContext = struct { child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; - child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) }); + child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) }); var stdout_buf = ArrayList(u8).init(b.allocator); var stderr_buf = ArrayList(u8).init(b.allocator); @@ -879,7 +879,7 @@ pub const CompileErrorContext = struct { child.stderr.?.inStream().readAllArrayList(&stderr_buf, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { - debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) }); + debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) }); }; switch (term) { .Exited => |code| { @@ -889,7 +889,7 @@ pub const CompileErrorContext = struct { } }, else => { - warn("Process {} terminated unexpectedly\n", .{b.zig_exe}); + warn("Process {s} terminated unexpectedly\n", .{b.zig_exe}); printInvocation(zig_args.items); return error.TestFailed; }, @@ -903,7 +903,7 @@ pub const CompileErrorContext = struct { \\ \\Expected empty stdout, instead found: \\================================================ - \\{} + \\{s} \\================================================ \\ , .{stdout}); @@ -926,7 +926,7 @@ pub const CompileErrorContext = struct { if (!ok) { warn("\n======== Expected these compile errors: ========\n", .{}); for (self.case.expected_errors.items) |expected| { - warn("{}\n", .{expected}); + warn("{s}\n", .{expected}); } } } else { @@ -935,7 +935,7 @@ pub const CompileErrorContext = struct { warn( \\ \\=========== Expected compile error: ============ - \\{} + \\{s} \\ , .{expected}); ok = false; @@ -947,7 +947,7 @@ pub const CompileErrorContext = struct { if (!ok) { warn( \\================= Full output: ================= - \\{} + \\{s} \\ , .{stderr}); return error.TestFailed; @@ -1023,7 +1023,7 @@ pub const CompileErrorContext = struct { pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void { const b = self.b; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {}", .{ + const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {s}", .{ case.name, }) catch unreachable; if (self.test_filter) |filter| { @@ -1058,7 +1058,7 @@ pub const StandaloneContext = struct { pub fn addBuildFile(self: *StandaloneContext, build_file: []const u8) void { const b = self.b; - const annotated_case_name = b.fmt("build {} (Debug)", .{build_file}); + const annotated_case_name = b.fmt("build {s} (Debug)", .{build_file}); if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -1079,7 +1079,7 @@ pub const StandaloneContext = struct { const run_cmd = b.addSystemCommand(zig_args.items); - const log_step = b.addLog("PASS {}\n", .{annotated_case_name}); + const log_step = b.addLog("PASS {s}\n", .{annotated_case_name}); log_step.step.dependOn(&run_cmd.step); self.step.dependOn(&log_step.step); @@ -1089,7 +1089,7 @@ pub const StandaloneContext = struct { const b = self.b; for (self.modes) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {} ({})", .{ + const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {s} ({s})", .{ root_src, @tagName(mode), }) catch unreachable; @@ -1103,7 +1103,7 @@ pub const StandaloneContext = struct { exe.linkSystemLibrary("c"); } - const log_step = b.addLog("PASS {}\n", .{annotated_case_name}); + const log_step = b.addLog("PASS {s}\n", .{annotated_case_name}); log_step.step.dependOn(&exe.step); self.step.dependOn(&log_step.step); @@ -1172,7 +1172,7 @@ pub const GenHContext = struct { const self = @fieldParentPtr(GenHCmpOutputStep, "step", step); const b = self.context.b; - warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); + warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name }); const full_h_path = self.obj.getOutputHPath(); const actual_h = try io.readFileAlloc(b.allocator, full_h_path); @@ -1182,9 +1182,9 @@ pub const GenHContext = struct { warn( \\ \\========= Expected this output: ================ - \\{} + \\{s} \\========= But found: =========================== - \\{} + \\{s} \\ , .{ expected_line, actual_h }); return error.TestFailed; @@ -1196,7 +1196,7 @@ pub const GenHContext = struct { fn printInvocation(args: []const []const u8) void { for (args) |arg| { - warn("{} ", .{arg}); + warn("{s} ", .{arg}); } warn("\n", .{}); } @@ -1232,7 +1232,7 @@ pub const GenHContext = struct { const b = self.b; const mode = builtin.Mode.Debug; - const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {} ({})", .{ case.name, @tagName(mode) }) catch unreachable; + const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {s} ({s})", .{ case.name, @tagName(mode) }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } @@ -1253,7 +1253,7 @@ pub const GenHContext = struct { fn printInvocation(args: []const []const u8) void { for (args) |arg| { - warn("{} ", .{arg}); + warn("{s} ", .{arg}); } warn("\n", .{}); }