jorts/src/value.zig

70 lines
1.5 KiB
Zig

const std = @import("std");
const Allocator = std.mem.Allocator;
// NOTE: right now, only numbers.
pub const ValueType = enum(u8) {
Bool,
Nil,
Number,
};
pub const ValueValue = union(ValueType) {
Bool: bool,
Nil: void,
Number: f64,
};
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 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),
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;
}
};