Skip to content

Commit

Permalink
Merge pull request #184 from lightpanda-io/nested
Browse files Browse the repository at this point in the history
Improve nested types
  • Loading branch information
francisbouvier authored Jan 18, 2024
2 parents 8da4cc6 + a9aa7db commit 1efc618
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
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

0 comments on commit 1efc618

Please sign in to comment.