feat: implementar msg de error dinamicos

This commit is contained in:
Fernando Araoz 2025-01-31 19:08:25 -05:00
parent db55a00ad2
commit 63d618e06f
3 changed files with 55 additions and 1 deletions

View File

@ -18,6 +18,27 @@ pub const TokenType = enum {
Newline,
// Each keyword will have its own token
K_Var,
pub fn to_string(self: *TokenType) []const u8 {
return switch (self.*) {
TokenType.Int => "Int",
TokenType.Float => "Float",
TokenType.Identifier => "Identifier",
TokenType.Datatype => "Datatype",
TokenType.Operator => "Operator",
TokenType.Comment => "Comment",
TokenType.String => "String",
TokenType.LeftParen => "LeftParen",
TokenType.RightParen => "RightParen",
TokenType.LeftBracket => "LeftBracket",
TokenType.RightBracket => "RightBracket",
TokenType.LeftBrace => "LeftBrace",
TokenType.RightBrace => "RightBrace",
TokenType.Comma => "Comma",
TokenType.Newline => "Newline",
TokenType.K_Var => "K_Var",
};
}
};
pub const Token = struct {

View File

@ -47,7 +47,20 @@ pub const VariableBinding = struct {
// try to parse an identifier
const identifier = if (utils.expect_token_type(lexic.TokenType.Identifier, &tokens.items[pos + 1])) |i| i else {
// TODO: populate error information
const faulty_token = &tokens.items[pos + 1];
var err = try ctx.create_and_append_error(
"Invalid variable declaration",
faulty_token.start_pos,
faulty_token.start_pos + faulty_token.value.len,
);
const token_name = faulty_token.token_type.to_string();
const error_name = try std.fmt.allocPrint(ctx.allocator, "Expected an identifier here, found a {s}", .{token_name});
try err.add_label(ctx.create_error_label_alloc(
error_name,
faulty_token.start_pos,
faulty_token.start_pos + faulty_token.value.len,
));
return ParseError.Error;
};

View File

@ -64,6 +64,26 @@ pub const CompilerContext = struct {
};
}
/// Creates a new ErrorLabel with a dynamic message.
/// Resource cleanup is automatic.
///
/// `message` **must** be allocated with the allocator
/// of this context, because on cleanup this will be
/// passed to `ctx.allocator.destroy(message)`.
pub fn create_error_label_alloc(
self: *CompilerContext,
message: []u8,
start: usize,
end: usize,
) ErrorLabel {
_ = self;
return .{
.message = .{ .dynamic = message },
.start = start,
.end = end,
};
}
pub fn deinit(self: *CompilerContext) void {
for (self.errors.items) |*error_item| {
error_item.deinit(self.allocator);