const std = @import("std"); pub const ParseError = error{ NoCommandGiven, UnknownCommand, }; pub const CommandType = enum { Noop, Load, Amp, Quicksave, }; pub const Command = struct { command: CommandType, args: ArgList, pub fn print(self: *const Command) void { std.debug.warn("cmd:{}\n", self.command); } }; pub const CommandList = std.ArrayList(*Command); pub const ArgList = std.ArrayList([]const u8); pub fn commandToCmdType(command: []const u8) ParseError!CommandType { if (std.mem.eql(u8, command, "noop")) { return CommandType.Noop; } else if (std.mem.eql(u8, command, "load")) { return CommandType.Load; } else if (std.mem.eql(u8, command, "amp")) { return CommandType.Amp; } else if (std.mem.eql(u8, command, "quicksave")) { return CommandType.Quicksave; } else { std.debug.warn("Unknown command: '{}'\n", command); return ParseError.UnknownCommand; } } pub const Lang = struct { allocator: *std.mem.Allocator, pub fn init(allocator: *std.mem.Allocator) Lang { return Lang{ .allocator = allocator }; } pub fn parse(self: *Lang, data: []const u8) !CommandList { var splitted_it = std.mem.separate(data, ";"); var cmds = CommandList.init(self.allocator); while (splitted_it.next()) |stmt_orig| { var stmt = std.mem.trimRight(u8, stmt_orig, "\n"); if (stmt.len == 0) continue; // TODO better tokenizer instead of just tokenize(" "); var tok_it = std.mem.tokenize(stmt, " "); var cmd_opt = tok_it.next(); if (cmd_opt == null) return ParseError.NoCommandGiven; var command = cmd_opt.?; var ctype = try commandToCmdType(command); var args = ArgList.init(self.allocator); while (tok_it.next()) |arg| { try args.append(arg); } // construct final Command based on command var cmd_ptr = try self.allocator.create(Command); cmd_ptr.* = Command{ .command = ctype, .args = args }; try cmds.append(cmd_ptr); } return cmds; } }; // TODO tests