-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcompiler.ts
7060 lines (6681 loc) · 239 KB
/
compiler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The AssemblyScript compiler.
* @module compiler
*//***/
import {
compileCall as compileBuiltinCall,
compileAllocate as compileBuiltinAllocate,
compileAbort as compileBuiltinAbort
} from "./builtins";
import {
DiagnosticCode,
DiagnosticEmitter
} from "./diagnostics";
import {
Module,
MemorySegment,
ExpressionRef,
UnaryOp,
BinaryOp,
NativeType,
FunctionRef,
ExpressionId,
FunctionTypeRef,
GlobalRef,
getExpressionId,
getExpressionType,
getConstValueI32,
getConstValueI64Low,
getConstValueI64High,
getConstValueF32,
getConstValueF64,
getFunctionBody,
getGetLocalIndex
} from "./module";
import {
Program,
ClassPrototype,
Class,
Element,
ElementKind,
Enum,
Field,
FunctionPrototype,
Function,
FunctionTarget,
Global,
Local,
Namespace,
EnumValue,
Property,
VariableLikeElement,
FlowFlags,
CommonFlags,
ConstantValueKind,
Flow,
OperatorKind,
DecoratorFlags,
PATH_DELIMITER,
INNER_DELIMITER,
INSTANCE_DELIMITER,
STATIC_DELIMITER,
GETTER_PREFIX,
SETTER_PREFIX
} from "./program";
import {
Token,
operatorTokenToString
} from "./tokenizer";
import {
Node,
NodeKind,
TypeNode,
Source,
Range,
Statement,
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DoStatement,
EmptyStatement,
EnumDeclaration,
ExportStatement,
ExpressionStatement,
FunctionDeclaration,
ForStatement,
IfStatement,
ImportStatement,
InterfaceDeclaration,
NamespaceDeclaration,
ReturnStatement,
SwitchStatement,
ThrowStatement,
TryStatement,
VariableDeclaration,
VariableStatement,
VoidStatement,
WhileStatement,
Expression,
AssertionExpression,
BinaryExpression,
CallExpression,
CommaExpression,
ElementAccessExpression,
FloatLiteralExpression,
FunctionExpression,
IdentifierExpression,
IntegerLiteralExpression,
LiteralExpression,
LiteralKind,
NewExpression,
ParenthesizedExpression,
PropertyAccessExpression,
TernaryExpression,
ArrayLiteralExpression,
StringLiteralExpression,
UnaryPostfixExpression,
UnaryPrefixExpression,
FieldDeclaration
} from "./ast";
import {
Type,
TypeKind,
TypeFlags,
Signature,
typesToNativeTypes
} from "./types";
import {
writeI32,
writeI64,
writeF32,
writeF64
} from "./util";
/** Compilation target. */
export enum Target {
/** WebAssembly with 32-bit pointers. */
WASM32,
/** WebAssembly with 64-bit pointers. Experimental and not supported by any runtime yet. */
WASM64
}
/** Compiler options. */
export class Options {
/** WebAssembly target. Defaults to {@link Target.WASM32}. */
target: Target = Target.WASM32;
/** If true, compiles everything instead of just reachable code. */
noTreeShaking: bool = false;
/** If true, replaces assertions with nops. */
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;
/** If true, imports the function table provided by the embedder. */
importTable: bool = false;
/** Static memory start offset. */
memoryBase: u32 = 0;
/** If true, generates information necessary for source maps. */
sourceMap: bool = false;
/** Global aliases. */
globalAliases: Map<string,string> | null = null;
/** Tests if the target is WASM64 or, otherwise, WASM32. */
get isWasm64(): bool {
return this.target == Target.WASM64;
}
/** Gets the unsigned size type matching the target. */
get usizeType(): Type {
return this.target == Target.WASM64 ? Type.usize64 : Type.usize32;
}
/** Gets the signed size type matching the target. */
get isizeType(): Type {
return this.target == Target.WASM64 ? Type.isize64 : Type.isize32;
}
/** Gets the native size type matching the target. */
get nativeSizeType(): NativeType {
return this.target == Target.WASM64 ? NativeType.I64 : NativeType.I32;
}
}
/** Indicates the desired kind of a conversion. */
export const enum ConversionKind {
/** No conversion. */
NONE,
/** Implicit conversion. */
IMPLICIT,
/** Explicit conversion. */
EXPLICIT
}
/** Indicates the desired wrap mode of a conversion. */
export const enum WrapMode {
/** No wrapping. */
NONE,
/** Wrap small integer values. */
WRAP
}
/** Compiler interface. */
export class Compiler extends DiagnosticEmitter {
/** Program reference. */
program: Program;
/** Provided options. */
options: Options;
/** Module instance being compiled. */
module: Module;
/** Current function in compilation. */
currentFunction: Function;
/** Outer function in compilation, if compiling a function expression. */
outerFunction: Function | null = null;
/** Current enum in compilation. */
currentEnum: Enum | null = null;
/** Current type in compilation. */
currentType: Type = Type.void;
/** Start function being compiled. */
startFunction: Function;
/** Start function statements. */
startFunctionBody: ExpressionRef[] = [];
/** Counting memory offset. */
memoryOffset: I64;
/** Memory segments being compiled. */
memorySegments: MemorySegment[] = new Array();
/** Map of already compiled static string segments. */
stringSegments: Map<string,MemorySegment> = new Map();
/** Function table being compiled. */
functionTable: Function[] = new Array();
/** Argument count helper global. */
argcVar: GlobalRef = 0;
/** Argument count helper setter. */
argcSet: FunctionRef = 0;
/** Compiles a {@link Program} to a {@link Module} using the specified options. */
static compile(program: Program, options: Options | null = null): Module {
return new Compiler(program, options).compile();
}
/** Constructs a new compiler for a {@link Program} using the specified options. */
constructor(program: Program, options: Options | null = null) {
super(program.diagnostics);
this.program = program;
if (!options) options = new Options();
this.options = options;
this.memoryOffset = i64_new(
max(options.memoryBase, options.usizeType.byteSize) // leave space for `null`
);
this.module = Module.create();
}
/** Performs compilation of the underlying {@link Program} to a {@link Module}. */
compile(): Module {
var options = this.options;
var module = this.module;
var program = this.program;
// initialize lookup maps, built-ins, imports, exports, etc.
program.initialize(options);
// set up the start function wrapping top-level statements, of all files.
var startFunctionPrototype = assert(program.elementsLookup.get("start"));
assert(startFunctionPrototype.kind == ElementKind.FUNCTION_PROTOTYPE);
var startFunctionInstance = new Function(
<FunctionPrototype>startFunctionPrototype,
startFunctionPrototype.internalName,
new Signature([], Type.void)
);
this.startFunction = startFunctionInstance;
this.currentFunction = startFunctionInstance;
// compile entry file(s) while traversing reachable elements
var sources = program.sources;
for (let i = 0, k = sources.length; i < k; ++i) {
if (sources[i].isEntry) this.compileSource(sources[i]);
}
// compile the start function if not empty
var startFunctionBody = this.startFunctionBody;
if (startFunctionBody.length) {
let signature = startFunctionInstance.signature;
let funcRef = module.addFunction(
startFunctionInstance.internalName,
this.ensureFunctionType(
signature.parameterTypes,
signature.returnType,
signature.thisType
),
typesToNativeTypes(startFunctionInstance.additionalLocals),
module.createBlock(null, startFunctionBody)
);
startFunctionInstance.finalize(module, funcRef);
module.setStart(funcRef);
}
// set up static memory segments and the heap base pointer
if (!options.noMemory) {
let memoryOffset = this.memoryOffset;
memoryOffset = i64_align(memoryOffset, options.usizeType.byteSize);
this.memoryOffset = memoryOffset;
if (options.isWasm64) {
module.addGlobal(
"HEAP_BASE",
NativeType.I64,
false,
module.createI64(i64_low(memoryOffset), i64_high(memoryOffset))
);
} else {
module.addGlobal(
"HEAP_BASE",
NativeType.I32,
false,
module.createI32(i64_low(memoryOffset))
);
}
// determine initial page size
let pages = i64_shr_u(i64_align(memoryOffset, 0x10000), i64_new(16, 0));
module.setMemory(
i64_low(pages),
this.options.isWasm64
? Module.MAX_MEMORY_WASM64
: Module.MAX_MEMORY_WASM32,
this.memorySegments,
options.target,
"memory"
);
}
// import memory if requested (default memory is named '0' by Binaryen)
if (options.importMemory) module.addMemoryImport("0", "env", "memory");
// set up function table
var functionTable = this.functionTable;
var functionTableSize = functionTable.length;
var functionTableExported = false;
if (functionTableSize) {
let entries = new Array<FunctionRef>(functionTableSize);
for (let i = 0; i < functionTableSize; ++i) {
entries[i] = functionTable[i].ref;
}
module.setFunctionTable(entries);
module.addTableExport("0", "table");
functionTableExported = true;
}
// import table if requested (default table is named '0' by Binaryen)
if (options.importTable) {
module.addTableImport("0", "env", "table");
if (!functionTableExported) module.addTableExport("0", "table");
}
return module;
}
// sources
/** Compiles a source by looking it up by path first. */
compileSourceByPath(normalizedPathWithoutExtension: string, reportNode: Node): void {
var source = this.program.lookupSourceByPath(normalizedPathWithoutExtension);
if (source) this.compileSource(source);
else {
this.error(
DiagnosticCode.File_0_not_found,
reportNode.range, normalizedPathWithoutExtension
);
}
}
/** Compiles a source. */
compileSource(source: Source): void {
if (source.is(CommonFlags.COMPILED)) return;
source.set(CommonFlags.COMPILED);
// compile top-level statements
var noTreeShaking = this.options.noTreeShaking;
var isEntry = source.isEntry;
var startFunction = this.startFunction;
var startFunctionBody = this.startFunctionBody;
var statements = source.statements;
for (let i = 0, k = statements.length; i < k; ++i) {
let statement = statements[i];
switch (statement.kind) {
case NodeKind.CLASSDECLARATION: {
if (
(noTreeShaking || (isEntry && statement.is(CommonFlags.EXPORT))) &&
!(<ClassDeclaration>statement).isGeneric
) {
this.compileClassDeclaration(<ClassDeclaration>statement, []);
}
break;
}
case NodeKind.INTERFACEDECLARATION: break;
case NodeKind.ENUMDECLARATION: {
if (noTreeShaking || (isEntry && statement.is(CommonFlags.EXPORT))) {
this.compileEnumDeclaration(<EnumDeclaration>statement);
}
break;
}
case NodeKind.FUNCTIONDECLARATION: {
if (
(noTreeShaking || (isEntry && statement.is(CommonFlags.EXPORT))) &&
!(<FunctionDeclaration>statement).isGeneric
) {
this.compileFunctionDeclaration(<FunctionDeclaration>statement, []);
}
break;
}
case NodeKind.IMPORT: {
this.compileSourceByPath(
(<ImportStatement>statement).normalizedPath,
(<ImportStatement>statement).path
);
break;
}
case NodeKind.NAMESPACEDECLARATION: {
if (noTreeShaking || (isEntry && statement.is(CommonFlags.EXPORT))) {
this.compileNamespaceDeclaration(<NamespaceDeclaration>statement);
}
break;
}
case NodeKind.VARIABLE: { // global, always compiled as initializers might have side effects
let variableInit = this.compileVariableStatement(<VariableStatement>statement);
if (variableInit) startFunctionBody.push(variableInit);
break;
}
case NodeKind.EXPORT: {
if ((<ExportStatement>statement).normalizedPath != null) {
this.compileSourceByPath(
<string>(<ExportStatement>statement).normalizedPath,
<StringLiteralExpression>(<ExportStatement>statement).path
);
}
if (noTreeShaking || isEntry) {
this.compileExportStatement(<ExportStatement>statement);
}
break;
}
default: { // otherwise a top-level statement that is part of the start function's body
let previousFunction = this.currentFunction;
this.currentFunction = startFunction;
startFunctionBody.push(this.compileStatement(statement));
this.currentFunction = previousFunction;
break;
}
}
}
}
// globals
compileGlobalDeclaration(declaration: VariableDeclaration): Global | null {
// look up the initialized program element
var element = assert(this.program.elementsLookup.get(declaration.fileLevelInternalName));
assert(element.kind == ElementKind.GLOBAL);
if (!this.compileGlobal(<Global>element)) return null; // reports
return <Global>element;
}
compileGlobal(global: Global): bool {
if (global.is(CommonFlags.COMPILED)) return true;
global.set(CommonFlags.COMPILED);
var module = this.module;
var declaration = global.declaration;
var initExpr: ExpressionRef = 0;
if (global.type == Type.void) { // type is void if not yet resolved or not annotated
if (declaration) {
// resolve now if annotated
if (declaration.type) {
let resolvedType = this.program.resolveType(declaration.type); // reports
if (!resolvedType) return false;
if (resolvedType == Type.void) {
this.error(
DiagnosticCode.Type_expected,
declaration.type.range
);
return false;
}
global.type = resolvedType;
// infer from initializer if not annotated
} else if (declaration.initializer) { // infer type using void/NONE for literal inference
initExpr = this.compileExpression( // reports
declaration.initializer,
Type.void,
ConversionKind.NONE,
WrapMode.WRAP
);
if (this.currentType == Type.void) {
this.error(
DiagnosticCode.Type_0_is_not_assignable_to_type_1,
declaration.initializer.range, this.currentType.toString(), "<auto>"
);
return false;
}
global.type = this.currentType;
// must either be annotated or have an initializer
} else {
this.error(
DiagnosticCode.Type_expected,
declaration.name.range.atEnd
);
return false;
}
} else {
assert(false); // must have a declaration if 'void' (and thus resolved later on)
}
}
// ambient builtins like 'HEAP_BASE' need to be resolved but are added explicitly
if (global.is(CommonFlags.AMBIENT | CommonFlags.BUILTIN)) return true;
var nativeType = global.type.toNativeType();
var isConstant = global.isAny(CommonFlags.CONST) || global.is(CommonFlags.STATIC | CommonFlags.READONLY);
// handle imports
if (global.is(CommonFlags.AMBIENT)) {
// constant global
if (isConstant) {
global.set(CommonFlags.MODULE_IMPORT);
module.addGlobalImport(
global.internalName,
global.parent
? global.parent.simpleName
: "env",
global.simpleName,
nativeType
);
global.set(CommonFlags.COMPILED);
return true;
// importing mutable globals is not supported in the MVP
} else {
this.error(
DiagnosticCode.Operation_not_supported,
assert(declaration).range
);
}
return false;
}
// the MVP does not yet support initializer expressions other than constant values (and
// get_globals), hence such initializations must be performed in the start function for now.
var initializeInStart = false;
// inlined constant can be compiled as-is
if (global.is(CommonFlags.INLINED)) {
initExpr = this.compileInlineConstant(global, global.type, true);
} else {
// evaluate initializer if present
if (declaration && declaration.initializer) {
if (!initExpr) {
initExpr = this.compileExpression(
declaration.initializer,
global.type,
ConversionKind.IMPLICIT,
WrapMode.WRAP
);
}
// check if the initializer is constant
if (getExpressionId(initExpr) != ExpressionId.Const) {
// if a constant global, check if the initializer becomes constant after precompute
if (isConstant) {
initExpr = this.precomputeExpressionRef(initExpr);
if (getExpressionId(initExpr) != ExpressionId.Const) {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
declaration.range
);
initializeInStart = true;
}
} else {
initializeInStart = true;
}
}
// initialize to zero if there's no initializer
} else {
initExpr = global.type.toNativeZero(module);
}
}
var internalName = global.internalName;
if (initializeInStart) { // initialize to mutable zero and set the actual value in start
module.addGlobal(internalName, nativeType, true, global.type.toNativeZero(module));
this.startFunctionBody.push(module.createSetGlobal(internalName, initExpr));
} else { // compile as-is
if (isConstant) {
let exprType = getExpressionType(initExpr);
switch (exprType) {
case NativeType.I32: {
global.constantValueKind = ConstantValueKind.INTEGER;
global.constantIntegerValue = i64_new(getConstValueI32(initExpr), 0);
break;
}
case NativeType.I64: {
global.constantValueKind = ConstantValueKind.INTEGER;
global.constantIntegerValue = i64_new(
getConstValueI64Low(initExpr),
getConstValueI64High(initExpr)
);
break;
}
case NativeType.F32: {
global.constantValueKind = ConstantValueKind.FLOAT;
global.constantFloatValue = getConstValueF32(initExpr);
break;
}
case NativeType.F64: {
global.constantValueKind = ConstantValueKind.FLOAT;
global.constantFloatValue = getConstValueF64(initExpr);
break;
}
default: {
assert(false);
return false;
}
}
global.set(CommonFlags.INLINED); // inline the value from now on
if (global.is(CommonFlags.MODULE_EXPORT)) {
module.addGlobal(internalName, nativeType, false, initExpr);
module.addGlobalExport(internalName, mangleExportName(global));
} else if (declaration && declaration.isTopLevel) { // might become re-exported
module.addGlobal(internalName, nativeType, false, initExpr);
}
} else /* mutable */ {
module.addGlobal(internalName, nativeType, !isConstant, initExpr);
}
}
return true;
}
// enums
compileEnumDeclaration(declaration: EnumDeclaration): Enum | null {
var element = assert(this.program.elementsLookup.get(declaration.fileLevelInternalName));
assert(element.kind == ElementKind.ENUM);
if (!this.compileEnum(<Enum>element)) return null;
return <Enum>element;
}
compileEnum(element: Enum): bool {
if (element.is(CommonFlags.COMPILED)) return true;
element.set(CommonFlags.COMPILED);
var module = this.module;
this.currentEnum = element;
var previousValue: EnumValue | null = null;
if (element.members) {
for (let member of element.members.values()) {
if (member.kind != ElementKind.ENUMVALUE) continue; // happens if an enum is also a namespace
let initInStart = false;
let val = <EnumValue>member;
let valueDeclaration = val.declaration;
val.set(CommonFlags.COMPILED);
if (val.is(CommonFlags.INLINED)) {
if (element.declaration.isTopLevelExport) {
module.addGlobal(
val.internalName,
NativeType.I32,
false, // constant
module.createI32(val.constantValue)
);
}
} else {
let initExpr: ExpressionRef;
if (valueDeclaration.value) {
initExpr = this.compileExpression(
<Expression>valueDeclaration.value,
Type.i32,
ConversionKind.IMPLICIT,
WrapMode.NONE
);
if (getExpressionId(initExpr) != ExpressionId.Const) {
initExpr = this.precomputeExpressionRef(initExpr);
if (getExpressionId(initExpr) != ExpressionId.Const) {
if (element.is(CommonFlags.CONST)) {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
valueDeclaration.range
);
}
initInStart = true;
}
}
} else if (previousValue == null) {
initExpr = module.createI32(0);
} else if (previousValue.is(CommonFlags.INLINED)) {
initExpr = module.createI32(previousValue.constantValue + 1);
} else {
// in TypeScript this errors with TS1061, but actually we can do:
initExpr = module.createBinary(BinaryOp.AddI32,
module.createGetGlobal(previousValue.internalName, NativeType.I32),
module.createI32(1)
);
if (element.is(CommonFlags.CONST)) {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
valueDeclaration.range
);
}
initInStart = true;
}
if (initInStart) {
module.addGlobal(
val.internalName,
NativeType.I32,
true, // mutable
module.createI32(0)
);
this.startFunctionBody.push(module.createSetGlobal(val.internalName, initExpr));
} else {
module.addGlobal(val.internalName, NativeType.I32, false, initExpr);
if (getExpressionType(initExpr) == NativeType.I32) {
val.constantValue = getConstValueI32(initExpr);
val.set(CommonFlags.INLINED);
} else {
assert(false);
val.constantValue = 0;
}
}
}
previousValue = <EnumValue>val;
// export values if the enum is exported
if (element.is(CommonFlags.MODULE_EXPORT)) {
if (member.is(CommonFlags.INLINED)) {
module.addGlobalExport(member.internalName, mangleExportName(member));
} else if (valueDeclaration) {
this.warning(
DiagnosticCode.Cannot_export_a_mutable_global,
valueDeclaration.range
);
}
}
}
}
this.currentEnum = null;
return true;
}
// functions
/** Compiles a top-level function given its declaration. */
compileFunctionDeclaration(
declaration: FunctionDeclaration,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null = null
): Function | null {
var element = assert(this.program.elementsLookup.get(declaration.fileLevelInternalName));
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
return this.compileFunctionUsingTypeArguments( // reports
<FunctionPrototype>element,
typeArguments,
contextualTypeArguments,
null, // no outer scope (is top level)
(<FunctionPrototype>element).declaration.name
);
}
/** Resolves the specified type arguments prior to compiling the resulting function instance. */
compileFunctionUsingTypeArguments(
prototype: FunctionPrototype,
typeArguments: TypeNode[],
contextualTypeArguments: Map<string,Type> | null,
outerScope: Flow | null,
reportNode: Node
): Function | null {
var instance = prototype.resolveUsingTypeArguments( // reports
typeArguments,
contextualTypeArguments,
reportNode
);
if (!instance) return null;
instance.outerScope = outerScope;
if (!this.compileFunction(instance)) return null;
return instance;
}
/** Either reuses or creates the function type matching the specified signature. */
private ensureFunctionType(
parameterTypes: Type[] | null,
returnType: Type,
thisType: Type | null = null
): FunctionTypeRef {
var numParameters = parameterTypes ? parameterTypes.length : 0;
var paramTypes: NativeType[];
var index = 0;
if (thisType) {
paramTypes = new Array(1 + numParameters);
paramTypes[0] = thisType.toNativeType();
index = 1;
} else {
paramTypes = new Array(numParameters);
}
if (parameterTypes) {
for (let i = 0; i < numParameters; ++i, ++index) {
paramTypes[index] = parameterTypes[i].toNativeType();
}
}
var resultType = returnType.toNativeType();
var module = this.module;
var typeRef = module.getFunctionTypeBySignature(resultType, paramTypes);
if (!typeRef) {
let name = Signature.makeSignatureString(parameterTypes, returnType, thisType);
typeRef = module.addFunctionType(name, resultType, paramTypes);
}
return typeRef;
}
/** Compiles a readily resolved function instance. */
compileFunction(instance: Function): bool {
if (instance.is(CommonFlags.COMPILED)) return true;
assert(!instance.is(CommonFlags.AMBIENT | CommonFlags.BUILTIN) || instance.internalName == "abort");
instance.set(CommonFlags.COMPILED);
// check that modifiers are matching but still compile as-is
var declaration = instance.prototype.declaration;
var body = declaration.body;
if (body) {
if (instance.is(CommonFlags.AMBIENT)) {
this.error(
DiagnosticCode.An_implementation_cannot_be_declared_in_ambient_contexts,
declaration.name.range
);
}
} else {
if (!instance.is(CommonFlags.AMBIENT)) {
this.error(
DiagnosticCode.Function_implementation_is_missing_or_not_immediately_following_the_declaration,
declaration.name.range
);
}
}
var ref: FunctionRef;
var signature = instance.signature;
var typeRef = this.ensureFunctionType(signature.parameterTypes, signature.returnType, signature.thisType);
var module = this.module;
if (body) {
let isConstructor = instance.is(CommonFlags.CONSTRUCTOR);
let returnType: Type = instance.signature.returnType;
// compile body
let previousFunction = this.currentFunction;
this.currentFunction = instance;
let flow = instance.flow;
let stmt: ExpressionRef;
if (body.kind == NodeKind.EXPRESSION) { // () => expression
assert(!instance.isAny(CommonFlags.CONSTRUCTOR | CommonFlags.GET | CommonFlags.SET));
assert(instance.is(CommonFlags.ARROW));
stmt = this.compileExpression(
(<ExpressionStatement>body).expression,
returnType,
ConversionKind.IMPLICIT,
WrapMode.NONE
);
flow.set(FlowFlags.RETURNS);
if (!flow.canOverflow(stmt, returnType)) flow.set(FlowFlags.RETURNS_WRAPPED);
} else {
assert(body.kind == NodeKind.BLOCK);
stmt = this.compileStatement(body);
flow.finalize();
if (isConstructor) {
let nativeSizeType = this.options.nativeSizeType;
assert(instance.is(CommonFlags.INSTANCE));
// implicitly return `this` if the constructor doesn't always return on its own
if (!flow.is(FlowFlags.RETURNS)) {
// if all branches are guaranteed to allocate, skip the final conditional allocation
if (flow.is(FlowFlags.ALLOCATES)) {
stmt = module.createBlock(null, [
stmt,
module.createGetLocal(0, nativeSizeType)
], nativeSizeType);
// if not all branches are guaranteed to allocate, also append a conditional allocation
} else {
let parent = assert(instance.parent);
assert(parent.kind == ElementKind.CLASS);
stmt = module.createBlock(null, [
stmt,
module.createTeeLocal(0,
this.makeConditionalAllocate(<Class>parent, declaration.name)
)
], nativeSizeType);
}
}
// make sure all branches return
} else if (returnType != Type.void && !flow.is(FlowFlags.RETURNS)) {
this.error(
DiagnosticCode.A_function_whose_declared_type_is_not_void_must_return_a_value,
declaration.signature.returnType.range
);
}
}
this.currentFunction = previousFunction;
// create the function
ref = module.addFunction(
instance.internalName,
typeRef,
typesToNativeTypes(instance.additionalLocals),
stmt
);
} else {
instance.set(CommonFlags.MODULE_IMPORT);
// create the function import
let parent = instance.prototype.parent;
ref = module.addFunctionImport(
instance.internalName,
parent
? parent.simpleName
: "env",
instance.simpleName,
typeRef
);
}
// check module-level export
if (instance.is(CommonFlags.MODULE_EXPORT)) {
if (signature.requiredParameters < signature.parameterTypes.length) {
// export the trampoline if the function takes optional parameters
instance = this.ensureTrampoline(instance);
this.ensureArgcSet();
}
module.addFunctionExport(instance.internalName, mangleExportName(instance));
}
instance.finalize(module, ref);
return true;
}
// namespaces
compileNamespaceDeclaration(declaration: NamespaceDeclaration): void {
var members = declaration.members;
var noTreeShaking = this.options.noTreeShaking;
for (let i = 0, k = members.length; i < k; ++i) {
let member = members[i];
switch (member.kind) {
case NodeKind.CLASSDECLARATION: {
if (
(noTreeShaking || member.is(CommonFlags.EXPORT)) &&
!(<ClassDeclaration>member).isGeneric
) {
this.compileClassDeclaration(<ClassDeclaration>member, []);
}
break;
}
case NodeKind.INTERFACEDECLARATION: {
if (
(noTreeShaking || member.is(CommonFlags.EXPORT)) &&
!(<InterfaceDeclaration>member).isGeneric
) {
this.compileInterfaceDeclaration(<InterfaceDeclaration>member, []);
}
break;
}
case NodeKind.ENUMDECLARATION: {
if (noTreeShaking || member.is(CommonFlags.EXPORT)) {
this.compileEnumDeclaration(<EnumDeclaration>member);
}
break;
}
case NodeKind.FUNCTIONDECLARATION: {
if (