diff --git a/src/main.zig b/src/main.zig index 78ef22a..7999f1f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -16,7 +16,15 @@ fn run(allocator: *Allocator, data: []u8) !void { var scanner = scanners.Scanner.init(allocator, data); while (true) { - var tok = try scanner.nextToken(); + var tok = scanner.nextToken() catch |err| { + try stdout.print( + "error at '{}': {}\n", + scanner.currentLexeme(), + err, + ); + + return Result.CompileError; + }; if (tok.ttype == .EOF) break; try stdout.print("{x}\n", tok); } diff --git a/src/scanner.zig b/src/scanner.zig index c7319fa..36d54b9 100644 --- a/src/scanner.zig +++ b/src/scanner.zig @@ -104,7 +104,7 @@ pub const Scanner = struct { return self.source[self.current - 1]; } - fn currentLexeme(self: *Scanner) []const u8 { + pub fn currentLexeme(self: *Scanner) []const u8 { return self.source[self.start..self.current]; } @@ -156,7 +156,25 @@ pub const Scanner = struct { return self.source[self.current + 1]; } + fn skipWhitespace(self: *Scanner) void { + while (true) { + var c = self.peek(); + + switch (c) { + ' ', '\r', '\t' => blk: { + _ = self.advance(); + }, + '\n' => blk: { + self.line += 1; + _ = self.advance(); + }, + else => return, + } + } + } + pub fn nextToken(self: *Scanner) !Token { + self.skipWhitespace(); self.start = self.current; if (self.isAtEnd()) return self.makeToken(TokenType.EOF);