Skip to content

Handle instanceof of entire classes #1108

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
Feb 14, 2020
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: 5 additions & 0 deletions src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1094,6 +1094,11 @@ export class NamedTypeNode extends TypeNode {
name: TypeName;
/** Type argument references. */
typeArguments: TypeNode[] | null;

get hasTypeArguments(): bool {
var typeArguments = this.typeArguments;
return typeArguments !== null && typeArguments.length > 0;
}
}

/** Represents a function type. */
Expand Down
54 changes: 53 additions & 1 deletion src/builtins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import {
Global,
DecoratorFlags,
Element,
Class
ClassPrototype
} from "./program";

import {
Expand Down Expand Up @@ -4971,6 +4971,58 @@ export function compileRTTI(compiler: Compiler): void {
}
}

/** Compiles a class-specific instanceof helper, checking a ref against all concrete instances. */
export function compileClassInstanceOf(compiler: Compiler, prototype: ClassPrototype): void {
var module = compiler.module;
var nativeSizeType = compiler.options.nativeSizeType;
var instanceofInstance = assert(prototype.program.instanceofInstance);
compiler.compileFunction(instanceofInstance);

var stmts = new Array<ExpressionRef>();

// if (!ref) return false
stmts.push(
module.if(
module.unary(
nativeSizeType == NativeType.I64
? UnaryOp.EqzI64
: UnaryOp.EqzI32,
module.local_get(0, nativeSizeType)
),
module.return(
module.i32(0)
)
)
);

// if (__instanceof(ref, ID[i])) return true
var instances = prototype.instances;
if (instances !== null && instances.size) {
for (let instance of instances.values()) {
stmts.push(
module.if(
module.call(instanceofInstance.internalName, [
module.local_get(0, nativeSizeType),
module.i32(instance.id)
], NativeType.I32),
module.return(
module.i32(1)
)
)
);
}
}

// return false
stmts.push(
module.return(
module.i32(0)
)
);

module.addFunction(prototype.internalName + "~instanceof", nativeSizeType, NativeType.I32, null, module.flatten(stmts));
}

// Helpers

/** Evaluates the constant type of a type argument *or* expression. */
Expand Down
94 changes: 86 additions & 8 deletions src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
compileVisitGlobals,
compileVisitMembers,
compileRTTI,
compileClassInstanceOf,
} from "./builtins";

import {
Expand Down Expand Up @@ -160,6 +161,8 @@ import {
UnaryPostfixExpression,
UnaryPrefixExpression,

NamedTypeNode,

nodeIsConstantValue,
findDecorator,
isTypeOmitted
Expand Down Expand Up @@ -335,6 +338,8 @@ export class Compiler extends DiagnosticEmitter {
inlineStack: Function[] = [];
/** Lazily compiled library functions. */
lazyLibraryFunctions: Set<Function> = new Set();
/** Pending class-specific instanceof helpers. */
pendingClassInstanceOf: Set<ClassPrototype> = new Set();

/** Compiles a {@link Program} to a {@link Module} using the specified options. */
static compile(program: Program): Module {
Expand Down Expand Up @@ -455,6 +460,11 @@ export class Compiler extends DiagnosticEmitter {
}
} while (lazyLibraryFunctions.size);

// compile pending class-specific instanceof helpers
for (let prototype of this.pendingClassInstanceOf.values()) {
compileClassInstanceOf(this, prototype);
}

// finalize runtime features
module.removeGlobal(BuiltinNames.rtti_base);
if (this.runtimeFeatures & RuntimeFeatures.RTTI) compileRTTI(this);
Expand Down Expand Up @@ -7666,21 +7676,42 @@ export class Compiler extends DiagnosticEmitter {
contextualType: Type,
constraints: Constraints
): ExpressionRef {
var module = this.module;
// NOTE that this differs from TypeScript in that the rhs is a type, not an expression. at the
// time of implementation, this seemed more useful because dynamic rhs expressions are not
// possible in AS anyway. also note that the code generated below must preserve side-effects of
// the LHS expression even when the result is a constant, i.e. return a block dropping `expr`.
var flow = this.currentFlow;
var expr = this.compileExpression(expression.expression, this.options.usizeType);
var actualType = this.currentType;
var isType = expression.isType;

// Mimic `instanceof CLASS`
if (isType.kind == NodeKind.NAMEDTYPE) {
let namedType = <NamedTypeNode>isType;
if (!(namedType.isNullable || namedType.hasTypeArguments)) {
let element = this.resolver.resolveTypeName(namedType.name, flow.actualFunction, ReportMode.SWALLOW);
if (element !== null && element.kind == ElementKind.CLASS_PROTOTYPE) {
let prototype = <ClassPrototype>element;
if (prototype.is(CommonFlags.GENERIC)) {
return this.makeInstanceofClass(expression, prototype);
}
}
}
}

// Fall back to `instanceof TYPE`
var expectedType = this.resolver.resolveType(
expression.isType,
flow.actualFunction,
makeMap(flow.contextualTypeArguments)
);
if (!expectedType) {
this.currentType = Type.bool;
return this.module.unreachable();
}
return this.makeInstanceofType(expression, expectedType);
}

private makeInstanceofType(expression: InstanceOfExpression, expectedType: Type): ExpressionRef {
var module = this.module;
var flow = this.currentFlow;
var expr = this.compileExpression(expression.expression, expectedType);
var actualType = this.currentType;
this.currentType = Type.bool;
if (!expectedType) return module.unreachable();

// instanceof <basic> - must be exact
if (!expectedType.is(TypeFlags.REFERENCE)) {
Expand Down Expand Up @@ -7802,6 +7833,53 @@ export class Compiler extends DiagnosticEmitter {
], NativeType.I32);
}

private makeInstanceofClass(expression: InstanceOfExpression, prototype: ClassPrototype): ExpressionRef {
var module = this.module;
var expr = this.compileExpression(expression.expression, Type.auto);
var actualType = this.currentType;
var nativeSizeType = actualType.toNativeType();

this.currentType = Type.bool;

// exclusively interested in class references here
var classReference = actualType.classReference;
if (actualType.is(TypeFlags.REFERENCE) && classReference !== null) {

// static check
if (classReference.extends(prototype)) {

// <nullable> instanceof <PROTOTYPE> - LHS must be != 0
if (actualType.is(TypeFlags.NULLABLE)) {
return module.binary(
nativeSizeType == NativeType.I64
? BinaryOp.NeI64
: BinaryOp.NeI32,
expr,
this.makeZero(actualType)
);

// <nonNullable> is just `true`
} else {
return module.block(null, [
module.drop(expr),
module.i32(1)
], NativeType.I32);
}

// dynamic check against all possible concrete ids
} else if (prototype.extends(classReference.prototype)) {
this.pendingClassInstanceOf.add(prototype);
return module.call(prototype.internalName + "~instanceof", [ expr ], NativeType.I32);
}
}

// false
return module.block(null, [
module.drop(expr),
module.i32(0)
], NativeType.I32);
}

private compileLiteralExpression(
expression: LiteralExpression,
contextualType: Type,
Expand Down
5 changes: 5 additions & 0 deletions tests/compiler/instanceof-class.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"asc_flags": [
"--runtime none"
]
}
Loading