forked from AssemblyScript/assemblyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.ts
More file actions
3805 lines (3541 loc) · 127 KB
/
program.ts
File metadata and controls
3805 lines (3541 loc) · 127 KB
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
/**
* AssemblyScript's intermediate representation describing a program's elements.
* @module program
*//***/
import {
CommonFlags,
PATH_DELIMITER,
STATIC_DELIMITER,
INSTANCE_DELIMITER,
GETTER_PREFIX,
SETTER_PREFIX,
INNER_DELIMITER,
LIBRARY_SUBST,
INDEX_SUFFIX,
CommonSymbols,
Feature,
Target
} from "./common";
import {
Options
} from "./compiler";
import {
DiagnosticCode,
DiagnosticMessage,
DiagnosticEmitter
} from "./diagnostics";
import {
Type,
TypeKind,
TypeFlags,
Signature
} from "./types";
import {
Node,
NodeKind,
Source,
SourceKind,
Range,
DecoratorNode,
DecoratorKind,
TypeParameterNode,
TypeNode,
NamedTypeNode,
FunctionTypeNode,
ArrowKind,
Expression,
IdentifierExpression,
LiteralExpression,
LiteralKind,
StringLiteralExpression,
Statement,
ClassDeclaration,
DeclarationStatement,
EnumDeclaration,
EnumValueDeclaration,
ExportMember,
ExportStatement,
FieldDeclaration,
FunctionDeclaration,
ImportDeclaration,
ImportStatement,
InterfaceDeclaration,
MethodDeclaration,
NamespaceDeclaration,
TypeDeclaration,
VariableDeclaration,
VariableLikeDeclarationStatement,
VariableStatement,
ExportDefaultStatement,
Token,
ParameterNode
} from "./ast";
import {
Module,
FunctionRef
} from "./module";
import {
CharCode,
writeI8,
writeI16,
writeI32,
writeF32,
writeF64
} from "./util";
import {
Resolver
} from "./resolver";
import {
Flow
} from "./flow";
import {
Parser
} from "./parser";
/** Represents a yet unresolved `import`. */
class QueuedImport {
constructor(
/** File being imported into. */
public localFile: File,
/** Identifier within the local file. */
public localIdentifier: IdentifierExpression,
/** Identifier within the other file. Is an `import *` if not set. */
public foreignIdentifier: IdentifierExpression | null,
/** Path to the other file. */
public foreignPath: string,
/** Alternative path to the other file. */
public foreignPathAlt: string
) {}
}
/** Represents a yet unresolved `export`. */
class QueuedExport {
constructor(
/** Identifier within the local file. */
public localIdentifier: IdentifierExpression,
/** Identifier within the other file. */
public foreignIdentifier: IdentifierExpression,
/** Path to the other file if a re-export. */
public foreignPath: string | null,
/** Alternative path to the other file if a re-export. */
public foreignPathAlt: string | null
) {}
}
/** Represents a yet unresolved `export *`. */
class QueuedExportStar {
// stored in a map with localFile as the key
constructor(
/** Path to the other file. */
public foreignPath: string,
/** Alternative path to the other file. */
public foreignPathAlt: string,
/** Reference to the path literal for reporting. */
public pathLiteral: StringLiteralExpression
) {}
}
/** Represents the kind of an operator overload. */
export enum OperatorKind {
INVALID,
// indexed access
INDEXED_GET, // a[]
INDEXED_SET, // a[]=b
UNCHECKED_INDEXED_GET, // unchecked(a[])
UNCHECKED_INDEXED_SET, // unchecked(a[]=b)
// binary
ADD, // a + b
SUB, // a - b
MUL, // a * b
DIV, // a / b
REM, // a % b
POW, // a ** b
BITWISE_AND, // a & b
BITWISE_OR, // a | b
BITWISE_XOR, // a ^ b
BITWISE_SHL, // a << b
BITWISE_SHR, // a >> b
BITWISE_SHR_U, // a >>> b
EQ, // a == b
NE, // a != b
GT, // a > b
GE, // a >= b
LT, // a < b
LE, // a <= b
// unary prefix
PLUS, // +a
MINUS, // -a
NOT, // !a
BITWISE_NOT, // ~a
PREFIX_INC, // ++a
PREFIX_DEC, // --a
// unary postfix
POSTFIX_INC, // a++
POSTFIX_DEC // a--
// not overridable:
// IDENTITY // a === b
// LOGICAL_AND // a && b
// LOGICAL_OR // a || b
}
export namespace OperatorKind {
/** Returns the operator kind represented by the specified decorator and string argument. */
export function fromDecorator(decoratorKind: DecoratorKind, arg: string): OperatorKind {
assert(arg.length);
switch (decoratorKind) {
case DecoratorKind.OPERATOR:
case DecoratorKind.OPERATOR_BINARY: {
switch (arg.charCodeAt(0)) {
case CharCode.OPENBRACKET: {
if (arg == "[]") return OperatorKind.INDEXED_GET;
if (arg == "[]=") return OperatorKind.INDEXED_SET;
break;
}
case CharCode.OPENBRACE: {
if (arg == "{}") return OperatorKind.UNCHECKED_INDEXED_GET;
if (arg == "{}=") return OperatorKind.UNCHECKED_INDEXED_SET;
break;
}
case CharCode.PLUS: {
if (arg == "+") return OperatorKind.ADD;
break;
}
case CharCode.MINUS: {
if (arg == "-") return OperatorKind.SUB;
break;
}
case CharCode.ASTERISK: {
if (arg == "*") return OperatorKind.MUL;
if (arg == "**") return OperatorKind.POW;
break;
}
case CharCode.SLASH: {
if (arg == "/") return OperatorKind.DIV;
break;
}
case CharCode.PERCENT: {
if (arg == "%") return OperatorKind.REM;
break;
}
case CharCode.AMPERSAND: {
if (arg == "&") return OperatorKind.BITWISE_AND;
break;
}
case CharCode.BAR: {
if (arg == "|") return OperatorKind.BITWISE_OR;
break;
}
case CharCode.CARET: {
if (arg == "^") return OperatorKind.BITWISE_XOR;
break;
}
case CharCode.EQUALS: {
if (arg == "==") return OperatorKind.EQ;
break;
}
case CharCode.EXCLAMATION: {
if (arg == "!=") return OperatorKind.NE;
break;
}
case CharCode.GREATERTHAN: {
if (arg == ">") return OperatorKind.GT;
if (arg == ">=") return OperatorKind.GE;
if (arg == ">>") return OperatorKind.BITWISE_SHR;
if (arg == ">>>") return OperatorKind.BITWISE_SHR_U;
break;
}
case CharCode.LESSTHAN: {
if (arg == "<") return OperatorKind.LT;
if (arg == "<=") return OperatorKind.LE;
if (arg == "<<") return OperatorKind.BITWISE_SHL;
break;
}
}
break;
}
case DecoratorKind.OPERATOR_PREFIX: {
switch (arg.charCodeAt(0)) {
case CharCode.PLUS: {
if (arg == "+") return OperatorKind.PLUS;
if (arg == "++") return OperatorKind.PREFIX_INC;
break;
}
case CharCode.MINUS: {
if (arg == "-") return OperatorKind.MINUS;
if (arg == "--") return OperatorKind.PREFIX_DEC;
break;
}
case CharCode.EXCLAMATION: {
if (arg == "!") return OperatorKind.NOT;
break;
}
case CharCode.TILDE: {
if (arg == "~") return OperatorKind.BITWISE_NOT;
break;
}
}
break;
}
case DecoratorKind.OPERATOR_POSTFIX: {
switch (arg.charCodeAt(0)) {
case CharCode.PLUS: {
if (arg == "++") return OperatorKind.POSTFIX_INC;
break;
}
case CharCode.MINUS: {
if (arg == "--") return OperatorKind.POSTFIX_DEC;
break;
}
}
break;
}
}
return OperatorKind.INVALID;
}
/** Converts a binary operator token to the respective operator kind. */
export function fromBinaryToken(token: Token): OperatorKind {
switch (token) {
case Token.PLUS:
case Token.PLUS_EQUALS: return OperatorKind.ADD;
case Token.MINUS:
case Token.MINUS_EQUALS: return OperatorKind.SUB;
case Token.ASTERISK:
case Token.ASTERISK_EQUALS: return OperatorKind.MUL;
case Token.SLASH:
case Token.SLASH_EQUALS: return OperatorKind.DIV;
case Token.PERCENT:
case Token.PERCENT_EQUALS: return OperatorKind.REM;
case Token.ASTERISK_ASTERISK:
case Token.ASTERISK_ASTERISK_EQUALS: return OperatorKind.POW;
case Token.AMPERSAND:
case Token.AMPERSAND_EQUALS: return OperatorKind.BITWISE_AND;
case Token.BAR:
case Token.BAR_EQUALS: return OperatorKind.BITWISE_OR;
case Token.CARET:
case Token.CARET_EQUALS: return OperatorKind.BITWISE_XOR;
case Token.LESSTHAN_LESSTHAN:
case Token.LESSTHAN_LESSTHAN_EQUALS: return OperatorKind.BITWISE_SHL;
case Token.GREATERTHAN_GREATERTHAN:
case Token.GREATERTHAN_GREATERTHAN_EQUALS: return OperatorKind.BITWISE_SHR;
case Token.GREATERTHAN_GREATERTHAN_GREATERTHAN:
case Token.GREATERTHAN_GREATERTHAN_GREATERTHAN_EQUALS: return OperatorKind.BITWISE_SHR_U;
case Token.EQUALS_EQUALS: return OperatorKind.EQ;
case Token.EXCLAMATION_EQUALS: return OperatorKind.NE;
case Token.GREATERTHAN: return OperatorKind.GT;
case Token.GREATERTHAN_EQUALS: return OperatorKind.GE;
case Token.LESSTHAN: return OperatorKind.LT;
case Token.LESSTHAN_EQUALS: return OperatorKind.LE;
}
return OperatorKind.INVALID;
}
/** Converts a unary prefix operator token to the respective operator kind. */
export function fromUnaryPrefixToken(token: Token): OperatorKind {
switch (token) {
case Token.PLUS: return OperatorKind.PLUS;
case Token.MINUS: return OperatorKind.MINUS;
case Token.EXCLAMATION: return OperatorKind.NOT;
case Token.TILDE: return OperatorKind.BITWISE_NOT;
case Token.PLUS_PLUS: return OperatorKind.PREFIX_INC;
case Token.MINUS_MINUS: return OperatorKind.PREFIX_DEC;
}
return OperatorKind.INVALID;
}
/** Converts a unary postfix operator token to the respective operator kind. */
export function fromUnaryPostfixToken(token: Token): OperatorKind {
switch (token) {
case Token.PLUS_PLUS: return OperatorKind.POSTFIX_INC;
case Token.MINUS_MINUS: return OperatorKind.POSTFIX_DEC;
}
return OperatorKind.INVALID;
}
}
/** Represents an AssemblyScript program. */
export class Program extends DiagnosticEmitter {
/** Parser instance. */
parser: Parser;
/** Resolver instance. */
resolver: Resolver;
/** Array of sources. */
sources: Source[] = [];
/** Diagnostic offset used where successively obtaining the next diagnostic. */
diagnosticsOffset: i32 = 0;
/** Compiler options. */
options: Options;
/** Special native code source. */
nativeSource: Source;
/** Special native code file. */
nativeFile: File;
// lookup maps
/** Files by unique internal name. */
filesByName: Map<string,File> = new Map();
/** Elements by unique internal name in element space. */
elementsByName: Map<string,Element> = new Map();
/** Elements by declaration. */
elementsByDeclaration: Map<DeclarationStatement,DeclaredElement> = new Map();
/** Element instances by unique internal name. */
instancesByName: Map<string,Element> = new Map();
/** Classes wrapping basic types like `i32`. */
wrapperClasses: Map<Type,Class> = new Map();
/** Managed classes contained in the program, by id. */
managedClasses: Map<i32,Class> = new Map();
/** A set of unique function signatures contained in the program, by id. */
uniqueSignatures: Signature[] = new Array<Signature>(0);
// standard references
/** ArrayBufferView reference. */
arrayBufferViewInstance: Class;
/** ArrayBuffer instance reference. */
arrayBufferInstance: Class;
/** Array prototype reference. */
arrayPrototype: ClassPrototype;
/** Set prototype reference. */
setPrototype: ClassPrototype;
/** Map prototype reference. */
mapPrototype: ClassPrototype;
/** Fixed array prototype reference. */
fixedArrayPrototype: ClassPrototype;
/** Int8Array prototype. */
i8ArrayPrototype: ClassPrototype;
/** Int16Array prototype. */
i16ArrayPrototype: ClassPrototype;
/** Int32Array prototype. */
i32ArrayPrototype: ClassPrototype;
/** Int64Array prototype. */
i64ArrayPrototype: ClassPrototype;
/** Uint8Array prototype. */
u8ArrayPrototype: ClassPrototype;
/** Uint8ClampedArray prototype. */
u8ClampedArrayPrototype: ClassPrototype;
/** Uint16Array prototype. */
u16ArrayPrototype: ClassPrototype;
/** Uint32Array prototype. */
u32ArrayPrototype: ClassPrototype;
/** Uint64Array prototype. */
u64ArrayPrototype: ClassPrototype;
/** Float32Array prototype. */
f32ArrayPrototype: ClassPrototype;
/** Float64Array prototype. */
f64ArrayPrototype: ClassPrototype;
/** String instance reference. */
stringInstance: Class;
/** Abort function reference, if not explicitly disabled. */
abortInstance: Function | null;
// runtime references
/** RT `__alloc(size: usize, id: u32): usize` */
allocInstance: Function;
/** RT `__realloc(ptr: usize, newSize: usize): usize` */
reallocInstance: Function;
/** RT `__free(ptr: usize): void` */
freeInstance: Function;
/** RT `__retain(ptr: usize): usize` */
retainInstance: Function;
/** RT `__release(ptr: usize): void` */
releaseInstance: Function;
/** RT `__collect(): void` */
collectInstance: Function;
/** RT `__visit(ptr: usize, cookie: u32): void` */
visitInstance: Function;
/** RT `__typeinfo(id: u32): RTTIFlags` */
typeinfoInstance: Function;
/** RT `__instanceof(ptr: usize, superId: u32): bool` */
instanceofInstance: Function;
/** RT `__allocArray(length: i32, alignLog2: usize, id: u32, data: usize = 0): usize` */
allocArrayInstance: Function;
/** Next class id. */
nextClassId: u32 = 0;
/** Next signature id. */
nextSignatureId: i32 = 0;
/** Constructs a new program, optionally inheriting parser diagnostics. */
constructor(
/** Compiler options. */
options: Options,
/** Shared array of diagnostic messages (emitted so far). */
diagnostics: DiagnosticMessage[] | null = null
) {
super(diagnostics);
this.options = options;
var nativeSource = new Source(LIBRARY_SUBST, "[native code]", SourceKind.LIBRARY_ENTRY);
this.nativeSource = nativeSource;
var nativeFile = new File(this, nativeSource);
this.nativeFile = nativeFile;
this.filesByName.set(nativeFile.internalName, nativeFile);
this.parser = new Parser(this);
this.resolver = new Resolver(this);
}
/** Obtains the source matching the specified internal path. */
getSource(internalPath: string): string | null {
var sources = this.sources;
for (let i = 0; i < sources.length; ++i) {
let source = sources[i];
if (source.internalPath == internalPath) return source.text;
}
return null;
}
/** Writes a common runtime header to the specified buffer. */
writeRuntimeHeader(buffer: Uint8Array, offset: i32, classInstance: Class, payloadSize: u32): void {
// BLOCK {
// mmInfo: usize // WASM64 TODO
// gcInfo: u32
// rtId: u32
// rtSize: u32
// }
assert(payloadSize < (1 << 28)); // 1 bit BUFFERED + 3 bits color
writeI32(payloadSize, buffer, offset);
writeI32(1, buffer, offset + 4); // RC=1
writeI32(classInstance.id, buffer, offset + 8);
writeI32(payloadSize, buffer, offset + 12);
}
/** Gets the size of a runtime header. */
get runtimeHeaderSize(): i32 {
return 16;
}
/** Creates a native variable declaration. */
makeNativeVariableDeclaration(
/** The simple name of the variable */
name: string,
/** Flags indicating specific traits, e.g. `CONST`. */
flags: CommonFlags = CommonFlags.NONE
): VariableDeclaration {
var range = this.nativeSource.range;
return Node.createVariableDeclaration(
Node.createIdentifierExpression(name, range),
null, null, null, flags, range
);
}
/** Creates a native type declaration. */
makeNativeTypeDeclaration(
/** The simple name of the type. */
name: string,
/** Flags indicating specific traits, e.g. `GENERIC`. */
flags: CommonFlags = CommonFlags.NONE
): TypeDeclaration {
var range = this.nativeSource.range;
var identifier = Node.createIdentifierExpression(name, range);
return Node.createTypeDeclaration(
identifier,
null,
Node.createOmittedType(range),
null, flags, range
);
}
// a dummy signature for programmatically generated native functions
private nativeDummySignature: FunctionTypeNode | null = null;
/** Creates a native function declaration. */
makeNativeFunctionDeclaration(
/** The simple name of the function. */
name: string,
/** Flags indicating specific traits, e.g. `DECLARE`. */
flags: CommonFlags = CommonFlags.NONE
): FunctionDeclaration {
var range = this.nativeSource.range;
return Node.createFunctionDeclaration(
Node.createIdentifierExpression(name, range),
null,
this.nativeDummySignature || (this.nativeDummySignature = Node.createFunctionType([],
Node.createNamedType( // ^ AST signature doesn't really matter, is overridden anyway
Node.createSimpleTypeName(CommonSymbols.void_, range),
null, false, range
),
null, false, range)
),
null, null, flags, ArrowKind.NONE, range
);
}
/** Creates a native namespace declaration. */
makeNativeNamespaceDeclaration(
/** The simple name of the namespace. */
name: string,
/** Flags indicating specific traits, e.g. `EXPORT`. */
flags: CommonFlags = CommonFlags.NONE
): NamespaceDeclaration {
var range = this.nativeSource.range;
return Node.createNamespaceDeclaration(
Node.createIdentifierExpression(name, range),
[], null, flags, range
);
}
/** Creates a native function. */
makeNativeFunction(
/** The simple name of the function. */
name: string,
/** Concrete function signature. */
signature: Signature,
/** Parent element, usually a file, class or namespace. */
parent: Element = this.nativeFile,
/** Flags indicating specific traits, e.g. `GENERIC`. */
flags: CommonFlags = CommonFlags.NONE,
/** Decorator flags representing built-in decorators. */
decoratorFlags: DecoratorFlags = DecoratorFlags.NONE
): Function {
return new Function(
name,
new FunctionPrototype(
name,
parent,
this.makeNativeFunctionDeclaration(name, flags),
decoratorFlags
),
signature
);
}
/** Gets the (possibly merged) program element linked to the specified declaration. */
getElementByDeclaration(declaration: DeclarationStatement): DeclaredElement | null {
var elementsByDeclaration = this.elementsByDeclaration;
return elementsByDeclaration.has(declaration)
? elementsByDeclaration.get(declaration)!
: null;
}
/** Initializes the program and its elements prior to compilation. */
initialize(options: Options): void {
this.options = options;
// register native types
this.registerNativeType(CommonSymbols.i8, Type.i8);
this.registerNativeType(CommonSymbols.i16, Type.i16);
this.registerNativeType(CommonSymbols.i32, Type.i32);
this.registerNativeType(CommonSymbols.i64, Type.i64);
this.registerNativeType(CommonSymbols.isize, options.isizeType);
this.registerNativeType(CommonSymbols.u8, Type.u8);
this.registerNativeType(CommonSymbols.u16, Type.u16);
this.registerNativeType(CommonSymbols.u32, Type.u32);
this.registerNativeType(CommonSymbols.u64, Type.u64);
this.registerNativeType(CommonSymbols.usize, options.usizeType);
this.registerNativeType(CommonSymbols.bool, Type.bool);
this.registerNativeType(CommonSymbols.f32, Type.f32);
this.registerNativeType(CommonSymbols.f64, Type.f64);
this.registerNativeType(CommonSymbols.void_, Type.void);
this.registerNativeType(CommonSymbols.number, Type.f64); // alias
this.registerNativeType(CommonSymbols.boolean, Type.bool); // alias
this.nativeFile.add(CommonSymbols.native, new TypeDefinition(
CommonSymbols.native,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonSymbols.native, CommonFlags.EXPORT | CommonFlags.GENERIC),
DecoratorFlags.BUILTIN
));
this.nativeFile.add(CommonSymbols.indexof, new TypeDefinition(
CommonSymbols.indexof,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonSymbols.indexof, CommonFlags.EXPORT | CommonFlags.GENERIC),
DecoratorFlags.BUILTIN
));
this.nativeFile.add(CommonSymbols.valueof, new TypeDefinition(
CommonSymbols.valueof,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonSymbols.valueof, CommonFlags.EXPORT | CommonFlags.GENERIC),
DecoratorFlags.BUILTIN
));
this.nativeFile.add(CommonSymbols.returnof, new TypeDefinition(
CommonSymbols.returnof,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonSymbols.returnof, CommonFlags.EXPORT | CommonFlags.GENERIC),
DecoratorFlags.BUILTIN
));
if (options.hasFeature(Feature.SIMD)) this.registerNativeType(CommonSymbols.v128, Type.v128);
if (options.hasFeature(Feature.REFERENCE_TYPES)) this.registerNativeType(CommonSymbols.anyref, Type.anyref);
// register compiler hints
this.registerConstantInteger(CommonSymbols.ASC_TARGET, Type.i32,
i64_new(options.isWasm64 ? Target.WASM64 : Target.WASM32));
this.registerConstantInteger(CommonSymbols.ASC_NO_ASSERT, Type.bool,
i64_new(options.noAssert ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_MEMORY_BASE, Type.i32,
i64_new(options.memoryBase, 0));
this.registerConstantInteger(CommonSymbols.ASC_OPTIMIZE_LEVEL, Type.i32,
i64_new(options.optimizeLevelHint, 0));
this.registerConstantInteger(CommonSymbols.ASC_SHRINK_LEVEL, Type.i32,
i64_new(options.shrinkLevelHint, 0));
// register feature hints
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_SIGN_EXTENSION, Type.bool,
i64_new(options.hasFeature(Feature.SIGN_EXTENSION) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_MUTABLE_GLOBALS, Type.bool,
i64_new(options.hasFeature(Feature.MUTABLE_GLOBALS) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_NONTRAPPING_F2I, Type.bool,
i64_new(options.hasFeature(Feature.NONTRAPPING_F2I) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_BULK_MEMORY, Type.bool,
i64_new(options.hasFeature(Feature.BULK_MEMORY) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_SIMD, Type.bool,
i64_new(options.hasFeature(Feature.SIMD) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_THREADS, Type.bool,
i64_new(options.hasFeature(Feature.THREADS) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_EXCEPTION_HANDLING, Type.bool,
i64_new(options.hasFeature(Feature.EXCEPTION_HANDLING) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_TAIL_CALLS, Type.bool,
i64_new(options.hasFeature(Feature.TAIL_CALLS) ? 1 : 0, 0));
this.registerConstantInteger(CommonSymbols.ASC_FEATURE_REFERENCE_TYPES, Type.bool,
i64_new(options.hasFeature(Feature.REFERENCE_TYPES) ? 1 : 0, 0));
// remember deferred elements
var queuedImports = new Array<QueuedImport>();
var queuedExports = new Map<File,Map<string,QueuedExport>>();
var queuedExportsStar = new Map<File,QueuedExportStar[]>();
var queuedExtends = new Array<ClassPrototype>();
var queuedImplements = new Array<ClassPrototype>();
// initialize relevant declaration-like statements of the entire program
for (let i = 0, k = this.sources.length; i < k; ++i) {
let source = this.sources[i];
let file = new File(this, source);
this.filesByName.set(file.internalName, file);
let statements = source.statements;
for (let j = 0, l = statements.length; j < l; ++j) {
let statement = statements[j];
switch (statement.kind) {
case NodeKind.EXPORT: {
this.initializeExports(<ExportStatement>statement, file, queuedExports, queuedExportsStar);
break;
}
case NodeKind.EXPORTDEFAULT: {
this.initializeExportDefault(<ExportDefaultStatement>statement, file, queuedExtends, queuedImplements);
break;
}
case NodeKind.IMPORT: {
this.initializeImports(<ImportStatement>statement, file, queuedImports, queuedExports);
break;
}
case NodeKind.VARIABLE: {
this.initializeVariables(<VariableStatement>statement, file);
break;
}
case NodeKind.CLASSDECLARATION: {
this.initializeClass(<ClassDeclaration>statement, file, queuedExtends, queuedImplements);
break;
}
case NodeKind.ENUMDECLARATION: {
this.initializeEnum(<EnumDeclaration>statement, file);
break;
}
case NodeKind.FUNCTIONDECLARATION: {
this.initializeFunction(<FunctionDeclaration>statement, file);
break;
}
case NodeKind.INTERFACEDECLARATION: {
this.initializeInterface(<InterfaceDeclaration>statement, file);
break;
}
case NodeKind.NAMESPACEDECLARATION: {
this.initializeNamespace(<NamespaceDeclaration>statement, file, queuedExtends, queuedImplements);
break;
}
case NodeKind.TYPEDECLARATION: {
this.initializeTypeDefinition(<TypeDeclaration>statement, file);
break;
}
}
}
}
// queued exports * should be linkable now that all files have been processed
for (let [file, exportsStar] of queuedExportsStar) {
for (let i = 0, k = exportsStar.length; i < k; ++i) {
let exportStar = exportsStar[i];
let foreignFile = this.lookupForeignFile(exportStar.foreignPath, exportStar.foreignPathAlt);
if (!foreignFile) {
this.error(
DiagnosticCode.File_0_not_found,
exportStar.pathLiteral.range, exportStar.pathLiteral.value
);
continue;
}
file.ensureExportStar(foreignFile);
}
}
// queued imports should be resolvable now through traversing exports and queued exports
for (let i = 0, k = queuedImports.length; i < k; ++i) {
let queuedImport = queuedImports[i];
let foreignIdentifier = queuedImport.foreignIdentifier;
if (foreignIdentifier) { // i.e. import { foo [as bar] } from "./baz"
let element = this.lookupForeign(
foreignIdentifier.text,
queuedImport.foreignPath,
queuedImport.foreignPathAlt,
queuedExports
);
if (element) {
queuedImport.localFile.add(
queuedImport.localIdentifier.text,
element,
true // isImport
);
} else {
// FIXME: file not found is not reported if this happens?
this.error(
DiagnosticCode.Module_0_has_no_exported_member_1,
foreignIdentifier.range, queuedImport.foreignPath, foreignIdentifier.text
);
}
} else { // i.e. import * as bar from "./bar"
let foreignFile = this.lookupForeignFile(queuedImport.foreignPath, queuedImport.foreignPathAlt);
if (foreignFile) {
let localFile = queuedImport.localFile;
let localName = queuedImport.localIdentifier.text;
localFile.add(
localName,
foreignFile.asImportedNamespace(
localName,
localFile
),
true // isImport
);
} else {
assert(false); // already reported by the parser not finding the file
}
}
}
// queued exports should be resolvable now that imports are finalized
for (let [file, exports] of queuedExports) {
for (let [exportName, queuedExport] of exports) {
let localName = queuedExport.localIdentifier.text;
let foreignPath = queuedExport.foreignPath;
if (foreignPath) { // i.e. export { foo [as bar] } from "./baz"
let element = this.lookupForeign(
localName,
foreignPath,
assert(queuedExport.foreignPathAlt), // must be set if foreignPath is
queuedExports
);
if (element) {
file.ensureExport(exportName, element);
} else {
this.error(
DiagnosticCode.Module_0_has_no_exported_member_1,
queuedExport.localIdentifier.range,
foreignPath, localName
);
}
} else { // i.e. export { foo [as bar] }
let element = file.lookupInSelf(localName);
if (element) {
file.ensureExport(exportName, element);
} else {
let globalElement = this.lookupGlobal(localName);
if (globalElement && globalElement instanceof DeclaredElement) { // export { memory }
file.ensureExport(exportName, <DeclaredElement>globalElement);
} else {
this.error(
DiagnosticCode.Module_0_has_no_exported_member_1,
queuedExport.foreignIdentifier.range,
file.internalName, queuedExport.foreignIdentifier.text
);
}
}
}
}
}
// register ArrayBuffer (id=0), String (id=1), ArrayBufferView (id=2)
assert(this.nextClassId == 0);
this.arrayBufferInstance = this.requireClass(CommonSymbols.ArrayBuffer);
assert(this.arrayBufferInstance.id == 0);
this.stringInstance = this.requireClass(CommonSymbols.String);
assert(this.stringInstance.id == 1);
this.arrayBufferViewInstance = this.requireClass(CommonSymbols.ArrayBufferView);
assert(this.arrayBufferViewInstance.id == 2);
// register classes backing basic types
this.registerWrapperClass(Type.i8, CommonSymbols.I8);
this.registerWrapperClass(Type.i16, CommonSymbols.I16);
this.registerWrapperClass(Type.i32, CommonSymbols.I32);
this.registerWrapperClass(Type.i64, CommonSymbols.I64);
this.registerWrapperClass(options.isizeType, CommonSymbols.Isize);
this.registerWrapperClass(Type.u8, CommonSymbols.U8);
this.registerWrapperClass(Type.u16, CommonSymbols.U16);
this.registerWrapperClass(Type.u32, CommonSymbols.U32);
this.registerWrapperClass(Type.u64, CommonSymbols.U64);
this.registerWrapperClass(options.usizeType, CommonSymbols.Usize);
this.registerWrapperClass(Type.bool, CommonSymbols.Bool);
this.registerWrapperClass(Type.f32, CommonSymbols.F32);
this.registerWrapperClass(Type.f64, CommonSymbols.F64);
if (options.hasFeature(Feature.SIMD)) this.registerWrapperClass(Type.v128, CommonSymbols.V128);
if (options.hasFeature(Feature.REFERENCE_TYPES)) this.registerWrapperClass(Type.anyref, CommonSymbols.Anyref);
// register views but don't instantiate them yet
this.i8ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Int8Array, ElementKind.CLASS_PROTOTYPE);
this.i16ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Int16Array, ElementKind.CLASS_PROTOTYPE);
this.i32ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Int32Array, ElementKind.CLASS_PROTOTYPE);
this.i64ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Int64Array, ElementKind.CLASS_PROTOTYPE);
this.u8ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Uint8Array, ElementKind.CLASS_PROTOTYPE);
this.u8ClampedArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Uint8ClampedArray, ElementKind.CLASS_PROTOTYPE);
this.u16ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Uint16Array, ElementKind.CLASS_PROTOTYPE);
this.u32ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Uint32Array, ElementKind.CLASS_PROTOTYPE);
this.u64ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Uint64Array, ElementKind.CLASS_PROTOTYPE);
this.f32ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Float32Array, ElementKind.CLASS_PROTOTYPE);
this.f64ArrayPrototype = <ClassPrototype>this.require(CommonSymbols.Float64Array, ElementKind.CLASS_PROTOTYPE);
// resolve base prototypes of derived classes
var resolver = this.resolver;
for (let i = 0, k = queuedExtends.length; i < k; ++i) {
let thisPrototype = queuedExtends[i];
let extendsNode = assert(thisPrototype.extendsNode); // must be present if in queuedExtends
let baseElement = resolver.resolveTypeName(extendsNode.name, thisPrototype.parent); // reports
if (!baseElement) continue;
if (baseElement.kind == ElementKind.CLASS_PROTOTYPE) {
let basePrototype = <ClassPrototype>baseElement;
if (basePrototype.hasDecorator(DecoratorFlags.SEALED)) {
this.error(
DiagnosticCode.Class_0_is_sealed_and_cannot_be_extended,
extendsNode.range, (<ClassPrototype>baseElement).identifierNode.text
);
}
if (
basePrototype.hasDecorator(DecoratorFlags.UNMANAGED) !=
thisPrototype.hasDecorator(DecoratorFlags.UNMANAGED)
) {
this.error(
DiagnosticCode.Unmanaged_classes_cannot_extend_managed_classes_and_vice_versa,
Range.join(thisPrototype.identifierNode.range, extendsNode.range)
);
}
thisPrototype.basePrototype = basePrototype;
} else {
this.error(
DiagnosticCode.A_class_may_only_extend_another_class,
extendsNode.range
);
}
}
// set up global aliases
{
let globalAliases = options.globalAliases;
if (globalAliases) {
for (let [alias, name] of globalAliases) {
if (!name.length) continue; // explicitly disabled
let firstChar = name.charCodeAt(0);
if (firstChar >= CharCode._0 && firstChar <= CharCode._9) {
this.registerConstantInteger(alias, Type.i32, i64_new(<i32>parseInt(name, 10)));
} else {
let elementsByName = this.elementsByName;
let element = elementsByName.get(name);
if (element) {
if (elementsByName.has(alias)) throw new Error("duplicate global element: " + name);
elementsByName.set(alias, element);
}
else throw new Error("no such global element: " + name);
}
}
}
}
// register stdlib components
this.arrayPrototype = <ClassPrototype>this.require(CommonSymbols.Array, ElementKind.CLASS_PROTOTYPE);
this.fixedArrayPrototype = <ClassPrototype>this.require(CommonSymbols.FixedArray, ElementKind.CLASS_PROTOTYPE);
this.setPrototype = <ClassPrototype>this.require(CommonSymbols.Set, ElementKind.CLASS_PROTOTYPE);
this.mapPrototype = <ClassPrototype>this.require(CommonSymbols.Map, ElementKind.CLASS_PROTOTYPE);
this.abortInstance = this.lookupFunction(CommonSymbols.abort); // can be disabled
this.allocInstance = this.requireFunction(CommonSymbols.alloc);
this.reallocInstance = this.requireFunction(CommonSymbols.realloc);
this.freeInstance = this.requireFunction(CommonSymbols.free);
this.retainInstance = this.requireFunction(CommonSymbols.retain);
this.releaseInstance = this.requireFunction(CommonSymbols.release);
this.collectInstance = this.requireFunction(CommonSymbols.collect);
this.typeinfoInstance = this.requireFunction(CommonSymbols.typeinfo);
this.instanceofInstance = this.requireFunction(CommonSymbols.instanceof_);
this.visitInstance = this.requireFunction(CommonSymbols.visit);
this.allocArrayInstance = this.requireFunction(CommonSymbols.allocArray);
// mark module exports, i.e. to apply proper wrapping behavior on the boundaries
for (let file of this.filesByName.values()) {
let exports = file.exports;
if (exports !== null && file.source.sourceKind == SourceKind.USER_ENTRY) {
for (let element of exports.values()) this.markModuleExport(element);
}
}
}
/** Requires that a global library element of the specified kind is present and returns it. */
private require(name: string, kind: ElementKind): Element {
var element = this.lookupGlobal(name);
if (!element) throw new Error("missing " + name);
if (element.kind != kind) throw new Error("unexpected " + name);
return element;
}
/** Requires that a non-generic global class is present and returns it. */
private requireClass(name: string): Class {
var prototype = this.require(name, ElementKind.CLASS_PROTOTYPE);
var resolved = this.resolver.resolveClass(<ClassPrototype>prototype, null);