forked from AssemblyScript/assemblyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresolver.ts
More file actions
1171 lines (1105 loc) Β· 40.3 KB
/
resolver.ts
File metadata and controls
1171 lines (1105 loc) Β· 40.3 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
/**
* Resolve infrastructure to obtain types and elements.
* @module resolver
*//***/
import {
DiagnosticEmitter,
DiagnosticCode
} from "./diagnostics";
import {
Program,
ElementKind,
OperatorKind,
FlowFlags,
Element,
Class,
ClassPrototype,
Function,
FunctionTarget,
FunctionPrototype,
VariableLikeElement,
Property,
DecoratorFlags,
FieldPrototype,
Field
} from "./program";
import {
SignatureNode,
ParameterKind,
CommonTypeNode,
NodeKind,
TypeNode,
TypeParameterNode,
Node,
Range,
IdentifierExpression,
CallExpression,
ElementAccessExpression,
PropertyAccessExpression,
LiteralExpression,
LiteralKind,
ParenthesizedExpression,
AssertionExpression,
Expression
} from "./ast";
import {
Type,
Signature,
typesToString
} from "./types";
import {
PATH_DELIMITER,
INSTANCE_DELIMITER,
CommonFlags
} from "./common";
/** Indicates whether errors are reported or not. */
export enum ReportMode {
/** Report errors. */
REPORT,
/** Swallow errors. */
SWALLOW
}
/** Provides tools to resolve types and expressions. */
export class Resolver extends DiagnosticEmitter {
/** The program this resolver belongs to. */
program: Program;
/** Target expression of the previously resolved property or element access. */
currentThisExpression: Expression | null = null;
/** Element expression of the previously resolved element access. */
currentElementExpression : Expression | null = null;
/** Constructs the resolver for the specified program. */
constructor(program: Program) {
super(program.diagnostics);
this.program = program;
}
/** Resolves a {@link CommonTypeNode} to a concrete {@link Type}. */
resolveType(
node: CommonTypeNode,
contextualTypeArguments: Map<string,Type> | null = null,
reportMode = ReportMode.REPORT
): Type | null {
// handle signatures specifically
if (node.kind == NodeKind.SIGNATURE) {
let signature = this.resolveSignature(<SignatureNode>node, contextualTypeArguments, reportMode);
if (!signature) return null;
return node.isNullable ? signature.type.asNullable() : signature.type;
}
// now dealing with TypeNode
assert(node.kind == NodeKind.TYPE);
var typeNode = <TypeNode>node;
var simpleName = typeNode.name.text;
var globalName = simpleName;
var localName = typeNode.range.source.internalPath + PATH_DELIMITER + simpleName; // TODO cache
// check file-global / program-global enum or class
{
let elementsLookup = this.program.elementsLookup;
let element: Element | null;
if (
(element = elementsLookup.get(localName)) || // file-global
(element = elementsLookup.get(globalName)) // program-global
) {
switch (element.kind) {
case ElementKind.ENUM: {
if (typeNode.typeArguments !== null && typeNode.typeArguments.length) {
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Type_0_is_not_generic,
node.range, element.internalName
);
}
return null;
}
return Type.i32;
}
case ElementKind.CLASS_PROTOTYPE: {
let instance = this.resolveClassInclTypeArguments(
<ClassPrototype>element,
typeNode.typeArguments,
contextualTypeArguments,
node
); // reports
if (!instance) return null;
return node.isNullable ? instance.type.asNullable() : instance.type;
}
}
}
}
// check (global) type alias
{
let alias = this.program.typeAliases.get(simpleName);
if (alias) return this.resolveType(alias.type, contextualTypeArguments, reportMode);
}
// resolve parameters
{
let typeArgumentNodes = typeNode.typeArguments;
if (typeArgumentNodes) {
let numTypeArguments = typeArgumentNodes.length;
let paramTypes = new Array<Type>(numTypeArguments);
for (let i = 0; i < numTypeArguments; ++i) {
let paramType = this.resolveType( // reports
typeArgumentNodes[i],
contextualTypeArguments,
reportMode
);
if (!paramType) return null;
paramTypes[i] = paramType;
}
if (numTypeArguments) { // can't be a placeholder if it has parameters
let instanceKey = typesToString(paramTypes);
if (instanceKey.length) {
localName += "<" + instanceKey + ">";
globalName += "<" + instanceKey + ">";
}
} else if (contextualTypeArguments) {
let placeholderType = contextualTypeArguments.get(globalName);
if (placeholderType) return placeholderType;
}
}
}
// check file-global / program-global type
{
let typesLookup = this.program.typesLookup;
let type: Type | null;
if (
(type = typesLookup.get(localName)) ||
(type = typesLookup.get(globalName))
) {
return type;
}
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Cannot_find_name_0,
typeNode.name.range, globalName
);
}
return null;
}
/** Resolves a {@link SignatureNode} to a concrete {@link Signature}. */
resolveSignature(
node: SignatureNode,
contextualTypeArguments: Map<string,Type> | null = null,
reportMode: ReportMode = ReportMode.REPORT
): Signature | null {
var explicitThisType = node.explicitThisType;
var thisType: Type | null = null;
if (explicitThisType) {
thisType = this.resolveType(explicitThisType, contextualTypeArguments, reportMode);
if (!thisType) return null;
}
var parameterTypeNodes = node.parameters;
var numParameters = parameterTypeNodes.length;
var parameterTypes = new Array<Type>(numParameters);
var parameterNames = new Array<string>(numParameters);
var requiredParameters = 0;
var hasRest = false;
for (let i = 0; i < numParameters; ++i) {
let parameterTypeNode = parameterTypeNodes[i];
switch (parameterTypeNode.parameterKind) {
case ParameterKind.DEFAULT: {
requiredParameters = i + 1;
break;
}
case ParameterKind.REST: {
assert(i == numParameters);
hasRest = true;
break;
}
}
let parameterType = this.resolveType(
assert(parameterTypeNode.type),
contextualTypeArguments,
reportMode
);
if (!parameterType) return null;
parameterTypes[i] = parameterType;
parameterNames[i] = parameterTypeNode.name.text;
}
var returnTypeNode = node.returnType;
var returnType: Type | null;
if (returnTypeNode) {
returnType = this.resolveType(returnTypeNode, contextualTypeArguments, reportMode);
if (!returnType) return null;
} else {
returnType = Type.void;
}
var signature = new Signature(parameterTypes, returnType, thisType);
signature.parameterNames = parameterNames;
signature.requiredParameters = requiredParameters;
signature.hasRest = hasRest;
return signature;
}
/** Resolves an array of type arguments to concrete types. */
resolveTypeArguments(
typeParameters: TypeParameterNode[],
typeArgumentNodes: CommonTypeNode[] | null,
contextualTypeArguments: Map<string,Type> | null = null,
alternativeReportNode: Node | null = null,
reportMode: ReportMode = ReportMode.REPORT
): Type[] | null {
var parameterCount = typeParameters.length;
var argumentCount = typeArgumentNodes ? typeArgumentNodes.length : 0;
if (parameterCount != argumentCount) {
if (argumentCount) {
this.error(
DiagnosticCode.Expected_0_type_arguments_but_got_1,
Range.join(
(<TypeNode[]>typeArgumentNodes)[0].range,
(<TypeNode[]>typeArgumentNodes)[argumentCount - 1].range
),
parameterCount.toString(10), argumentCount.toString(10)
);
} else if (alternativeReportNode) {
this.error(
DiagnosticCode.Expected_0_type_arguments_but_got_1,
alternativeReportNode.range.atEnd, parameterCount.toString(10), "0"
);
}
return null;
}
var typeArguments = new Array<Type>(parameterCount);
for (let i = 0; i < parameterCount; ++i) {
let type = this.resolveType( // reports
(<TypeNode[]>typeArgumentNodes)[i],
contextualTypeArguments,
reportMode
);
if (!type) return null;
// TODO: check extendsType
typeArguments[i] = type;
}
return typeArguments;
}
/** Resolves an identifier to the element it refers to. */
resolveIdentifier(
identifier: IdentifierExpression,
context: Element | null,
reportMode: ReportMode = ReportMode.REPORT
): Element | null {
var name = identifier.text;
var element: Element | null;
if (context) {
switch (context.kind) {
case ElementKind.FUNCTION: { // search locals, use prototype
element = (<Function>context).flow.getScopedLocal(name);
if (element) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return element;
}
context = (<Function>context).prototype.parent;
break;
}
case ElementKind.CLASS: { // use prototype
context = (<Class>context).prototype.parent;
break;
}
}
// search context
while (context) {
let members = context.members;
if (members) {
if (element = members.get(name)) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return element;
}
}
context = context.parent;
}
}
// search current file
var elementsLookup = this.program.elementsLookup;
if (element = elementsLookup.get(identifier.range.source.internalPath + PATH_DELIMITER + name)) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return element; // GLOBAL, FUNCTION_PROTOTYPE, CLASS_PROTOTYPE
}
// search global scope
if (element = elementsLookup.get(name)) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return element; // GLOBAL, FUNCTION_PROTOTYPE, CLASS_PROTOTYPE
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Cannot_find_name_0,
identifier.range, name
);
}
return null;
}
/** Resolves a property access to the element it refers to. */
resolvePropertyAccess(
propertyAccess: PropertyAccessExpression,
contextualFunction: Function,
reportMode: ReportMode = ReportMode.REPORT
): Element | null {
// start by resolving the lhs target (expression before the last dot)
var targetExpression = propertyAccess.expression;
var target = this.resolveExpression(targetExpression, contextualFunction, reportMode); // reports
if (!target) return null;
// at this point we know exactly what the target is, so look up the element within
var propertyName = propertyAccess.property.text;
// Resolve variable-likes to the class type they reference first
switch (target.kind) {
case ElementKind.GLOBAL:
case ElementKind.LOCAL:
case ElementKind.FIELD: {
let type = (<VariableLikeElement>target).type;
assert(type != Type.void);
let classReference = type.classReference;
if (!classReference) {
this.error(
DiagnosticCode.Property_0_does_not_exist_on_type_1,
propertyAccess.property.range, propertyName, (<VariableLikeElement>target).type.toString()
);
return null;
}
target = classReference;
break;
}
case ElementKind.PROPERTY: {
let getter = this.resolveFunction(
assert((<Property>target).getterPrototype),
null,
null,
reportMode
);
if (!getter) return null;
let classReference = getter.signature.returnType.classReference;
if (!classReference) {
this.error(
DiagnosticCode.Property_0_does_not_exist_on_type_1,
propertyAccess.property.range, propertyName, getter.signature.returnType.toString()
);
return null;
}
target = classReference;
break;
}
case ElementKind.CLASS: {
let elementExpression = this.currentElementExpression;
if (elementExpression) {
let indexedGet = (<Class>target).lookupOverload(OperatorKind.INDEXED_GET);
if (!indexedGet) {
this.error(
DiagnosticCode.Index_signature_is_missing_in_type_0,
elementExpression.range, (<Class>target).internalName
);
return null;
}
let returnType = indexedGet.signature.returnType;
if (!(target = returnType.classReference)) {
this.error(
DiagnosticCode.Property_0_does_not_exist_on_type_1,
propertyAccess.property.range, propertyName, returnType.toString()
);
return null;
}
}
break;
}
}
// Look up the member within
switch (target.kind) {
case ElementKind.CLASS_PROTOTYPE:
case ElementKind.CLASS: {
do {
let members = target.members;
let member: Element | null;
if (members && (member = members.get(propertyName))) {
this.currentThisExpression = targetExpression;
this.currentElementExpression = null;
return member; // instance FIELD, static GLOBAL, FUNCTION_PROTOTYPE...
}
// traverse inherited static members on the base prototype if target is a class prototype
if (target.kind == ElementKind.CLASS_PROTOTYPE) {
if ((<ClassPrototype>target).basePrototype) {
target = <ClassPrototype>(<ClassPrototype>target).basePrototype;
} else {
break;
}
// traverse inherited instance members on the base class if target is a class instance
} else if (target.kind == ElementKind.CLASS) {
if ((<Class>target).base) {
target = <Class>(<Class>target).base;
} else {
break;
}
} else {
break;
}
} while (true);
break;
}
default: { // enums or other namespace-like elements
let members = target.members;
if (members) {
let member = members.get(propertyName);
if (member) {
this.currentThisExpression = targetExpression;
this.currentElementExpression = null;
return member; // static ENUMVALUE, static GLOBAL, static FUNCTION_PROTOTYPE...
}
}
break;
}
}
this.error(
DiagnosticCode.Property_0_does_not_exist_on_type_1,
propertyAccess.property.range, propertyName, target.internalName
);
return null;
}
resolveElementAccess(
elementAccess: ElementAccessExpression,
contextualFunction: Function,
reportMode: ReportMode = ReportMode.REPORT
): Element | null {
var targetExpression = elementAccess.expression;
var target = this.resolveExpression(targetExpression, contextualFunction, reportMode);
if (!target) return null;
switch (target.kind) {
case ElementKind.GLOBAL:
case ElementKind.LOCAL:
case ElementKind.FIELD: {
let type = (<VariableLikeElement>target).type;
if (target = type.classReference) {
this.currentThisExpression = targetExpression;
this.currentElementExpression = elementAccess.elementExpression;
return target;
}
break;
}
case ElementKind.CLASS: { // element access on element access
let indexedGet = (<Class>target).lookupOverload(OperatorKind.INDEXED_GET);
if (!indexedGet) {
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Index_signature_is_missing_in_type_0,
elementAccess.range, (<Class>target).internalName
);
}
return null;
}
let returnType = indexedGet.signature.returnType;
if (target = returnType.classReference) {
this.currentThisExpression = targetExpression;
this.currentElementExpression = elementAccess.elementExpression;
return target;
}
break;
}
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Operation_not_supported,
targetExpression.range
);
}
return null;
}
resolveExpression(
expression: Expression,
contextualFunction: Function,
reportMode: ReportMode = ReportMode.REPORT
): Element | null {
while (expression.kind == NodeKind.PARENTHESIZED) {
expression = (<ParenthesizedExpression>expression).expression;
}
switch (expression.kind) {
case NodeKind.ASSERTION: {
let type = this.resolveType(
(<AssertionExpression>expression).toType,
contextualFunction.flow.contextualTypeArguments,
reportMode
);
if (type) {
let classType = type.classReference;
if (classType) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return classType;
}
}
return null;
}
case NodeKind.BINARY: { // TODO: string concatenation, mostly
throw new Error("not implemented");
}
case NodeKind.THIS: { // -> Class / ClassPrototype
if (contextualFunction.flow.is(FlowFlags.INLINE_CONTEXT)) {
let explicitLocal = contextualFunction.flow.getScopedLocal("this");
if (explicitLocal) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return explicitLocal;
}
}
let parent = contextualFunction.parent;
if (parent) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return parent;
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode._this_cannot_be_referenced_in_current_location,
expression.range
);
}
return null;
}
case NodeKind.SUPER: { // -> Class
if (contextualFunction.flow.is(FlowFlags.INLINE_CONTEXT)) {
let explicitLocal = contextualFunction.flow.getScopedLocal("super");
if (explicitLocal) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return explicitLocal;
}
}
let parent = contextualFunction.parent;
if (parent && parent.kind == ElementKind.CLASS && (parent = (<Class>parent).base)) {
this.currentThisExpression = null;
this.currentElementExpression = null;
return parent;
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode._super_can_only_be_referenced_in_a_derived_class,
expression.range
);
}
return null;
}
case NodeKind.IDENTIFIER: {
return this.resolveIdentifier(<IdentifierExpression>expression, contextualFunction, reportMode);
}
case NodeKind.LITERAL: {
switch ((<LiteralExpression>expression).literalKind) {
case LiteralKind.STRING: {
this.currentThisExpression = expression;
this.currentElementExpression = null;
return this.program.stringInstance;
}
// case LiteralKind.ARRAY: // TODO
}
break;
}
case NodeKind.PROPERTYACCESS: {
return this.resolvePropertyAccess(
<PropertyAccessExpression>expression,
contextualFunction,
reportMode
);
}
case NodeKind.ELEMENTACCESS: {
return this.resolveElementAccess(
<ElementAccessExpression>expression,
contextualFunction,
reportMode
);
}
case NodeKind.CALL: {
let targetExpression = (<CallExpression>expression).expression;
let target = this.resolveExpression(targetExpression, contextualFunction, reportMode);
if (!target) return null;
if (target.kind == ElementKind.FUNCTION_PROTOTYPE) {
let instance = this.resolveFunctionInclTypeArguments(
<FunctionPrototype>target,
(<CallExpression>expression).typeArguments,
contextualFunction.flow.contextualTypeArguments,
expression,
reportMode
);
if (!instance) return null;
let returnType = instance.signature.returnType;
let classType = returnType.classReference;
if (classType) {
// reuse resolvedThisExpression (might be property access)
// reuse resolvedElementExpression (might be element access)
return classType;
} else {
let signature = returnType.signatureReference;
if (signature) {
let functionTarget = signature.cachedFunctionTarget;
if (!functionTarget) {
functionTarget = new FunctionTarget(this.program, signature);
signature.cachedFunctionTarget = functionTarget;
}
// reuse resolvedThisExpression (might be property access)
// reuse resolvedElementExpression (might be element access)
return functionTarget;
}
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures,
targetExpression.range, target.internalName
);
}
return null;
}
break;
}
}
if (reportMode == ReportMode.REPORT) {
this.error(
DiagnosticCode.Operation_not_supported,
expression.range
);
}
return null;
}
/** Resolves a function prototype to an instance using the specified concrete type arguments. */
resolveFunction(
prototype: FunctionPrototype,
typeArguments: Type[] | null,
contextualTypeArguments: Map<string,Type> | null = null,
reportMode: ReportMode = ReportMode.REPORT
): Function | null {
var instanceKey = typeArguments ? typesToString(typeArguments) : "";
var instance = prototype.instances.get(instanceKey);
if (instance) return instance;
var declaration = prototype.declaration;
var isInstance = prototype.is(CommonFlags.INSTANCE);
var classPrototype = prototype.classPrototype;
// inherit contextual type arguments as provided. might be overridden.
var inheritedTypeArguments = contextualTypeArguments;
contextualTypeArguments = new Map();
if (inheritedTypeArguments) {
for (let [inheritedName, inheritedType] of inheritedTypeArguments) {
contextualTypeArguments.set(
inheritedName,
inheritedType
);
}
}
// override with class type arguments if a partially resolved instance method
var classTypeArguments = prototype.classTypeArguments;
if (classTypeArguments) { // set only if partially resolved
assert(prototype.is(CommonFlags.INSTANCE));
let classDeclaration = assert(classPrototype).declaration;
let classTypeParameters = classDeclaration.typeParameters;
let numClassTypeParameters = classTypeParameters.length;
assert(numClassTypeParameters == classTypeArguments.length);
for (let i = 0; i < numClassTypeParameters; ++i) {
contextualTypeArguments.set(
classTypeParameters[i].name.text,
classTypeArguments[i]
);
}
} else {
assert(!classTypeArguments);
}
// override with function specific type arguments
var signatureNode = declaration.signature;
var functionTypeParameters = declaration.typeParameters;
var numFunctionTypeArguments: i32;
if (typeArguments && (numFunctionTypeArguments = typeArguments.length)) {
assert(functionTypeParameters && numFunctionTypeArguments == functionTypeParameters.length);
for (let i = 0; i < numFunctionTypeArguments; ++i) {
contextualTypeArguments.set(
(<TypeParameterNode[]>functionTypeParameters)[i].name.text,
typeArguments[i]
);
}
} else {
assert(!functionTypeParameters || functionTypeParameters.length == 0);
}
// resolve class if an instance method
var classInstance: Class | null = null;
var thisType: Type | null = null;
if (isInstance) {
classInstance = this.resolveClass(
assert(classPrototype),
classTypeArguments,
contextualTypeArguments,
reportMode
);
if (!classInstance) return null;
thisType = classInstance.type;
contextualTypeArguments.set("this", thisType);
}
// resolve signature node
var signatureParameters = signatureNode.parameters;
var signatureParameterCount = signatureParameters.length;
var parameterTypes = new Array<Type>(signatureParameterCount);
var parameterNames = new Array<string>(signatureParameterCount);
var requiredParameters = 0;
for (let i = 0; i < signatureParameterCount; ++i) {
let parameterDeclaration = signatureParameters[i];
if (parameterDeclaration.parameterKind == ParameterKind.DEFAULT) {
requiredParameters = i + 1;
}
let typeNode = assert(parameterDeclaration.type);
let parameterType = this.resolveType(typeNode, contextualTypeArguments, reportMode);
if (!parameterType) return null;
parameterTypes[i] = parameterType;
parameterNames[i] = parameterDeclaration.name.text;
}
var returnType: Type;
if (prototype.is(CommonFlags.SET)) {
returnType = Type.void; // not annotated
} else if (prototype.is(CommonFlags.CONSTRUCTOR)) {
returnType = assert(classInstance).type; // not annotated
} else {
let typeNode = assert(signatureNode.returnType);
let type = this.resolveType(typeNode, contextualTypeArguments, reportMode);
if (!type) return null;
returnType = type;
}
var signature = new Signature(parameterTypes, returnType, thisType);
signature.parameterNames = parameterNames;
signature.requiredParameters = requiredParameters;
var internalName = prototype.internalName;
if (instanceKey.length) internalName += "<" + instanceKey + ">";
instance = new Function(
prototype,
internalName,
signature,
classInstance
? classInstance
: classPrototype,
contextualTypeArguments
);
prototype.instances.set(instanceKey, instance);
this.program.instancesLookup.set(internalName, instance);
return instance;
}
/** Resolves a function prototype partially by applying the specified type arguments. */
resolveFunctionPartially(
prototype: FunctionPrototype,
typeArguments: Type[] | null,
reportMode: ReportMode = ReportMode.REPORT
): FunctionPrototype | null {
assert(prototype.is(CommonFlags.INSTANCE));
var classPrototype = assert(prototype.classPrototype);
if (!(typeArguments && typeArguments.length)) return prototype; // no need to clone
var simpleName = prototype.simpleName;
var partialKey = typesToString(typeArguments);
var partialPrototype = new FunctionPrototype(
this.program,
simpleName,
classPrototype.internalName + "<" + partialKey + ">" + INSTANCE_DELIMITER + simpleName,
prototype.declaration,
classPrototype,
prototype.decoratorFlags
);
partialPrototype.flags = prototype.flags;
partialPrototype.operatorKind = prototype.operatorKind;
partialPrototype.classTypeArguments = typeArguments;
return partialPrototype;
}
/** Resolves a function prototype to an instance by first resolving the specified type arguments. */
resolveFunctionInclTypeArguments(
prototype: FunctionPrototype,
typeArgumentNodes: CommonTypeNode[] | null,
contextualTypeArguments: Map<string,Type> | null,
reportNode: Node,
reportMode: ReportMode = ReportMode.REPORT
): Function | null {
var resolvedTypeArguments: Type[] | null = null;
if (prototype.is(CommonFlags.GENERIC)) {
assert(typeArgumentNodes != null && typeArgumentNodes.length != 0);
resolvedTypeArguments = this.resolveTypeArguments( // reports
assert(prototype.declaration.typeParameters),
typeArgumentNodes,
contextualTypeArguments,
reportNode,
reportMode
);
if (!resolvedTypeArguments) return null;
}
return this.resolveFunction(
prototype,
resolvedTypeArguments,
contextualTypeArguments,
reportMode
);
}
/** Resolves a class prototype using the specified concrete type arguments. */
resolveClass(
prototype: ClassPrototype,
typeArguments: Type[] | null,
contextualTypeArguments: Map<string,Type> | null = null,
reportMode: ReportMode = ReportMode.REPORT
): Class | null {
var instanceKey = typeArguments ? typesToString(typeArguments) : "";
// Check if this exact instance has already been resolved
var instance = prototype.instances.get(instanceKey);
if (instance) return instance;
// Copy contextual type arguments so we don't pollute the original map
var inheritedTypeArguments = contextualTypeArguments;
contextualTypeArguments = new Map();
if (inheritedTypeArguments) {
for (let [inheritedName, inheritedType] of inheritedTypeArguments) {
contextualTypeArguments.set(inheritedName, inheritedType);
}
}
// Insert contextual type arguments for this operation. Internally, this method is always
// called with matching type parameter / argument counts.
var declaration = prototype.declaration;
if (typeArguments) {
let typeParameters = declaration.typeParameters;
let expectedTypeArguments = typeParameters.length;
let actualTypeArguments = typeArguments.length;
assert(actualTypeArguments == expectedTypeArguments);
for (let i = 0; i < actualTypeArguments; ++i) {
contextualTypeArguments.set(typeParameters[i].name.text, typeArguments[i]);
}
} else {
assert(declaration.typeParameters.length == 0);
}
// Resolve base class if applicable
var baseClass: Class | null = null;
if (declaration.extendsType) {
let baseClassType = this.resolveType(
declaration.extendsType,
contextualTypeArguments,
reportMode
);
if (!baseClassType) return null;
if (!(baseClass = baseClassType.classReference)) {
if (reportMode == ReportMode.REPORT) {
this.program.error(
DiagnosticCode.A_class_may_only_extend_another_class,
declaration.extendsType.range
);
}
return null;
}
if (baseClass.hasDecorator(DecoratorFlags.SEALED)) {
if (reportMode == ReportMode.REPORT) {
this.program.error(
DiagnosticCode.Class_0_is_sealed_and_cannot_be_extended,
declaration.extendsType.range, baseClass.internalName
);
}
return null;
}
if (baseClass.hasDecorator(DecoratorFlags.UNMANAGED) != prototype.hasDecorator(DecoratorFlags.UNMANAGED)) {
if (reportMode == ReportMode.REPORT) {
this.program.error(
DiagnosticCode.Unmanaged_classes_cannot_extend_managed_classes_and_vice_versa,
Range.join(declaration.name.range, declaration.extendsType.range)
);
}
return null;
}
}
// Construct the instance and remember that it has been resolved already
var simpleName = prototype.simpleName;
var internalName = prototype.internalName;
if (instanceKey.length) {
simpleName += "<" + instanceKey + ">";
internalName += "<" + instanceKey + ">";
}
instance = new Class(prototype, simpleName, internalName, typeArguments, baseClass);
instance.contextualTypeArguments = contextualTypeArguments;
prototype.instances.set(instanceKey, instance);
this.program.instancesLookup.set(internalName, instance);
// Inherit base class members and set up the initial memory offset for own fields
var memoryOffset: u32 = 0;
if (baseClass) {
if (baseClass.members) {
if (!instance.members) instance.members = new Map();
for (let inheritedMember of baseClass.members.values()) {
instance.members.set(inheritedMember.simpleName, inheritedMember);
}
}
memoryOffset = baseClass.currentMemoryOffset;
}
// Resolve constructor by first applying the class type arguments
if (prototype.constructorPrototype) {
let constructorPartial = this.resolveFunctionPartially(
prototype.constructorPrototype,
typeArguments,
reportMode
);
if (!constructorPartial) return null;
instance.constructorInstance = this.resolveFunction(constructorPartial, null, null, reportMode);
}
// Resolve instance members
if (prototype.instanceMembers) {
for (let member of prototype.instanceMembers.values()) {
switch (member.kind) {
// Lay out fields in advance
case ElementKind.FIELD_PROTOTYPE: {
if (!instance.members) instance.members = new Map();
let fieldDeclaration = (<FieldPrototype>member).declaration;
let fieldType: Type | null = null;
// TODO: handle duplicate non-private fields
if (!fieldDeclaration.type) {
if (baseClass !== null && baseClass.members !== null) {
let baseField = baseClass.members.get((<FieldPrototype>member).simpleName);
if (baseField && !baseField.is(CommonFlags.PRIVATE)) {
assert(baseField.kind == ElementKind.FIELD);
fieldType = (<Field>baseField).type;
}
}