adding a new command to the REPL

This commit is contained in:
Lynn Leichtle 2024-09-15 22:56:42 +02:00
parent 5f81630224
commit 2f16975be7
Signed by: lynn
GPG key ID: 55E797F631DDA03C
2 changed files with 35 additions and 6 deletions

View file

@ -1,18 +1,32 @@
const std = @import("std");
const mem = @import("memory.zig");
pub fn main() !void {
var memory = mem.Memory.init();
var input = std.io.getStdIn().reader();
std.debug.print("MI-HA-RU (386) REPL\nType 'exit' to quit.\n", .{});
var buffer: [256]u8 = undefined;
while (true) {
std.debug.print("> ", .{});
const line = try input.readUntilDelimiterOrEof(&buffer, '\n');
if (line == null) {
const clean = std.mem.trim(u8, line.?, " \n\r");
var it = std.mem.splitSequence(u8, clean, " ");
if (it.next()) |first_argument| {
if (std.mem.eql(u8, first_argument, "exit")) {
break;
} else if (std.mem.eql(u8, first_argument, "mem")) {
try handleMemoryCommand(&memory, &it);
}
if (std.mem.eql(u8, line.?, "exit")) {
break;
} else {
// noop
}
}
}
fn handleMemoryCommand(memory: *mem.Memory, it: anytype) !void {
if (it.next()) |next_argument| {
const addr = try std.fmt.parseUnsigned(u8, next_argument, 10);
const value = try memory.readByte(addr);
std.debug.print("{}\n", .{value});
}
}

15
src/memory.zig Normal file
View file

@ -0,0 +1,15 @@
const MEM_SIZE: usize = 1 * 1024 * 1024; // 1mb
pub const Memory = struct {
data: [MEM_SIZE]u8,
pub fn init() Memory {
return Memory{
.data = [_]u8{0} ** MEM_SIZE,
};
}
pub fn readByte(self: *Memory, addr: u8) !u8 {
return self.data[addr];
}
};