assemblyscript/src/compiler.ts

5228 lines
172 KiB
TypeScript
Raw Normal View History

import {
2017-12-24 03:19:47 +01:00
compileCall as compileBuiltinCall,
compileGetConstant as compileBuiltinGetConstant,
compileAllocate as compileBuiltinAllocate
2017-12-24 03:19:47 +01:00
} from "./builtins";
2017-12-24 03:19:47 +01:00
import {
DiagnosticCode,
DiagnosticEmitter
} from "./diagnostics";
import {
Module,
MemorySegment,
ExpressionRef,
UnaryOp,
BinaryOp,
NativeType,
FunctionRef,
2018-02-25 00:13:39 +01:00
ExpressionId
} from "./module";
2017-12-24 03:19:47 +01:00
import {
Program,
ClassPrototype,
2017-12-24 03:19:47 +01:00
Class,
Element,
ElementKind,
Enum,
Field,
FunctionPrototype,
Function,
Global,
Local,
Namespace,
EnumValue,
Property,
VariableLikeElement,
FlowFlags,
ElementFlags,
ConstantValueKind,
2018-02-25 00:13:39 +01:00
Parameter,
PATH_DELIMITER,
LIBRARY_PREFIX
} from "./program";
2017-12-24 03:19:47 +01:00
2017-09-28 13:08:25 +02:00
import {
2017-12-24 03:19:47 +01:00
Token
} from "./tokenizer";
2017-09-28 13:08:25 +02:00
2017-12-24 03:19:47 +01:00
import {
2017-10-07 14:29:43 +02:00
Node,
2017-09-28 13:08:25 +02:00
NodeKind,
TypeNode,
2017-10-02 12:52:15 +02:00
Source,
Range,
Statement,
2017-09-28 13:08:25 +02:00
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DoStatement,
EmptyStatement,
EnumDeclaration,
2017-10-02 12:52:15 +02:00
ExportStatement,
2017-09-28 13:08:25 +02:00
ExpressionStatement,
FunctionDeclaration,
ForStatement,
IfStatement,
ImportStatement,
2017-12-18 03:46:36 +01:00
InterfaceDeclaration,
2017-09-28 13:08:25 +02:00
ModifierKind,
NamespaceDeclaration,
ReturnStatement,
SwitchStatement,
ThrowStatement,
TryStatement,
VariableDeclaration,
VariableStatement,
WhileStatement,
Expression,
2017-09-28 13:08:25 +02:00
AssertionExpression,
BinaryExpression,
CallExpression,
2018-01-05 01:55:59 +01:00
CommaExpression,
2017-09-28 13:08:25 +02:00
ElementAccessExpression,
FloatLiteralExpression,
FunctionExpression,
2017-09-28 13:08:25 +02:00
IdentifierExpression,
IntegerLiteralExpression,
LiteralExpression,
LiteralKind,
NewExpression,
ParenthesizedExpression,
PropertyAccessExpression,
TernaryExpression,
2018-01-29 07:42:40 +01:00
ArrayLiteralExpression,
2017-09-28 13:08:25 +02:00
StringLiteralExpression,
UnaryPostfixExpression,
UnaryPrefixExpression,
2017-12-18 03:46:36 +01:00
hasModifier
2017-09-28 13:08:25 +02:00
} from "./ast";
2017-12-24 03:19:47 +01:00
import {
2017-09-28 13:08:25 +02:00
Type,
2017-10-07 14:29:43 +02:00
TypeKind,
TypeFlags,
2017-12-24 03:19:47 +01:00
typesToNativeTypes
2017-10-02 12:52:15 +02:00
} from "./types";
2017-12-24 03:19:47 +01:00
2017-12-14 11:55:35 +01:00
/** Compilation target. */
2017-09-28 13:08:25 +02:00
export enum Target {
/** WebAssembly with 32-bit pointers. */
2017-09-28 13:08:25 +02:00
WASM32,
2017-11-26 04:03:28 +01:00
/** WebAssembly with 64-bit pointers. Experimental and not supported by any runtime yet. */
2017-09-28 13:08:25 +02:00
WASM64
}
2017-12-14 11:55:35 +01:00
/** Compiler options. */
2017-09-28 13:08:25 +02:00
export class Options {
2018-01-21 17:52:44 +01:00
/** WebAssembly target. Defaults to {@link Target.WASM32}. */
2017-09-28 13:08:25 +02:00
target: Target = Target.WASM32;
/** If true, compiles everything instead of just reachable code. */
noTreeShaking: bool = false;
2017-12-04 02:00:48 +01:00
/** If true, replaces assertions with nops. */
2017-12-13 23:24:13 +01:00
noAssert: bool = false;
/** If true, does not set up a memory. */
noMemory: bool = false;
/** If true, imports the memory provided by the embedder. */
importMemory: bool = false;
/** Static memory start offset. */
memoryBase: u32 = 0;
/** Memory allocation implementation to use. */
allocateImpl: string = "allocate_memory";
/** Memory freeing implementation to use. */
freeImpl: string = "free_memory";
/** If true, generates information necessary for source maps. */
sourceMap: bool = false;
2018-01-21 17:52:44 +01:00
/** Tests if the target is WASM64 or, otherwise, WASM32. */
2018-02-25 00:13:39 +01:00
get isWasm64(): bool {
return this.target == Target.WASM64;
}
2018-01-21 17:52:44 +01:00
/** Gets the unsigned size type matching the target. */
2018-02-25 00:13:39 +01:00
get usizeType(): Type {
return this.target == Target.WASM64 ? Type.usize64 : Type.usize32;
}
2018-01-21 17:52:44 +01:00
/** Gets the signed size type matching the target. */
2018-02-25 00:13:39 +01:00
get isizeType(): Type {
return this.target == Target.WASM64 ? Type.isize64 : Type.isize32;
}
2018-01-21 17:52:44 +01:00
/** Gets the native size type matching the target. */
2018-02-25 00:13:39 +01:00
get nativeSizeType(): NativeType {
return this.target == Target.WASM64 ? NativeType.I64 : NativeType.I32;
}
2017-09-28 13:08:25 +02:00
}
2017-12-14 11:55:35 +01:00
/** Indicates the desired kind of a conversion. */
2017-12-15 17:23:04 +01:00
export const enum ConversionKind {
/** No conversion. */
NONE,
/** Implicit conversion. */
IMPLICIT,
/** Explicit conversion. */
EXPLICIT
}
2017-12-14 11:55:35 +01:00
/** Compiler interface. */
2017-09-28 13:08:25 +02:00
export class Compiler extends DiagnosticEmitter {
2017-11-26 04:03:28 +01:00
/** Program reference. */
2017-09-28 13:08:25 +02:00
program: Program;
2017-11-26 04:03:28 +01:00
/** Provided options. */
2017-09-28 13:08:25 +02:00
options: Options;
2017-11-26 04:03:28 +01:00
/** Module instance being compiled. */
2017-09-28 13:08:25 +02:00
module: Module;
2017-11-26 04:03:28 +01:00
/** Start function being compiled. */
2017-11-17 14:33:51 +01:00
startFunction: Function;
/** Start function statements. */
2017-11-26 04:03:28 +01:00
startFunctionBody: ExpressionRef[] = new Array();
2017-10-02 12:52:15 +02:00
2017-11-26 04:03:28 +01:00
/** Current function in compilation. */
2017-11-17 14:33:51 +01:00
currentFunction: Function;
2018-01-24 03:08:09 +01:00
/** Current enum in compilation. */
currentEnum: Enum | null = null;
/** Current type in compilation. */
currentType: Type = Type.void;
2017-09-28 13:08:25 +02:00
2017-11-26 04:03:28 +01:00
/** Counting memory offset. */
memoryOffset: I64;
2017-11-26 04:03:28 +01:00
/** Memory segments being compiled. */
2017-09-28 13:08:25 +02:00
memorySegments: MemorySegment[] = new Array();
/** Map of already compiled static string segments. */
stringSegments: Map<string,MemorySegment> = new Map();
2017-09-28 13:08:25 +02:00
/** Function table being compiled. */
functionTable: Function[] = new Array();
2017-11-26 04:03:28 +01:00
/** Already processed file names. */
files: Set<string> = new Set();
2017-11-26 04:03:28 +01:00
/** Compiles a {@link Program} to a {@link Module} using the specified options. */
2017-09-28 13:08:25 +02:00
static compile(program: Program, options: Options | null = null): Module {
return new Compiler(program, options).compile();
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
/** Constructs a new compiler for a {@link Program} using the specified options. */
2017-09-28 13:08:25 +02:00
constructor(program: Program, options: Options | null = null) {
super(program.diagnostics);
this.program = program;
this.options = options ? options : new Options();
2018-02-25 00:13:39 +01:00
this.memoryOffset = i64_new(
max(this.options.memoryBase, this.options.usizeType.byteSize) // leave space for `null`
);
this.module = Module.create();
}
2017-09-28 13:08:25 +02:00
2017-11-26 04:03:28 +01:00
/** Performs compilation of the underlying {@link Program} to a {@link Module}. */
2017-09-28 13:08:25 +02:00
compile(): Module {
2017-12-05 13:35:14 +01:00
// initialize lookup maps, built-ins, imports, exports, etc.
2018-01-21 17:52:44 +01:00
this.program.initialize(this.options);
2017-09-28 13:08:25 +02:00
// set up the start function wrapping top-level statements, of all files.
var startFunctionPrototype = assert(this.program.elements.get("start"));
assert(startFunctionPrototype.kind == ElementKind.FUNCTION_PROTOTYPE);
2018-02-25 00:13:39 +01:00
var startFunctionInstance = new Function(
<FunctionPrototype>startFunctionPrototype,
startFunctionPrototype.internalName,
null, // not generic
null, // no parameters
Type.void
);
startFunctionInstance.set(ElementFlags.START);
this.currentFunction = this.startFunction = startFunctionInstance;
var sources = this.program.sources;
// compile entry file(s) while traversing to reachable elements
2018-02-25 00:13:39 +01:00
for (var i = 0, k = sources.length; i < k; ++i) {
if (sources[i].isEntry) {
this.compileSource(sources[i]);
}
}
// compile the start function if not empty
if (this.startFunctionBody.length) {
var typeRef = this.module.getFunctionTypeBySignature(NativeType.None, []);
if (!typeRef) typeRef = this.module.addFunctionType("v", NativeType.None, []);
var ref: FunctionRef;
this.module.setStart(
2018-02-25 00:13:39 +01:00
ref = this.module.addFunction(
this.startFunction.prototype.internalName,
typeRef,
typesToNativeTypes(this.startFunction.additionalLocals),
2017-12-23 17:49:06 +01:00
this.module.createBlock(null, this.startFunctionBody)
)
);
this.startFunction.finalize(this.module, ref);
}
// set up static memory segments and the heap base pointer
if (!this.options.noMemory) {
var memoryOffset = this.memoryOffset;
2018-02-25 00:13:39 +01:00
memoryOffset = i64_align(memoryOffset, this.options.usizeType.byteSize);
this.memoryOffset = memoryOffset;
if (this.options.isWasm64) {
this.module.addGlobal(
"HEAP_BASE",
NativeType.I64,
false,
this.module.createI64(i64_low(memoryOffset), i64_high(memoryOffset))
);
} else {
this.module.addGlobal(
"HEAP_BASE",
NativeType.I32,
false,
this.module.createI32(i64_low(memoryOffset))
);
}
// determine initial page size
var pages = i64_shr_u(i64_align(memoryOffset, 0x10000), i64_new(16, 0));
2018-02-25 00:13:39 +01:00
this.module.setMemory(
i64_low(pages),
Module.MAX_MEMORY_WASM32 /* TODO: not WASM64 compatible yet */,
this.memorySegments,
this.options.target,
"memory"
);
}
// import memory if requested
if (this.options.importMemory) {
2018-03-02 12:57:33 +01:00
this.module.addMemoryImport("0", "env", "memory");
}
// set up function table
if (k = this.functionTable.length) {
var entries = new Array<FunctionRef>(k);
for (i = 0; i < k; ++i) {
entries[i] = this.functionTable[i].ref;
}
this.module.setFunctionTable(entries);
}
return this.module;
}
// sources
compileSourceByPath(normalizedPathWithoutExtension: string, reportNode: Node): void {
var sources = this.program.sources;
2018-02-25 00:13:39 +01:00
var source: Source;
var expected = normalizedPathWithoutExtension + ".ts";
for (var i = 0, k = sources.length; i < k; ++i) {
2018-02-25 00:13:39 +01:00
source = sources[i];
if (source.normalizedPath == expected) {
this.compileSource(source);
return;
}
}
expected = normalizedPathWithoutExtension + "/index.ts";
2018-02-25 00:13:39 +01:00
for (i = 0, k = sources.length; i < k; ++i) {
source = sources[i];
if (source.normalizedPath == expected) {
this.compileSource(source);
return;
}
}
expected = LIBRARY_PREFIX + normalizedPathWithoutExtension + ".ts";
2018-02-25 00:13:39 +01:00
for (i = 0, k = sources.length; i < k; ++i) {
source = sources[i];
if (source.normalizedPath == expected) {
this.compileSource(source);
return;
}
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.File_0_not_found,
reportNode.range, normalizedPathWithoutExtension
);
}
compileSource(source: Source): void {
var files = this.files;
2018-02-25 00:13:39 +01:00
if (files.has(source.normalizedPath)) return;
files.add(source.normalizedPath);
var noTreeShaking = this.options.noTreeShaking;
var isEntry = source.isEntry;
var startFunctionBody = this.startFunctionBody;
var statements = source.statements;
for (var i = 0, k = statements.length; i < k; ++i) {
var statement = statements[i];
2017-09-28 13:08:25 +02:00
switch (statement.kind) {
case NodeKind.CLASSDECLARATION:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking ||
(isEntry && hasModifier(ModifierKind.EXPORT, (<ClassDeclaration>statement).modifiers))
) &&
!(<ClassDeclaration>statement).typeParameters.length
) {
this.compileClassDeclaration(<ClassDeclaration>statement, []);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
break;
case NodeKind.ENUMDECLARATION:
2018-02-25 00:13:39 +01:00
if (
noTreeShaking ||
(isEntry && hasModifier(ModifierKind.EXPORT, (<EnumDeclaration>statement).modifiers))
) {
this.compileEnumDeclaration(<EnumDeclaration>statement);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
break;
case NodeKind.FUNCTIONDECLARATION:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking ||
(isEntry && hasModifier(ModifierKind.EXPORT, (<FunctionDeclaration>statement).modifiers))
) &&
!(<FunctionDeclaration>statement).isGeneric
2018-02-25 00:13:39 +01:00
) {
this.compileFunctionDeclaration(<FunctionDeclaration>statement, []);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
break;
case NodeKind.IMPORT:
2018-02-25 00:13:39 +01:00
this.compileSourceByPath(
(<ImportStatement>statement).normalizedPath,
(<ImportStatement>statement).path
);
break;
case NodeKind.NAMESPACEDECLARATION:
2018-02-25 00:13:39 +01:00
if (
noTreeShaking ||
(isEntry && hasModifier(ModifierKind.EXPORT, (<NamespaceDeclaration>statement).modifiers))
) {
this.compileNamespaceDeclaration(<NamespaceDeclaration>statement);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
break;
2018-02-25 00:13:39 +01:00
case NodeKind.VARIABLE: // global, always compiled as initializers might have side effects
var variableInit = this.compileVariableStatement(<VariableStatement>statement);
if (variableInit) startFunctionBody.push(variableInit);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.EXPORT:
2018-02-25 00:13:39 +01:00
if ((<ExportStatement>statement).normalizedPath != null) {
this.compileSourceByPath(
<string>(<ExportStatement>statement).normalizedPath,
<StringLiteralExpression>(<ExportStatement>statement).path
);
}
if (noTreeShaking || isEntry) {
this.compileExportStatement(<ExportStatement>statement);
2018-02-25 00:13:39 +01:00
}
break;
// otherwise a top-level statement that is part of the start function's body
default:
var previousFunction = this.currentFunction;
2017-10-02 12:52:15 +02:00
this.currentFunction = this.startFunction;
var expr = this.compileStatement(statement);
this.startFunctionBody.push(expr);
2017-10-02 12:52:15 +02:00
this.currentFunction = previousFunction;
2017-09-28 13:08:25 +02:00
break;
}
}
}
2017-09-28 13:08:25 +02:00
// globals
2017-09-28 13:08:25 +02:00
compileGlobalDeclaration(declaration: VariableDeclaration): Global | null {
var element = this.program.elements.get(declaration.fileLevelInternalName);
2018-02-25 00:13:39 +01:00
if (!element || element.kind != ElementKind.GLOBAL) {
2017-12-23 17:49:06 +01:00
throw new Error("global expected");
2018-02-25 00:13:39 +01:00
}
if (!this.compileGlobal(<Global>element)) { // reports
return null;
2018-02-25 00:13:39 +01:00
}
return <Global>element;
2017-09-28 13:08:25 +02:00
}
2017-12-13 04:46:05 +01:00
compileGlobal(global: Global): bool {
2018-02-25 00:13:39 +01:00
if (global.is(ElementFlags.COMPILED) || global.is(ElementFlags.BUILTIN)) {
2017-12-23 13:48:04 +01:00
return true;
2018-02-25 00:13:39 +01:00
}
2017-12-16 02:27:39 +01:00
var declaration = global.declaration;
var initExpr: ExpressionRef = 0;
if (global.type == Type.void) { // infer type
if (declaration.type) {
var resolvedType = this.program.resolveType(declaration.type); // reports
2018-02-25 00:13:39 +01:00
if (!resolvedType) return false;
if (resolvedType == Type.void) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Type_0_is_not_assignable_to_type_1,
declaration.type.range, "*", resolvedType.toString()
);
2017-12-23 13:48:04 +01:00
return false;
2017-12-23 17:49:06 +01:00
}
global.type = resolvedType;
2018-02-25 00:13:39 +01:00
} else if (declaration.initializer) { // infer type using void/NONE for literal inference
initExpr = this.compileExpression( // reports
declaration.initializer,
Type.void,
ConversionKind.NONE
);
if (this.currentType == Type.void) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Type_0_is_not_assignable_to_type_1,
declaration.initializer.range, this.currentType.toString(), "<auto>"
);
return false;
}
global.type = this.currentType;
} else {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Type_expected,
declaration.name.range.atEnd
);
return false;
}
}
2017-12-23 17:49:06 +01:00
var nativeType = global.type.toNativeType();
2017-12-27 22:38:32 +01:00
if (global.is(ElementFlags.DECLARED)) {
if (global.is(ElementFlags.CONSTANT)) {
2018-02-25 00:13:39 +01:00
this.module.addGlobalImport(
global.internalName,
global.namespace
? global.namespace.simpleName
: "env",
global.simpleName,
nativeType
);
global.set(ElementFlags.COMPILED);
2017-12-27 22:38:32 +01:00
return true;
2018-02-25 00:13:39 +01:00
} else {
this.error(
DiagnosticCode.Operation_not_supported,
declaration.range
);
}
2017-12-27 22:38:32 +01:00
return false;
}
var initializeInStart = false;
2017-12-23 17:49:06 +01:00
if (global.is(ElementFlags.INLINED)) {
initExpr = this.compileInlineConstant(global, global.type, true);
} else {
if (declaration.initializer) {
2018-02-25 00:13:39 +01:00
if (!initExpr) {
2017-12-23 17:49:06 +01:00
initExpr = this.compileExpression(declaration.initializer, global.type);
2018-02-25 00:13:39 +01:00
}
if (_BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
if (global.is(ElementFlags.CONSTANT)) {
2017-12-23 17:49:06 +01:00
initExpr = this.precomputeExpressionRef(initExpr);
if (_BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
2018-02-25 00:13:39 +01:00
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
declaration.range
);
initializeInStart = true;
}
2018-02-25 00:13:39 +01:00
} else {
initializeInStart = true;
2018-02-25 00:13:39 +01:00
}
}
2018-02-25 00:13:39 +01:00
} else {
2017-12-24 03:19:47 +01:00
initExpr = global.type.toNativeZero(this.module);
2018-02-25 00:13:39 +01:00
}
}
2017-12-16 02:27:39 +01:00
var internalName = global.internalName;
2017-10-07 14:29:43 +02:00
if (initializeInStart) {
2017-12-24 03:19:47 +01:00
this.module.addGlobal(internalName, nativeType, true, global.type.toNativeZero(this.module));
var setExpr = this.module.createSetGlobal(internalName, initExpr);
this.startFunctionBody.push(setExpr);
} else {
if (global.is(ElementFlags.CONSTANT)) {
var exprType = _BinaryenExpressionGetType(initExpr);
switch (exprType) {
case NativeType.I32:
global.constantValueKind = ConstantValueKind.INTEGER;
global.constantIntegerValue = i64_new(_BinaryenConstGetValueI32(initExpr), 0);
break;
case NativeType.I64:
global.constantValueKind = ConstantValueKind.INTEGER;
2018-02-25 00:13:39 +01:00
global.constantIntegerValue = i64_new(
_BinaryenConstGetValueI64Low(initExpr),
_BinaryenConstGetValueI64High(initExpr)
);
break;
case NativeType.F32:
global.constantValueKind = ConstantValueKind.FLOAT;
global.constantFloatValue = _BinaryenConstGetValueF32(initExpr);
break;
case NativeType.F64:
global.constantValueKind = ConstantValueKind.FLOAT;
global.constantFloatValue = _BinaryenConstGetValueF64(initExpr);
break;
default:
throw new Error("concrete type expected");
}
global.set(ElementFlags.INLINED);
2018-02-25 00:13:39 +01:00
if (declaration.isTopLevel) { // might be re-exported
this.module.addGlobal(internalName, nativeType, !global.is(ElementFlags.CONSTANT), initExpr);
2018-02-25 00:13:39 +01:00
}
if (declaration.range.source.isEntry && declaration.isTopLevelExport) {
this.module.addGlobalExport(global.internalName, declaration.programLevelInternalName);
2018-02-25 00:13:39 +01:00
}
} else {
this.module.addGlobal(internalName, nativeType, !global.is(ElementFlags.CONSTANT), initExpr);
2018-02-25 00:13:39 +01:00
}
}
global.set(ElementFlags.COMPILED);
2017-12-13 04:46:05 +01:00
return true;
2017-09-28 13:08:25 +02:00
}
// enums
compileEnumDeclaration(declaration: EnumDeclaration): Enum | null {
var element = this.program.elements.get(declaration.fileLevelInternalName);
2018-02-25 00:13:39 +01:00
if (!element || element.kind != ElementKind.ENUM) throw new Error("enum expected");
return this.compileEnum(<Enum>element) ? <Enum>element : null;
2017-10-07 14:29:43 +02:00
}
compileEnum(element: Enum): bool {
2018-02-25 00:13:39 +01:00
if (element.is(ElementFlags.COMPILED)) return true;
2017-12-23 17:49:06 +01:00
// members might reference each other, triggering another compile
element.set(ElementFlags.COMPILED);
2018-01-24 03:08:09 +01:00
this.currentEnum = element;
var previousValue: EnumValue | null = null;
2018-02-25 00:13:39 +01:00
if (element.members) {
for (var member of element.members.values()) {
2018-02-25 00:13:39 +01:00
if (member.kind != ElementKind.ENUMVALUE) continue; // happens if an enum is also a namespace
var initInStart = false;
var val = <EnumValue>member;
var valueDeclaration = val.declaration;
2018-01-24 03:08:09 +01:00
val.set(ElementFlags.COMPILED);
if (val.is(ElementFlags.INLINED)) {
2018-02-25 00:13:39 +01:00
if (element.declaration.isTopLevelExport) {
this.module.addGlobal(
val.internalName,
NativeType.I32,
false, // constant
this.module.createI32(val.constantValue)
);
}
} else {
var initExpr: ExpressionRef;
if (valueDeclaration.value) {
initExpr = this.compileExpression(<Expression>valueDeclaration.value, Type.i32);
if (_BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
2017-12-23 17:49:06 +01:00
initExpr = this.precomputeExpressionRef(initExpr);
if (_BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
2018-02-25 00:13:39 +01:00
if (element.is(ElementFlags.CONSTANT)) {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
valueDeclaration.range
);
}
2017-12-23 17:49:06 +01:00
initInStart = true;
}
}
} else if (previousValue == null) {
2017-12-23 17:49:06 +01:00
initExpr = this.module.createI32(0);
} else if (previousValue.is(ElementFlags.INLINED)) {
2017-12-23 17:49:06 +01:00
initExpr = this.module.createI32(previousValue.constantValue + 1);
} else {
// in TypeScript this errors with TS1061, but actually we can do:
2017-12-23 17:49:06 +01:00
initExpr = this.module.createBinary(BinaryOp.AddI32,
this.module.createGetGlobal(previousValue.internalName, NativeType.I32),
this.module.createI32(1)
);
2018-02-25 00:13:39 +01:00
if (element.is(ElementFlags.CONSTANT)) {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
valueDeclaration.range
);
}
2017-12-23 17:49:06 +01:00
initInStart = true;
}
2017-12-23 17:49:06 +01:00
if (initInStart) {
2018-02-25 00:13:39 +01:00
this.module.addGlobal(
val.internalName,
NativeType.I32,
true, // mutable
this.module.createI32(0)
);
var setExpr = this.module.createSetGlobal(val.internalName, initExpr);
this.startFunctionBody.push(setExpr);
} else {
2017-12-23 17:49:06 +01:00
this.module.addGlobal(val.internalName, NativeType.I32, false, initExpr);
if (_BinaryenExpressionGetType(initExpr) == NativeType.I32) {
val.constantValue = _BinaryenConstGetValueI32(initExpr);
val.set(ElementFlags.INLINED);
2018-02-25 00:13:39 +01:00
} else {
throw new Error("i32 expected");
2018-02-25 00:13:39 +01:00
}
}
}
previousValue = <EnumValue>val;
// export values if the enum is exported
if (element.declaration.range.source.isEntry && element.declaration.isTopLevelExport) {
2018-02-25 00:13:39 +01:00
if (member.is(ElementFlags.INLINED)) {
this.module.addGlobalExport(member.internalName, member.internalName);
2018-02-25 00:13:39 +01:00
} else if (valueDeclaration) {
this.warning(
DiagnosticCode.Cannot_export_a_mutable_global,
valueDeclaration.range
);
}
}
}
2018-02-25 00:13:39 +01:00
}
2018-01-24 03:08:09 +01:00
this.currentEnum = null;
return true;
}
2017-10-07 14:29:43 +02:00
// functions
2017-10-07 14:29:43 +02:00
2018-02-25 00:13:39 +01:00
compileFunctionDeclaration(
declaration: FunctionDeclaration,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null = null
): Function | null {
var element = this.program.elements.get(declaration.fileLevelInternalName);
2018-02-25 00:13:39 +01:00
if (!element || element.kind != ElementKind.FUNCTION_PROTOTYPE) {
throw new Error("function expected");
2018-02-25 00:13:39 +01:00
}
return this.compileFunctionUsingTypeArguments( // reports
<FunctionPrototype>element,
typeArguments,
contextualTypeArguments,
(<FunctionPrototype>element).declaration.name
);
2017-11-20 23:39:50 +01:00
}
2018-02-25 00:13:39 +01:00
compileFunctionUsingTypeArguments(
prototype: FunctionPrototype,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null,
reportNode: Node
): Function | null {
var instance = prototype.resolveInclTypeArguments( // reports
typeArguments,
contextualTypeArguments,
reportNode
);
if (!instance) return null;
2017-12-02 23:33:01 +01:00
return this.compileFunction(instance) ? instance : null;
}
2017-10-07 14:29:43 +02:00
2017-12-02 23:33:01 +01:00
compileFunction(instance: Function): bool {
2018-02-25 00:13:39 +01:00
if (instance.is(ElementFlags.COMPILED)) return true;
2017-10-07 14:29:43 +02:00
assert(!instance.is(ElementFlags.BUILTIN) || instance.simpleName == "abort");
2017-10-07 14:29:43 +02:00
var declaration = instance.prototype.declaration;
if (instance.is(ElementFlags.DECLARED)) {
2018-02-27 00:30:04 +01:00
if (declaration.body) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.An_implementation_cannot_be_declared_in_ambient_contexts,
declaration.name.range
);
2017-12-04 19:26:50 +01:00
return false;
}
2018-02-27 00:30:04 +01:00
} else if (!declaration.body) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Function_implementation_is_missing_or_not_immediately_following_the_declaration,
declaration.name.range
);
return false;
2017-10-07 14:29:43 +02:00
}
// might trigger compilation of other functions referring to this one
instance.set(ElementFlags.COMPILED);
2017-10-07 14:29:43 +02:00
// compile statements
2018-02-27 00:30:04 +01:00
var stmt: ExpressionRef = 0;
if (!instance.is(ElementFlags.DECLARED)) {
var previousFunction = this.currentFunction;
2017-12-04 19:26:50 +01:00
this.currentFunction = instance;
2018-02-27 00:30:04 +01:00
var body = assert(declaration.body, "implementation expected");
stmt = this.compileStatement(body);
// make sure the top-level branch or all child branches return
var allBranchesReturn = this.currentFunction.flow.finalize();
2018-02-25 00:13:39 +01:00
if (instance.returnType != Type.void && !allBranchesReturn) {
this.error(
DiagnosticCode.A_function_whose_declared_type_is_not_void_must_return_a_value,
assert(declaration.returnType, "return type expected").range
);
}
2017-12-04 19:26:50 +01:00
this.currentFunction = previousFunction;
}
2017-10-07 14:29:43 +02:00
2017-12-04 19:26:50 +01:00
// create the function type
2018-02-25 00:13:39 +01:00
var numParameters = instance.parameters ? instance.parameters.length : 0;
var numParametersInclThis = instance.instanceMethodOf ? numParameters + 1 : numParameters;
var paramIndex = 0;
var nativeResultType = instance.returnType.toNativeType();
var nativeParamTypes = new Array<NativeType>(numParametersInclThis);
var signatureNameParts = new Array<string>(numParametersInclThis + 1);
if (instance.instanceMethodOf) {
2018-02-25 00:13:39 +01:00
nativeParamTypes[paramIndex] = this.options.isWasm64 ? NativeType.I64 : NativeType.I32;
signatureNameParts[paramIndex++] = instance.instanceMethodOf.type.toSignatureString();
}
2018-02-25 00:13:39 +01:00
if (instance.parameters) {
for (var i = 0; i < numParameters; ++i) {
nativeParamTypes[paramIndex] = instance.parameters[i].type.toNativeType();
signatureNameParts[paramIndex++] = instance.parameters[i].type.toSignatureString();
}
}
signatureNameParts[paramIndex] = instance.returnType.toSignatureString();
var typeRef = this.module.getFunctionTypeBySignature(nativeResultType, nativeParamTypes);
2018-02-25 00:13:39 +01:00
if (!typeRef) {
typeRef = this.module.addFunctionType(
signatureNameParts.join(""),
nativeResultType,
nativeParamTypes
);
}
2017-12-04 19:26:50 +01:00
// create the function
var ref: FunctionRef;
2018-02-25 00:13:39 +01:00
if (instance.is(ElementFlags.DECLARED)) {
ref = this.module.addFunctionImport(
instance.internalName,
instance.prototype.namespace
? instance.prototype.namespace.simpleName
: "env",
instance.simpleName,
typeRef
);
} else {
ref = this.module.addFunction(
instance.internalName,
typeRef,
typesToNativeTypes(instance.additionalLocals),
2018-02-27 00:30:04 +01:00
assert(stmt)
2018-02-25 00:13:39 +01:00
);
}
// check module export
2018-02-25 00:13:39 +01:00
if (declaration.range.source.isEntry && declaration.isTopLevelExport) {
this.module.addFunctionExport(instance.internalName, declaration.name.text);
2018-02-25 00:13:39 +01:00
}
instance.finalize(this.module, ref);
2017-12-02 23:33:01 +01:00
return true;
2017-09-28 13:08:25 +02:00
}
// namespaces
2017-10-02 12:52:15 +02:00
compileNamespaceDeclaration(declaration: NamespaceDeclaration): void {
var members = declaration.members;
var noTreeShaking = this.options.noTreeShaking;
for (var i = 0, k = members.length; i < k; ++i) {
var member = members[i];
2017-10-07 14:29:43 +02:00
switch (member.kind) {
case NodeKind.CLASSDECLARATION:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking ||
hasModifier(ModifierKind.EXPORT, (<ClassDeclaration>member).modifiers)
) && !(<ClassDeclaration>member).typeParameters.length
) {
this.compileClassDeclaration(<ClassDeclaration>member, []);
2018-02-25 00:13:39 +01:00
}
2017-10-07 14:29:43 +02:00
break;
case NodeKind.INTERFACEDECLARATION:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking ||
hasModifier(ModifierKind.EXPORT, (<InterfaceDeclaration>member).modifiers)
) && !(<InterfaceDeclaration>member).typeParameters.length
) {
2017-12-15 15:00:19 +01:00
this.compileInterfaceDeclaration(<InterfaceDeclaration>member, []);
2018-02-25 00:13:39 +01:00
}
2017-12-15 15:00:19 +01:00
break;
case NodeKind.ENUMDECLARATION:
2018-02-25 00:13:39 +01:00
if (
noTreeShaking ||
hasModifier(ModifierKind.EXPORT, (<EnumDeclaration>member).modifiers)
) {
this.compileEnumDeclaration(<EnumDeclaration>member);
2018-02-25 00:13:39 +01:00
}
2017-10-07 14:29:43 +02:00
break;
case NodeKind.FUNCTIONDECLARATION:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking ||
hasModifier(ModifierKind.EXPORT, (<FunctionDeclaration>member).modifiers)
) &&
!(<FunctionDeclaration>member).isGeneric
2018-02-25 00:13:39 +01:00
) {
this.compileFunctionDeclaration(<FunctionDeclaration>member, []);
2018-02-25 00:13:39 +01:00
}
2017-10-07 14:29:43 +02:00
break;
case NodeKind.NAMESPACEDECLARATION:
2018-02-25 00:13:39 +01:00
if (
noTreeShaking ||
hasModifier(ModifierKind.EXPORT, (<NamespaceDeclaration>member).modifiers)
) {
this.compileNamespaceDeclaration(<NamespaceDeclaration>member);
2018-02-25 00:13:39 +01:00
}
2017-10-07 14:29:43 +02:00
break;
case NodeKind.VARIABLE:
2018-02-25 00:13:39 +01:00
if (
noTreeShaking ||
hasModifier(ModifierKind.EXPORT, (<VariableStatement>member).modifiers)
) {
var variableInit = this.compileVariableStatement(<VariableStatement>member, true);
2018-02-25 00:13:39 +01:00
if (variableInit) this.startFunctionBody.push(variableInit);
}
2017-10-07 14:29:43 +02:00
break;
default:
throw new Error("namespace member expected");
2017-10-07 14:29:43 +02:00
}
}
2017-09-28 13:08:25 +02:00
}
compileNamespace(ns: Namespace): void {
2018-02-25 00:13:39 +01:00
if (!ns.members) return;
2017-12-23 17:49:06 +01:00
var noTreeShaking = this.options.noTreeShaking;
for (var element of ns.members.values()) {
switch (element.kind) {
2017-10-02 12:52:15 +02:00
2017-11-17 14:33:51 +01:00
case ElementKind.CLASS_PROTOTYPE:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking ||
(<ClassPrototype>element).is(ElementFlags.EXPORTED)
) && !(<ClassPrototype>element).is(ElementFlags.GENERIC)
) {
2017-11-20 23:39:50 +01:00
this.compileClassUsingTypeArguments(<ClassPrototype>element, []);
2018-02-25 00:13:39 +01:00
}
break;
2017-10-02 12:52:15 +02:00
case ElementKind.ENUM:
this.compileEnum(<Enum>element);
2017-10-02 12:52:15 +02:00
break;
2017-11-17 14:33:51 +01:00
case ElementKind.FUNCTION_PROTOTYPE:
2018-02-25 00:13:39 +01:00
if (
(
noTreeShaking || (<FunctionPrototype>element).is(ElementFlags.EXPORTED)
) && !(<FunctionPrototype>element).is(ElementFlags.GENERIC)
) {
this.compileFunctionUsingTypeArguments(
<FunctionPrototype>element,
[],
null,
(<FunctionPrototype>element).declaration.name
);
}
2017-10-02 12:52:15 +02:00
break;
case ElementKind.GLOBAL:
this.compileGlobal(<Global>element);
2017-10-02 12:52:15 +02:00
break;
case ElementKind.NAMESPACE:
this.compileNamespace(<Namespace>element);
2017-10-02 12:52:15 +02:00
break;
}
}
}
// exports
2017-10-02 12:52:15 +02:00
compileExportStatement(statement: ExportStatement): void {
var members = statement.members;
for (var i = 0, k = members.length; i < k; ++i) {
var member = members[i];
2018-02-25 00:13:39 +01:00
var internalExportName = (
statement.range.source.internalPath +
PATH_DELIMITER +
member.externalName.text
);
var element = this.program.exports.get(internalExportName);
2018-02-25 00:13:39 +01:00
if (!element) continue; // reported in Program#initialize
switch (element.kind) {
2017-11-17 14:33:51 +01:00
case ElementKind.CLASS_PROTOTYPE:
2018-02-25 00:13:39 +01:00
if (!(<ClassPrototype>element).is(ElementFlags.GENERIC)) {
2017-11-20 23:39:50 +01:00
this.compileClassUsingTypeArguments(<ClassPrototype>element, []);
2018-02-25 00:13:39 +01:00
}
2017-10-02 12:52:15 +02:00
break;
case ElementKind.ENUM:
this.compileEnum(<Enum>element);
break;
2017-11-17 14:33:51 +01:00
case ElementKind.FUNCTION_PROTOTYPE:
2018-02-25 00:13:39 +01:00
if (
!(<FunctionPrototype>element).is(ElementFlags.GENERIC) &&
statement.range.source.isEntry
) {
var functionInstance = this.compileFunctionUsingTypeArguments(
<FunctionPrototype>element,
[],
null,
(<FunctionPrototype>element).declaration.name
);
if (functionInstance) {
var functionDeclaration = functionInstance.prototype.declaration;
2018-02-25 00:13:39 +01:00
if (functionDeclaration && functionDeclaration.needsExplicitExport(member)) {
this.module.addFunctionExport(functionInstance.internalName, member.externalName.text);
2018-02-25 00:13:39 +01:00
}
}
2017-12-02 23:33:01 +01:00
}
break;
case ElementKind.GLOBAL:
if (this.compileGlobal(<Global>element) && statement.range.source.isEntry) {
var globalDeclaration = (<Global>element).declaration;
if (globalDeclaration && globalDeclaration.needsExplicitExport(member)) {
2018-02-25 00:13:39 +01:00
if ((<Global>element).is(ElementFlags.INLINED)) {
this.module.addGlobalExport(element.internalName, member.externalName.text);
} else {
this.warning(
DiagnosticCode.Cannot_export_a_mutable_global,
member.range
);
}
}
}
break;
case ElementKind.NAMESPACE:
this.compileNamespace(<Namespace>element);
break;
2017-10-02 12:52:15 +02:00
}
}
}
// classes
2018-02-25 00:13:39 +01:00
compileClassDeclaration(
declaration: ClassDeclaration,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null = null,
alternativeReportNode: Node | null = null
): void {
var element = this.program.elements.get(declaration.fileLevelInternalName);
2018-02-25 00:13:39 +01:00
if (!element || element.kind != ElementKind.CLASS_PROTOTYPE) {
throw new Error("class expected");
2018-02-25 00:13:39 +01:00
}
this.compileClassUsingTypeArguments(
<ClassPrototype>element,
typeArguments,
contextualTypeArguments,
alternativeReportNode
);
2017-11-20 23:39:50 +01:00
}
2018-02-25 00:13:39 +01:00
compileClassUsingTypeArguments(
prototype: ClassPrototype,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null = null,
alternativeReportNode: Node | null = null
): void {
var instance = prototype.resolveInclTypeArguments( // reports
typeArguments,
contextualTypeArguments,
alternativeReportNode
);
if (!instance) return;
2017-11-20 23:39:50 +01:00
this.compileClass(instance);
}
compileClass(instance: Class): bool {
2018-02-25 00:13:39 +01:00
if (instance.is(ElementFlags.COMPILED)) return true;
instance.set(ElementFlags.COMPILED);
return true;
2017-10-02 12:52:15 +02:00
}
2018-02-25 00:13:39 +01:00
compileInterfaceDeclaration(
declaration: InterfaceDeclaration,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null = null,
alternativeReportNode: Node | null = null
): void {
2017-12-15 15:00:19 +01:00
throw new Error("not implemented");
}
2017-09-28 13:08:25 +02:00
// memory
/** Adds a static memory segment with the specified data. */
addMemorySegment(buffer: Uint8Array, alignment: i32 = 8): MemorySegment {
var memoryOffset = i64_align(this.memoryOffset, alignment);
var segment = MemorySegment.create(buffer, memoryOffset);
2017-09-28 13:08:25 +02:00
this.memorySegments.push(segment);
this.memoryOffset = i64_add(memoryOffset, i64_new(buffer.length, 0));
2017-09-28 13:08:25 +02:00
return segment;
}
// function table
/** Adds a function table entry and returns the assigned index. */
addFunctionTableEntry(func: Function): i32 {
assert(func.is(ElementFlags.COMPILED));
if (func.functionTableIndex >= 0) {
return func.functionTableIndex;
}
var index = this.functionTable.length;
this.functionTable.push(func);
func.functionTableIndex = index;
return index;
}
2017-09-28 13:08:25 +02:00
// statements
2017-11-26 04:03:28 +01:00
compileStatement(statement: Statement): ExpressionRef {
var expr: ExpressionRef;
2017-09-28 13:08:25 +02:00
switch (statement.kind) {
case NodeKind.BLOCK:
expr = this.compileBlockStatement(<BlockStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.BREAK:
expr = this.compileBreakStatement(<BreakStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.CONTINUE:
expr = this.compileContinueStatement(<ContinueStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.DO:
expr = this.compileDoStatement(<DoStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.EMPTY:
expr = this.compileEmptyStatement(<EmptyStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.EXPRESSION:
expr = this.compileExpressionStatement(<ExpressionStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.FOR:
expr = this.compileForStatement(<ForStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.IF:
expr = this.compileIfStatement(<IfStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.RETURN:
expr = this.compileReturnStatement(<ReturnStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.SWITCH:
expr = this.compileSwitchStatement(<SwitchStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.THROW:
expr = this.compileThrowStatement(<ThrowStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.TRY:
expr = this.compileTryStatement(<TryStatement>statement);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.VARIABLE:
var variableInit = this.compileVariableStatement(<VariableStatement>statement);
expr = variableInit ? variableInit : this.module.createNop();
break;
2017-09-28 13:08:25 +02:00
case NodeKind.WHILE:
expr = this.compileWhileStatement(<WhileStatement>statement);
break;
case NodeKind.TYPEDECLARATION:
2018-02-25 00:13:39 +01:00
if (this.currentFunction == this.startFunction) {
return this.module.createNop();
2018-02-25 00:13:39 +01:00
}
// fall-through: must be top-level; function bodies are not guaranteed to be evaluated
default:
throw new Error("statement expected");
2017-09-28 13:08:25 +02:00
}
this.addDebugLocation(expr, statement.range);
return expr;
}
2017-11-26 04:03:28 +01:00
compileStatements(statements: Statement[]): ExpressionRef[] {
var k = statements.length;
var stmts = new Array<ExpressionRef>(k);
2018-02-25 00:13:39 +01:00
for (var i = 0; i < k; ++i) {
stmts[i] = this.compileStatement(statements[i]);
2018-02-25 00:13:39 +01:00
}
2017-12-23 17:49:06 +01:00
return stmts; // array of 0-es in noEmit-mode
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileBlockStatement(statement: BlockStatement): ExpressionRef {
var statements = statement.statements;
// NOTE that we could optimize this to a NOP if empty or unwrap a single
// statement, but that's not what the source told us to do and left to the
// optimizer.
// Not actually a branch, but can contain its own scoped variables.
this.currentFunction.flow = this.currentFunction.flow.enterBranchOrScope();
var stmt = this.module.createBlock(null, this.compileStatements(statements), NativeType.None);
var stmtReturns = this.currentFunction.flow.is(FlowFlags.RETURNS);
// Switch back to the parent flow
this.currentFunction.flow = this.currentFunction.flow.leaveBranchOrScope();
2018-02-25 00:13:39 +01:00
if (stmtReturns) {
this.currentFunction.flow.set(FlowFlags.RETURNS);
2018-02-25 00:13:39 +01:00
}
return stmt;
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileBreakStatement(statement: BreakStatement): ExpressionRef {
2017-12-23 17:49:06 +01:00
if (statement.label) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
statement.label.range
);
2017-12-23 17:49:06 +01:00
return this.module.createUnreachable();
}
var breakLabel = this.currentFunction.flow.breakLabel;
if (breakLabel == null) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement,
statement.range
);
return this.module.createUnreachable();
}
this.currentFunction.flow.set(FlowFlags.POSSIBLY_BREAKS);
return this.module.createBreak(breakLabel);
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileContinueStatement(statement: ContinueStatement): ExpressionRef {
2017-12-23 17:49:06 +01:00
if (statement.label) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
statement.label.range
);
2017-12-23 17:49:06 +01:00
return this.module.createUnreachable();
}
// Check if 'continue' is allowed here
var continueLabel = this.currentFunction.flow.continueLabel;
if (continueLabel == null) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement,
statement.range
);
return this.module.createUnreachable();
}
this.currentFunction.flow.set(FlowFlags.POSSIBLY_CONTINUES);
return this.module.createBreak(continueLabel);
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileDoStatement(statement: DoStatement): ExpressionRef {
// A do statement does not initiate a new branch because it is executed at
// least once, but has its own break and continue labels.
var label = this.currentFunction.enterBreakContext();
var previousBreakLabel = this.currentFunction.flow.breakLabel;
var previousContinueLabel = this.currentFunction.flow.continueLabel;
var breakLabel = this.currentFunction.flow.breakLabel = "break|" + label;
var continueLabel = this.currentFunction.flow.continueLabel = "continue|" + label;
var body = this.compileStatement(statement.statement);
// Reset to the previous break and continue labels, if any.
this.currentFunction.flow.breakLabel = previousBreakLabel;
this.currentFunction.flow.continueLabel = previousContinueLabel;
var condition = makeIsTrueish(
this.compileExpression(statement.condition, Type.i32, ConversionKind.NONE),
this.currentType,
this.module
);
2017-10-07 14:29:43 +02:00
this.currentFunction.leaveBreakContext();
2017-10-07 14:29:43 +02:00
return this.module.createBlock(breakLabel, [
this.module.createLoop(continueLabel,
this.module.createBlock(null, [
body,
this.module.createBreak(continueLabel, condition)
2017-11-26 04:03:28 +01:00
], NativeType.None))
], NativeType.None);
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileEmptyStatement(statement: EmptyStatement): ExpressionRef {
2017-09-28 13:08:25 +02:00
return this.module.createNop();
}
2017-11-26 04:03:28 +01:00
compileExpressionStatement(statement: ExpressionStatement): ExpressionRef {
var expr = this.compileExpression(statement.expression, Type.void, ConversionKind.NONE);
if (this.currentType != Type.void) {
expr = this.module.createDrop(expr);
this.currentType = Type.void;
}
return expr;
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileForStatement(statement: ForStatement): ExpressionRef {
// A for statement initiates a new branch with its own scoped variables
// possibly declared in its initializer, and break context.
var context = this.currentFunction.enterBreakContext();
this.currentFunction.flow = this.currentFunction.flow.enterBranchOrScope();
var breakLabel = this.currentFunction.flow.breakLabel = "break|" + context;
var continueLabel = this.currentFunction.flow.continueLabel = "continue|" + context;
// Compile in correct order
2018-02-25 00:13:39 +01:00
var initializer = statement.initializer
? this.compileStatement(<Statement>statement.initializer)
: this.module.createNop();
var condition = statement.condition
? this.compileExpression(<Expression>statement.condition, Type.i32)
: this.module.createI32(1);
var incrementor = statement.incrementor
? this.compileExpression(<Expression>statement.incrementor, Type.void)
: this.module.createNop();
var body = this.compileStatement(statement.statement);
var alwaysReturns = !statement.condition && this.currentFunction.flow.is(FlowFlags.RETURNS);
// TODO: check other always-true conditions as well, not just omitted
// Switch back to the parent flow
this.currentFunction.flow = this.currentFunction.flow.leaveBranchOrScope();
2017-10-07 14:29:43 +02:00
this.currentFunction.leaveBreakContext();
var expr = this.module.createBlock(breakLabel, [
2017-10-07 14:29:43 +02:00
initializer,
this.module.createLoop(continueLabel, this.module.createBlock(null, [
this.module.createIf(condition, this.module.createBlock(null, [
body,
incrementor,
this.module.createBreak(continueLabel)
2017-11-26 04:03:28 +01:00
], NativeType.None))
], NativeType.None))
], NativeType.None);
// If the loop is guaranteed to run and return, propagate that and append a hint
if (alwaysReturns) {
this.currentFunction.flow.set(FlowFlags.RETURNS);
expr = this.module.createBlock(null, [
expr,
this.module.createUnreachable()
]);
}
return expr;
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileIfStatement(statement: IfStatement): ExpressionRef {
// The condition doesn't initiate a branch yet
var condition = makeIsTrueish(
this.compileExpression(statement.condition, Type.i32, ConversionKind.NONE),
this.currentType,
this.module
);
// Each arm initiates a branch
this.currentFunction.flow = this.currentFunction.flow.enterBranchOrScope();
var ifTrue = this.compileStatement(statement.ifTrue);
var ifTrueReturns = this.currentFunction.flow.is(FlowFlags.RETURNS);
this.currentFunction.flow = this.currentFunction.flow.leaveBranchOrScope();
var ifFalse: ExpressionRef = 0;
var ifFalseReturns = false;
if (statement.ifFalse) {
this.currentFunction.flow = this.currentFunction.flow.enterBranchOrScope();
ifFalse = this.compileStatement(statement.ifFalse);
ifFalseReturns = this.currentFunction.flow.is(FlowFlags.RETURNS);
this.currentFunction.flow = this.currentFunction.flow.leaveBranchOrScope();
}
2018-02-25 00:13:39 +01:00
if (ifTrueReturns && ifFalseReturns) { // not necessary to append a hint
this.currentFunction.flow.set(FlowFlags.RETURNS);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
return this.module.createIf(condition, ifTrue, ifFalse);
}
2017-11-26 04:03:28 +01:00
compileReturnStatement(statement: ReturnStatement): ExpressionRef {
var expression: ExpressionRef = 0;
2018-02-25 00:13:39 +01:00
if (statement.value) {
expression = this.compileExpression(<Expression>statement.value, this.currentFunction.returnType);
2018-02-25 00:13:39 +01:00
}
// Remember that this flow returns
this.currentFunction.flow.set(FlowFlags.RETURNS);
return this.module.createReturn(expression);
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileSwitchStatement(statement: SwitchStatement): ExpressionRef {
// Everything within a switch uses the same break context
var context = this.currentFunction.enterBreakContext();
// introduce a local for evaluating the condition (exactly once)
var tempLocal = this.currentFunction.getTempLocal(Type.u32);
var k = statement.cases.length;
// Prepend initializer to inner block. Does not initiate a new branch, yet.
var breaks = new Array<ExpressionRef>(1 + k);
2018-02-25 00:13:39 +01:00
breaks[0] = this.module.createSetLocal( // initializer
tempLocal.index,
this.compileExpression(statement.condition, Type.u32)
2018-02-25 00:13:39 +01:00
);
2017-12-02 20:58:39 +01:00
// make one br_if per (possibly dynamic) labeled case (binaryen optimizes to br_table where possible)
var breakIndex = 1;
var defaultIndex = -1;
for (var i = 0; i < k; ++i) {
var case_ = statement.cases[i];
if (case_.label) {
breaks[breakIndex++] = this.module.createBreak("case" + i.toString(10) + "|" + context,
2017-12-02 20:58:39 +01:00
this.module.createBinary(BinaryOp.EqI32,
2017-12-12 09:38:20 +01:00
this.module.createGetLocal(tempLocal.index, NativeType.I32),
2017-12-02 20:58:39 +01:00
this.compileExpression(case_.label, Type.i32)
)
);
2018-02-25 00:13:39 +01:00
} else {
defaultIndex = i;
2018-02-25 00:13:39 +01:00
}
}
2017-12-12 09:38:20 +01:00
this.currentFunction.freeTempLocal(tempLocal);
// otherwise br to default respectively out of the switch if there is no default case
breaks[breakIndex] = this.module.createBreak((defaultIndex >= 0
? "case" + defaultIndex.toString(10)
: "break"
) + "|" + context);
// nest blocks in order
var currentBlock = this.module.createBlock("case0|" + context, breaks, NativeType.None);
var alwaysReturns = true;
for (i = 0; i < k; ++i) {
case_ = statement.cases[i];
var l = case_.statements.length;
var body = new Array<ExpressionRef>(1 + l);
body[0] = currentBlock;
// Each switch case initiates a new branch
this.currentFunction.flow = this.currentFunction.flow.enterBranchOrScope();
var breakLabel = this.currentFunction.flow.breakLabel = "break|" + context;
var fallsThrough = i != k - 1;
var nextLabel = !fallsThrough ? breakLabel : "case" + (i + 1).toString(10) + "|" + context;
for (var j = 0; j < l; ++j) {
body[j + 1] = this.compileStatement(case_.statements[j]);
}
2018-02-25 00:13:39 +01:00
if (!(fallsThrough || this.currentFunction.flow.is(FlowFlags.RETURNS))) {
alwaysReturns = false; // ignore fall-throughs
2018-02-25 00:13:39 +01:00
}
// Switch back to the parent flow
this.currentFunction.flow = this.currentFunction.flow.leaveBranchOrScope();
2017-11-26 04:03:28 +01:00
currentBlock = this.module.createBlock(nextLabel, body, NativeType.None);
}
this.currentFunction.leaveBreakContext();
// If the switch has a default and always returns, propagate that
if (defaultIndex >= 0 && alwaysReturns) {
this.currentFunction.flow.set(FlowFlags.RETURNS);
// Binaryen understands that so we don't need a hint
}
return currentBlock;
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileThrowStatement(statement: ThrowStatement): ExpressionRef {
// Remember that this branch possibly throws
this.currentFunction.flow.set(FlowFlags.POSSIBLY_THROWS);
// FIXME: without try-catch it is safe to assume RETURNS as well for now
this.currentFunction.flow.set(FlowFlags.RETURNS);
// TODO: requires exception-handling spec.
return this.module.createUnreachable();
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileTryStatement(statement: TryStatement): ExpressionRef {
2017-09-28 13:08:25 +02:00
throw new Error("not implemented");
2017-10-07 14:29:43 +02:00
// can't yet support something like: try { return ... } finally { ... }
// worthwhile to investigate lowering returns to block results (here)?
2017-09-28 13:08:25 +02:00
}
/**
* Compiles a variable statement. Returns `0` if an initializer is not
* necessary.
*/
compileVariableStatement(statement: VariableStatement, isKnownGlobal: bool = false): ExpressionRef {
var declarations = statement.declarations;
// top-level variables and constants become globals
if (isKnownGlobal || (
this.currentFunction == this.startFunction &&
statement.parent && statement.parent.kind == NodeKind.SOURCE
)) {
// NOTE that the above condition also covers top-level variables declared with 'let', even
// though such variables could also become start function locals if, and only if, not used
// within any function declared in the same source, which is unknown at this point. the only
// efficient way to deal with this would be to keep track of all occasions it is used and
// replace these instructions afterwards, dynamically. (TOOD: what about a Binaryen pass?)
2018-02-25 00:13:39 +01:00
for (var i = 0, k = declarations.length; i < k; ++i) {
this.compileGlobalDeclaration(declarations[i]);
2018-02-25 00:13:39 +01:00
}
return 0;
2017-10-07 14:29:43 +02:00
}
2017-10-07 14:29:43 +02:00
// other variables become locals
var initializers = new Array<ExpressionRef>();
for (i = 0, k = declarations.length; i < k; ++i) {
var declaration = declarations[i];
var name = declaration.name.text;
var type: Type | null = null;
var init: ExpressionRef = 0;
2017-10-07 14:29:43 +02:00
if (declaration.type) {
2018-02-25 00:13:39 +01:00
type = this.program.resolveType( // reports
declaration.type,
this.currentFunction.contextualTypeArguments
);
if (!type) continue;
if (declaration.initializer) {
init = this.compileExpression(declaration.initializer, type); // reports
2018-02-25 00:13:39 +01:00
}
} else if (declaration.initializer) { // infer type using void/NONE for proper literal inference
2018-02-25 00:13:39 +01:00
init = this.compileExpression( // reports
declaration.initializer,
Type.void,
ConversionKind.NONE
);
2018-01-04 01:36:26 +01:00
if (this.currentType == Type.void) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Type_0_is_not_assignable_to_type_1,
declaration.range, this.currentType.toString(), "<auto>"
);
2017-12-23 13:48:04 +01:00
continue;
2018-01-04 01:36:26 +01:00
}
type = this.currentType;
2017-12-14 11:55:35 +01:00
} else {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Type_expected,
declaration.name.range.atEnd
);
2017-12-23 13:48:04 +01:00
continue;
}
if (hasModifier(ModifierKind.CONST, declaration.modifiers)) {
if (init) {
init = this.precomputeExpressionRef(init);
if (_BinaryenExpressionGetId(init) == ExpressionId.Const) {
var local = new Local(this.program, name, -1, type);
switch (_BinaryenExpressionGetType(init)) {
case NativeType.I32:
local = local.withConstantIntegerValue(_BinaryenConstGetValueI32(init), 0);
break;
case NativeType.I64:
2018-02-25 00:13:39 +01:00
local = local.withConstantIntegerValue(
_BinaryenConstGetValueI64Low(init),
_BinaryenConstGetValueI64High(init)
);
break;
case NativeType.F32:
local = local.withConstantFloatValue(<f64>_BinaryenConstGetValueF32(init));
break;
case NativeType.F64:
local = local.withConstantFloatValue(_BinaryenConstGetValueF64(init));
break;
default:
throw new Error("concrete type expected");
}
// Create a virtual local that doesn't actually exist in WebAssembly
var scopedLocals = this.currentFunction.flow.scopedLocals;
2018-02-25 00:13:39 +01:00
if (!scopedLocals) scopedLocals = this.currentFunction.flow.scopedLocals = new Map();
else if (scopedLocals.has(name)) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Duplicate_identifier_0,
declaration.name.range, name
);
return 0;
}
scopedLocals.set(name, local);
return 0;
2018-02-25 00:13:39 +01:00
} else {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
declaration.range
);
}
} else {
this.error(
DiagnosticCode._const_declarations_must_be_initialized,
declaration.range
);
}
2017-10-07 14:29:43 +02:00
}
2018-02-25 00:13:39 +01:00
if (hasModifier(ModifierKind.LET, declaration.modifiers)) { // here: not top-level
this.currentFunction.flow.addScopedLocal(name, type, declaration.name); // reports
2018-02-25 00:13:39 +01:00
} else {
this.currentFunction.addLocal(type, name); // reports
2018-02-25 00:13:39 +01:00
}
if (init) {
initializers.push(this.compileAssignmentWithValue(declaration.name, init));
2018-02-25 00:13:39 +01:00
}
2017-10-07 14:29:43 +02:00
}
2018-02-25 00:13:39 +01:00
return initializers.length // we can unwrap these here because the
? initializers.length == 1 // source didn't tell us exactly what to do
? initializers[0]
: this.module.createBlock(null, initializers, NativeType.None)
: 0;
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileWhileStatement(statement: WhileStatement): ExpressionRef {
// The condition does not yet initialize a branch
var condition = makeIsTrueish(
this.compileExpression(statement.condition, Type.i32, ConversionKind.NONE),
this.currentType,
this.module
);
// Statements initiate a new branch with its own break context
var label = this.currentFunction.enterBreakContext();
this.currentFunction.flow = this.currentFunction.flow.enterBranchOrScope();
var breakLabel = this.currentFunction.flow.breakLabel = "break|" + label;
var continueLabel = this.currentFunction.flow.continueLabel = "continue|" + label;
var body = this.compileStatement(statement.statement);
var alwaysReturns = false && this.currentFunction.flow.is(FlowFlags.RETURNS);
// TODO: evaluate possible always-true conditions
// Switch back to the parent flow
this.currentFunction.flow = this.currentFunction.flow.leaveBranchOrScope();
2017-10-02 12:52:15 +02:00
this.currentFunction.leaveBreakContext();
var expr = this.module.createBlock(breakLabel, [
this.module.createLoop(continueLabel,
this.module.createIf(condition, this.module.createBlock(null, [
body,
this.module.createBreak(continueLabel)
2017-11-26 04:03:28 +01:00
], NativeType.None))
)
2017-11-26 04:03:28 +01:00
], NativeType.None);
// If the loop is guaranteed to run and return, propagate that and append a hint
if (alwaysReturns) {
expr = this.module.createBlock(null, [
expr,
this.module.createUnreachable()
]);
}
return expr;
2017-09-28 13:08:25 +02:00
}
// expressions
/**
* Compiles the value of an inlined constant element.
* @param retainType If true, the annotated type of the constant is retained. Otherwise, the value
* is precomputed according to context.
*/
compileInlineConstant(
element: VariableLikeElement,
contextualType: Type,
retainType: bool
): ExpressionRef {
assert(element.is(ElementFlags.INLINED));
2018-02-25 00:13:39 +01:00
switch (
!retainType &&
2018-02-25 00:13:39 +01:00
element.type.is(TypeFlags.INTEGER) &&
contextualType.is(TypeFlags.INTEGER) &&
element.type.size < contextualType.size
? (this.currentType = contextualType).kind // essentially precomputes a (sign-)extension
: (this.currentType = element.type).kind
) {
case TypeKind.I8:
case TypeKind.I16:
var shift = element.type.computeSmallIntegerShift(Type.i32);
2018-02-25 00:13:39 +01:00
return this.module.createI32(
element.constantValueKind == ConstantValueKind.INTEGER
? i64_low(element.constantIntegerValue) << shift >> shift
: 0
);
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
var mask = element.type.computeSmallIntegerMask(Type.i32);
2018-02-25 00:13:39 +01:00
return this.module.createI32(
element.constantValueKind == ConstantValueKind.INTEGER
? i64_low(element.constantIntegerValue) & mask
: 0
);
case TypeKind.I32:
case TypeKind.U32:
2018-02-25 00:13:39 +01:00
return this.module.createI32(
element.constantValueKind == ConstantValueKind.INTEGER
? i64_low(element.constantIntegerValue)
: 0
);
case TypeKind.ISIZE:
case TypeKind.USIZE:
2018-02-25 00:13:39 +01:00
if (!element.program.options.isWasm64) {
return this.module.createI32(
element.constantValueKind == ConstantValueKind.INTEGER
? i64_low(element.constantIntegerValue)
: 0
);
}
// fall-through
case TypeKind.I64:
case TypeKind.U64:
return element.constantValueKind == ConstantValueKind.INTEGER
2018-02-25 00:13:39 +01:00
? this.module.createI64(
i64_low(element.constantIntegerValue),
i64_high(element.constantIntegerValue)
)
: this.module.createI64(0);
case TypeKind.F32:
2018-02-25 00:13:39 +01:00
return this.module.createF32((<VariableLikeElement>element).constantFloatValue);
case TypeKind.F64:
return this.module.createF64((<VariableLikeElement>element).constantFloatValue);
default:
throw new Error("concrete type expected");
}
}
2018-02-25 00:13:39 +01:00
compileExpression(
expression: Expression,
contextualType: Type,
conversionKind: ConversionKind = ConversionKind.IMPLICIT,
wrapSmallIntegers: bool = true
): ExpressionRef {
this.currentType = contextualType;
2017-09-28 13:08:25 +02:00
var expr: ExpressionRef;
2017-09-28 13:08:25 +02:00
switch (expression.kind) {
case NodeKind.ASSERTION:
expr = this.compileAssertionExpression(<AssertionExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.BINARY:
expr = this.compileBinaryExpression(<BinaryExpression>expression, contextualType, wrapSmallIntegers);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.CALL:
expr = this.compileCallExpression(<CallExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
2018-01-05 01:55:59 +01:00
case NodeKind.COMMA:
expr = this.compileCommaExpression(<CommaExpression>expression, contextualType);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.ELEMENTACCESS:
expr = this.compileElementAccessExpression(<ElementAccessExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.FUNCTION:
case NodeKind.FUNCTIONARROW:
expr = this.compileFunctionExpression(<FunctionExpression>expression, contextualType);
break;
2017-09-28 13:08:25 +02:00
case NodeKind.IDENTIFIER:
case NodeKind.FALSE:
case NodeKind.NULL:
case NodeKind.THIS:
case NodeKind.TRUE:
expr = this.compileIdentifierExpression(
<IdentifierExpression>expression,
contextualType,
conversionKind == ConversionKind.NONE // retain type of inlined constants
);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.LITERAL:
expr = this.compileLiteralExpression(<LiteralExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.NEW:
expr = this.compileNewExpression(<NewExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.PARENTHESIZED:
expr = this.compileParenthesizedExpression(<ParenthesizedExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.PROPERTYACCESS:
expr = this.compilePropertyAccessExpression(
<PropertyAccessExpression>expression,
contextualType,
conversionKind == ConversionKind.NONE // retain type of inlined constants
);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.TERNARY:
expr = this.compileTernaryExpression(<TernaryExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.UNARYPOSTFIX:
expr = this.compileUnaryPostfixExpression(<UnaryPostfixExpression>expression, contextualType);
2017-09-28 13:08:25 +02:00
break;
case NodeKind.UNARYPREFIX:
expr = this.compileUnaryPrefixExpression(<UnaryPrefixExpression>expression, contextualType, wrapSmallIntegers);
2017-09-28 13:08:25 +02:00
break;
default:
throw new Error("expression expected");
2017-09-28 13:08:25 +02:00
}
2017-12-05 15:06:44 +01:00
if (conversionKind != ConversionKind.NONE && this.currentType != contextualType) {
expr = this.convertExpression(expr, this.currentType, contextualType, conversionKind, expression);
this.currentType = contextualType;
2017-09-28 13:08:25 +02:00
}
this.addDebugLocation(expr, expression.range);
2017-09-28 13:08:25 +02:00
return expr;
}
compileExpressionRetainType(expression: Expression, contextualType: Type, wrapSmallIntegers: bool = true) {
return this.compileExpression(
expression,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
wrapSmallIntegers
);
}
2018-02-25 00:13:39 +01:00
precomputeExpression(
expression: Expression,
contextualType: Type,
conversionKind: ConversionKind = ConversionKind.IMPLICIT
): ExpressionRef {
return this.precomputeExpressionRef(this.compileExpression(expression, contextualType, conversionKind));
}
precomputeExpressionRef(expr: ExpressionRef): ExpressionRef {
var nativeType = this.currentType.toNativeType();
var typeRef = this.module.getFunctionTypeBySignature(nativeType, []);
var typeRefAdded = false;
if (!typeRef) {
typeRef = this.module.addFunctionType(this.currentType.toSignatureString(), nativeType, []);
typeRefAdded = true;
}
var funcRef = this.module.addFunction("__precompute", typeRef, [], expr);
this.module.runPasses([ "precompute" ], funcRef);
var ret = _BinaryenFunctionGetBody(funcRef);
this.module.removeFunction("__precompute");
if (typeRefAdded) {
// TODO: also remove the function type somehow if no longer used or make the C-API accept
// a `null` typeRef, using an implicit type.
}
return ret;
}
2018-02-25 00:13:39 +01:00
convertExpression(
expr: ExpressionRef,
fromType: Type,
toType: Type,
conversionKind: ConversionKind,
reportNode: Node
): ExpressionRef {
if (conversionKind == ConversionKind.NONE) {
assert(false, "concrete type expected");
return expr;
}
2017-09-28 13:08:25 +02:00
// void to any
if (fromType.kind == TypeKind.VOID) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Type_0_is_not_assignable_to_type_1,
reportNode.range, fromType.toString(), toType.toString()
);
2018-01-04 01:36:26 +01:00
return this.module.createUnreachable();
}
2017-09-28 13:08:25 +02:00
// any to void
2018-02-25 00:13:39 +01:00
if (toType.kind == TypeKind.VOID) {
2017-09-28 13:08:25 +02:00
return this.module.createDrop(expr);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
if (conversionKind == ConversionKind.IMPLICIT && !fromType.isAssignableTo(toType)) {
this.error(
DiagnosticCode.Conversion_from_type_0_to_1_requires_an_explicit_cast,
reportNode.range, fromType.toString(), toType.toString()
);
}
if (fromType.is(TypeFlags.FLOAT)) {
2017-09-28 13:08:25 +02:00
// float to float
if (toType.is(TypeFlags.FLOAT)) {
2017-09-28 13:08:25 +02:00
if (fromType.kind == TypeKind.F32) {
// f32 to f64
2018-02-25 00:13:39 +01:00
if (toType.kind == TypeKind.F64) {
expr = this.module.createUnary(UnaryOp.PromoteF32, expr);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
// otherwise f32 to f32
2017-09-28 13:08:25 +02:00
// f64 to f32
} else if (toType.kind == TypeKind.F32) {
expr = this.module.createUnary(UnaryOp.DemoteF64, expr);
2017-09-28 13:08:25 +02:00
}
// otherwise f64 to f64
2017-09-28 13:08:25 +02:00
// float to int
} else if (toType.is(TypeFlags.INTEGER)) {
2017-09-28 13:08:25 +02:00
// f32 to int
if (fromType.kind == TypeKind.F32) {
if (toType.is(TypeFlags.SIGNED)) {
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(UnaryOp.TruncF32ToI64, expr);
2018-02-25 00:13:39 +01:00
} else {
expr = this.module.createUnary(UnaryOp.TruncF32ToI32, expr);
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.SMALL)) {
expr = makeSmallIntegerWrap(expr, toType, this.module);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
}
} else {
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(UnaryOp.TruncF32ToU64, expr);
2018-02-25 00:13:39 +01:00
} else {
expr = this.module.createUnary(UnaryOp.TruncF32ToU32, expr);
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.SMALL)) {
expr = makeSmallIntegerWrap(expr, toType, this.module);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
}
}
// f64 to int
} else {
if (toType.is(TypeFlags.SIGNED)) {
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(UnaryOp.TruncF64ToI64, expr);
2018-02-25 00:13:39 +01:00
} else {
expr = this.module.createUnary(UnaryOp.TruncF64ToI32, expr);
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.SMALL)) {
expr = makeSmallIntegerWrap(expr, toType, this.module);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
}
} else {
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(UnaryOp.TruncF64ToU64, expr);
2018-02-25 00:13:39 +01:00
} else {
expr = this.module.createUnary(UnaryOp.TruncF64ToU32, expr);
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.SMALL)) {
expr = makeSmallIntegerWrap(expr, toType, this.module);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
}
}
}
// float to void
} else {
assert(toType.flags == TypeFlags.NONE, "void type expected");
expr = this.module.createDrop(expr);
2017-09-28 13:08:25 +02:00
}
// int to float
} else if (fromType.is(TypeFlags.INTEGER) && toType.is(TypeFlags.FLOAT)) {
2017-09-28 13:08:25 +02:00
// int to f32
if (toType.kind == TypeKind.F32) {
if (fromType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(
2018-02-25 00:13:39 +01:00
fromType.is(TypeFlags.SIGNED)
? UnaryOp.ConvertI64ToF32
: UnaryOp.ConvertU64ToF32,
expr
);
2017-12-14 11:55:35 +01:00
} else {
expr = this.module.createUnary(
2018-02-25 00:13:39 +01:00
fromType.is(TypeFlags.SIGNED)
? UnaryOp.ConvertI32ToF32
: UnaryOp.ConvertU32ToF32,
expr
);
2017-12-14 11:55:35 +01:00
}
2017-09-28 13:08:25 +02:00
// int to f64
} else {
if (fromType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(
2018-02-25 00:13:39 +01:00
fromType.is(TypeFlags.SIGNED)
? UnaryOp.ConvertI64ToF64
: UnaryOp.ConvertU64ToF64,
expr
);
} else {
expr = this.module.createUnary(
2018-02-25 00:13:39 +01:00
fromType.is(TypeFlags.SIGNED)
? UnaryOp.ConvertI32ToF64
: UnaryOp.ConvertU32ToF64,
expr
);
}
2017-09-28 13:08:25 +02:00
}
// int to int
} else {
if (fromType.is(TypeFlags.LONG)) {
2017-09-28 13:08:25 +02:00
// i64 to i32
if (!toType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(UnaryOp.WrapI64, expr); // discards upper bits
2018-02-25 00:13:39 +01:00
if (toType.is(TypeFlags.SMALL)) {
expr = makeSmallIntegerWrap(expr, toType, this.module);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
}
// i32 to i64
} else if (toType.is(TypeFlags.LONG)) {
expr = this.module.createUnary(toType.is(TypeFlags.SIGNED) ? UnaryOp.ExtendI32 : UnaryOp.ExtendU32, expr);
// i32 or smaller to even smaller or same size int with change of sign
2018-02-25 00:13:39 +01:00
} else if (
toType.is(TypeFlags.SMALL) &&
(
fromType.size > toType.size ||
(
fromType.size == toType.size &&
fromType.is(TypeFlags.SIGNED) != toType.is(TypeFlags.SIGNED)
)
)
) {
expr = makeSmallIntegerWrap(expr, toType, this.module);
2017-09-28 13:08:25 +02:00
}
// otherwise (smaller) i32/u32 to (same size) i32/u32
2017-09-28 13:08:25 +02:00
}
this.currentType = toType;
2017-09-28 13:08:25 +02:00
return expr;
}
2017-11-26 04:03:28 +01:00
compileAssertionExpression(expression: AssertionExpression, contextualType: Type): ExpressionRef {
2018-02-25 00:13:39 +01:00
var toType = this.program.resolveType( // reports
expression.toType,
this.currentFunction.contextualTypeArguments
);
if (!toType) return this.module.createUnreachable();
return this.compileExpression(expression.expression, toType, ConversionKind.EXPLICIT);
2017-09-28 13:08:25 +02:00
}
2018-02-25 00:13:39 +01:00
compileBinaryExpression(
expression: BinaryExpression,
contextualType: Type,
wrapSmallIntegers: bool = true
): ExpressionRef {
var left: ExpressionRef;
var leftType: Type;
var right: ExpressionRef;
var rightType: Type;
var commonType: Type | null;
var condition: ExpressionRef;
var expr: ExpressionRef;
var compound = false;
var possiblyOverflows = false;
2018-02-25 00:13:39 +01:00
var tempLocal: Local | null = null;
2017-12-04 16:26:34 +01:00
switch (expression.operator) {
case Token.LESSTHAN:
left = this.compileExpressionRetainType(expression.left, contextualType);
leftType = this.currentType;
right = this.compileExpressionRetainType(expression.right, leftType);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, true)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "<", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
switch (commonType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
expr = this.module.createBinary(BinaryOp.LtI32, left, right);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.LtI64, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.LtI64
: BinaryOp.LtI32,
left,
right
);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.LtU32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.LtU64
: BinaryOp.LtU32,
left,
right
);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.LtU64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.LtF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.LtF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.GREATERTHAN:
left = this.compileExpressionRetainType(expression.left, contextualType);
leftType = this.currentType;
right = this.compileExpressionRetainType(expression.right, leftType);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, true)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, ">", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
switch (commonType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
expr = this.module.createBinary(BinaryOp.GtI32, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.GtI64
: BinaryOp.GtI32,
left,
right
);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.GtI64, left, right);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.GtU32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.GtU64
: BinaryOp.GtU32,
left,
right
);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.GtU64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.GtF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.GtF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.LESSTHAN_EQUALS:
left = this.compileExpressionRetainType(expression.left, contextualType);
leftType = this.currentType;
right = this.compileExpressionRetainType(expression.right, leftType);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, true)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "<=", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
switch (commonType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
expr = this.module.createBinary(BinaryOp.LeI32, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.LeI64
: BinaryOp.LeI32,
left,
right
);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.LeI64, left, right);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.LeU32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.LeU64
: BinaryOp.LeU32,
left,
right
);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.LeU64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.LeF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.LeF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.GREATERTHAN_EQUALS:
left = this.compileExpressionRetainType(expression.left, contextualType);
leftType = this.currentType;
right = this.compileExpressionRetainType(expression.right, leftType);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, true)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, ">=", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
switch (commonType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
expr = this.module.createBinary(BinaryOp.GeI32, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.GeI64
: BinaryOp.GeI32,
left,
right
);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.GeI64, left, right);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.GeU32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.GeU64
: BinaryOp.GeU32,
left,
right
);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.GeU64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.GeF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.GeF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.EQUALS_EQUALS_EQUALS:
// TODO?
case Token.EQUALS_EQUALS:
2018-01-02 23:20:57 +01:00
// NOTE that this favors correctness, in terms of emitting a binary expression, over
// checking for a possible use of unary EQZ. while the most classic of all optimizations,
// that's not what the source told us to do. for reference, `!left` emits unary EQZ.
left = this.compileExpressionRetainType(expression.left, contextualType);
leftType = this.currentType;
right = this.compileExpressionRetainType(expression.right, leftType);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, Token.operatorToString(expression.operator), leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
switch (commonType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.EqI32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.EqI64
: BinaryOp.EqI32,
left,
right
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.EqI64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.EqF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.EqF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.EXCLAMATION_EQUALS_EQUALS:
// TODO?
case Token.EXCLAMATION_EQUALS:
left = this.compileExpressionRetainType(expression.left, contextualType);
leftType = this.currentType;
right = this.compileExpressionRetainType(expression.right, leftType);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, Token.operatorToString(expression.operator), leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
switch (commonType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.NeI32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.NeI64
: BinaryOp.NeI32,
left,
right
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.NeI64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.NeF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.NeF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
2017-10-07 14:29:43 +02:00
case Token.EQUALS:
return this.compileAssignment(expression.left, expression.right, contextualType);
case Token.PLUS_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.PLUS:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "+", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
case TypeKind.I32:
case TypeKind.U32:
expr = this.module.createBinary(BinaryOp.AddI32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.AddI64
: BinaryOp.AddI32,
left,
right
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.AddI64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.AddF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.AddF64, left, right);
break;
default:
throw new Error("concrete type expected");
}
break;
case Token.MINUS_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.MINUS:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "-", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
case TypeKind.I32:
case TypeKind.U32:
expr = this.module.createBinary(BinaryOp.SubI32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.SubI64
: BinaryOp.SubI32,
left,
right
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.SubI64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.SubF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.SubF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.ASTERISK_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.ASTERISK:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "*", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
// fall-through
case TypeKind.I32:
case TypeKind.U32:
expr = this.module.createBinary(BinaryOp.MulI32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.MulI64
: BinaryOp.MulI32,
left,
right
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.MulI64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.MulF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.MulF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.SLASH_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.SLASH:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
true // TODO: when can division remain unwrapped? does it overflow?
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "/", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
possiblyOverflows = true;
case TypeKind.I32:
expr = this.module.createBinary(BinaryOp.DivI32, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.DivI64
: BinaryOp.DivI32,
left,
right
);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.DivI64, left, right);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
case TypeKind.U32:
expr = this.module.createBinary(BinaryOp.DivU32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.DivU64
: BinaryOp.DivU32,
left,
right
);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.DivU64, left, right);
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.DivF32, left, right);
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.DivF64, left, right);
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.PERCENT_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.PERCENT:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
true // TODO: when can remainder remain unwrapped? does it overflow?
2018-02-25 00:13:39 +01:00
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "%", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
expr = this.module.createBinary(BinaryOp.RemI32, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.RemI64
: BinaryOp.RemI32,
left,
right
);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.RemI64, left, right);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
expr = this.module.createBinary(BinaryOp.RemU32, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.RemU64
: BinaryOp.RemU32,
left,
right
);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.RemU64, left, right);
break;
case TypeKind.F32:
case TypeKind.F64:
// TODO: internal fmod, possibly simply imported from JS
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
expr = this.module.createUnreachable();
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.LESSTHAN_LESSTHAN_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.LESSTHAN_LESSTHAN:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
default:
expr = this.module.createBinary(BinaryOp.ShlI32, left, right);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.ShlI64, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.ShlI64
: BinaryOp.ShlI32,
left,
right
);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.GREATERTHAN_GREATERTHAN_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.GREATERTHAN_GREATERTHAN:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
true // must wrap small integers
);
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
true // ^
);
switch (this.currentType.kind) {
default:
// assumes signed shr on signed small integers does not overflow
expr = this.module.createBinary(BinaryOp.ShrI32, left, right);
break;
case TypeKind.I64:
expr = this.module.createBinary(BinaryOp.ShrI64, left, right);
break;
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.ShrI64
: BinaryOp.ShrI32,
left,
right
);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
// assumes unsigned shr on unsigned small integers does not overflow
case TypeKind.U32:
expr = this.module.createBinary(BinaryOp.ShrU32, left, right);
break;
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.ShrU64, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.ShrU64
: BinaryOp.ShrU32,
left,
right
);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.GREATERTHAN_GREATERTHAN_GREATERTHAN_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.GREATERTHAN_GREATERTHAN_GREATERTHAN:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
true // modifies low bits of small integers if unsigned
);
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
true // ^
);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
possiblyOverflows = true;
// fall-through
default:
// assumes that unsigned shr on unsigned small integers does not overflow
expr = this.module.createBinary(BinaryOp.ShrU32, left, right);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.ShrU64, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.ShrU64
: BinaryOp.ShrU32,
left,
right
);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.AMPERSAND_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.AMPERSAND:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "&", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // if left or right already did
default:
expr = this.module.createBinary(BinaryOp.AndI32, left, right);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.AndI64, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.AndI64
: BinaryOp.AndI32,
left,
right
);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.BAR_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.BAR:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "|", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // if left or right already did
default:
expr = this.module.createBinary(BinaryOp.OrI32, left, right);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.OrI64, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.OrI64
: BinaryOp.OrI32,
left,
right
);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.CARET_EQUALS:
compound = true;
2018-02-25 00:13:39 +01:00
case Token.CARET:
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType,
2018-02-25 00:13:39 +01:00
false // retains low bits of small integers
);
if (compound) {
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false // ^
);
} else {
leftType = this.currentType;
right = this.compileExpressionRetainType(
expression.right,
leftType,
false // ^
);
rightType = this.currentType;
if (commonType = Type.commonCompatible(leftType, rightType, false)) {
left = this.convertExpression(left, leftType, commonType, ConversionKind.IMPLICIT, expression.left);
right = this.convertExpression(right, rightType, commonType, ConversionKind.IMPLICIT, expression.right);
} else {
this.error(
DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2,
expression.range, "^", leftType.toString(), rightType.toString()
);
this.currentType = contextualType;
return this.module.createUnreachable();
}
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // if left or right already did
default:
expr = this.module.createBinary(BinaryOp.XorI32, left, right);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.XorI64, left, right);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.XorI64
: BinaryOp.XorI32,
left,
right
);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
// logical (no overloading)
2017-12-04 16:26:34 +01:00
case Token.AMPERSAND_AMPERSAND: // left && right
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType
2018-02-25 00:13:39 +01:00
);
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false
);
// clone left if free of side effects
expr = this.module.cloneExpression(left, true, 0);
// if not possible, tee left to a temp. local
if (!expr) {
tempLocal = this.currentFunction.getAndFreeTempLocal(this.currentType);
left = this.module.createTeeLocal(tempLocal.index, left);
}
possiblyOverflows = this.currentType.is(TypeFlags.SMALL | TypeFlags.INTEGER);
condition = makeIsTrueish(left, this.currentType, this.module);
// simplify when cloning left without side effects was successful
2018-02-25 00:13:39 +01:00
if (expr) {
expr = this.module.createIf(
condition, // left
2018-02-25 00:13:39 +01:00
right, // ? right
expr // : cloned left
);
2018-02-25 00:13:39 +01:00
}
// otherwise make use of the temp. local
else {
expr = this.module.createIf(
condition,
right,
2018-02-25 00:13:39 +01:00
this.module.createGetLocal(
assert(tempLocal, "tempLocal must be set").index,
this.currentType.toNativeType()
)
);
}
break;
2017-12-04 16:26:34 +01:00
case Token.BAR_BAR: // left || right
left = this.compileExpressionRetainType(
2018-02-25 00:13:39 +01:00
expression.left,
contextualType
2018-02-25 00:13:39 +01:00
);
right = this.compileExpression(
expression.right,
this.currentType,
ConversionKind.IMPLICIT,
false
);
// clone left if free of side effects
expr = this.module.cloneExpression(left, true, 0);
// if not possible, tee left to a temp. local
if (!expr) {
tempLocal = this.currentFunction.getAndFreeTempLocal(this.currentType);
left = this.module.createTeeLocal(tempLocal.index, left);
}
2018-02-25 00:13:39 +01:00
possiblyOverflows = this.currentType.is(TypeFlags.SMALL | TypeFlags.INTEGER); // if right did
condition = makeIsTrueish(left, this.currentType, this.module);
// simplify when cloning left without side effects was successful
2018-02-25 00:13:39 +01:00
if (expr) {
expr = this.module.createIf(
condition, // left
2018-02-25 00:13:39 +01:00
expr, // ? cloned left
right // : right
);
2018-02-25 00:13:39 +01:00
}
// otherwise make use of the temp. local
else {
expr = this.module.createIf(
condition,
2018-02-25 00:13:39 +01:00
this.module.createGetLocal(
assert(tempLocal, "tempLocal must be set").index,
this.currentType.toNativeType()
),
right
);
}
break;
2017-12-04 16:26:34 +01:00
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("not implemented");
}
if (possiblyOverflows && wrapSmallIntegers) {
2018-02-25 00:13:39 +01:00
assert(this.currentType.is(TypeFlags.SMALL | TypeFlags.INTEGER), "small integer type expected");
expr = makeSmallIntegerWrap(expr, this.currentType, this.module);
2017-10-07 14:29:43 +02:00
}
return compound
? this.compileAssignmentWithValue(expression.left, expr, contextualType != Type.void)
: expr;
2017-10-07 14:29:43 +02:00
}
2017-11-26 04:03:28 +01:00
compileAssignment(expression: Expression, valueExpression: Expression, contextualType: Type): ExpressionRef {
var resolved = this.program.resolveExpression(expression, this.currentFunction); // reports
2018-02-25 00:13:39 +01:00
if (!resolved) return this.module.createUnreachable();
2018-01-04 01:36:26 +01:00
// to compile just the value, we need to know the target's type
var element = resolved.element;
var elementType: Type;
2017-12-23 17:49:06 +01:00
switch (element.kind) {
2017-12-23 17:49:06 +01:00
case ElementKind.GLOBAL:
2018-02-25 00:13:39 +01:00
if (!this.compileGlobal(<Global>element)) { // reports; not yet compiled if a static field compiled as a global
2018-01-05 01:55:59 +01:00
return this.module.createUnreachable();
2018-02-25 00:13:39 +01:00
}
assert((<Global>element).type != Type.void, "concrete type expected");
2018-01-05 01:55:59 +01:00
// fall-through
case ElementKind.LOCAL:
case ElementKind.FIELD:
elementType = (<VariableLikeElement>element).type;
2017-12-23 17:49:06 +01:00
break;
case ElementKind.PROPERTY:
var setterPrototype = (<Property>element).setterPrototype;
if (setterPrototype) {
var setterInstance = setterPrototype.resolve(); // reports
2018-02-25 00:13:39 +01:00
if (!setterInstance) return this.module.createUnreachable();
assert(setterInstance.parameters && setterInstance.parameters.length == 1);
elementType = (<Parameter[]>setterInstance.parameters)[0].type;
break;
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property,
expression.range, (<Property>element).internalName
);
return this.module.createUnreachable();
case ElementKind.FUNCTION_PROTOTYPE:
if (expression.kind == NodeKind.ELEMENTACCESS) { // @operator("[]")
2018-02-25 00:13:39 +01:00
assert(
resolved.target &&
resolved.target.kind == ElementKind.CLASS &&
element.simpleName == (<Class>resolved.target).prototype.fnIndexedGet
);
var resolvedIndexedSet = (<FunctionPrototype>element).resolve(null);
if (resolvedIndexedSet) {
elementType = resolvedIndexedSet.returnType;
break;
}
}
// fall-through
2017-12-23 17:49:06 +01:00
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
2017-12-23 17:49:06 +01:00
}
2018-01-04 01:36:26 +01:00
// now compile the value and do the assignment
this.currentType = elementType;
2018-02-25 00:13:39 +01:00
return this.compileAssignmentWithValue(
expression,
this.compileExpression(valueExpression, elementType),
contextualType != Type.void
);
}
2018-02-25 00:13:39 +01:00
compileAssignmentWithValue(
expression: Expression,
valueWithCorrectType: ExpressionRef,
tee: bool = false
): ExpressionRef {
var resolved = this.program.resolveExpression(expression, this.currentFunction); // reports
2018-02-25 00:13:39 +01:00
if (!resolved) return this.module.createUnreachable();
var element = resolved.element;
var tempLocal: Local;
var targetExpr: ExpressionRef;
switch (element.kind) {
case ElementKind.LOCAL:
this.currentType = tee ? (<Local>element).type : Type.void;
if ((<Local>element).is(ElementFlags.CONSTANT)) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property,
expression.range, (<Local>element).internalName
);
return this.module.createUnreachable();
}
return tee
? this.module.createTeeLocal((<Local>element).index, valueWithCorrectType)
: this.module.createSetLocal((<Local>element).index, valueWithCorrectType);
case ElementKind.GLOBAL:
2018-02-25 00:13:39 +01:00
if (!this.compileGlobal(<Global>element)) { // reports; not yet compiled if a static field
return this.module.createUnreachable();
2018-02-25 00:13:39 +01:00
}
assert((<Global>element).type != Type.void, "concrete type expected");
this.currentType = tee ? (<Global>element).type : Type.void;
if ((<Local>element).is(ElementFlags.CONSTANT)) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property,
expression.range,
(<Local>element).internalName
);
return this.module.createUnreachable();
}
2018-02-25 00:13:39 +01:00
if (!tee) {
return this.module.createSetGlobal((<Global>element).internalName, valueWithCorrectType);
2018-02-25 00:13:39 +01:00
}
var globalNativeType = (<Global>element).type.toNativeType();
return this.module.createBlock(null, [ // emulated teeGlobal
this.module.createSetGlobal((<Global>element).internalName, valueWithCorrectType),
2017-11-26 04:03:28 +01:00
this.module.createGetGlobal((<Global>element).internalName, globalNativeType)
], globalNativeType);
2017-09-28 13:08:25 +02:00
case ElementKind.FIELD:
if ((<Field>element).prototype.isReadonly) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property,
expression.range, (<Field>element).internalName
);
return this.module.createUnreachable();
}
assert(resolved.targetExpression != null, "target expression expected");
2018-02-25 00:13:39 +01:00
targetExpr = this.compileExpression(
<Expression>resolved.targetExpression,
this.options.isWasm64
? Type.usize64
: Type.usize32,
ConversionKind.NONE
);
assert(this.currentType.classType, "class type expected");
this.currentType = tee ? (<Field>element).type : Type.void;
var elementNativeType = (<Field>element).type.toNativeType();
2018-02-25 00:13:39 +01:00
if (!tee) {
return this.module.createStore(
(<Field>element).type.size >> 3,
targetExpr,
valueWithCorrectType,
elementNativeType,
(<Field>element).memoryOffset
);
}
tempLocal = this.currentFunction.getAndFreeTempLocal((<Field>element).type);
2018-02-25 00:13:39 +01:00
// TODO: simplify if valueWithCorrectType has no side effects
return this.module.createBlock(null, [
this.module.createSetLocal(tempLocal.index, valueWithCorrectType),
2018-02-25 00:13:39 +01:00
this.module.createStore(
(<Field>element).type.size >> 3,
targetExpr,
this.module.createGetLocal(tempLocal.index, elementNativeType),
elementNativeType,
(<Field>element).memoryOffset
),
this.module.createGetLocal(tempLocal.index, elementNativeType)
], elementNativeType);
case ElementKind.PROPERTY:
var setterPrototype = (<Property>element).setterPrototype;
if (setterPrototype) {
var setterInstance = setterPrototype.resolve(); // reports
if (setterInstance) {
2018-02-25 00:13:39 +01:00
assert(setterInstance.parameters && setterInstance.parameters.length == 1);
2018-01-04 01:36:26 +01:00
if (!tee) {
if (setterInstance.is(ElementFlags.INSTANCE)) {
assert(resolved.targetExpression != null);
2018-02-25 00:13:39 +01:00
targetExpr = this.compileExpression(
<Expression>resolved.targetExpression,
this.options.isWasm64
? Type.usize64
: Type.usize32,
ConversionKind.NONE
);
assert(this.currentType.classType);
this.currentType = Type.void;
return this.makeCall(setterInstance, [ targetExpr, valueWithCorrectType ]);
} else {
this.currentType = Type.void;
return this.makeCall(setterInstance, [ valueWithCorrectType ]);
}
2018-01-04 01:36:26 +01:00
}
var getterPrototype = (<Property>element).getterPrototype;
assert(getterPrototype != null);
var getterInstance = (<FunctionPrototype>getterPrototype).resolve(); // reports
2018-01-04 01:36:26 +01:00
if (getterInstance) {
2018-02-25 00:13:39 +01:00
assert(!getterInstance.parameters || !getterInstance.parameters.length);
if (setterInstance.is(ElementFlags.INSTANCE)) {
assert(resolved.targetExpression != null);
2018-02-25 00:13:39 +01:00
targetExpr = this.compileExpression(
<Expression>resolved.targetExpression,
this.options.isWasm64
? Type.usize64
: Type.usize32,
ConversionKind.NONE
);
assert(this.currentType.classType);
tempLocal = this.currentFunction.getAndFreeTempLocal(getterInstance.returnType);
return this.module.createBlock(null, [
2018-02-25 00:13:39 +01:00
this.makeCall(setterInstance, [
this.module.createTeeLocal(tempLocal.index, targetExpr), valueWithCorrectType
]),
this.makeCall(getterInstance, [
this.module.createGetLocal(tempLocal.index, tempLocal.type.toNativeType())
])
], (this.currentType = getterInstance.returnType).toNativeType());
2018-02-25 00:13:39 +01:00
} else {
return this.module.createBlock(null, [
this.makeCall(setterInstance, [ valueWithCorrectType ]),
this.makeCall(getterInstance)
], (this.currentType = getterInstance.returnType).toNativeType());
2018-02-25 00:13:39 +01:00
}
2018-01-04 01:36:26 +01:00
}
}
2018-02-25 00:13:39 +01:00
} else {
this.error(
DiagnosticCode.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property,
expression.range, (<Property>element).internalName
);
}
return this.module.createUnreachable();
case ElementKind.FUNCTION_PROTOTYPE:
if (expression.kind == NodeKind.ELEMENTACCESS) { // @operator("[]")
assert(resolved.target && resolved.target.kind == ElementKind.CLASS);
var resolvedIndexedGet = (<FunctionPrototype>element).resolve();
2018-02-25 00:13:39 +01:00
if (!resolvedIndexedGet) return this.module.createUnreachable();
var indexedSetName = (<Class>resolved.target).prototype.fnIndexedSet;
var indexedSet: Element | null;
2018-02-25 00:13:39 +01:00
if (
indexedSetName != null &&
(<Class>resolved.target).members &&
(indexedSet = (<Map<string,Element>>(<Class>resolved.target).members).get(indexedSetName)) &&
indexedSet.kind == ElementKind.FUNCTION_PROTOTYPE
) { // @operator("[]=")
var resolvedIndexedSet = (<FunctionPrototype>indexedSet).resolve();
2018-02-25 00:13:39 +01:00
if (!resolvedIndexedSet) return this.module.createUnreachable();
targetExpr = this.compileExpression(
<Expression>resolved.targetExpression,
this.options.isWasm64
? Type.usize64
: Type.usize32,
ConversionKind.NONE
);
assert(this.currentType.classType);
2018-02-25 00:13:39 +01:00
var elementExpr = this.compileExpression(
(<ElementAccessExpression>expression).elementExpression,
Type.i32
);
if (!tee) {
this.currentType = resolvedIndexedSet.returnType;
2018-02-25 00:13:39 +01:00
return this.makeCall(resolvedIndexedSet, [
targetExpr,
elementExpr,
valueWithCorrectType
]);
}
this.currentType = resolvedIndexedGet.returnType;
tempLocal = this.currentFunction.getAndFreeTempLocal(this.currentType);
return this.module.createBlock(null, [
2018-02-25 00:13:39 +01:00
this.makeCall(resolvedIndexedSet, [
targetExpr,
elementExpr,
this.module.createTeeLocal(tempLocal.index, valueWithCorrectType)
]),
// TODO: could be different from an actual __get (needs 2 temp locals)
this.module.createGetLocal(tempLocal.index, tempLocal.type.toNativeType())
], this.currentType.toNativeType());
} else {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Index_signature_in_type_0_only_permits_reading,
expression.range, (<Class>resolved.target).internalName
);
return this.module.createUnreachable();
}
}
// fall-through
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
2018-01-04 01:36:26 +01:00
return this.module.createUnreachable();
}
compileCallExpression(expression: CallExpression, contextualType: Type): ExpressionRef {
var resolved = this.program.resolveExpression(expression.expression, this.currentFunction); // reports
2018-02-25 00:13:39 +01:00
if (!resolved) return this.module.createUnreachable();
2017-12-05 01:45:15 +01:00
var element = resolved.element;
if (element.kind != ElementKind.FUNCTION_PROTOTYPE) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures,
expression.range, element.internalName
);
return this.module.createUnreachable();
}
2017-12-04 02:00:48 +01:00
var functionPrototype = <FunctionPrototype>element;
var functionInstance: Function | null = null;
// TODO: generalize?
if (functionPrototype.is(ElementFlags.BUILTIN)) {
var resolvedTypeArguments: Type[] | null = null;
if (expression.typeArguments) {
var k = expression.typeArguments.length;
resolvedTypeArguments = new Array<Type>(k);
for (var i = 0; i < k; ++i) {
2018-02-25 00:13:39 +01:00
var resolvedType = this.program.resolveType( // reports
expression.typeArguments[i],
this.currentFunction.contextualTypeArguments,
true
);
if (!resolvedType) return this.module.createUnreachable();
resolvedTypeArguments[i] = resolvedType;
}
2017-12-01 02:08:03 +01:00
}
2018-02-25 00:13:39 +01:00
var expr = compileBuiltinCall(
this,
functionPrototype,
resolvedTypeArguments,
expression.arguments,
contextualType,
expression
);
if (!expr) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
2017-11-20 23:39:50 +01:00
return this.module.createUnreachable();
}
return expr;
}
// TODO: infer type arguments from parameter types if omitted
2018-02-25 00:13:39 +01:00
functionInstance = functionPrototype.resolveInclTypeArguments( // reports
expression.typeArguments,
this.currentFunction.contextualTypeArguments,
expression
);
if (!functionInstance) return this.module.createUnreachable();
// TODO: generalize? (see above)
/* if (functionInstance.is(ElementFlags.BUILTIN)) {
2018-02-25 00:13:39 +01:00
var expr = compileBuiltinCall(
this,
functionPrototype,
functionInstance.typeArguments,
expression.arguments,
contextualType,
expression
);
if (!expr) {
this.error(DiagnosticCode.Operation_not_supported, expression.range);
return this.module.createUnreachable();
}
return expr;
} */
var numArguments = expression.arguments.length;
2018-02-25 00:13:39 +01:00
var numArgumentsInclThis = functionInstance.instanceMethodOf
? numArguments + 1
: numArguments;
var argumentIndex = 0;
var args = new Array<Expression>(numArgumentsInclThis);
if (functionInstance.instanceMethodOf) {
assert(resolved.targetExpression != null);
args[argumentIndex++] = <Expression>resolved.targetExpression;
2017-11-20 23:39:50 +01:00
}
2018-02-25 00:13:39 +01:00
for (i = 0; i < numArguments; ++i) {
args[argumentIndex++] = expression.arguments[i];
2018-02-25 00:13:39 +01:00
}
return this.compileCall(functionInstance, args, expression);
2017-11-20 23:39:50 +01:00
}
2018-01-28 15:13:31 +01:00
/**
* Compiles a call to a function. If an instance method, `this` is the first element in
* `argumentExpressions` or can be specified explicitly as the last argument.
*/
2018-02-25 00:13:39 +01:00
compileCall(
functionInstance: Function,
argumentExpressions: Expression[],
reportNode: Node,
thisArg: ExpressionRef = 0
): ExpressionRef {
2017-11-26 04:03:28 +01:00
// validate and compile arguments
var parameters = functionInstance.parameters;
2018-02-25 00:13:39 +01:00
var numParameters = parameters ? parameters.length : 0;
var numParametersInclThis = functionInstance.instanceMethodOf != null
? numParameters + 1
: numParameters;
var numArgumentsInclThis = argumentExpressions.length;
2018-02-25 00:13:39 +01:00
var numArguments = functionInstance.instanceMethodOf != null
? numArgumentsInclThis - 1
: numArgumentsInclThis;
if (thisArg) numArgumentsInclThis++;
if (numArgumentsInclThis > numParametersInclThis) { // too many arguments
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Expected_0_arguments_but_got_1,
reportNode.range, numParameters.toString(10), numArguments.toString(10)
2017-11-26 04:03:28 +01:00
);
2017-11-17 14:33:51 +01:00
return this.module.createUnreachable();
}
var operands = new Array<ExpressionRef>(numParametersInclThis);
var operandIndex = 0;
2018-01-28 15:13:31 +01:00
var argumentIndex = 0;
if (functionInstance.instanceMethodOf) {
2018-02-25 00:13:39 +01:00
if (thisArg) {
2018-01-28 15:13:31 +01:00
operands[operandIndex++] = thisArg;
2017-11-20 23:39:50 +01:00
} else {
2018-02-25 00:13:39 +01:00
operands[operandIndex++] = this.compileExpression(
argumentExpressions[argumentIndex++],
functionInstance.instanceMethodOf.type
);
}
}
if (parameters) {
for (; operandIndex < numParametersInclThis; ++operandIndex) {
// argument has been provided
if (numArgumentsInclThis > operandIndex) {
operands[operandIndex] = this.compileExpression(
argumentExpressions[argumentIndex++],
parameters[operandIndex + numParameters - numParametersInclThis].type
2017-11-26 04:03:28 +01:00
);
2018-02-25 00:13:39 +01:00
// argument has been omitted
} else {
var initializer = parameters[operandIndex + numParameters - numParametersInclThis].initializer;
if (initializer) { // fall back to provided initializer
operands[operandIndex] = this.compileExpression(
initializer,
parameters[operandIndex + numParameters - numParametersInclThis].type
);
// FIXME: here, the initializer is compiled in the caller's scope.
// a solution could be to use a stub for each possible overload, calling the
// full function with optional arguments being part of the stub's body.
} else { // too few arguments
this.error(
DiagnosticCode.Expected_at_least_0_arguments_but_got_1,
reportNode.range,
(operandIndex + numParameters - numParametersInclThis).toString(10),
numArguments.toString(10)
);
return this.module.createUnreachable();
}
2017-11-20 23:39:50 +01:00
}
}
}
2017-11-26 04:03:28 +01:00
this.currentType = functionInstance.returnType;
return this.makeCall(functionInstance, operands);
}
2017-12-01 02:08:03 +01:00
/** Makes a call operation as is. */
makeCall(functionInstance: Function, operands: ExpressionRef[] | null = null): ExpressionRef {
2018-02-25 00:13:39 +01:00
if (!(functionInstance.is(ElementFlags.COMPILED) || this.compileFunction(functionInstance))) {
return this.module.createUnreachable();
2018-02-25 00:13:39 +01:00
}
2017-12-01 02:08:03 +01:00
// imported function
2018-02-25 00:13:39 +01:00
if (functionInstance.is(ElementFlags.DECLARED)) {
return this.module.createCallImport(
functionInstance.internalName,
operands,
functionInstance.returnType.toNativeType()
);
}
2017-12-01 02:08:03 +01:00
// internal function
2018-02-25 00:13:39 +01:00
return this.module.createCall(
functionInstance.internalName,
operands,
functionInstance.returnType.toNativeType()
);
2017-09-28 13:08:25 +02:00
}
2018-01-05 01:55:59 +01:00
compileCommaExpression(expression: CommaExpression, contextualType: Type): ExpressionRef {
var expressions = expression.expressions;
var k = expressions.length;
var exprs = new Array<ExpressionRef>(k--);
2018-02-25 00:13:39 +01:00
for (var i = 0; i < k; ++i) {
2018-01-05 01:55:59 +01:00
exprs[i] = this.compileExpression(expressions[i], Type.void); // drop all
2018-02-25 00:13:39 +01:00
}
2018-01-05 01:55:59 +01:00
exprs[i] = this.compileExpression(expressions[i], contextualType); // except last
return this.module.createBlock(null, exprs, this.currentType.toNativeType());
}
2017-11-26 04:03:28 +01:00
compileElementAccessExpression(expression: ElementAccessExpression, contextualType: Type): ExpressionRef {
var resolved = this.program.resolveElementAccess(expression, this.currentFunction); // reports
2018-02-25 00:13:39 +01:00
if (!resolved) return this.module.createUnreachable();
assert(
resolved.element.kind == ElementKind.FUNCTION_PROTOTYPE &&
resolved.target &&
resolved.target.kind == ElementKind.CLASS
);
var instance = (<FunctionPrototype>resolved.element).resolve(
null,
(<Class>resolved.target).contextualTypeArguments
);
if (!instance) return this.module.createUnreachable();
return this.compileCall(instance, [
expression.expression,
expression.elementExpression
], expression);
2017-09-28 13:08:25 +02:00
}
compileFunctionExpression(expression: FunctionExpression, contextualType: Type): ExpressionRef {
var declaration = expression.declaration;
var simpleName = (declaration.name.text.length
? declaration.name.text
: "anonymous") + "|" + this.functionTable.length.toString(10);
var prototype = new FunctionPrototype(
this.program,
simpleName,
this.currentFunction.internalName + "~" + simpleName,
declaration
);
var instance = this.compileFunctionUsingTypeArguments(prototype, [], null, declaration);
if (!instance) return this.module.createUnreachable();
this.currentType = Type.u32.asFunction(instance);
// NOTE that, in order to make this work in every case, the function must be represented by a
// value, so we add it and rely on the optimizer to figure out where it can be called directly.
var index = this.addFunctionTableEntry(instance);
if (index < 0) return this.module.createUnreachable();
return this.module.createI32(index);
}
/**
* Compiles an identifier in the specified context.
* @param retainConstantType Retains the type of inlined constants if `true`, otherwise
* precomputes them according to context.
*/
compileIdentifierExpression(
expression: IdentifierExpression,
contextualType: Type,
retainConstantType: bool
): ExpressionRef {
// check special keywords first
switch (expression.kind) {
case NodeKind.NULL:
2018-02-25 00:13:39 +01:00
if (this.options.isWasm64) {
if (!contextualType.classType) {
assert(contextualType.kind == TypeKind.USIZE);
this.currentType = Type.usize64;
}
return this.module.createI64(0);
}
if (!contextualType.classType) {
assert(contextualType.kind == TypeKind.USIZE);
this.currentType = Type.usize32;
}
return this.module.createI32(0);
case NodeKind.TRUE:
this.currentType = Type.bool;
return this.module.createI32(1);
case NodeKind.FALSE:
this.currentType = Type.bool;
return this.module.createI32(0);
case NodeKind.THIS:
if (this.currentFunction.instanceMethodOf) {
this.currentType = this.currentFunction.instanceMethodOf.type;
return this.module.createGetLocal(0, this.currentType.toNativeType());
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode._this_cannot_be_referenced_in_current_location,
expression.range
);
this.currentType = this.options.isWasm64 ? Type.usize64 : Type.usize32;
return this.module.createUnreachable();
case NodeKind.SUPER:
if (this.currentFunction.instanceMethodOf && this.currentFunction.instanceMethodOf.base) {
this.currentType = this.currentFunction.instanceMethodOf.base.type;
return this.module.createGetLocal(0, this.currentType.toNativeType());
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode._super_can_only_be_referenced_in_a_derived_class,
expression.range
);
this.currentType = this.options.isWasm64 ? Type.usize64 : Type.usize32;
return this.module.createUnreachable();
2017-10-07 14:29:43 +02:00
}
// otherwise resolve
2018-02-25 00:13:39 +01:00
var resolved = this.program.resolveIdentifier( // reports
expression,
this.currentFunction,
this.currentEnum
);
if (!resolved) return this.module.createUnreachable();
var element = resolved.element;
switch (element.kind) {
case ElementKind.LOCAL:
2018-02-25 00:13:39 +01:00
if ((<Local>element).is(ElementFlags.INLINED)) {
return this.compileInlineConstant(<Local>element, contextualType, retainConstantType);
2018-02-25 00:13:39 +01:00
}
assert((<Local>element).index >= 0);
this.currentType = (<Local>element).type;
return this.module.createGetLocal((<Local>element).index, this.currentType.toNativeType());
case ElementKind.GLOBAL:
2018-02-25 00:13:39 +01:00
if (element.is(ElementFlags.BUILTIN)) {
2018-01-05 01:55:59 +01:00
return compileBuiltinGetConstant(this, <Global>element, expression);
2018-02-25 00:13:39 +01:00
}
if (!this.compileGlobal(<Global>element)) { // reports; not yet compiled if a static field
return this.module.createUnreachable();
2018-02-25 00:13:39 +01:00
}
assert((<Global>element).type != Type.void);
2018-02-25 00:13:39 +01:00
if ((<Global>element).is(ElementFlags.INLINED)) {
return this.compileInlineConstant(<Global>element, contextualType, retainConstantType);
2018-02-25 00:13:39 +01:00
}
this.currentType = (<Global>element).type;
return this.module.createGetGlobal((<Global>element).internalName, this.currentType.toNativeType());
2018-01-24 03:08:09 +01:00
case ElementKind.ENUMVALUE: // here: if referenced from within the same enum
if (!element.is(ElementFlags.COMPILED)) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums,
expression.range
);
2018-01-24 03:08:09 +01:00
this.currentType = Type.i32;
return this.module.createUnreachable();
}
this.currentType = Type.i32;
2018-02-25 00:13:39 +01:00
if ((<EnumValue>element).is(ElementFlags.INLINED)) {
2018-01-24 03:08:09 +01:00
return this.module.createI32((<EnumValue>element).constantValue);
2018-02-25 00:13:39 +01:00
}
2018-01-24 03:08:09 +01:00
return this.module.createGetGlobal((<EnumValue>element).internalName, NativeType.I32);
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
2017-09-28 13:08:25 +02:00
}
2018-02-25 00:13:39 +01:00
compileLiteralExpression(
expression: LiteralExpression,
contextualType: Type,
implicitNegate: bool = false
): ExpressionRef {
2017-09-28 13:08:25 +02:00
switch (expression.literalKind) {
2018-01-29 07:42:40 +01:00
case LiteralKind.ARRAY:
assert(!implicitNegate);
2018-01-29 07:42:40 +01:00
var classType = contextualType.classType;
2018-02-25 00:13:39 +01:00
if (
classType &&
classType == this.program.elements.get("Array") &&
classType.typeArguments && classType.typeArguments.length == 1
) {
return this.compileStaticArray(
classType.typeArguments[0],
(<ArrayLiteralExpression>expression).elementExpressions
);
}
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
2018-01-29 07:42:40 +01:00
return this.module.createUnreachable();
2017-09-28 13:08:25 +02:00
case LiteralKind.FLOAT: {
var floatValue = (<FloatLiteralExpression>expression).value;
2018-02-25 00:13:39 +01:00
if (implicitNegate) {
floatValue = -floatValue;
2018-02-25 00:13:39 +01:00
}
if (contextualType == Type.f32) {
return this.module.createF32(<f32>floatValue);
2018-02-25 00:13:39 +01:00
}
2017-09-28 13:08:25 +02:00
this.currentType = Type.f64;
return this.module.createF64(floatValue);
}
2017-09-28 13:08:25 +02:00
case LiteralKind.INTEGER:
var intValue = (<IntegerLiteralExpression>expression).value;
2018-02-25 00:13:39 +01:00
if (implicitNegate) {
intValue = i64_sub(
i64_new(0),
intValue
);
}
switch (contextualType.kind) {
// compile to contextualType if matching
case TypeKind.I8:
2018-02-25 00:13:39 +01:00
if (i64_is_i8(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.I16:
2018-02-25 00:13:39 +01:00
if (i64_is_i16(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.I32:
2018-02-25 00:13:39 +01:00
if (i64_is_i32(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.U8:
2018-02-25 00:13:39 +01:00
if (i64_is_u8(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.U16:
2018-02-25 00:13:39 +01:00
if (i64_is_u16(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.U32:
2018-02-25 00:13:39 +01:00
if (i64_is_u32(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.BOOL:
2018-02-25 00:13:39 +01:00
if (i64_is_bool(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.ISIZE:
if (!this.options.isWasm64) {
2018-02-25 00:13:39 +01:00
if (i64_is_u32(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
}
return this.module.createI64(i64_low(intValue), i64_high(intValue));
case TypeKind.USIZE:
if (!this.options.isWasm64) {
2018-02-25 00:13:39 +01:00
if (i64_is_u32(intValue)) {
return this.module.createI32(i64_low(intValue));
2018-02-25 00:13:39 +01:00
}
break;
}
return this.module.createI64(i64_low(intValue), i64_high(intValue));
case TypeKind.I64:
case TypeKind.U64:
return this.module.createI64(i64_low(intValue), i64_high(intValue));
case TypeKind.F32:
2018-02-25 00:13:39 +01:00
if (i64_is_f32(intValue)) {
return this.module.createF32(i64_to_f32(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.F64:
2018-02-25 00:13:39 +01:00
if (i64_is_f64(intValue)) {
return this.module.createF64(i64_to_f64(intValue));
2018-02-25 00:13:39 +01:00
}
break;
case TypeKind.VOID:
2018-03-02 12:57:33 +01:00
break; // compiles to best fitting type below, being dropped
default:
assert(false);
break;
}
// otherwise compile to best fitting native type
if (i64_is_i32(intValue)) {
this.currentType = Type.i32;
return this.module.createI32(i64_low(intValue));
} else {
2017-12-23 13:48:04 +01:00
this.currentType = Type.i64;
return this.module.createI64(i64_low(intValue), i64_high(intValue));
2017-12-23 13:48:04 +01:00
}
2017-09-28 13:08:25 +02:00
case LiteralKind.STRING:
assert(!implicitNegate);
return this.compileStaticString((<StringLiteralExpression>expression).value);
2017-09-28 13:08:25 +02:00
// case LiteralKind.OBJECT:
// case LiteralKind.REGEXP:
}
2018-03-02 12:57:33 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
this.currentType = contextualType;
return this.module.createUnreachable();
2017-09-28 13:08:25 +02:00
}
compileStaticString(stringValue: string): ExpressionRef {
var stringSegment: MemorySegment | null = this.stringSegments.get(stringValue);
if (!stringSegment) {
var stringLength = stringValue.length;
var stringBuffer = new Uint8Array(4 + stringLength * 2);
stringBuffer[0] = stringLength & 0xff;
stringBuffer[1] = (stringLength >>> 8) & 0xff;
stringBuffer[2] = (stringLength >>> 16) & 0xff;
stringBuffer[3] = (stringLength >>> 24) & 0xff;
for (var i = 0; i < stringLength; ++i) {
stringBuffer[4 + i * 2] = stringValue.charCodeAt(i) & 0xff;
stringBuffer[5 + i * 2] = (stringValue.charCodeAt(i) >>> 8) & 0xff;
}
stringSegment = this.addMemorySegment(stringBuffer, this.options.usizeType.byteSize);
this.stringSegments.set(stringValue, stringSegment);
}
var stringOffset = stringSegment.offset;
var stringType = this.program.types.get("string");
this.currentType = stringType ? stringType : this.options.usizeType;
2018-02-25 00:13:39 +01:00
if (this.options.isWasm64) {
return this.module.createI64(i64_low(stringOffset), i64_high(stringOffset));
2018-02-25 00:13:39 +01:00
}
assert(i64_is_i32(stringOffset));
return this.module.createI32(i64_low(stringOffset));
}
2018-01-29 07:42:40 +01:00
compileStaticArray(elementType: Type, expressions: (Expression | null)[]): ExpressionRef {
// compile as static if all element expressions are precomputable, otherwise
// initialize in place.
var isStatic = true;
var size = expressions.length;
var nativeType = elementType.toNativeType();
var values: usize;
switch (nativeType) {
case NativeType.I32:
values = changetype<usize>(new Int32Array(size));
break;
case NativeType.I64:
values = changetype<usize>(new Array<I64>(size));
break;
case NativeType.F32:
values = changetype<usize>(new Float32Array(size));
break;
case NativeType.F64:
values = changetype<usize>(new Float64Array(size));
break;
default:
throw new Error("concrete type expected");
}
var exprs = new Array<ExpressionRef>(size);
2018-01-29 07:42:40 +01:00
var expr: BinaryenExpressionRef;
for (var i = 0; i < size; ++i) {
2018-02-25 00:13:39 +01:00
exprs[i] = expressions[i]
? this.compileExpression(<Expression>expressions[i], elementType)
: elementType.toNativeZero(this.module);
if (isStatic) {
2018-02-25 00:13:39 +01:00
expr = this.precomputeExpressionRef(exprs[i]);
if (_BinaryenExpressionGetId(expr) == ExpressionId.Const) {
assert(_BinaryenExpressionGetType(expr) == nativeType);
switch (nativeType) {
case NativeType.I32:
changetype<i32[]>(values)[i] = _BinaryenConstGetValueI32(expr);
break;
case NativeType.I64:
2018-02-25 00:13:39 +01:00
changetype<I64[]>(values)[i] = i64_new(
_BinaryenConstGetValueI64Low(expr),
_BinaryenConstGetValueI64High(expr)
);
break;
case NativeType.F32:
changetype<f32[]>(values)[i] = _BinaryenConstGetValueF32(expr);
break;
case NativeType.F64:
changetype<f64[]>(values)[i] = _BinaryenConstGetValueF64(expr);
break;
default:
assert(false); // checked above
}
} else {
// TODO: emit a warning if declared 'const'
isStatic = false;
}
}
}
if (isStatic) {
// TODO: convert to Uint8Array and create the segment
} else {
// TODO: initialize in place
2018-01-29 07:42:40 +01:00
}
// TODO: alternatively, static elements could go into data segments while
// dynamic ones are initialized on top? any benefits? (doesn't seem so)
2018-01-28 23:42:55 +01:00
throw new Error("not implemented");
}
2017-11-26 04:03:28 +01:00
compileNewExpression(expression: NewExpression, contextualType: Type): ExpressionRef {
2018-02-25 00:13:39 +01:00
var resolved = this.program.resolveExpression( // reports
expression.expression,
this.currentFunction
);
if (resolved) {
if (resolved.element.kind == ElementKind.CLASS_PROTOTYPE) {
var prototype = <ClassPrototype>resolved.element;
2018-02-25 00:13:39 +01:00
var instance = prototype.resolveInclTypeArguments( // reports
expression.typeArguments,
null,
expression
);
if (instance) {
2018-01-28 15:13:31 +01:00
var thisExpr = compileBuiltinAllocate(this, instance, expression);
var initializers = new Array<ExpressionRef>();
// use a temp local for 'this'
var tempLocal = this.currentFunction.getTempLocal(this.options.usizeType);
initializers.push(this.module.createSetLocal(tempLocal.index, thisExpr));
// apply field initializers
2018-02-25 00:13:39 +01:00
if (instance.members) {
2018-01-28 15:13:31 +01:00
for (var member of instance.members.values()) {
if (member.kind == ElementKind.FIELD) {
var field = <Field>member;
var fieldDeclaration = field.prototype.declaration;
if (field.is(ElementFlags.CONSTANT)) {
assert(false); // there are no built-in fields currently
} else if (fieldDeclaration && fieldDeclaration.initializer) {
initializers.push(this.module.createStore(field.type.byteSize,
this.module.createGetLocal(tempLocal.index, this.options.nativeSizeType),
this.compileExpression(fieldDeclaration.initializer, field.type),
field.type.toNativeType(),
field.memoryOffset
));
}
}
}
2018-02-25 00:13:39 +01:00
}
2018-01-28 15:13:31 +01:00
// apply constructor
var constructorInstance = instance.constructorInstance;
2018-02-25 00:13:39 +01:00
if (constructorInstance) {
2018-01-28 15:13:31 +01:00
initializers.push(this.compileCall(constructorInstance, expression.arguments, expression,
this.module.createGetLocal(tempLocal.index, this.options.nativeSizeType)
));
2018-02-25 00:13:39 +01:00
}
2018-01-28 15:13:31 +01:00
// return 'this'
initializers.push(this.module.createGetLocal(tempLocal.index, this.options.nativeSizeType));
this.currentFunction.freeTempLocal(tempLocal);
thisExpr = this.module.createBlock(null, initializers, this.options.nativeSizeType);
this.currentType = instance.type;
2018-01-28 15:13:31 +01:00
return thisExpr;
}
2018-02-25 00:13:39 +01:00
} else {
this.error(
DiagnosticCode.Cannot_use_new_with_an_expression_whose_type_lacks_a_construct_signature,
expression.expression.range
);
}
}
return this.module.createUnreachable();
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileParenthesizedExpression(expression: ParenthesizedExpression, contextualType: Type): ExpressionRef {
// does not change types, just order
return this.compileExpression(expression.expression, contextualType, ConversionKind.NONE);
2017-09-28 13:08:25 +02:00
}
/**
* Compiles a property access in the specified context.
* @param retainConstantType Retains the type of inlined constants if `true`, otherwise
* precomputes them according to context.
*/
compilePropertyAccessExpression(
propertyAccess: PropertyAccessExpression,
contextualType: Type,
retainConstantType: bool
): ExpressionRef {
var resolved = this.program.resolvePropertyAccess(propertyAccess, this.currentFunction); // reports
2018-02-25 00:13:39 +01:00
if (!resolved) return this.module.createUnreachable();
2017-12-13 23:24:13 +01:00
var element = resolved.element;
var targetExpr: ExpressionRef;
2017-12-13 23:24:13 +01:00
switch (element.kind) {
case ElementKind.GLOBAL: // static property
2018-02-25 00:13:39 +01:00
if (element.is(ElementFlags.BUILTIN)) {
2018-01-05 01:55:59 +01:00
return compileBuiltinGetConstant(this, <Global>element, propertyAccess);
2018-02-25 00:13:39 +01:00
}
if (!this.compileGlobal(<Global>element)) { // reports; not yet compiled if a static field
2017-12-15 15:00:19 +01:00
return this.module.createUnreachable();
2018-02-25 00:13:39 +01:00
}
assert((<Global>element).type != Type.void);
2018-02-25 00:13:39 +01:00
if ((<Global>element).is(ElementFlags.INLINED)) {
return this.compileInlineConstant(<Global>element, contextualType, retainConstantType);
2018-02-25 00:13:39 +01:00
}
this.currentType = (<Global>element).type;
return this.module.createGetGlobal((<Global>element).internalName, this.currentType.toNativeType());
case ElementKind.ENUMVALUE: // enum value
2018-02-25 00:13:39 +01:00
if (!this.compileEnum((<EnumValue>element).enum)) {
2017-12-13 23:24:13 +01:00
return this.module.createUnreachable();
2018-02-25 00:13:39 +01:00
}
this.currentType = Type.i32;
2018-02-25 00:13:39 +01:00
if ((<EnumValue>element).is(ElementFlags.INLINED)) {
return this.module.createI32((<EnumValue>element).constantValue);
2018-02-25 00:13:39 +01:00
}
return this.module.createGetGlobal((<EnumValue>element).internalName, NativeType.I32);
case ElementKind.FIELD: // instance field
assert(resolved.target != null);
assert(resolved.targetExpression != null);
assert((<Field>element).memoryOffset >= 0);
2018-02-25 00:13:39 +01:00
targetExpr = this.compileExpression(
<Expression>resolved.targetExpression,
this.options.usizeType,
ConversionKind.NONE
2018-02-25 00:13:39 +01:00
);
this.currentType = (<Field>element).type;
2018-02-25 00:13:39 +01:00
return this.module.createLoad(
(<Field>element).type.size >> 3,
(<Field>element).type.is(TypeFlags.SIGNED | TypeFlags.INTEGER),
targetExpr,
(<Field>element).type.toNativeType(),
(<Field>element).memoryOffset
);
case ElementKind.PROPERTY: // instance property (here: getter)
var getter = (<Property>element).getterPrototype;
assert(getter != null);
2018-01-14 21:17:43 +01:00
var getterInstance = (<FunctionPrototype>getter).resolve(null); // reports
2018-02-25 00:13:39 +01:00
if (!getterInstance) return this.module.createUnreachable();
assert(!getterInstance.parameters || !getterInstance.parameters.length);
2018-01-04 01:36:26 +01:00
this.currentType = getterInstance.returnType;
if (getterInstance.is(ElementFlags.INSTANCE)) {
2018-02-25 00:13:39 +01:00
targetExpr = this.compileExpression(
<Expression>resolved.targetExpression,
this.options.usizeType,
ConversionKind.NONE
2018-02-25 00:13:39 +01:00
);
this.currentType = getterInstance.returnType;
return this.makeCall(getterInstance, [ targetExpr ]);
2018-02-25 00:13:39 +01:00
} else {
return this.makeCall(getterInstance);
2018-02-25 00:13:39 +01:00
}
2017-12-13 23:24:13 +01:00
}
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
propertyAccess.range
);
return this.module.createUnreachable();
2017-09-28 13:08:25 +02:00
}
compileTernaryExpression(expression: TernaryExpression, contextualType: Type): ExpressionRef {
var condition = makeIsTrueish(
this.compileExpression(expression.condition, Type.u32, ConversionKind.NONE),
this.currentType,
this.module
);
var ifThen = this.compileExpression(expression.ifThen, contextualType);
var ifElse = this.compileExpression(expression.ifElse, contextualType);
return this.module.createIf(condition, ifThen, ifElse);
2017-09-28 13:08:25 +02:00
}
2017-11-26 04:03:28 +01:00
compileUnaryPostfixExpression(expression: UnaryPostfixExpression, contextualType: Type): ExpressionRef {
2017-12-03 01:18:35 +01:00
// make a getter for the expression (also obtains the type)
2018-02-25 00:13:39 +01:00
var getValue = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
false // wrapped below
);
2017-12-03 01:18:35 +01:00
var op: BinaryOp;
var nativeType: NativeType;
var nativeOne: ExpressionRef;
var possiblyOverflows = false;
2017-10-02 12:52:15 +02:00
switch (expression.operator) {
2017-12-03 01:18:35 +01:00
case Token.PLUS_PLUS:
if (this.currentType.isReference) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
default:
op = BinaryOp.AddI32;
nativeType = NativeType.I32;
nativeOne = this.module.createI32(1);
break;
2017-12-03 01:18:35 +01:00
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
op = this.options.isWasm64
? BinaryOp.AddI64
: BinaryOp.AddI32;
nativeType = this.options.isWasm64
? NativeType.I64
: NativeType.I32;
nativeOne = this.currentType.toNativeOne(this.module);
break;
2017-12-03 01:18:35 +01:00
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.AddI64;
nativeType = NativeType.I64;
nativeOne = this.module.createI64(1);
break;
case TypeKind.F32:
op = BinaryOp.AddF32;
nativeType = NativeType.F32;
nativeOne = this.module.createF32(1);
break;
case TypeKind.F64:
op = BinaryOp.AddF64;
nativeType = NativeType.F64;
nativeOne = this.module.createF64(1);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
case Token.MINUS_MINUS:
if (this.currentType.isReference) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true;
default:
op = BinaryOp.SubI32;
nativeType = NativeType.I32;
nativeOne = this.module.createI32(1);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
op = this.options.isWasm64
? BinaryOp.SubI64
: BinaryOp.SubI32;
nativeType = this.options.isWasm64
? NativeType.I64
: NativeType.I32;
nativeOne = this.currentType.toNativeOne(this.module);
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.SubI64;
nativeType = NativeType.I64;
nativeOne = this.module.createI64(1);
break;
case TypeKind.F32:
op = BinaryOp.SubF32;
nativeType = NativeType.F32;
nativeOne = this.module.createF32(1);
break;
case TypeKind.F64:
op = BinaryOp.SubF64;
nativeType = NativeType.F64;
nativeOne = this.module.createF64(1);
break;
case TypeKind.VOID:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("concrete type expected");
}
break;
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("unary postfix operator expected");
2017-10-02 12:52:15 +02:00
}
var setValue: ExpressionRef;
var tempLocal: Local | null = null;
// simplify if dropped anyway
if (contextualType == Type.void) {
setValue = this.module.createBinary(op,
getValue,
nativeOne
);
2017-12-03 01:18:35 +01:00
// otherwise use a temp local for the intermediate value
} else {
tempLocal = this.currentFunction.getTempLocal(this.currentType);
setValue = this.module.createBinary(op,
this.module.createGetLocal(tempLocal.index, nativeType),
nativeOne
);
}
if (possiblyOverflows) {
assert(this.currentType.is(TypeFlags.SMALL | TypeFlags.INTEGER));
setValue = makeSmallIntegerWrap(setValue, this.currentType, this.module);
}
2018-02-25 00:13:39 +01:00
setValue = this.compileAssignmentWithValue(expression.operand, setValue, false);
// ^ sets currentType = void
if (contextualType == Type.void) {
assert(!tempLocal);
return setValue;
}
this.currentType = assert(tempLocal).type;
this.currentFunction.freeTempLocal(<Local>tempLocal);
2017-10-02 12:52:15 +02:00
return this.module.createBlock(null, [
this.module.createSetLocal((<Local>tempLocal).index, getValue),
2017-12-03 01:18:35 +01:00
setValue,
this.module.createGetLocal((<Local>tempLocal).index, nativeType)
2017-11-26 04:03:28 +01:00
], nativeType);
2017-09-28 13:08:25 +02:00
}
2018-02-25 00:13:39 +01:00
compileUnaryPrefixExpression(
expression: UnaryPrefixExpression,
contextualType: Type,
wrapSmallIntegers: bool = true
): ExpressionRef {
var possiblyOverflows = false;
var compound = false;
var expr: ExpressionRef;
switch (expression.operator) {
case Token.PLUS:
if (this.currentType.isReference) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
2018-02-25 00:13:39 +01:00
expr = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
false // wrapped below
);
possiblyOverflows = this.currentType.is(TypeFlags.SMALL | TypeFlags.INTEGER); // if operand already did
break;
case Token.MINUS:
if (this.currentType.isReference) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
if (expression.operand.kind == NodeKind.LITERAL && (
(<LiteralExpression>expression.operand).literalKind == LiteralKind.INTEGER ||
(<LiteralExpression>expression.operand).literalKind == LiteralKind.FLOAT
)) {
// implicitly negate integer and float literals. also enables proper checking of literal ranges.
expr = this.compileLiteralExpression(<LiteralExpression>expression.operand, contextualType, true);
this.addDebugLocation(expr, expression.range); // compileExpression normally does this
} else {
2018-02-25 00:13:39 +01:00
expr = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
false // wrapped below
);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // or if operand already did
default:
expr = this.module.createBinary(BinaryOp.SubI32, this.module.createI32(0), expr);
break;
case TypeKind.USIZE:
if (this.currentType.isReference) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.SubI64
: BinaryOp.SubI32,
this.currentType.toNativeZero(this.module),
expr
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.SubI64, this.module.createI64(0), expr);
break;
case TypeKind.F32:
expr = this.module.createUnary(UnaryOp.NegF32, expr);
break;
case TypeKind.F64:
expr = this.module.createUnary(UnaryOp.NegF64, expr);
break;
}
}
break;
2017-10-02 12:52:15 +02:00
case Token.PLUS_PLUS:
if (this.currentType.isReference) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
compound = true;
2018-02-25 00:13:39 +01:00
expr = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
false // wrapped below
);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // or if operand already did
default:
expr = this.module.createBinary(BinaryOp.AddI32, expr, this.module.createI32(1));
break;
case TypeKind.USIZE:
if (this.currentType.isReference) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
// fall-through
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.AddI64
: BinaryOp.AddI32,
expr,
this.currentType.toNativeOne(this.module)
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.AddI64, expr, this.module.createI64(1));
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.AddF32, expr, this.module.createF32(1));
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.AddF64, expr, this.module.createF64(1));
break;
}
break;
2017-10-02 12:52:15 +02:00
case Token.MINUS_MINUS:
if (this.currentType.isReference) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
compound = true;
2018-02-25 00:13:39 +01:00
expr = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
false // wrapped below
);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // or if operand already did
// fall-through
default:
expr = this.module.createBinary(BinaryOp.SubI32, expr, this.module.createI32(1));
break;
case TypeKind.USIZE:
if (this.currentType.isReference) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
// fall-through
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.SubI64
: BinaryOp.SubI32,
expr,
this.currentType.toNativeOne(this.module)
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.SubI64, expr, this.module.createI64(1));
break;
case TypeKind.F32:
expr = this.module.createBinary(BinaryOp.SubF32, expr, this.module.createF32(1));
break;
case TypeKind.F64:
expr = this.module.createBinary(BinaryOp.SubF64, expr, this.module.createF64(1));
break;
}
break;
2018-02-25 00:13:39 +01:00
case Token.EXCLAMATION:
expr = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType,
ConversionKind.NONE,
true // must wrap small integers
);
expr = makeIsFalseish(expr, this.currentType, this.module);
this.currentType = Type.bool;
break;
2018-02-25 00:13:39 +01:00
case Token.TILDE:
if (this.currentType.isReference) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
2018-02-25 00:13:39 +01:00
expr = this.compileExpression(
expression.operand,
contextualType == Type.void
? Type.i32
: contextualType.is(TypeFlags.FLOAT)
? Type.i64
: contextualType,
contextualType == Type.void
? ConversionKind.NONE
: ConversionKind.IMPLICIT,
false // retains low bits of small integers
);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
possiblyOverflows = true; // or if operand already did
default:
expr = this.module.createBinary(BinaryOp.XorI32, expr, this.module.createI32(-1));
break;
case TypeKind.USIZE:
if (this.currentType.isReference) {
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
return this.module.createUnreachable();
}
// fall-through
case TypeKind.ISIZE:
2018-02-25 00:13:39 +01:00
expr = this.module.createBinary(
this.options.isWasm64
? BinaryOp.XorI64
: BinaryOp.XorI32,
expr,
this.currentType.toNativeNegOne(this.module)
);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = this.module.createBinary(BinaryOp.XorI64, expr, this.module.createI64(-1, -1));
break;
}
break;
2018-01-15 00:08:06 +01:00
case Token.TYPEOF:
2018-02-25 00:13:39 +01:00
// it might make sense to implement typeof in a way that a generic function can detect
// whether its type argument is a class type or string. that could then be used, for
// example, to generate hash codes for sets and maps, depending on the kind of type
// parameter we have. ideally the comparison would not involve actual string comparison and
// limit available operations to hard-coded string literals.
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
2018-01-15 00:08:06 +01:00
throw new Error("not implemented");
default:
2018-02-25 00:13:39 +01:00
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
throw new Error("unary operator expected");
}
if (possiblyOverflows && wrapSmallIntegers) {
assert(this.currentType.is(TypeFlags.SMALL | TypeFlags.INTEGER));
expr = makeSmallIntegerWrap(expr, this.currentType, this.module);
}
return compound
? this.compileAssignmentWithValue(expression.operand, expr, contextualType != Type.void)
: expr;
2017-09-28 13:08:25 +02:00
}
addDebugLocation(expr: ExpressionRef, range: Range): void {
if (this.options.sourceMap != null) {
var source = range.source;
2018-02-25 00:13:39 +01:00
if (source.debugInfoIndex < 0) {
source.debugInfoIndex = this.module.addDebugInfoFile(source.normalizedPath);
2018-02-25 00:13:39 +01:00
}
range.debugInfoRef = expr;
2018-02-25 00:13:39 +01:00
if (!this.currentFunction.debugLocations) this.currentFunction.debugLocations = [];
this.currentFunction.debugLocations.push(range);
}
}
2017-09-28 13:08:25 +02:00
}
2017-10-02 12:52:15 +02:00
// helpers
2018-02-25 00:13:39 +01:00
/** Wraps a 32-bit integer expression so it evaluates to a valid value of the specified type. */
export function makeSmallIntegerWrap(expr: ExpressionRef, type: Type, module: Module): ExpressionRef {
switch (type.kind) {
case TypeKind.I8:
expr = module.createBinary(BinaryOp.ShrI32,
module.createBinary(BinaryOp.ShlI32,
expr,
module.createI32(24)
),
module.createI32(24)
);
break;
case TypeKind.I16:
expr = module.createBinary(BinaryOp.ShrI32,
module.createBinary(BinaryOp.ShlI32,
expr,
module.createI32(16)
),
module.createI32(16)
);
break;
case TypeKind.U8:
expr = module.createBinary(BinaryOp.AndI32,
expr,
module.createI32(0xff)
);
break;
case TypeKind.U16:
expr = module.createBinary(BinaryOp.AndI32,
expr,
module.createI32(0xffff)
);
break;
case TypeKind.BOOL:
expr = module.createBinary(BinaryOp.AndI32,
expr,
module.createI32(0x1)
);
break;
case TypeKind.VOID:
throw new Error("concrete type expected");
}
return expr;
}
/** Creates a comparison whether an expression is not 'true' in a broader sense. */
export function makeIsFalseish(expr: ExpressionRef, type: Type, module: Module): ExpressionRef {
switch (type.kind) {
default: // any integer up to 32 bits
expr = module.createUnary(UnaryOp.EqzI32, expr);
break;
case TypeKind.I64:
case TypeKind.U64:
expr = module.createUnary(UnaryOp.EqzI64, expr);
break;
case TypeKind.USIZE:
// TODO: strings
case TypeKind.ISIZE:
expr = module.createUnary(type.size == 64 ? UnaryOp.EqzI64 : UnaryOp.EqzI32, expr);
break;
case TypeKind.F32:
expr = module.createBinary(BinaryOp.EqF32, expr, module.createF32(0));
break;
case TypeKind.F64:
expr = module.createBinary(BinaryOp.EqF64, expr, module.createF64(0));
break;
case TypeKind.VOID:
throw new Error("concrete type expected");
}
return expr;
}
/** Creates a comparison whether an expression is 'true' in a broader sense. */
export function makeIsTrueish(
expr: ExpressionRef,
type: Type,
module: Module
): ExpressionRef {
switch (type.kind) {
case TypeKind.I64:
case TypeKind.U64:
expr = module.createBinary(BinaryOp.NeI64, expr, module.createI64(0));
break;
case TypeKind.USIZE:
// TODO: strings
case TypeKind.ISIZE:
if (type.size == 64) {
expr = module.createBinary(BinaryOp.NeI64, expr, module.createI64(0));
}
break;
case TypeKind.F32:
expr = module.createBinary(BinaryOp.NeF32, expr, module.createF32(0));
break;
case TypeKind.F64:
expr = module.createBinary(BinaryOp.NeF64, expr, module.createF64(0));
break;
case TypeKind.VOID:
throw new Error("concrete type expected");
}
return expr;
}