-
-
Notifications
You must be signed in to change notification settings - Fork 670
/
Copy pathcompiler.ts
7830 lines (7394 loc) · 266 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,
compileAbort,
compileIterateRoots,
ensureGCHook
} 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,
getGetLocalIndex,
getBlockChildCount,
getBlockChild,
getBlockName,
needsExplicitUnreachable
} from "./module";
import {
CommonFlags,
PATH_DELIMITER,
INNER_DELIMITER,
INSTANCE_DELIMITER,
STATIC_DELIMITER,
GETTER_PREFIX,
SETTER_PREFIX
} from "./common";
import {
Program,
ClassPrototype,
Class,
Element,
ElementKind,
Enum,
Field,
FunctionPrototype,
Function,
FunctionTarget,
Global,
Local,
Namespace,
EnumValue,
Property,
VariableLikeElement,
FlowFlags,
ConstantValueKind,
Flow,
OperatorKind,
DecoratorFlags
} from "./program";
import {
Resolver, ReportMode
} from "./resolver";
import {
Token,
operatorTokenToString
} from "./tokenizer";
import {
Node,
NodeKind,
TypeNode,
Source,
Range,
DecoratorKind,
AssertionKind,
Statement,
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DeclarationStatement,
DoStatement,
EmptyStatement,
EnumDeclaration,
ExportStatement,
ExpressionStatement,
FunctionDeclaration,
ForStatement,
IfStatement,
ImportStatement,
InstanceOfExpression,
InterfaceDeclaration,
NamespaceDeclaration,
ReturnStatement,
SwitchStatement,
ThrowStatement,
TryStatement,
VariableDeclaration,
VariableStatement,
VoidStatement,
WhileStatement,
Expression,
AssertionExpression,
BinaryExpression,
CallExpression,
CommaExpression,
ElementAccessExpression,
FloatLiteralExpression,
FunctionExpression,
IdentifierExpression,
IntegerLiteralExpression,
LiteralExpression,
LiteralKind,
NewExpression,
ObjectLiteralExpression,
ParenthesizedExpression,
PropertyAccessExpression,
TernaryExpression,
ArrayLiteralExpression,
StringLiteralExpression,
UnaryPostfixExpression,
UnaryPrefixExpression,
FieldDeclaration,
nodeIsConstantValue,
isLastStatement,
findDecorator
} from "./ast";
import {
Type,
TypeKind,
TypeFlags,
Signature,
typesToNativeTypes
} from "./types";
import {
writeI8,
writeI16,
writeI32,
writeI64,
writeF32,
writeF64,
makeMap
} 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, imports the memory provided by the embedder. */
importMemory: bool = false;
/** If true, imports the function table provided by the embedder. */
importTable: bool = false;
/** If true, generates information necessary for source maps. */
sourceMap: bool = false;
/** Static memory start offset. */
memoryBase: i32 = 0;
/** Global aliases. */
globalAliases: Map<string,string> | null = null;
/** Additional features to activate. */
features: Feature = Feature.NONE;
/** 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;
}
/** Tests if a specific feature is activated. */
hasFeature(feature: Feature): bool {
return (this.features & feature) != 0;
}
}
/** Indicates specific features to activate. */
export const enum Feature {
/** No additional features. */
NONE = 0,
/** Sign extension operations. */
SIGN_EXTENSION = 1 << 0, // see: https://github.com/WebAssembly/sign-extension-ops
/** Mutable global imports and exports. */
MUTABLE_GLOBAL = 1 << 1 // see: https://github.com/WebAssembly/mutable-global
}
/** 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;
/** Resolver reference. */
resolver: Resolver;
/** Provided options. */
options: Options;
/** Module instance being compiled. */
module: Module;
/** Current function in compilation. */
currentFunction: Function;
/** Current outer function in compilation, if compiling a function expression. */
currentOuterFunction: Function | null = null;
/** Current inline functions stack. */
currentInlineFunctions: Function[] = [];
/** Current enum in compilation. */
currentEnum: Enum | null = null;
/** Current type in compilation. */
currentType: Type = Type.void;
/** Start function being compiled. */
startFunctionInstance: Function;
/** Start function statements. */
startFunctionBody: 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. */
functionTable: string[] = [ "null" ];
/** Argument count helper global. */
argcVar: GlobalRef = 0;
/** Argument count helper setter. */
argcSet: FunctionRef = 0;
/** Indicates whether the iterateRoots function must be generated. */
needsIterateRoots: bool = false;
/** 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;
this.resolver = program.resolver;
if (!options) options = new Options();
this.options = options;
this.memoryOffset = i64_new(
// leave space for `null`. also functions as a sentinel for erroneous stores at offset 0.
// note that Binaryen's asm.js output utilizes the first 8 bytes for reinterpretations (#1547)
max(options.memoryBase, 8)
);
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
var startFunctionInstance = new Function(program.startFunction, "start", new Signature([], Type.void));
this.startFunctionInstance = startFunctionInstance;
var startFunctionBody = new Array<ExpressionRef>();
this.startFunctionBody = startFunctionBody;
this.currentFunction = startFunctionInstance;
// add a mutable heap base dummy
if (options.isWasm64) {
module.addGlobal(
"HEAP_BASE",
NativeType.I64,
true,
module.createI64(0, 0)
);
} else {
module.addGlobal(
"HEAP_BASE",
NativeType.I32,
false,
module.createI32(0)
);
}
// 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 or called by main
if (startFunctionBody.length || program.mainFunction !== null) {
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);
if (!program.mainFunction) module.setStart(funcRef);
}
// update the heap base pointer
var memoryOffset = this.memoryOffset;
memoryOffset = i64_align(memoryOffset, options.usizeType.byteSize);
this.memoryOffset = memoryOffset;
module.removeGlobal("HEAP_BASE");
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))
);
}
// set up memory
module.setMemory(
this.options.memoryBase /* is specified */ || this.memorySegments.length
? i64_low(i64_shr_u(i64_align(memoryOffset, 0x10000), i64_new(16, 0)))
: 0,
Module.UNLIMITED_MEMORY,
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;
module.setFunctionTable(functionTable.length, 0xffffffff, functionTable);
module.addTableExport("0", "table");
module.addFunction("null", this.ensureFunctionType(null, Type.void), null, module.createBlock(null, []));
// import table if requested (default table is named '0' by Binaryen)
if (options.importTable) module.addTableImport("0", "env", "table");
// set up module exports
for (let [name, moduleExport] of program.moduleLevelExports) {
this.makeModuleExport(name, moduleExport.element);
}
// set up gc
if (this.needsIterateRoots) compileIterateRoots(this);
return module;
}
/** Applies the respective module export(s) for the specified element. */
private makeModuleExport(name: string, element: Element, prefix: string = ""): void {
// 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) {
for (let member of members.values()) {
if (!member.is(CommonFlags.EXPORT)) continue;
this.makeModuleExport(member.simpleName, member, subPrefix);
}
} else {
for (let member of members.values()) {
if (member.is(CommonFlags.PRIVATE)) continue;
this.makeModuleExport(member.simpleName, member, subPrefix);
}
}
}
switch (element.kind) {
// export global
case ElementKind.GLOBAL: {
let isConst = element.is(CommonFlags.CONST) || element.is(CommonFlags.STATIC | CommonFlags.READONLY);
if (!isConst && !this.options.hasFeature(Feature.MUTABLE_GLOBAL)) {
let declaration = (<Global>element).declaration;
if (declaration) {
this.error(
DiagnosticCode.Cannot_export_a_mutable_global,
declaration.name.range
);
}
} else {
this.module.addGlobalExport(element.internalName, prefix + name);
}
break;
}
case ElementKind.ENUMVALUE: {
if (!assert(element.parent).is(CommonFlags.CONST) && !this.options.hasFeature(Feature.MUTABLE_GLOBAL)) {
let declaration = (<EnumValue>element).declaration;
if (declaration) {
this.error(
DiagnosticCode.Cannot_export_a_mutable_global,
declaration.name.range
);
}
} else {
this.module.addGlobalExport(element.internalName, prefix + name);
}
break;
}
// export function
case ElementKind.FUNCTION: {
let instance = <Function>element;
let signature = instance.signature;
if (signature.requiredParameters < signature.parameterTypes.length) {
// utilize trampoline to fill in omitted arguments
instance = this.ensureTrampoline(instance);
this.ensureArgcSet();
}
if (instance.is(CommonFlags.COMPILED)) this.module.addFunctionExport(instance.internalName, prefix + name);
break;
}
// export getter and setter
case ElementKind.PROPERTY: {
let getter = assert((<Property>element).getterPrototype);
this.makeModuleExport(GETTER_PREFIX + name, getter, prefix);
let setter = (<Property>element).setterPrototype;
if (setter) this.makeModuleExport(SETTER_PREFIX + name, setter, prefix);
break;
}
// export a getter and a setter
case ElementKind.FIELD: {
let module = this.module;
let type = (<Field>element).type;
let nativeType = type.toNativeType();
let offset = (<Field>element).memoryOffset;
let usizeType = this.options.usizeType;
let nativeSizeType = this.options.nativeSizeType;
// make a getter
let getterName = prefix + GETTER_PREFIX + name;
module.addFunction(
getterName,
this.ensureFunctionType(null, type, usizeType),
null,
module.createLoad(
type.byteSize,
type.is(TypeFlags.SIGNED),
module.createGetLocal(0, nativeSizeType),
nativeType,
offset
)
);
module.addFunctionExport(getterName, getterName);
// make a setter
if (!element.is(CommonFlags.READONLY)) {
let setterName = prefix + SETTER_PREFIX + name;
module.addFunction(
setterName,
this.ensureFunctionType([ type ], Type.void, usizeType),
null,
module.createStore(
type.byteSize,
module.createGetLocal(0, nativeSizeType),
module.createGetLocal(1, nativeType),
nativeType,
offset
)
);
module.addFunctionExport(setterName, setterName);
}
break;
}
// skip prototype and export instances
case ElementKind.FUNCTION_PROTOTYPE: {
for (let instances of (<FunctionPrototype>element).instances.values()) {
for (let instance of instances.values()) {
let instanceName = name;
if (instance.is(CommonFlags.GENERIC)) {
let fullName = instance.internalName;
instanceName += fullName.substring(fullName.lastIndexOf("<"));
}
this.makeModuleExport(instanceName, instance, prefix);
}
}
break;
}
case ElementKind.CLASS_PROTOTYPE: {
for (let instance of (<ClassPrototype>element).instances.values()) {
let instanceName = name;
if (instance.is(CommonFlags.GENERIC)) {
let fullName = instance.internalName;
instanceName += fullName.substring(fullName.lastIndexOf("<"));
}
let ctor = instance.constructorInstance;
if (ctor) this.makeModuleExport(instanceName + INSTANCE_DELIMITER + ctor.simpleName, ctor, prefix);
this.makeModuleExport(instanceName, instance, prefix);
}
break;
}
// all possible members already handled above
case ElementKind.ENUM:
case ElementKind.CLASS:
case ElementKind.NAMESPACE: break;
default: assert(false);
}
}
// 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 startFunctionInstance = this.startFunctionInstance;
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 = startFunctionInstance;
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.is(CommonFlags.RESOLVED)) {
if (declaration) {
// resolve now if annotated
if (declaration.type) {
let resolvedType = this.resolver.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;
global.set(CommonFlags.RESOLVED);
// infer from initializer if not annotated
} else if (declaration.initializer) { // infer type using void/NONE for literal inference
initExpr = this.compileExpressionRetainType( // reports
declaration.initializer,
Type.void,
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;
global.set(CommonFlags.RESOLVED);
// 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 resolved lazily
}
}
// ambient builtins like 'HEAP_BASE' need to be resolved but are added explicitly
if (global.is(CommonFlags.AMBIENT) && global.hasDecorator(DecoratorFlags.BUILTIN)) return true;
var nativeType = global.type.toNativeType();
var isDeclaredConstant = global.is(CommonFlags.CONST) || global.is(CommonFlags.STATIC | CommonFlags.READONLY);
// handle imports
if (global.is(CommonFlags.AMBIENT)) {
// constant global
if (isDeclaredConstant || this.options.hasFeature(Feature.MUTABLE_GLOBAL)) {
global.set(CommonFlags.MODULE_IMPORT);
if (declaration) {
mangleImportName(global, declaration);
} else {
mangleImportName_moduleName = "env";
mangleImportName_elementName = global.simpleName;
}
module.addGlobalImport(
global.internalName,
mangleImportName_moduleName,
mangleImportName_elementName,
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 constant
// get_globals), hence such initializations must be performed in the start function for now.
var initializeInStart = false;
// evaluate initializer if present
if (declaration !== null && declaration.initializer !== null) {
if (!initExpr) {
initExpr = this.compileExpression(
declaration.initializer,
global.type,
ConversionKind.IMPLICIT,
WrapMode.WRAP
);
}
if (getExpressionId(initExpr) != ExpressionId.Const) {
if (isDeclaredConstant) {
initExpr = module.precomputeExpression(initExpr);
if (getExpressionId(initExpr) != ExpressionId.Const) {
this.warning(
DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable,
declaration.range
);
initializeInStart = true;
}
} else {
initializeInStart = true;
}
}
// explicitly inline if annotated
if (global.hasDecorator(DecoratorFlags.INLINE)) {
if (!initializeInStart) { // reported above
assert(getExpressionId(initExpr) == ExpressionId.Const);
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
}
}
// 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 normally
module.addGlobal(internalName, nativeType, !isDeclaredConstant, 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;
var previousValueIsMut = false;
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);
let initExpr: ExpressionRef;
if (valueDeclaration.value) {
initExpr = this.compileExpression(
<Expression>valueDeclaration.value,
Type.i32,
ConversionKind.IMPLICIT,
WrapMode.NONE
);
if (getExpressionId(initExpr) != ExpressionId.Const) {
if (element.is(CommonFlags.CONST)) {
initExpr = module.precomputeExpression(initExpr);
if (getExpressionId(initExpr) != ExpressionId.Const) {
this.error(
DiagnosticCode.In_const_enum_declarations_member_initializer_must_be_constant_expression,
valueDeclaration.value.range
);
initInStart = true;
}
} else {
initInStart = true;
}
}
} else if (previousValue == null) {
initExpr = module.createI32(0);
} else {
if (previousValueIsMut) {
this.error(
DiagnosticCode.Enum_member_must_have_initializer,
valueDeclaration.range
);
}
initExpr = module.createBinary(BinaryOp.AddI32,
module.createGetGlobal(previousValue.internalName, NativeType.I32),
module.createI32(1)
);
initExpr = module.precomputeExpression(initExpr);
if (getExpressionId(initExpr) != ExpressionId.Const) {
if (element.is(CommonFlags.CONST)) {
this.error(
DiagnosticCode.In_const_enum_declarations_member_initializer_must_be_constant_expression,
valueDeclaration.range
);
}
initInStart = true;
}
}
if (initInStart) {
module.addGlobal(val.internalName, NativeType.I32, true, module.createI32(0));
this.startFunctionBody.push(module.createSetGlobal(val.internalName, initExpr));
previousValueIsMut = true;
} else {
module.addGlobal(val.internalName, NativeType.I32, !element.is(CommonFlags.CONST), initExpr);
previousValueIsMut = false;
}
previousValue = <EnumValue>val;
}
}
this.currentEnum = null;
return true;
}
// functions
/** Compiles a top-level function given its declaration. */
compileFunctionDeclaration(
declaration: FunctionDeclaration,
typeArguments: TypeNode[]
): Function | null {
var element = assert(this.program.elementsLookup.get(declaration.fileLevelInternalName));
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
return this.compileFunctionUsingTypeArguments( // reports
<FunctionPrototype>element,
typeArguments,
makeMap<string,Type>(),
null,
(<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>,
outerScope: Flow | null,
reportNode: Node
): Function | null {
var instance = this.resolver.resolveFunctionInclTypeArguments(
prototype,
typeArguments,
contextualTypeArguments,
reportNode
);
if (!instance) return null;
instance.outerScope = outerScope;
if (!this.compileFunction(instance)) return null; // reports
return instance;
}
/** Either reuses or creates the function type matching the specified signature. */
ensureFunctionType(
parameterTypes: Type[] | null,
returnType: Type,
thisType: Type | null = null
): FunctionTypeRef {