From c19f6df834f712642bec3958be94db21bcf204b5 Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 4 Jun 2019 21:27:05 -0300 Subject: [PATCH] split main code into a runner struct --- src/main.zig | 26 +++++--------------------- src/parser.zig | 1 + src/runner.zig | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 21 deletions(-) create mode 100644 src/parser.zig create mode 100644 src/runner.zig diff --git a/src/main.zig b/src/main.zig index e538343..b9ca981 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,6 +1,6 @@ const std = @import("std"); -const scanners = @import("scanner.zig"); +const runners = @import("runner.zig"); const Allocator = std.mem.Allocator; @@ -9,30 +9,14 @@ pub const Result = error{ CompileError, }; +pub const StdOut = *std.io.OutStream(std.fs.File.WriteError); + fn run(allocator: *Allocator, data: []u8) !void { var stdout_file = try std.io.getStdOut(); const stdout = &stdout_file.outStream().stream; - var scanner = scanners.Scanner.init(allocator, data); - - while (true) { - var tok_opt = scanner.nextToken() catch |err| { - try stdout.print( - "error at '{}': {}\n", - scanner.currentLexeme(), - err, - ); - - return Result.CompileError; - }; - - if (tok_opt) |tok| { - if (tok.ttype == .EOF) break; - try stdout.print("{x}\n", tok); - } - } - - return Result.Ok; + var runner = runners.Runner.init(allocator, stdout); + return runner.execute(data); } fn runFile(allocator: *Allocator, path: []const u8) !void { diff --git a/src/parser.zig b/src/parser.zig new file mode 100644 index 0000000..c4deda6 --- /dev/null +++ b/src/parser.zig @@ -0,0 +1 @@ +pub const Parser = struct {}; diff --git a/src/runner.zig b/src/runner.zig new file mode 100644 index 0000000..0846552 --- /dev/null +++ b/src/runner.zig @@ -0,0 +1,38 @@ +const std = @import("std"); +const scanners = @import("scanner.zig"); +const main = @import("main.zig"); + +const Allocator = std.mem.Allocator; +const Result = main.Result; + +pub const Runner = struct { + allocator: *Allocator, + stdout: main.StdOut, + + pub fn init(allocator: *Allocator, stdout: var) Runner { + return Runner{ .allocator = allocator, .stdout = stdout }; + } + + pub fn execute(self: *Runner, code: []u8) !void { + var scanner = scanners.Scanner.init(self.allocator, code); + + while (true) { + var tok_opt = scanner.nextToken() catch |err| { + try self.stdout.print( + "error at '{}': {}\n", + scanner.currentLexeme(), + err, + ); + + return Result.CompileError; + }; + + if (tok_opt) |tok| { + if (tok.ttype == .EOF) break; + try self.stdout.print("{x}\n", tok); + } + } + + return Result.Ok; + } +};