add nicer error handling, whitespace skipping
This commit is contained in:
parent
59083198c6
commit
1453bef6c5
2 changed files with 28 additions and 2 deletions
10
src/main.zig
10
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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
Loading…
Reference in a new issue