DzLox

:)
git clone https://git.sr.ht/~ashymad/DzLox
Log | Files | Refs | Submodules | LICENSE

main.zig (1696B)


      1 const std = @import("std");
      2 const linenoise = @import("linenoise");
      3 
      4 const vm = @import("vm.zig");
      5 
      6 pub fn main(init: std.process.Init) anyerror!u8 {
      7     const allocator = init.gpa;
      8     const io = init.io;
      9 
     10     const args = try init.minimal.args.toSlice(init.arena.allocator());
     11 
     12     if (args.len == 1) {
     13         try repl(allocator, io, false);
     14     } else if (args.len == 2) {
     15         if (std.mem.eql(u8, args[1], "-d")) {
     16             try repl(allocator, io, true);
     17         } else {
     18             try runFile(allocator, io, args[1], false);
     19         }
     20     } else if (args.len == 3) {
     21         if (std.mem.eql(u8, args[1], "-d")) {
     22             try runFile(allocator, io, args[2], true);
     23         } else {
     24             try runFile(allocator, io, args[1], true);
     25         }
     26     } else {
     27         std.debug.print("Usage: {s} [path]\n", .{args[0]});
     28         return 64;
     29     }
     30 
     31     return 0;
     32 }
     33 
     34 pub fn runFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8, dbg: bool) anyerror!void {
     35     const text = try std.Io.Dir.cwd().readFileAlloc(io, path, allocator, std.Io.Limit.unlimited);
     36     defer allocator.free(text);
     37     var VM = try vm.VM.init(allocator, io);
     38     defer VM.deinit();
     39 
     40     try VM.interpret(text, dbg);
     41 }
     42 
     43 pub fn repl(allocator: std.mem.Allocator, io: std.Io, dbg: bool) anyerror!void {
     44     var VM = try vm.VM.init(allocator, io);
     45     defer VM.deinit();
     46 
     47     _ = linenoise.linenoiseHistorySetMaxLen(100);
     48 
     49     while (linenoise.linenoise("lox> ")) |line| {
     50         defer linenoise.linenoiseFree(line);
     51         VM.interpret(std.mem.span(line), dbg) catch |err| {
     52             std.debug.print("\nError: {any}\n", .{err});
     53         };
     54         _ = linenoise.linenoiseHistoryAdd(line);
     55     }
     56 }