Skip to content

Fixing internalization of null slice and array fields #1303

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

Merged
merged 1 commit into from
May 6, 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
6 changes: 6 additions & 0 deletions compiler/prelude/jsmapping.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,9 @@ var $internalize = (v, t, recv, seen, makeWrapper) => {
case $kindFloat64:
return parseFloat(v);
case $kindArray:
if (v === null || v === undefined) {
$throwRuntimeError("cannot internalize "+v+" as a "+t.string);
}
if (v.length !== t.len) {
$throwRuntimeError("got array with wrong size from JavaScript native");
}
Expand Down Expand Up @@ -331,6 +334,9 @@ var $internalize = (v, t, recv, seen, makeWrapper) => {
return $internalize(v, t.elem, makeWrapper);
}
case $kindSlice:
if (v == null) {
return t.zero();
}
return new t($mapArray(v, e => { return $internalize(e, t.elem, makeWrapper); }));
case $kindString:
v = String(v);
Expand Down
39 changes: 39 additions & 0 deletions tests/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,45 @@ func TestExternalize(t *testing.T) {
}
}

func TestInternalizeSlice(t *testing.T) {
tests := []struct {
name string
init []int
want string
}{
{
name: `nil slice`,
init: []int(nil),
want: `[]int(nil)`,
},
{
name: `empty slice`,
init: []int{},
want: `[]int{}`,
},
{
name: `non-empty slice`,
init: []int{42, 53, 64},
want: `[]int{42, 53, 64}`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := struct {
*js.Object
V []int `js:"V"` // V is externalized
}{Object: js.Global.Get("Object").New()}
b.V = tt.init

result := fmt.Sprintf(`%#v`, b.V) // internalize b.V
if result != tt.want {
t.Errorf(`Unexpected result %q != %q`, result, tt.want)
}
})
}
}

func TestInternalizeExternalizeNull(t *testing.T) {
type S struct {
*js.Object
Expand Down
Loading