From 69a3fa57a82a2ce30cf52cd29cdf97b54d15423d Mon Sep 17 00:00:00 2001 From: Fernando Araoz Date: Tue, 21 Jan 2025 20:42:44 -0500 Subject: [PATCH] feat: serialize ErrorLabel to json --- src/errors/error_label.zig | 61 ++++++++++++++++++++++++++++++++++++++ src/errors/root.zig | 13 ++++---- 2 files changed, 68 insertions(+), 6 deletions(-) create mode 100644 src/errors/error_label.zig diff --git a/src/errors/error_label.zig b/src/errors/error_label.zig new file mode 100644 index 0000000..0e955df --- /dev/null +++ b/src/errors/error_label.zig @@ -0,0 +1,61 @@ +const std = @import("std"); + +pub const ErrorLabel = struct { + message: []const u8, + start: usize, + end: usize, + + /// Converts this struct into JSON + pub fn json(self: ErrorLabel, alloc: std.mem.Allocator) ![]u8 { + return try std.json.stringifyAlloc(alloc, .{ + .message = self.message, + .start = self.start, + .end = self.end, + }, .{}); + } +}; + +test "should serialize" { + const label = ErrorLabel{ + .message = "Error", + .start = 5, + .end = 6, + }; + const json_str = try label.json(std.testing.allocator); + defer std.testing.allocator.free(json_str); + + const expected = + \\{"message":"Error","start":5,"end":6} + ; + try std.testing.expectEqualStrings(expected, json_str); +} + +test "should handle special characters" { + const label = ErrorLabel{ + .message = "Error\"with\"quotes", + .start = 0, + .end = 1, + }; + const json_str = try label.json(std.testing.allocator); + defer std.testing.allocator.free(json_str); + + const expected = + \\{"message":"Error\"with\"quotes","start":0,"end":1} + ; + try std.testing.expectEqualStrings(expected, json_str); +} + +test "should serialize empty message" { + const label = ErrorLabel{ + .message = "", + .start = 0, + .end = 0, + }; + const json_str = try label.json(std.testing.allocator); + defer std.testing.allocator.free(json_str); + + const expected = + \\{"message":"","start":0,"end":0} + ; + try std.testing.expectEqualStrings(expected, json_str); +} diff --git a/src/errors/root.zig b/src/errors/root.zig index e84d72f..ee27bdd 100644 --- a/src/errors/root.zig +++ b/src/errors/root.zig @@ -1,10 +1,5 @@ const std = @import("std"); - -pub const ErrorLabel = struct { - message: []const u8, - start: usize, - end: usize, -}; +pub const ErrorLabel = @import("./error_label.zig").ErrorLabel; /// Holds information about errors generated during the compilation, /// and pretty prints them. @@ -158,6 +153,12 @@ pub const ErrorData = struct { // - Get previous, current and next line // - Display message + /// Transform this error into a JSON + pub fn json(alloc: std.mem.Allocator) void { + _ = alloc; + std.debug.panic(":c"); + } + pub fn deinit(self: *@This()) void { self.labels.deinit(); }