2019-06-02 17:01:54 +00:00
|
|
|
const std = @import("std");
|
2019-06-02 17:52:19 +00:00
|
|
|
const vm = @import("vm.zig");
|
2019-06-02 17:01:54 +00:00
|
|
|
|
|
|
|
const Allocator = std.mem.Allocator;
|
|
|
|
|
|
|
|
pub const ObjType = enum {
|
|
|
|
String,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub const ObjValue = struct {
|
|
|
|
String: []u8,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub const Object = struct {
|
|
|
|
otype: ObjType,
|
|
|
|
value: ObjValue,
|
2019-06-02 17:52:19 +00:00
|
|
|
next: ?*Object = null,
|
2019-06-02 17:01:54 +00:00
|
|
|
};
|
|
|
|
|
2019-06-02 17:52:19 +00:00
|
|
|
pub fn allocateObject(
|
|
|
|
vmach: *vm.VM,
|
|
|
|
otype: ObjType,
|
|
|
|
value: ObjValue,
|
|
|
|
) !*Object {
|
|
|
|
var obj = try vmach.allocator.create(Object);
|
|
|
|
obj.otype = otype;
|
|
|
|
obj.value = value;
|
|
|
|
|
|
|
|
obj.next = vmach.objs;
|
|
|
|
vmach.objs = obj;
|
2019-06-02 17:18:01 +00:00
|
|
|
return obj;
|
|
|
|
}
|
|
|
|
|
2019-06-02 17:52:19 +00:00
|
|
|
fn createString(vmach: *vm.VM, data: []u8) !*Object {
|
|
|
|
return allocateObject(vmach, ObjType.String, ObjValue{ .String = data });
|
|
|
|
}
|
2019-06-02 17:01:54 +00:00
|
|
|
|
2019-06-02 17:52:19 +00:00
|
|
|
pub fn copyString(vmach: *vm.VM, data: []const u8) !*Object {
|
|
|
|
var str = try vmach.allocator.alloc(u8, data.len);
|
|
|
|
std.mem.copy(u8, str, data);
|
|
|
|
return try createString(vmach, str);
|
2019-06-02 17:18:01 +00:00
|
|
|
}
|
2019-06-02 17:01:54 +00:00
|
|
|
|
2019-06-02 17:18:01 +00:00
|
|
|
/// Assumes it can take ownership of the given data.
|
2019-06-02 17:52:19 +00:00
|
|
|
pub fn takeString(vmach: *vm.VM, data: []u8) !*Object {
|
|
|
|
return try createString(vmach, data);
|
2019-06-02 17:01:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn printObject(stdout: var, obj: Object) !void {
|
|
|
|
switch (obj.otype) {
|
|
|
|
.String => try stdout.print("{}", obj.value.String),
|
|
|
|
else => unreachable,
|
|
|
|
}
|
|
|
|
}
|