Skip to content

Commit

Permalink
update main zig file
Browse files Browse the repository at this point in the history
  • Loading branch information
rubenkristian committed Aug 30, 2022
1 parent 5dd0f42 commit 52921b0
Showing 1 changed file with 38 additions and 11 deletions.
49 changes: 38 additions & 11 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 52921b0

Please sign in to comment.