-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
TypeChecker.cpp
2631 lines (2212 loc) · 106 KB
/
TypeChecker.cpp
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
// Copyright (c) 2021-2024 ChilliBits. All rights reserved.
#include "TypeChecker.h"
#include <SourceFile.h>
#include <ast/ASTBuilder.h>
#include <ast/Attributes.h>
#include <symboltablebuilder/ScopeHandle.h>
#include <symboltablebuilder/SymbolTableBuilder.h>
#include <typechecker/TypeMatcher.h>
namespace spice::compiler {
TypeChecker::TypeChecker(GlobalResourceManager &resourceManager, SourceFile *sourceFile, TypeCheckerMode typeCheckerMode)
: CompilerPass(resourceManager, sourceFile), typeCheckerMode(typeCheckerMode), warnings(sourceFile->compilerOutput.warnings) {
}
std::any TypeChecker::visitEntry(EntryNode *node) {
// Initialize
currentScope = rootScope;
reVisitRequested = false;
// Initialize AST nodes with size of 1
const bool isPrepare = typeCheckerMode == TC_MODE_PRE;
if (isPrepare)
node->resizeToNumberOfManifestations(1);
// Visit children
visitChildren(node);
// Check which implicit structures we need for each struct, defined in this source file
if (isPrepare) {
for (const auto &[structName, manifestations] : rootScope->getStructs()) {
for (const auto &[manifestationName, manifestation] : manifestations) {
createDefaultCtorIfRequired(manifestation, manifestation.scope);
createDefaultCopyCtorIfRequired(manifestation, manifestation.scope);
createDefaultDtorIfRequired(manifestation, manifestation.scope);
}
}
}
return nullptr;
}
std::any TypeChecker::visitMainFctDef(MainFctDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitMainFctDefPrepare(node);
else
return visitMainFctDefCheck(node);
}
std::any TypeChecker::visitFctDef(FctDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitFctDefPrepare(node);
else
return visitFctDefCheck(node);
}
std::any TypeChecker::visitProcDef(ProcDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitProcDefPrepare(node);
else
return visitProcDefCheck(node);
}
std::any TypeChecker::visitStructDef(StructDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitStructDefPrepare(node);
else
return visitStructDefCheck(node);
}
std::any TypeChecker::visitInterfaceDef(InterfaceDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitInterfaceDefPrepare(node);
return nullptr;
}
std::any TypeChecker::visitEnumDef(EnumDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitEnumDefPrepare(node);
return nullptr;
}
std::any TypeChecker::visitGenericTypeDef(GenericTypeDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitGenericTypeDefPrepare(node);
return nullptr;
}
std::any TypeChecker::visitAliasDef(AliasDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitAliasDefPrepare(node);
return nullptr;
}
std::any TypeChecker::visitGlobalVarDef(GlobalVarDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitGlobalVarDefPrepare(node);
return nullptr;
}
std::any TypeChecker::visitExtDecl(ExtDeclNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitExtDeclPrepare(node);
return nullptr;
}
std::any TypeChecker::visitImportDef(ImportDefNode *node) {
if (typeCheckerMode == TC_MODE_PRE)
return visitImportDefPrepare(node);
return nullptr;
}
std::any TypeChecker::visitUnsafeBlock(UnsafeBlockNode *node) {
// Change to unsafe block body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::UNSAFE_BODY);
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitForLoop(ForLoopNode *node) {
// Change to for body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::FOR_BODY);
// Visit loop variable declaration
visit(node->initDecl());
// Visit condition
SymbolType conditionType = std::any_cast<ExprResult>(visit(node->condAssign())).type;
HANDLE_UNRESOLVED_TYPE_PTR(conditionType)
// Check if condition evaluates to bool
if (!conditionType.is(TY_BOOL))
SOFT_ERROR_ER(node->condAssign(), CONDITION_MUST_BE_BOOL, "For loop condition must be of type bool")
// Visit incrementer
visit(node->incAssign());
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitForeachLoop(ForeachLoopNode *node) {
// Change to foreach body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::FOREACH_BODY);
// Visit iterator assignment
AssignExprNode *iteratorNode = node->iteratorAssign();
SymbolType iteratorOrIterableType = std::any_cast<ExprResult>(visit(iteratorNode)).type;
HANDLE_UNRESOLVED_TYPE_PTR(iteratorOrIterableType)
iteratorOrIterableType = iteratorOrIterableType.removeReferenceWrapper();
// Retrieve iterator type
SymbolType iteratorType = iteratorOrIterableType;
if (iteratorOrIterableType.isIterable(node)) {
const SymbolType &iterableType = iteratorOrIterableType;
if (iteratorOrIterableType.isArray()) { // Array
const NameRegistryEntry *nameRegistryEntry = sourceFile->getNameRegistryEntry(ARRAY_ITERATOR_NAME);
if (!nameRegistryEntry) {
softError(node, UNKNOWN_DATATYPE, "Forgot to import of \"std/iterator/array-iterator\"?");
return nullptr;
}
nameRegistryEntry->targetEntry->used = nameRegistryEntry->importEntry->used = true;
Scope *matchScope = nameRegistryEntry->targetScope->parent;
assert(matchScope->type == ScopeType::GLOBAL);
SymbolType unsignedLongType(TY_LONG);
unsignedLongType.specifiers.isSigned = false;
unsignedLongType.specifiers.isUnsigned = true;
const ArgList argTypes = {Arg(iterableType, false), Arg(unsignedLongType, false)};
const SymbolType thisType(TY_DYN);
node->getIteratorFct = FunctionManager::matchFunction(matchScope, "iterate", thisType, argTypes, {}, true, iteratorNode);
} else { // Struct, implementing Iterator interface
Scope *matchScope = iterableType.getBodyScope();
node->getIteratorFct = FunctionManager::matchFunction(matchScope, "getIterator", iterableType, {}, {}, true, iteratorNode);
}
assert(node->getIteratorFct != nullptr);
iteratorType = node->getIteratorFct->returnType;
// Create anonymous entry for the iterator
currentScope->symbolTable.insertAnonymous(iteratorType, iteratorNode);
}
// Check iterator type
if (!iteratorType.isIterator(node)) {
const std::string errMsg =
"Can only iterate over arrays or data structures, inheriting from IIterator or IIterable. You provided " +
iteratorType.getName();
softError(node->iteratorAssign(), OPERATOR_WRONG_DATA_TYPE, errMsg);
return nullptr;
}
const std::vector<SymbolType> &iteratorTemplateTypes = iteratorType.getTemplateTypes();
if (iteratorTemplateTypes.empty())
SOFT_ERROR_ER(node->iteratorAssign(), INVALID_ITERATOR,
"Iterator has no generic arguments so that the item type could not be inferred")
const bool hasIdx = node->idxVarDecl();
if (hasIdx) {
// Visit index declaration or assignment
auto indexType = std::any_cast<SymbolType>(visit(node->idxVarDecl()));
HANDLE_UNRESOLVED_TYPE_PTR(indexType)
// Check if index type is int
if (!indexType.is(TY_LONG))
SOFT_ERROR_ER(node->idxVarDecl(), FOREACH_IDX_NOT_LONG,
"Index in foreach loop must be of type long. You provided " + indexType.getName())
}
// Retrieve .get(), .getIdx(), .isValid() and .next() functions
Scope *matchScope = iteratorType.getBodyScope();
SymbolType iteratorItemType;
if (hasIdx) {
node->getIdxFct = FunctionManager::matchFunction(matchScope, "getIdx", iteratorType, {}, {}, false, node);
assert(node->getIdxFct != nullptr);
iteratorItemType = node->getIdxFct->returnType.getTemplateTypes().back();
} else {
node->getFct = FunctionManager::matchFunction(matchScope, "get", iteratorType, {}, {}, false, node);
assert(node->getFct != nullptr);
iteratorItemType = node->getFct->returnType;
}
node->isValidFct = FunctionManager::matchFunction(matchScope, "isValid", iteratorType, {}, {}, false, node);
assert(node->isValidFct != nullptr);
node->nextFct = FunctionManager::matchFunction(matchScope, "next", iteratorType, {}, {}, false, node);
assert(node->nextFct != nullptr);
// Retrieve item variable entry
SymbolTableEntry *itemVarSymbol = currentScope->lookupStrict(node->itemVarDecl()->varName);
assert(itemVarSymbol != nullptr);
// Check type of the item
auto itemType = std::any_cast<SymbolType>(visit(node->itemVarDecl()));
HANDLE_UNRESOLVED_TYPE_PTR(itemType)
if (itemType.is(TY_DYN)) { // Perform type inference
// Update evaluated symbol type of the declaration data type
node->itemVarDecl()->dataType()->setEvaluatedSymbolType(iteratorItemType, manIdx);
// Update item type
itemType = iteratorItemType;
} else {
// Check item type
const ExprResult itemResult = {itemType, itemVarSymbol};
const ExprResult iteratorItemResult = {iteratorItemType, nullptr /* always a temporary */};
OpRuleManager::getAssignResultType(node->itemVarDecl(), itemResult, iteratorItemResult, true, ERROR_FOREACH_ITEM);
}
// Update type of item
itemVarSymbol->updateType(itemType, true);
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitWhileLoop(WhileLoopNode *node) {
// Change to while body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::WHILE_BODY);
// Visit condition
SymbolType conditionType = std::any_cast<ExprResult>(visit(node->condition())).type;
HANDLE_UNRESOLVED_TYPE_PTR(conditionType)
// Check if condition evaluates to bool
if (!conditionType.is(TY_BOOL))
SOFT_ERROR_ER(node->condition(), CONDITION_MUST_BE_BOOL, "While loop condition must be of type bool")
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitDoWhileLoop(DoWhileLoopNode *node) {
// Change to while body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::WHILE_BODY);
// Visit body
visit(node->body());
// Visit condition
SymbolType conditionType = std::any_cast<ExprResult>(visit(node->condition())).type;
HANDLE_UNRESOLVED_TYPE_PTR(conditionType)
// Check if condition evaluates to bool
if (!conditionType.is(TY_BOOL))
SOFT_ERROR_ER(node->condition(), CONDITION_MUST_BE_BOOL, "Do-While loop condition must be of type bool")
return nullptr;
}
std::any TypeChecker::visitIfStmt(IfStmtNode *node) {
// Change to then body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::IF_ELSE_BODY);
// Visit condition
AssignExprNode *condition = node->condition();
SymbolType conditionType = std::any_cast<ExprResult>(visit(condition)).type;
HANDLE_UNRESOLVED_TYPE_PTR(conditionType)
// Check if condition evaluates to bool
if (!conditionType.is(TY_BOOL))
SOFT_ERROR_ER(node->condition(), CONDITION_MUST_BE_BOOL, "If condition must be of type bool")
// Warning for bool assignment
if (condition->op == AssignExprNode::OP_ASSIGN)
sourceFile->compilerOutput.warnings.emplace_back(condition->codeLoc, BOOL_ASSIGN_AS_CONDITION,
"If you want to compare the values, use '=='");
// Visit body
visit(node->thenBody());
// Leave then body scope
scopeHandle.leaveScopeEarly();
// Visit else statement if existing
if (node->elseStmt())
visit(node->elseStmt());
return nullptr;
}
std::any TypeChecker::visitElseStmt(ElseStmtNode *node) {
// Visit if statement in the case of an else if branch
if (node->isElseIf) {
visit(node->ifStmt());
return nullptr;
}
// Change to else body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::IF_ELSE_BODY);
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitSwitchStmt(SwitchStmtNode *node) {
// Check expression type
AssignExprNode *expr = node->assignExpr();
SymbolType exprType = std::any_cast<ExprResult>(visit(expr)).type;
HANDLE_UNRESOLVED_TYPE_PTR(exprType)
if (!exprType.isOneOf({TY_INT, TY_SHORT, TY_LONG, TY_BYTE, TY_CHAR, TY_BOOL}))
SOFT_ERROR_ER(node->assignExpr(), SWITCH_EXPR_MUST_BE_PRIMITIVE,
"Switch expression must be of int, short, long, byte, char or bool type")
// Visit children
visitChildren(node);
// Check if case constant types match switch expression type
for (CaseBranchNode *caseBranchNode : node->caseBranches())
for (CaseConstantNode *constantNode : caseBranchNode->caseConstants()) {
const SymbolType constantType = std::any_cast<ExprResult>(visit(constantNode)).type;
if (!constantType.matches(exprType, false, true, true))
SOFT_ERROR_ER(constantNode, SWITCH_CASE_TYPE_MISMATCH, "Case value type does not match the switch expression type")
}
return nullptr;
}
std::any TypeChecker::visitCaseBranch(CaseBranchNode *node) {
// Change to case body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::CASE_BODY);
// Visit constant list
for (CaseConstantNode *constant : node->caseConstants())
visit(constant);
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitDefaultBranch(DefaultBranchNode *node) {
// Change to default body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::DEFAULT_BODY);
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitAnonymousBlockStmt(AnonymousBlockStmtNode *node) {
// Change to anonymous scope body scope
ScopeHandle scopeHandle(this, node->getScopeId(), ScopeType::ANONYMOUS_BLOCK_BODY);
// Visit body
visit(node->body());
return nullptr;
}
std::any TypeChecker::visitStmtLst(StmtLstNode *node) {
// Visit nodes in this scope
for (ASTNode *stmt : node->children) {
if (!stmt)
continue;
// Print warning if statement is unreachable
if (stmt->unreachable) {
warnings.emplace_back(stmt->codeLoc, UNREACHABLE_CODE, "This statement is unreachable");
continue;
}
// Visit the statement
visit(stmt);
}
// Do cleanup of this scope, e.g. dtor calls for struct instances
doScopeCleanup(node);
return nullptr;
}
std::any TypeChecker::visitParamLst(ParamLstNode *node) {
NamedParamList namedParams;
bool metOptional = false;
for (DeclStmtNode *param : node->params()) {
// Visit param
const auto paramType = std::any_cast<SymbolType>(visit(param));
if (paramType.is(TY_UNRESOLVED))
continue;
// Check if the type could be inferred. Dyn without a default value is forbidden
if (paramType.is(TY_DYN)) {
softError(node, FCT_PARAM_IS_TYPE_DYN, "Type of parameter '" + param->varName + "' is invalid");
continue;
}
// Ensure that no optional param comes after a mandatory param
if (param->hasAssignment) {
metOptional = true;
} else if (metOptional) {
softError(param, INVALID_PARAM_ORDER, "Mandatory parameters must go before any optional parameters");
continue;
}
// Add parameter to named param list
namedParams.push_back({param->varName, paramType, metOptional});
}
return namedParams;
}
std::any TypeChecker::visitField(FieldNode *node) {
auto fieldType = std::any_cast<SymbolType>(visit(node->dataType()));
HANDLE_UNRESOLVED_TYPE_ST(fieldType)
if (TernaryExprNode *defaultValueNode = node->defaultValue()) {
const SymbolType defaultValueType = std::any_cast<ExprResult>(visit(defaultValueNode)).type;
HANDLE_UNRESOLVED_TYPE_ST(defaultValueType)
if (!fieldType.matches(defaultValueType, false, true, true))
SOFT_ERROR_ST(node, FIELD_TYPE_NOT_MATCHING, "Type of the default values does not match the field type")
}
return fieldType;
}
std::any TypeChecker::visitSignature(SignatureNode *node) {
const bool isFunction = node->signatureType == SignatureNode::TYPE_FUNCTION;
// Retrieve function template types
std::vector<GenericType> usedGenericTypes;
if (node->hasTemplateTypes) {
for (DataTypeNode *dataType : node->templateTypeLst()->dataTypes()) {
// Visit template type
auto templateType = std::any_cast<SymbolType>(visit(dataType));
if (templateType.is(TY_UNRESOLVED))
return static_cast<std::vector<Function *> *>(nullptr);
// Check if it is a generic type
if (!templateType.is(TY_GENERIC)) {
softError(dataType, EXPECTED_GENERIC_TYPE, "A template list can only contain generic types");
return static_cast<std::vector<Function *> *>(nullptr);
}
// Convert generic symbol type to generic type
GenericType *genericType = rootScope->lookupGenericType(templateType.getSubType());
assert(genericType != nullptr);
usedGenericTypes.push_back(*genericType);
}
}
// Visit return type
SymbolType returnType(TY_DYN);
if (isFunction) {
returnType = std::any_cast<SymbolType>(visit(node->returnType()));
if (returnType.is(TY_UNRESOLVED))
return static_cast<std::vector<Function *> *>(nullptr);
if (!returnType.isCoveredByGenericTypeList(usedGenericTypes))
softError(node->returnType(), GENERIC_TYPE_NOT_IN_TEMPLATE,
"Generic return type not included in the template type list of the function");
}
// Visit params
std::vector<SymbolType> paramTypes;
ParamList paramList;
if (node->hasParams) {
paramList.reserve(node->paramTypeLst()->dataTypes().size());
for (DataTypeNode *param : node->paramTypeLst()->dataTypes()) {
auto paramType = std::any_cast<SymbolType>(visit(param));
if (paramType.is(TY_UNRESOLVED))
return static_cast<std::vector<Function *> *>(nullptr);
// Check if the type is present in the template for generic types
if (!paramType.isCoveredByGenericTypeList(usedGenericTypes)) {
softError(node->paramTypeLst(), GENERIC_TYPE_NOT_IN_TEMPLATE,
"Generic param type not included in the template type list of the function");
continue;
}
paramTypes.push_back(paramType);
paramList.push_back({paramType, false});
}
}
// Build signature object
Function signature(node->methodName, nullptr, SymbolType(TY_DYN), returnType, paramList, usedGenericTypes, node);
// Add signature to current scope
Function *manifestation = FunctionManager::insertFunction(currentScope, signature, &node->signatureManifestations);
manifestation->entry = node->entry;
manifestation->used = true;
// Prepare signature type
SymbolType signatureType(isFunction ? TY_FUNCTION : TY_PROCEDURE);
signatureType.specifiers = node->signatureSpecifiers;
if (isFunction)
signatureType.setFunctionReturnType(returnType);
signatureType.setFunctionParamTypes(paramTypes);
// Set entry to signature type
assert(node->entry != nullptr);
node->entry->updateType(signatureType, false);
node->entry->used = true;
return &node->signatureManifestations;
}
std::any TypeChecker::visitDeclStmt(DeclStmtNode *node) {
// Retrieve entry of the lhs variable
SymbolTableEntry *localVarEntry = currentScope->lookupStrict(node->varName);
assert(localVarEntry != nullptr);
SymbolType localVarType;
if (node->hasAssignment) {
// Visit the right side
auto rhs = std::any_cast<ExprResult>(visit(node->assignExpr()));
auto [rhsTy, rhsEntry] = rhs;
// If there is an anonymous entry attached (e.g. for struct instantiation), delete it
if (rhsEntry != nullptr && rhsEntry->anonymous) {
currentScope->symbolTable.deleteAnonymous(rhsEntry->name);
rhs.entry = rhsEntry = nullptr;
}
// Visit data type
localVarType = std::any_cast<SymbolType>(visit(node->dataType()));
// Infer the type left to right if the right side is an empty array initialization
if (rhsTy.isArrayOf(TY_DYN))
rhsTy = localVarType;
// Check if type has to be inferred or both types are fixed
if (!localVarType.is(TY_UNRESOLVED) && !rhsTy.is(TY_UNRESOLVED)) {
const ExprResult lhsResult = {localVarType, localVarEntry};
localVarType = OpRuleManager::getAssignResultType(node, lhsResult, rhs, true);
// Call copy ctor if required
if (localVarType.is(TY_STRUCT) && !node->isParam && !rhs.isTemporary()) {
Scope *matchScope = localVarType.getBodyScope();
assert(matchScope != nullptr);
// Check if we have a no-args ctor to call
const SymbolType &thisType = localVarType;
const ArgList args = {{thisType.toConstReference(node), false}};
node->calledCopyCtor = FunctionManager::matchFunction(matchScope, CTOR_FUNCTION_NAME, thisType, args, {}, true, node);
}
// If this is a struct type, check if the type is known. If not, error out
if (localVarType.isBaseType(TY_STRUCT) && !sourceFile->getNameRegistryEntry(localVarType.getBaseType().getSubType())) {
const std::string structName = localVarType.getBaseType().getSubType();
softError(node->dataType(), UNKNOWN_DATATYPE, "Unknown struct type '" + structName + "'. Forgot to import?");
localVarType = SymbolType(TY_UNRESOLVED);
}
} else {
localVarType = SymbolType(TY_UNRESOLVED);
}
} else {
// Visit data type
localVarType = std::any_cast<SymbolType>(visit(node->dataType()));
// References with no initialization are illegal
if (localVarType.isRef() && !node->isParam && !node->isForEachItem)
softError(node, REFERENCE_WITHOUT_INITIALIZER, "References must always be initialized directly");
// If this is a struct, check for the default ctor
if (localVarType.is(TY_STRUCT) && !node->isParam && !node->isForEachItem) {
Scope *matchScope = localVarType.getBodyScope();
assert(matchScope != nullptr);
// Check if we need to call a ctor
node->isCtorCallRequired = matchScope->hasRefFields();
// Check if we have a no-args ctor to call
const std::string &structName = localVarType.getSubType();
const SymbolType &thisType = localVarType;
node->calledInitCtor = FunctionManager::matchFunction(matchScope, CTOR_FUNCTION_NAME, thisType, {}, {}, false, node);
if (!node->calledInitCtor && node->isCtorCallRequired)
SOFT_ERROR_ST(node, MISSING_NO_ARGS_CTOR, "Struct '" + structName + "' misses a no-args constructor")
}
}
// Update the type of the variable
localVarEntry->updateType(localVarType, true);
node->entries.at(manIdx) = localVarEntry;
// Update the state of the variable
localVarEntry->updateState(INITIALIZED, node, true);
return node->setEvaluatedSymbolType(localVarType, manIdx);
}
std::any TypeChecker::visitCaseConstant(CaseConstantNode *node) {
// If we have a normal constant, we can take the symbol type from there
if (node->constant())
return visit(node->constant());
// Check if a local or global variable can be found by searching for the name
if (node->identifierFragments.size() == 1)
node->enumItemEntry = currentScope->lookup(node->identifierFragments.back());
// If no local or global was found, search in the name registry
if (!node->enumItemEntry) {
const NameRegistryEntry *registryEntry = sourceFile->getNameRegistryEntry(node->fqIdentifier);
if (!registryEntry)
SOFT_ERROR_ER(node, REFERENCED_UNDEFINED_VARIABLE, "The variable '" + node->fqIdentifier + "' could not be found")
node->enumItemEntry = registryEntry->targetEntry;
}
assert(node->enumItemEntry != nullptr);
// Check for the correct type
if (node->enumItemEntry->scope->type != ScopeType::ENUM)
SOFT_ERROR_ER(node, CASE_CONSTANT_NOT_ENUM, "Case constants must be of type enum")
const SymbolType varType = node->enumItemEntry->getType();
assert(varType.is(TY_INT));
return ExprResult{node->setEvaluatedSymbolType(varType, manIdx)};
}
std::any TypeChecker::visitReturnStmt(ReturnStmtNode *node) {
// Retrieve return variable entry
SymbolTableEntry *returnVar = currentScope->lookup(RETURN_VARIABLE_NAME);
const bool isFunction = returnVar != nullptr;
SymbolType returnType = isFunction ? returnVar->getType() : SymbolType(TY_DYN);
// Check if procedure with return value
if (!isFunction) {
if (node->hasReturnValue)
SOFT_ERROR_ER(node->assignExpr(), RETURN_WITH_VALUE_IN_PROCEDURE, "Return with value in procedure is not allowed")
return nullptr;
}
if (!node->hasReturnValue && !returnVar->isInitialized())
SOFT_ERROR_ST(node, RETURN_WITHOUT_VALUE_RESULT, "Return without value, but result variable is not initialized yet")
if (!node->hasReturnValue)
return nullptr;
// Visit right side
auto rhs = std::any_cast<ExprResult>(visit(node->assignExpr()));
HANDLE_UNRESOLVED_TYPE_ST(rhs.type)
// Check if types match
const ExprResult returnResult = {returnType, returnVar};
OpRuleManager::getAssignResultType(node->assignExpr(), returnResult, rhs, true, ERROR_MSG_RETURN);
// Manager dtor call
if (rhs.entry != nullptr) {
if (rhs.entry->anonymous) {
// If there is an anonymous entry attached (e.g. for struct instantiation), delete it
currentScope->symbolTable.deleteAnonymous(rhs.entry->name);
rhs.entry = nullptr;
} else {
// Otherwise omit the destructor call, because the caller destructs the value
rhs.entry->omitDtorCall = true;
}
}
return node->setEvaluatedSymbolType(returnType, manIdx);
}
std::any TypeChecker::visitBreakStmt(BreakStmtNode *node) {
// Check if the stated number is valid
if (node->breakTimes < 1)
SOFT_ERROR_ER(node, INVALID_BREAK_NUMBER, "Break count must be >= 1, you provided " + std::to_string(node->breakTimes))
// Check if we can break this often
const unsigned int maxBreaks = currentScope->getLoopNestingDepth();
if (static_cast<unsigned int>(node->breakTimes) > maxBreaks)
SOFT_ERROR_ER(node, INVALID_BREAK_NUMBER, "We can only break " + std::to_string(maxBreaks) + " time(s) here")
return nullptr;
}
std::any TypeChecker::visitContinueStmt(ContinueStmtNode *node) {
// Check if the stated number is valid
if (node->continueTimes < 1)
SOFT_ERROR_ER(node, INVALID_CONTINUE_NUMBER,
"Continue count must be >= 1, you provided " + std::to_string(node->continueTimes))
// Check if we can continue this often
const unsigned int maxContinues = currentScope->getLoopNestingDepth();
if (static_cast<unsigned int>(node->continueTimes) > maxContinues)
SOFT_ERROR_ER(node, INVALID_CONTINUE_NUMBER, "We can only continue " + std::to_string(maxContinues) + " time(s) here")
return nullptr;
}
std::any TypeChecker::visitFallthroughStmt(FallthroughStmtNode *node) {
// Check if we can do a fallthrough here
if (!currentScope->isInCaseBranch())
SOFT_ERROR_ER(node, FALLTHROUGH_NOT_ALLOWED, "Fallthrough is only allowed in case branches")
return nullptr;
}
std::any TypeChecker::visitAssertStmt(AssertStmtNode *node) {
// Visit condition
SymbolType conditionType = std::any_cast<ExprResult>(visit(node->assignExpr())).type;
HANDLE_UNRESOLVED_TYPE_ER(conditionType)
// Check if condition evaluates to bool
if (!conditionType.is(TY_BOOL))
SOFT_ERROR_ER(node->assignExpr(), ASSERTION_CONDITION_BOOL, "The asserted condition must be of type bool")
return nullptr;
}
std::any TypeChecker::visitPrintfCall(PrintfCallNode *node) {
// Check if assignment types match placeholder types
size_t placeholderCount = 0;
size_t index = node->templatedString.find_first_of('%');
while (index != std::string::npos && index != node->templatedString.size() - 1) {
// Check if there is another assignExpr
if (node->args().size() <= placeholderCount)
SOFT_ERROR_ER(node, PRINTF_ARG_COUNT_ERROR, "The placeholder string contains more placeholders than arguments")
// Get next assignment
AssignExprNode *assignment = node->args().at(placeholderCount);
// Visit assignment
SymbolType argType = std::any_cast<ExprResult>(visit(assignment)).type;
HANDLE_UNRESOLVED_TYPE_ER(argType)
argType = argType.removeReferenceWrapper();
switch (node->templatedString.at(index + 1)) {
case 'c': {
if (!argType.is(TY_CHAR))
SOFT_ERROR_ER(assignment, PRINTF_TYPE_ERROR, "The placeholder string expects char, but got " + argType.getName())
placeholderCount++;
break;
}
case 'd':
case 'i':
case 'l':
case 'o':
case 'u':
case 'x':
case 'X': {
if (!argType.isOneOf({TY_INT, TY_SHORT, TY_LONG, TY_BYTE, TY_BOOL}))
SOFT_ERROR_ER(assignment, PRINTF_TYPE_ERROR,
"The placeholder string expects int, short, long, byte or bool, but got " + argType.getName())
placeholderCount++;
break;
}
case 'a':
case 'A':
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G': {
if (!argType.is(TY_DOUBLE))
SOFT_ERROR_ER(assignment, PRINTF_TYPE_ERROR, "The placeholder string expects double, but got " + argType.getName())
placeholderCount++;
break;
}
case 's': {
if (!argType.is(TY_STRING) && !argType.isStringObj() && !argType.isPtrOf(TY_CHAR) && !argType.isArrayOf(TY_CHAR))
SOFT_ERROR_ER(assignment, PRINTF_TYPE_ERROR,
"The placeholder string expects string, String, char* or char[], but got " + argType.getName())
placeholderCount++;
break;
}
case 'p': {
if (!argType.isPtr() && !argType.isArray() && !argType.is(TY_STRING))
SOFT_ERROR_ER(assignment, PRINTF_TYPE_ERROR,
"The placeholder string expects pointer, array or string, but got " + argType.getName())
placeholderCount++;
break;
}
default:
SOFT_ERROR_ER(node, PRINTF_TYPE_ERROR, "The placeholder string contains an invalid placeholder")
}
index = node->templatedString.find_first_of('%', index + 2); // We can also skip the following char
}
// Check if the number of placeholders matches the number of args
if (placeholderCount < node->args().size())
SOFT_ERROR_ER(node, PRINTF_ARG_COUNT_ERROR, "The placeholder string contains less placeholders than arguments")
return ExprResult{node->setEvaluatedSymbolType(SymbolType(TY_BOOL), manIdx)};
}
std::any TypeChecker::visitSizeofCall(SizeofCallNode *node) {
if (node->isType) { // Size of type
visit(node->dataType());
} else { // Size of value
visit(node->assignExpr());
}
return ExprResult{node->setEvaluatedSymbolType(SymbolType(TY_LONG), manIdx)};
}
std::any TypeChecker::visitAlignofCall(AlignofCallNode *node) {
if (node->isType) { // Align of type
visit(node->dataType());
} else { // Align of value
visit(node->assignExpr());
}
return ExprResult{node->setEvaluatedSymbolType(SymbolType(TY_LONG), manIdx)};
}
std::any TypeChecker::visitLenCall(LenCallNode *node) {
SymbolType argType = std::any_cast<ExprResult>(visit(node->assignExpr())).type;
HANDLE_UNRESOLVED_TYPE_ER(argType)
argType = argType.removeReferenceWrapper();
// Check if arg is of type array
if (!argType.isArray() && !argType.is(TY_STRING))
SOFT_ERROR_ER(node->assignExpr(), EXPECTED_ARRAY_TYPE, "The len builtin can only work on arrays or strings")
// If we want to use the len builtin on a string, we need to import the string runtime module
if (argType.is(TY_STRING) && !sourceFile->isStringRT())
sourceFile->requestRuntimeModule(STRING_RT);
return ExprResult{node->setEvaluatedSymbolType(SymbolType(TY_LONG), manIdx)};
}
std::any TypeChecker::visitPanicCall(PanicCallNode *node) {
SymbolType argType = std::any_cast<ExprResult>(visit(node->assignExpr())).type;
HANDLE_UNRESOLVED_TYPE_ER(argType)
argType = argType.removeReferenceWrapper();
// Check if arg is of type array
if (!argType.isErrorObj())
SOFT_ERROR_ER(node->assignExpr(), EXPECTED_ERROR_TYPE, "The panic builtin can only work with errors")
return ExprResult{node->setEvaluatedSymbolType(SymbolType(TY_DYN), manIdx)};
}
std::any TypeChecker::visitAssignExpr(AssignExprNode *node) {
// Check if ternary
if (node->ternaryExpr()) {
auto result = std::any_cast<ExprResult>(visit(node->ternaryExpr()));
node->setEvaluatedSymbolType(result.type, manIdx);
return result;
}
// Check if assignment
if (node->op != AssignExprNode::OP_NONE) {
// Visit the right side first
auto rhs = std::any_cast<ExprResult>(visit(node->rhs()));
auto [rhsType, rhsEntry] = rhs;
HANDLE_UNRESOLVED_TYPE_ER(rhsType)
// Then visit the left side
auto lhs = std::any_cast<ExprResult>(visit(node->lhs()));
auto [lhsType, lhsVar] = lhs;
HANDLE_UNRESOLVED_TYPE_ER(lhsType)
// Take a look at the operator
if (node->op == AssignExprNode::OP_ASSIGN) {
rhsType = OpRuleManager::getAssignResultType(node, lhs, rhs);
// If there is an anonymous entry attached (e.g. for struct instantiation), delete it
if (rhsEntry != nullptr && rhsEntry->anonymous) {
currentScope->symbolTable.deleteAnonymous(rhsEntry->name);
rhsEntry = nullptr;
}
} else if (node->op == AssignExprNode::OP_PLUS_EQUAL) {
rhsType = opRuleManager.getPlusEqualResultType(node, lhs, rhs, 0).type;
} else if (node->op == AssignExprNode::OP_MINUS_EQUAL) {
rhsType = opRuleManager.getMinusEqualResultType(node, lhs, rhs, 0).type;
} else if (node->op == AssignExprNode::OP_MUL_EQUAL) {
rhsType = opRuleManager.getMulEqualResultType(node, lhs, rhs, 0).type;
} else if (node->op == AssignExprNode::OP_DIV_EQUAL) {
rhsType = opRuleManager.getDivEqualResultType(node, lhs, rhs, 0).type;
} else if (node->op == AssignExprNode::OP_REM_EQUAL) {
rhsType = OpRuleManager::getRemEqualResultType(node, lhs, rhs);
} else if (node->op == AssignExprNode::OP_SHL_EQUAL) {
rhsType = OpRuleManager::getSHLEqualResultType(node, lhs, rhs);
} else if (node->op == AssignExprNode::OP_SHR_EQUAL) {
rhsType = OpRuleManager::getSHREqualResultType(node, lhs, rhs);
} else if (node->op == AssignExprNode::OP_AND_EQUAL) {
rhsType = OpRuleManager::getAndEqualResultType(node, lhs, rhs);
} else if (node->op == AssignExprNode::OP_OR_EQUAL) {
rhsType = OpRuleManager::getOrEqualResultType(node, lhs, rhs);
} else if (node->op == AssignExprNode::OP_XOR_EQUAL) {
rhsType = OpRuleManager::getXorEqualResultType(node, lhs, rhs);
}
if (lhsVar) { // Variable is involved on the left side
// Perform type inference
if (lhsType.is(TY_DYN))
lhsVar->updateType(rhsType, false);
// In case the lhs variable is captured, notify the capture about the write access
if (Capture *lhsCapture = currentScope->symbolTable.lookupCapture(lhsVar->name); lhsCapture)
lhsCapture->setAccessType(READ_WRITE);
// Update the state of the variable
lhsVar->updateState(INITIALIZED, node, false);
}
return ExprResult{node->setEvaluatedSymbolType(rhsType, manIdx)};
}
throw CompilerError(UNHANDLED_BRANCH, "AssignExpr fall-through"); // GCOV_EXCL_LINE
}
std::any TypeChecker::visitTernaryExpr(TernaryExprNode *node) {
// Check if there is a ternary operator applied
if (node->children.size() == 1)
return visit(node->operands().front());
// Visit condition
LogicalOrExprNode *condition = node->operands()[0];
SymbolType conditionType = std::any_cast<ExprResult>(visit(condition)).type;
HANDLE_UNRESOLVED_TYPE_ER(conditionType)
SymbolType trueType;
SymbolType falseType;
if (node->isShortened) {
trueType = conditionType;
falseType = std::any_cast<ExprResult>(visit(node->operands()[1])).type;
} else {
trueType = std::any_cast<ExprResult>(visit(node->operands()[1])).type;
HANDLE_UNRESOLVED_TYPE_ER(trueType)
falseType = std::any_cast<ExprResult>(visit(node->operands()[2])).type;
}
HANDLE_UNRESOLVED_TYPE_ER(falseType)
// Check if the condition evaluates to bool
if (!conditionType.is(TY_BOOL))
SOFT_ERROR_ER(condition, OPERATOR_WRONG_DATA_TYPE, "Condition operand in ternary must be a bool")
// Check if trueType and falseType are matching
const SymbolType trueTypeModified = trueType.removeReferenceWrapper();
const SymbolType falseTypeModified = falseType.removeReferenceWrapper();
if (!trueTypeModified.matches(falseTypeModified, false, true, false))
SOFT_ERROR_ER(node, OPERATOR_WRONG_DATA_TYPE,
"True and false operands in ternary must be of same data type. Got " + trueType.getName(true) + " and " +
falseType.getName(true))
return ExprResult{node->setEvaluatedSymbolType(trueType, manIdx)};
}
std::any TypeChecker::visitLogicalOrExpr(LogicalOrExprNode *node) {
// Check if a logical or operator is applied
if (node->children.size() == 1)
return visit(node->operands().front());
// Visit leftmost operand
auto currentOperand = std::any_cast<ExprResult>(visit(node->operands()[0]));
HANDLE_UNRESOLVED_TYPE_ER(currentOperand.type)
// Loop through all remaining operands
for (size_t i = 1; i < node->operands().size(); i++) {
auto rhsOperand = std::any_cast<ExprResult>(visit(node->operands()[i]));
HANDLE_UNRESOLVED_TYPE_ER(rhsOperand.type)
currentOperand = {OpRuleManager::getLogicalOrResultType(node, currentOperand, rhsOperand)};
}
node->setEvaluatedSymbolType(currentOperand.type, manIdx);
return currentOperand;
}
std::any TypeChecker::visitLogicalAndExpr(LogicalAndExprNode *node) {
// Check if a logical and operator is applied
if (node->children.size() == 1)
return visit(node->operands().front());
// Visit leftmost operand
auto currentOperand = std::any_cast<ExprResult>(visit(node->operands()[0]));
HANDLE_UNRESOLVED_TYPE_ER(currentOperand.type)
// Loop through all remaining operands
for (size_t i = 1; i < node->operands().size(); i++) {
auto rhsOperand = std::any_cast<ExprResult>(visit(node->operands()[i]));
HANDLE_UNRESOLVED_TYPE_ER(rhsOperand.type)
currentOperand = {OpRuleManager::getLogicalAndResultType(node, currentOperand, rhsOperand)};
}
node->setEvaluatedSymbolType(currentOperand.type, manIdx);