I have written a lexer for an assembly like language in zig. i have also implemented a .eql() function for my tokens to make sure that they are the same.
This is my test file:
const std = @import("std");
const testing = std.testing;
const assert = testing.expect;
const allocator = testing.allocator;
const TokenKind = @import("token").TokenKind;
const Token = @import("token").Token;
const L = @import("lexer");
const Lexer = L.Lexer;
fn assert_eq(slice1: []const Token, slice2: []const Token) !void {
if (slice1.len != slice2.len) return error.TestUnexpectedResult;
for (slice1, 0..) |_, i| {
if (slice1[i].eql(slice2[i])) {
continue;
} else {
return error.TestUnexpectedResult;
}
}
}
test "test single character tokens" {
const input: []const u8 = "[] () .,: #";
var lexer = Lexer.init(allocator, input);
defer lexer.deinit();
const tests = [_]Token{
.{ .kind = .LBracket, .line = 1 },
.{ .kind = .RBracket, .line = 1 },
.{ .kind = .LParen, .line = 1 },
.{ .kind = .RParen, .line = 1 },
.{ .kind = .Dot, .line = 1 },
.{ .kind = .Comma, .line = 1 },
.{ .kind = .Colon, .line = 1 },
.{ .kind = .Hashtag, .line = 1 },
.{ .kind = .Eof, .line = 1 },
};
try lexer.tokenize();
try assert(lexer.errors.items.len == 0);
try testing.expectEqualSlices(Token, &tests, lexer.tokens.items);
}
test "test whitespace and newlines" {
const input: []const u8 =
\\ADD
\\
\\HALT
;
var lexer = Lexer.init(allocator, input);
defer lexer.deinit();
const tests = [_]Token{ .{ .kind = .{ .Identifier = "ADD" }, .line = 1 }, .{ .kind = .{ .Identifier = "HALT" }, .line = 3 }, .{ .kind = .Eof, .line = 3 } };
const tokens = try lexer.getTokens();
try assert(lexer.errors.items.len == 0);
try assert_eq(tests[0..], tokens);
}
I have checked before that the .eql function works between tokens. Then during this call specifically in the second test for the lexer
try std.testing.expectEqualSlices(Token, &tests, tokens);
i get this output:
============ expected this output: ============= len: 3 (0x3)
[0]: .{ .kind = .{ .Identifier = { 65, 68, 68 } }, .line = 1 }
[1]: .{ .kind = .{ .Identifier = { 72, 65, 76, 84 } }, .line = 3 }
[2]: .{ .kind = .{ .Eof = void }, .line = 3 }
============= instead found this: ============== len: 3 (0x3)
[0]: .{ .kind = .{ .Identifier = { 65, 68, 68 } }, .line = 1 }
[1]: .{ .kind = .{ .Identifier = { 72, 65, 76, 84 } }, .line = 3 }
[2]: .{ .kind = .{ .Eof = void }, .line = 3 }
================================================
the function states that the two slices are identical, yet it fails. Is this a fault on my end?