-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantics.cpp
More file actions
3336 lines (3182 loc) · 119 KB
/
Copy pathsemantics.cpp
File metadata and controls
3336 lines (3182 loc) · 119 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 "semantics.hpp"
//#include "SymbolTable.hpp"
#include "check.hpp"
#include <assert.h>
#include <stack>
namespace semantics
{
int is_if;
vector<int> condition; //根据if条件设置该变量
vector<int> cur_condition; //通过比较该值和上面的值判断是否修改执行栈的动作
vector<llvm::BasicBlock *> block;
int is_while;
int iscall; //为1时处于调用阶段,constantid不入栈
int depth; // 记录语义层次,只有为0时才做语义动作
int type_declaration; // 若该值为1,则表示当前处于type字段的record中,此时进入var_declaration不进行语义动作
int var_record; // 若该值为1,说明当前正在var字段的record中,此时进入var_declaration会将数据保存到栈顶符号(必是一个record型变量)的数据域中
// int var_para;//若该值为1,说明当前节点的父节点是
SymbolTable stack_st; // 开始语义分析之前,创建栈式符号表
std::unique_ptr<llvm::LLVMContext> context; // llvm需要用的context智能指针
std::unique_ptr<llvm::Module> mod; // 同上
std::unique_ptr<llvm::IRBuilder<>> builder;
llvm::TargetMachine *theTargetMachine;
vector<string> exp_type;
vector<string> exp_value; // 该值仅是给人和符号表看的,在计算时不要用直接用这里的值
vector<llvm::Value *> llvm_value; // llvm_value 保存 llvm 形式的值,当需要值的时候,可以取出来;保存时,可能需要用到 CreateLoad 等 api
vector<int> index; //存放数组下标
int is_assign; //为1时表示数组或记录在赋值号左侧,为2时表示在赋值号右侧
int cur_range; //当前数组的维度
vector<int> arr_index; //保存数组的下标
int arr_or_rec; // 0表示都不是,1表示是数组,2表示记录
string id; //当数组和记录在右侧时,保存他们的名字
string record_id; //记录内元素的名字
int id_varparts_num; //记录当前是否是数组访问的最后一维
vector<string> r_type;
bool pass; //为1时是引用传参
bool is_array_access; //为true时表示当前数字或字符是数组下标,不需要入exp_value的栈
// struct record_elements r_ele;
}
void semanticsListener::enterProgram(PascalSParser::ProgramContext *ctx)
{
// 初始化命名空间的相关数据
semantics::depth = 0;
semantics::iscall = 0;
semantics::type_declaration = 0;
semantics::var_record = 0;
semantics::is_assign = 0;
semantics::index.push_back(0);
semantics::cur_range = 0;
semantics::pass = false;
semantics::id_varparts_num = 0;
semantics::is_array_access = false;
// 初始化llvm以及设置目标机器
llvm::InitializeNativeTarget();
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
llvm::InitializeAllAsmPrinters();
// 初始化context以及module
semantics::context = std::make_unique<llvm::LLVMContext>();
semantics::mod = std::make_unique<llvm::Module>("main", *semantics::context);
// 获取目标三元组并设置
auto targetTriple = llvm::sys::getDefaultTargetTriple();
semantics::mod->setTargetTriple(targetTriple);
// 获取目标机数据类型并设置
std::string targetError;
auto target = llvm::TargetRegistry::lookupTarget(targetTriple, targetError);
auto cpu = "generic";
auto features = "";
llvm::TargetOptions options;
auto relocationModel = llvm::Reloc::Model::PIC_;
// auto theTargetMachine = target->createTargetMachine(targetTriple, cpu, features, options, relocationModel);
semantics::theTargetMachine = target->createTargetMachine(targetTriple, cpu, features, options, relocationModel);
// semantics::mod->setDataLayout(theTargetMachine->createDataLayout());
semantics::mod->setDataLayout(semantics::theTargetMachine->createDataLayout());
// 创建 printf 函数
llvm::SmallVector<llvm::Type *, 1> args;
args.push_back(llvm::Type::getInt8PtrTy(*semantics::context));
auto printfType = llvm::FunctionType::get(llvm::Type::getInt32Ty(*semantics::context), args, true);
auto printfFunction = llvm::Function::Create(printfType, llvm::Function::ExternalLinkage, "printf", semantics::mod.get());
// 创建 scanf 函数
llvm::SmallVector<llvm::Type *, 1> args_out;
args_out.push_back(llvm::Type::getInt8PtrTy(*semantics::context));
auto scanfType = llvm::FunctionType::get(llvm::Type::getInt32Ty(*semantics::context), args_out, true);
auto scanfFunction = llvm::Function::Create(scanfType, llvm::Function::ExternalLinkage, "scanf", semantics::mod.get());
}
void semanticsListener::enterProgram_head(PascalSParser::Program_headContext *ctx)
{
// 进入主程序,为主程序创建符号
std::string id = ctx->ID()->getText();
table symbol(id, "main"); // 主程序类型用main标识
// llvm创建主程序以及builder
symbol.functiontype = llvm::FunctionType::get(llvm::Type::getInt32Ty(*semantics::context), false);
symbol.function = llvm::Function::Create(symbol.functiontype, llvm::GlobalValue::ExternalLinkage, id, semantics::mod.get());
symbol.block = llvm::BasicBlock::Create(*semantics::context, "", symbol.function);
semantics::builder = std::make_unique<llvm::IRBuilder<>>(symbol.block);
// 主程序入栈
semantics::stack_st.insert_table(symbol);
}
void semanticsListener::enterSingleConstDeclaration(PascalSParser::SingleConstDeclarationContext *ctx)
{
// 若声明的深度不为0,则直接跳过语义动作
if (semantics::depth != 0)
return;
// 常量声明
std::string const_id = ctx->ID()->getText();
// cout<<"here is: "<<const_id<<endl;
std::string const_value = ctx->const_variable()->getText();
std::string type = type_of(const_value);
if ("integer" == type)
{
// 常量类型为整形
table symbol(const_id, "integer", const_value);
symbol.is_const = true;
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
// 获取值
auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), atoi(const_value.c_str()));
// 将值存入该常量的分配空间中
semantics::builder->CreateStore(value, symbol.all);
// 符号入栈
semantics::stack_st.insert_table(symbol);
}
else if ("real" == type)
{
// 常量类型为浮点
table symbol(const_id, "real", const_value);
symbol.is_const = true;
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
// 获取浮点值
auto value = llvm::ConstantFP::get(llvm::Type::getFloatTy(*semantics::context), atof(const_value.c_str()));
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if ("char" == type)
{
// 常量类型为字符
table symbol(const_id, "char", const_value);
symbol.is_const = true;
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt8Ty(*semantics::context), const_value[1]);
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if ("id" == type)
{
// 当类型为id时,实际上需要将符号表中的指定符号中的属性复制一份过来
auto target_symbol = semantics::stack_st.locate_table(const_value);
if ("err" == target_symbol.type)
{
// 返回的符号类型是err时表示没有找到该符号
std::cout << "Line " << ctx->getStart()->getLine() << ": Undeclared symbol" << std::endl;
return;
}
else
{
// 常量如果赋值为标识符,那么该标识符不能是函数、过程、type或结构体这种没有value属性的
if (target_symbol.is_func or target_symbol.is_proc or target_symbol.is_type or target_symbol.is_record)
{
std::cout << "Line " << ctx->getStart()->getLine() << ": Illegal expression" << std::endl;
return;
}
table symbol(const_id, target_symbol.type, target_symbol.value);
symbol.is_const = true;
if ("integer" == target_symbol.type)
{
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
llvm::ConstantInt *value;
if ('-' == const_value[0])
value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), -atoi(target_symbol.value.c_str()));
else
value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), atoi(target_symbol.value.c_str()));
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if ("real" == target_symbol.type)
{
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
llvm::Constant *value;
if ('-' == const_value[0])
value = llvm::ConstantFP::get(llvm::Type::getFloatTy(*semantics::context), -atof(target_symbol.value.c_str()));
else
value = llvm::ConstantFP::get(llvm::Type::getFloatTy(*semantics::context), atof(target_symbol.value.c_str()));
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if ("char" == target_symbol.type)
{
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
if ('-' == const_value[0])
{
std::cout << "Line " << ctx->getStart()->getLine() << ": Illegal expression" << std::endl;
return;
}
auto value = llvm::ConstantInt::get(llvm::Type::getInt8Ty(*semantics::context), target_symbol.value[1]);
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
}
}
}
void semanticsListener::enterSingleTypeDeclaration(PascalSParser::SingleTypeDeclarationContext *ctx)
{
if (semantics::depth != 0)
return;
semantics::type_declaration = 1;
// type 字段声明的标识符不需要实际空间,故不用调用llvm api
std::string type_id = ctx->ID()->getText();
std::string type_value = ctx->type()->getText();
// 对于记录型和数组型,保存其等效的类型为value,之后在var部分若遇到该符号表示的类型,则用value替换
if (0 == type_value.find("record"))
{
// 当前type为记录型
table symbol(type_id, "record", type_value);
symbol.is_type = true;
semantics::stack_st.insert_table(symbol);
}
else if (0 == type_value.find("array"))
{
// 当前type为数组型
table symbol(type_id, "array", type_value);
symbol.is_type = true;
semantics::stack_st.insert_table(symbol);
}
else
{
// 当前type为基础类型
table symbol(type_id, type_value, type_value);
symbol.is_type = true;
semantics::stack_st.insert_table(symbol);
}
}
void semanticsListener::exitSingleTypeDeclaration(PascalSParser::SingleTypeDeclarationContext *ctx)
{
semantics::type_declaration = 0;
}
void semanticsListener::enterSingleVarDeclaration(PascalSParser::SingleVarDeclarationContext *ctx)
{
if (semantics::depth != 0 or semantics::type_declaration == 1)
return;
std::string id_list = ctx->identifier_list()->getText(); // 改变量是以逗号为分割的若干标识符
std::string var_type = ctx->type()->getText();
int split_pos;
std::string id;
// 如果var_record开关是打开的,表示当前处于var字段的record中的变量声明
if (1 == semantics::var_record)
{
do
{
split_pos = id_list.find(',');
id = id_list.substr(0, split_pos); // 提取出每个单独的id
id.erase(0, id.find_first_not_of(" ")); // 去除前空格
id.erase(id.find_last_not_of(" ") + 1); // 去除后空格
table &symbol = semantics::stack_st.get_top_table();
assert(true == symbol.is_record); // 从栈顶取出来的符号必然是一个record型变量
struct record_elements element;
if ("integer" == var_type)
{
element.type = "integer";
element.value = "0";
element.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), 0);
semantics::builder->CreateStore(value, element.all);
}
else if ("real" == var_type)
{
element.type = "real";
element.value = "0.0";
element.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
auto value = llvm::ConstantFP::get(llvm::Type::getFloatTy(*semantics::context), 0.0);
semantics::builder->CreateStore(value, element.all);
}
else if ("char" == var_type)
{
element.type = "char";
element.value = "\0";
element.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt8Ty(*semantics::context), 0);
semantics::builder->CreateStore(value, element.all);
}
else if ("boolean" == var_type)
{
element.type = "boolean";
element.value = "false";
element.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), 0);
semantics::builder->CreateStore(value, element.all);
}
else if (0 == var_type.find("array"))
{
// 这里的处理与后面对array符号的处理是基本一致的,但是类型不同,且不会入栈
element.is_array = true;
std::string array_type = ctx->type()->type()->getText();
std::string array_range = ctx->type()->periods()->getText();
element.type = array_type;
// 接下来需要处理数组的维度,每一维度用逗号区分
std::string period; // period 表示每一维度的范围
std::string range_begin, range_end; // 表示每一维的起止符号
int range_split;
do
{
range_split = array_range.find(',');
period = array_range.substr(0, range_split);
range_begin = period.substr(0, period.find(".."));
range_end = period.substr(period.find("..") + 2);
// 去除begin和end前后的空白字符
range_begin.erase(0, range_begin.find_first_not_of(" "));
range_end.erase(0, range_end.find_first_not_of(" "));
range_begin.erase(range_begin.find_last_not_of(" ") + 1);
range_end.erase(range_end.find_last_not_of(" ") + 1);
if ("integer" == type_of(range_begin) and "integer" == type_of(range_end))
{
// 范围必须是整数型,且 end 大于 begin
int begin = atoi(range_begin.c_str());
int end = atoi(range_end.c_str());
if (begin <= end)
{
element.range_type.push_back("integer");
element.range.push_back(std::pair<int, int>(begin, end - begin + 1));
}
else
{
std::cout << "Line " << ctx->getStart()->getLine() << ": Unreasonable array range" << std::endl;
}
}
else if ("char" == type_of(range_begin) and "char" == type_of(range_end))
{
// 范围由单字符组成
if (range_end[1] >= range_begin[1])
{
element.range_type.push_back("char");
element.range.push_back(std::pair<int, int>(range_begin[1], range_end[1] - range_begin[1] + 1));
}
else
{
std::cout << "Line " << ctx->getStart()->getLine() << ": Unreasonable array range" << std::endl;
}
}
else
{
// 除了单字符和整数表示,其余的场景是无效的字符范围
std::cout << "Line " << ctx->getStart()->getLine() << ": Unreasonable array range" << std::endl;
}
array_range = array_range.substr(range_split + 1);
} while (std::string::npos != range_split);
// 处理完每一维度的之后,要为数组分配总空间
int range = 1;
for (auto iter = element.range.begin(); iter != element.range.end(); iter++)
{
range *= iter->second;
}
// int range = (element.range.end() - 1)->second;
if ("integer" == array_type)
{
element.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(*semantics::context), range), nullptr));
}
else if ("char" == array_type)
{
element.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt8Ty(*semantics::context), range), nullptr));
}
else if ("real" == array_type)
{
element.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getFloatTy(*semantics::context), range), nullptr));
}
else if ("boolean" == array_type)
{
element.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(*semantics::context), range), nullptr));
}
else
{
// 目前该项目仅支持基础基础类型的数组
std::cout << "Line " << ctx->getStart()->getLine() << ": Unsupported array type" << std::endl;
}
}
symbol.push_record_elements(id, element);
id_list = id_list.substr(split_pos + 1); // 将处理后的id剔除出去
} while (std::string::npos != split_pos);
return; //结束后直接返回,后续动作是针对普通的变量声明的
}
do
{
split_pos = id_list.find(',');
id = id_list.substr(0, split_pos); // 提取出每个单独的id
id.erase(0, id.find_first_not_of(" ")); // 去除前空格
id.erase(id.find_last_not_of(" ") + 1); // 去除后空格
// 对每个id,都要建立相应的符号并入栈
if ("integer" == var_type)
{
table symbol(id, "integer", "0");
// 分配空间后将默认初始化的值放入空间当中
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), 0);
semantics::builder->CreateStore(value, symbol.all);
// 符号入栈
semantics::stack_st.insert_table(symbol);
}
else if ("real" == var_type)
{
table symbol(id, "real", "0");
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
auto value = llvm::ConstantFP::get(llvm::Type::getFloatTy(*semantics::context), 0.0);
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if ("char" == var_type)
{
table symbol(id, "char", "\0");
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt8Ty(*semantics::context), 0);
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if ("boolean" == var_type)
{
// 对布尔值,看作是整形,并以0为false,非0为true
table symbol(id, "boolean", "false");
symbol.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), 0);
semantics::builder->CreateStore(value, symbol.all);
semantics::stack_st.insert_table(symbol);
}
else if (0 == var_type.find("record"))
{
table symbol(id, "record", "record");
// 对于一个 record 来说,在当前规则中只能先将该符号入栈
// record里面的变量以及 llvm 能做的事必须要到 record_body 中才能做
symbol.is_record = true;
semantics::stack_st.insert_table(symbol);
}
else if (0 == var_type.find("array"))
{
std::string array_type = ctx->type()->type()->getText();
std::string array_range = ctx->type()->periods()->getText();
table symbol(id, array_type, array_type);
// cout<<"arr:"<<array_type<<endl;
symbol.is_array = true;
// 接下来需要处理数组的维度,每一维度用逗号区分
std::string period; // period 表示每一维度的范围
std::string range_begin, range_end; // 表示每一维的起止符号
int range_split;
do
{
range_split = array_range.find(',');
period = array_range.substr(0, range_split);
range_begin = period.substr(0, period.find(".."));
range_end = period.substr(period.find("..") + 2);
// 去除begin和end前后的空白字符
range_begin.erase(0, range_begin.find_first_not_of(" "));
range_end.erase(0, range_end.find_first_not_of(" "));
range_begin.erase(range_begin.find_last_not_of(" ") + 1);
range_end.erase(range_end.find_last_not_of(" ") + 1);
if ("integer" == type_of(range_begin) and "integer" == type_of(range_end))
{
// 范围必须是整数型,且 end 大于 begin
int begin = atoi(range_begin.c_str());
int end = atoi(range_end.c_str());
if (begin <= end)
{
symbol.range_type.push_back("integer");
symbol.range.push_back(std::pair<int, int>(begin, end - begin + 1));
}
else
{
std::cout << "Line " << ctx->getStart()->getLine() << ": Unreasonable array range" << std::endl;
}
}
else if ("char" == type_of(range_begin) and "char" == type_of(range_end))
{
// 范围由单字符组成
if (range_end[1] >= range_begin[1])
{
symbol.range_type.push_back("char");
symbol.range.push_back(std::pair<int, int>(range_begin[1], range_end[1] - range_begin[1] + 1));
}
else
{
std::cout << "Line " << ctx->getStart()->getLine() << ": Unreasonable array range" << std::endl;
}
}
else
{
// 除了单字符和整数表示,其余的场景是无效的字符范围
std::cout << "Line " << ctx->getStart()->getLine() << ": Unreasonable array range" << std::endl;
}
array_range = array_range.substr(range_split + 1);
} while (std::string::npos != range_split);
// 处理完所有维度的范围之后,要为数组分配总空间
int range = 1;
for (auto iter = symbol.range.begin(); iter != symbol.range.end(); iter++)
{
range *= iter->second;
}
// int range = (symbol.range.end() - 1)->second;
symbol.arr_len = range;
if ("integer" == array_type)
{
symbol.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(*semantics::context), range), nullptr));
}
else if ("char" == array_type)
{
symbol.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt8Ty(*semantics::context), range), nullptr));
}
else if ("real" == array_type)
{
symbol.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getFloatTy(*semantics::context), range), nullptr));
}
else if ("boolean" == array_type)
{
symbol.all_item.push_back(semantics::builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(*semantics::context), range), nullptr));
}
else
{
// 目前该项目仅支持基础基础类型的数组
std::cout << "Line " << ctx->getStart()->getLine() << ": Unsupported array type" << std::endl;
}
semantics::stack_st.insert_table(symbol);
}
id_list = id_list.substr(split_pos + 1); // 将处理后的id剔除出去
} while (std::string::npos != split_pos);
}
void semanticsListener::exitProgram(PascalSParser::ProgramContext *ctx)
{
semantics::builder->CreateRet(llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), 0));
// 输出汇编文件
std::error_code errorCode;
std::string filename = "main.s"; // 汇编文件名
llvm::raw_fd_ostream dest(filename, errorCode, llvm::sys::fs::OF_None);
llvm::legacy::PassManager pass;
llvm::CodeGenFileType type = llvm::CGFT_AssemblyFile; // 文件类型为汇编
// llvm::CodeGenFileType type = llvm::CGFT_ObjectFile; // 文件类型为可执行文件
semantics::theTargetMachine->addPassesToEmitFile(pass, dest, nullptr, type);
pass.run(*semantics::mod);
dest.flush();
semantics::mod->print(llvm::outs(), nullptr); // 打印ir
}
void semanticsListener::exitProgram_body(PascalSParser::Program_bodyContext *ctx)
{
//semantics::stack_st.pint_table();
if (0 != semantics::depth)
semantics::depth--;
}
void semanticsListener::enterRecord_body(PascalSParser::Record_bodyContext *ctx)
{
if (1 == semantics::type_declaration)
return;
// 如果这不是在type字段的record,就一定是在var字段的,要将var_record开关打开
semantics::var_record = 1;
}
void semanticsListener::exitRecord_body(PascalSParser::Record_bodyContext *ctx)
{
if (1 == semantics::var_record)
semantics::var_record = 0;
}
void semanticsListener::exitSubprogram_declaration(PascalSParser::Subprogram_declarationContext *ctx)
{
if (semantics::depth != 0)
return;
table &temp = semantics::stack_st.get_top_table();
temp.ctx = ctx->program_body();
}
void semanticsListener::exitFunctionDeclaration(PascalSParser::FunctionDeclarationContext *ctx)
{
// 从子程序的声明头出来的时候,意味着即将进入子程序的声明体
// 但是在声明这里我们是对子程序的程序体不做语义动作的,通过semantics::depth来控制是否跳过
semantics::depth++;
}
void semanticsListener::exitProcedureDeclaration(PascalSParser::ProcedureDeclarationContext *ctx)
{
// 同上
semantics::depth++;
}
void semanticsListener::enterSubprogram_declaration(PascalSParser::Subprogram_declarationContext *ctx)
{
// semantics::depth = 0;
}
void semanticsListener::enterProgram_body(PascalSParser::Program_bodyContext *ctx)
{
return;
}
void semanticsListener::enterFunctionDeclaration(PascalSParser::FunctionDeclarationContext *ctx)
{
if (semantics::depth != 0)
return;
string name = ctx->ID()->getText(); /*
cout<<"DECLARE: "<<name<<endl; */
string return_type = ctx->standard_type()->getText();
table func(name, return_type, 1, 0);
semantics::stack_st.insert_table(func);
}
void semanticsListener::enterProcedureDeclaration(PascalSParser::ProcedureDeclarationContext *ctx)
{
if (semantics::depth != 0)
return;
string name = ctx->ID()->getText();
table func(name, "", 0, 1);
semantics::stack_st.insert_table(func);
}
void semanticsListener::enterVarPara(PascalSParser::VarParaContext *ctx)
{
if (semantics::depth != 0)
return;
semantics::pass = true;
table &temp = semantics::stack_st.get_top_table();
string para_type = ctx->var_parameter()->value_parameter()->standard_type()->getText();
if ("real" != para_type && "integer" != para_type && "boolean" != para_type && "char" != para_type)
{
cout << "Line: " << ctx->getStart()->getLine() << " Wrong type of arguments (" << ctx->getText() << ")\n";
return;
}
string paralist = ctx->var_parameter()->value_parameter()->identifier_list()->getText();
// cout<<para_type<<endl<<paralist<<endl;
string paralist_2 = paralist + ",";
int i = paralist_2.find(',');
while (string::npos != i)
{
string temppara = paralist_2.substr(0, i);
struct Argument arg(temppara, para_type, true);
temp.push_argument(arg);
paralist_2 = paralist_2.substr(i + 1, paralist_2.size());
i = paralist_2.find(',');
}
}
void semanticsListener::exitVarPara(PascalSParser::VarParaContext *ctx)
{
if (semantics::depth != 0)
return;
semantics::pass = false;
}
void semanticsListener::enterValuePara(PascalSParser::ValueParaContext *ctx)
{
if (semantics::depth != 0)
return;
if (semantics::pass)
return;
table &temp = semantics::stack_st.get_top_table();
string para_type = ctx->value_parameter()->standard_type()->getText();
if ("real" != para_type && "integer" != para_type && "boolean" != para_type && "char" != para_type)
{
cout << "Line: " << ctx->getStart()->getLine() << " Wrong type of arguments (" << ctx->getText() << ")\n";
return;
}
string paralist = ctx->value_parameter()->identifier_list()->getText();
string paralist_2 = paralist + ",";
int i = paralist_2.find(',');
while (string::npos != i)
{
string temppara = paralist_2.substr(0, i);
struct Argument arg(temppara, para_type, false);
temp.push_argument(arg);
paralist_2 = paralist_2.substr(i + 1, paralist_2.size());
i = paralist_2.find(',');
}
}
void semanticsListener::enterAssign(PascalSParser::AssignContext *ctx)
{
if (semantics::depth != 0)
return;
semantics::is_assign = 1;
string var_name = ctx->variable()->ID()->getText();
table &temp = semantics::stack_st.locate_table(var_name);
if ("err" == temp.type)
{
cout << "Line: " << ctx->variable()->getStart()->getLine() << " No declaration of " << var_name << endl;
return;
}
if (temp.is_const)
{
cout << "Line: " << ctx->variable()->getStart()->getLine() << " cannot change the value of the constant " << var_name << endl;
return;
}
}
void semanticsListener::exitAssign(PascalSParser::AssignContext *ctx)
{
if (semantics::depth != 0)
return;
string var_name = ctx->variable()->ID()->getText();
table &temp = semantics::stack_st.locate_table(var_name);
/* 普通变量的赋值 */
if (0 == ctx->variable()->id_varparts()->getText().size())
{
/* 非函数的赋值 */
if (!temp.is_func && !temp.is_proc)
{
if (temp.type != semantics::exp_type.back() && !("real" == temp.type && "integer" == semantics::exp_type.back()))
{
cout << "Line:" << ctx->variable()->getStart()->getLine() << " Cannot assign values to variables of different types" << endl;
semantics::exp_type.pop_back();
semantics::exp_type.pop_back();
}
else
{
if ("integer" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
}
/* real型可以兼容integer */
if ("integer" == temp.type)
{
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
}
else if ("real" == temp.type)
{
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
}
temp.value = semantics::exp_value.back();
}
else if ("char" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
}
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
temp.value = semantics::exp_value.back();
}
else if ("real" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
}
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
temp.value = semantics::exp_value.back();
}
else if ("boolean" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
}
// auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), b);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
temp.value = semantics::exp_value.back();
}
semantics::llvm_value.pop_back();
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
}
}
/* 函数返回值的赋值 */
else if (temp.is_func && temp.name == var_name)
{
/* cout<<"TEMP: "<<temp.name<<" TYPE: "<<temp.type<<endl;
cout<<"FUNCTION "<<semantics::exp_type.size()<<endl;
cout<<"TYPE: "<<semantics::exp_type.back()<<" VALUE: "<<semantics::exp_value.back()<<endl; */
if (temp.type != semantics::exp_type.back() && !("real" == temp.type && "integer" == semantics::exp_type.back()))
{
cout << "Line:" << ctx->variable()->getStart()->getLine() << " Cannot assign values to variables of different types" << endl;
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
semantics::llvm_value.pop_back();
}
else
{
if ("integer" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
}
/* real型可以兼容integer */
if ("integer" == temp.type)
{
// int integer = atoi(semantics::exp_value.back().c_str());
// cout<<"int:"<<integer<<endl;
// auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), integer);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
}
else if ("real" == temp.type)
{
// int integer = atoi(semantics::exp_value.back().c_str());
// auto value = llvm::ConstantInt::get(llvm::Type::getFloatTy(*semantics::context), integer);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
}
temp.value = semantics::exp_value.back();
}
else if ("char" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
}
// char ch = atoi(semantics::exp_value.back().c_str());
// cout << "ch:" << ch << endl;
// auto value = llvm::ConstantInt::get(llvm::Type::getInt8Ty(*semantics::context), ch);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
temp.value = semantics::exp_value.back();
}
else if ("real" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
}
// double real = atof(semantics::exp_value.back().c_str());
// auto value = llvm::ConstantInt::get(llvm::Type::getFloatTy(*semantics::context), real);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
temp.value = semantics::exp_value.back();
}
else if ("boolean" == semantics::exp_type.back())
{
if (NULL == temp.all)
{
temp.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
}
// auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), b);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp.all);
temp.value = semantics::exp_value.back();
}
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
semantics::llvm_value.pop_back();
}
}
/* 函数参数的赋值,指引用,因为传值的参数会建立新的符号表,当作变量赋值即可 */
else if (temp.is_arg)
{
temp.is_arg = false;
int loc = 0;
for (int i = 0; i < temp.arguments_num; i++)
{
if (var_name == temp.arguments[i].name)
{
loc = temp.arguments[i].location;
break;
}
}
table &temp2 = semantics::stack_st.get_var_table(loc);
if (temp2.type != semantics::exp_type.back() && !("real" == temp2.type && "integer" == semantics::exp_type.back()))
{
cout << "Line:" << ctx->variable()->getStart()->getLine() << " Cannot assign values to variables of different types:" << loc << endl;
semantics::exp_type.pop_back();
semantics::exp_type.pop_back();
return;
}
else
{
if ("integer" == semantics::exp_type.back())
{
if (NULL == temp2.all)
{
temp2.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
}
if ("integer" == temp2.type)
{
// int integer = atoi(semantics::exp_value.back().c_str());
// auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), integer);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp2.all);
}
else if ("real" == temp2.type)
{
// int integer = atoi(semantics::exp_value.back().c_str());
// auto value = llvm::ConstantInt::get(llvm::Type::getFloatTy(*semantics::context), integer);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp2.all);
}
/* int integer = atoi(semantics::exp_value.back().c_str());
auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), integer);
semantics::builder->CreateStore(value, temp.all); */
temp2.value = semantics::exp_value.back();
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
semantics::llvm_value.pop_back();
}
else if ("char" == semantics::exp_type.back())
{
if (NULL == temp2.all)
{
temp2.all = semantics::builder->CreateAlloca(llvm::Type::getInt8Ty(*semantics::context), nullptr);
}
// char ch = atoi(semantics::exp_value.back().c_str());
// cout << "ch:" << ch << endl;
// auto value = llvm::ConstantInt::get(llvm::Type::getInt8Ty(*semantics::context), ch);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp2.all);
temp2.value = semantics::exp_value.back();
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
semantics::llvm_value.pop_back();
}
else if ("real" == semantics::exp_type.back())
{
if (NULL == temp2.all)
{
temp2.all = semantics::builder->CreateAlloca(llvm::Type::getFloatTy(*semantics::context), nullptr);
}
// double real = atof(semantics::exp_value.back().c_str());
// auto value = llvm::ConstantInt::get(llvm::Type::getFloatTy(*semantics::context), real);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp2.all);
temp2.value = semantics::exp_value.back();
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
semantics::llvm_value.pop_back();
}
else if ("boolean" == semantics::exp_type.back())
{
if (NULL == temp2.all)
{
temp2.all = semantics::builder->CreateAlloca(llvm::Type::getInt32Ty(*semantics::context), nullptr);
}
// auto value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*semantics::context), b);
semantics::builder->CreateStore(semantics::llvm_value.back(), temp2.all);
temp2.value = semantics::exp_value.back();
semantics::exp_type.pop_back();
semantics::exp_value.pop_back();
semantics::llvm_value.pop_back();
}
}
semantics::cur_range = 0;
return;
}
/* 过程没有返回值,报错 */
else
{
cout << "line:" << ctx->getStart()->getLine() << " Procedure has no return value!\n";
return;
}
}
/* 数组和记录的赋值 */
else
{
if (temp.is_array)
{
/* 数组型变量 */
string list = ctx->variable()->id_varparts()->getText();
vector<int> periods;
int i = list.find('[');
while (string::npos != i)
{
list = list.replace(i, 1, ",");
i = list.find('[');
}
i = list.find(']');
while (string::npos != i)
{
list = list.replace(i, 1, ",");
i = list.find(']');
}
i = list.find(",,");
while (string::npos != i)
{