From 52921b062cc12f5170711c270c10f962784a6429 Mon Sep 17 00:00:00 2001 From: rubenkristian Date: Wed, 31 Aug 2022 00:04:07 +0700 Subject: [PATCH] update main zig file --- src/main.zig | 49 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/src/main.zig b/src/main.zig index 6c0f615..b156e74 100644 --- a/src/main.zig +++ b/src/main.zig @@ -4,32 +4,59 @@ const heap = std.heap; const bf = @import("./bf.zig"); const expect = std.testing.expect; +const ReadError = error { + FileNotFound, + AllocatorError, + StatError, + ReaderError, +}; + pub fn main() !void { - const alloc: Allocator = heap.page_allocator; + const alloc = heap.page_allocator; var args = try std.process.argsAlloc(alloc); defer alloc.free(args); if (args.len > 1) { const file: []const u8 = args[1]; - const content = try readFile(alloc, file); + const content = readFile(alloc, file) catch |readError| { + switch (readError) { + ReadError.FileNotFound => { + std.log.err("File not found", .{}); + }, + ReadError.AllocatorError => { + std.log.err("Allocation error", .{}); + }, + ReadError.StatError => { + std.log.err("Cannot check file", .{}); + }, + ReadError.ReaderError => { + std.log.err("Cannot read file", .{}); + } + } + return; + }; var brainfuck = try bf.Brainf.init(alloc); defer brainfuck.deinit(); - const tokens: []bf.Token = try brainfuck.tokenize(content); - - std.debug.print("{}\n", .{tokens.len}); + + // brainfuck.reset(); + _ = try brainfuck.tokenize(content); + + try brainfuck.Interpreter(); } else { - std.log.warn("missing brainfuck file", .{}); + std.log.warn("missing command brainfuck file", .{}); } } -fn readFile(allocator: Allocator, file: []const u8) ![]const u8 { - const read_file = try std.fs.cwd().openFile(file, .{ .mode = .read_only }); +fn readFile(allocator: Allocator, file: []const u8) ReadError![]const u8 { + const read_file = std.fs.cwd().openFile(file, .{ .mode = .read_only }) catch { + return error.FileNotFound; + }; defer read_file.close(); - const file_size = (try read_file.stat()).size; - var buffer = try allocator.alloc(u8, file_size); - try read_file.reader().readNoEof(buffer); + const file_size = (read_file.stat() catch return error.StatError).size; + var buffer = allocator.alloc(u8, file_size) catch return error.AllocatorError; + read_file.reader().readNoEof(buffer) catch return error.ReaderError; return buffer; }