-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathanalyzer.ts
More file actions
1316 lines (1124 loc) · 47.5 KB
/
analyzer.ts
File metadata and controls
1316 lines (1124 loc) · 47.5 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
// https://www.angelcode.com/angelscript/sdk/docs/manual/doc_expressions.html
import {
AccessModifier,
funcHeadDestructor,
isFunctionHeadReturnValue,
isMemberMethodInPostOp,
NodeArgList,
NodeAssign,
NodeCase,
NodeCast,
NodeClass,
NodeCondition,
NodeDoWhile,
NodeEnum,
NodeExpr,
NodeExprPostOp,
NodeExprPostOp1,
NodeExprPostOp2,
NodeExprStat,
NodeExprTerm,
NodeExprTerm2,
NodeExprValue,
NodeFor,
NodeFunc,
NodeFuncCall,
NodeFuncDef,
NodeIf,
NodeInitList,
NodeInterface,
NodeIntfMethod,
NodeLambda,
NodeLiteral,
NodeMixin,
NodeName,
NodeNamespace,
NodeParamList,
NodeReturn,
NodeScope,
NodeScript,
NodeStatBlock,
NodeStatement,
NodeSwitch,
NodeTry,
NodeType,
NodeTypeDef,
NodeVar,
NodeVarAccess,
NodeVirtualProp,
NodeWhile,
ParsedEnumMember,
ParsedRange
} from "../compiler_parser/nodes";
import {
getSourceNodeName,
isSourceNodeClassOrInterface,
SymbolFunction,
SymbolObject,
SymbolType,
SymbolVariable
} from "./symbolObject";
import {diagnostic} from "../code/diagnostic";
import {LocationInfo, NumberLiterals, TokenKind} from "../compiler_tokenizer/tokens";
import {
AnalyzedScope,
copySymbolsInScope,
createAnonymousIdentifier,
createSymbolScope,
createSymbolScopeAndInsert,
findGlobalScope,
findScopeShallowly,
findScopeShallowlyOrInsert,
findScopeWithParentByNodes,
isSymbolConstructorInScope, SymbolScope
} from "./symbolScope";
import {checkFunctionMatch} from "./checkFunction";
import {ParserToken} from "../compiler_parser/parserToken";
import {canTypeConvert, checkTypeMatch, isAllowedToAccessMember} from "./checkType";
import {
getIdentifierInType,
getLocationBetween,
getNextTokenIfExist,
getNodeLocation
} from "../compiler_parser/nodesUtils";
import {
builtinBoolType,
builtinSetterValueToken,
builtinThisToken,
resolvedBuiltinBool,
resolvedBuiltinDouble,
resolvedBuiltinFloat,
resolvedBuiltinInt,
resolvedBuiltinString,
tryGetBuiltInType
} from "./symbolBuiltin";
import {ComplementKind, pushHintOfCompletionScopeToParent} from "./symbolComplement";
import {
findSymbolShallowly,
findSymbolWithParent,
getSymbolAndScopeIfExist,
insertSymbolObject,
isResolvedAutoType,
stringifyResolvedType,
stringifyResolvedTypes,
TemplateTranslation,
tryInsertSymbolObject
} from "./symbolUtils";
import {Mutable} from "../utils/utilities";
import {getGlobalSettings} from "../code/settings";
import {createVirtualToken} from "../compiler_tokenizer/tokenUtils";
import assert = require("node:assert");
import {ResolvedType} from "./resolvedType";
export type HoistQueue = (() => void)[];
export type AnalyzeQueue = (() => void)[];
// SCRIPT ::= {IMPORT | ENUM | TYPEDEF | CLASS | MIXIN | INTERFACE | FUNCDEF | VIRTPROP | VAR | FUNC | NAMESPACE | ';'}
// NAMESPACE ::= 'namespace' IDENTIFIER {'::' IDENTIFIER} '{' SCRIPT '}'
// ENUM ::= {'shared' | 'external'} 'enum' IDENTIFIER (';' | ('{' IDENTIFIER ['=' EXPR] {',' IDENTIFIER ['=' EXPR]} '}'))
// CLASS ::= {'shared' | 'abstract' | 'final' | 'external'} 'class' IDENTIFIER (';' | ([':' IDENTIFIER {',' IDENTIFIER}] '{' {VIRTPROP | FUNC | VAR | FUNCDEF} '}'))
// TYPEDEF ::= 'typedef' PRIMTYPE IDENTIFIER ';'
// FUNC ::= {'shared' | 'external'} ['private' | 'protected'] [((TYPE ['&']) | '~')] IDENTIFIER PARAMLIST ['const'] FUNCATTR (';' | STATBLOCK)
export function analyzeFunc(scope: SymbolScope, func: NodeFunc) {
if (func.head === funcHeadDestructor) {
analyzeStatBlock(scope, func.statBlock);
return;
}
// Add arguments to the scope
analyzeParamList(scope, func.paramList);
// Analyze the scope
analyzeStatBlock(scope, func.statBlock);
}
// INTERFACE ::= {'external' | 'shared'} 'interface' IDENTIFIER (';' | ([':' IDENTIFIER {',' IDENTIFIER}] '{' {VIRTPROP | INTFMTHD} '}'))
// VAR ::= ['private'|'protected'] TYPE IDENTIFIER [( '=' (INITLIST | ASSIGN)) | ARGLIST] {',' IDENTIFIER [( '=' (INITLIST | ASSIGN)) | ARGLIST]} ';'
export function analyzeVar(scope: SymbolScope, nodeVar: NodeVar, isInstanceMember: boolean) {
let varType = analyzeType(scope, nodeVar.type);
for (const declaredVar of nodeVar.variables) {
const initializer = declaredVar.initializer;
if (initializer === undefined) continue;
const initType = analyzeVarInitializer(scope, varType, declaredVar.identifier, initializer);
// Resolve the auto type
if (initType !== undefined && isResolvedAutoType(varType)) {
varType = initType;
}
}
insertVariables(scope, varType, nodeVar, isInstanceMember);
}
export function insertVariables(scope: SymbolScope, varType: ResolvedType | undefined, nodeVar: NodeVar, isInstanceMember: boolean) {
for (const declaredVar of nodeVar.variables) {
const variable: SymbolVariable = SymbolVariable.create({
declaredPlace: declaredVar.identifier,
declaredScope: scope,
type: varType,
isInstanceMember: isInstanceMember,
accessRestriction: nodeVar.accessor,
});
insertSymbolObject(scope.symbolMap, variable);
}
}
export function analyzeVarInitializer(
scope: SymbolScope,
varType: ResolvedType | undefined,
varIdentifier: ParserToken,
initializer: NodeInitList | NodeAssign | NodeArgList
): ResolvedType | undefined {
if (initializer.nodeName === NodeName.InitList) {
return analyzeInitList(scope, initializer);
} else if (initializer.nodeName === NodeName.Assign) {
const exprType = analyzeAssign(scope, initializer);
checkTypeMatch(exprType, varType, initializer.nodeRange);
return exprType;
} else if (initializer.nodeName === NodeName.ArgList) {
if (varType === undefined || varType.symbolType instanceof SymbolFunction) return undefined;
return analyzeConstructorCaller(scope, varIdentifier, initializer, varType);
}
}
// IMPORT ::= 'import' TYPE ['&'] IDENTIFIER PARAMLIST FUNCATTR 'from' STRING ';'
// FUNCDEF ::= {'external' | 'shared'} 'funcdef' TYPE ['&'] IDENTIFIER PARAMLIST ';'
// VIRTPROP ::= ['private' | 'protected'] TYPE ['&'] IDENTIFIER '{' {('get' | 'set') ['const'] FUNCATTR (STATBLOCK | ';')} '}'
// MIXIN ::= 'mixin' CLASS
// INTFMTHD ::= TYPE ['&'] IDENTIFIER PARAMLIST ['const'] ';'
// STATBLOCK ::= '{' {VAR | STATEMENT} '}'
export function analyzeStatBlock(scope: SymbolScope, statBlock: NodeStatBlock) {
// Append completion information to the scope
pushHintOfCompletionScopeToParent(scope.parentScope, scope, statBlock.nodeRange);
for (const statement of statBlock.statementList) {
if (statement.nodeName === NodeName.Var) {
analyzeVar(scope, statement, false);
} else {
analyzeStatement(scope, statement as NodeStatement);
}
}
}
// PARAMLIST ::= '(' ['void' | (TYPE TYPEMOD [IDENTIFIER] ['=' EXPR] {',' TYPE TYPEMOD [IDENTIFIER] ['=' EXPR]})] ')'
export function analyzeParamList(scope: SymbolScope, paramList: NodeParamList) {
for (const param of paramList) {
if (param.defaultExpr === undefined) continue;
analyzeExpr(scope, param.defaultExpr);
}
}
// TYPEMOD ::= ['&' ['in' | 'out' | 'inout']]
// TYPE ::= ['const'] SCOPE DATATYPE ['<' TYPE {',' TYPE} '>'] { ('[' ']') | ('@' ['const']) }
export function analyzeType(scope: SymbolScope, nodeType: NodeType): ResolvedType | undefined {
const reservedType = nodeType.isArray ? undefined : analyzeReservedType(scope, nodeType);
if (reservedType !== undefined) return reservedType;
const typeIdentifier = nodeType.dataType.identifier;
const searchScope = nodeType.scope !== undefined
? (analyzeScope(scope, nodeType.scope) ?? scope)
: scope;
let givenTypeTemplates = nodeType.typeTemplates;
let givenIdentifier = typeIdentifier.text;
if (nodeType.isArray) {
// If the type is an array, we replace the identifier with array type.
givenIdentifier = getGlobalSettings().builtinArrayType;
const copiedNodeType: Mutable<NodeType> = {...nodeType};
copiedNodeType.isArray = false;
givenTypeTemplates = [copiedNodeType];
}
let symbolAndScope = findSymbolWithParent(searchScope, givenIdentifier);
if (symbolAndScope !== undefined
&& isSymbolConstructorInScope(symbolAndScope)
&& symbolAndScope.scope.parentScope !== undefined
) {
// When traversing the parent hierarchy, the constructor is sometimes found before the class type,
// in which case search further up the hierarchy.
symbolAndScope = getSymbolAndScopeIfExist(
findSymbolShallowly(symbolAndScope.scope.parentScope, givenIdentifier), symbolAndScope.scope.parentScope);
}
if (symbolAndScope === undefined) {
diagnostic.addError(typeIdentifier.location, `'${givenIdentifier}' is not defined.`);
return undefined;
}
const {symbol: foundSymbol, scope: foundScope} = symbolAndScope;
if (foundSymbol instanceof SymbolFunction && foundSymbol.sourceNode.nodeName === NodeName.FuncDef) {
return completeAnalyzingType(scope, typeIdentifier, foundSymbol, foundScope, true);
} else if (foundSymbol instanceof SymbolType === false) {
diagnostic.addError(typeIdentifier.location, `'${givenIdentifier}' is not a type.`);
return undefined;
} else {
const typeTemplates = analyzeTemplateTypes(scope, givenTypeTemplates, foundSymbol.templateTypes);
return completeAnalyzingType(scope, typeIdentifier, foundSymbol, foundScope, undefined, typeTemplates);
}
}
function completeAnalyzingType(
scope: SymbolScope,
identifier: ParserToken,
foundSymbol: SymbolType | SymbolFunction,
foundScope: SymbolScope,
isHandler?: boolean,
typeTemplates?: TemplateTranslation | undefined,
): ResolvedType | undefined {
scope.referencedList.push({
declaredSymbol: foundSymbol,
referencedToken: identifier
});
return ResolvedType.create({
symbolType: foundSymbol,
isHandler: isHandler,
templateTranslate: typeTemplates
});
}
// PRIMTYPE | '?' | 'auto'
function analyzeReservedType(scope: SymbolScope, nodeType: NodeType): ResolvedType | undefined {
const typeIdentifier = nodeType.dataType.identifier;
if (typeIdentifier.kind !== TokenKind.Reserved) return;
if (nodeType.scope !== undefined) {
diagnostic.addError(typeIdentifier.location, `Invalid scope.`);
}
const foundBuiltin = tryGetBuiltInType(typeIdentifier);
if (foundBuiltin !== undefined) return new ResolvedType(foundBuiltin);
return undefined;
}
function analyzeTemplateTypes(scope: SymbolScope, nodeType: NodeType[], templateTypes: ParserToken[] | undefined) {
if (templateTypes === undefined) return undefined;
const translation: TemplateTranslation = new Map();
for (let i = 0; i < nodeType.length; i++) {
if (i >= templateTypes.length) {
diagnostic.addError(getNodeLocation(nodeType[nodeType.length - 1].nodeRange), `Too many template types.`);
break;
}
const template = nodeType[i];
translation.set(templateTypes[i], analyzeType(scope, template));
}
return translation;
}
// INITLIST ::= '{' [ASSIGN | INITLIST] {',' [ASSIGN | INITLIST]} '}'
function analyzeInitList(scope: SymbolScope, initList: NodeInitList) {
for (const init of initList.initList) {
if (init.nodeName === NodeName.Assign) {
analyzeAssign(scope, init);
} else if (init.nodeName === NodeName.InitList) {
analyzeInitList(scope, init);
}
}
// TODO: InitList 型判定
return undefined;
}
// SCOPE ::= ['::'] {IDENTIFIER '::'} [IDENTIFIER ['<' TYPE {',' TYPE} '>'] '::']
function analyzeScope(parentScope: SymbolScope, nodeScope: NodeScope): SymbolScope | undefined {
let scopeIterator = parentScope;
if (nodeScope.isGlobal) {
scopeIterator = findGlobalScope(parentScope);
}
for (let i = 0; i < nodeScope.scopeList.length; i++) {
const nextScope = nodeScope.scopeList[i];
// Search for the scope corresponding to the name.
let found: SymbolScope | undefined = undefined;
for (; ;) {
found = findScopeShallowly(scopeIterator, nextScope.text);
if (found?.ownerNode?.nodeName === NodeName.Func) found = undefined;
if (found !== undefined) break;
if (i == 0 && scopeIterator.parentScope !== undefined) {
// If it is not a global scope, search further up the hierarchy.
scopeIterator = scopeIterator.parentScope;
} else {
diagnostic.addError(nextScope.location, `Undefined scope: ${nextScope.text}`);
return undefined;
}
}
// Update the scope iterator.
scopeIterator = found;
// Append a hint for completion of the namespace to the scope.
const complementRange: LocationInfo = {...nextScope.location};
complementRange.end = getNextTokenIfExist(getNextTokenIfExist(nextScope)).location.start;
parentScope.completionHints.push({
complementKind: ComplementKind.Namespace,
complementLocation: complementRange,
namespaceList: nodeScope.scopeList.slice(0, i + 1)
});
}
return scopeIterator;
}
// DATATYPE ::= (IDENTIFIER | PRIMTYPE | '?' | 'auto')
// PRIMTYPE ::= 'void' | 'int' | 'int8' | 'int16' | 'int32' | 'int64' | 'uint' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'float' | 'double' | 'bool'
// FUNCATTR ::= {'override' | 'final' | 'explicit' | 'property'}
// STATEMENT ::= (IF | FOR | WHILE | RETURN | STATBLOCK | BREAK | CONTINUE | DOWHILE | SWITCH | EXPRSTAT | TRY)
function analyzeStatement(scope: SymbolScope, statement: NodeStatement) {
switch (statement.nodeName) {
case NodeName.If:
analyzeIf(scope, statement);
break;
case NodeName.For:
analyzeFor(scope, statement);
break;
case NodeName.While:
analyzeWhile(scope, statement);
break;
case NodeName.Return:
analyzeReturn(scope, statement);
break;
case NodeName.StatBlock: {
const childScope = createSymbolScopeAndInsert(undefined, scope, createAnonymousIdentifier());
analyzeStatBlock(childScope, statement);
break;
}
case NodeName.Break:
break;
case NodeName.Continue:
break;
case NodeName.DoWhile:
analyzeDoWhile(scope, statement);
break;
case NodeName.Switch:
analyzeSwitch(scope, statement);
break;
case NodeName.ExprStat:
analyzeExprStat(scope, statement);
break;
case NodeName.Try:
analyzeTry(scope, statement);
break;
default:
break;
}
}
// SWITCH ::= 'switch' '(' ASSIGN ')' '{' {CASE} '}'
function analyzeSwitch(scope: SymbolScope, ast: NodeSwitch) {
analyzeAssign(scope, ast.assign);
for (const c of ast.caseList) {
analyzeCase(scope, c);
}
}
// BREAK ::= 'break' ';'
// FOR ::= 'for' '(' (VAR | EXPRSTAT) EXPRSTAT [ASSIGN {',' ASSIGN}] ')' STATEMENT
function analyzeFor(scope: SymbolScope, nodeFor: NodeFor) {
if (nodeFor.initial.nodeName === NodeName.Var) analyzeVar(scope, nodeFor.initial, false);
else analyzeExprStat(scope, nodeFor.initial);
if (nodeFor.condition !== undefined) analyzeExprStat(scope, nodeFor.condition);
for (const inc of nodeFor.incrementList) {
analyzeAssign(scope, inc);
}
if (nodeFor.statement !== undefined) analyzeStatement(scope, nodeFor.statement);
}
// WHILE ::= 'while' '(' ASSIGN ')' STATEMENT
function analyzeWhile(scope: SymbolScope, nodeWhile: NodeWhile) {
const assignType = analyzeAssign(scope, nodeWhile.assign);
checkTypeMatch(assignType, new ResolvedType(builtinBoolType), nodeWhile.assign.nodeRange);
if (nodeWhile.statement !== undefined) analyzeStatement(scope, nodeWhile.statement);
}
// DOWHILE ::= 'do' STATEMENT 'while' '(' ASSIGN ')' ';'
function analyzeDoWhile(scope: SymbolScope, doWhile: NodeDoWhile) {
analyzeStatement(scope, doWhile.statement);
if (doWhile.assign === undefined) return;
const assignType = analyzeAssign(scope, doWhile.assign);
checkTypeMatch(assignType, new ResolvedType(builtinBoolType), doWhile.assign.nodeRange);
}
// IF ::= 'if' '(' ASSIGN ')' STATEMENT ['else' STATEMENT]
function analyzeIf(scope: SymbolScope, nodeIf: NodeIf) {
const conditionType = analyzeAssign(scope, nodeIf.condition);
checkTypeMatch(conditionType, new ResolvedType(builtinBoolType), nodeIf.condition.nodeRange);
if (nodeIf.thenStat !== undefined) analyzeStatement(scope, nodeIf.thenStat);
if (nodeIf.elseStat !== undefined) analyzeStatement(scope, nodeIf.elseStat);
}
// CONTINUE ::= 'continue' ';'
// EXPRSTAT ::= [ASSIGN] ';'
function analyzeExprStat(scope: SymbolScope, exprStat: NodeExprStat) {
if (exprStat.assign === undefined) return;
const assign = analyzeAssign(scope, exprStat.assign);
if (assign?.isHandler !== true && assign?.symbolType instanceof SymbolFunction) {
diagnostic.addError(getNodeLocation(exprStat.assign.nodeRange), `Function call without handler.`);
}
}
// TRY ::= 'try' STATBLOCK 'catch' STATBLOCK
function analyzeTry(scope: SymbolScope, nodeTry: NodeTry) {
analyzeStatBlock(scope, nodeTry.tryBlock);
if (nodeTry.catchBlock !== undefined) analyzeStatBlock(scope, nodeTry.catchBlock);
}
// RETURN ::= 'return' [ASSIGN] ';'
function analyzeReturn(scope: SymbolScope, nodeReturn: NodeReturn) {
const returnType = nodeReturn.assign !== undefined ? analyzeAssign(scope, nodeReturn.assign) : undefined;
const functionScope = findScopeWithParentByNodes(scope, [NodeName.Func, NodeName.VirtualProp, NodeName.Lambda]);
if (functionScope === undefined || functionScope.ownerNode === undefined) return;
// TODO: Support for lambda
if (functionScope.ownerNode.nodeName === NodeName.Func) {
let functionReturn = functionScope.parentScope?.symbolMap.get(functionScope.key);
if (functionReturn === undefined || functionReturn instanceof SymbolFunction === false) return;
// Select suitable overload if there are multiple overloads
while (functionReturn.nextOverload !== undefined) {
if (functionReturn.sourceNode === functionScope.ownerNode) break;
functionReturn = functionReturn.nextOverload;
}
const expectedReturn = functionReturn.returnType?.symbolType;
if (expectedReturn instanceof SymbolType && expectedReturn?.identifierText === 'void') {
if (nodeReturn.assign === undefined) return;
diagnostic.addError(getNodeLocation(nodeReturn.nodeRange), `Function does not return a value.`);
} else {
checkTypeMatch(returnType, functionReturn.returnType, nodeReturn.nodeRange);
}
} else if (functionScope.ownerNode.nodeName === NodeName.VirtualProp) {
const key = functionScope.key;
const isGetter = key.startsWith('get_');
if (isGetter === false) {
if (nodeReturn.assign === undefined) return;
diagnostic.addError(getNodeLocation(nodeReturn.nodeRange), `Property setter does not return a value.`);
return;
}
const varName = key.substring(4, key.length);
const functionReturn = functionScope.parentScope?.symbolMap.get(varName);
if (functionReturn === undefined || functionReturn instanceof SymbolVariable === false) return;
checkTypeMatch(returnType, functionReturn.type, nodeReturn.nodeRange);
}
}
// CASE ::= (('case' EXPR) | 'default') ':' {STATEMENT}
function analyzeCase(scope: SymbolScope, nodeCase: NodeCase) {
if (nodeCase.expr !== undefined) analyzeExpr(scope, nodeCase.expr);
for (const statement of nodeCase.statementList) {
analyzeStatement(scope, statement);
}
}
// EXPR ::= EXPRTERM {EXPROP EXPRTERM}
function analyzeExpr(scope: SymbolScope, expr: NodeExpr): ResolvedType | undefined {
// Evaluate by Shunting Yard Algorithm
// https://qiita.com/phenan/items/df157fef2fea590e3fa9
type Term = [ResolvedType | undefined, ParsedRange];
type Op = ParserToken;
function isOp(termOrOp: (Term | Op)): termOrOp is Op {
return 'text' in termOrOp;
}
function precedence(termOrOp: (Term | Op)) {
return isOp(termOrOp) ? getOperatorPrecedence(termOrOp) : 1;
}
const inputList: (Term | Op)[] = [];
for (let cursor: NodeExpr | undefined = expr; ;) {
inputList.push([analyzeExprTerm(scope, cursor.head), cursor.head.nodeRange]);
if (cursor.tail === undefined) break;
inputList.push(cursor.tail.operator);
cursor = cursor.tail.expression;
}
const stackList: (Term | Op)[] = [];
const outputList: (Term | Op)[] = [];
while (inputList.length > 0 || stackList.length > 0) {
const inputToStack: boolean = stackList.length === 0
|| (inputList.length > 0 && precedence(inputList[0]) > precedence(stackList[stackList.length - 1]));
if (inputToStack) {
stackList.push(inputList.shift()!);
} else {
outputList.push(stackList.pop()!);
}
}
const outputTerm: Term[] = [];
while (outputList.length > 0) {
const item = outputList.shift()!;
if (isOp(item)) {
const rhs = outputTerm.pop();
const lhs = outputTerm.pop();
if (lhs === undefined || rhs === undefined) return undefined;
outputTerm.push([analyzeExprOp(
scope, item, lhs[0], rhs[0], lhs[1], rhs[1]), {start: lhs[1].start, end: rhs[1].end}]);
} else {
outputTerm.push(item);
}
}
return outputTerm.length > 0 ? outputTerm[0][0] : undefined;
}
function getOperatorPrecedence(operator: ParserToken): number {
const op = operator.text;
switch (op) {
case '**':
return 0;
case '*':
case '/':
case '%':
return -1;
case '+':
case '-':
return -2;
case '<<':
case '>>':
case '>>>':
return -3;
case '&':
return -4;
case '^':
return -5;
case '|':
return -6;
case '<':
case '>':
case '<=':
case '>=':
return -7;
case '==':
case '!=':
case 'xor':
case '^^':
case 'is':
case '!is':
return -8;
case 'and':
case '&&':
return -9;
case 'or':
case '||':
return -10;
default:
assert(false);
}
}
// EXPRTERM ::= ([TYPE '='] INITLIST) | ({EXPRPREOP} EXPRVALUE {EXPRPOSTOP})
function analyzeExprTerm(scope: SymbolScope, ast: NodeExprTerm): ResolvedType | undefined {
if (ast.exprTerm === 1) {
// TODO
} else if (ast.exprTerm === 2) {
return analyzeExprTerm2(scope, ast);
}
return undefined;
}
// {EXPRPREOP} EXPRVALUE {EXPRPOSTOP}
function analyzeExprTerm2(scope: SymbolScope, exprTerm: NodeExprTerm2) {
let exprValue = analyzeExprValue(scope, exprTerm.value);
for (const postOp of exprTerm.postOps) {
if (exprValue === undefined) break;
exprValue = analyzeExprPostOp(scope, postOp, exprValue, exprTerm.nodeRange);
}
return exprValue;
}
// EXPRVALUE ::= 'void' | CONSTRUCTCALL | FUNCCALL | VARACCESS | CAST | LITERAL | '(' ASSIGN ')' | LAMBDA
function analyzeExprValue(scope: SymbolScope, exprValue: NodeExprValue): ResolvedType | undefined {
switch (exprValue.nodeName) {
case NodeName.ConstructCall:
break;
case NodeName.FuncCall:
return analyzeFuncCall(scope, exprValue);
case NodeName.VarAccess:
return analyzeVarAccess(scope, exprValue);
case NodeName.Cast:
return analyzeCast(scope, exprValue);
case NodeName.Literal:
return analyzeLiteral(scope, exprValue);
case NodeName.Assign:
return analyzeAssign(scope, exprValue);
case NodeName.Lambda:
return analyzeLambda(scope, exprValue);
default:
break;
}
return undefined;
}
// CONSTRUCTCALL ::= TYPE ARGLIST
export function analyzeConstructorCaller(
scope: SymbolScope,
callerIdentifier: ParserToken,
callerArgList: NodeArgList,
constructorType: ResolvedType
): ResolvedType | undefined {
const constructor = findConstructorForResolvedType(constructorType);
if (constructor === undefined || constructor instanceof SymbolFunction === false) {
return analyzeBuiltinConstructorCaller(scope, callerIdentifier, callerArgList, constructorType);
}
analyzeFunctionCaller(scope, callerIdentifier, callerArgList, constructor, constructorType.templateTranslate);
return constructorType;
}
export function findConstructorForResolvedType(resolvedType: ResolvedType | undefined): SymbolObject | undefined {
if (resolvedType?.sourceScope === undefined) return undefined;
const constructorIdentifier = resolvedType.symbolType.declaredPlace.text;
const classScope = findScopeShallowly(resolvedType.sourceScope, constructorIdentifier);
return classScope !== undefined ? findSymbolShallowly(classScope, constructorIdentifier) : undefined;
}
function analyzeBuiltinConstructorCaller(
scope: SymbolScope,
callerIdentifier: ParserToken,
callerArgList: NodeArgList,
constructorType: ResolvedType
) {
const constructorIdentifier = constructorType.symbolType.declaredPlace.text;
if (constructorType.sourceScope === undefined) return undefined;
if (constructorType.symbolType instanceof SymbolType
&& getSourceNodeName(constructorType.symbolType.sourceNode) === NodeName.Enum) {
// Constructor for enum
const argList = callerArgList.argList;
if (argList.length != 1 || canTypeConvert(
analyzeAssign(scope, argList[0].assign),
resolvedBuiltinInt) === false) {
diagnostic.addError(
callerIdentifier.location,
`Enum constructor '${constructorIdentifier}' requires an integer.`);
}
scope.referencedList.push({declaredSymbol: constructorType.symbolType, referencedToken: callerIdentifier});
return constructorType;
}
if (callerArgList.argList.length === 0) {
// Default constructor
scope.referencedList.push({declaredSymbol: constructorType.symbolType, referencedToken: callerIdentifier});
return constructorType;
}
diagnostic.addError(callerIdentifier.location, `Constructor '${constructorIdentifier}' is missing.`);
return undefined;
}
// EXPRPREOP ::= '-' | '+' | '!' | '++' | '--' | '~' | '@'
// EXPRPOSTOP ::= ('.' (FUNCCALL | IDENTIFIER)) | ('[' [IDENTIFIER ':'] ASSIGN {',' [IDENTIFIER ':' ASSIGN} ']') | ARGLIST | '++' | '--'
function analyzeExprPostOp(scope: SymbolScope, exprPostOp: NodeExprPostOp, exprValue: ResolvedType, exprRange: ParsedRange) {
if (exprPostOp.postOp === 1) {
return analyzeExprPostOp1(scope, exprPostOp, exprValue);
} else if (exprPostOp.postOp === 2) {
return analyzeExprPostOp2(scope, exprPostOp, exprValue, exprRange);
}
}
// ('.' (FUNCCALL | IDENTIFIER))
function analyzeExprPostOp1(scope: SymbolScope, exprPostOp: NodeExprPostOp1, exprValue: ResolvedType) {
if (exprValue.symbolType instanceof SymbolType === false) {
diagnostic.addError(getNodeLocation(exprPostOp.nodeRange), `Invalid access to type.`);
return undefined;
}
// Append a hint for complement of class members.
const complementRange = getLocationBetween(
exprPostOp.nodeRange.start,
getNextTokenIfExist(exprPostOp.nodeRange.start));
scope.completionHints.push({
complementKind: ComplementKind.Type,
complementLocation: complementRange,
targetType: exprValue.symbolType
});
const member = exprPostOp.member;
const isMemberMethod = isMemberMethodInPostOp(member);
const identifier = isMemberMethod ? member.identifier : member;
if (identifier === undefined) return undefined;
if (isSourceNodeClassOrInterface(exprValue.symbolType.sourceNode) === false) {
diagnostic.addError(identifier.location, `'${identifier.text}' is not a member.`);
return undefined;
}
const classScope = exprValue.symbolType.membersScope;
if (classScope === undefined) return undefined;
if (isMemberMethod) {
// Analyze method call.
const method = findSymbolShallowly(classScope, identifier.text);
if (method === undefined) {
diagnostic.addError(identifier.location, `'${identifier.text}' is not defined.`);
return undefined;
}
if (method instanceof SymbolFunction === false) {
diagnostic.addError(identifier.location, `'${identifier.text}' is not a method.`);
return undefined;
}
return analyzeFunctionCaller(scope, identifier, member.argList, method, exprValue.templateTranslate);
} else {
// Analyze field access.
return analyzeVariableAccess(scope, classScope, identifier);
}
}
// ('[' [IDENTIFIER ':'] ASSIGN {',' [IDENTIFIER ':' ASSIGN} ']')
function analyzeExprPostOp2(scope: SymbolScope, exprPostOp: NodeExprPostOp2, exprValue: ResolvedType, exprRange: ParsedRange) {
const args = exprPostOp.indexerList.map(indexer => analyzeAssign(scope, indexer.assign));
return analyzeOperatorAlias(
scope,
exprPostOp.nodeRange.end,
exprValue,
args,
exprRange,
exprPostOp.nodeRange,
'opIndex');
}
// CAST ::= 'cast' '<' TYPE '>' '(' ASSIGN ')'
function analyzeCast(scope: SymbolScope, cast: NodeCast): ResolvedType | undefined {
const castedType = analyzeType(scope, cast.type);
analyzeAssign(scope, cast.assign);
return castedType;
}
// LAMBDA ::= 'function' '(' [[TYPE TYPEMOD] [IDENTIFIER] {',' [TYPE TYPEMOD] [IDENTIFIER]}] ')' STATBLOCK
function analyzeLambda(scope: SymbolScope, lambda: NodeLambda): ResolvedType | undefined {
const childScope = createSymbolScopeAndInsert(lambda, scope, createAnonymousIdentifier());
// Append arguments to the scope
for (const param of lambda.paramList) {
if (param.identifier === undefined) continue;
const argument: SymbolVariable = SymbolVariable.create({
declaredPlace: param.identifier,
declaredScope: scope,
type: param.type !== undefined ? analyzeType(scope, param.type) : undefined,
isInstanceMember: false,
accessRestriction: undefined,
});
insertSymbolObject(childScope.symbolMap, argument);
}
if (lambda.statBlock !== undefined) analyzeStatBlock(childScope, lambda.statBlock);
// TODO: 左辺からラムダ式の型を推定したい
return undefined;
}
// LITERAL ::= NUMBER | STRING | BITS | 'true' | 'false' | 'null'
function analyzeLiteral(scope: SymbolScope, literal: NodeLiteral): ResolvedType | undefined {
const literalValue = literal.value;
if (literalValue.kind === TokenKind.Number) {
switch (literalValue.numeric) {
case NumberLiterals.Integer:
return resolvedBuiltinInt;
case NumberLiterals.Float:
return resolvedBuiltinFloat;
case NumberLiterals.Double:
return resolvedBuiltinDouble;
}
}
if (literalValue.kind === TokenKind.String) {
return resolvedBuiltinString;
}
if (literalValue.text === 'true' || literalValue.text === 'false') {
return resolvedBuiltinBool;
}
// FIXME: Handling null?
return undefined;
}
// FUNCCALL ::= SCOPE IDENTIFIER ARGLIST
function analyzeFuncCall(scope: SymbolScope, funcCall: NodeFuncCall): ResolvedType | undefined {
let searchScope = scope;
if (funcCall.scope !== undefined) {
const namespaceScope = analyzeScope(scope, funcCall.scope);
if (namespaceScope === undefined) return undefined;
searchScope = namespaceScope;
}
const calleeFunc = findSymbolWithParent(searchScope, funcCall.identifier.text);
if (calleeFunc?.symbol === undefined) {
diagnostic.addError(funcCall.identifier.location, `'${funcCall.identifier.text}' is not defined.`);
return undefined;
}
const [calleeSymbol, calleeScope] = [calleeFunc.symbol, calleeFunc.scope];
if (calleeSymbol instanceof SymbolType) {
const constructorType: ResolvedType = new ResolvedType(calleeSymbol);
return analyzeConstructorCaller(scope, funcCall.identifier, funcCall.argList, constructorType);
}
if (calleeSymbol instanceof SymbolVariable && calleeSymbol.type?.symbolType instanceof SymbolFunction) {
return analyzeFunctionCaller(
scope,
funcCall.identifier,
funcCall.argList,
calleeSymbol.type.symbolType,
undefined);
}
if (calleeSymbol instanceof SymbolVariable) {
return analyzeOpCallCaller(scope, funcCall, calleeSymbol);
}
if (calleeSymbol instanceof SymbolFunction === false) {
diagnostic.addError(funcCall.identifier.location, `'${funcCall.identifier.text}' is not a function.`);
return undefined;
}
return analyzeFunctionCaller(scope, funcCall.identifier, funcCall.argList, calleeSymbol, undefined);
}
function analyzeOpCallCaller(scope: SymbolScope, funcCall: NodeFuncCall, calleeVariable: SymbolVariable) {
const varType = calleeVariable.type;
if (varType === undefined || varType.sourceScope === undefined) {
diagnostic.addError(funcCall.identifier.location, `'${funcCall.identifier.text}' is not callable.`);
return;
}
const classScope = findScopeShallowly(varType.sourceScope, varType.symbolType.declaredPlace.text);
if (classScope === undefined) return undefined;
const opCall = findSymbolShallowly(classScope, 'opCall');
if (opCall === undefined || opCall instanceof SymbolFunction === false) {
diagnostic.addError(
funcCall.identifier.location,
`'opCall' is not defined in type '${varType.symbolType.declaredPlace.text}'.`);
return;
}
return analyzeFunctionCaller(scope, funcCall.identifier, funcCall.argList, opCall, varType.templateTranslate);
}
function analyzeFunctionCaller(
scope: SymbolScope,
callerIdentifier: ParserToken,
callerArgList: NodeArgList,
calleeFunc: SymbolFunction,
templateTranslate: TemplateTranslation | undefined
) {
const callerArgTypes = analyzeArgList(scope, callerArgList);
if (calleeFunc.sourceNode.nodeName === NodeName.FuncDef) {
// If the callee is a delegate, return it as a function handler.
const handlerType = new ResolvedType(calleeFunc);
if (callerArgTypes.length === 1 && canTypeConvert(callerArgTypes[0], handlerType)) {
return callerArgTypes[0];
}
}
// Append a hint for completion of function arguments to the scope.
const complementRange = getLocationBetween(
callerArgList.nodeRange.start,
getNextTokenIfExist(callerArgList.nodeRange.end));
scope.completionHints.push({
complementKind: ComplementKind.Arguments,
complementLocation: complementRange,
expectedCallee: calleeFunc,
passingRanges: callerArgList.argList.map(arg => arg.assign.nodeRange),
templateTranslate: templateTranslate
});
return checkFunctionMatch({
scope: scope,
callerIdentifier: callerIdentifier,
callerRange: callerArgList.nodeRange,
callerArgRanges: callerArgList.argList.map(arg => arg.assign.nodeRange),
callerArgTypes: callerArgTypes,
calleeFunc: calleeFunc,
templateTranslators: [templateTranslate]
});
}
// VARACCESS ::= SCOPE IDENTIFIER
function analyzeVarAccess(scope: SymbolScope, varAccess: NodeVarAccess): ResolvedType | undefined {
let accessedScope = scope;
if (varAccess.scope !== undefined) {
const namespaceScope = analyzeScope(scope, varAccess.scope);
if (namespaceScope === undefined) return undefined;
accessedScope = namespaceScope;
}