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
3575 lines (3296 loc) Β· 114 KB
/
program.ts
File metadata and controls
3575 lines (3296 loc) Β· 114 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,
LIBRARY_PREFIX,
GETTER_PREFIX,
SETTER_PREFIX,
FILESPACE_PREFIX
} from "./common";
import {
Options,
Feature
} from "./compiler";
import {
DiagnosticCode,
DiagnosticMessage,
DiagnosticEmitter
} from "./diagnostics";
import {
Type,
TypeKind,
TypeFlags,
Signature
} from "./types";
import {
Node,
NodeKind,
Source,
Range,
CommonTypeNode,
TypeParameterNode,
DecoratorNode,
DecoratorKind,
Expression,
IdentifierExpression,
LiteralExpression,
LiteralKind,
StringLiteralExpression,
ClassDeclaration,
DeclarationStatement,
EnumDeclaration,
EnumValueDeclaration,
ExportMember,
ExportStatement,
FieldDeclaration,
FunctionDeclaration,
ImportDeclaration,
ImportStatement,
InterfaceDeclaration,
MethodDeclaration,
NamespaceDeclaration,
TypeDeclaration,
VariableDeclaration,
VariableLikeDeclarationStatement,
VariableStatement,
decoratorNameToKind,
findDecorator
} from "./ast";
import {
Module,
NativeType,
FunctionRef,
ExpressionRef,
ExpressionId,
BinaryOp,
UnaryOp,
getExpressionId,
getGetLocalIndex,
isTeeLocal,
getSetLocalValue,
getBinaryOp,
getConstValueI32,
getBinaryLeft,
getBinaryRight,
getUnaryOp,
getExpressionType,
getLoadBytes,
isLoadSigned,
getIfTrue,
getIfFalse,
getSelectThen,
getSelectElse,
getCallTarget,
getBlockChildCount,
getBlockChild,
getBlockName,
getConstValueF32,
getConstValueF64,
getConstValueI64Low
} from "./module";
import {
CharCode
} from "./util";
import {
Resolver
} from "./resolver";
/** Represents a yet unresolved import. */
class QueuedImport {
localName: string;
externalName: string;
externalNameAlt: string;
declaration: ImportDeclaration | null; // not set if a filespace
}
/** Represents a yet unresolved export. */
class QueuedExport {
externalName: string;
isReExport: bool;
member: ExportMember;
}
/** Represents a type alias. */
class TypeAlias {
typeParameters: TypeParameterNode[] | null;
type: CommonTypeNode;
}
/** Represents a module-level export. */
class ModuleExport {
element: Element;
identifier: IdentifierExpression;
}
/** 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
}
/** Returns the operator kind represented by the specified decorator and string argument. */
function operatorKindFromDecorator(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;
}
const noTypesYet = new Map<string,Type>();
/** Represents an AssemblyScript program. */
export class Program extends DiagnosticEmitter {
/** Array of source files. */
sources: Source[];
/** Resolver instance. */
resolver: Resolver;
/** Diagnostic offset used where successively obtaining the next diagnostic. */
diagnosticsOffset: i32 = 0;
/** Compiler options. */
options: Options;
/** Elements by internal name. */
elementsLookup: Map<string,Element> = new Map();
/** Class and function instances by internal name. */
instancesLookup: Map<string,Element> = new Map();
/** Types by internal name. */
typesLookup: Map<string,Type> = noTypesYet;
/** Declared type aliases. */
typeAliases: Map<string,TypeAlias> = new Map();
/** File-level exports by exported name. */
fileLevelExports: Map<string,Element> = new Map();
/** Module-level exports by exported name. */
moduleLevelExports: Map<string,ModuleExport> = new Map();
/** ArrayBuffer instance reference. */
arrayBufferInstance: Class | null = null;
/** Array prototype reference. */
arrayPrototype: ClassPrototype | null = null;
/** String instance reference. */
stringInstance: Class | null = null;
/** Start function reference. */
startFunction: FunctionPrototype;
/** Main function reference, if present. */
mainFunction: FunctionPrototype | null = null;
/** Abort function reference, if present. */
abortInstance: Function | null = null;
/** Memory allocation function. */
memoryAllocateInstance: Function | null = null;
/** Whether a garbage collector is present or not. */
hasGC: bool = false;
/** Garbage collector allocation function. */
gcAllocateInstance: Function | null = null;
/** Garbage collector link function called when a managed object is referenced from a parent. */
gcLinkInstance: Function | null = null;
/** Garbage collector mark function called to on reachable managed objects. */
gcMarkInstance: Function | null = null;
/** Size of a managed object header. */
gcHeaderSize: u32 = 0;
/** Offset of the GC hook. */
gcHookOffset: u32 = 0;
/** Currently processing filespace. */
currentFilespace: Filespace;
/** Constructs a new program, optionally inheriting parser diagnostics. */
constructor(diagnostics: DiagnosticMessage[] | null = null) {
super(diagnostics);
this.resolver = new Resolver(this);
this.sources = [];
}
/** Gets a source by its exact path. */
getSource(normalizedPath: string): Source | null {
var sources = this.sources;
for (let i = 0, k = sources.length; i < k; ++i) {
let source = sources[i];
if (source.normalizedPath == normalizedPath) return source;
}
return null;
}
/** Looks up the source for the specified possibly ambiguous path. */
lookupSourceByPath(normalizedPathWithoutExtension: string): Source | null {
var tmp: string;
return (
this.getSource(normalizedPathWithoutExtension + ".ts") ||
this.getSource(normalizedPathWithoutExtension + "/index.ts") ||
this.getSource((tmp = LIBRARY_PREFIX + normalizedPathWithoutExtension) + ".ts") ||
this.getSource( tmp + "/index.ts")
);
}
/** Initializes the program and its elements prior to compilation. */
initialize(options: Options): void {
this.options = options;
// add built-in types
this.typesLookup = new Map([
["i8", Type.i8],
["i16", Type.i16],
["i32", Type.i32],
["i64", Type.i64],
["isize", options.isizeType],
["u8", Type.u8],
["u16", Type.u16],
["u32", Type.u32],
["u64", Type.u64],
["usize", options.usizeType],
["bool", Type.bool],
["f32", Type.f32],
["f64", Type.f64],
["void", Type.void],
["number", Type.f64],
["boolean", Type.bool]
]);
// add compiler hints
this.setConstantInteger("ASC_TARGET", Type.i32,
i64_new(options.isWasm64 ? 2 : 1));
this.setConstantInteger("ASC_NO_TREESHAKING", Type.bool,
i64_new(options.noTreeShaking ? 1 : 0, 0));
this.setConstantInteger("ASC_NO_ASSERT", Type.bool,
i64_new(options.noAssert ? 1 : 0, 0));
this.setConstantInteger("ASC_MEMORY_BASE", Type.i32,
i64_new(options.memoryBase, 0));
this.setConstantInteger("ASC_OPTIMIZE_LEVEL", Type.i32,
i64_new(options.optimizeLevelHint, 0));
this.setConstantInteger("ASC_SHRINK_LEVEL", Type.i32,
i64_new(options.shrinkLevelHint, 0));
this.setConstantInteger("ASC_FEATURE_MUTABLE_GLOBAL", Type.bool,
i64_new(options.hasFeature(Feature.MUTABLE_GLOBAL) ? 1 : 0, 0));
this.setConstantInteger("ASC_FEATURE_SIGN_EXTENSION", Type.bool,
i64_new(options.hasFeature(Feature.SIGN_EXTENSION) ? 1 : 0, 0));
// remember deferred elements
var queuedImports = new Array<QueuedImport>();
var queuedExports = new Map<string,QueuedExport>();
var queuedExtends = new Array<ClassPrototype>();
var queuedImplements = new Array<ClassPrototype>();
// build initial lookup maps of internal names to declarations
for (let i = 0, k = this.sources.length; i < k; ++i) {
let source = this.sources[i];
// create one filespace per source
let filespace = new Filespace(this, source);
this.elementsLookup.set(filespace.internalName, filespace);
this.currentFilespace = filespace;
// process this source's statements
let statements = source.statements;
for (let j = 0, l = statements.length; j < l; ++j) {
let statement = statements[j];
switch (statement.kind) {
case NodeKind.CLASSDECLARATION: {
this.initializeClass(<ClassDeclaration>statement, queuedExtends, queuedImplements);
break;
}
case NodeKind.ENUMDECLARATION: {
this.initializeEnum(<EnumDeclaration>statement);
break;
}
case NodeKind.EXPORT: {
this.initializeExports(<ExportStatement>statement, queuedExports);
break;
}
case NodeKind.FUNCTIONDECLARATION: {
this.initializeFunction(<FunctionDeclaration>statement);
break;
}
case NodeKind.IMPORT: {
this.initializeImports(<ImportStatement>statement, queuedExports, queuedImports);
break;
}
case NodeKind.INTERFACEDECLARATION: {
this.initializeInterface(<InterfaceDeclaration>statement);
break;
}
case NodeKind.NAMESPACEDECLARATION: {
this.initializeNamespace(<NamespaceDeclaration>statement, queuedExtends, queuedImplements);
break;
}
case NodeKind.TYPEDECLARATION: {
this.initializeTypeAlias(<TypeDeclaration>statement);
break;
}
case NodeKind.VARIABLE: {
this.initializeVariables(<VariableStatement>statement);
break;
}
}
}
}
// queued imports should be resolvable now through traversing exports and queued exports
for (let i = 0; i < queuedImports.length;) {
let queuedImport = queuedImports[i];
let declaration = queuedImport.declaration;
if (declaration) { // named
let element = this.tryLocateImport(queuedImport.externalName, queuedExports);
if (element) {
this.elementsLookup.set(queuedImport.localName, element);
queuedImports.splice(i, 1);
} else {
if (element = this.tryLocateImport(queuedImport.externalNameAlt, queuedExports)) {
this.elementsLookup.set(queuedImport.localName, element);
queuedImports.splice(i, 1);
} else {
this.error(
DiagnosticCode.Module_0_has_no_exported_member_1,
declaration.range,
(<ImportStatement>declaration.parent).path.value,
declaration.externalName.text
);
++i;
}
}
} else { // filespace
let element = this.elementsLookup.get(queuedImport.externalName);
if (element) {
this.elementsLookup.set(queuedImport.localName, element);
queuedImports.splice(i, 1);
} else {
if (element = this.elementsLookup.get(queuedImport.externalNameAlt)) {
this.elementsLookup.set(queuedImport.localName, element);
queuedImports.splice(i, 1);
} else {
assert(false); // already reported by the parser not finding the file
++i;
}
}
}
}
// queued exports should be resolvable now that imports are finalized
for (let [exportName, queuedExport] of queuedExports) {
let currentExport: QueuedExport | null = queuedExport; // nullable below
let element: Element | null;
do {
if (currentExport.isReExport) {
if (element = this.fileLevelExports.get(currentExport.externalName)) {
this.setExportAndCheckLibrary(
exportName,
element,
queuedExport.member.externalName
);
break;
}
currentExport = queuedExports.get(currentExport.externalName);
if (!currentExport) {
this.error(
DiagnosticCode.Module_0_has_no_exported_member_1,
queuedExport.member.externalName.range,
(<StringLiteralExpression>(<ExportStatement>queuedExport.member.parent).path).value,
queuedExport.member.externalName.text
);
}
} else {
if (
// normal export
(element = this.elementsLookup.get(currentExport.externalName)) ||
// library re-export
(element = this.elementsLookup.get(currentExport.member.name.text))
) {
this.setExportAndCheckLibrary(
exportName,
element,
queuedExport.member.externalName
);
} else {
this.error(
DiagnosticCode.Cannot_find_name_0,
queuedExport.member.range, queuedExport.member.name.text
);
}
break;
}
} while (currentExport);
}
// resolve base prototypes of derived classes
var resolver = this.resolver;
for (let i = 0, k = queuedExtends.length; i < k; ++i) {
let derivedPrototype = queuedExtends[i];
let derivedDeclaration = derivedPrototype.declaration;
let derivedType = assert(derivedDeclaration.extendsType);
let baseElement = resolver.resolveIdentifier(derivedType.name, null); // reports
if (!baseElement) continue;
if (baseElement.kind == ElementKind.CLASS_PROTOTYPE) {
let basePrototype = <ClassPrototype>baseElement;
derivedPrototype.basePrototype = basePrototype;
} else {
this.error(
DiagnosticCode.A_class_may_only_extend_another_class,
derivedType.range
);
}
}
// set up global aliases
{
let globalAliases = options.globalAliases;
if (globalAliases) {
for (let [alias, name] of globalAliases) {
if (!name.length) continue; // explicitly disabled
let element = this.elementsLookup.get(name);
if (element) this.elementsLookup.set(alias, element);
else throw new Error("element not found: " + name);
}
}
}
// register 'ArrayBuffer'
if (this.elementsLookup.has("ArrayBuffer")) {
let element = assert(this.elementsLookup.get("ArrayBuffer"));
assert(element.kind == ElementKind.CLASS_PROTOTYPE);
this.arrayBufferInstance = resolver.resolveClass(<ClassPrototype>element, null);
}
// register 'Array'
if (this.elementsLookup.has("Array")) {
let element = assert(this.elementsLookup.get("Array"));
assert(element.kind == ElementKind.CLASS_PROTOTYPE);
this.arrayPrototype = <ClassPrototype>element;
}
// register 'String'
if (this.elementsLookup.has("String")) {
let element = assert(this.elementsLookup.get("String"));
assert(element.kind == ElementKind.CLASS_PROTOTYPE);
let instance = resolver.resolveClass(<ClassPrototype>element, null);
if (instance) {
if (this.typesLookup.has("string")) {
let declaration = (<ClassPrototype>element).declaration;
this.error(
DiagnosticCode.Duplicate_identifier_0,
declaration.name.range, declaration.programLevelInternalName
);
} else {
this.stringInstance = instance;
this.typesLookup.set("string", instance.type);
}
}
}
// register 'start'
{
let element = assert(this.elementsLookup.get("start"));
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
this.startFunction = <FunctionPrototype>element;
}
// register 'main' if present
if (this.moduleLevelExports.has("main")) {
let element = (<ModuleExport>this.moduleLevelExports.get("main")).element;
if (
element.kind == ElementKind.FUNCTION_PROTOTYPE &&
!(<FunctionPrototype>element).isAny(CommonFlags.GENERIC | CommonFlags.AMBIENT)
) {
(<FunctionPrototype>element).set(CommonFlags.MAIN);
this.mainFunction = <FunctionPrototype>element;
}
}
// register 'abort' if present
if (this.elementsLookup.has("abort")) {
let element = <Element>this.elementsLookup.get("abort");
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
let instance = this.resolver.resolveFunction(<FunctionPrototype>element, null);
if (instance) this.abortInstance = instance;
}
// register 'memory.allocate' if present
if (this.elementsLookup.has("memory")) {
let element = <Element>this.elementsLookup.get("memory");
let members = element.members;
if (members) {
if (members.has("allocate")) {
element = assert(members.get("allocate"));
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
let instance = this.resolver.resolveFunction(<FunctionPrototype>element, null);
if (instance) this.memoryAllocateInstance = instance;
}
}
}
// register GC hooks if present
if (
this.elementsLookup.has("__gc_allocate") &&
this.elementsLookup.has("__gc_link") &&
this.elementsLookup.has("__gc_mark")
) {
// __gc_allocate(usize, (ref: usize) => void): usize
let element = <Element>this.elementsLookup.get("__gc_allocate");
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
let gcAllocateInstance = assert(this.resolver.resolveFunction(<FunctionPrototype>element, null));
let signature = gcAllocateInstance.signature;
assert(signature.parameterTypes.length == 2);
assert(signature.parameterTypes[0] == this.options.usizeType);
assert(signature.parameterTypes[1].signatureReference);
assert(signature.returnType == this.options.usizeType);
// __gc_link(usize, usize): void
element = <Element>this.elementsLookup.get("__gc_link");
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
let gcLinkInstance = assert(this.resolver.resolveFunction(<FunctionPrototype>element, null));
signature = gcLinkInstance.signature;
assert(signature.parameterTypes.length == 2);
assert(signature.parameterTypes[0] == this.options.usizeType);
assert(signature.parameterTypes[1] == this.options.usizeType);
assert(signature.returnType == Type.void);
// __gc_mark(usize): void
element = <Element>this.elementsLookup.get("__gc_mark");
assert(element.kind == ElementKind.FUNCTION_PROTOTYPE);
let gcMarkInstance = assert(this.resolver.resolveFunction(<FunctionPrototype>element, null));
signature = gcMarkInstance.signature;
assert(signature.parameterTypes.length == 1);
assert(signature.parameterTypes[0] == this.options.usizeType);
assert(signature.returnType == Type.void);
this.gcAllocateInstance = gcAllocateInstance;
this.gcLinkInstance = gcLinkInstance;
this.gcMarkInstance = gcMarkInstance;
let gcHookOffset = 2 * options.usizeType.byteSize; // .next + .prev
this.gcHookOffset = gcHookOffset;
this.gcHeaderSize = (gcHookOffset + 4 + 7) & ~7; // + .hook index + alignment
this.hasGC = true;
}
}
/** Sets a constant integer value. */
setConstantInteger(globalName: string, type: Type, value: I64): void {
assert(type.is(TypeFlags.INTEGER));
this.elementsLookup.set(globalName,
new Global(this, globalName, globalName, type, null, DecoratorFlags.NONE)
.withConstantIntegerValue(value)
);
}
/** Sets a constant float value. */
setConstantFloat(globalName: string, type: Type, value: f64): void {
assert(type.is(TypeFlags.FLOAT));
this.elementsLookup.set(globalName,
new Global(this, globalName, globalName, type, null, DecoratorFlags.NONE)
.withConstantFloatValue(value)
);
}
/** Tries to locate an import by traversing exports and queued exports. */
private tryLocateImport(
externalName: string,
queuedNamedExports: Map<string,QueuedExport>
): Element | null {
var element: Element | null;
var fileLevelExports = this.fileLevelExports;
do {
if (element = fileLevelExports.get(externalName)) return element;
let queuedExport = queuedNamedExports.get(externalName);
if (!queuedExport) break;
if (queuedExport.isReExport) {
externalName = queuedExport.externalName;
continue;
}
return this.elementsLookup.get(queuedExport.externalName);
} while (true);
return null;
}
/** Checks that only supported decorators are present. */
private checkDecorators(
decorators: DecoratorNode[],
acceptedFlags: DecoratorFlags
): DecoratorFlags {
var presentFlags = DecoratorFlags.NONE;
for (let i = 0, k = decorators.length; i < k; ++i) {
let decorator = decorators[i];
let kind = decoratorNameToKind(decorator.name);
let flag = decoratorKindToFlag(kind);
if (flag) {
if (flag == DecoratorFlags.BUILTIN) {
if (decorator.range.source.isLibrary) {
presentFlags |= flag;
} else {
this.error(
DiagnosticCode.Decorator_0_is_not_valid_here,
decorator.range, decorator.name.range.toString()
);
}
} else if (!(acceptedFlags & flag)) {
this.error(
DiagnosticCode.Decorator_0_is_not_valid_here,
decorator.range, decorator.name.range.toString()
);
} else if (presentFlags & flag) {
this.error(
DiagnosticCode.Duplicate_decorator,
decorator.range, decorator.name.range.toString()
);
} else {
presentFlags |= flag;
}
}
}
return presentFlags;
}
/** Checks and sets up global options of an element. */
private checkGlobal(
element: Element,
declaration: DeclarationStatement
): void {
var parentNode = declaration.parent;
// alias globally if explicitly annotated @global or exported from a top-level library file
if (
(element.hasDecorator(DecoratorFlags.GLOBAL)) ||
(
declaration.range.source.isLibrary &&
element.is(CommonFlags.EXPORT) &&
(
assert(parentNode).kind == NodeKind.SOURCE ||
(
<Node>parentNode).kind == NodeKind.VARIABLE &&
assert((<Node>parentNode).parent).kind == NodeKind.SOURCE
)
)
) {
let globalName = declaration.programLevelInternalName;
if (this.elementsLookup.has(globalName)) {
this.error(
DiagnosticCode.Duplicate_identifier_0,
declaration.name.range, element.internalName
);
} else {
this.elementsLookup.set(globalName, element);
}
}
// builtins use the global name directly
if (element.hasDecorator(DecoratorFlags.BUILTIN)) {
element.internalName = declaration.programLevelInternalName;
}
}
/** Initializes a class declaration. */
private initializeClass(
declaration: ClassDeclaration,
queuedExtends: ClassPrototype[],
queuedImplements: ClassPrototype[],
namespace: Element | null = null
): void {
var internalName = declaration.fileLevelInternalName;
if (this.elementsLookup.has(internalName)) {
this.error(
DiagnosticCode.Duplicate_identifier_0,
declaration.name.range, internalName
);
return;
}
var decorators = declaration.decorators;
var simpleName = declaration.name.text;
var prototype = new ClassPrototype(
this,
simpleName,
internalName,
declaration,
decorators
? this.checkDecorators(decorators,
DecoratorFlags.GLOBAL |
DecoratorFlags.SEALED |
DecoratorFlags.UNMANAGED
)
: DecoratorFlags.NONE
);
prototype.parent = namespace;
this.elementsLookup.set(internalName, prototype);
var implementsTypes = declaration.implementsTypes;
if (implementsTypes) {
let numImplementsTypes = implementsTypes.length;
if (prototype.hasDecorator(DecoratorFlags.UNMANAGED)) {
if (numImplementsTypes) {
this.error(
DiagnosticCode.Unmanaged_classes_cannot_implement_interfaces,
Range.join(
declaration.name.range,
implementsTypes[numImplementsTypes - 1].range
)
);
}
// remember classes that implement interfaces
} else if (numImplementsTypes) {
for (let i = 0; i < numImplementsTypes; ++i) {
this.warning( // TODO
DiagnosticCode.Operation_not_supported,
implementsTypes[i].range
);
}
queuedImplements.push(prototype);
}
}
// remember classes that extend another one
if (declaration.extendsType) queuedExtends.push(prototype);
// add as namespace member if applicable
if (namespace) {
if (namespace.members) {
if (namespace.members.has(simpleName)) {
this.error(
DiagnosticCode.Duplicate_identifier_0,
declaration.name.range, internalName
);
return;
}
} else {
namespace.members = new Map();
}
namespace.members.set(simpleName, prototype);
if (namespace.is(CommonFlags.MODULE_EXPORT) && prototype.is(CommonFlags.EXPORT)) {
prototype.set(CommonFlags.MODULE_EXPORT);
}
// otherwise add to file-level exports if exported
} else if (prototype.is(CommonFlags.EXPORT)) {
if (this.fileLevelExports.has(internalName)) {
this.error(
DiagnosticCode.Export_declaration_conflicts_with_exported_declaration_of_0,
declaration.name.range, internalName
);
return;
}
this.fileLevelExports.set(internalName, prototype);
this.currentFilespace.members.set(simpleName, prototype);
if (prototype.is(CommonFlags.EXPORT) && declaration.range.source.isEntry) {
if (this.moduleLevelExports.has(simpleName)) {
let existingExport = <ModuleExport>this.moduleLevelExports.get(simpleName);
this.error(
DiagnosticCode.Export_declaration_conflicts_with_exported_declaration_of_0,
declaration.name.range, existingExport.element.internalName
);
return;
}
prototype.set(CommonFlags.MODULE_EXPORT);
this.moduleLevelExports.set(simpleName, <ModuleExport>{
element: prototype,
identifier: declaration.name
});
}
}
// initialize members
var memberDeclarations = declaration.members;
for (let i = 0, k = memberDeclarations.length; i < k; ++i) {
let memberDeclaration = memberDeclarations[i];
switch (memberDeclaration.kind) {
case NodeKind.FIELDDECLARATION: {
this.initializeField(<FieldDeclaration>memberDeclaration, prototype);
break;
}
case NodeKind.METHODDECLARATION: {
if (memberDeclaration.isAny(CommonFlags.GET | CommonFlags.SET)) {
this.initializeAccessor(<MethodDeclaration>memberDeclaration, prototype);
} else {
this.initializeMethod(<MethodDeclaration>memberDeclaration, prototype);
}
break;
}
default: {
assert(false); // should have been reported while parsing
return;
}
}
}
this.checkGlobal(prototype, declaration);
}
/** Initializes a field of a class or interface. */
private initializeField(
declaration: FieldDeclaration,
classPrototype: ClassPrototype
): void {
var name = declaration.name.text;
var internalName = declaration.fileLevelInternalName;
var decorators = declaration.decorators;
var isInterface = classPrototype.kind == ElementKind.INTERFACE_PROTOTYPE;
// static fields become global variables
if (declaration.is(CommonFlags.STATIC)) {
if (isInterface) {
// should have been reported while parsing
assert(false);
}
if (this.elementsLookup.has(internalName)) {
this.error(
DiagnosticCode.Duplicate_identifier_0,
declaration.name.range, internalName
);
return;
}
if (classPrototype.members) {