Skip to content

Commit df8c113

Browse files
committed
simplified metaprogramming interface
1 parent 9ed4529 commit df8c113

File tree

3 files changed

+29
-8
lines changed

3 files changed

+29
-8
lines changed

src/fuzz/context.zig

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ const TestValue = union(Tag) {
6262
gpa: std.mem.Allocator,
6363
args: []const TestValue,
6464
) !TestValue {
65+
_ = gpa;
6566
if (args.len != 0) return .{ .err = "'len' wants no arguments" };
66-
return TestValue.from(gpa, str.len);
67+
return TestValue.from(str.len);
6768
}
6869
};
6970
};
@@ -86,7 +87,7 @@ const TestValue = union(Tag) {
8687
return .{ .bool = b };
8788
}
8889

89-
pub fn from(gpa: std.mem.Allocator, value: anytype) TestValue {
90+
pub fn from(gpa: std.mem.Allocator, value: anytype) !TestValue {
9091
_ = gpa;
9192
const T = @TypeOf(value);
9293
switch (T) {

src/types.zig

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@ pub fn defaultCall(comptime Value: type) fn (
4444
) error{ OutOfMemory, Interrupt }!Value {
4545
switch (value) {
4646
inline else => |v, tag| {
47-
const Builtin = Value.builtinsFor(tag);
47+
const Builtin = if (@hasDecl(Value, "builtinsFor"))
48+
Value.builtinsFor(tag)
49+
else
50+
defaultBuiltinsFor(Value, @TypeOf(v));
4851

4952
inline for (@typeInfo(Builtin).Struct.decls) |decl| {
5053
if (decl.name[0] == '_') continue;
@@ -86,3 +89,24 @@ inline fn constify(comptime T: type, comptime mut: bool) type {
8689
false => *const T,
8790
};
8891
}
92+
93+
pub fn defaultBuiltinsFor(comptime Value: type, comptime Field: type) type {
94+
inline for (std.meta.fields(Value)) |f| {
95+
if (f.type == Field) {
96+
switch (@typeInfo(f.type)) {
97+
.Pointer => |ptr| {
98+
if (@typeInfo(ptr.child) == .Struct) {
99+
return @field(ptr.child, "Builtins");
100+
}
101+
},
102+
.Struct => {
103+
return @field(f.type, "Builtins");
104+
},
105+
else => {},
106+
}
107+
108+
return struct {};
109+
}
110+
}
111+
@compileError("Value has no field of value " ++ @typeName(Field));
112+
}

src/vm.zig

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@ pub fn VM(
1616
comptime _Context: type,
1717
comptime _Value: type,
1818
) type {
19-
if (!@hasDecl(_Value, "builtinsFor")) {
20-
@compileLog("Value type must specify builtinsFor");
21-
}
22-
2319
return struct {
2420
parser: Parser = .{},
2521
stack: std.MultiArrayList(Result) = .{},
@@ -180,7 +176,7 @@ pub fn VM(
180176
const path = src[start..end];
181177

182178
const old_value = if (global)
183-
Value.from(gpa, ctx)
179+
try Value.from(gpa, ctx)
184180
else blk: {
185181
if (builtin.mode == .Debug) {
186182
const stack_debug = slice.items(.debug);

0 commit comments

Comments
 (0)