-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeGenerator.cpp
2192 lines (1843 loc) · 73 KB
/
CodeGenerator.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 <iostream>
#include <vector>
#include <stack>
#include <list>
#include <regex>
#include <algorithm>
#include <iomanip>
using namespace std;
#include "CodeGenerator.h"
static int Stack_Address = 5;
static int Struct_Stack_Address = 0;
const int MAX = 100;
/***************************************************** Aux Classes ************************************************/
vector<string> tokenize(const string str, const regex re) {
sregex_token_iterator it{str.begin(), str.end(), re, -1};
vector<string> tokenized{it, {}};
// Additional check to remove empty strings
tokenized.erase(std::remove_if(tokenized.begin(), tokenized.end(),
[](std::string const &s) {
return s.size() == 0;
}), tokenized.end());
return tokenized;
}
template<class T>
class MyStack : public stack<T> {
public:
// Old pop was weird, so I changed it.
T pop() {
T elem = this->top();
stack<T>::pop();
return elem;
}
void collect(const T &to_collect) {
this->push(to_collect);
}
};
typedef MyStack<int> Dims;
typedef MyStack<treenode *> ASTNodes;
template<class T>
class OrderedArray : public vector<T> {
public:
OrderedArray() = default;
explicit OrderedArray(const MyStack<T> &st) {
MyStack<T> copy(st);
while (!copy.empty()) {
vector<T>::push_back(copy.pop());
}
}
};
class OrderedDims : public OrderedArray<int> {
public:
OrderedDims() = default;
OrderedDims(const OrderedDims ©) = default;
explicit OrderedDims(const Dims &st) : OrderedArray<int>(st) {}
};
class OrderedNodes : public OrderedArray<treenode *> {
public:
OrderedNodes() = default;
explicit OrderedNodes(const ASTNodes &astNodes) : OrderedArray<treenode *>(astNodes) {}
};
/**********************************************************************************************************************/
class Variable {
/* Think! what does a Variable contain? */
const string identifier, type;
int address, size;
Variable *next;
OrderedDims ordered_dims;
bool heap_allocd;
list<Variable> fields;
public:
Variable(string key, string type, int address, int size, const Dims &dims = Dims(), bool heap_allocd = false,
list<Variable> fields = list<Variable>())
: identifier(key), size(size),
type(type), address(address),
next(nullptr),
ordered_dims(dims), heap_allocd(heap_allocd), fields(fields) {}
Variable(string key, string type, int address, int size, const OrderedDims &o_dims, bool heap_allocd = false,
list<Variable> fields = list<Variable>())
: identifier(key), size(size),
type(type), address(address),
next(nullptr),
ordered_dims(o_dims), heap_allocd(heap_allocd), fields(fields) {}
const string &getIdentifier() const { return identifier; }
const string &getType() const { return type; }
int getAddress() const { return address; }
int getSize() const { return size; }
const OrderedDims &getOrderedDims() const { return ordered_dims; }
bool is_heap_allocd() const { return heap_allocd; }
static list<Variable> get_fields(int absolute_address, const list<Variable> &fields) {
int abs_address = absolute_address; // struct starting address.
list<Variable> abs_fields;
for (const auto &field: fields) {
Variable copy(field);
copy.address = abs_address;
abs_address += field.size;
abs_fields.push_back(copy);
}
return abs_fields;
}
const list<Variable> &get_fields_rel() const {
return fields;
}
void setFields(list<Variable> _fields) {
fields.clear();
for (auto &field: _fields) {
fields.push_back(field);
}
}
friend class SymbolTable;
};
class StructDef {
string name;
int curr_rel_address;
int size;
list<Variable> fields;
static bool in_progress;
public:
explicit StructDef(const string &_name) : name("struct " + _name), curr_rel_address(0), size(-1) {}
StructDef(const string &_name, const list<Variable> &var_list) : name(_name), curr_rel_address(0), size(-1) {
for (const auto &var: var_list) {
add_field(var);
}
}
void add_field(const Variable &field, bool single_field = false) {
const string &identifier(field.getIdentifier()), &type(field.getType());
int f_size(field.getSize());
fields.emplace_back(identifier, type, curr_rel_address, f_size, field.getOrderedDims(), false,
field.get_fields_rel());
curr_rel_address += field.getSize();
if (single_field)
size = curr_rel_address;
}
const string &get_name() const {
return name;
}
Variable get_field(const string &field_name) const {
for (const auto &field: fields) {
if (field_name == field.getIdentifier()) {
return field;
}
}
cout << "Field unfound!" << endl;
exit(-1);
}
int get_size() const {
if (size == -1) {
cout << "Struct not constructed yet!" << endl;
exit(-1);
}
return size;
}
list<Variable> get_fields() const { return fields; }
static bool is_in_progress() {
return in_progress;
}
void start() {
in_progress = true;
}
void finish() {
in_progress = false;
size = curr_rel_address; // at the end should be total size.
Struct_Stack_Address = 0;
}
~StructDef() {}
};
bool StructDef::in_progress = false;
class StructFieldsGenerated {
list<Variable> fields;
public:
void add_field(const Variable &field) { fields.push_back(field); }
void reset() { fields.clear(); }
list<Variable> get_sfg() const { return fields; }
};
class StructDefinitions {
list<StructDef> struct_defs;
public:
void add_definition(const StructDef &struct_def) { struct_defs.push_back(struct_def); }
const StructDef &find_def(const string &strct_type) const {
for (const auto &def: struct_defs) {
if (strct_type.find(def.get_name()) != string::npos)
return def;
}
cout << "Struct definition not found!" << endl;
exit(-1);
}
};
class SymbolTable {
/* Think! what can you add to symbol_table */
Variable *head[MAX];
// list<StructDef> struct_definitions;
StructFieldsGenerated sfg;
StructDefinitions sd;
struct {
const string i;
const string f;
const string d;
const string p;
bool isBasic(const string &type) { return type == i || type == f || type == d || type == p; }
} base_t;
friend class Array;
public:
SymbolTable() : base_t({"int", "float", "double", "pointer"}) {
for (int i = 0; i < MAX; i++) {
head[i] = nullptr;
}
}
// Function to find a variable, nullptr is returned if not found.
const Variable *find(const string &id) {
bool is_struct_field = false;
string struct_id, struct_field;
auto iter = id.find('.');
if (iter != string::npos) {
struct_id = id.substr(0, iter);
struct_field = id.substr(iter + 1);
is_struct_field = true;
}
int index = is_struct_field ? hashf(struct_id) : hashf(id);
Variable *start = head[index];
if (start == nullptr)
return nullptr;
while (start != nullptr) {
if (start->identifier == struct_id && is_struct_field) {
string struct_type = start->getType();
const StructDef &s_def = get_struct_definition(struct_type);
const Variable field = s_def.get_field(struct_field);
string f_id = field.identifier;
string f_type = field.type;
int f_address = start->address + field.address;
int f_size = field.size;
OrderedDims f_dims = field.getOrderedDims();
return new Variable(f_id, f_type, f_address, f_size, f_dims, true);
}
if (start->identifier == id) {
return start;
}
start = start->next;
}
return nullptr; // not found
}
// Function to insert an identifier
bool insert(const string &id, const string &type, int address, int size, const Dims &dims = Dims(),
list<Variable> fields = list<Variable>()) {
int index = hashf(id);
list<Variable> fields_to_insert = StructDef::is_in_progress() ? fields : Variable::get_fields(address, fields);
Variable *p = new Variable(id, type, address, size, dims, false, fields_to_insert);
if (StructDef::is_in_progress()) {
sfg.add_field(*p);
delete p;
return true;
}
if (head[index] == nullptr) {
head[index] = p;
return true;
} else {
Variable *start = head[index];
while (start->next != nullptr)
start = start->next;
start->next = p;
return true;
}
return false;
}
// Function to insert an identifier
bool insert(Variable *var) {
int index = hashf(var->identifier);
Variable *p = var;
Variable **ref;
if (StructDef::is_in_progress()) {
sfg.add_field(*p);
delete p;
return true;
} else {
ref = head;
}
if (ref[index] == nullptr) {
ref[index] = p;
return true;
} else {
Variable *start = ref[index];
while (start->next != nullptr)
start = start->next;
start->next = p;
return true;
}
return false;
}
int hashf(string id) {
int asciiSum = 0;
for (int i = 0; i < id.length(); i++) {
asciiSum = asciiSum + id[i];
}
return (asciiSum % MAX);
}
static void print() {
cout << "print() placeholder" << endl;
}
static string CalcType(string type, int num_of_stars) {
for (int i = 0; i < num_of_stars; ++i) {
type += "*";
}
return type;
}
int CalcSize(const string &type, const Dims &dims_of_array = Dims()) {
string t(type);
int type_size = 0;
Dims dims(dims_of_array);
// might make problems currently with int* arr[5]!
if (t.find('*') != string::npos) t = "pointer";
if (base_t.isBasic(t)) // int,float,double,pointer
type_size = 1;
else {
type_size = sd.find_def(type).get_size();
}
//maybe insert dims into table,can't hurt right? meh...
while (!dims.empty()) {
type_size *= dims.pop();
}
if (type_size == 0) {
cout << "Size was not defined!" << endl;
exit(-1);
}
return type_size;
}
bool is_pointer(const string &id) {
const Variable *var = find(id);
if (!var) {
cout << "Var not in symbol table!" << endl;
exit(-1);
}
const string &var_type = var->getType();
if (var->is_heap_allocd())
delete var;
if (var_type.find('*') != string::npos)
return true;
return false;
}
bool is_array(const string &id) {
const Variable *var = find(id);
if (!var) {
cout << "Var not in symbol table!" << endl;
exit(-1);
}
OrderedDims var_dims = var->getOrderedDims();
if (var->is_heap_allocd())
delete var;
if (!var_dims.empty())
return true;
return false;
}
list<Variable> get_generated_fields() const { return sfg.get_sfg(); }
~SymbolTable() {
for (auto var: head) {
if (var) delete var->next;
delete var;
}
}
void add_struct_definition(const StructDef &structDef) {
sd.add_definition(structDef);
sfg.reset();
}
const StructDef &get_struct_definition(string struct_type) const {
return sd.find_def(struct_type);
}
};
SymbolTable ST;
//ostream& operator<<(ostream& os, double val)
//{
// os << dt.mo << '/' << dt.da << '/' << dt.yr;
// return os;
//}
list<Variable> add_struct_subfields(Variable v) {
string type = v.getType();
if (type.find('*') != string::npos) { // pointer
return list<Variable>();
}
const StructDef &s_def = ST.get_struct_definition(type);
list<Variable> fields = Variable::get_fields(v.getAddress(), s_def.get_fields());
for (auto &field: fields) {
if (field.getType().find("struct") != string::npos) {
field.setFields(add_struct_subfields(field));
}
}
return fields;
}
class TreeNode { //base class
public:
/*you can add another son nodes */
TreeNode *son1;
TreeNode *son2;
virtual ~TreeNode() {
delete son1;
delete son2;
};
TreeNode(TreeNode *left = nullptr, TreeNode *right = nullptr) : son1(left), son2(right) {};
/*recursive function to make Pcode*/
virtual void gencode(string c_type = "") {
if (son1 != nullptr) son1->gencode(c_type);
if (son2 != nullptr) son2->gencode(c_type);
};
};
/******************************************************* IMPLEMENTATION ZONE ***************************************************************/
TreeNode *obj_tree(treenode *root);
bool is_constant(TreeNode *expr);
bool is_zero_expr(TreeNode *expr);
double calculate_value(TreeNode *expr);
/*
* Generic class to have the option to collect according to tree structure.
* Inherit from this class to add functionality.
*/
template<class CollectorObject, class LeftField = string, class CollectedType = int>
class Collector {
const treenode *start;
CollectorObject &collector_o; // container with collect method
LeftField &left_field;
protected:
tn_t follow_up_node;
public:
Collector(const treenode *start, CollectorObject &collector, tn_t follow_up_node_type, LeftField &left_field)
: start(start),
collector_o(collector),
follow_up_node(
follow_up_node_type),
left_field(left_field) {}
void collect() {
const treenode *curr = start;
CollectedType item_to_collect;
while (curr->lnode->hdr.type == follow_up_node) { // collect
item_to_collect = right_field_selector(curr->rnode);
collector_o.collect(item_to_collect);
curr = curr->lnode;
}
collector_o.collect(right_field_selector(curr->rnode));
left_field = left_field_selector(curr->lnode);
}
virtual CollectedType right_field_selector(treenode *to_collect_from) = 0;
virtual LeftField left_field_selector(treenode *to_collect_from) = 0;
};
typedef list<treenode *> FieldNodes;
class StructComponentCollectorO {
FieldNodes components;
public:
void collect(treenode *component) { components.push_front(component); }
const list<treenode *> &get_components() const { return components; }
};
class StructFieldCollector : public Collector<StructComponentCollectorO, treenode *, treenode *> {
StructComponentCollectorO collector;
treenode *left_field;
public:
StructFieldCollector(treenode *field_list_node) : Collector<StructComponentCollectorO, treenode *, treenode *>(
field_list_node, collector, TN_FIELD_LIST, left_field) {
collect();
collector.collect(left_field);
}
treenode *right_field_selector(treenode *to_collect_from) override {
if (to_collect_from->hdr.type != TN_COMP_DECL) {
cout << "RNode Selector: Wrong node collected!" << endl;
exit(-1);
}
return to_collect_from;
}
treenode *left_field_selector(treenode *to_collect_from) override {
if (to_collect_from->hdr.type != TN_COMP_DECL) {
cout << "LNode Selector: Wrong node collected!" << endl;
exit(-1);
}
return to_collect_from;
}
const FieldNodes &get_field_nodes() const {
return collector.get_components();
}
};
// This class adds labels to ST, it does NOT create pcode.
class ArrayLabelAdder : public Collector<Dims> {
Dims dims;
string type;
string name;
public:
ArrayLabelAdder(treenode *arr_decl_node, const string &type) : Collector<Dims>(arr_decl_node, dims,
TN_ARRAY_DECL, name), type(type) {
collect(); // collect dimensions + name.
int size = ST.CalcSize(type, dims);
int &address = StructDef::is_in_progress() ? Struct_Stack_Address : Stack_Address;
list<Variable> fields;
if (type.find("struct") != string::npos) {
fields = ST.get_struct_definition(type).get_fields();
}
ST.insert(name, type, address, size, dims, fields);
address += size;
}
int right_field_selector(treenode *to_collect_from) override {
return reinterpret_cast<leafnode *>(to_collect_from)->data.ival;
}
string left_field_selector(treenode *to_collect_from) override {
return reinterpret_cast<leafnode *>(to_collect_from)->data.sval->str;
}
};
class ArrayIndexCollector : public Collector<ASTNodes, string, treenode *> {
ASTNodes treenodes;
string name;
public:
explicit ArrayIndexCollector(treenode *index_node) : Collector<ASTNodes, string, treenode *>(index_node, treenodes,
TN_INDEX,
name) {
collect();
}
treenode *right_field_selector(treenode *to_collect_from) override {
return to_collect_from;
}
string left_field_selector(treenode *to_collect_from) override {
if (!to_collect_from)
return "";
if (to_collect_from->hdr.type == TN_SELECT) {
string field = reinterpret_cast<leafnode *>(to_collect_from->rnode)->data.sval->str;
bool is_dot = to_collect_from->hdr.tok == DOT;
string op = is_dot ? "." : "->";
if (to_collect_from->lnode && to_collect_from->lnode->hdr.type == TN_SELECT) {
return left_field_selector(to_collect_from->lnode) + op + field;
}
string instance_name = reinterpret_cast<leafnode *>(to_collect_from->lnode)->data.sval->str;
return instance_name + op + field;
} else {
return reinterpret_cast<leafnode *>(to_collect_from)->data.sval->str;
}
}
OrderedNodes get_ordered_nodes() const { return OrderedNodes(treenodes); }
string get_var_name() const { return name; }
};
static bool switch_is_const = false;
static double switch_value = -1;
class LoopBreak : public TreeNode {
static MyStack<string> label_refs;
public:
void gencode(string c_type) override {
if (!switch_is_const) {
const string &last_label = label_refs.top();
cout << "ujp " << last_label << std::endl;
}
}
static void AddLastLabel(const string &end_label) {
label_refs.push(end_label);
}
static void RemoveLastLabel() { label_refs.pop(); }
};
MyStack<string> LoopBreak::label_refs;
class Print : public TreeNode {
public:
explicit Print(treenode *rr_node) : TreeNode(nullptr, obj_tree(rr_node)) {}
void gencode(string c_type) override {
if (son2) son2->gencode("coder");
cout << "print" << endl;
}
};
class For : public TreeNode {
TreeNode *increment, *statement;
static int for_loop_idx;
static int for_end_idx;
public:
For(treenode *init, treenode *cond, treenode *increment, treenode *statement) : TreeNode(obj_tree(init),
obj_tree(cond)),
increment(obj_tree(increment)),
statement(
obj_tree(
statement)) {}
void gencode(string c_type) override {
const string &for_loop_label("for_loop" + to_string(for_loop_idx++));
const string &for_end_label("for_end" + to_string(for_end_idx++));
LoopBreak::AddLastLabel(for_end_label);
son1->gencode(""); // init
cout << for_loop_label + ":" << endl;
son2->gencode("coder"); // check condition
cout << "fjp " + for_end_label << endl;
statement->gencode("coder"); // for body
LoopBreak::RemoveLastLabel(); //if a break was in the loop, it would occur by now.
increment->gencode("coder"); // increment
cout << "ujp " + for_loop_label << endl;
cout << for_end_label + ":" << endl;
}
~For() override {
delete increment;
delete statement;
}
};
int For::for_loop_idx = 0;
int For::for_end_idx = 0;
class While : public TreeNode {
static int _while_loop_label_idx;
static int _while_end_idx;
public:
While(treenode *expression, treenode *statement) : TreeNode(obj_tree(expression),
obj_tree(statement)) {}
void gencode(string c_type) override {
const string &while_loop_label("while_loop" + to_string(_while_loop_label_idx++));
const string &while_end_label("while_end" + to_string(_while_end_idx++));
LoopBreak::AddLastLabel(while_end_label);
cout << while_loop_label + ":" << endl;
son1->gencode("coder");
cout << "fjp " + while_end_label << endl;
son2->gencode("coder");
LoopBreak::RemoveLastLabel(); //if a break was in the loop, it would occur by now.
cout << "ujp " + while_loop_label << endl;
cout << while_end_label + ":" << endl;
}
};
int While::_while_loop_label_idx = 0;
int While::_while_end_idx = 0;
class DoWhile : public TreeNode {
static int _dowhile_loop_label_idx;
public:
DoWhile(treenode *expression, treenode *statement) : TreeNode(obj_tree(expression),
obj_tree(statement)) {}
void gencode(string c_type) override {
const string &dowhile_label("do_while" + to_string(_dowhile_loop_label_idx));
const string dowhile_endlabel("do_while_end" + to_string(_dowhile_loop_label_idx++));
LoopBreak::AddLastLabel(dowhile_endlabel);
cout << dowhile_label + ":" << endl;
son2->gencode("coder"); //do stuff
son1->gencode("coder"); //check whether to continue
LoopBreak::RemoveLastLabel(); //if a break was in the loop, it would occur by now.
cout << "not" << endl; //if expression is true, then convert to false,and we can jump.
cout << "fjp " + dowhile_label << endl; //else just go to next code section.
cout << dowhile_endlabel + ":" << endl;
}
};
int DoWhile::_dowhile_loop_label_idx = 0;
class If : public TreeNode {
static int _if_end_label_idx;
static int _ifelse_else_label_idx;
static int _ifelse_end_label_idx;
public:
TreeNode *_else_do;
If(treenode *cond, treenode *thenDo, treenode *elseDo = nullptr) : TreeNode(obj_tree(cond), obj_tree(thenDo)),
_else_do(obj_tree(elseDo)) {}
~If() override {
delete _else_do;
}
void gencode(string c_type) override {
if (!_else_do) {// simple if case.
if (son1 && son2) {
if (is_constant(son1)) {
if (calculate_value(son1)) {
son2->gencode("coder");
}
} else {
son1->gencode("coder");
const string &ifend_label("if_end" + to_string(_if_end_label_idx++));
cout << "fjp " + ifend_label << endl;
son2->gencode("coder");
cout << ifend_label + ":" << endl;
}
} else {
throw "something wrong with AST node to TreeNode conversion.\n";
}
} else {// if else case.
if (is_constant(son1)) {
if (is_zero_expr(son1)) {
_else_do->gencode("coder");
} else {
son2->gencode("coder");
}
} else {
son1->gencode("coder");
const string &ifelse_else_label("ifelse_else" + to_string(_ifelse_else_label_idx++));
const string &ifelse_end_label("ifelse_end" + to_string(_ifelse_end_label_idx++));
cout << "fjp " + ifelse_else_label << endl;
son2->gencode("coder");
cout << "ujp " + ifelse_end_label << endl;
cout << ifelse_else_label + ":" << endl;
_else_do->gencode("coder");
cout << ifelse_end_label + ":" << endl;
}
}
}
};
int If::_if_end_label_idx = 0;
int If::_ifelse_else_label_idx = 0;
int If::_ifelse_end_label_idx = 0;
class Ternary : public TreeNode {
static int _cond_else_idx;
static int _condLabel_end_idx;
public:
TreeNode *_else_ret;
Ternary(treenode *cond, treenode *then_ret, treenode *otherwise_ret) : TreeNode(obj_tree(cond),
obj_tree(then_ret)),
_else_ret(obj_tree(otherwise_ret)) {}
~Ternary() override {
delete _else_ret;
}
void gencode(string c_type) override {
const string &cond_else_label("cond_else" + to_string(_cond_else_idx++));
const string &cond_end_label("condLabel_end" + to_string(_condLabel_end_idx++));
if (is_constant(son1)) {
if (calculate_value(son1)) {
son2->gencode("coder");
} else {
_else_ret->gencode("coder");
}
} else {
son1->gencode("coder"); // cond check
cout << "fjp " + cond_else_label << endl;
son2->gencode("coder"); // then return expr
cout << "ujp " + cond_end_label << endl;
cout << cond_else_label + ":" << endl; // otherwise return expr
_else_ret->gencode("coder");
cout << cond_end_label + ":" << endl;
}
}
};
int Ternary::_cond_else_idx = 0;
int Ternary::_condLabel_end_idx = 0;
/* Notice that this class expects rhs expressions. */
class BinOp : public TreeNode {
protected:
string _op;
public:
explicit BinOp(const string &pcode_op, treenode *left, treenode *right) : TreeNode(nullptr, nullptr),
_op(pcode_op) {
son1 = obj_tree(left);
son2 = obj_tree(right);
}
const string &get_op() const { return _op; }
void gencode(string c_type) override {
if (is_constant(this)) { // handles the unary ' - ' sign too.
cout << fixed << setprecision(6); // eww but ok?
cout << "ldc " << calculate_value(this) << endl;
return;
} else if (_op == "add" || _op == "or") {
if (_op == "or"){
if ((is_constant(son1) && !is_zero_expr(son1)) || (is_constant(son2) && !is_zero_expr(son2))){
cout << "ldc 1.000000" << endl;
return;
}
}
if (is_constant(son1) && is_zero_expr(son1)) {
son2->gencode("coder");
return;
} else if (is_constant(son2) && is_zero_expr(son2)) {
son1->gencode("coder");
return;
}
} else if (_op == "sub") {
if (is_constant(son1) && is_zero_expr(son1)) {
son2->gencode("coder");
cout << "neg" << endl;
return;
}
if (is_constant(son2) && is_zero_expr(son2)) {
son1->gencode("coder");
return;
}
} else if (_op == "mul" || _op == "and") {
if ((is_constant(son1) && is_zero_expr(son1)) || (is_constant(son2) && is_zero_expr(son2))) {
cout << "ldc 0" << endl;
return;
} else if (is_constant(son1) && calculate_value(son1) == 1) {
son2->gencode("coder");
return;
} else if (is_constant(son2) && calculate_value(son2) == 1) {
son1->gencode("coder");
return;
}
} else if (_op == "div") {
if (is_constant(son2) && calculate_value(son2) == 1) {
son1->gencode("coder");
return;
} else if (is_constant(son1) && is_zero_expr(son1)) {
cout << "ldc 0" << endl;
return;
}
}
if (!son1 && son2) { //only case is when its ' -x '
son2->gencode("coder");
cout << "neg" << endl;
} else {
if (son1 != nullptr) son1->gencode("coder");
if (son2 != nullptr) son2->gencode("coder");
cout << _op << endl;
}
}
};
class AssignBinOp : public BinOp {
public:
explicit AssignBinOp(const string &op, treenode *lnode, treenode *rnode) : BinOp(op, lnode, rnode) {}
void gencode(string c_type) override {
if ((_op == "add" || _op == "sub") && is_constant(son2) && is_zero_expr(son2)) {
return;
} else if ((_op == "div" || _op == "mul") && is_constant(son2) && calculate_value(son2) == 1) {
return;
} else {
if (son1 != nullptr) son1->gencode("codel");
if (_op == "mul" && is_constant(son2) && is_zero_expr(son2)) {
cout << "ldc 0" << endl;
} else
BinOp::gencode("");
cout << "sto" << endl;
}
}
};
/*
* you have to add functions/implement of gencode()... of derived classes
*/
class Assign : public TreeNode {
public:
virtual void gencode(string c_type) {
if (son1 != nullptr) son1->gencode("codel"); //return address
if (son2 != nullptr) son2->gencode("coder"); // return value
cout << "sto" << endl;
}
};
class Index : public TreeNode {
int size_of_basic;
OrderedDims *current_dims;
int _dim_ptr;
string arr_name;
public:
Index() : size_of_basic(0), current_dims(nullptr), _dim_ptr(-1) {}
void gencode(string c_type) override {
son1->gencode("codel");
son2->gencode("coder");
Index *left_node = dynamic_cast<Index *>(son1);
if (left_node) {
// pass its data here...
size_of_basic = left_node->size_of_basic;
current_dims = left_node->current_dims;
_dim_ptr = left_node->_dim_ptr;
arr_name = left_node->arr_name;
}
if (_dim_ptr == -1) {
cout << "ixa " << size_of_basic << endl;
} else {
int dims_mul = (*current_dims)[_dim_ptr];
if (_dim_ptr + 1 != current_dims->size()) {