Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement toTuple and custom functions for toAny and pushAny #123

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 129 additions & 7 deletions src/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,34 @@ pub fn Parsed(comptime T: type) type {
};
}

const internals = [_][]const u8{ "toStruct", "toSlice", "toTuple", "toAnyInternal" };

// wrap over some internal functions of the Lua struct
pub const Internals = blk: {
axdank marked this conversation as resolved.
Show resolved Hide resolved
const StructField = std.builtin.Type.StructField;
var fields: [internals.len]StructField = undefined;
for (internals, 0..) |entry, i| {
const F = @field(Lua, entry);
const T = @TypeOf(F);
fields[i] = .{
.name = @ptrCast(entry),
.type = T,
.default_value = &F,
.is_comptime = false,
.alignment = @alignOf(T),
};
}

const TT = @Type(.{ .@"struct" = .{
.layout = .auto,
.fields = &fields,
.decls = &.{},
.is_tuple = false,
} });

break :blk TT{};
};

/// A Zig wrapper around the Lua C API
/// Represents a Lua state or thread and contains the entire state of the Lua interpreter
pub const Lua = opaque {
Expand Down Expand Up @@ -4343,7 +4371,27 @@ pub const Lua = opaque {
/// Works with ints, floats, booleans, structs,
/// tagged unions, optionals, and strings
pub fn pushAny(lua: *Lua, value: anytype) !void {
switch (@typeInfo(@TypeOf(value))) {
const T = @TypeOf(value);
const type_info = @typeInfo(T);

if (type_info == .@"struct" or type_info == .@"union" or type_info == .@"enum") {
if (@hasDecl(T, "ziglua_pushAny")) {
axdank marked this conversation as resolved.
Show resolved Hide resolved
const fnInfo = @typeInfo(@TypeOf(T.ziglua_pushAny)).@"fn";
switch (fnInfo.params.len) {
// fn(self, lua) -> void
2 => {
if (@typeInfo(fnInfo.return_type.?) == .error_union) {
return try value.ziglua_pushAny(lua);
} else {
return value.ziglua_pushAny(lua);
}
},
else => @compileError(@typeName(T) ++ ".ziglua_pushAny has invalid signature, required: fn(self: T, lua: *Lua) void"),
}
}
}

switch (type_info) {
.int, .comptime_int => {
lua.pushInteger(@intCast(value));
},
Expand Down Expand Up @@ -4398,10 +4446,18 @@ pub const Lua = opaque {
},
.@"struct" => |info| {
lua.createTable(0, 0);
inline for (info.fields) |field| {
try lua.pushAny(field.name);
try lua.pushAny(@field(value, field.name));
lua.setTable(-3);
if (info.is_tuple) {
inline for (0..info.fields.len) |i| {
try lua.pushAny(i + 1);
try lua.pushAny(value[i]);
lua.setTable(-3);
}
} else {
inline for (info.fields) |field| {
try lua.pushAny(field.name);
try lua.pushAny(@field(value, field.name));
lua.setTable(-3);
}
}
},
.@"union" => |info| {
Expand Down Expand Up @@ -4468,7 +4524,26 @@ pub const Lua = opaque {
}
}

switch (@typeInfo(T)) {
const type_info = @typeInfo(T);

if (type_info == .@"struct" or type_info == .@"union" or type_info == .@"enum") {
if (@hasDecl(T, "ziglua_toAny")) {
const fnInfo = @typeInfo(@TypeOf(T.ziglua_toAny)).@"fn";
axdank marked this conversation as resolved.
Show resolved Hide resolved
switch (fnInfo.params.len) {
axdank marked this conversation as resolved.
Show resolved Hide resolved
// fn(lua_state, alloc, allow_alloc, index) -> T
4 => {
if (@typeInfo(fnInfo.return_type.?) == .error_union) {
return try T.ziglua_toAny(lua, a, allow_alloc, index);
} else {
return T.ziglua_toAny(lua, a, allow_alloc, index);
}
},
else => @compileError(@typeName(T) ++ ".ziglua_toAny has invalid signature, required: fn(lua: *Lua, alloc: ?std.mem.Allocator, comptime allow_alloc: bool, index: i32) T"),
}
}
}

switch (type_info) {
.int => {
const result = try lua.toInteger(index);
return @as(T, @intCast(result));
Expand Down Expand Up @@ -4542,7 +4617,11 @@ pub const Lua = opaque {
return error.LuaInvalidEnumTagName;
},
.@"struct" => {
return try lua.toStruct(T, a, allow_alloc, index);
if (type_info.@"struct".is_tuple) {
return try lua.toTuple(T, a, allow_alloc, index);
} else {
return try lua.toStruct(T, a, allow_alloc, index);
}
},
.@"union" => |u| {
if (u.tag_type == null) @compileError("Parameter type is not a tagged union");
Expand Down Expand Up @@ -4608,6 +4687,49 @@ pub const Lua = opaque {
return result;
}

/// Converts value at given index to a zig struct tuple if possible
fn toTuple(lua: *Lua, comptime T: type, a: ?std.mem.Allocator, comptime allow_alloc: bool, raw_index: i32) !T {
const stack_size_on_entry = lua.getTop();
defer std.debug.assert(lua.getTop() == stack_size_on_entry);

const info = @typeInfo(T).@"struct";
const index = lua.absIndex(raw_index);

var result: T = undefined;

if (lua.isTable(index)) {
lua.pushValue(index);
defer lua.pop(1);

inline for (info.fields, 0..) |field, i| {
if (lua.getMetaField(-1, "__index")) |_| {
lua.pushValue(-2);
lua.pushInteger(@intCast(i + 1));
lua.call(.{ .args = 1, .results = 1 });
} else |_| {
_ = lua.rawGetIndex(-1, @intCast(i + 1));
}
defer lua.pop(1);
result[i] = try lua.toAnyInternal(field.type, a, allow_alloc, -1);
}
} else {
// taking it as vararg
const in_range = if (raw_index < 0) (index - @as(i32, info.fields.len)) >= 0 else ((index + @as(i32, info.fields.len)) - 1) <= stack_size_on_entry;
if (in_range) {
inline for (info.fields, 0..) |field, i| {
const stack_size_before_call = lua.getTop();
const idx = if (raw_index < 0) index - @as(i32, @intCast(i)) else index + @as(i32, @intCast(i));
result[i] = try lua.toAnyInternal(field.type, a, allow_alloc, idx);
std.debug.assert(stack_size_before_call == lua.getTop());
}
} else {
return error.NotInRange;
}
}

return result;
}

/// Converts value at given index to a zig struct if possible
fn toStruct(lua: *Lua, comptime T: type, a: ?std.mem.Allocator, comptime allow_alloc: bool, raw_index: i32) !T {
const stack_size_on_entry = lua.getTop();
Expand Down
128 changes: 128 additions & 0 deletions src/tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2382,6 +2382,91 @@ test "toAny struct" {
));
}

test "toAny tuple from vararg" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();

const Tuple = std.meta.Tuple(&.{ i32, bool, i32 });

lua.pushInteger(100);
lua.pushBoolean(true);
lua.pushInteger(300);

const result = try lua.toAny(Tuple, 1);
try testing.expect(std.meta.eql(result, .{ 100, true, 300 }));

const result_reverse = try lua.toAny(Tuple, -1);
try testing.expect(std.meta.eql(result_reverse, .{ 300, true, 100 }));

const result_error = lua.toAny(Tuple, 2);
try testing.expectError(error.NotInRange, result_error);

const result_reverse_error = lua.toAny(Tuple, -2);
try testing.expectError(error.NotInRange, result_reverse_error);
}

test "toAny tuple from struct" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();

const MyType = struct {
foo: i32,
bar: bool,
tuple: std.meta.Tuple(&.{ i32, bool, struct { foo: bool } }),
};

try lua.doString(
\\ value = {
\\ ["foo"] = 10,
\\ ["bar"] = false,
\\ ["tuple"] = {100, false, {["foo"] = true}}
\\ }
);

const lua_type = try lua.getGlobal("value");
try testing.expect(lua_type == .table);
const my_struct = try lua.toAny(MyType, 1);
try testing.expect(std.meta.eql(
my_struct,
MyType{ .foo = 10, .bar = false, .tuple = .{ 100, false, .{ .foo = true } } },
));
}

test "toAny from struct with custom toAny" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();

const MyType = struct {
foo: bool,
bar: struct {
const Self = @This();
foo: i32,

pub fn ziglua_toAny(l: *Lua, a: ?std.mem.Allocator, comptime aa: bool, i: i32) !Self {
return try ziglua.Internals.toStruct(l, Self, a, aa, i);
}
},
};

try lua.doString(
\\ value = {
\\ ["foo"] = true,
\\ ["bar"] = {
\\ ["foo"] = 12
\\ }
\\ }
);

const lua_type = try lua.getGlobal("value");
try testing.expect(lua_type == .table);
const my_struct = try lua.toAny(MyType, 1);
lua.pop(-1);
try testing.expect(std.meta.eql(
my_struct,
MyType{ .foo = true, .bar = .{ .foo = 12 } },
));
}

test "toAny mutable string" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();
Expand Down Expand Up @@ -2591,6 +2676,49 @@ test "pushAny struct" {
try testing.expect(value.bar == (MyType{}).bar);
}

test "pushAny tuple" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();

const Tuple = std.meta.Tuple(&.{ i32, bool, i32 });
const value: Tuple = .{ 500, false, 600 };

try lua.pushAny(value);

const result = try lua.toAny(Tuple, 1);
try testing.expect(std.meta.eql(result, .{ 500, false, 600 }));
}

test "pushAny from struct with custom pushAny" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();

const MyType = struct {
const Self = @This();
foo: i32,
tuple: std.meta.Tuple(&.{ i32, i32 }),

pub fn ziglua_pushAny(self: *const Self, l: *Lua) !void {
l.newTable();

inline for (@typeInfo(Self).@"struct".fields) |f| {
try l.pushAny(f.name);
try l.pushAny(@field(self, f.name));
l.setTable(-3);
}
}
};

const value: MyType = .{ .foo = 15, .tuple = .{ 1, 2 } };

try lua.pushAny(value);
const my_struct = try lua.toAny(MyType, 1);
try testing.expect(std.meta.eql(
my_struct,
MyType{ .foo = 15, .tuple = .{ 1, 2 } },
));
}

test "pushAny tagged union" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();
Expand Down
Loading