feat: serialize ErrorLabel to json

This commit is contained in:
Fernando Araoz 2025-01-21 20:42:44 -05:00
parent 184745e83d
commit 69a3fa57a8
2 changed files with 68 additions and 6 deletions

View File

@ -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);
}

View File

@ -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();
}