-
-
Notifications
You must be signed in to change notification settings - Fork 670
/
Copy pathcompiler.ts
10342 lines (9745 loc) · 367 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
/**
* @fileoverview The AssemblyScript compiler.
* @license Apache-2.0
*/
import {
BuiltinNames,
BuiltinContext,
builtins,
compileVisitGlobals,
compileVisitMembers,
compileRTTI,
compileClassInstanceOf,
} from "./builtins";
import {
DiagnosticCode,
DiagnosticEmitter
} from "./diagnostics";
import {
Module,
MemorySegment,
ExpressionRef,
UnaryOp,
BinaryOp,
NativeType,
FunctionRef,
ExpressionId,
GlobalRef,
FeatureFlags,
Index,
getExpressionId,
getExpressionType,
getConstValueI32,
getConstValueI64Low,
getConstValueI64High,
getConstValueF32,
getConstValueF64,
getBlockChildCount,
getBlockChild,
getBlockName,
getLocalGetIndex,
isLocalTee,
getLocalSetIndex,
needsExplicitUnreachable,
getLocalSetValue,
getGlobalGetName,
isGlobalMutable,
hasSideEffects,
getFunctionBody,
getFunctionParams,
getFunctionResults,
getFunctionVars,
createType
} from "./module";
import {
CommonFlags,
INSTANCE_DELIMITER,
STATIC_DELIMITER,
GETTER_PREFIX,
SETTER_PREFIX,
CommonNames,
INDEX_SUFFIX,
Feature,
Target
} from "./common";
import {
Program,
ClassPrototype,
Class,
Element,
ElementKind,
Enum,
Field,
FunctionPrototype,
Function,
FunctionTarget,
Global,
Local,
EnumValue,
Property,
VariableLikeElement,
ConstantValueKind,
OperatorKind,
DecoratorFlags,
PropertyPrototype,
IndexSignature,
File,
mangleInternalName
} from "./program";
import {
FlowFlags,
Flow,
LocalFlags,
ConditionKind,
findUsedLocals
} from "./flow";
import {
Resolver,
ReportMode
} from "./resolver";
import {
Token,
Range,
operatorTokenToString
} from "./tokenizer";
import {
Node,
NodeKind,
DecoratorKind,
AssertionKind,
SourceKind,
Statement,
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DeclarationStatement,
DoStatement,
EmptyStatement,
EnumDeclaration,
ExportDefaultStatement,
ExportStatement,
ExpressionStatement,
FieldDeclaration,
ForStatement,
ForOfStatement,
FunctionDeclaration,
IfStatement,
ImportStatement,
InstanceOfExpression,
NamespaceDeclaration,
ReturnStatement,
SwitchStatement,
ThrowStatement,
TryStatement,
VariableStatement,
VoidStatement,
WhileStatement,
Expression,
AssertionExpression,
BinaryExpression,
CallExpression,
CommaExpression,
ElementAccessExpression,
FloatLiteralExpression,
FunctionExpression,
IdentifierExpression,
IntegerLiteralExpression,
LiteralExpression,
LiteralKind,
NewExpression,
ObjectLiteralExpression,
ParenthesizedExpression,
PropertyAccessExpression,
TernaryExpression,
ArrayLiteralExpression,
StringLiteralExpression,
UnaryPostfixExpression,
UnaryPrefixExpression,
NamedTypeNode,
findDecorator,
isTypeOmitted
} from "./ast";
import {
Type,
TypeKind,
TypeFlags,
Signature,
typesToNativeTypes
} from "./types";
import {
writeI8,
writeI16,
writeI32,
writeI64,
writeF32,
writeF64,
makeMap
} from "./util";
/** Compiler options. */
export class Options {
/** WebAssembly target. Defaults to {@link Target.WASM32}. */
target: Target = Target.WASM32;
/** If true, replaces assertions with nops. */
noAssert: bool = false;
/** If true, imports the memory provided by the embedder. */
importMemory: bool = false;
/** If greater than zero, declare memory as shared by setting max memory to sharedMemory. */
sharedMemory: i32 = 0;
/** If true, imports the function table provided by the embedder. */
importTable: bool = false;
/** If true, exports the function table. */
exportTable: bool = false;
/** If true, generates information necessary for source maps. */
sourceMap: bool = false;
/** If true, generates an explicit start function. */
explicitStart: bool = false;
/** Static memory start offset. */
memoryBase: i32 = 0;
/** Static table start offset. */
tableBase: i32 = 0;
/** Global aliases, mapping alias names as the key to internal names to be aliased as the value. */
globalAliases: Map<string,string> | null = null;
/** Features to activate by default. These are the finished proposals. */
features: Feature = Feature.MUTABLE_GLOBALS;
/** If true, disallows unsafe features in user code. */
noUnsafe: bool = false;
/** If true, enables pedantic diagnostics. */
pedantic: bool = false;
/** Indicates a very low (<64k) memory limit. */
lowMemoryLimit: i32 = 0;
/** Hinted optimize level. Not applied by the compiler itself. */
optimizeLevelHint: i32 = 0;
/** Hinted shrink level. Not applied by the compiler itself. */
shrinkLevelHint: i32 = 0;
/** 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;
}
/** Gets if any optimizations will be performed. */
get willOptimize(): bool {
return this.optimizeLevelHint > 0 || this.shrinkLevelHint > 0;
}
/** Tests if a specific feature is activated. */
hasFeature(feature: Feature): bool {
return (this.features & feature) != 0;
}
}
/** Various constraints in expression compilation. */
export const enum Constraints {
NONE = 0,
/** Must implicitly convert to the target type. */
CONV_IMPLICIT = 1 << 0,
/** Must explicitly convert to the target type. */
CONV_EXPLICIT = 1 << 1,
/** Must wrap small integer values to match the target type. */
MUST_WRAP = 1 << 2,
/** Indicates that the value will be dropped immediately. */
WILL_DROP = 1 << 3,
/** Indicates that the value will be retained immediately. */
WILL_RETAIN = 1 << 4,
/** Indicates that static data is preferred. */
PREFER_STATIC = 1 << 5
}
/** Runtime features to be activated by the compiler. */
export const enum RuntimeFeatures {
NONE = 0,
/** Requires heap setup. */
HEAP = 1 << 0,
/** Requires runtime type information setup. */
RTTI = 1 << 1,
/** Requires the built-in globals visitor. */
visitGlobals = 1 << 2,
/** Requires the built-in members visitor. */
visitMembers = 1 << 3
}
/** Exported names of compiler-generated elements. */
export namespace ExportNames {
/** Name of the explicit start function, if applicable. */
export const start = "_start"; // match WASI
/** Name of the argumentsLength varargs helper global. */
export const argumentsLength = "__argumentsLength";
/** Name of the alternative argumentsLength setter function. */
export const setArgumentsLength = "__setArgumentsLength";
/** Name of the memory instance, if exported. */
export const memory = "memory";
/** Name of the table instance, if exported. */
export const table = "table";
}
/** Compiler interface. */
export class Compiler extends DiagnosticEmitter {
/** Program reference. */
program: Program;
/** Resolver reference. */
get resolver(): Resolver { return this.program.resolver; }
/** Provided options. */
get options(): Options { return this.program.options; }
/** Module instance being compiled. */
module: Module;
/** Current control flow. */
currentFlow: Flow;
/** Current parent element if not a function, i.e. an enum or namespace. */
currentParent: Element | null = null;
/** Current type in compilation. */
currentType: Type = Type.void;
/** Start function statements. */
currentBody: ExpressionRef[];
/** Counting memory offset. */
memoryOffset: i64;
/** Memory segments being compiled. */
memorySegments: MemorySegment[] = [];
/** Map of already compiled static string segments. */
stringSegments: Map<string,MemorySegment> = new Map();
/** Function table being compiled. First elem is blank. */
functionTable: Function[] = [];
/** Arguments length helper global. */
builtinArgumentsLength: GlobalRef = 0;
/** Requires runtime features. */
runtimeFeatures: RuntimeFeatures = RuntimeFeatures.NONE;
/** Expressions known to have skipped an autorelease. Usually function returns. */
skippedAutoreleases: Set<ExpressionRef> = new Set();
/** Current inline functions stack. */
inlineStack: Function[] = [];
/** Lazily compiled library functions. */
lazyLibraryFunctions: Set<Function> = new Set();
/** Pending class-specific instanceof helpers. */
pendingClassInstanceOf: Set<ClassPrototype> = new Set();
/** Functions potentially involving a virtual call. */
virtualCalls: Set<Function> = new Set();
/** Compiles a {@link Program} to a {@link Module} using the specified options. */
static compile(program: Program): Module {
return new Compiler(program).compile();
}
/** Constructs a new compiler for a {@link Program} using the specified options. */
constructor(program: Program) {
super(program.diagnostics);
this.program = program;
var options = program.options;
var module = Module.create();
this.module = module;
if (options.memoryBase) {
this.memoryOffset = i64_new(options.memoryBase);
module.setLowMemoryUnused(false);
} else {
if (!options.lowMemoryLimit && options.optimizeLevelHint >= 2) {
this.memoryOffset = i64_new(1024);
module.setLowMemoryUnused(true);
} else {
this.memoryOffset = i64_new(8);
module.setLowMemoryUnused(false);
}
}
var featureFlags: FeatureFlags = 0;
if (options.hasFeature(Feature.SIGN_EXTENSION)) featureFlags |= FeatureFlags.SignExt;
if (options.hasFeature(Feature.MUTABLE_GLOBALS)) featureFlags |= FeatureFlags.MutableGloabls;
if (options.hasFeature(Feature.NONTRAPPING_F2I)) featureFlags |= FeatureFlags.NontrappingFPToInt;
if (options.hasFeature(Feature.BULK_MEMORY)) featureFlags |= FeatureFlags.BulkMemory;
if (options.hasFeature(Feature.SIMD)) featureFlags |= FeatureFlags.SIMD128;
if (options.hasFeature(Feature.THREADS)) featureFlags |= FeatureFlags.Atomics;
if (options.hasFeature(Feature.EXCEPTION_HANDLING)) featureFlags |= FeatureFlags.ExceptionHandling;
if (options.hasFeature(Feature.TAIL_CALLS)) featureFlags |= FeatureFlags.TailCall;
if (options.hasFeature(Feature.REFERENCE_TYPES)) featureFlags |= FeatureFlags.ReferenceTypes;
if (options.hasFeature(Feature.MULTI_VALUE)) featureFlags |= FeatureFlags.MultiValue;
module.setFeatures(featureFlags);
}
initializeProgram(): void {
// initialize lookup maps, built-ins, imports, exports, etc.
this.program.initialize(this.options);
}
/** 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;
// check and perform this program initialization if it hasn't been done
this.initializeProgram();
// set up the main start function
var startFunctionInstance = program.makeNativeFunction(BuiltinNames.start, new Signature(program, [], Type.void));
startFunctionInstance.internalName = BuiltinNames.start;
var startFunctionBody = new Array<ExpressionRef>();
this.currentFlow = startFunctionInstance.flow;
this.currentBody = startFunctionBody;
// add mutable heap and rtti base dummies
if (options.isWasm64) {
module.addGlobal(BuiltinNames.heap_base, NativeType.I64, true, module.i64(0));
module.addGlobal(BuiltinNames.rtti_base, NativeType.I64, true, module.i64(0));
} else {
module.addGlobal(BuiltinNames.heap_base, NativeType.I32, true, module.i32(0));
module.addGlobal(BuiltinNames.rtti_base, NativeType.I32, true, module.i32(0));
}
// compile entry file(s) while traversing reachable elements
var files = program.filesByName;
// TODO: for (let file of files.values()) {
for (let _values = Map_values(files), i = 0, k = _values.length; i < k; ++i) {
let file = unchecked(_values[i]);
if (file.source.sourceKind == SourceKind.USER_ENTRY) {
this.compileFile(file);
this.compileExports(file);
}
}
// compile the start function if not empty or if explicitly requested
var startIsEmpty = !startFunctionBody.length;
var explicitStart = program.isWasi || options.explicitStart;
if (!startIsEmpty || explicitStart) {
let signature = startFunctionInstance.signature;
if (!startIsEmpty && explicitStart) {
module.addGlobal(BuiltinNames.started, NativeType.I32, true, module.i32(0));
startFunctionBody.unshift(
module.if(
module.global_get(BuiltinNames.started, NativeType.I32),
module.return(),
module.global_set(BuiltinNames.started, module.i32(1))
)
);
}
let funcRef = module.addFunction(
startFunctionInstance.internalName,
signature.nativeParams,
signature.nativeResults,
typesToNativeTypes(startFunctionInstance.additionalLocals),
module.flatten(startFunctionBody)
);
startFunctionInstance.finalize(module, funcRef);
if (!explicitStart) module.setStart(funcRef);
else module.addFunctionExport(startFunctionInstance.internalName, ExportNames.start);
}
// check if the entire program is acyclic
var cyclicClasses = program.findCyclicClasses();
if (cyclicClasses.size) {
if (options.pedantic) {
// TODO: for (let classInstance of cyclicClasses) {
for (let _values = Set_values(cyclicClasses), i = 0, k = _values.length; i < k; ++i) {
let classInstance = unchecked(_values[i]);
this.pedantic(
DiagnosticCode.Type_0_is_cyclic_Module_will_include_deferred_garbage_collection,
classInstance.identifierNode.range, classInstance.internalName
);
}
}
} else {
program.registerConstantInteger("__GC_ALL_ACYCLIC", Type.bool, i64_new(1, 0));
}
// compile lazy library functions
var lazyLibraryFunctions = this.lazyLibraryFunctions;
do {
let functionsToCompile = new Array<Function>();
// TODO: for (let instance of lazyLibraryFunctions) {
for (let _values = Set_values(lazyLibraryFunctions), i = 0, k = _values.length; i < k; ++i) {
let instance = unchecked(_values[i]);
functionsToCompile.push(instance);
}
lazyLibraryFunctions.clear();
for (let i = 0, k = functionsToCompile.length; i < k; ++i) {
this.compileFunction(unchecked(functionsToCompile[i]), true);
}
} while (lazyLibraryFunctions.size);
// compile pending class-specific instanceof helpers
// TODO: for (let prototype of this.pendingClassInstanceOf.values()) {
for (let _values = Set_values(this.pendingClassInstanceOf), i = 0, k = _values.length; i < k; ++i) {
let prototype = unchecked(_values[i]);
compileClassInstanceOf(this, prototype);
}
// set up virtual lookup tables
var functionTable = this.functionTable;
for (let i = 0, k = functionTable.length; i < k; ++i) {
let instance = functionTable[i];
if (instance.is(CommonFlags.VIRTUAL)) {
assert(instance.is(CommonFlags.INSTANCE));
this.makeVirtual(instance);
}
}
var virtualCalls = this.virtualCalls;
for (let _values = Set_values(virtualCalls), i = 0, k = _values.length; i < k; ++i) {
let instance = unchecked(_values[i]);
this.makeVirtual(instance);
}
// finalize runtime features
module.removeGlobal(BuiltinNames.rtti_base);
if (this.runtimeFeatures & RuntimeFeatures.RTTI) compileRTTI(this);
if (this.runtimeFeatures & RuntimeFeatures.visitGlobals) compileVisitGlobals(this);
if (this.runtimeFeatures & RuntimeFeatures.visitMembers) compileVisitMembers(this);
// update the heap base pointer
var memoryOffset = this.memoryOffset;
memoryOffset = i64_align(memoryOffset, options.usizeType.byteSize);
var lowMemoryLimit32 = this.options.lowMemoryLimit;
if (lowMemoryLimit32) {
let lowMemoryLimit = i64_new(lowMemoryLimit32 & ~15);
if (i64_gt(memoryOffset, lowMemoryLimit)) {
this.error(
DiagnosticCode.Low_memory_limit_exceeded_by_static_data_0_1,
null, i64_to_string(memoryOffset), i64_to_string(lowMemoryLimit)
);
}
}
this.memoryOffset = memoryOffset;
module.removeGlobal(BuiltinNames.heap_base);
if (this.runtimeFeatures & RuntimeFeatures.HEAP) {
if (options.isWasm64) {
module.addGlobal(
BuiltinNames.heap_base,
NativeType.I64,
false,
module.i64(i64_low(memoryOffset), i64_high(memoryOffset))
);
} else {
module.addGlobal(
BuiltinNames.heap_base,
NativeType.I32,
false,
module.i32(i64_low(memoryOffset))
);
}
}
// set up memory
var isSharedMemory = options.hasFeature(Feature.THREADS) && options.sharedMemory > 0;
module.setMemory(
this.options.memoryBase /* is specified */ || this.memorySegments.length
? i64_low(i64_shr_u(i64_align(memoryOffset, 0x10000), i64_new(16)))
: 0,
isSharedMemory ? options.sharedMemory : Module.UNLIMITED_MEMORY,
this.memorySegments,
options.target,
ExportNames.memory,
isSharedMemory
);
// import memory if requested (default memory is named '0' by Binaryen)
if (options.importMemory) module.addMemoryImport("0", "env", "memory", isSharedMemory);
// set up function table (first elem is blank)
var tableBase = this.options.tableBase;
if (!tableBase) tableBase = 1; // leave first elem blank
var functionTableNames = new Array<string>(functionTable.length);
for (let i = 0, k = functionTable.length; i < k; ++i) {
functionTableNames[i] = functionTable[i].internalName;
}
module.setFunctionTable(tableBase + functionTable.length, Module.UNLIMITED_TABLE, functionTableNames, module.i32(tableBase));
// import and/or export table if requested (default table is named '0' by Binaryen)
if (options.importTable) {
module.addTableImport("0", "env", "table");
if (options.pedantic && options.willOptimize) {
this.pedantic(
DiagnosticCode.Importing_the_table_disables_some_indirect_call_optimizations,
null
);
}
}
if (options.exportTable) {
module.addTableExport("0", ExportNames.table);
if (options.pedantic && options.willOptimize) {
this.pedantic(
DiagnosticCode.Exporting_the_table_disables_some_indirect_call_optimizations,
null
);
}
}
// set up module exports
// TODO: for (let file of this.program.filesByName.values()) {
for (let _values = Map_values(this.program.filesByName), i = 0, k = _values.length; i < k; ++i) {
let file = unchecked(_values[i]);
if (file.source.sourceKind == SourceKind.USER_ENTRY) this.ensureModuleExports(file);
}
return module;
}
/** Makes a normally compiled function virtual by injecting a vtable. */
private makeVirtual(instance: Function): void {
// Check if this function has already been processed
var ref = instance.ref;
var body = getFunctionBody(ref);
if (getExpressionId(body) == ExpressionId.Block && getBlockName(body) == "vt") return;
// Wouldn't be here if there wasn't at least one overload
var overloadPrototypes = assert(instance.prototype.overloads);
assert(overloadPrototypes.size);
var module = this.module;
var usizeType = this.options.usizeType;
var usizeSize = usizeType.byteSize;
var isWasm64 = usizeSize == 8;
var nativeSizeType = usizeType.toNativeType();
// Add an additional temporary local holding this's class id
var vars = getFunctionVars(ref);
var tempIndex = 1 + instance.signature.parameterTypes.length + vars.length;
vars.push(NativeType.I32);
// Check that this's class id is what we expect if we don't call an overload
if (!this.options.noAssert) {
let parent = instance.parent;
let actualParent = parent.kind == ElementKind.PROPERTY
? parent.parent
: parent;
assert(actualParent.kind == ElementKind.CLASS);
body = module.if(
module.binary(BinaryOp.EqI32,
module.local_get(tempIndex, NativeType.I32),
module.i32((<Class>actualParent).id)
),
body,
module.unreachable() // TODO: abort?
);
}
// A method's `overloads` property contains its unbound overload prototypes
// so we first have to find the concrete classes it became bound to, obtain
// their bound prototypes and make sure these are resolved and compiled as
// we are going to call them conditionally based on this's class id.
for (let _values = Set_values(overloadPrototypes), i = 0, k = _values.length; i < k; ++i) {
let unboundOverloadPrototype = _values[i];
assert(!unboundOverloadPrototype.isBound);
let unboundOverloadParent = unboundOverloadPrototype.parent;
assert(unboundOverloadParent.kind == ElementKind.CLASS_PROTOTYPE);
let classInstances = (<ClassPrototype>unboundOverloadParent).instances;
if (classInstances) {
for (let _values = Map_values(classInstances), j = 0, l = _values.length; j < l; ++j) {
let classInstance = _values[j];
let boundPrototype = assert(classInstance.members!.get(unboundOverloadPrototype.name));
assert(boundPrototype.kind == ElementKind.FUNCTION_PROTOTYPE);
let overloadInstance = this.resolver.resolveFunction(<FunctionPrototype>boundPrototype, instance.typeArguments);
if (!overloadInstance || !this.compileFunction(overloadInstance)) continue;
let parameterTypes = overloadInstance.signature.parameterTypes;
let numParameters = parameterTypes.length;
let paramExprs = new Array<ExpressionRef>(1 + numParameters);
paramExprs[0] = module.local_get(0, nativeSizeType); // this
for (let n = 0; n < numParameters; ++n) {
paramExprs[1 + n] = module.local_get(1 + n, parameterTypes[n].toNativeType());
}
// TODO: verify signature and use trampoline if overload has additional
// optional parameters.
// TODO: split this into two functions, one with the actual code and one
// with the vtable since calling the super function must circumvent the
// vtable. Perhaps, if we know we are inserting a vtable, we'd generate
// a stub for the vtable function using the function's original name,
// and generate the code function right away as |virtual?
body = module.if(
module.binary(BinaryOp.EqI32,
module.local_get(tempIndex, NativeType.I32),
module.i32(classInstance.id)
),
module.call(overloadInstance.internalName, paramExprs, overloadInstance.signature.returnType.toNativeType()),
body
);
}
}
}
// Finally replace the function and mark it with a vtable block
body = module.block("vt", [
module.local_set(tempIndex, // BLOCK(this)#id @ this - 8
module.load(4, false,
module.binary(
isWasm64
? BinaryOp.SubI64
: BinaryOp.SubI32,
module.local_get(0, nativeSizeType),
isWasm64
? module.i64(8)
: module.i32(8)
),
NativeType.I32
)
),
body
], getExpressionType(body));
var prevParams = getFunctionParams(ref);
var prevResults = getFunctionResults(ref);
module.removeFunction(instance.internalName);
module.addFunction(instance.internalName, prevParams, prevResults, vars, body);
}
// === Exports ==================================================================================
/** Applies the respective module exports for the specified file. */
private ensureModuleExports(file: File): void {
var exports = file.exports;
if (exports) {
// TODO: for (let [elementName, element] of exports) {
for (let _keys = Map_keys(exports), i = 0, k = _keys.length; i < k; ++i) {
let elementName = unchecked(_keys[i]);
let element = assert(exports.get(elementName));
this.ensureModuleExport(elementName, element);
}
}
var exportsStar = file.exportsStar;
if (exportsStar) {
for (let i = 0, k = exportsStar.length; i < k; ++i) {
this.ensureModuleExports(exportsStar[i]);
}
}
}
/** Applies the respective module export(s) for the specified element. */
private ensureModuleExport(name: string, element: Element, prefix: string = ""): void {
switch (element.kind) {
// traverse instances
case ElementKind.FUNCTION_PROTOTYPE: {
let functionInstances = (<FunctionPrototype>element).instances;
if (functionInstances) {
// TODO: for (let instance of instances.values()) {
for (let _values = Map_values(functionInstances), i = 0, k = _values.length; i < k; ++i) {
let instance = unchecked(_values[i]);
let instanceName = name;
if (instance.is(CommonFlags.GENERIC)) {
let fullName = instance.internalName;
instanceName += fullName.substring(fullName.lastIndexOf("<"));
}
this.ensureModuleExport(instanceName, instance, prefix);
}
}
break;
}
case ElementKind.CLASS_PROTOTYPE: {
let classInstances = (<ClassPrototype>element).instances;
if (classInstances) {
// TODO: for (let instance of instances.values()) {
for (let _values = Map_values(classInstances), i = 0, k = _values.length; i < k; ++i) {
let instance = unchecked(_values[i]);
let instanceName = name;
if (instance.is(CommonFlags.GENERIC)) {
let fullName = instance.internalName;
instanceName += fullName.substring(fullName.lastIndexOf("<"));
}
this.ensureModuleExport(instanceName, instance, prefix);
}
}
break;
}
case ElementKind.PROPERTY_PROTOTYPE: {
let propertyPrototype = <PropertyPrototype>element;
let getterPrototype = propertyPrototype.getterPrototype;
if (getterPrototype) this.ensureModuleExport(GETTER_PREFIX + name, getterPrototype, prefix);
let setterPrototype = propertyPrototype.setterPrototype;
if (setterPrototype) this.ensureModuleExport(SETTER_PREFIX + name, setterPrototype, prefix);
break;
}
// export concrete elements
case ElementKind.GLOBAL: {
let global = <Global>element;
let isConst = global.is(CommonFlags.CONST) || global.is(CommonFlags.STATIC | CommonFlags.READONLY);
if (!isConst && !this.options.hasFeature(Feature.MUTABLE_GLOBALS)) {
this.error(
DiagnosticCode.Cannot_export_a_mutable_global,
global.identifierNode.range
);
} else {
this.module.addGlobalExport(element.internalName, prefix + name);
}
break;
}
case ElementKind.ENUMVALUE: {
let enumValue = <EnumValue>element;
if (!enumValue.isImmutable && !this.options.hasFeature(Feature.MUTABLE_GLOBALS)) {
this.error(
DiagnosticCode.Cannot_export_a_mutable_global,
enumValue.identifierNode.range
);
} else {
this.module.addGlobalExport(element.internalName, prefix + name);
}
break;
}
case ElementKind.FUNCTION: {
let functionInstance = <Function>element;
let signature = functionInstance.signature;
if (signature.requiredParameters < signature.parameterTypes.length) {
// utilize trampoline to fill in omitted arguments
functionInstance = this.ensureTrampoline(functionInstance);
this.ensureBuiltinArgumentsLength();
}
if (functionInstance.is(CommonFlags.COMPILED)) this.module.addFunctionExport(functionInstance.internalName, prefix + name);
break;
}
case ElementKind.PROPERTY: {
let propertyInstance = <Property>element;
let getter = propertyInstance.getterInstance;
if (getter) this.ensureModuleExport(GETTER_PREFIX + name, getter, prefix);
let setter = propertyInstance.setterInstance;
if (setter) this.ensureModuleExport(SETTER_PREFIX + name, setter, prefix);
break;
}
case ElementKind.FIELD: {
let fieldInstance = <Field>element;
if (element.is(CommonFlags.COMPILED)) {
let module = this.module;
module.addFunctionExport(fieldInstance.internalGetterName, prefix + GETTER_PREFIX + name);
if (!element.is(CommonFlags.READONLY)) {
module.addFunctionExport(fieldInstance.internalSetterName, prefix + SETTER_PREFIX + name);
}
}
break;
}
case ElementKind.CLASS: {
let classInstance = <Class>element;
// make the class name itself represent its runtime id
if (!classInstance.type.isUnmanaged) {
let module = this.module;
let internalName = classInstance.internalName;
module.addGlobal(internalName, NativeType.I32, false, module.i32(classInstance.id));
module.addGlobalExport(internalName, prefix + name);
}
break;
}
// just traverse members below
case ElementKind.ENUM:
case ElementKind.NAMESPACE:
case ElementKind.TYPEDEFINITION:
case ElementKind.INDEXSIGNATURE: break;
default: assert(false); // unexpected module export
}
// traverse members
var members = element.members;
if (members) {
let subPrefix = prefix + name + (element.kind == ElementKind.CLASS
? INSTANCE_DELIMITER
: STATIC_DELIMITER
);
if (element.kind == ElementKind.NAMESPACE) {
let implicitExport = element.is(CommonFlags.SCOPED);
// TODO: for (let [memberName, member] of members) {
for (let _keys = Map_keys(members), i = 0, k = _keys.length; i < k; ++i) {
let memberName = unchecked(_keys[i]);
let member = assert(members.get(memberName));
if (implicitExport || member.is(CommonFlags.EXPORT)) {
this.ensureModuleExport(memberName, member, subPrefix);
}
}
} else {
// TODO: for (let [memberName, member] of members) {
for (let _keys = Map_keys(members), i = 0, k = _keys.length; i < k; ++i) {
let memberName = unchecked(_keys[i]);
let member = assert(members.get(memberName));
if (!member.is(CommonFlags.PRIVATE)) {
this.ensureModuleExport(memberName, member, subPrefix);
}
}
}
}
}
// === Elements =================================================================================
/** Compiles any element. */
compileElement(element: Element, compileMembers: bool = true): void {
switch (element.kind) {
case ElementKind.GLOBAL: {
this.compileGlobal(<Global>element);
break;
}
case ElementKind.ENUM: {
this.compileEnum(<Enum>element);
break;
}
case ElementKind.FUNCTION_PROTOTYPE: {
if (!element.is(CommonFlags.GENERIC)) {
let instance = this.resolver.resolveFunction(<FunctionPrototype>element, null);
if (instance) this.compileFunction(instance);
}
break;
}
case ElementKind.CLASS_PROTOTYPE: {
if (!element.is(CommonFlags.GENERIC)) {
let instance = this.resolver.resolveClass(<ClassPrototype>element, null);
if (instance) this.compileClass(instance);
}
break;
}
case ElementKind.PROPERTY_PROTOTYPE: {
let propertyPrototype = <PropertyPrototype>element;
let getterPrototype = propertyPrototype.getterPrototype;
if (getterPrototype) {
assert(!getterPrototype.is(CommonFlags.GENERIC));
let instance = this.resolver.resolveFunction(getterPrototype, null);
if (instance) this.compileFunction(instance);
}
let setterPrototype = propertyPrototype.setterPrototype;
if (setterPrototype) {
assert(!setterPrototype.is(CommonFlags.GENERIC));
let instance = this.resolver.resolveFunction(setterPrototype, null);
if (instance) this.compileFunction(instance);
}
break;
}
case ElementKind.NAMESPACE:
case ElementKind.TYPEDEFINITION:
case ElementKind.ENUMVALUE:
case ElementKind.INDEXSIGNATURE: break;
default: assert(false);
}
if (compileMembers) {
let members = element.members;
if (members) {
// TODO: for (let element of members.values()) {
for (let _values = Map_values(members), i = 0, k = _values.length; i < k; ++i) {
let element = unchecked(_values[i]);
this.compileElement(element);
}
}
}
}
/** Compiles a file's exports. */
compileExports(file: File): void {
var exports = file.exports;
if (exports) {
// TODO: for (let element of exports.values()) {
for (let _values = Map_values(exports), i = 0, k = _values.length; i < k; ++i) {
let element = unchecked(_values[i]);
this.compileElement(element);
}
}
var exportsStar = file.exportsStar;
if (exportsStar) {
for (let i = 0, k = exportsStar.length; i < k; ++i) {
let exportStar = unchecked(exportsStar[i]);
this.compileFile(exportStar);
this.compileExports(exportStar);
}
}
}
// files
/** Compiles the file matching the specified path. */
compileFileByPath(normalizedPathWithoutExtension: string, reportNode: Node): void {
var file: File;
var filesByName = this.program.filesByName;
var pathWithIndex: string;
if (filesByName.has(normalizedPathWithoutExtension)) {
file = assert(filesByName.get(normalizedPathWithoutExtension));
} else if (filesByName.has(pathWithIndex = normalizedPathWithoutExtension + INDEX_SUFFIX)) {
file = assert(filesByName.get(pathWithIndex));
} else {
this.error(
DiagnosticCode.File_0_not_found,
reportNode.range, normalizedPathWithoutExtension
);
return;
}
this.compileFile(file);
}
/** Compiles the specified file. */
compileFile(file: File): void {
if (file.is(CommonFlags.COMPILED)) return;
file.set(CommonFlags.COMPILED);
// compile top-level statements within the file's start function
var startFunction = file.startFunction;
var startSignature = startFunction.signature;