scritcher/src/lang.zig

78 lines
1.9 KiB
Zig
Raw Normal View History

2019-07-08 02:03:55 +00:00
const std = @import("std");
pub const CommandType = enum {
Noop,
Load,
Amp,
Quicksave,
2019-07-08 03:09:34 +00:00
// TODO proper errs
Error,
2019-07-08 02:03:55 +00:00
};
pub const Command = struct {
command: CommandType,
2019-07-08 03:09:34 +00:00
args: ArgList,
2019-07-08 02:03:55 +00:00
pub fn print(self: *const Command) void {
2019-07-08 03:09:34 +00:00
std.debug.warn("cmd:{}\n", self.command);
2019-07-08 02:03:55 +00:00
}
};
2019-07-08 03:09:34 +00:00
pub const CommandList = std.ArrayList(*Command);
pub const ArgList = std.ArrayList([]const u8);
pub fn commandToCmdType(command: []const u8) CommandType {
if (std.mem.eql(u8, command, "noop")) {
return .Noop;
} else if (std.mem.eql(u8, command, "load")) {
return .Load;
} else if (std.mem.eql(u8, command, "amp")) {
return .Amp;
} else if (std.mem.eql(u8, command, "quicksave")) {
return .Quicksave;
} else {
return .Error;
}
}
2019-07-08 02:03:55 +00:00
pub const Lang = struct {
allocator: *std.mem.Allocator,
pub fn init(allocator: *std.mem.Allocator) Lang {
return Lang{ .allocator = allocator };
}
2019-07-08 03:09:34 +00:00
pub fn parse(self: *Lang, data: []const u8) !CommandList {
2019-07-08 02:03:55 +00:00
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;
2019-07-08 03:09:34 +00:00
// TODO better tokenizer instead of just tokenize(" ");
var tok_it = std.mem.tokenize(stmt, " ");
// TODO send errors
var command = tok_it.next().?;
var ctype = 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);
2019-07-08 02:03:55 +00:00
}
return cmds;
}
};
2019-07-08 03:09:34 +00:00
// TODO tests