-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpl0e.cpp
More file actions
3507 lines (3065 loc) · 73.6 KB
/
Copy pathpl0e.cpp
File metadata and controls
3507 lines (3065 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cctype>
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <string>
#include <memory>
#include <vector>
#include <map>
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TargetRegistry.h"
#include "pl0e-jit.h"
#define PAUSE printf("press ENTER key to continue...\n");getchar();while(getchar() != '\n');
//+---------------+
// Helper
//+---------------+
//namespace
using namespace llvm;
using namespace llvm::orc;
//lexer
static int CurTok;
static double NumVal;
static std::string IdentName;
static std::vector<int> Tokens; //collect Tokens
static std::string SourceText; //save source file text
static unsigned LineNum;
enum Token
{
tok_eof = -1 , tok_num = -2 , tok_ident = -3,
//block
tok_int = -11 , tok_double = -12 , tok_void = -13 ,
tok_proc = -14 ,
//stat
tok_call = -21 , tok_begin = -22 , tok_end = -23 ,
tok_if = -24 , tok_then = -25 , tok_else = -26 ,
tok_while = -27 , tok_do = -28 , tok_ret =-29 ,
//op
//+ - * / %
//== != >
//>= < <=
//&& ||
tok_add = -31 , tok_sub = -32 , tok_mul = -33 , tok_div = -40 , tok_rem = -43 ,
tok_equ = -34 , tok_neq = -35 , tok_gth = -36 ,
tok_geq = -37 , tok_lth = -38 , tok_leq = -39 ,
tok_and = -41 , tok_or = -42
};
static int getToken();
static void getNextToken()
{
CurTok=getToken();
Tokens.push_back(CurTok);
}
int getNextChar()
{
int ch;
ch = getchar();
SourceText += ch;
return ch;
}
//class declaration
class ExprAST;
class VarExprAST;
class VariableAST;
class BlockAST;
class PrototypeAST;
class StatAST;
class CallAST;
class FunctionAST;
//operator precedence
static int getTokenPrecedence()
{
switch(CurTok)
{
//logical
case tok_or:
case tok_and:return 5;
//comparation
case tok_equ:
case tok_neq:
case tok_gth:
case tok_geq:
case tok_lth:
case tok_leq:return 10;
//arithmetic
case tok_add:
case tok_sub:return 20;
case tok_rem:return 25;//remainder
case tok_mul:
case tok_div:return 30;
//others
default:return -1;
}
}
//code generation helper
static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);
static std::unique_ptr<Module> TheModule;
static std::map<std::string,AllocaInst*> LocalVarAddr; //local var addr
static std::map<std::string,AllocaInst*> ArgVarAddr; //arg var addr
static BasicBlock* RetBB;
static bool hasRetStat;
Type* Int32Type = Type::getInt32Ty(TheContext);
Type* Int32PtrType = Type::getInt32PtrTy(TheContext);
Type* DoubleType = Type::getDoubleTy(TheContext);
Type* DoublePtrType = Type::getDoublePtrTy(TheContext);
Type* VoidType = Type::getVoidTy(TheContext);
extern "C" void getf(double* var)
{
scanf("%lf",var);
}
extern "C" void geti(int* var)
{
scanf("%d",var);
}
extern "C" void putf(double val)
{
printf("%lf",val);
}
extern "C" void puti(int val)
{
printf("%d",val);
}
extern "C" void putch(char c)
{
printf("%c",c);
}
extern "C" int getrem(int a,int b)
{
return a%b;
}
static void logError(const char*,char);
//log error helper
static void logError(const char* err,char kind)
{
if(kind == 'p')
{
printf("%-70s %s\n","parser error info","line num");
printf("%-70s %s\n","-----------------","--------");
printf("%-70s %d\n\n",err,LineNum);
}
if(kind == 'c')
{
printf("%s\n","codegen error info");
printf("%s\n","------------------");
printf("%s\n\n",err);
}
if(kind == 'g')
{
printf("%s\n","generic error info");
printf("%s\n","------------------");
printf("%s\n\n",err);
}
}
static std::unique_ptr<ExprAST> logErrorE(const char* err)
{
logError(err,'p');
return nullptr;
}
static std::unique_ptr<VarExprAST> logErrorVE(const char* err)
{
logError(err,'p');
return nullptr;
}
static std::unique_ptr<BlockAST> logErrorB(const char* err)
{
logError(err,'p');
return nullptr;
}
static std::unique_ptr<StatAST> logErrorS(const char* err)
{
logError(err,'p');
return nullptr;
}
static std::unique_ptr<CallAST> logErrorC(const char* err)
{
logError(err,'p');
return nullptr;
}
static std::unique_ptr<FunctionAST> logErrorF(const char* err)
{
logError(err,'p');
return nullptr;
}
static std::unique_ptr<VariableAST> logErrorVar(const char* err)
{
logError(err,'p');
return nullptr;
}
static PrototypeAST* logErrorProto(const char* err)
{
logError(err,'p');
return nullptr;
}
static Value* logErrorV(const char* err)
{
logError(err,'c');
return nullptr;
}
static Function* logErrorFunc(const char* err)
{
logError(err,'c');
return nullptr;
}
static AllocaInst* logErrorA(const char* err)
{
logError(err,'c');
return nullptr;
}
static bool logErrorL(const char* err)
{
logError(err,'c');
return false;
}
//JIT support
std::unique_ptr<Pl0JIT> JIT;
//AST
enum BasicType
{
IntT = 1 , DoubleT = 2 , VoidT =3 ,
};
struct VarType
{
BasicType BT;
std::vector<int> DimensionInfo;
};
static std::vector<int> RecPosition; //record positions that need to be print
static int CurPosition = 0; //current print position
void printRecord()
{
int index=0;
for(unsigned i=0 ; i<RecPosition.size() ; i++)
{
for( ; index<CurPosition ; index++)
{
if(index == RecPosition[i])
{
fprintf(stderr,"|");
index++;
break;
}
fprintf(stderr," ");
}
}
while(index++<CurPosition)
fprintf(stderr," ");
}
void printBasicType(int BT)
{
switch(BT)
{
case IntT:
fprintf(stderr," (int)\n");
break;
case DoubleT:
fprintf(stderr," (double)\n");
break;
case VoidT:
fprintf(stderr," (void)\n");
break;
default:
fprintf(stderr," (undefined)\n");
return;
}
}
void printVarType(VarType VT)
{
if(VT.DimensionInfo.size() == 0)
printBasicType(VT.BT);
else
{
std::string BTName;
switch(VT.BT)
{
case IntT:
BTName = "int";
break;
case DoubleT:
BTName = "double";
break;
default:
BTName = "undefined";
break;
}
//save ']' nums
int n = 0;
fprintf(stderr," ");
for(unsigned i = 0 ; i < VT.DimensionInfo.size() ; i++)
{
if(i == VT.DimensionInfo.size()-1)
fprintf(stderr,"[%d x %s]",VT.DimensionInfo[i],BTName.c_str());
else
{
n++;
fprintf(stderr,"[%d x ",VT.DimensionInfo[i]);
}
}
//print ']'
while(n-- > 0)
fprintf(stderr,"]");
fprintf(stderr,"\n");
}
}
void printOperator(int Op)
{
switch(Op)
{
case tok_and:fprintf(stderr,"&&");break;
case tok_or:fprintf(stderr,"||");break;
case tok_add:fprintf(stderr,"+");break;
case tok_sub:fprintf(stderr,"-");break;
case tok_rem:fprintf(stderr,"%c",'%');break;
case tok_mul:fprintf(stderr,"*");break;
case tok_div:fprintf(stderr,"/");break;
case tok_equ:fprintf(stderr,"==");break;
case tok_neq:fprintf(stderr,"!=");break;
case tok_gth:fprintf(stderr,">");break;
case tok_geq:fprintf(stderr,">=");break;
case tok_lth:fprintf(stderr,"<");break;
case tok_leq:fprintf(stderr,"<=");break;
default:fprintf(stderr,"err");break;
}
}
//parser helper
static bool isTypeToken()
{
switch(CurTok)
{
case tok_int:
case tok_double:
case tok_void:
return true;
default:
return false;
}
}
static bool isOpToken()
{
switch(CurTok)
{
//logical
case tok_or:
case tok_and:
//arithmetic
case tok_add:
case tok_sub:
case tok_rem:
case tok_mul:
case tok_div:
//comparation
case tok_equ:
case tok_neq:
case tok_gth:
case tok_geq:
case tok_lth:
case tok_leq:return true;
//others
default:return false;
}
}
struct ParserSymbolTable
{
std::map<std::string,VarType*> GVT; //global
std::map<std::string,VarType*> LVT; //local
std::map<std::string,VarType*> AVT; //argument
//below two used for call checking
std::vector<PrototypeAST*> AvailableFuncs;
PrototypeAST* CurrentFunc;
};
static ParserSymbolTable PST;
//support function
static void addIOSupportFunction()
{
FunctionType* FT;
Function* F;
//getf
FT = FunctionType::get(Type::getVoidTy(TheContext),DoublePtrType,false);
F = Function::Create(FT,Function::ExternalLinkage,"getf",TheModule.get());
if(!F)
return logError("Fail to create getf at addIOSupportFunction()!",'g');
//geti
FT = FunctionType::get(Type::getVoidTy(TheContext),Int32PtrType,false);
F = Function::Create(FT,Function::ExternalLinkage,"geti",TheModule.get());
if(!F)
return logError("Fail to create geti at addIOSupportFunction()!",'g');
//putf
FT = FunctionType::get(Type::getVoidTy(TheContext),DoubleType,false);
F = Function::Create(FT,Function::ExternalLinkage,"putf",TheModule.get());
if(!F)
return logError("Fail to create putf at addIOSupportFunction()!",'g');
//puti
FT = FunctionType::get(Type::getVoidTy(TheContext),Int32Type,false);
F = Function::Create(FT,Function::ExternalLinkage,"puti",TheModule.get());
if(!F)
return logError("Fail to create puti at addIOSupportFunction()!",'g');
//putch
FT = FunctionType::get(Type::getVoidTy(TheContext),Type::getInt8Ty(TheContext),false);
F = Function::Create(FT,Function::ExternalLinkage,"putch",TheModule.get());
if(!F)
return logError("Fail to create putch at addIOSupportFunction()!",'g');
}
static void addMathSupportFunction();
static void addOpSupportFunction()
{
//getrem
FunctionType* FT;
Function* F;
std::vector<Type*> Types(2,Int32Type);
FT = FunctionType::get(Int32Type,Types,false);
F = Function::Create(FT,Function::ExternalLinkage,"getrem",TheModule.get());
if(!F)
return logError("Fail to create getrem at addOpSupportFunction()!",'g');
}
//initialization
static int getToken();
static void initialization()
{
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
TheModule = llvm::make_unique<Module>("llvm module",TheContext);
addIOSupportFunction();
addOpSupportFunction();
addMathSupportFunction();
LineNum = 1;
hasRetStat = false;
getNextToken();
}
//+----------------+
// Lexer
//+----------------+
static int getToken()
{
static int CurChar=' ';
while(isspace(CurChar))
{
if(CurChar == '\n')
LineNum++;
CurChar=getNextChar();
}
//<re> num = [-] digit (digit | '.')*
if(isdigit(CurChar) || CurChar == '-')
{
if(CurChar == '-')
{
if(CurTok==tok_num || CurTok==tok_ident || CurTok == ')' || CurTok == ']' || CurTok == '\'')
{
CurChar=getNextChar();
return tok_sub;
}
}
std::string NumStr;
NumStr+=CurChar;
while(isdigit(CurChar=getNextChar()) || CurChar=='.')
NumStr+=CurChar;
NumVal=strtod(NumStr.c_str(),NULL);
return tok_num;
}
//<re> ident = letter(letter | digit)*
if(isalpha(CurChar))
{
IdentName=CurChar;
while(isalnum(CurChar=getNextChar()))
IdentName+=CurChar;
//block
if(IdentName=="PROCEDURE")
return tok_proc;
if(IdentName=="INT")
return tok_int;
if(IdentName=="DOUBLE")
return tok_double;
if(IdentName=="VOID")
return tok_void;
//stat
if(IdentName=="CALL")
return tok_call;
if(IdentName=="RET")
return tok_ret;
if(IdentName=="BEGIN")
return tok_begin;
if(IdentName=="END")
return tok_end;
if(IdentName=="IF")
return tok_if;
if(IdentName=="THEN")
return tok_then;
if(IdentName=="ELSE")
return tok_else;
if(IdentName=="WHILE")
return tok_while;
if(IdentName=="DO")
return tok_do;
return tok_ident;
}
if(CurChar == '+')
{
CurChar=getNextChar();
return tok_add;
}
if(CurChar == '%')
{
CurChar=getNextChar();
return tok_rem;
}
if(CurChar == '*')
{
CurChar=getNextChar();
return tok_mul;
}
if(CurChar == '/')
{
CurChar=getNextChar();
return tok_div;
}
if(CurChar == '=')
{
CurChar=getNextChar();
if(CurChar == '=')
{
CurChar=getNextChar();
return tok_equ;
}
return '=';
}
if(CurChar == '!')
{
CurChar=getNextChar();
if(CurChar == '=')
{
CurChar=getNextChar();
return tok_neq;
}
return '!';
}
if(CurChar == '>')
{
CurChar=getNextChar();
if(CurChar == '=')
{
CurChar=getNextChar();
return tok_geq;
}
return tok_gth;
}
if(CurChar == '<')
{
CurChar=getNextChar();
if(CurChar == '=')
{
CurChar=getNextChar();
return tok_leq;
}
return tok_lth;
}
if(CurChar == '&')
{
CurChar=getNextChar();
if(CurChar == '&')
{
CurChar=getNextChar();
return tok_and;
}
return '&';
}
if(CurChar == '|')
{
CurChar=getNextChar();
if(CurChar == '|')
{
CurChar=getNextChar();
return tok_or;
}
return '|';
}
if(CurChar=='#')
{
do
{
CurChar=getNextChar();
}while(CurChar!='\n' && CurChar!=EOF);
if(CurChar=='\n')
return getToken();
}
if(CurChar==EOF)
return tok_eof;
int temp=CurChar;
CurChar=getNextChar();
return temp;
}
//+------------+
// AST
//+------------+
//expression AST
class ExprAST
{
private:
int BT;
public:
ExprAST(int BT = -1):BT(BT){}
virtual ~ExprAST()=default;
virtual Value* exprCodegen()=0;
virtual void printAST()=0;
int getType(){return BT;}
void setType(int DestType){BT=DestType;}
};
template <typename T>
class NumExprAST:public ExprAST
{
private:
T Val;
public:
NumExprAST(int BT,T Val):ExprAST(BT),Val(Val){}
virtual Value* exprCodegen();
virtual void printAST();
};
class VarExprAST:public ExprAST
{
private:
std::string Name;
std::vector<std::unique_ptr<ExprAST>> Indexs;
public:
VarExprAST(int BT,std::string Name,std::vector<std::unique_ptr<ExprAST>> Indexs):ExprAST(BT),Name(Name),Indexs(std::move(Indexs)){}
virtual Value* exprCodegen();
Value* exprCodegenPtr();
virtual void printAST();
std::string getName(){return Name;}
};
class ParenExprAST:public ExprAST
{
private:
std::unique_ptr<ExprAST> Val;
public:
ParenExprAST(int BT,std::unique_ptr<ExprAST> Val):ExprAST(BT),Val(std::move(Val)){}
virtual Value* exprCodegen();
virtual void printAST();
};
class BinExprAST:public ExprAST
{
private:
int Op;
std::unique_ptr<ExprAST> LHS,RHS;
public:
BinExprAST(int BT,int Op,std::unique_ptr<ExprAST> LHS,std::unique_ptr<ExprAST> RHS):ExprAST(BT),Op(Op),LHS(std::move(LHS)),RHS(std::move(RHS)){}
virtual Value* exprCodegen();
virtual void printAST();
int getOp(){return Op;}
};
//statement AST
class StatAST
{
public:
virtual ~StatAST()=default;
virtual bool statCodegen()=0;
virtual void printAST()=0;
};
class AssignStatAST:public StatAST
{
private:
std::unique_ptr<VarExprAST> Var;
std::unique_ptr<ExprAST> Val;
public:
AssignStatAST(std::unique_ptr<VarExprAST> Var,std::unique_ptr<ExprAST> Val):Var(std::move(Var)),Val(std::move(Val)){}
virtual bool statCodegen();
virtual void printAST();
};
class CallAST:public StatAST,public ExprAST
{
private:
std::string Callee;
std::vector<std::unique_ptr<ExprAST>> Args;
public:
CallAST(BasicType BT,std::string Callee,std::vector<std::unique_ptr<ExprAST>> Args):ExprAST(BT),Callee(Callee),Args(std::move(Args)){}
virtual bool statCodegen();
virtual Value* exprCodegen();
virtual void printAST();
};
class RetStatAST:public StatAST
{
private:
std::unique_ptr<ExprAST> Val;
public:
RetStatAST(std::unique_ptr<ExprAST> Val):Val(std::move(Val)){}
virtual bool statCodegen();
virtual void printAST();
};
class IfStatAST:public StatAST
{
private:
std::unique_ptr<ExprAST> CondExpr;
std::unique_ptr<StatAST> ThenStat,ElseStat;
public:
IfStatAST(std::unique_ptr<ExprAST> CondExpr,std::unique_ptr<StatAST> ThenStat,std::unique_ptr<StatAST> ElseStat = nullptr):CondExpr(std::move(CondExpr)),ThenStat(std::move(ThenStat)),ElseStat(std::move(ElseStat)){}
virtual bool statCodegen();
virtual void printAST();
};
class WhileStatAST:public StatAST
{
private:
std::unique_ptr<ExprAST> Cond;
std::unique_ptr<StatAST> Stat;
public:
WhileStatAST(std::unique_ptr<ExprAST> Cond,std::unique_ptr<StatAST> Stat):Cond(std::move(Cond)),Stat(std::move(Stat)){}
virtual bool statCodegen();
virtual void printAST();
};
class InputStatAST:public StatAST
{
private:
std::unique_ptr<VarExprAST> Var;
public:
InputStatAST(std::unique_ptr<VarExprAST> Var):Var(std::move(Var)){}
virtual bool statCodegen();
virtual void printAST();
};
class OutputStatAST:public StatAST
{
private:
std::unique_ptr<VarExprAST> Var;
char Char;
public:
OutputStatAST(std::unique_ptr<VarExprAST> Var,char Char):Var(std::move(Var)),Char(Char){}
virtual bool statCodegen();
virtual void printAST();
};
class MultiStatAST:public StatAST
{
private:
std::vector<std::unique_ptr<StatAST>> Stats;
public:
MultiStatAST(std::vector<std::unique_ptr<StatAST>> Stats):Stats(std::move(Stats)){}
virtual bool statCodegen();
virtual void printAST();
};
class PrototypeAST
{
private:
BasicType RetType;
std::string Name;
std::vector<std::unique_ptr<VariableAST>> Args;
public:
PrototypeAST(BasicType RetType,std::string Name,std::vector<std::unique_ptr<VariableAST>> Args):RetType(RetType),Name(Name),Args(std::move(Args)){}
Function* codegen();
void printAST();
std::vector<std::unique_ptr<VariableAST>>& getArgs(){return Args;}
BasicType getRetType(){return RetType;}
std::string getName(){return Name;}
};
class FunctionAST
{
private:
PrototypeAST* Proto;
std::unique_ptr<BlockAST> Block;
public:
FunctionAST(PrototypeAST* Proto,std::unique_ptr<BlockAST> Block):Proto(Proto),Block(std::move(Block)){}
~FunctionAST(){delete Proto;}
bool codegen();
void printAST();
};
class VariableAST
{
private:
std::string Name;
VarType VT;
public:
VariableAST(std::string Name,VarType VT):Name(Name),VT(VT){}
AllocaInst* codegenLocal();
AllocaInst* codegenArg();
Value* codegenGlobal();
void printAST();
std::string getName(){return Name;}
BasicType getBasicType(){return VT.BT;}
};
class BlockAST
{
private:
std::vector<std::unique_ptr<VariableAST>> Vars;
std::vector<std::unique_ptr<FunctionAST>> Funcs;
std::unique_ptr<StatAST> Stat;
public:
BlockAST(std::vector<std::unique_ptr<VariableAST>> Vars,std::vector<std::unique_ptr<FunctionAST>> Funcs,std::unique_ptr<StatAST> Stat):Vars(std::move(Vars)),Funcs(std::move(Funcs)),Stat(std::move(Stat)){}
bool codegen();
bool codegenP(); //codegen for program block that uses global var
void printAST();
};
/* add math support function */
static void addMathSupportFunction()
{
FunctionType* FT;
Function* F;
std::vector<std::unique_ptr<VariableAST>> Vars;
VarType VT;
//sqrt
FT = FunctionType::get(DoubleType,DoubleType,false);
F = Function::Create(FT,Function::ExternalLinkage,"sqrt",TheModule.get());
if(!F)
return logError("Fail to create sqrt at addMathSupportFunction()!",'g');
//add to available funcs table
VT.BT = DoubleT;
Vars.push_back(llvm::make_unique<VariableAST>("",VT));
PST.AvailableFuncs.push_back(new PrototypeAST(DoubleT,"sqrt",std::move(Vars)));
}
//implement print AST
//expr
template <typename T>
void NumExprAST<T>::printAST()
{
int BT = getType();
switch(BT)
{
case IntT:
if(Val<0)
fprintf(stderr,"(%d)",(int)Val);
else
fprintf(stderr,"%d",(int)Val);
printBasicType(BT);
break;
case DoubleT:
if(Val<0)
fprintf(stderr,"(%lf)",(double)Val);
else
fprintf(stderr,"%lf",(double)Val);
printBasicType(BT);
break;
default:
fprintf(stderr,"undefined type val\n");
return;
}
}
void VarExprAST::printAST()
{
fprintf(stderr,"%s",Name.c_str());
printBasicType(getType());
for(unsigned i=0; i<Indexs.size(); i++)
{
if(i == Indexs.size()-1)
{
printRecord();
fprintf(stderr,"\\---[]\n");
CurPosition += 4;
printRecord();
fprintf(stderr,"\\---");
CurPosition += 4;
Indexs[i]->printAST();
CurPosition -= 4;
CurPosition -= 4;
}
else
{
printRecord();
fprintf(stderr,"+---[]\n");
RecPosition.push_back(CurPosition);
CurPosition += 4;
printRecord();
fprintf(stderr,"\\---");
CurPosition += 4;
Indexs[i]->printAST();
CurPosition -= 4;
CurPosition -= 4;
RecPosition.pop_back();
}
}
}
void ParenExprAST::printAST()
{
fprintf(stderr,"()");
printBasicType(getType());
printRecord();
fprintf(stderr,"\\---");
CurPosition+=4;
Val->printAST();
CurPosition-=4;
}
void BinExprAST::printAST()
{
fprintf(stderr,"\"");
printOperator(getOp());
fprintf(stderr,"\"");
printBasicType(getType());
printRecord();
fprintf(stderr,"+---");
RecPosition.push_back(CurPosition);
CurPosition+=4;
LHS->printAST();
CurPosition-=4;
RecPosition.pop_back();
printRecord();
fprintf(stderr,"|\n");
printRecord();
fprintf(stderr,"\\---");
CurPosition+=4;
RHS->printAST();
CurPosition-=4;
}
//stat print AST
void InputStatAST::printAST()
{
fprintf(stderr,"\"?\"\n");
printRecord();
fprintf(stderr,"\\---");
CurPosition += 4;
Var->printAST();
CurPosition -= 4;
}
void OutputStatAST::printAST()
{
fprintf(stderr,"\"!\"\n");
printRecord();
fprintf(stderr,"\\---");
CurPosition += 4;
if(Var)
Var->printAST();
else
fprintf(stderr,"%d\n",(int)Char);
CurPosition -= 4;
}
void CallAST::printAST()
{
fprintf(stderr,"call\n");
printRecord();
fprintf(stderr,"+---callee\n");
RecPosition.push_back(CurPosition);
CurPosition += 4;