-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtypecheck.cpp
2331 lines (2123 loc) · 84.6 KB
/
typecheck.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
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "ast.h"
#include "alloc.h"
#include "array.h"
#include "common.h"
#include "debug_print.h"
#include "error.h" // log()
// WARNING: error.h gives access to the global `loc`
#include "hash_table.h"
#include "llvm.h"
#include "str_intern.h"
extern config_t config;
/* Errors
*/
// TODO: Stop typechecking altogether after a threshold of errors.
static int num_global_typecheck_errors;
template <typename... Args>
void typecheck_error_no_ln(location_t __loc, Args... args) {
++num_global_typecheck_errors;
log(__loc);
yellow_on();
bold_on();
log(" Semantic Error: ");
bold_off();
yellow_off();
log(args...);
}
template <typename... Args>
static void typecheck_error(location_t __loc, Args... args) {
++num_global_typecheck_errors;
log(__loc);
yellow_on();
bold_on();
log(" Semantic Error: ");
bold_off();
yellow_off();
log(args...);
printf("\n");
}
/* End of errors */
// Used only in virtual table generation. It contains
// the roots of inheritance trees.
static Buf<IdType *> inher_roots;
void typecheck_init() {
set_indent_char('*');
}
/// Fill the type_table.
TypeTable install_type_declarations(Goal *goal) {
DeclarationVisitor decl_visitor(goal->type_decls.len);
goal->accept(&decl_visitor);
// Free memory that was used for allocating objects
// for parsing that doenot persist in pass 2 of type-checking.
deallocate(MEM::PARSE_TEMP);
return decl_visitor.type_table;
}
void full_typecheck(Goal *goal, TypeTable type_table) {
MainTypeCheckVisitor main_visitor(type_table);
goal->accept(&main_visitor);
}
static bool params_match(Method *m1, Method *m2) {
if (m1->param_len != m2->param_len) return false;
size_t it = 0;
for (Local *p1 : m1->locals) {
if (it == m1->param_len) break;
Local *p2 = m2->locals[it];
if (p1->type != p2->type) return false;
++it;
}
return true;
}
bool methods_have_same_signature(Method *m1, Method *m2) {
if (m1->ret_type != m2->ret_type)
return false;
return params_match(m1, m2);
}
static void print_param_types(Method *method) {
size_t param_len = method->param_len;
for (size_t i = 0; i != param_len; ++i) {
Local *param = method->locals[i];
printf("%s", param->type->name());
if (i + 1 != param_len) {
printf(", ");
}
}
}
constexpr ssize_t bucket_cap = 8;
struct Bucket {
const char *method_ids[bucket_cap];
ssize_t indexes[bucket_cap];
Bucket *next;
Bucket() {
next = NULL;
}
static void *operator new(size_t size) {
return allocate(size, MEM::VTABLE);
}
void insert(const char *method_id, ssize_t index_in_serial_buf, ssize_t index_in_bucket) {
assert(index_in_bucket >= 0 && index_in_bucket < bucket_cap);
method_ids[index_in_bucket] = method_id;
indexes[index_in_bucket] = index_in_serial_buf;
}
ssize_t find(const char *id, ssize_t lim) const {
for (ssize_t i = 0; i <= lim; ++i) {
if (method_ids[i] == id) {
return indexes[i];
}
}
return -1;
}
};
struct FirstBucket {
Bucket b;
ssize_t nelems = 0;
Bucket *last_bucket;
FirstBucket() {
clear();
}
void insert(const char *method_id, ssize_t index_in_serial_buf) {
ssize_t index_in_bucket = nelems % bucket_cap;
if (nelems != 0 && index_in_bucket == 0) {
// It may have been allocated from a previous downward
// tree traversal.
Bucket *b;
if (last_bucket->next == NULL) {
b = new Bucket;
last_bucket->next = b;
} else {
b = last_bucket->next;
}
last_bucket = b;
}
last_bucket->insert(method_id, index_in_serial_buf, index_in_bucket);
nelems++;
}
ssize_t find(const char *id) const {
const Bucket *runner = &b;
ssize_t lim = bucket_cap;
ssize_t i = nelems;
while (i > 0) {
assert(runner);
ssize_t lim = bucket_cap - 1;
if (i < bucket_cap) {
lim = i - 1;
}
ssize_t ndx = runner->find(id, lim);
if (ndx >= 0) {
return ndx;
}
runner = runner->next;
i -= bucket_cap;
}
return -1;
}
void clear() {
nelems = 0;
b.next = NULL;
last_bucket = &b;
}
};
struct VMethod {
Method *method;
const char *enclosing;
};
struct RestorePair {
Bucket *last_bucket;
ssize_t nelems;
};
struct VirtualTable {
constexpr static size_t nbuckets = 32;
size_t nelems;
FirstBucket buckets[nbuckets];
Buf<VMethod> vmethods;
VirtualTable() {
vmethods.reserve(32);
nelems = 0;
}
inline ssize_t hash(const char *key) const {
// Note: We have asserted that the key is not NULL,
// by definition, which leads to a fast and good
// multiplicative hasing.
// Prime factor
uint32_t factor = 100001029;
// Non-zero key gets hashed
uint64_t h = (uint32_t) ((uintptr_t)key * factor);
h = ((h * (uint64_t) this->nbuckets) >> 32);
return (ssize_t) h;
}
// NOTE: We don't test for duplicates.
void insert(Method *method, const char *enclosing) {
assert(method);
// Keep index that it will be pushed in the serial buffer.
ssize_t index = vmethods.len;
vmethods.push({method, enclosing});
// Insert it into the table (giving it an index to keep
// in the serial buffer)
const char *method_id = method->id;
ssize_t val = this->hash(method_id);
buckets[val].insert(method_id, index);
}
// Note that for the specific usage of this
// table, when we search for something, if it is
// found, we want to replace it. But only want
// to replace the "value" part, i.e. the VMethod.
// That's why we return a pointer to that.
VMethod *find(const char *id) {
ssize_t val = this->hash(id);
ssize_t index = buckets[val].find(id);
if (index == -1) {
return NULL;
}
return &vmethods[index];
}
void clear() {
nelems = 0;
vmethods.clear();
for (ssize_t i = 0; i < nbuckets; ++i) {
buckets[i].clear();
}
deallocate(MEM::VTABLE);
}
void save_first_buckets(RestorePair arr[VirtualTable::nbuckets]) {
for (ssize_t i = 0; i < VirtualTable::nbuckets; ++i) {
arr[i].nelems = buckets[i].nelems;
arr[i].last_bucket = buckets[i].last_bucket;
}
}
void restore_first_buckets(RestorePair arr[VirtualTable::nbuckets]) {
for (ssize_t i = 0; i < VirtualTable::nbuckets; ++i) {
buckets[i].nelems = arr[i].nelems;
buckets[i].last_bucket = arr[i].last_bucket;
}
}
};
bool check_method_for_overriding(Method *method, IdType *type, VirtualTable *vtable) {
VMethod *vmethod = vtable->find(method->id);
if (!vmethod) {
return false;
}
Method *method_parent = vmethod->method;
assert(method_parent);
if (!methods_have_same_signature(method, method_parent)) {
typecheck_error_no_ln(method->loc, method->ret_type->name(), " ", method->id, "(");
print_param_types(method);
printf(") in `%s` can't override %s %s(", type->id, method_parent->ret_type->name(),
method_parent->id);
print_param_types(method_parent);
printf(") in `%s`\n", vmethod->enclosing);
return false;
}
vmethod->enclosing = type->id;
method->offset = method_parent->offset;
return true;
}
void TypeTable::compute_and_print_offsets_for_type(IdType *type, size_t start_fields, size_t start_methods, VirtualTable *vtable) {
if (type == NULL) {
return;
}
IdType *parent = type->parent;
if (parent) {
// Inherits, so include the parent at the start of the type.
emit("%%class.%s = type { %%class.%s", type->id, parent->id);
} else {
// The first parent in the inheritance tree - create
// a vptr.
emit("%%class.%s = type { i8 (...)**", type->id);
}
// Process methods first to know how many methods we have so we
// can emit the respective virtual pointer.
int num_methods = start_methods / 8;
size_t running_offset = start_methods;
for (Method *method: type->methods) {
if (!check_method_for_overriding(method, type, vtable)) {
if (config.offsets) {
printf("%s.%s: %zd\n", type->id, method->id, running_offset);
}
method->offset = running_offset;
running_offset += 8;
++num_methods;
vtable->insert(method, type->id);
}
}
size_t methods_size = running_offset - start_methods;
// Generate offsets for fields and also emit the fields.
running_offset = start_fields;
for (Local *field : type->fields) {
field->offset = running_offset;
if (config.offsets) {
printf("%s.%s: %zd\n", type->id, field->id, field->offset);
}
emit(", ");
if (field->type == this->bool_type) {
emit("i1");
running_offset += 1;
} else if (field->type == this->int_type) {
emit("i32");
running_offset += 4;
} else if (field->type == this->int_arr_type) {
emit("i32*");
running_offset += 8;
} else {
IdType *idtype = field->type->is_IdType();
assert(idtype);
emit("%%class.%s*", idtype->id);
running_offset += 8;
}
}
emit(" }\n");
size_t fields_size = running_offset - start_fields;
start_fields = start_fields + fields_size;
type->__sizeof = start_fields;
start_methods = start_methods + methods_size;
Buf<VMethod> vmethods = vtable->vmethods;
type->vmethods_len = vmethods.len;
emit("@.%s = global [%d x i8*]\n[\n", type->id, vmethods.len);
ssize_t i = 0;
for (ssize_t i = 0; i < vmethods.len; ++i) {
VMethod vmethod = vmethods[i];
emit("i8* bitcast (");
emit_vmethod_signature(type, vmethod.method);
emit(" @%s__%s to i8*)", vmethod.enclosing, vmethod.method->id);
if (i != vmethods.len - 1) {
emit(",");
}
emit("\n");
}
emit("]\n");
assert(type->children);
auto children = *(type->children);
size_t len = children.len;
if (len) {
Buf<VMethod> deep_copy;
// We only need deep copy for more than one children.
RestorePair save[VirtualTable::nbuckets];
if (len > 1) {
deep_copy = vtable->vmethods.deep_copy();
vtable->save_first_buckets(save);
}
compute_and_print_offsets_for_type(children[0], start_fields, start_methods, vtable);
if (len > 1) {
for (ssize_t index = 1; index < len; ++index) {
vtable->vmethods = deep_copy;
vtable->restore_first_buckets(save);
IdType *child = children[index];
compute_and_print_offsets_for_type(child, start_fields, start_methods, vtable);
vtable->vmethods.free();
if (index != len - 1) {
deep_copy = vtable->vmethods.deep_copy();
}
}
}
}
type->invalidate_children();
}
void TypeTable::offset_computation() {
VirtualTable vtable;
for (IdType *type : inher_roots) {
//printf("-- Inheritance root: %s -- \n\n", type->id);
constexpr size_t start_fields = 0;
constexpr size_t start_methods = 0;
compute_and_print_offsets_for_type(type, start_fields, start_methods, &vtable);
vtable.clear();
//printf("\n");
}
deallocate(MEM::CHILDREN);
emit("\n");
}
bool typecheck(Goal *goal) {
typecheck_init();
constexpr int approximated_num_of_classes_per_inheritance_tree = 8;
// +1 for the main class
int type_decls_len = goal->type_decls.len + 1;
inher_roots.reserve(type_decls_len /
approximated_num_of_classes_per_inheritance_tree);
// Pass 1
TypeTable type_table = install_type_declarations(goal);
if (config.log) {
printf("\n");
}
// TODO: How able we are to continue?
// Print types that could not be inserted. This can
// happen if the types used are more than the type
// declarations. See TypeTable.
// TODO: The types in `could_not_be_inserted` might actually have a
// declaration. Consider that if say we have space in the table for 2
// type declarations. The declarations that _exist_ are for A and D.
// In A, let's say we use A, B, C and D in that order. D will be inserted
// last and it won't be in the type table. It will be in the
// `could_not_be_inserted` because of lack of space. But D
// actually has a declaration.
for (IdType *type : type_table.could_not_be_inserted) {
typecheck_error(type->loc, "Type `", type->id, "` has not been ",
"defined");
}
// Offset computation
type_table.offset_computation();
// Print calloc declarations etc.
cgen_init();
// Pass 2
full_typecheck(goal, type_table);
if (num_global_typecheck_errors == 0) {
return true;
}
return false;
}
/* Declaration Visitor
*/
IdType* DeclarationVisitor::id_to_type(const char *id, location_t loc) {
// Check if it already exists.
IdType *type = this->type_table.find(id);
if (type) {
return type;
}
// Otherwise construct a new one and
// save it in the table.
type = new IdType(id);
type->loc = loc;
this->type_table.insert(type->id, type);
return type;
}
// This is member of the visitor so that we have
// access to the type table.
Type* DeclarationVisitor::typespec_to_type(Typespec tspec, location_t loc) {
switch (tspec.kind) {
case TYSPEC::UNDEFINED: assert(0);
case TYSPEC::INT: return type_table.int_type;
case TYSPEC::ARR: return type_table.int_arr_type;
case TYSPEC::BOOL: return type_table.bool_type;
case TYSPEC::ID: return this->id_to_type(tspec.id, loc);
default: assert(0);
}
}
/* Type Table
*/
void TypeTable::initialize(size_t n) {
type_table.reserve(n);
undefined_type = new Type(TY::UNDEFINED);
bool_type = new Type(TY::BOOL);
int_type = new Type(TY::INT);
int_arr_type = new Type(TY::ARR);
}
void TypeTable::insert(const char *id, IdType* v) {
if (!type_table.insert(id, v)) {
// Search in the auxiliary buffer
for (IdType *type : could_not_be_inserted) {
if (type->id == id) {
return;
}
}
could_not_be_inserted.push(v);
}
}
DeclarationVisitor::DeclarationVisitor(size_t ntype_decls) {
// IMPORTANT: Before installing a type, the user
// is responsible for checking if it exists.
// +1 for the main class
this->type_table.initialize(ntype_decls + 1);
}
void DeclarationVisitor::visit(Goal *goal) {
LOG_SCOPE;
debug_print("Pass1::Goal\n");
goal->main_class.accept(this);
for (TypeDeclaration *type_decl : goal->type_decls) {
type_decl->accept(this);
}
}
void DeclarationVisitor::visit(MainClass *main_class) {
LOG_SCOPE;
debug_print("Pass1::MainClass: %s\n", main_class->id);
// Assert that we visit this first i.e., no types have been created
assert(this->type_table.len_inserted() == 0);
IdType *main_cls_type = new IdType(main_class->id,
/* nfields = */ 0,
/* nmethods = */ 0);
main_cls_type->loc = main_class->loc;
this->type_table.main_cls_type = main_cls_type;
this->type_table.insert(main_class->id, main_cls_type);
inher_roots.push(main_cls_type);
// Construct a custom method for `main()`
Method *main_method = Method::construct_main_method(this, main_class);
this->type_table.main_method = main_method;
}
// Note - IMPORTANT:
// A lot of IdTypes just start undefined (i.e. kind == TY::UNDEFINED)
// if we have seen a declaration with this type but we have
// not yet seen a definition. For example:
// int test(A a)
// if we have not yet have seen the definition of A.
// We install (i.e allocate) a type (if one does not exist already for id `A`)
// but we just keep it undefined (and keep a pointer to it).
// If we then _see_
// class A { ...
// we don't allocate a new type (note below that we're searching the table).
// We do the changes in the same memory that was allocated when we were in `test(A a)`.
// And we change the type from undefined.
// If we never see the definition of `A`, it will be caught in pass 2 as described below.
// Essentially, this almost eliminates searches in the type table in the pass 2.
// We just check the pointer and if the type was never defined, it will have
// remained undefined and we issue an error. Otherwise, the definition of this
// type will be in the same memory location.
void DeclarationVisitor::visit(TypeDeclaration *type_decl) {
LOG_SCOPE;
assert(!type_decl->is_undefined());
print_indentation();
debug_log(type_decl->loc, "Pass1::TypeDeclaration: ", type_decl->id, "\n");
IdType *type = this->type_table.find(type_decl->id);
// If it exists and it's declared (i.e. we have processed
// a type with the same `id`), then we have redeclaration error.
if (type) {
if (type->is_defined()) {
typecheck_error(type_decl->loc, "Type with id: `", type_decl->id,
"` has already been declared");
return;
} else {
// Overwrite the location. If the type is already inserted, its
// loc is its first usage.
type->loc = type_decl->loc;
type->set_sizes(type_decl->vars.len, type_decl->methods.len);
}
} else {
type = new IdType(type_decl->id, type_decl->vars.len, type_decl->methods.len);
type->loc = type_decl->loc;
this->type_table.insert(type->id, type);
}
// Handle inheritance
if (type_decl->extends) {
IdType *parent = this->id_to_type(type_decl->extends, type_decl->loc);
type->set_parent(parent);
parent->add_child(type);
} else {
inher_roots.push(type);
}
for (LocalDeclaration *ld : type_decl->vars) {
// Check redefinition in fields.
// IMPORTANT:
// - A field must not conflict with a field of the current class.
// - A field can conflict with a field of the parent class and
// this is called shadowing. And it's correct (when we refer
// to the field, we refer to the most immediate in the
// inheritance tree).
// - A field can't possibly conflict with a method
// of the current class because first we define all the fields,
// then all the methods (so, only a method can conflict with a field).
// - A field can conflict with a method of a parent class, but that's
// NOT an error. Because it is disambiguated in what we refer to
// by the way we dereference.
Field *field = type->fields.find(ld->id);
if (field) {
typecheck_error(ld->loc, "In class with id: `", type_decl->id,
"`, redefinition of field with id: `", field->id, "`");
} else {
field = ld->accept(this);
field->kind = (int)LOCAL_KIND::FIELD;
type->fields.insert(field->id, field);
}
}
for (MethodDeclaration *md : type_decl->methods) {
// Check redefinition
// IMPORTANT:
// - A method must not conflict with a method of the current class.
// - A method must not conflict with a field of the current class.
// - A method can conflict with a method of the parent class:
// -- If the methods have the same return type and the _same_
// parameters, then it's valid overriding.
// -- Otherwise, it's an error.
// We CAN'T check this in the first pass as it is possible that
// we have not processed the parent type yet. Note that we don't
// check this at the typecheck visitor but at the offset computation.
// - A method can conflict with a field of the parent
// but that's NOT an error. Because it is disambiguated in what
// we refer to by the way we dereference.
Method *method = type->methods.find(md->id);
if (method) {
typecheck_error(md->loc, "In class with id: `", type_decl->id,
"`, redefinition of method with id: `", method->id,
"`. Note that you can override but not overload ",
"a method");
} else {
method = md->accept(this);
assert(method);
assert(method->id);
type->methods.insert(method->id, method);
}
}
}
Local *DeclarationVisitor::visit(LocalDeclaration *local_decl) {
// Note: It's responsibility of the one who calls this visit
// to have assured that a local declaration with the same
// id does not exist.
LOG_SCOPE;
assert(!local_decl->is_undefined());
print_indentation();
debug_log(local_decl->loc, "LocalDeclaration: ", local_decl->id, "\n");
if (local_decl->typespec.id != NULL
&& local_decl->typespec.id == this->type_table.main_cls_type->id)
{
typecheck_error(local_decl->loc, "You can't declare a local of type of",
" the main class.");
}
Type *type = typespec_to_type(local_decl->typespec, local_decl->loc);
Local *local = new Local(local_decl->id, type);
return local;
}
const char *DeclarationVisitor::gen_id() {
static int count = 0;
char buf[64];
sprintf(buf, "a%d", count);
count++;
return str_intern(buf);
}
Method *DeclarationVisitor::visit(MethodDeclaration *method_decl) {
// Note: It's responsibility of the one who calls this visit
// to have assured that a method with the same id does not exist.
LOG_SCOPE;
assert(!method_decl->is_undefined());
print_indentation();
debug_log(method_decl->loc, "MethodDeclaration: ", method_decl->id, "\n");
Method *method = new Method(method_decl);
assert(method);
method->ret_type = this->typespec_to_type(method_decl->typespec, method_decl->ret->loc);
for (LocalDeclaration *par : method_decl->params) {
// We accept the param anyway. But in the case that there is
// another param with the same name, we still insert this
// (so that the rest of type-checking can sort of continue) but
// we have to generate a (dummy) id for it.
Param *param = par->accept(this);
if (method->locals.find(par->id)) {
typecheck_error(par->loc, "Parameter `", par->id, "` is already defined",
" in method `", method_decl->id, "`");
param->id = gen_id();
}
method->locals.insert(param->id, param);
}
for (LocalDeclaration *var : method_decl->vars) {
if (method->locals.find(var->id)) {
typecheck_error(var->loc, "Variable `", var->id, "` is already defined",
" in method `", method_decl->id, "`");
} else {
Var *v = var->accept(this);
method->locals.insert(v->id, v);
}
}
return method;
}
/* Main TypeCheck Visitor (Pass 2)
*/
void MainTypeCheckVisitor::visit(Goal *goal) {
LOG_SCOPE;
debug_print("MainTypeCheck::Goal\n");
goal->main_class.accept(this);
for (IdType *type : this->type_table) {
if (type->is_defined()) {
type->accept(this);
} else {
// type->loc is going to be the location of its first usage (Check
// id_to_type()). Ideally, we would like to have all the locations
// it was used, or some, but this will at least make this a not very
// bad message.
typecheck_error(type->loc, "Type `", type->id, "` has not been ",
"defined");
}
}
}
void MainTypeCheckVisitor::visit(MainClass *main_class) {
LOG_SCOPE;
debug_print("MainTypeCheck::MainClass\n");
this->curr_class = this->type_table.main_cls_type;
this->type_table.main_method->accept(this, this->curr_class->id);
this->curr_class = NULL;
}
void MainTypeCheckVisitor::visit(IdType *type) {
LOG_SCOPE;
assert(type->is_IdType());
assert(type->is_defined());
debug_print("MainTypeCheck::IdType %s\n", type->id);
this->curr_class = type;
for (Method *method : type->methods) {
method->accept(this, type->id);
}
this->curr_class = NULL;
}
// True if `rhs` is child of `lhs` (or they're equal)
static bool compatible_types(Type *lhs, Type *rhs) {
if (lhs == rhs) return true;
IdType *ty1 = lhs->is_IdType();
IdType *ty2 = rhs->is_IdType();
if (ty1 && ty2) {
IdType *runner = ty2;
while (runner->parent) {
runner = runner->parent;
if (runner == ty1) {
return true;
}
// Cyclic inheritance, we issue error elsewhere.
if (runner == ty2) break;
}
return false;
}
return false;
}
extern ExprContext __expr_context;
static bool type_transitively_extends_Main(MainTypeCheckVisitor *visitor,
const char *class_name) {
IdType *type = visitor->type_table.find(class_name);
const char *main_cls_id = visitor->type_table.main_cls_type->id;
assert(type);
IdType *parent = type->parent;
while (parent != NULL) {
if (parent->id == main_cls_id) {
return true;
}
parent = parent->parent;
}
return false;
}
void MainTypeCheckVisitor::visit(Method *method, const char *class_name) {
LOG_SCOPE;
debug_print("MainTypeCheck::Method %s\n", method->id);
this->curr_method = method;
__expr_context.method = method;
bool is_main_method = method->id == main_method_string;
cgen_start_method(method, class_name, is_main_method);
if (is_main_method && type_transitively_extends_Main(this, class_name))
{
typecheck_error(method->loc, "In type: `", class_name,
"` you can't name a method `main` because "
"the type transitively extends `Main` class.");
}
for (int i = 0; i < __expr_context.nesting_level; ++i) {
for (int j = 0; j < __expr_context.if_bufs[i].len; ++j) {
__expr_context.if_bufs[i][j].assigned = false;
}
for (int j = 0; j < __expr_context.else_bufs[i].len; ++j) {
__expr_context.else_bufs[i][j].assigned = false;
}
}
__expr_context.nesting_level = 0;
for (Statement *stmt : method->stmts) {
stmt->accept(this);
}
// An undefined return expression may actually end up here.
// Check parse.cpp
// A null expression may also come here because of the `main()` method.
if (!is_main_method && !method->ret_expr->is_undefined()) {
assert(method->ret_expr);
Type *ret_type = method->ret_expr->accept(this);
if (ret_type->kind != TY::UNDEFINED) {
assert(ret_type);
assert(method->ret_type);
llvalue_t ret_val = __expr_context.llval;
if (!compatible_types(method->ret_type, ret_type)) {
location_t loc_here = method->ret_expr->loc;
typecheck_error(loc_here, "The type: `", ret_type->name(),
"` of the return expression does not match the ",
"return type: `", method->ret_type->name(),
"` of method: `", method->id, "`");
} else {
llvm_ret(ret_type, ret_val);
}
}
}
this->curr_method = NULL;
cgen_end_method(is_main_method);
// Free arena for objects of function lifetime
deallocate(MEM::FUNC);
}
static Local *lookup_local(const char *id, Method *method, IdType *cls) {
// Check current method's locals (vars and params).
Local *local = method->locals.find(id);
if (local) {
return local;
}
// Check current class's fields.
local = cls->fields.find(id);
if (local) {
return local;
}
// Check parent's fields (account for cyclic inheritance).
IdType *runner = cls;
while (runner->parent) {
runner = runner->parent;
local = runner->fields.find(id);
if (local) {
return local;
}
// Cyclic inheritance, we issue error elsewhere.
if (runner == cls) break;
}
return NULL;
}
static bool check_expr_list_against_method(FuncArr<Type*> expr_list, Method *method) {
if (expr_list.len != method->param_len) {
return false;
}
size_t formal_param_counter = 0;
for (Type *ety : expr_list) {
Type *formal_type = method->locals[formal_param_counter]->type;
if (!compatible_types(formal_type, ety)) {
return false;
}
++formal_param_counter;
}
assert(formal_param_counter == method->param_len);
return true;
}
static Method *lookup_method_parent(const char *id, IdType *cls, IdType **ret_parent = NULL) {
IdType *runner = cls;
while (runner->parent) {
runner = runner->parent;
Method *method = runner->methods.find(id);
if (method) {
if (ret_parent) {
*ret_parent = runner;
}
return method;
}
// Cyclic inheritance, we issue error elsewhere.
if (runner == cls) break;
}
return NULL;
}
static Method *lookup_method(const char *id, IdType *cls) {
// Check current class's methods
Method *method = cls->methods.find(id);
if (method) {
return method;
}
// Check parent's methods (account for cyclic inheritance).
return lookup_method_parent(id, cls);
}
static Method *deduce_method(FuncArr<Type*> expr_list, const char *method_id, IdType *cls) {
IdType *runner = cls;
do {
Method *method = lookup_method(method_id, runner);
if (method) {
if (check_expr_list_against_method(expr_list, method)) {
return method;
}
}
runner = runner->parent;
// Cyclic inheritance, we issue error elsewhere.
if (runner == cls) break;
} while (runner);
return NULL;
}
// Only used for EXPR::AND
static Type *typecheck_and_helper(bool is_correct, Expression *expr,
MainTypeCheckVisitor *v, Type *boolty, Type *undefinedty) {
Type *ty = expr->accept(v);
if (ty->kind == TY::UNDEFINED) {
return undefinedty;
}
if (ty != boolty) {
typecheck_error(expr->loc, "Bad right operand for binary operator `&&`. Operand ",
"of boolean type was expected, found: `", ty->name(), "`");
is_correct = false;
}
if (is_correct) {
return boolty;
}
return undefinedty;
}
#define poison_expr(t) \
if (t->kind == TY::UNDEFINED) { \
return this->type_table.undefined_type; \
} \
// IMPORTANT: DO NOT check if a type is undefined with equality test with
// type_table.undefined_type. Check a note above on a full explanation.
// A lot of types can have remained undefined (either because we never saw a definition
// or the definition was invalid) but are not pointing to
// type_table.undefined_type. type_table.undefined_type is only for denoting
// an undefined type in general (e.g. an expression has undefined type, return
// type_table.undefined_type as its type. The caller checks for equality
// with type_table.undefined_type to see if it was valid).
// TODO: Maybe pass a second argument which is the expected return type. This is
// because a lot of times, when we find an error, we don't want to introduce useless
// cascading errors by return e.g. undefined_type. But currently, we can't know
// what the caller expects so we can just return that.
Type* MainTypeCheckVisitor::visit(Expression *expr) {
LOG_SCOPE;
assert(!expr->is_undefined());
// Used in binary expression cases.
BinaryExpression *be = (BinaryExpression *) expr;
switch (expr->kind) {
case EXPR::BOOL_LIT:
{
debug_print("MainTypeCheck::BoolExpression\n");
/// Codegen ///
__expr_context.llval.kind = LLVALUE::CONST;
__expr_context.llval.val = expr->lit_val;
/// End of Codegen ///
return this->type_table.bool_type;
} break;
case EXPR::ID:
{
debug_print("MainTypeCheck::IdExpression: %s\n", expr->id);
assert(this->curr_method);
assert(this->curr_class);
Local *local = lookup_local(expr->id, this->curr_method, this->curr_class);
if (!local) {
typecheck_error(expr->loc, "In identifier expression, Identifier: `",
expr->id, "` is not defined.");