authorgravatar for johnnymarler@gmail.comJonathan Marler <johnnymarler@gmail.com> 2021-01-03 13:49:51-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-07 23:49:22-08:00
log31802c6c68a98bdbe34766d3cfdaf65b782851da
tree88ea8704da9344e62347bee9b064d4c42cfdec83
parenta9b505fa7774e2e8451bedfa7bea27d7227572e7

remove z/Z format specifiers

Zig's format system is flexible enough to add custom formatters. This PR removes the new z/Z format specifiers that were added for printing Zig identifiers and replaces them with custom formatters.

10 files changed, 153 insertions(+), 110 deletions(-)

lib/std/build.zig+16-16
...@@ -1852,25 +1852,25 @@ pub const LibExeObjStep = struct {...@@ -1852,25 +1852,25 @@ pub const LibExeObjStep = struct {
1852 const out = self.build_options_contents.writer();1852 const out = self.build_options_contents.writer();
1853 switch (T) {1853 switch (T) {
1854 []const []const u8 => {1854 []const []const u8 => {
1855 out.print("pub const {z}: []const []const u8 = &[_][]const u8{{\n", .{name}) catch unreachable;1855 out.print("pub const {}: []const []const u8 = &[_][]const u8{{\n", .{std.zig.fmtId(name)}) catch unreachable;
1856 for (value) |slice| {1856 for (value) |slice| {
1857 out.print(" \"{Z}\",\n", .{slice}) catch unreachable;1857 out.print(" \"{}\",\n", .{std.zig.fmtEscapes(slice)}) catch unreachable;
1858 }1858 }
1859 out.writeAll("};\n") catch unreachable;1859 out.writeAll("};\n") catch unreachable;
1860 return;1860 return;
1861 },1861 },
1862 [:0]const u8 => {1862 [:0]const u8 => {
1863 out.print("pub const {z}: [:0]const u8 = \"{Z}\";\n", .{ name, value }) catch unreachable;1863 out.print("pub const {}: [:0]const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
1864 return;1864 return;
1865 },1865 },
1866 []const u8 => {1866 []const u8 => {
1867 out.print("pub const {z}: []const u8 = \"{Z}\";\n", .{ name, value }) catch unreachable;1867 out.print("pub const {}: []const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
1868 return;1868 return;
1869 },1869 },
1870 ?[]const u8 => {1870 ?[]const u8 => {
1871 out.print("pub const {z}: ?[]const u8 = ", .{name}) catch unreachable;1871 out.print("pub const {}: ?[]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
1872 if (value) |payload| {1872 if (value) |payload| {
1873 out.print("\"{Z}\";\n", .{payload}) catch unreachable;1873 out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
1874 } else {1874 } else {
1875 out.writeAll("null;\n") catch unreachable;1875 out.writeAll("null;\n") catch unreachable;
1876 }1876 }
...@@ -1878,14 +1878,14 @@ pub const LibExeObjStep = struct {...@@ -1878,14 +1878,14 @@ pub const LibExeObjStep = struct {
1878 },1878 },
1879 std.builtin.Version => {1879 std.builtin.Version => {
1880 out.print(1880 out.print(
1881 \\pub const {z}: @import("builtin").Version = .{{1881 \\pub const {}: @import("builtin").Version = .{{
1882 \\ .major = {d},1882 \\ .major = {d},
1883 \\ .minor = {d},1883 \\ .minor = {d},
1884 \\ .patch = {d},1884 \\ .patch = {d},
1885 \\}};1885 \\}};
1886 \\1886 \\
1887 , .{1887 , .{
1888 name,1888 std.zig.fmtId(name),
18891889
1890 value.major,1890 value.major,
1891 value.minor,1891 value.minor,
...@@ -1894,23 +1894,23 @@ pub const LibExeObjStep = struct {...@@ -1894,23 +1894,23 @@ pub const LibExeObjStep = struct {
1894 },1894 },
1895 std.SemanticVersion => {1895 std.SemanticVersion => {
1896 out.print(1896 out.print(
1897 \\pub const {z}: @import("std").SemanticVersion = .{{1897 \\pub const {}: @import("std").SemanticVersion = .{{
1898 \\ .major = {d},1898 \\ .major = {d},
1899 \\ .minor = {d},1899 \\ .minor = {d},
1900 \\ .patch = {d},1900 \\ .patch = {d},
1901 \\1901 \\
1902 , .{1902 , .{
1903 name,1903 std.zig.fmtId(name),
19041904
1905 value.major,1905 value.major,
1906 value.minor,1906 value.minor,
1907 value.patch,1907 value.patch,
1908 }) catch unreachable;1908 }) catch unreachable;
1909 if (value.pre) |some| {1909 if (value.pre) |some| {
1910 out.print(" .pre = \"{Z}\",\n", .{some}) catch unreachable;1910 out.print(" .pre = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
1911 }1911 }
1912 if (value.build) |some| {1912 if (value.build) |some| {
1913 out.print(" .build = \"{Z}\",\n", .{some}) catch unreachable;1913 out.print(" .build = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
1914 }1914 }
1915 out.writeAll("};\n") catch unreachable;1915 out.writeAll("};\n") catch unreachable;
1916 return;1916 return;
...@@ -1919,15 +1919,15 @@ pub const LibExeObjStep = struct {...@@ -1919,15 +1919,15 @@ pub const LibExeObjStep = struct {
1919 }1919 }
1920 switch (@typeInfo(T)) {1920 switch (@typeInfo(T)) {
1921 .Enum => |enum_info| {1921 .Enum => |enum_info| {
1922 out.print("pub const {z} = enum {{\n", .{@typeName(T)}) catch unreachable;1922 out.print("pub const {} = enum {{\n", .{std.zig.fmtId(@typeName(T))}) catch unreachable;
1923 inline for (enum_info.fields) |field| {1923 inline for (enum_info.fields) |field| {
1924 out.print(" {z},\n", .{field.name}) catch unreachable;1924 out.print(" {},\n", .{std.zig.fmtId(field.name)}) catch unreachable;
1925 }1925 }
1926 out.writeAll("};\n") catch unreachable;1926 out.writeAll("};\n") catch unreachable;
1927 },1927 },
1928 else => {},1928 else => {},
1929 }1929 }
1930 out.print("pub const {z}: {s} = {};\n", .{ name, @typeName(T), value }) catch unreachable;1930 out.print("pub const {}: {s} = {};\n", .{ std.zig.fmtId(name), @typeName(T), value }) catch unreachable;
1931 }1931 }
19321932
1933 /// The value is the path in the cache dir.1933 /// The value is the path in the cache dir.
...@@ -2157,7 +2157,7 @@ pub const LibExeObjStep = struct {...@@ -2157,7 +2157,7 @@ pub const LibExeObjStep = struct {
2157 // Render build artifact options at the last minute, now that the path is known.2157 // Render build artifact options at the last minute, now that the path is known.
2158 for (self.build_options_artifact_args.items) |item| {2158 for (self.build_options_artifact_args.items) |item| {
2159 const out = self.build_options_contents.writer();2159 const out = self.build_options_contents.writer();
2160 out.print("pub const {s}: []const u8 = \"{Z}\";\n", .{ item.name, item.artifact.getOutputPath() }) catch unreachable;2160 out.print("pub const {s}: []const u8 = \"{}\";\n", .{ item.name, std.zig.fmtEscapes(item.artifact.getOutputPath()) }) catch unreachable;
2161 }2161 }
21622162
2163 const build_options_file = try fs.path.join(2163 const build_options_file = try fs.path.join(
lib/std/fmt.zig+29-60
...@@ -715,9 +715,9 @@ pub fn formatText(...@@ -715,9 +715,9 @@ pub fn formatText(
715 }715 }
716 return;716 return;
717 } else if (comptime std.mem.eql(u8, fmt, "z")) {717 } else if (comptime std.mem.eql(u8, fmt, "z")) {
718 return formatZigIdentifier(bytes, options, writer);718 @compileError("specifier 'z' has been deprecated, wrap your argument in std.zig.fmtId instead");
719 } else if (comptime std.mem.eql(u8, fmt, "Z")) {719 } else if (comptime std.mem.eql(u8, fmt, "Z")) {
720 return formatZigEscapes(bytes, options, writer);720 @compileError("specifier 'Z' has been deprecated, wrap your argument in std.zig.fmtEscapes instead");
721 } else {721 } else {
722 @compileError("Unknown format string: '" ++ fmt ++ "'");722 @compileError("Unknown format string: '" ++ fmt ++ "'");
723 }723 }
...@@ -782,52 +782,6 @@ pub fn formatBuf(...@@ -782,52 +782,6 @@ pub fn formatBuf(
782 }782 }
783}783}
784784
785/// Print the string as a Zig identifier escaping it with @"" syntax if needed.
786pub fn formatZigIdentifier(
787 bytes: []const u8,
788 options: FormatOptions,
789 writer: anytype,
790) !void {
791 if (isValidZigIdentifier(bytes)) {
792 return writer.writeAll(bytes);
793 }
794 try writer.writeAll("@\"");
795 try formatZigEscapes(bytes, options, writer);
796 try writer.writeByte('"');
797}
798
799fn isValidZigIdentifier(bytes: []const u8) bool {
800 for (bytes) |c, i| {
801 switch (c) {
802 '_', 'a'...'z', 'A'...'Z' => {},
803 '0'...'9' => if (i == 0) return false,
804 else => return false,
805 }
806 }
807 return std.zig.Token.getKeyword(bytes) == null;
808}
809
810pub fn formatZigEscapes(
811 bytes: []const u8,
812 options: FormatOptions,
813 writer: anytype,
814) !void {
815 for (bytes) |byte| switch (byte) {
816 '\n' => try writer.writeAll("\\n"),
817 '\r' => try writer.writeAll("\\r"),
818 '\t' => try writer.writeAll("\\t"),
819 '\\' => try writer.writeAll("\\\\"),
820 '"' => try writer.writeAll("\\\""),
821 '\'' => try writer.writeAll("\\'"),
822 ' ', '!', '#'...'&', '('...'[', ']'...'~' => try writer.writeByte(byte),
823 // Use hex escapes for rest any unprintable characters.
824 else => {
825 try writer.writeAll("\\x");
826 try formatInt(byte, 16, false, .{ .width = 2, .fill = '0' }, writer);
827 },
828 };
829}
830
831/// Print a float in scientific notation to the specified precision. Null uses full precision.785/// Print a float in scientific notation to the specified precision. Null uses full precision.
832/// It should be the case that every full precision, printed value can be re-parsed back to the786/// It should be the case that every full precision, printed value can be re-parsed back to the
833/// same type unambiguously.787/// same type unambiguously.
...@@ -1173,6 +1127,32 @@ pub const ParseIntError = error{...@@ -1173,6 +1127,32 @@ pub const ParseIntError = error{
1173 InvalidCharacter,1127 InvalidCharacter,
1174};1128};
11751129
1130/// Creates a Formatter type from a format function. Wrapping data in Formatter(func) causes
1131/// the data to be formatted using the given function `func`. `func` must be of the following
1132/// form:
1133///
1134/// fn formatExample(
1135/// data: T,
1136/// comptime fmt: []const u8,
1137/// options: std.fmt.FormatOptions,
1138/// writer: anytype,
1139/// ) !void;
1140///
1141pub fn Formatter(comptime format_fn: anytype) type {
1142 const Data = @typeInfo(@TypeOf(format_fn)).Fn.args[0].arg_type.?;
1143 return struct {
1144 data: Data,
1145 pub fn format(
1146 self: @This(),
1147 comptime fmt: []const u8,
1148 options: std.fmt.FormatOptions,
1149 writer: anytype,
1150 ) @TypeOf(writer).Error!void {
1151 try format_fn(self.data, fmt, options, writer);
1152 }
1153 };
1154}
1155
1176/// Parses the string `buf` as signed or unsigned representation in the1156/// Parses the string `buf` as signed or unsigned representation in the
1177/// specified radix of an integral value of type `T`.1157/// specified radix of an integral value of type `T`.
1178///1158///
...@@ -1608,17 +1588,6 @@ test "escape non-printable" {...@@ -1608,17 +1588,6 @@ test "escape non-printable" {
1608 try testFmt("ab\\xFFc", "{E}", .{"ab\xffc"});1588 try testFmt("ab\\xFFc", "{E}", .{"ab\xffc"});
1609}1589}
16101590
1611test "escape invalid identifiers" {
1612 try testFmt("@\"while\"", "{z}", .{"while"});
1613 try testFmt("hello", "{z}", .{"hello"});
1614 try testFmt("@\"11\\\"23\"", "{z}", .{"11\"23"});
1615 try testFmt("@\"11\\x0f23\"", "{z}", .{"11\x0F23"});
1616 try testFmt("\\x0f", "{Z}", .{0x0f});
1617 try testFmt(
1618 \\" \\ hi \x07 \x11 \" derp \'"
1619 , "\"{Z}\"", .{" \\ hi \x07 \x11 \" derp '"});
1620}
1621
1622test "pointer" {1591test "pointer" {
1623 {1592 {
1624 const value = @intToPtr(*align(1) i32, 0xdeadbeef);1593 const value = @intToPtr(*align(1) i32, 0xdeadbeef);
...@@ -1898,7 +1867,7 @@ test "bytes.hex" {...@@ -1898,7 +1867,7 @@ test "bytes.hex" {
1898 try testFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{bytes_with_zeros});1867 try testFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{bytes_with_zeros});
1899}1868}
19001869
1901fn testFmt(expected: []const u8, comptime template: []const u8, args: anytype) !void {1870pub fn testFmt(expected: []const u8, comptime template: []const u8, args: anytype) !void {
1902 var buf: [100]u8 = undefined;1871 var buf: [100]u8 = undefined;
1903 const result = try bufPrint(buf[0..], template, args);1872 const result = try bufPrint(buf[0..], template, args);
1904 if (mem.eql(u8, result, expected)) return;1873 if (mem.eql(u8, result, expected)) return;
lib/std/fs/wasi.zig+1-1
...@@ -38,7 +38,7 @@ pub const PreopenType = union(PreopenTypeTag) {...@@ -38,7 +38,7 @@ pub const PreopenType = union(PreopenTypeTag) {
38 pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void {38 pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void {
39 try out_stream.print("PreopenType{{ ", .{});39 try out_stream.print("PreopenType{{ ", .{});
40 switch (self) {40 switch (self) {
41 PreopenType.Dir => |path| try out_stream.print(".Dir = '{z}'", .{path}),41 PreopenType.Dir => |path| try out_stream.print(".Dir = '{}'", .{std.zig.fmtId(path)}),
42 }42 }
43 return out_stream.print(" }}", .{});43 return out_stream.print(" }}", .{});
44 }44 }
lib/std/zig.zig+2
...@@ -8,6 +8,8 @@ const tokenizer = @import("zig/tokenizer.zig");...@@ -8,6 +8,8 @@ const tokenizer = @import("zig/tokenizer.zig");
88
9pub const Token = tokenizer.Token;9pub const Token = tokenizer.Token;
10pub const Tokenizer = tokenizer.Tokenizer;10pub const Tokenizer = tokenizer.Tokenizer;
11pub const fmtId = @import("zig/fmt.zig").fmtId;
12pub const fmtEscapes = @import("zig/fmt.zig").fmtEscapes;
11pub const parse = @import("zig/parse.zig").parse;13pub const parse = @import("zig/parse.zig").parse;
12pub const parseStringLiteral = @import("zig/string_literal.zig").parse;14pub const parseStringLiteral = @import("zig/string_literal.zig").parse;
13pub const render = @import("zig/render.zig").render;15pub const render = @import("zig/render.zig").render;
lib/std/zig/fmt.zig created+71
...@@ -0,0 +1,71 @@
1const std = @import("std");
2const mem = std.mem;
3
4/// Print the string as a Zig identifier escaping it with @"" syntax if needed.
5pub fn formatId(
6 bytes: []const u8,
7 comptime fmt: []const u8,
8 options: std.fmt.FormatOptions,
9 writer: anytype,
10) !void {
11 if (isValidId(bytes)) {
12 return writer.writeAll(bytes);
13 }
14 try writer.writeAll("@\"");
15 try formatEscapes(bytes, fmt, options, writer);
16 try writer.writeByte('"');
17}
18
19/// Return a Formatter for a Zig identifier
20pub fn fmtId(bytes: []const u8) std.fmt.Formatter(formatId) {
21 return .{ .data = bytes };
22}
23
24pub fn isValidId(bytes: []const u8) bool {
25 for (bytes) |c, i| {
26 switch (c) {
27 '_', 'a'...'z', 'A'...'Z' => {},
28 '0'...'9' => if (i == 0) return false,
29 else => return false,
30 }
31 }
32 return std.zig.Token.getKeyword(bytes) == null;
33}
34
35pub fn formatEscapes(
36 bytes: []const u8,
37 comptime fmt: []const u8,
38 options: std.fmt.FormatOptions,
39 writer: anytype,
40) !void {
41 for (bytes) |byte| switch (byte) {
42 '\n' => try writer.writeAll("\\n"),
43 '\r' => try writer.writeAll("\\r"),
44 '\t' => try writer.writeAll("\\t"),
45 '\\' => try writer.writeAll("\\\\"),
46 '"' => try writer.writeAll("\\\""),
47 '\'' => try writer.writeAll("\\'"),
48 ' ', '!', '#'...'&', '('...'[', ']'...'~' => try writer.writeByte(byte),
49 // Use hex escapes for rest any unprintable characters.
50 else => {
51 try writer.writeAll("\\x");
52 try std.fmt.formatInt(byte, 16, false, .{ .width = 2, .fill = '0' }, writer);
53 },
54 };
55}
56
57/// Return a Formatter for Zig Escapes
58pub fn fmtEscapes(bytes: []const u8) std.fmt.Formatter(formatEscapes) {
59 return .{ .data = bytes };
60}
61
62test "escape invalid identifiers" {
63 try std.fmt.testFmt("@\"while\"", "{}", .{fmtId("while")});
64 try std.fmt.testFmt("hello", "{}", .{fmtId("hello")});
65 try std.fmt.testFmt("@\"11\\\"23\"", "{}", .{fmtId("11\"23")});
66 try std.fmt.testFmt("@\"11\\x0f23\"", "{}", .{fmtId("11\x0F23")});
67 try std.fmt.testFmt("\\x0f", "{}", .{fmtEscapes("\x0f")});
68 try std.fmt.testFmt(
69 \\" \\ hi \x07 \x11 \" derp \'"
70 , "\"{}\"", .{fmtEscapes(" \\ hi \x07 \x11 \" derp '")});
71}
src/Compilation.zig+22-22
...@@ -2703,27 +2703,27 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8...@@ -2703,27 +2703,27 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
2703 \\pub const arch = Target.current.cpu.arch;2703 \\pub const arch = Target.current.cpu.arch;
2704 \\/// Deprecated2704 \\/// Deprecated
2705 \\pub const endian = Target.current.cpu.arch.endian();2705 \\pub const endian = Target.current.cpu.arch.endian();
2706 \\pub const output_mode = OutputMode.{z};2706 \\pub const output_mode = OutputMode.{};
2707 \\pub const link_mode = LinkMode.{z};2707 \\pub const link_mode = LinkMode.{};
2708 \\pub const is_test = {};2708 \\pub const is_test = {};
2709 \\pub const single_threaded = {};2709 \\pub const single_threaded = {};
2710 \\pub const abi = Abi.{z};2710 \\pub const abi = Abi.{};
2711 \\pub const cpu: Cpu = Cpu{{2711 \\pub const cpu: Cpu = Cpu{{
2712 \\ .arch = .{z},2712 \\ .arch = .{},
2713 \\ .model = &Target.{z}.cpu.{z},2713 \\ .model = &Target.{}.cpu.{},
2714 \\ .features = Target.{z}.featureSet(&[_]Target.{z}.Feature{{2714 \\ .features = Target.{}.featureSet(&[_]Target.{}.Feature{{
2715 \\2715 \\
2716 , .{2716 , .{
2717 @tagName(comp.bin_file.options.output_mode),2717 std.zig.fmtId(@tagName(comp.bin_file.options.output_mode)),
2718 @tagName(comp.bin_file.options.link_mode),2718 std.zig.fmtId(@tagName(comp.bin_file.options.link_mode)),
2719 comp.bin_file.options.is_test,2719 comp.bin_file.options.is_test,
2720 comp.bin_file.options.single_threaded,2720 comp.bin_file.options.single_threaded,
2721 @tagName(target.abi),2721 std.zig.fmtId(@tagName(target.abi)),
2722 @tagName(target.cpu.arch),2722 std.zig.fmtId(@tagName(target.cpu.arch)),
2723 generic_arch_name,2723 std.zig.fmtId(generic_arch_name),
2724 target.cpu.model.name,2724 std.zig.fmtId(target.cpu.model.name),
2725 generic_arch_name,2725 std.zig.fmtId(generic_arch_name),
2726 generic_arch_name,2726 std.zig.fmtId(generic_arch_name),
2727 });2727 });
27282728
2729 for (target.cpu.arch.allFeaturesList()) |feature, index_usize| {2729 for (target.cpu.arch.allFeaturesList()) |feature, index_usize| {
...@@ -2742,10 +2742,10 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8...@@ -2742,10 +2742,10 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
2742 \\ }}),2742 \\ }}),
2743 \\}};2743 \\}};
2744 \\pub const os = Os{{2744 \\pub const os = Os{{
2745 \\ .tag = .{z},2745 \\ .tag = .{},
2746 \\ .version_range = .{{2746 \\ .version_range = .{{
2747 ,2747 ,
2748 .{@tagName(target.os.tag)},2748 .{std.zig.fmtId(@tagName(target.os.tag))},
2749 );2749 );
27502750
2751 switch (target.os.getVersionRange()) {2751 switch (target.os.getVersionRange()) {
...@@ -2828,8 +2828,8 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8...@@ -2828,8 +2828,8 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
2828 (comp.bin_file.options.skip_linker_dependencies and comp.bin_file.options.parent_compilation_link_libc);2828 (comp.bin_file.options.skip_linker_dependencies and comp.bin_file.options.parent_compilation_link_libc);
28292829
2830 try buffer.writer().print(2830 try buffer.writer().print(
2831 \\pub const object_format = ObjectFormat.{z};2831 \\pub const object_format = ObjectFormat.{};
2832 \\pub const mode = Mode.{z};2832 \\pub const mode = Mode.{};
2833 \\pub const link_libc = {};2833 \\pub const link_libc = {};
2834 \\pub const link_libcpp = {};2834 \\pub const link_libcpp = {};
2835 \\pub const have_error_return_tracing = {};2835 \\pub const have_error_return_tracing = {};
...@@ -2837,11 +2837,11 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8...@@ -2837,11 +2837,11 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
2837 \\pub const position_independent_code = {};2837 \\pub const position_independent_code = {};
2838 \\pub const position_independent_executable = {};2838 \\pub const position_independent_executable = {};
2839 \\pub const strip_debug_info = {};2839 \\pub const strip_debug_info = {};
2840 \\pub const code_model = CodeModel.{z};2840 \\pub const code_model = CodeModel.{};
2841 \\2841 \\
2842 , .{2842 , .{
2843 @tagName(comp.bin_file.options.object_format),2843 std.zig.fmtId(@tagName(comp.bin_file.options.object_format)),
2844 @tagName(comp.bin_file.options.optimize_mode),2844 std.zig.fmtId(@tagName(comp.bin_file.options.optimize_mode)),
2845 link_libc,2845 link_libc,
2846 comp.bin_file.options.link_libcpp,2846 comp.bin_file.options.link_libcpp,
2847 comp.bin_file.options.error_return_tracing,2847 comp.bin_file.options.error_return_tracing,
...@@ -2849,7 +2849,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8...@@ -2849,7 +2849,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
2849 comp.bin_file.options.pic,2849 comp.bin_file.options.pic,
2850 comp.bin_file.options.pie,2850 comp.bin_file.options.pie,
2851 comp.bin_file.options.strip,2851 comp.bin_file.options.strip,
2852 @tagName(comp.bin_file.options.machine_code_model),2852 std.zig.fmtId(@tagName(comp.bin_file.options.machine_code_model)),
2853 });2853 });
28542854
2855 if (comp.bin_file.options.is_test) {2855 if (comp.bin_file.options.is_test) {
src/codegen/c.zig+2-2
...@@ -169,8 +169,8 @@ pub const DeclGen = struct {...@@ -169,8 +169,8 @@ pub const DeclGen = struct {
169 .undef, .empty_struct_value, .empty_array => try writer.writeAll("{}"),169 .undef, .empty_struct_value, .empty_array => try writer.writeAll("{}"),
170 .bytes => {170 .bytes => {
171 const bytes = val.castTag(.bytes).?.data;171 const bytes = val.castTag(.bytes).?.data;
172 // TODO: make our own C string escape instead of using {Z}172 // TODO: make our own C string escape instead of using std.zig.fmtEscapes
173 try writer.print("\"{Z}\"", .{bytes});173 try writer.print("\"{}\"", .{std.zig.fmtEscapes(bytes)});
174 },174 },
175 else => {175 else => {
176 // Fall back to generic implementation.176 // Fall back to generic implementation.
src/translate_c.zig+4-3
...@@ -2031,7 +2031,7 @@ fn transStringLiteral(...@@ -2031,7 +2031,7 @@ fn transStringLiteral(
2031 const bytes_ptr = stmt.getString_bytes_begin_size(&len);2031 const bytes_ptr = stmt.getString_bytes_begin_size(&len);
2032 const str = bytes_ptr[0..len];2032 const str = bytes_ptr[0..len];
20332033
2034 const token = try appendTokenFmt(rp.c, .StringLiteral, "\"{Z}\"", .{str});2034 const token = try appendTokenFmt(rp.c, .StringLiteral, "\"{}\"", .{std.zig.fmtEscapes(str)});
2035 const node = try rp.c.arena.create(ast.Node.OneToken);2035 const node = try rp.c.arena.create(ast.Node.OneToken);
2036 node.* = .{2036 node.* = .{
2037 .base = .{ .tag = .StringLiteral },2037 .base = .{ .tag = .StringLiteral },
...@@ -2944,7 +2944,8 @@ fn transCharLiteral(...@@ -2944,7 +2944,8 @@ fn transCharLiteral(
2944 if (val > 255)2944 if (val > 255)
2945 break :blk try transCreateNodeInt(rp.c, val);2945 break :blk try transCreateNodeInt(rp.c, val);
2946 }2946 }
2947 const token = try appendTokenFmt(rp.c, .CharLiteral, "'{Z}'", .{@intCast(u8, val)});2947 const val_array = [_]u8 { @intCast(u8, val) };
2948 const token = try appendTokenFmt(rp.c, .CharLiteral, "'{}'", .{std.zig.fmtEscapes(&val_array)});
2948 const node = try rp.c.arena.create(ast.Node.OneToken);2949 const node = try rp.c.arena.create(ast.Node.OneToken);
2949 node.* = .{2950 node.* = .{
2950 .base = .{ .tag = .CharLiteral },2951 .base = .{ .tag = .CharLiteral },
...@@ -5315,7 +5316,7 @@ fn isZigPrimitiveType(name: []const u8) bool {...@@ -5315,7 +5316,7 @@ fn isZigPrimitiveType(name: []const u8) bool {
5315}5316}
53165317
5317fn appendIdentifier(c: *Context, name: []const u8) !ast.TokenIndex {5318fn appendIdentifier(c: *Context, name: []const u8) !ast.TokenIndex {
5318 return appendTokenFmt(c, .Identifier, "{z}", .{name});5319 return appendTokenFmt(c, .Identifier, "{}", .{std.zig.fmtId(name)});
5319}5320}
53205321
5321fn transCreateNodeIdentifier(c: *Context, name: []const u8) !*ast.Node {5322fn transCreateNodeIdentifier(c: *Context, name: []const u8) !*ast.Node {
src/value.zig+2-2
...@@ -491,8 +491,8 @@ pub const Value = extern union {...@@ -491,8 +491,8 @@ pub const Value = extern union {
491 val = elem_ptr.array_ptr;491 val = elem_ptr.array_ptr;
492 },492 },
493 .empty_array => return out_stream.writeAll(".{}"),493 .empty_array => return out_stream.writeAll(".{}"),
494 .enum_literal => return out_stream.print(".{z}", .{self.castTag(.enum_literal).?.data}),494 .enum_literal => return out_stream.print(".{}", .{std.zig.fmtId(self.castTag(.enum_literal).?.data)}),
495 .bytes => return out_stream.print("\"{Z}\"", .{self.castTag(.bytes).?.data}),495 .bytes => return out_stream.print("\"{}\"", .{std.zig.fmtEscapes(self.castTag(.bytes).?.data)}),
496 .repeated => {496 .repeated => {
497 try out_stream.writeAll("(repeated) ");497 try out_stream.writeAll("(repeated) ");
498 val = val.castTag(.repeated).?.data;498 val = val.castTag(.repeated).?.data;
src/zir.zig+4-4
...@@ -1308,17 +1308,17 @@ const Writer = struct {...@@ -1308,17 +1308,17 @@ const Writer = struct {
1308 try stream.writeByte('}');1308 try stream.writeByte('}');
1309 },1309 },
1310 bool => return stream.writeByte("01"[@boolToInt(param)]),1310 bool => return stream.writeByte("01"[@boolToInt(param)]),
1311 []u8, []const u8 => return stream.print("\"{Z}\"", .{param}),1311 []u8, []const u8 => return stream.print("\"{}\"", .{std.zig.fmtEscapes(param)}),
1312 BigIntConst, usize => return stream.print("{}", .{param}),1312 BigIntConst, usize => return stream.print("{}", .{param}),
1313 TypedValue => return stream.print("TypedValue{{ .ty = {}, .val = {}}}", .{ param.ty, param.val }),1313 TypedValue => return stream.print("TypedValue{{ .ty = {}, .val = {}}}", .{ param.ty, param.val }),
1314 *IrModule.Decl => return stream.print("Decl({s})", .{param.name}),1314 *IrModule.Decl => return stream.print("Decl({s})", .{param.name}),
1315 *Inst.Block => {1315 *Inst.Block => {
1316 const name = self.block_table.get(param).?;1316 const name = self.block_table.get(param).?;
1317 return stream.print("\"{Z}\"", .{name});1317 return stream.print("\"{}\"", .{std.zig.fmtEscapes(name)});
1318 },1318 },
1319 *Inst.Loop => {1319 *Inst.Loop => {
1320 const name = self.loop_table.get(param).?;1320 const name = self.loop_table.get(param).?;
1321 return stream.print("\"{Z}\"", .{name});1321 return stream.print("\"{}\"", .{std.zig.fmtEscapes(name)});
1322 },1322 },
1323 [][]const u8 => {1323 [][]const u8 => {
1324 try stream.writeByte('[');1324 try stream.writeByte('[');
...@@ -1326,7 +1326,7 @@ const Writer = struct {...@@ -1326,7 +1326,7 @@ const Writer = struct {
1326 if (i != 0) {1326 if (i != 0) {
1327 try stream.writeAll(", ");1327 try stream.writeAll(", ");
1328 }1328 }
1329 try stream.print("\"{Z}\"", .{str});1329 try stream.print("\"{}\"", .{std.zig.fmtEscapes(str)});
1330 }1330 }
1331 try stream.writeByte(']');1331 try stream.writeByte(']');
1332 },1332 },