forked from AssemblyScript/assemblyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram.ts
4929 lines (4607 loc) · 173 KB
/
program.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview AssemblyScript's intermediate representation.
*
* The compiler uses Binaryen IR, which is fairly low level, as its
* primary intermediate representation, with the following structures
* holding any higher level information that cannot be represented by
* Binaryen IR alone, for example higher level types.
*
* Similar to the AST being composed of `Node`s in `Source`s, the IR is
* composed of `Element`s in a `Program`. Each class or function is
* represented by a "prototype" holding all the relevant information,
* including each's concrete instances. If a class or function is not
* generic, there is exactly one instance, otherwise there is one for
* each concrete set of type arguments.
*
* @license Apache-2.0
*/
// Element Base class of all elements
// ├─DeclaredElement Base class of elements with a declaration
// │ ├─TypedElement Base class of elements resolving to a type
// │ │ ├─TypeDefinition Type alias declaration
// │ │ ├─VariableLikeElement Base class of all variable-like elements
// │ │ │ ├─EnumValue Enum value
// │ │ │ ├─Global File global
// │ │ │ ├─Local Function local
// │ │ │ └─Property Class property (incl. instance fields)
// │ │ ├─IndexSignature Class index signature
// │ │ ├─Function Concrete function instance
// │ │ └─Class Concrete class instance
// │ ├─Namespace Namespace with static members
// │ ├─FunctionPrototype Prototype of concrete function instances
// │ ├─PropertyPrototype Prototype of concrete property instances
// │ └─ClassPrototype Prototype of concrete classe instances
// └─File File, analogous to Source in the AST
import {
CommonFlags,
PATH_DELIMITER,
STATIC_DELIMITER,
INSTANCE_DELIMITER,
GETTER_PREFIX,
SETTER_PREFIX,
INNER_DELIMITER,
INDEX_SUFFIX,
STUB_DELIMITER,
CommonNames,
Feature,
Target,
featureToString
} from "./common";
import {
Options
} from "./compiler";
import {
Range,
DiagnosticCode,
DiagnosticMessage,
DiagnosticEmitter
} from "./diagnostics";
import {
Type,
TypeKind,
Signature,
TypeFlags
} from "./types";
import {
Token
} from "./tokenizer";
import {
Node,
NodeKind,
Source,
SourceKind,
DecoratorNode,
DecoratorKind,
TypeParameterNode,
TypeNode,
NamedTypeNode,
FunctionTypeNode,
ArrowKind,
Expression,
IdentifierExpression,
LiteralKind,
StringLiteralExpression,
Statement,
ClassDeclaration,
DeclarationStatement,
EnumDeclaration,
EnumValueDeclaration,
ExportMember,
ExportDefaultStatement,
ExportStatement,
FieldDeclaration,
FunctionDeclaration,
ImportDeclaration,
ImportStatement,
InterfaceDeclaration,
MethodDeclaration,
NamespaceDeclaration,
TypeDeclaration,
VariableDeclaration,
VariableLikeDeclarationStatement,
VariableStatement,
ParameterKind,
ParameterNode,
TypeName
} from "./ast";
import {
Module,
FunctionRef,
MemorySegment,
getFunctionName
} from "./module";
import {
CharCode,
writeI8,
writeI16,
writeI32,
writeF32,
writeF64,
writeI64,
writeI32AsI64,
writeI64AsI32
} from "./util";
import {
Resolver
} from "./resolver";
import {
Flow
} from "./flow";
import {
Parser
} from "./parser";
import {
BuiltinNames
} from "./builtins";
// Memory manager constants
const AL_SIZE = 16;
const AL_MASK = AL_SIZE - 1;
/** 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
IndexedGet, // a[]
IndexedSet, // a[]=b
UncheckedIndexedGet, // unchecked(a[])
UncheckedIndexedSet, // unchecked(a[]=b)
// binary
Add, // a + b
Sub, // a - b
Mul, // a * b
Div, // a / b
Rem, // a % b
Pow, // a ** b
BitwiseAnd, // a & b
BitwiseOr, // a | b
BitwiseXor, // a ^ b
BitwiseShl, // a << b
BitwiseShr, // a >> b
BitwiseShrU, // a >>> b
Eq, // a == b, a === b
Ne, // a != b, a !== b
Gt, // a > b
Ge, // a >= b
Lt, // a < b
Le, // a <= b
// unary prefix
Plus, // +a
Minus, // -a
Not, // !a
BitwiseNot, // ~a
PrefixInc, // ++a
PrefixDec, // --a
// unary postfix
PostfixInc, // a++
PostfixDec // a--
// not overridable:
// LogicalAnd // a && b
// LogicalOr // 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.OperatorBinary: {
switch (arg.charCodeAt(0)) {
case CharCode.OpenBracket: {
if (arg == "[]") return OperatorKind.IndexedGet;
if (arg == "[]=") return OperatorKind.IndexedSet;
break;
}
case CharCode.OpenBrace: {
if (arg == "{}") return OperatorKind.UncheckedIndexedGet;
if (arg == "{}=") return OperatorKind.UncheckedIndexedSet;
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.BitwiseAnd;
break;
}
case CharCode.Bar: {
if (arg == "|") return OperatorKind.BitwiseOr;
break;
}
case CharCode.Caret: {
if (arg == "^") return OperatorKind.BitwiseXor;
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.BitwiseShr;
if (arg == ">>>") return OperatorKind.BitwiseShrU;
break;
}
case CharCode.LessThan: {
if (arg == "<") return OperatorKind.Lt;
if (arg == "<=") return OperatorKind.Le;
if (arg == "<<") return OperatorKind.BitwiseShl;
break;
}
}
break;
}
case DecoratorKind.OperatorPrefix: {
switch (arg.charCodeAt(0)) {
case CharCode.Plus: {
if (arg == "+") return OperatorKind.Plus;
if (arg == "++") return OperatorKind.PrefixInc;
break;
}
case CharCode.Minus: {
if (arg == "-") return OperatorKind.Minus;
if (arg == "--") return OperatorKind.PrefixDec;
break;
}
case CharCode.Exclamation: {
if (arg == "!") return OperatorKind.Not;
break;
}
case CharCode.Tilde: {
if (arg == "~") return OperatorKind.BitwiseNot;
break;
}
}
break;
}
case DecoratorKind.OperatorPostfix: {
switch (arg.charCodeAt(0)) {
case CharCode.Plus: {
if (arg == "++") return OperatorKind.PostfixInc;
break;
}
case CharCode.Minus: {
if (arg == "--") return OperatorKind.PostfixDec;
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.BitwiseAnd;
case Token.Bar:
case Token.Bar_Equals: return OperatorKind.BitwiseOr;
case Token.Caret:
case Token.Caret_Equals: return OperatorKind.BitwiseXor;
case Token.LessThan_LessThan:
case Token.LessThan_LessThan_Equals: return OperatorKind.BitwiseShl;
case Token.GreaterThan_GreaterThan:
case Token.GreaterThan_GreaterThan_Equals: return OperatorKind.BitwiseShr;
case Token.GreaterThan_GreaterThan_GreaterThan:
case Token.GreaterThan_GreaterThan_GreaterThan_Equals: return OperatorKind.BitwiseShrU;
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.BitwiseNot;
case Token.Plus_Plus: return OperatorKind.PrefixInc;
case Token.Minus_Minus: return OperatorKind.PrefixDec;
}
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.PostfixInc;
case Token.Minus_Minus: return OperatorKind.PostfixDec;
}
return OperatorKind.Invalid;
}
}
/** Represents an AssemblyScript program. */
export class Program extends DiagnosticEmitter {
/** Constructs a new program, optionally inheriting parser diagnostics. */
constructor(
/** Compiler options. */
public options: Options,
/** Shared array of diagnostic messages (emitted so far). */
diagnostics: DiagnosticMessage[] | null = null
) {
super(diagnostics);
this.module = Module.create(options.stackSize > 0, options.sizeTypeRef);
this.parser = new Parser(this.diagnostics, this.sources);
this.resolver = new Resolver(this);
let nativeFile = new File(this, Source.native);
this.nativeFile = nativeFile;
this.filesByName.set(nativeFile.internalName, nativeFile);
}
/** Module instance. */
module: Module;
/** 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;
/** Special native code file. */
nativeFile!: File;
/** Next class id. */
nextClassId: u32 = 0;
/** Next signature id. */
nextSignatureId: i32 = 0;
/** An indicator if the program has been initialized. */
initialized: bool = false;
// 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);
/** Module exports. */
moduleExports: Map<string,Element> = new Map();
/** Module imports. */
moduleImports: Map<string,Map<string,Element>> = new Map();
// Standard library
/** Gets the standard `ArrayBufferView` instance. */
get arrayBufferViewInstance(): Class {
let cached = this._arrayBufferViewInstance;
if (!cached) this._arrayBufferViewInstance = cached = this.requireClass(CommonNames.ArrayBufferView);
return cached;
}
private _arrayBufferViewInstance: Class | null = null;
/** Gets the standard `ArrayBuffer` instance. */
get arrayBufferInstance(): Class {
let cached = this._arrayBufferInstance;
if (!cached) this._arrayBufferInstance = cached = this.requireClass(CommonNames.ArrayBuffer);
return cached;
}
private _arrayBufferInstance: Class | null = null;
/** Gets the standard `Array` prototype. */
get arrayPrototype(): ClassPrototype {
let cached = this._arrayPrototype;
if (!cached) this._arrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Array, ElementKind.ClassPrototype);
return cached;
}
private _arrayPrototype: ClassPrototype | null = null;
/** Gets the standard `StaticArray` prototype. */
get staticArrayPrototype(): ClassPrototype {
let cached = this._staticArrayPrototype;
if (!cached) this._staticArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.StaticArray, ElementKind.ClassPrototype);
return cached;
}
private _staticArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Set` prototype. */
get setPrototype(): ClassPrototype {
let cached = this._setPrototype;
if (!cached) this._setPrototype = cached = <ClassPrototype>this.require(CommonNames.Set, ElementKind.ClassPrototype);
return cached;
}
private _setPrototype: ClassPrototype | null = null;
/** Gets the standard `Map` prototype. */
get mapPrototype(): ClassPrototype {
let cached = this._mapPrototype;
if (!cached) this._mapPrototype = cached = <ClassPrototype>this.require(CommonNames.Map, ElementKind.ClassPrototype);
return cached;
}
private _mapPrototype: ClassPrototype | null = null;
/** Gets the standard `Function` prototype. */
get functionPrototype(): ClassPrototype {
let cached = this._functionPrototype;
if (!cached) this._functionPrototype = cached = <ClassPrototype>this.require(CommonNames.Function, ElementKind.ClassPrototype);
return cached;
}
private _functionPrototype: ClassPrototype | null = null;
/** Gets the standard `Int8Array` prototype. */
get int8ArrayPrototype(): ClassPrototype {
let cached = this._int8ArrayPrototype;
if (!cached) this._int8ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Int8Array, ElementKind.ClassPrototype);
return cached;
}
private _int8ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Int16Array` prototype. */
get int16ArrayPrototype(): ClassPrototype {
let cached = this._int16ArrayPrototype;
if (!cached) this._int16ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Int16Array, ElementKind.ClassPrototype);
return cached;
}
private _int16ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Int32Array` prototype. */
get int32ArrayPrototype(): ClassPrototype {
let cached = this._int32ArrayPrototype;
if (!cached) this._int32ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Int32Array, ElementKind.ClassPrototype);
return cached;
}
private _int32ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Int64Array` prototype. */
get int64ArrayPrototype(): ClassPrototype {
let cached = this._int64ArrayPrototype;
if (!cached) this._int64ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Int64Array, ElementKind.ClassPrototype);
return cached;
}
private _int64ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Uint8Array` prototype. */
get uint8ArrayPrototype(): ClassPrototype {
let cached = this._uint8ArrayPrototype;
if (!cached) this._uint8ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Uint8Array, ElementKind.ClassPrototype);
return cached;
}
private _uint8ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Uint8ClampedArray` prototype. */
get uint8ClampedArrayPrototype(): ClassPrototype {
let cached = this._uint8ClampedArrayPrototype;
if (!cached) this._uint8ClampedArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Uint8ClampedArray, ElementKind.ClassPrototype);
return cached;
}
private _uint8ClampedArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Uint16Array` prototype. */
get uint16ArrayPrototype(): ClassPrototype {
let cached = this._uint16ArrayPrototype;
if (!cached) this._uint16ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Uint16Array, ElementKind.ClassPrototype);
return cached;
}
private _uint16ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Uint32Array` prototype. */
get uint32ArrayPrototype(): ClassPrototype {
let cached = this._uint32ArrayPrototype;
if (!cached) this._uint32ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Uint32Array, ElementKind.ClassPrototype);
return cached;
}
private _uint32ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Uint64Array` prototype. */
get uint64ArrayPrototype(): ClassPrototype {
let cached = this._uint64ArrayPrototype;
if (!cached) this._uint64ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Uint64Array, ElementKind.ClassPrototype);
return cached;
}
private _uint64ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Float32Array` prototype. */
get float32ArrayPrototype(): ClassPrototype {
let cached = this._float32ArrayPrototype;
if (!cached) this._float32ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Float32Array, ElementKind.ClassPrototype);
return cached;
}
private _float32ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `Float64Array` prototype. */
get float64ArrayPrototype(): ClassPrototype {
let cached = this._float64ArrayPrototype;
if (!cached) this._float64ArrayPrototype = cached = <ClassPrototype>this.require(CommonNames.Float64Array, ElementKind.ClassPrototype);
return cached;
}
private _float64ArrayPrototype: ClassPrototype | null = null;
/** Gets the standard `String` instance. */
get stringInstance(): Class {
let cached = this._stringInstance;
if (!cached) this._stringInstance = cached = this.requireClass(CommonNames.String);
return cached;
}
private _stringInstance: Class | null = null;
/** Gets the standard `RegExp` instance. */
get regexpInstance(): Class {
let cached = this._regexpInstance;
if (!cached) this._regexpInstance = cached = this.requireClass(CommonNames.RegExp);
return cached;
}
private _regexpInstance: Class | null = null;
/** Gets the standard `Object` instance. */
get objectInstance(): Class {
let cached = this._objectInstance;
if (!cached) this._objectInstance = cached = this.requireClass(CommonNames.Object);
return cached;
}
private _objectInstance: Class | null = null;
/** Gets the standard `TemplateStringsArray` instance. */
get templateStringsArrayInstance(): Class {
let cached = this._templateStringsArrayInstance;
if (!cached) this._templateStringsArrayInstance = cached = this.requireClass(CommonNames.TemplateStringsArray);
return cached;
}
private _templateStringsArrayInstance: Class | null = null;
/** Gets the standard `abort` instance, if not explicitly disabled. */
get abortInstance(): Function | null {
let prototype = this.lookup(CommonNames.abort);
if (!prototype || prototype.kind != ElementKind.FunctionPrototype) return null;
return this.resolver.resolveFunction(<FunctionPrototype>prototype, null);
}
// Runtime interface
/** Gets the runtime `__alloc(size: usize): usize` instance. */
get allocInstance(): Function {
let cached = this._allocInstance;
if (!cached) this._allocInstance = cached = this.requireFunction(CommonNames.alloc);
return cached;
}
private _allocInstance: Function | null = null;
/** Gets the runtime `__realloc(ptr: usize, newSize: usize): usize` instance. */
get reallocInstance(): Function {
let cached = this._reallocInstance;
if (!cached) this._reallocInstance = cached = this.requireFunction(CommonNames.realloc);
return cached;
}
private _reallocInstance: Function | null = null;
/** Gets the runtime `__free(ptr: usize): void` instance. */
get freeInstance(): Function {
let cached = this._freeInstance;
if (!cached) this._freeInstance = cached = this.requireFunction(CommonNames.free);
return cached;
}
private _freeInstance: Function | null = null;
/** Gets the runtime `__new(size: usize, id: u32): usize` instance. */
get newInstance(): Function {
let cached = this._newInstance;
if (!cached) this._newInstance = cached = this.requireFunction(CommonNames.new_);
return cached;
}
private _newInstance: Function | null = null;
/** Gets the runtime `__renew(ptr: usize, size: usize): usize` instance. */
get renewInstance(): Function {
let cached = this._renewInstance;
if (!cached) this._renewInstance = cached = this.requireFunction(CommonNames.renew);
return cached;
}
private _renewInstance: Function | null = null;
/** Gets the runtime `__link(parentPtr: usize, childPtr: usize, expectMultiple: bool): void` instance. */
get linkInstance(): Function {
let cached = this._linkInstance;
if (!cached) this._linkInstance = cached = this.requireFunction(CommonNames.link);
return cached;
}
private _linkInstance: Function | null = null;
/** Gets the runtime `__collect(): void` instance. */
get collectInstance(): Function {
let cached = this._collectInstance;
if (!cached) this._collectInstance = cached = this.requireFunction(CommonNames.collect);
return cached;
}
private _collectInstance: Function | null = null;
/** Gets the runtime `__visit(ptr: usize, cookie: u32): void` instance. */
get visitInstance(): Function {
let cached = this._visitInstance;
if (!cached) this._visitInstance = cached = this.requireFunction(CommonNames.visit);
return cached;
}
private _visitInstance: Function | null = null;
/** Gets the runtime `__newBuffer(size: usize, id: u32, data: usize = 0): usize` instance. */
get newBufferInstance(): Function {
let cached = this._newBufferInstance;
if (!cached) this._newBufferInstance = cached = this.requireFunction(CommonNames.newBuffer);
return cached;
}
private _newBufferInstance: Function | null = null;
/** Gets the runtime `__newArray(length: i32, alignLog2: usize, id: u32, data: usize = 0): usize` instance. */
get newArrayInstance(): Function {
let cached = this._newArrayInstance;
if (!cached) this._newArrayInstance = cached = this.requireFunction(CommonNames.newArray);
return cached;
}
private _newArrayInstance: Function | null = null;
/** Gets the runtime's internal `BLOCK` instance. */
get BLOCKInstance(): Class {
let cached = this._BLOCKInstance;
if (!cached) this._BLOCKInstance = cached = this.requireClass(CommonNames.BLOCK);
return cached;
}
private _BLOCKInstance: Class | null = null;
/** Gets the runtime's internal `OBJECT` instance. */
get OBJECTInstance(): Class {
let cached = this._OBJECTInstance;
if (!cached) this._OBJECTInstance = cached = this.requireClass(CommonNames.OBJECT);
return cached;
}
private _OBJECTInstance: Class | null = null;
// Utility
/** Obtains the source matching the specified internal path. */
getSource(internalPath: string): string | null {
let sources = this.sources;
for (let i = 0; i < sources.length; ++i) {
let source = sources[i];
if (source.internalPath == internalPath) return source.text;
}
return null;
}
/** Gets the overhead of a memory manager block. */
get blockOverhead(): i32 {
// BLOCK | data...
// ^ 16b alignment
return this.BLOCKInstance.nextMemoryOffset;
}
/** Gets the overhead of a managed object, excl. block overhead, incl. alignment. */
get objectOverhead(): i32 {
// OBJECT+align | data...
// └ 0 ┘ ^ 16b alignment
return (this.OBJECTInstance.nextMemoryOffset - this.blockOverhead + AL_MASK) & ~AL_MASK;
}
/** Gets the total overhead of a managed object, incl. block overhead. */
get totalOverhead(): i32 {
// BLOCK | OBJECT+align | data...
// └ = TOTAL ┘ ^ 16b alignment
return this.blockOverhead + this.objectOverhead;
}
searchFunctionByRef(ref: FunctionRef): Function | null {
const modifiedFunctionName = getFunctionName(ref);
if (modifiedFunctionName) {
const instancesByName = this.instancesByName;
if (instancesByName.has(modifiedFunctionName)) {
const element = assert(instancesByName.get(modifiedFunctionName));
if (element.kind == ElementKind.Function) {
return <Function>element;
}
}
}
return null;
}
/** Computes the next properly aligned offset of a memory manager block, given the current bump offset. */
computeBlockStart(currentOffset: i32): i32 {
let blockOverhead = this.blockOverhead;
return ((currentOffset + blockOverhead + AL_MASK) & ~AL_MASK) - blockOverhead;
}
/** Computes the next properly aligned offset of a memory manager block, given the current bump offset. */
computeBlockStart64(currentOffset: i64): i64 {
let blockOverhead = i64_new(this.blockOverhead);
return i64_sub(i64_align(i64_add(currentOffset, blockOverhead), AL_SIZE), blockOverhead);
}
/** Computes the size of a memory manager block, excl. block overhead. */
computeBlockSize(payloadSize: i32, isManaged: bool): i32 {
// see: std/rt/tlsf.ts, computeSize; becomes mmInfo
if (isManaged) payloadSize += this.objectOverhead;
// we know that payload must be aligned, and that block sizes must be chosen
// so that blocks are adjacent with the next payload aligned. hence, block
// size is payloadSize rounded up to where the next block would start:
let blockSize = this.computeBlockStart(payloadSize);
// make sure that block size is valid according to TLSF requirements
let blockOverhead = this.blockOverhead;
let blockMinsize = ((3 * this.options.usizeType.byteSize + blockOverhead + AL_MASK) & ~AL_MASK) - blockOverhead;
if (blockSize < blockMinsize) blockSize = blockMinsize;
const blockMaxsize = 1 << 30; // 1 << (FL_BITS + SB_BITS - 1), exclusive
const tagsMask = 3;
if (blockSize >= blockMaxsize || (blockSize & tagsMask) != 0) {
throw new Error("invalid block size");
}
return blockSize;
}
/** 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 {
let range = Source.native.range;
return Node.createVariableDeclaration(
Node.createIdentifierExpression(name, range),
null, flags, null, null, 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 {
let range = Source.native.range;
let identifier = Node.createIdentifierExpression(name, range);
return Node.createTypeDeclaration(
identifier,
null, flags, null,
Node.createOmittedType(range),
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 {
let range = Source.native.range;
let signature = this.nativeDummySignature;
if (!signature) {
this.nativeDummySignature = signature = Node.createFunctionType([],
Node.createNamedType( // ^ AST signature doesn't really matter, is overridden anyway
Node.createSimpleTypeName(CommonNames.void_, range),
null, false, range
),
null, false, range
);
}
return Node.createFunctionDeclaration(
Node.createIdentifierExpression(name, range),
null, flags, null, signature, null, 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 {
let range = Source.native.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
),
null,
signature
);
}
/** Gets the (possibly merged) program element linked to the specified declaration. */
getElementByDeclaration(declaration: DeclarationStatement): DeclaredElement | null {
let elementsByDeclaration = this.elementsByDeclaration;
return elementsByDeclaration.has(declaration)
? assert(elementsByDeclaration.get(declaration))
: null;
}
/** Initializes the program and its elements prior to compilation. */
initialize(): void {
if (this.initialized) return;
this.initialized = true;
let options = this.options;
// register native types
this.registerNativeType(CommonNames.i8, Type.i8);
this.registerNativeType(CommonNames.i16, Type.i16);
this.registerNativeType(CommonNames.i32, Type.i32);
this.registerNativeType(CommonNames.i64, Type.i64);
this.registerNativeType(CommonNames.isize, options.isizeType);
this.registerNativeType(CommonNames.u8, Type.u8);
this.registerNativeType(CommonNames.u16, Type.u16);
this.registerNativeType(CommonNames.u32, Type.u32);
this.registerNativeType(CommonNames.u64, Type.u64);
this.registerNativeType(CommonNames.usize, options.usizeType);
this.registerNativeType(CommonNames.bool, Type.bool);
this.registerNativeType(CommonNames.f32, Type.f32);
this.registerNativeType(CommonNames.f64, Type.f64);
this.registerNativeType(CommonNames.void_, Type.void);
this.registerNativeType(CommonNames.number, Type.f64); // alias
this.registerNativeType(CommonNames.boolean, Type.bool); // alias
this.nativeFile.add(CommonNames.native, new TypeDefinition(
CommonNames.native,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonNames.native, CommonFlags.Export | CommonFlags.Generic),
DecoratorFlags.Builtin
));
this.nativeFile.add(CommonNames.indexof, new TypeDefinition(
CommonNames.indexof,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonNames.indexof, CommonFlags.Export | CommonFlags.Generic),
DecoratorFlags.Builtin
));
this.nativeFile.add(CommonNames.valueof, new TypeDefinition(
CommonNames.valueof,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonNames.valueof, CommonFlags.Export | CommonFlags.Generic),
DecoratorFlags.Builtin
));
this.nativeFile.add(CommonNames.returnof, new TypeDefinition(
CommonNames.returnof,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonNames.returnof, CommonFlags.Export | CommonFlags.Generic),
DecoratorFlags.Builtin
));
this.nativeFile.add(CommonNames.nonnull, new TypeDefinition(
CommonNames.nonnull,
this.nativeFile,
this.makeNativeTypeDeclaration(CommonNames.nonnull, CommonFlags.Export | CommonFlags.Generic),