Skip to content

Invert reference type null checks #1719

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 6 commits into from
Mar 7, 2021
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
5 changes: 4 additions & 1 deletion src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9941,7 +9941,10 @@ export class Compiler extends DiagnosticEmitter {
case TypeKind.EQREF:
case TypeKind.DATAREF:
case TypeKind.I31REF: {
return module.ref_is(RefIsOp.RefIsNull, expr);
// Needs to be true (i.e. not zero) when the ref is _not_ null,
// which means `ref.is_null` returns false (i.e. zero).
return module.unary(UnaryOp.EqzI32, module.ref_is(RefIsOp.RefIsNull, expr));

}
default: {
assert(false);
Expand Down
6 changes: 6 additions & 0 deletions tests/compiler/features/reference-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ exports.preInstantiate = function(imports, exports) {
external: function(a) {
return a;
},
somethingReal() {
return {};
},
somethingNull() {
return null;
},
someObject: {
theKey: "Hello world!"
},
Expand Down
40 changes: 40 additions & 0 deletions tests/compiler/features/reference-types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// can use externref as a parameter or return type

export declare function external(a: externref): externref;
export declare function somethingReal(): externref;
export declare function somethingNull(): externref;

export function internal(a: externref): externref {
const b = external(a);
Expand All @@ -26,6 +28,44 @@ console.log(someObject);
console.log(someKey);
console.log(Reflect.get(someObject, someKey));

// Truthiness conversion
if(!somethingReal()) {
assert(false);
}
if(!somethingNull()) {
// nop
} else {
assert(false);
}
if(somethingReal()) {
// nop
} else {
assert(false);
}
if(somethingNull()) {
assert(false);
}

// Explicit null checks (don’t work yet)
/*
if(somethingReal() !== null) {
// nop
} else {
assert(false);
}
if(somethingReal() === null) {
assert(false);
}
if(somethingNull() === null) {
// nop
} else {
assert(false);
}
if(somethingNull() !== null) {
assert(false);
}
*/

// can represent and recognize 'null'

var funcGlobal: funcref;
Expand Down
Loading