basic parser

This commit is contained in:
Luna 2019-07-08 00:09:34 -03:00
parent 4bbe980014
commit be280d44f3
2 changed files with 41 additions and 7 deletions

View file

@ -5,18 +5,36 @@ pub const CommandType = enum {
Load,
Amp,
Quicksave,
// TODO proper errs
Error,
};
pub const Command = struct {
command: CommandType,
args: []const u8,
args: ArgList,
pub fn print(self: *const Command) void {
std.debug.warn("cmd:{} args:{}\n", self.command, self.args);
std.debug.warn("cmd:{}\n", self.command);
}
};
pub const CommandList = std.ArrayList(Command);
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;
}
}
pub const Lang = struct {
allocator: *std.mem.Allocator,
@ -25,7 +43,7 @@ pub const Lang = struct {
return Lang{ .allocator = allocator };
}
pub fn parse(self: *Lang, data: []const u8) CommandList {
pub fn parse(self: *Lang, data: []const u8) !CommandList {
var splitted_it = std.mem.separate(data, ";");
var cmds = CommandList.init(self.allocator);
@ -34,10 +52,26 @@ pub const Lang = struct {
if (stmt.len == 0) continue;
// TODO parse stmt
std.debug.warn("full cmd: '{}'\n", stmt);
// 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);
}
return cmds;
}
};
// TODO tests

View file

@ -323,7 +323,7 @@ pub fn main() !void {
var data = try allocator.alloc(u8, total_bytes);
_ = try file.read(data);
var cmds = lang.parse(data);
var cmds = try lang.parse(data);
var it = cmds.iterator();
while (it.next()) |cmd| {
cmd.print();