jorts/src/value.zig

81 lines
1.9 KiB
Zig

const std = @import("std");
const objects = @import("object.zig");
const Allocator = std.mem.Allocator;
pub const ValueType = enum(u8) {
Bool,
Nil,
Number,
Object,
};
pub const ValueValue = union(ValueType) {
Bool: bool,
Nil: void,
Number: f64,
Object: *objects.Object,
};
pub const Value = struct {
vtype: ValueType,
as: ValueValue,
};
// helper functions
pub fn BoolVal(val: bool) Value {
return Value{ .vtype = .Bool, .as = ValueValue{ .Bool = val } };
}
pub fn NilVal() Value {
return Value{ .vtype = .Nil, .as = ValueValue{ .Nil = {} } };
}
pub fn NumberVal(val: f64) Value {
return Value{ .vtype = .Number, .as = ValueValue{ .Number = val } };
}
pub fn ObjVal(val: *objects.Object) Value {
return Value{ .vtype = .Object, .as = ValueValue{ .Object = val } };
}
pub fn isObjType(val: Value, otype: objects.ObjType) bool {
return val.vtype == .Object and val.as.Object.otype == otype;
}
pub fn printValue(stdout: var, value: Value) !void {
switch (value.as) {
.Nil => try stdout.print("nil"),
.Bool => try stdout.print("{}", value.as.Bool),
.Number => try stdout.print("{}", value.as.Number),
.Object => try objects.printObject(stdout, value.as.Object.*),
else => unreachable,
}
}
pub const ValueList = struct {
count: usize,
values: []Value,
allocator: *Allocator,
pub fn init(allocator: *Allocator) !ValueList {
return ValueList{
.count = 0,
.allocator = allocator,
.values = try allocator.alloc(Value, 0),
};
}
pub fn write(self: *ValueList, value: Value) !void {
if (self.values.len < self.count + 1) {
self.values = try self.allocator.realloc(
self.values,
self.count + 1,
);
}
self.values[self.count] = value;
self.count += 1;
}
};