feat: minimal, single digit, int lexer

This commit is contained in:
Araozu 2024-11-16 06:42:26 -05:00
parent d8df211f46
commit 5b940c9e44
2 changed files with 58 additions and 15 deletions

View File

@ -1,3 +1,52 @@
pub fn stub() i32 { const std = @import("std");
return 322; const t = std.testing;
const TokenType = enum {
Int,
Float,
};
const Token = struct {
value: []const u8,
token_type: TokenType,
start_pos: usize,
pub fn init(value: []const u8, token_type: TokenType, start: usize) Token {
return Token{
.value = value,
.token_type = token_type,
.start_pos = start,
};
}
};
pub fn tokenize(input: []const u8) !void {
const next_token = try number(input, 0);
_ = next_token;
std.debug.print("tokenize :D {s}\n", .{input});
}
fn number(input: []const u8, start: usize) !?Token {
const first_char = input[start];
if (!is_digit(first_char)) {
return null;
}
return Token.init(input[start .. start + 1], TokenType.Int, start);
}
fn is_digit(c: u8) bool {
return '0' <= c and c <= '9';
}
test "number lexer" {
const input = "3";
const result = try number(input, 0);
if (result) |r| {
try std.testing.expectEqual("3", r.value);
} else {
try std.testing.expect(false);
}
} }

View File

@ -5,9 +5,6 @@ const thp_version: []const u8 = "0.0.0";
pub fn main() !void { pub fn main() !void {
try repl(); try repl();
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
} }
fn repl() !void { fn repl() !void {
@ -15,18 +12,20 @@ fn repl() !void {
var bw = std.io.bufferedWriter(stdout_file); var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer(); const stdout = bw.writer();
try stdout.print("The THP REPL, v{s}\n", .{thp_version}); try stdout.print("The THP REPL, v{s}\n", .{thp_version});
try stdout.print("Enter expressions to evaluate. Enter CTRL-D to exit.\n\n", .{}); try stdout.print("Enter expressions to evaluate. Enter CTRL-D to exit.\n", .{});
try bw.flush(); try bw.flush();
const stdin = std.io.getStdIn().reader(); const stdin = std.io.getStdIn().reader();
try stdout.print("thp => ", .{}); try stdout.print("\nthp => ", .{});
try bw.flush(); try bw.flush();
const user_input = try stdin.readUntilDelimiterAlloc(std.heap.page_allocator, '\n', 8192); const bare_line = try stdin.readUntilDelimiterAlloc(std.heap.page_allocator, '\n', 8192);
defer std.heap.page_allocator.free(user_input); defer std.heap.page_allocator.free(bare_line);
const line = std.mem.trim(u8, bare_line, "\r");
try lexic.tokenize(line);
try stdout.print("got: `{s}`\n", .{user_input});
try bw.flush(); try bw.flush();
} }
@ -36,8 +35,3 @@ test "simple test" {
try list.append(42); try list.append(42);
try std.testing.expectEqual(@as(i32, 42), list.pop()); try std.testing.expectEqual(@as(i32, 42), list.pop());
} }
test "new test" {
const res = lexic.stub();
try std.testing.expectEqual(@as(i32, 322), res);
}