diff --git a/lib/std/zig/Ast/Render.zig b/lib/std/zig/Ast/Render.zig index e9caab17a3..a501b21d10 100644 --- a/lib/std/zig/Ast/Render.zig +++ b/lib/std/zig/Ast/Render.zig @@ -3257,6 +3257,9 @@ fn renderIdentifierContents(ais: *AutoIndentingStream, bytes: []const u8) !void } }, .failure => { + // Escape the stray backslash + // This also avoids cases like "\x3\x39" becoming "\x39" + try ais.writeByte('\\'); try ais.writeAll(escape_sequence); }, } diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index ab0181ede8..800caf0e94 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -6666,6 +6666,24 @@ test "zig fmt: doc comments on fn parameters" { ); } +test "zig fmt: canonicalize stray backslashes in identifiers" { + try testTransform( + \\const @"\x" = undefined; + \\const @"\x3" = undefined; + \\const @"\x3\x39" = undefined; + \\const @"\u{" = undefined; + \\const @"\?" = undefined; + \\ + , + \\const @"\\x" = undefined; + \\const @"\\x3" = undefined; + \\const @"\\x39" = undefined; + \\const @"\\u{" = undefined; + \\const @"\\?" = undefined; + \\ + ); +} + test "recovery: top level" { try testError( \\test "" {inline}