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

Improve nested types #184

Merged
merged 2 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 13 additions & 3 deletions src/engines/v8/types_primitives.zig
Original file line number Diff line number Diff line change
Expand Up @@ -166,19 +166,29 @@ pub fn jsToObject(
isolate: v8.Isolate,
ctx: v8.Context,
) !T {
const info = @typeInfo(T);

// JS Null or Undefined value
if (js_val.isNull() or js_val.isUndefined()) {
// if Native optional type return null
if (comptime info == .Optional) {
return null;
}
}

// check it's a JS object
if (!js_val.isObject()) {
return error.JSNotObject;
}

// unwrap Optional
const info = @typeInfo(T);
if (comptime info == .Optional) {
return try jsToObject(alloc, nested_T, info.Optional.child, js_val, isolate, ctx);
}

const js_obj = js_val.castTo(v8.Object);
var obj: T = undefined;
inline for (nested_T.fields) |field| {
inline for (nested_T.fields, 0..) |field, i| {
const name = field.name.?;
const key = v8.String.initUtf8(isolate, name);
if (js_obj.has(ctx, key.toValue())) {
Expand All @@ -188,7 +198,7 @@ pub fn jsToObject(
} else {
if (comptime field.underOpt() != null) {
@field(obj, name) = null;
} else {
} else if (comptime !refl.hasDefaultValue(nested_T.T, i)) {
return error.JSWrongObject;
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/reflect.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1656,6 +1656,11 @@ pub fn postAttachFunc(comptime T: type) !?type {
return argsT(func);
}

pub fn hasDefaultValue(comptime T: type, comptime index: usize) bool {
std.debug.assert(@inComptime());
return @typeInfo(T).Struct.fields[index].default_value != null;
}

// Utils funcs
// -----------

Expand Down