diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..4c3514c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,39 @@ +project(SysYCompiler) + +cmake_minimum_required(VERSION 3.5) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -Wall -g -pedantic") + +# include generated files in project environment +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/ASTBuilder) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/ASTPrinter) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/ErrorReporter) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/Grammar) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/SysYIR) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/SysYBuilder) + +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/ASTBuilder) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/ASTPrinter) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/ErrorReporter) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/Grammar) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/SysYIR) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/SysYBuilder) + +add_executable( + SysYCompiler + ${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp +) + +target_link_libraries( + SysYCompiler + SysYBuilder + IRLib + Driver + ASTPrinter + ErrReporter +) diff --git a/README.md b/README.md index 3f01bda..3889d3f 100644 --- a/README.md +++ b/README.md @@ -1 +1,116 @@ - Init README.md \ No newline at end of file +# PW6 实验文档 +本实验由黄庄湫、吴毓辰助教设计 +- [PW6 实验文档](#pw6-实验文档) + - [0. 前言](#0-前言) + - [主要工作](#主要工作) + - [1. 实验要求](#1-实验要求) + - [1.1 目录结构](#11-目录结构) + - [1.2 提交要求和评分标准](#12-提交要求和评分标准) +## 0. 前言 + +本次实验分为3关,前2关是个人实验,第3关为组队实验。**本次实验请务必使用git提交**。 +本次实验的目的是让大家熟悉生成中间代码所需要的相关知识: LLVM IR、 SysY IR(LLVM IR的轻量级C++接口),并实际实现一个IR Builder。 +在开始实验之前,请确保LLVM的版本不低于10.0.1,且PATH环境变量配置正确。可以通过`lli --version`命令是否可以输出10.0.1的版本信息来验证。 + +### 主要工作 + +1. 第一部分: 了解LLVM IR。通过clang生成的.ll,了解LLVM IR与c代码的对应关系。相应文档见[phase1.md](./doc/phase1.md) +2. 第二部分: 了解SysY IR。通过助教提供的c++例子,了解SysY IR的c++接口及实现。相应文档见[phase2.md](./doc/phase2.md) +3. 第三部分: 使用SysY IR,实现一个IR Builder,使其可以通过抽象语法树生成LLVM兼容的IR代码。相应文档见[phase3.md](./doc/phase3.md) +4. 实验报告:在[report.md](./report.md)中撰写报告。 + +## 1. 实验要求 + +### 1.1 目录结构 +除了下面指明你所要修改或提交的文件,其他文件请勿修改。 +``` log +. +├── CMakeLists.txt +├── README.md <- PW6实验文档说明(你在这里) +├── contribution.md <- PW6所需提交的组员贡献(队长提交即可) +├── report.md <- PW6所需提交的实验报告 +├── doc +│   ├── AST.md +│   ├── phase1.md +│   ├── phase2.md +│   ├── phase3.md +| └── SysYIR.md <- SysY IR 相关文档 +├── include <- 实验所需的头文件 +│   ├── ... +│   └── SysYIR +├── src +│   ├── ... +│   ├── SysYIR +│   └── SysYBuilder +| ├── CMakeLists.txt +| └── SysYBuilder.cpp <- 第三部分你需要修改的文件 +└── SysYF_Student + ├── CMakeLists.txt + ├── SysYF_Task1 + | ├── student_ll <- PW6所需提交的.ll目录(第一部分) + | | ├── assign_hand.ll + |   │   ├── fun_hand.ll + |   │   ├── if_hand.ll + |   │   └── while_hand.ll + | ├── student_sy + | | ├── assign.sy + |   │   ├── fun.sy + |   │   ├── if.sy + |   │   └── while.sy + | └── ta_demo + |      └── go_upstairs.c + ├── SysYF_Task2 + | ├── student_cpp <- PW6所需提交的.cpp目录(第二部分) + | | ├── CMakeLists.txt + | | ├── assign_gen.cpp + |   │   ├── fun_gen.cpp + |   │   ├── if_gen.cpp + |   │   └── while_gen.cpp + | ├── student_sy + | | ├── assign.sy + |   │   ├── fun.sy + |   │   ├── if.sy + |   │   └── while.sy + | └── ta_demo + |      |── CMakeLists.txt + |      |── go_upstairs.sy + |      └── go_upstairs_gen.cpp <- 助教提供的打印go_upstairs.ll的cpp + └── SysYF_Task3 + └── Test_H + ├── test_H.py <- PW6第三部分评测脚本 + └── Easy_H <- 测试样例文件夹 +``` + +### 1.2 提交要求和评分标准 +* 提交要求 + 本实验的提交要求分为两部分: 实验部分的文件和报告。 + * 实验部分: + * 需要完成 `./SysYF_Student/SysYF_Task1/student_ll`目录下的4个文件 + * 需要完成 `./SysYF_Student/SysYF_Task2/student_cpp`目录下的4个文件 + * 需要完成 `./src/SysYBuilder/SysYBuilder.cpp` + * 需要在 `./report.md` 中撰写实验报告 + * 实验报告内容包括: + * 实验要求、问题回答、实验设计、实验难点及解决方案、实验总结、实验反馈、组间交流(具体参考[report.md](./report.md)) + * 本次实验报告**参与**评分标准. + * 提交规范: + * 不破坏目录结构(`report.md`如果需要放图片,请放在`./report_figs/`下) + * 不上传临时文件(凡是自动生成的文件和临时文件请不要上传) +* **组队实验要求** + * 由队长在 `contribution.md` 中解释每位队员的贡献,并说明贡献比例 + * 组队实验意味着合作,但是小组间的交流是受限的,且**严格禁止**代码的共享。除此之外,如果小组和其它组进行了交流,必须在 `report.md` 中记录交流的小组和你们之间交流内容 +* 评分标准: 本次实验分为3部分, 请注意前两部分为个人实验, 第三部分为组队实验, 个人实验需要各自完成, 组队实验的代码和报告我们只检查组长的仓库 + * **禁止执行恶意代码,违者本次实验0分处理** + * 第一部分10分: `.ll`运行结果正确(1个2分, 注释共2分) + * 第二部分20分: `.cpp`运行结果正确(1个5分) + * 第三部分70分: 该部分成绩由5部分组成(团队代码得分, 实验报告得分, 迟交天数, 组员贡献比, 组长奖励加分) +* 实验检查 + * 线上: 助教会在educoder上检查前两部分, 该部分是每个人需要独自完成的 + * 线下: 线下检查只检查第三部分, 组长带组员到负责组长的助教处检查 +* 迟交规定 + * 迟交需要邮件通知助教: + * 邮箱: huangzq@mail.ustc.edu.cn + * 邮件主题: PW6迟交-学号 + * 内容: 包括迟交原因、最后版本commitID、迟交时间等 +* 关于抄袭和雷同 + 经过助教和老师判定属于作业抄袭或雷同情况,所有参与方一律零分,不接受任何解释和反驳。 +如有任何问题,欢迎提issue进行批判指正。 diff --git a/SysYF_Student/SysYF_Task1/student_ll/assign_hand.ll b/SysYF_Student/SysYF_Task1/student_ll/assign_hand.ll new file mode 100644 index 0000000..e69de29 diff --git a/SysYF_Student/SysYF_Task1/student_ll/func_hand.ll b/SysYF_Student/SysYF_Task1/student_ll/func_hand.ll new file mode 100644 index 0000000..e69de29 diff --git a/SysYF_Student/SysYF_Task1/student_ll/if_hand.ll b/SysYF_Student/SysYF_Task1/student_ll/if_hand.ll new file mode 100644 index 0000000..e69de29 diff --git a/SysYF_Student/SysYF_Task1/student_ll/while_hand.ll b/SysYF_Student/SysYF_Task1/student_ll/while_hand.ll new file mode 100644 index 0000000..e69de29 diff --git a/SysYF_Student/SysYF_Task1/student_sy/assign_test.sy b/SysYF_Student/SysYF_Task1/student_sy/assign_test.sy new file mode 100644 index 0000000..87e3097 --- /dev/null +++ b/SysYF_Student/SysYF_Task1/student_sy/assign_test.sy @@ -0,0 +1,6 @@ +int main(){ + float b = 1.8; + int a[2] = {2}; + a[1] = a[0] * b; + return a[1]; +} diff --git a/SysYF_Student/SysYF_Task1/student_sy/func_test.sy b/SysYF_Student/SysYF_Task1/student_sy/func_test.sy new file mode 100644 index 0000000..5f752e2 --- /dev/null +++ b/SysYF_Student/SysYF_Task1/student_sy/func_test.sy @@ -0,0 +1,12 @@ +int a,b,c; + +int add(int a,int b){ + c=a+b; + return (c-1); +} + +int main(){ + a=3; + b=2; + return c + add(a,b); +} diff --git a/SysYF_Student/SysYF_Task1/student_sy/if_test.sy b/SysYF_Student/SysYF_Task1/student_sy/if_test.sy new file mode 100644 index 0000000..5fbc540 --- /dev/null +++ b/SysYF_Student/SysYF_Task1/student_sy/if_test.sy @@ -0,0 +1,9 @@ +int a; + +int main(){ + a = 10; + if( a>0 ){ + return a; + } + return 0; +} diff --git a/SysYF_Student/SysYF_Task1/student_sy/while_test.sy b/SysYF_Student/SysYF_Task1/student_sy/while_test.sy new file mode 100644 index 0000000..374f82d --- /dev/null +++ b/SysYF_Student/SysYF_Task1/student_sy/while_test.sy @@ -0,0 +1,11 @@ +int a; +int b; +int main(){ + b=0; + a=3; + while(a>0){ + b = b+a; + a = a-1; + } + return b; +} diff --git a/SysYF_Student/SysYF_Task1/ta_demo/go_upstairs.c b/SysYF_Student/SysYF_Task1/ta_demo/go_upstairs.c new file mode 100644 index 0000000..e9176e9 --- /dev/null +++ b/SysYF_Student/SysYF_Task1/ta_demo/go_upstairs.c @@ -0,0 +1,28 @@ +int num[2] = {4, 8}; +int x[1]; +int n; +int tmp = 1; + +int climbStairs(int n) { + if(n < 4) + return n; + int dp[10]; + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + int i; + i = 3; + while(i0 ){ + return a; + } + return 0; +} diff --git a/SysYF_Student/SysYF_Task2/student_sy/while_test.sy b/SysYF_Student/SysYF_Task2/student_sy/while_test.sy new file mode 100644 index 0000000..374f82d --- /dev/null +++ b/SysYF_Student/SysYF_Task2/student_sy/while_test.sy @@ -0,0 +1,11 @@ +int a; +int b; +int main(){ + b=0; + a=3; + while(a>0){ + b = b+a; + a = a-1; + } + return b; +} diff --git a/SysYF_Student/SysYF_Task2/ta_demo/CMakeLists.txt b/SysYF_Student/SysYF_Task2/ta_demo/CMakeLists.txt new file mode 100644 index 0000000..8a83a7a --- /dev/null +++ b/SysYF_Student/SysYF_Task2/ta_demo/CMakeLists.txt @@ -0,0 +1,8 @@ +add_executable( + go_upstairs_generator + go_upstairs_gen.cpp +) +target_link_libraries( + go_upstairs_generator + IRLib +) diff --git a/SysYF_Student/SysYF_Task2/ta_demo/go_upstairs.sy b/SysYF_Student/SysYF_Task2/ta_demo/go_upstairs.sy new file mode 100644 index 0000000..e9176e9 --- /dev/null +++ b/SysYF_Student/SysYF_Task2/ta_demo/go_upstairs.sy @@ -0,0 +1,28 @@ +int num[2] = {4, 8}; +int x[1]; +int n; +int tmp = 1; + +int climbStairs(int n) { + if(n < 4) + return n; + int dp[10]; + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + int i; + i = 3; + while(i +#include + +#ifdef DEBUG // 用于调试信息,大家可以在编译过程中通过" -DDEBUG"来开启这一选项 +#define DEBUG_OUTPUT std::cout << __LINE__ << std::endl; // 输出行号的简单示例 +#else +#define DEBUG_OUTPUT +#endif + +#define CONST_INT(num) \ + ConstantInt::get(num, module) + +#define CONST_FP(num) \ + ConstantFP::get(num, module) // 得到常数值的表示,方便后面多次用到 + +int main() { + auto module = new Module("SysY code"); // module name是什么无关紧要 + auto builder = new IRBuilder(nullptr, module); + Type *Int32Type = Type::get_int32_type(module); + + // 全局数组,num,x + auto *arrayType_num = ArrayType::get(Int32Type, 2); + auto *arrayType_x = ArrayType::get(Int32Type, 1); + auto zero_initializer = ConstantZero::get(Int32Type, module); + std::vector init_val; + init_val.push_back(CONST_INT(4)); + init_val.push_back(CONST_INT(8)); + auto num_initializer = ConstantArray::get(arrayType_num, init_val); + auto num = GlobalVariable::create("num", module, arrayType_num, false, num_initializer);// 是否是常量定义,初始化常量(ConstantZero类) + auto x = GlobalVariable::create("x", module, arrayType_x, false, zero_initializer);// 参数解释: 名字name,所属module,全局变量类型type, + + auto n = GlobalVariable::create("n", module, Int32Type, false, zero_initializer); + auto tmp = GlobalVariable::create("tmp", module, Int32Type, false, CONST_INT(1)); + + // climbStairs函数 + // 函数参数类型的vector + std::vector Ints(1, Int32Type); + + //通过返回值类型与参数类型列表得到函数类型 + auto climbStairsFunTy = FunctionType::get(Int32Type, Ints); + + // 由函数类型得到函数 + auto climbStairsFun = Function::create(climbStairsFunTy, + "climbStairs", module); + + // BB的名字在生成中无所谓,但是可以方便阅读 + auto bb = BasicBlock::create(module, "entry", climbStairsFun); + + builder->set_insert_point(bb); // 一个BB的开始,将当前插入指令点的位置设在bb + + auto retAlloca = builder->create_alloca(Int32Type); // 在内存中分配返回值的位置 + auto nAlloca = builder->create_alloca(Int32Type); // 在内存中分配参数n的位置 + + std::vector args; // 获取climbStairs函数的形参,通过Function中的iterator + for (auto arg = climbStairsFun->arg_begin(); arg != climbStairsFun->arg_end(); arg++) { + args.push_back(*arg); // * 号运算符是从迭代器中取出迭代器当前指向的元素 + } + + builder->create_store(args[0], nAlloca); // store参数n + + auto retBB = BasicBlock::create( + module, "", climbStairsFun); // return分支,提前create,以便true分支可以br + + auto nLoad = builder->create_load(nAlloca); // 将参数n load上来 + auto icmp = builder->create_icmp_lt(nLoad, CONST_INT(4)); // n和4的比较,注意ICMPLT + + auto trueBB = BasicBlock::create(module, "trueBB_if", climbStairsFun); // true分支 + auto falseBB = BasicBlock::create(module, "falseBB_if", climbStairsFun); // false分支 + + builder->create_cond_br(icmp, trueBB, falseBB); // 条件BR + DEBUG_OUTPUT // 我调试的时候故意留下来的,以醒目地提醒你这个调试用的宏定义方法 + builder->set_insert_point(trueBB); // if true; 分支的开始需要SetInsertPoint设置 + nLoad = builder->create_load(nAlloca); + builder->create_store(nLoad, retAlloca); + builder->create_br(retBB); // br retBB + + builder->set_insert_point(falseBB); // if false + auto *arrayType_dp = ArrayType::get(Int32Type, 10); + auto dpAlloca = builder->create_alloca(arrayType_dp); + + auto dp0Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(0)}); + builder->create_store(CONST_INT(0), dp0Gep); + + auto dp1Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(1)}); + builder->create_store(CONST_INT(1), dp1Gep); + + auto dp2Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(2)}); + builder->create_store(CONST_INT(2), dp2Gep); + + auto iAlloca = builder->create_alloca(Int32Type); + builder->create_store(CONST_INT(3), iAlloca); + + auto condBB = BasicBlock::create(module, "condBB_while", climbStairsFun); // 条件BB + trueBB = BasicBlock::create(module, "trueBB_while", climbStairsFun); // true分支 + falseBB = BasicBlock::create(module, "falseBB_while", climbStairsFun); // false分支 + + builder->create_br(condBB); + + builder->set_insert_point(condBB); + + auto iLoad = builder->create_load(iAlloca); + nLoad = builder->create_load(nAlloca); + auto add = builder->create_iadd(nLoad, CONST_INT(1)); + + icmp = builder->create_icmp_lt(iLoad, add); + builder->create_cond_br(icmp, trueBB, falseBB); + + builder->set_insert_point(trueBB); + + iLoad = builder->create_load(iAlloca); + auto sub = builder->create_isub(iLoad, CONST_INT(1)); + auto dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), sub}); + auto dp1Load = builder->create_load(dpGep); + + iLoad = builder->create_load(iAlloca); + sub = builder->create_isub(iLoad, CONST_INT(2)); + dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), sub}); + auto dp2Load = builder->create_load(dpGep); + + add = builder->create_iadd(dp1Load, dp2Load); + iLoad = builder->create_load(iAlloca); + dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), iLoad}); + builder->create_store(add, dpGep); + + iLoad = builder->create_load(iAlloca); + add = builder->create_iadd(iLoad, CONST_INT(1)); + builder->create_store(add, iAlloca); + + builder->create_br(condBB); + + builder->set_insert_point(falseBB); + nLoad = builder->create_load(nAlloca); + dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), nLoad}); + auto dpLoad = builder->create_load(dpGep); + builder->create_store(dpLoad, retAlloca); + builder->create_br(retBB); + + builder->set_insert_point(retBB); // ret分支 + auto retLoad = builder->create_load(retAlloca); + builder->create_ret(retLoad); + + // main函数 + auto mainFun = Function::create(FunctionType::get(Int32Type, {}), + "main", module); + bb = BasicBlock::create(module, "entry", mainFun); + // BasicBlock的名字在生成中无所谓,但是可以方便阅读 + builder->set_insert_point(bb); + + retAlloca = builder->create_alloca(Int32Type); + auto resAlloca = builder->create_alloca(Int32Type); + + auto num0Gep = builder->create_gep(num, {CONST_INT(0), CONST_INT(0)}); // GEP: 这里为什么是{0, 0}呢? (实验报告相关) + auto num0Load = builder->create_load(num0Gep); + builder->create_store(num0Load, n); + + auto tmpLoad = builder->create_load(tmp); + auto numGep = builder->create_gep(num, {CONST_INT(0), tmpLoad}); + auto numLoad = builder->create_load(numGep); + auto x0Gep = builder->create_gep(x, {CONST_INT(0), CONST_INT(0)}); + builder->create_store(numLoad, x0Gep); + + nLoad = builder->create_load(n); + tmpLoad = builder->create_load(tmp); + add = builder->create_iadd(nLoad, tmpLoad); + auto call = builder->create_call(climbStairsFun, {add}); // 为什么这里传的是{add}呢? + builder->create_store(call, resAlloca); + + auto resLoad = builder->create_load(resAlloca); + x0Gep = builder->create_gep(x, {CONST_INT(0), CONST_INT(0)}); + auto x0Load = builder->create_load(x0Gep); + sub = builder->create_isub(resLoad, x0Load); + builder->create_store(sub, retAlloca); + retLoad = builder->create_load(retAlloca); + builder->create_ret(retLoad); + // 给这么多注释了,但是可能你们还是会弄很多bug + // 所以强烈建议配置AutoComplete,效率会大大提高! + // 别人配了AutoComplete,只花1小时coding + // 你没有配AutoComplete,找method花5小时,debug花5小时,肯定哭唧唧! + // 最后,如果猜不到某个IR指令对应的C++的函数,建议把指令翻译成英语然后在method列表中搜索一下 + // 最后的最后,这个例子只涉及到了一点基本的指令生成, + // 对于额外的指令,包括数组,在之后的实验中可能需要大家好好搜索一下思考一下, + // 还有涉及到的C++语法,可以在gitlab上发issue提问或者向大家提供指导 + // 对于这个例子里的代码风格/用法,如果有好的建议也欢迎提出! + std::cout << module->print(); + delete module; + return 0; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/01_main.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/01_main.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/01_main.out @@ -0,0 +1 @@ +0 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/01_main.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/01_main.sy new file mode 100644 index 0000000..ade4548 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/01_main.sy @@ -0,0 +1,3 @@ +int main(){ + return 0; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/02_var_defn.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/02_var_defn.out new file mode 100644 index 0000000..f04c001 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/02_var_defn.out @@ -0,0 +1 @@ +29 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/02_var_defn.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/02_var_defn.sy new file mode 100644 index 0000000..d0d0f2c --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/02_var_defn.sy @@ -0,0 +1,8 @@ +int a,b; + +int main(){ + a=10; + b=5; + int c=a*2+b*1.1+3.6; + return c; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/03_empty_stmt.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/03_empty_stmt.out new file mode 100644 index 0000000..aabe6ec --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/03_empty_stmt.out @@ -0,0 +1 @@ +21 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/03_empty_stmt.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/03_empty_stmt.sy new file mode 100644 index 0000000..a8c161f --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/03_empty_stmt.sy @@ -0,0 +1,5 @@ +int main() { + int a = 10; + ; + return a * 2 + 1; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/04_arr_defn.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/04_arr_defn.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/04_arr_defn.out @@ -0,0 +1 @@ +0 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/04_arr_defn.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/04_arr_defn.sy new file mode 100644 index 0000000..0fa1ceb --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/04_arr_defn.sy @@ -0,0 +1,4 @@ +int a[10]; +int main(){ + return 0; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/05_arr_assign.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/05_arr_assign.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/05_arr_assign.out @@ -0,0 +1 @@ +0 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/05_arr_assign.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/05_arr_assign.sy new file mode 100644 index 0000000..3fe56ba --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/05_arr_assign.sy @@ -0,0 +1,5 @@ +int a[10]; +int main(){ + a[0]=1; + return 0; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/06_const_defn.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/06_const_defn.out new file mode 100644 index 0000000..b8626c4 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/06_const_defn.out @@ -0,0 +1 @@ +4 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/06_const_defn.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/06_const_defn.sy new file mode 100644 index 0000000..6804194 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/06_const_defn.sy @@ -0,0 +1,5 @@ +const int x=4; + +int main(){ + return x; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/07_const_array_defn.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/07_const_array_defn.out new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/07_const_array_defn.out @@ -0,0 +1 @@ +8 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/07_const_array_defn.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/07_const_array_defn.sy new file mode 100644 index 0000000..0ae4d90 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/07_const_array_defn.sy @@ -0,0 +1,7 @@ +const int a[5]={0,1,2,3,4}; +const int b = 3; +float c = a[b + 1]; + +int main(){ + return a[4] + c; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/08_var_defn_func.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/08_var_defn_func.out new file mode 100644 index 0000000..b8626c4 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/08_var_defn_func.out @@ -0,0 +1 @@ +4 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/08_var_defn_func.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/08_var_defn_func.sy new file mode 100644 index 0000000..03ab608 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/08_var_defn_func.sy @@ -0,0 +1,8 @@ +int defn(){ + return 4; +} + +int main(){ + int a=defn(); + return a; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/09_void_func.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/09_void_func.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/09_void_func.out @@ -0,0 +1 @@ +5 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/09_void_func.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/09_void_func.sy new file mode 100644 index 0000000..2799e1e --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/09_void_func.sy @@ -0,0 +1,13 @@ +int a,b,c; + +void add(int a,int b){ + c=a+b; + return; +} + +int main(){ + a=3; + b=2; + add(a,b); + return c; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/10_if.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/10_if.out new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/10_if.out @@ -0,0 +1 @@ +1 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/10_if.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/10_if.sy new file mode 100644 index 0000000..a908d63 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/10_if.sy @@ -0,0 +1,9 @@ +int a; + +int main(){ + a = 10; + if( a>0 ){ + return 1; + } + return 0; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/11_if_else.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/11_if_else.out new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/11_if_else.out @@ -0,0 +1 @@ +1 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/11_if_else.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/11_if_else.sy new file mode 100644 index 0000000..a4f5062 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/11_if_else.sy @@ -0,0 +1,10 @@ +int a; +int main(){ + a = 10; + if( a>0 ){ + return 1; + } + else{ + return 0; + } +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/12_while.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/12_while.out new file mode 100644 index 0000000..1e8b314 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/12_while.out @@ -0,0 +1 @@ +6 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/12_while.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/12_while.sy new file mode 100644 index 0000000..374f82d --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/12_while.sy @@ -0,0 +1,11 @@ +int a; +int b; +int main(){ + b=0; + a=3; + while(a>0){ + b = b+a; + a = a-1; + } + return b; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/13_break.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/13_break.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/13_break.out @@ -0,0 +1 @@ +5 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/13_break.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/13_break.sy new file mode 100644 index 0000000..55b40dc --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/13_break.sy @@ -0,0 +1,9 @@ +int main(){ + int a=10; + while(a>0){ + a=a-1; + if(a==5) + break; + } + return a; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/14_continue.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/14_continue.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/14_continue.out @@ -0,0 +1 @@ +5 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/14_continue.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/14_continue.sy new file mode 100644 index 0000000..d0f9e50 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/14_continue.sy @@ -0,0 +1,11 @@ +int main(){ + int a=10; + while(a>0){ + if(a>5){ + a=a-1; + continue; + } + return a; + } + return a; +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.in b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.in new file mode 100644 index 0000000..f599e28 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.in @@ -0,0 +1 @@ +10 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.out new file mode 100644 index 0000000..f599e28 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.out @@ -0,0 +1 @@ +10 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.sy new file mode 100644 index 0000000..5a7c254 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/15_getint.sy @@ -0,0 +1,5 @@ +int main(){ + int a; + a = getint(); + return a; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/16_func_test.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/16_func_test.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/16_func_test.out @@ -0,0 +1 @@ +5 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/16_func_test.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/16_func_test.sy new file mode 100644 index 0000000..67645a3 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/16_func_test.sy @@ -0,0 +1,23 @@ +int a; + +int myFunc(int a, int b, int c) { + a = 2; + { + int c; + c = 0; + if (c != 0) { + return 0; + } + } + while (b > 0) { + b = b - 1; + } + return (a)+(b); +} + +int main() { + a = (3); + int b; + b = myFunc(1, 2, 1); + return ((a+b)); +} \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.in b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.in new file mode 100644 index 0000000..bce4388 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.in @@ -0,0 +1 @@ +3 2 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.out @@ -0,0 +1 @@ +0 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.sy new file mode 100644 index 0000000..1453cdb --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/17_equal.sy @@ -0,0 +1,12 @@ +int a; +int b; +int main(){ + a = getint(); + b = getint(); + if ( a == b ){ + return 1; + } + else{ + return 0; + } +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/18_scope.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/18_scope.out new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/18_scope.out @@ -0,0 +1 @@ +8 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/18_scope.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/18_scope.sy new file mode 100644 index 0000000..afc6d97 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/18_scope.sy @@ -0,0 +1,17 @@ +const int a = 5; +int b; + +int my_sum(int x, float y){ + b = a + x - y; + return b; +} + +int main(){ + int a = 7; + { + const float a = 3.3; + my_sum(a, a); + } + my_sum(a, b); + return b; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.in b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.in new file mode 100644 index 0000000..4271cf2 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.in @@ -0,0 +1,2 @@ +4 +20 \ No newline at end of file diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.out b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.out new file mode 100644 index 0000000..b8626c4 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.out @@ -0,0 +1 @@ +4 diff --git a/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.sy b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.sy new file mode 100644 index 0000000..1d20bc5 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/Easy_H/19_gcd.sy @@ -0,0 +1,34 @@ +int n; + +int gcd(int m,int n) +{ + int t; + int r; + + if(m 0) { + hanoi(getint(), 1, 2, 3); + putch(10); + n = n - 1; + } + return 0; +} diff --git a/SysYF_Student/SysYF_Task3/Test_H/test_H.py b/SysYF_Student/SysYF_Task3/Test_H/test_H.py new file mode 100644 index 0000000..cd89867 --- /dev/null +++ b/SysYF_Student/SysYF_Task3/Test_H/test_H.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +import subprocess +import os + +IRBuild_ptn = '"{}" "-emit-ir" "-o" "{}" "{}"' +ExeGen_ptn = '"clang" "{}" "-o" "{}" "{}" "../../../lib/lib.c"' +Exe_ptn = '"{}"' + +def eval(EXE_PATH, TEST_BASE_PATH, optimization): + print('===========TEST START===========') + print('now in {}'.format(TEST_BASE_PATH)) + dir_succ = True + for case in testcases: + print('Case %s:' % case, end='') + TEST_PATH = TEST_BASE_PATH + case + SY_PATH = TEST_BASE_PATH + case + '.sy' + LL_PATH = TEST_BASE_PATH + case + '.ll' + INPUT_PATH = TEST_BASE_PATH + case + '.in' + OUTPUT_PATH = TEST_BASE_PATH + case + '.out' + need_input = testcases[case] + + IRBuild_result = subprocess.run(IRBuild_ptn.format(EXE_PATH, LL_PATH, SY_PATH), shell=True, stderr=subprocess.PIPE) + if IRBuild_result.returncode == 0: + input_option = None + if need_input: + with open(INPUT_PATH, "rb") as fin: + input_option = fin.read() + + try: + subprocess.run(ExeGen_ptn.format(optimization, TEST_PATH, LL_PATH), shell=True, stderr=subprocess.PIPE) + result = subprocess.run(Exe_ptn.format(TEST_PATH), shell=True, input=input_option, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out = result.stdout.split(b'\n') + if result.returncode != b'': + out.append(str(result.returncode).encode()) + for i in range(len(out)-1, -1, -1): + out[i] = out[i].strip(b'\r') + if out[i] == b'': + out.remove(b'') + case_succ = True + with open(OUTPUT_PATH, "rb") as fout: + i = 0 + for line in fout.readlines(): + line = line.strip(b'\r').strip(b'\n') + if line == '': + continue + if out[i] != line: + dir_succ = False + case_succ = False + i = i + 1 + if case_succ: + print('\t\033[32mPass\033[0m') + else: + print('\t\033[31mWrong Answer\033[0m') + except Exception as _: + dir_succ = False + print(_, end='') + print('\t\033[31mCodeGen or CodeExecute Fail\033[0m') + finally: + subprocess.call(["rm", "-rf", TEST_PATH, TEST_PATH]) + subprocess.call(["rm", "-rf", TEST_PATH, TEST_PATH + ".o"]) + subprocess.call(["rm", "-rf", TEST_PATH, TEST_PATH + ".ll"]) + + else: + dir_succ = False + print('\t\033[31mIRBuild Fail\033[0m') + if dir_succ: + print('\t\033[32mSuccess\033[0m in dir {}'.format(TEST_BASE_PATH)) + else: + print('\t\033[31mFail\033[0m in dir {}'.format(TEST_BASE_PATH)) + + print('============TEST END============') + + +if __name__ == "__main__": + + # you can only modify this to add your testcase + TEST_DIRS = [ + './Easy_H/', + ] + # you can only modify this to add your testcase + + optimization = "-O0" # -O0 -O1 -O2 -O3 -O4(currently = -O3) -Ofast + for TEST_BASE_PATH in TEST_DIRS: + testcases = {} # { name: need_input } + EXE_PATH = os.path.abspath('../../../build/SysYCompiler') + testcase_list = list(map(lambda x: x.split('.'), os.listdir(TEST_BASE_PATH))) + testcase_list.sort() + for i in range(len(testcase_list)-1, -1, -1): + if len(testcase_list[i]) == 1: + testcase_list.remove(testcase_list[i]) + for i in range(len(testcase_list)): + testcases[testcase_list[i][0]] = False + for i in range(len(testcase_list)): + testcases[testcase_list[i][0]] = testcases[testcase_list[i][0]] | (testcase_list[i][1] == 'in') + eval(EXE_PATH, TEST_BASE_PATH, optimization=optimization) diff --git a/SysYF语言定义.pdf b/SysYF语言定义.pdf new file mode 100644 index 0000000..3b50c12 Binary files /dev/null and b/SysYF语言定义.pdf differ diff --git a/contribution.md b/contribution.md new file mode 100644 index 0000000..b2257ca --- /dev/null +++ b/contribution.md @@ -0,0 +1,17 @@ +# 组员贡献 + +## 贡献详述 + +### 组员1 张三 + +### 组员2 李四 + +### 组员3 王五 + +## 评定结果 + +| 组员姓名 | 贡献百分比 | +| :-----: | :-------: | +| 张三 | xx% | +| 李四 | xx% | +| 王五 | xx% | diff --git a/doc/AST.md b/doc/AST.md new file mode 100644 index 0000000..54ef981 --- /dev/null +++ b/doc/AST.md @@ -0,0 +1,473 @@ +# AST + +**源码链接:** + +[SyntaxTree.h](../include/SyntaxTree.h) + +[SyntaxTree.cpp](../src/SyntaxTree.cpp) + + +## 目录 + +[Ptr](#ptr) + +[PtrLst](#ptrlist) + +[Position](#position) + +[Type](#type) + +[Binop](#binop) + +[UnaryOp](#unaryOp) + +[UnaryCondOp](#unarycondop) + +[BinaryCondOp](#binarycondop) + +[Node](#node) + +[Assembly](#assembly) + +[InitVal](#initval) + +[GlobalDef](#globaldef) + +[FuncDef](#funcdef) + +[VarDef](#vardef) + +[Stmt](#stmt) + +[AssignStmt](#assignstmt) + +[ReturnStmt](#returnstmt) + +[BlockStmt](#blockstmt) + +[EmptyStmt](#emptystmt) + +[ExprStmt](#exprstmt) + +[Expr](#expr) + +[CondExpr](#condexpr) + +[AddExpr](#addexpr) + +[UnaryCondExpr](#unarycondexpr) + +[BinaryCondExpr](#binarycondexpr) + +[BinaryExpr](#binaryexpr) + +[UnaryExpr](#unaryexpr) + +[LVal](#lval) + +[Literal](#literal) + +[FuncCallStmt](#funccallstmt) + +[FuncParam](#funcparam) + +[FuncFParamList](#funcfparamlist) + +[IfStmt](#ifstmt) + +[WhileStmt](#whilestmt) + +[BreakStmt](#breakstmt) + +[ContinueStmt](#continuestmt) + +[Visitor](#visitor) + +## Ptr + +AST中使用的指针类型。实际上是`std::shared_ptr` + +## PtrList + +存放[Ptr](#ptr)的list,实际上是`std::vector` + +## Position + +该节点代表的语法结构在源文件的位置信息,实际上是`yy::location`。由bison/flex自动生成。 + +## Type +包含SysY语言支持的数据类型:`Type::INT`以及`Type::VOID`。 + +多出的`Type::STRING`类型用作系统调用的参数类型,`Type::BOOL`作为条件表达式类型。 + +## Binop + +双目算术表达式的操作符。包含 + +`Binop::PLUS` 加 + +`Binop::MINUS`减 + +`Binop::MULTIPLY`乘 + +`Binop::DIVIDE`除 + +`Binop::MODULO`模 + +## UnaryOp + +单目算术表达式操作符,包含 + +`UnaryOp::PLUS`正 + +`UnaryOp::MINUS`负 + + +## UnaryCondOp + +单目条件表达式操作符,包含 + +`UnaryCondOp::NOT`非 + +## BinaryCondOp + +双目条件表达式操作符,包含 + +`BinaryCondOp::LT`小于 + +`BinaryCondOp::LTE`小于等于 + +`BinaryCondOp::GT`大于 + +`BinaryCondOp::GTE`大于等于 + +`BinaryCondOp::EQ`等于等于 + +`BinaryCondOp::NEQ`不等于 + +`BinaryCondOp::LAND`逻辑与 + +`BinaryCondOp::LOR`逻辑或 + +## Node + +语法树所有结点的基类, + +`Node::loc`是其在对应源文件的位置信息。类型为[Position](#position) + +`virtual void Node::accept(Visitor &visitor)`为虚函数,用于访问者模式,接受一个[Visitor](#visitor)。需要进行重写。 + +## Assembly + +AST的根结点 + +[PtrList](#ptrlist)<[GlobalDef](#globaldef)> `Assembly::global_defs`存放所有[GlobalDef](#globaldef)指针。 + +## InitVal + +代表初值的结点。该结点为嵌套定义。以下类型的变量初值均可表示: + +```c++ +int a = 1 + 1; +int b[2] = {1,2}; +int c[2][2] = {{1,2},{3,4}} +... +``` + +`bool InitVal::isExp` + +为真时初值为[Expr](#expr)类型。为假时代表以`{...}`的形式进行赋初值 +eg +```c++ +int a = 3 + 1;//isExp=true +int c[2][2] = {{1,2},{3,4}};//isExp=false +``` +所有`InitVal`结点最底层一定是[Expr](#expr)类型。也即`isExp`为true + +[PtrList](#ptrlist)<[InitVal](#initval)> `InitVal::elementList` + +当`isExp`为false时该域才有意义。是包含`{}`中其余`InitVal`结点指针的列表。 + +[Ptr](#ptr)<[Expr](#expr)> `InitVal::expr` + +当`isExp`为true时该域才有意义。一个初值表达式的指针。 + +## GlobalDef + +所有def结点的基类 + +## FuncDef + +代表函数定义。 + +[Type](#type) `FuncDef::ret_type`。 + +函数的返回值类型 + +[Ptr](#ptr)<[FuncFParamList](#funcfparamlist)> `FuncDef::param_list`。 + +函数的形参指针 + +`std::string FuncDef::name` + +函数名 + +[Ptr](#ptr)<[BlockStmt](#blockstmt)> `FuncDef::body` + +函数体指针 + +## VarDef + +代表变量定义 + +`bool VarDef::is_constant` + +是否为常量 + +[Type](#type) `VarDef::btype` + +变量类型(在sysY中只能是int) + +`std::string VarDef::name` + +变量名 + +`bool VarDef::is_inited` + +是否初始化 + +[PtrList](#ptrlist)<[Expr](#expr)> `VarDef::array_length` + +若为数组,则是存放各维长度表达式指针的列表,否则为空 + +[Ptr](#ptr)<[InitVal](#initval)> `VarDef::initializers` + +若初始化,则是指向初值定义的指针 + +## Stmt + +所有statement的基类 + +## AssignStmt + +表示如下类型的语句: +```c++ +target = value +``` + +即赋值型语句 + +[Ptr](#ptr)<[Lval](#lval)> `AssignStmt::target` + +赋值表达式的左值指针 + +[Ptr](#ptr)<[Expr](#expr)> `AssignStmt::value` + +赋值表达式右边表达式指针 + +## ReturnStmt + +代表return 语句 + +[Ptr](#ptr)<[Expr](#expr)> `ReturnStmt::ret` + +return 语句返回的表达式指针。空指针代表void return + +## BlockStmt + +代表使用`{}`括起来的stmt。 + +[PtrList](#ptrlist)<[Stmt](#stmt)> `BlockStmt::body` + +该block中所有stmt指针的列表 + +## EmptyStmt + +空语句 + +## ExprStmt + +表达式语句 + +[Ptr](#ptr)<[Expr](#exp)> `ExprStmt::exp` + +表达式语句对应表达式的指针 + +## Expr + +所有表达式的基类 + +## CondExpr + +所有条件表达式的基类 + +## AddExpr + +所有算术表达式的基类 + +## UnaryCondExpr + +单目条件表达式 + +`UnaryCondOp UnaryCondExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `UnaryCondExpr::rhs` + +操作符右端表达式指针 + +## BinaryCondExpr + +双目条件表达式 + +`BinaryCondOp BinaryCondExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `BinaryCondExpr::lhs, rhs` + +操作符左右两端表达式指针 + +## BinaryExpr + +双目算术表达式 + +`BinOp BinaryExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `BinaryExpr::lhs, rhs` + +操作符左右两端表达式指针 + +## UnaryExpr + +单目算术表达式 + +`UnaryOp UnaryExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `UnaryExpr::rhs` + +操作符右端表达式指针 + +## LVal + +左值表达式 + +`std::string Lval::name` + +变量名 + +[PtrList](#ptrlist)<[Expr](#expr)> `LVal::array_index` + +数组索引的指针列表。若不是数组,则为空 + +## Literal + +语义值类型,包含整数和字符串 + +`bool Literal::is_int` + +是否为整形 + +`int Literal::int_const` + +整数语义值 + +`std::string Literal::str` + +字符串语义值(未处理转义) + +## FuncCallStmt + +函数调用 + +`std::string FuncCallStmt::name` + +被调用的函数名 + +[PtrList](#ptrlist)<[Expr](#expr)> `FuncCallStmt::params` + +存放函数实参表达式指针的列表 + +## FuncParam + +单个函数形参 + +`std::string FuncParam::name` + +形参名 + +[Type](#type) `FuncParam::param_type` + +形参类型 + +[PtrList](#ptrlist)<[Expr](#expr)> `FuncParam::array_index` + +形参的数组维度列表,存放每一维的表达式指针。若非数组则为空 + +## FuncFParamList + +存放一个函数的所有形参 + +[PtrList](#ptrlist)<[FuncParam](#funcparam)> `FuncFParamList::params` + +存放所有形参指针的列表 + +## IfStmt + +表示如下结构: +```c++ +if(cond_exp) + if_stmt +或 +if(cond_exp) + if_stmt +else + else_stmt +``` + +[Ptr](#ptr)<[Expr](#expr)> `IfStmt::cond_exp` + +cond_exp的指针 + +[Ptr](#ptr)<[Stmt](#stmt)> `IfStmt::if_statement` + +if_stmt的指针 + +[Ptr](#ptr)<[Stmt](#stmt)> `IfStmt::else_statement` + +else_stmt的指针(若无else,则为空) + + +## WhileStmt + +表示如下结构 +```c++ +while(cond_exp) + stmt +``` + +[Ptr](#ptr)<[Expr](#expr)> `WhileStmt::cond_exp` + +cond_exp的指针 + +[Ptr](#ptr)<[Stmt](#stmt)> `WhileStmt::statement` + +stmt的指针 + + +## BreakStmt + +表示一个break语句 + +## ContinueStmt + +表示一个continue语句 + +## Visitor + +访问者模式的基类,用于访问AST。需要重写其中的visit函数。 \ No newline at end of file diff --git a/doc/SysYIR.md b/doc/SysYIR.md new file mode 100644 index 0000000..a7e5896 --- /dev/null +++ b/doc/SysYIR.md @@ -0,0 +1,624 @@ +# SysY IR + +- [SysY IR](#sysy-ir) + - [IR](#ir) + - [IR Features](#ir-features) + - [IR Format](#ir-format) + - [Instruction](#instruction) + - [Terminator Instructions](#terminator-instructions) + - [Ret](#ret) + - [Br](#br) + - [Standard binary operators](#standard-binary-operators) + - [Add FAdd](#add-fadd) + - [Sub FSub](#sub-fsub) + - [Mul FMul](#mul-fmul) + - [SDiv FDiv](#sdiv-fdiv) + - [SRem](#srem) + - [Memory operators](#memory-operators) + - [Alloca](#alloca) + - [Load](#load) + - [Store](#store) + - [CastInst](#castinst) + - [ZExt](#zext) + - [FpToSi](#fptosi) + - [SiToFp](#sitofp) + - [Other operators](#other-operators) + - [ICmp FCmp](#icmp-fcmp) + - [Call](#call) + - [GetElementPtr](#getelementptr) + - [C++ APIs](#c-apis) + - [核心类概念图](#核心类概念图) + - [BasicBlock](#basicblock) + - [Constant](#constant) + - [Function](#function) + - [GlobalVariable](#globalvariable) + - [IRBuilder](#irbuilder) + - [Instruction](#instruction-1) + - [Module](#module) + - [Type](#type) + - [User](#user) + - [Value](#value) + - [总结](#总结) + +## IR + +### IR Features +- 采用 3 地址的方式 + - 区别于 X86 汇编的目标和源寄存器共用的模式: ADD EAX, EBX + - %2 = add i32 %0, %1 +- SSA 形式 + 无限寄存器 + - 每个变量都只被赋值一次 + - 容易确定操作间的依赖关系,便于优化分析 +- 强类型系统 + - 每个 Value 都具备自身的类型, + - IR类型系统: + - `i1`:1位宽的整数类型 + - `i32`:32位宽的整数类型 + - `float`:单精度浮点数类型 + - `pointer`:指针类型 + - 例如:`i32*, [10 x i32*]` + - `label` bb的标识符类型 + - `functiontype`函数类型,包括函数返回值类型与参数类型(下述文档未提及) + +### IR Format +以下面的`easy.c`与`easy.ll`为例进行说明。 +通过命令`clang -S -emit-llvm easy.c`可以得到对应的`easy.ll`如下(助教增加了额外的注释)。`.ll`文件中注释以`;`开头。 + +- `easy.c`: + ``` c + int main(){ + int a; + int b; + a = 1; + b = 2; + if(a < b) + b = 3; + return a + b; + } + ``` +- `easy.ll`: + ``` c + ; 注释: .ll文件中注释以';'开头 + ; ModuleID = 'easy.c' + source_filename = "easy.c" + ; 注释: target的开始 + target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" + target triple = "x86_64-unknown-linux-gnu" + ; 注释: target的结束 + + ; 注释: 全局main函数的定义 + ; Function Attrs: noinline nounwind optnone uwtable + define dso_local i32 @main() #0 { + ; 注释: 第一个基本块的开始 + %1 = alloca i32, align 4 + %2 = alloca i32, align 4 + %3 = alloca i32, align 4 + store i32 0, i32* %1, align 4 + store i32 1, i32* %2, align 4 + store i32 2, i32* %3, align 4 + %4 = load i32, i32* %2, align 4 + %5 = load i32, i32* %3, align 4 + %6 = icmp slt i32 %4, %5 + br i1 %6, label %7, label %8 + ; 注释: 第一个基本块的结束 + + ; 注释: 第二个基本块的开始 + 7: ; preds = %0 + store i32 3, i32* %3, align 4 + br label %8 + ; 注释: 第二个基本块的结束 + + ; 注释: 第三个基本块的开始 + 8: ; preds = %7, %0 + %9 = load i32, i32* %2, align 4 + %10 = load i32, i32* %3, align 4 + %11 = add nsw i32 %9, %10 + ret i32 %11 ; 注释: 返回语句 + ; 注释: 第三个基本块的结束 + } + + attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } + + !llvm.module.flags = !{!0} + !llvm.ident = !{!1} + + !0 = !{i32 1, !"wchar_size", i32 4} + !1 = !{!"clang version 10.0.1 "} + ``` +其中,每个program由1个或多个module组成,module之间由LLVM Linker合并。 +每个module组成如下: +- Target Information: + ``` c + target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" + target triple = "x86_64-unknown-linux-gnu" + ``` +- Global Symbols: main函数的定义 +- Others:尾部其他信息 + +每个函数的组成如下: +- 头部:函数返回值类型,函数名,函数参数 +- 一个或多个基本块: + - 每个基本块又有Label和Instruction组成。 + ``` c + 8: ; preds = %7, %0 + %9 = load i32, i32* %2, align 4 + %10 = load i32, i32* %3, align 4 + %11 = add nsw i32 %9, %10 + ret i32 %11 + ``` + 这个例子中,`8`就是Label。 + `%9 = load i32, i32* %2, align 4`中的`%9`是目的操作数,`load`是指令助记符,`i32`是`int32`的类型,`i32*`是指向`int32`的地址类型,`%2`是源操作数,`align 4`表示对齐。 +### Instruction +#### Terminator Instructions +**注**:ret与br都是Terminator Instructions也就是终止指令,在llvm基本块的定义里,基本块是单进单出的,因此只能有一条终止指令(ret或br)。当一个基本块有两条终止指令,clang 在做解析会认为第一个终结指令是此基本块的结束,并会开启一个新的匿名的基本块(并占用了下一个编号)。 +##### Ret +- 格式 + - `ret ` + - `ret void` +- 例子: + - `ret i32 %0` + - `ret void` +- 概念:` ret`指令用于将控制流(以及可选的值)从函数返回给调用者。`ret`指令有两种形式:一种返回值,然后终结函数,另一种仅终结函数。 + +##### Br +- 格式: + - `br i1 , label , label ` + - `br label ` +- 例子: + - `br i1 %cond label %truebb label %falsebb` + - `br label %bb` +- 概念:`br`指令用于使控制流转移到当前功能中的另一个基本块。 该指令有两种形式,分别对应于条件分支和无条件分支。 + +#### Standard binary operators +##### Add FAdd +- 格式: + - ` = add , ` + - ` = fadd , ` +- 例子: + - `%2 = add i32 %1, %0` + - `%2 = fadd float %1, %0` +- 概念:`add`指令返回其两个`i32`类型的操作数之和,返回值为`i32`类型,`fadd`指令返回其两个`float`类型的操作数之和,返回值为`float`类型 + +##### Sub FSub +- 格式与例子与`add`,`fadd`类似 +- 概念:`sub`指令返回其两个`i32`类型的操作数之差,返回值为`i32`类型,`fsub`指令返回其两个`float`类型的操作数之差,返回值为`float`类型 + +##### Mul FMul +- 格式与例子与`add`,`fadd`类似 +- 概念:`mul`指令返回其两个`i32`类型的操作数之积,返回值为`i32`类型,`fmul`指令返回其两个`float`类型的操作数之积,返回值为`float`类型 + +##### SDiv FDiv +- 格式与例子与`add`,`fadd`类似 +- 概念:`sdiv`指令返回其两个`i32`类型的操作数之商,返回值为`i32`类型,`fdiv`指令返回其两个`float`类型的操作数之商,返回值为`float`类型 + +##### SRem +- 格式与例子与`add`类似 +- 概念:`srem`指令返回其两个`i32`类型的操作数之模,返回值为`i32`类型 + +#### Memory operators +##### Alloca +- 格式:` = alloca ` +- 例子: + - `%ptr = alloca i32` + - `%ptr = alloca [10 x i32]` +- 概念: `alloca`指令在当前执行函数的堆栈帧上分配内存,当该函数返回其调用者时将自动释放该内存。 始终在地址空间中为数据布局中指示的分配资源分配对象 + +##### Load +- 格式:` = load , * ` +- 例子:`%val = load i32, i32* %ptr` +- 概念:`load`指令用于从内存中读取。 + +##### Store +- 格式:`store , * ` +- 例子:`store i32 3, i32* %ptr` +- 概念:`store`指令用于写入内存 + +#### CastInst +##### ZExt +- 格式:` = zext to ` +- 例子:`%1 = zext i1 %0 to i32` +- 概念:`zext`指令将其操作数**零**扩展为`type2`类型。 + +##### FpToSi +- 概念:`fptosi`指令将浮点值转换为`type2`(整数)类型。 +- 格式:` = fptosi to ` +- 例子:`%Y = fptosi float 1.0E-247 to i32` + +##### SiToFp +- 格式:` = sitofp to ` +- 例子:`%X = sitofp i32 257 to float` +- 概念:`sitofp`指令将有符号整数转换为`type2`(浮点数)类型。 + +#### Other operators +##### ICmp FCmp +- 格式: + - ` = icmp , ` + - ` = eq | ne | sgt | sge | slt | sle` + - ` = fcmp , ` + - ` = eq | ne | ugt | uge | ult | ule` +- 例子:`i1 %2 = icmp sge i32 %0, %1` +- 概念:`icmp`指令根据两个整数的比较返回布尔值,`fcmp`指令根据两个浮点数的比较返回布尔值。 + +##### Call +- 格式: + - ` = call () ` +- 例子: + - `%0 = call i32 @func( i32 %1, i32* %0)` + - `call @func( i32 %arg)` +- 概念:`call`指令用于使控制流转移到指定的函数,其传入参数绑定到指定的值。 在被调用函数中执行`ret`指令后,控制流程将在函数调用后继续执行该指令,并且该函数的返回值绑定到`result`参数。 + +##### GetElementPtr +- 格式:` = getelementptr , * [, ]` +- 例子: + - `%2 = getelementptr [10 x i32], [10 x i32]* %1, i32 0, i32 %0` + - `%2 = getelementptr i32, i32* %1 i32 %0` +- 参数解释:第一个参数是计算基础类型,第二第三个参数表示索引开始的指针类型及指针,`[]`表示可重复参数,里面表示的数组索引的偏移类型及偏移值。(思考指针类型为`[10 x i32]`指针和`i32`指针`getelementptr`用法的不同) +- 概念:`getelementptr`指令用于获取数组结构的元素的地址。 它仅执行地址计算,并且不访问内存。 + +## C++ APIs + +### 核心类概念图 + +to make + +### BasicBlock +- 继承:从[value](#value)继承 + +- 含义:基本块,是一个是单入单出的代码块,该类维护了一个指令链表,基本块本身属于 Value, 类型是 \,会被分支指令调用 + +- 成员: + + - instr_list_:指令链表 + - pre_basic_blocks_: bb前驱集合 + - succ_basic_blocks_:bb后继集合 + +- API: + + ```c++ + static BasicBlock *create(Module *m, const std::string &name , Function *parent ) + // 创建并返回BB块,参数分别是BB块所属的Module,name是其名字默认为空,BB块所属的Function + Function *get_parent(); + // 返回BB块所属的函数 + Module *get_module(); + // 返回BB块所属的Module + Instruction *get_terminator(); + // 返回BB块的终止指令(ret|br)若BB块最后一条指令不是终止指令返回null + void add_instruction(Instruction *instr); + // 将instr指令添加到此BB块指令链表结尾,调用IRBuilder里来创建函数会自动调用此方法 + void add_instr_begin(Instruction *instr); + // 将instr指令添加到此BB块指令链表开头 + void delete_instr(Instruction *instr); + // 将instr指令从BB块指令链表中移除,同时调用api维护好instr的操作数的use链表。 + bool empty(); + // BB块中为空返回true + int get_num_of_instr(); + // 返回BB块中指令的数目 + std::list &get_instructions(); + //返回BB块的指令链表 + void erase_from_parent(); + // 将此BB块从所属函数的bb链表中移除 + + /****************api about cfg****************/ + std::list &get_pre_basic_blocks() // 返回前驱快集合 + std::list &get_succ_basic_blocks() // 返回后继块集合 + void add_pre_basic_block(BasicBlock *bb) // 添加前驱块 + void add_succ_basic_block(BasicBlock *bb) // 添加后继块 + void remove_pre_basic_block(BasicBlock *bb) // 移除前驱块 + void remove_succ_basic_block(BasicBlock *bb) // 移除后继块 + /****************api about cfg****************/ + + ``` + + +### Constant +- 继承:从[User](#user)继承 +- 含义:常数,各种类型常量的基类 +- 子类: + - ConstantInt: + - 含义:int类型的常数 + + - 成员: + + - val_:常数值 + + - API: + + ```cpp + int get_value() // 返回该常数类型中存的常数值 + static int get_value(ConstantInt *const_val)// 返回该常数类型const_val中存的常数值 + static ConstantInt *get(int val, Module *m) // 以val值来创建常数类 + static ConstantInt *get(bool val, Module *m) // 以val值来创建bool常数类 + ``` + + - ConstantFP: + - 含义:float类型的常数 + + - 成员: + + - val_:常数值 + + - API: + + ```cpp + static ConstantFP *get(float val, Module *m) // 以val值创建并返回浮点数常量类 + float get_value() // 返回该常数类型中存的常数值 + ``` + + - ConstantZero: + + - 含义:用于全局变量初始化的常量0值。 + + - API: + + ```cpp + static ConstantZero *get(Type *ty, Module *m);// 创建并返回ConstantZero常量类 + ``` + + - ConstantArray + + - 含义:数组类型的常数 + - 成员: + - const_array_:数组常量值 + + - API:cminus语法不需要数组常量的支持(本次实验不需要用到),在此不过多解释。感兴趣可以自行查看源代码。 +### Function +- 继承:从[Value](#value)继承 + +- 含义:函数,该类描述 LLVM 的一个简单过程,维护基本块表,格式化参数表 + +- 成员: + - basic_blocks_:基本块列表 + - arguments_:形参列表 + - parent_:函数属于的module + +- API: + + ```cpp + static Function *create(FunctionType *ty, const std::string &name, Module *parent); + // 创建并返回Function,参数依次是待创建函数类型ty,函数名字name(不可为空),函数所属的Module + FunctionType *get_function_type() const; + // 返回此函数类的函数类型 + Type *get_return_type() const; + // 返回此函数类型的返回值类型 + void add_basic_block(BasicBlock *bb); + // 将bb添加至Function的bb链表上(调用bb里的创建函数时会自动调用此函数挂在function的bb链表上) + unsigned get_num_of_args() const; + // 得到函数形参数数量 + unsigned get_num_basic_blocks() const; + // 得到函数基本块数量 + Module *get_parent() const; + // 得到函数所属的Module + std::list::iterator arg_begin() + // 得到函数形参的list的起始迭代器 + std::list::iterator arg_end() + // 得到函数形参的list的终止迭代器 + void remove(BasicBlock* bb) + // 从函数的bb链表中删除一个bb + std::list &get_basic_blocks() + // 返回函数bb链表 + std::list &get_args() + // 返回函数的形参链表 + void set_instr_name(); + // 给函数中未命名的基本块和指令命名 + ``` + + + +- 相关类: + - Argument: + - 含义:参数 + + - 成员: + - arg_no_:参数序号 + - parent_:参数属于哪个函数 + + - API + + ```cpp + Function *get_parent() // 返回参数的所属函数 + unsigned get_arg_no() const // 返回参数在所在函数的第几个参数 + ``` +### GlobalVariable +- 继承:从[User](#user)继承 +- 含义:全局变量,该类用于表示全局变量,是 GlobalValue 的子类,根据地址来访问 +- 成员: + - is_const:是否为常量 + - init_val_:初始值 +- API:由于cminusf语义要求所有的全局变量都默认初始化为0,故`GlobalVariable`中成员和API再构造CminusFBuilder用不到 +### IRBuilder +- 含义:生成IR的辅助类,该类提供了独立的接口创建各种 IR 指令,并将它们插入基本块中, 该辅助类不做任何类型检查。 + +- API: + + ```cpp + BasicBlock *get_insert_block()// 返回正在插入指令的BB + void set_insert_point(BasicBlock *bb)// 设置当前需要插入指令的bb + Instruction *create_[instr_type]()// 创建instr_type(具体名字参考IRBuilder.h代码)的指令并对应插入到正在插入的BB块,这种类型的指令看函数名字和参数名字和IR文档是一一对应的。 + ``` + + +### Instruction +- 继承:从[User](#user)继承 +- 含义:指令,该类是所有 LLVM 指令的基类,主要维护指令的操作码(指令类别),指令所属的基本块,指令的操作数个数信息 +- 成员: + - parent_:指令所属的BasicBlock + - op_id_:指令的类型id + - num_ops_指令的操作数个数 +- 子类: + - BinaryInst:双目运算指令包括add、sub、mul、div + - 其他子类和前述文档中提到的指令一一对应,不在此赘述。 +- API:所有指令的创建都要通过IRBuilder进行,不需要关注Instruction类的实现细节,(**注**:不通过IRBuilder来创建指令,而直接调用指令子类的创建方法未经助教完善的测试) +### Module +- 含义:一个编译单元,在此源语言的意义下是一个文件 + +- 成员: + - function_list_:函数链表,记录了这个编译单元的所有函数 + - global_list_:全局变量链表 + - instr_id2string_:通过指令类型id得到其打印的string + - module_name_, source_file_name:未使用 + - 从module中能取到的基本类型 + +- API: + + ```cpp + Type *get_void_type(); + // 得到IR中的void类型其他类型可以用类似的API得到(推荐取得类型采用lab3助教提供的方法Type::get()) + void add_function(Function *f); + // 将f挂在module的function链表上,在function被创建的时候会自动调用此方法来添加function + void add_global_variable(GlobalVariable* g); + // 将g挂在module的GlobalVariable链表上,在GlobalVariable被创建的时候会自动调用此方法来添加GlobalVariable + std::list get_global_variable(); + // 获取全局变量列表 + std::string get_instr_op_name( Instruction::OpID instr ); + // 获取instr对应的指令名(打印ir时调用) + void set_print_name(); + // 设置打印ir的指令与bb名字; + ``` + + +### Type +- 含义:IR的类型,该类是所有类型的超类 + +- 成员: + + - tid_:枚举类型,表示type的类型(包含VoidType、LabelType、FloatType、Int1、Int32、ArrayType、PointerType) + +- 子类: + - IntegerType + - 含义:int 类型 + + - 成员: + + - num_bits:长度(i1或者i32) + + - API: + + ```cpp + unsigned get_num_bits();// 返回int的位数 + ``` + - FloatType + + - 含义:float 类型 + - FunctionType + - 含义:函数类型 + + - 成员: + - result_:返回值类型 + - args_:参数类型列表 + + - API: + + ```cpp + static FunctionType *get(Type *result, std::vector params); + // 返回函数类型,参数依次是返回值类型result,形参类型列表params + unsigned get_num_of_args() const; + // 返回形参个数 + Type *get_param_type(unsigned i) const; + // 返回第i个形参的类型 + std::vector::iterator param_begin() + // 返回形参类型列表的起始迭代器 + std::vector::iterator param_end() + // 返回形参类型列表的终止迭代器 + Type *get_return_type() const; + // 返回函数类型中的返回值类型 + ``` + - ArrayType + - 含义:数组类型 + + - 成员: + - contained_:数组成员的类型 + - num_elements_:数组维数 + + - API: + + ```cpp + static ArrayType *get(Type *contained, unsigned num_elements) + // 返回数组类型,参数依次是 数组元素的类型contained,数组元素个数num_elements + Type *get_element_type() const + // 返回数组元素类型 + unsigned get_num_of_elements() const + // 返回数组元素个数 + ``` + - PointerType + - 含义:指针类型 + + - 成员: + + - contained_:指针指向的类型 + + - API: + + ```cpp + Type *get_element_type() const { return contained_; } + // 返回指针指向的类型 + static PointerType *get(Type *contained); + // 创建指向contained类型的指针类型 + Type *get_pointer_element_type() + // 对于pointertype而言返回指针指向的类型,其他则返回nullptr + ``` + +- API: + + ```cpp + bool is_void_type()// 判断是否是void类型其他类型有类似API请查看Type.h + static Type *get_void_type(Module *m);// 得到void类型 + Type *get_pointer_element_type();// 若是PointerType则返回指向的类型,若不是则返回nullptr。 + Type *get_array_element_type();// 若是ArrayType则返回指向的类型,若不是则返回nullptr。 + ``` + + +### User +- 继承:从[value](#value)继承 + +- 含义:使用者,提供一个操作数表,表中每个操作数都直接指向一个 Value, 提供了 use-def 信息,它本身是 Value 的子类, Value 类会维护一个该数据使用者的列表,提供def-use信息。简单来说操作数表表示我用了谁,该数据使用者列表表示谁用了我。这两个表在后续的**优化实验**会比较重要请务必理解。 + +- 成员: + - operands_:参数列表,表示这个使用者所用到的参数 + - num_ops_:表示该使用者使用的参数的个数 + +- API: + + ```cpp + Value *get_operand(unsigned i) const; + // 从user的操作数链表中取出第i个操作数 + void set_operand(unsigned i, Value *v); + // 将user的第i个操作数设为v + void add_operand(Value *v); + // 将v挂到User的操作数链表上 + unsigned get_num_operand() const; + // 得到操作数链表的大小 + void remove_use_of_ops(); + // 从User的操作数链表中的所有操作数处的use_list_ 移除该User; + void remove_operands(int index1,int index2); + // 移除操作数链表中索引为index1-index2的操作数,例如想删除第0个操作数:remove_operands(0,0) + ``` + + + + +### Value +- 含义:最基础的类,代表一个操作数,代表一个可能用于指令操作数的带类型数据 + +- 成员: + - use_list_:记录了所有使用该操作数的指令的列表 + - name_:名字 + - type_:类型,一个type类,表示操作数的类型 + +- API: + + ```cpp + Type *get_type() const //返回这个操作数的类型 + std::list &get_use_list() // 返回value的使用者链表 + void add_use(Value *val, unsigned arg_no = 0); + // 添加val至this的使用者链表上 + void replace_all_use_with(Value *new_val); + // 将this在所有的地方用new_val替代,并且维护好use_def与def_use链表 + void remove_use(Value *val); + // 将val从this的use_list_中移除 + ``` + + + +### 总结 + +助教在接口文档里筛选了可能会需要用到的接口,如果对API有问题的请移步issue讨论,本次`SysY IR`接口由助教自行设计实现,并做了大量测试,如有对助教的实现方法有异议或者建议的也请移步issue讨论,**请不要直接修改助教的代码,若因修改助教代码造成后续实验仓库合并的冲突请自行解决**。 \ No newline at end of file diff --git a/doc/phase1.md b/doc/phase1.md new file mode 100644 index 0000000..6f1f9c6 --- /dev/null +++ b/doc/phase1.md @@ -0,0 +1,33 @@ +# IR实验阶段一 +本实验由黄庄湫、吴毓辰助教设计 + +## 前言 +本次实验的目的是让大家熟悉阶段三所需相关知识: +LLVM IR + +## 任务描述 +[了解LLVM IR](#llvm-ir介绍) +[通过clang生成的.ll,了解LLVM IR与c代码的对应关系](#例子-利用clang生成的ll) +[根据c程序手写.ll文件实现相同功能](#你需要做-手动编写ll) + +## 实验内容 +### LLVM IR介绍 +根据[维基百科](https://zh.wikipedia.org/zh-cn/LLVM)的介绍,LLVM是一个自由软件项目,它是一种编译器基础设施,以C++写成,包含一系列模块化的编译器组件和工具链,用来开发编译器前端和后端。IR的全称是Intermediate Representation,即中间表示。LLVM IR是一种类似于汇编的底层语言。 +LLVM IR的具体指令可以参考[Reference Manual](http://llvm.org/docs/LangRef.html)。但是你会发现其内容庞杂。虽然助教认为,高效地查阅官方文档及手册是非常必要的一项技能,但是由于其手册过于复杂,因此助教筛选了后续实验中将要用到的子集,总结为了[精简的IR Reference手册](./SysYIR.md)。 +作为一开始的参考,你可以先阅读其中`IR Features`和`IR Format`两节,后续有需要再反复参考。 + +### 例子: 利用clang生成的.ll +阅读`SysYF_Student/SysYF_Task1/ta_demo/go_upstairs.c` +在对应文件夹内输入`clang -S -emit-llvm go_upstairs.c`指令,你可以得到对应的`go_upstairs.ll` +你需要结合`go_upstairs.c`阅读`go_upstairs.ll`,理解其中每条LLVM IR指令与c代码的对应情况。 +通过`lli go_upstairs.ll; echo $?`指令,你可以测试`go_upstairs.ll`执行结果的正确性。 + +### 你需要做: 手动编写.ll +助教在`SysYF_Student/SysYF_Task1/student_sy/`内提供了四个简单的sy程序:assign_test.sy,func_test.sy,if_test.sy,while_test.sy +你需要在`SysYF_Student/SysYF_Task1/student_ll/`内手工完成自己的assign_test.ll,func_test.ll,if_test.ll,while_test.ll文件,以实现与上述C程序相同的逻辑功能。你需要添加必要的注释,`.ll`文件的注释是以`;`开头的 +必要的情况下,你可以参考`clang -S -emit-llvm`的输出,但是你提交的结果必须避免同此输出一字不差 +注:`.sy`文件是我们定义的语言文件,`clang`无法直接识别 + +### 运行.ll文件 +- `lli`会运行`*.ll`文件 +- `$?`的内容是上一条命令所返回的结果,而`echo $?`可以将其输出到终端中 \ No newline at end of file diff --git a/doc/phase2.md b/doc/phase2.md new file mode 100644 index 0000000..9b91ae4 --- /dev/null +++ b/doc/phase2.md @@ -0,0 +1,37 @@ +# IR实验阶段二 +本实验由黄庄湫、吴毓辰助教设计 + +## 前言 +本次实验的目的是让大家熟悉阶段三所需相关知识: +SysY IR(由助教编写的LLVM IR的轻量级C++接口)。 + +## 任务描述 +[了解SysY IR](#sysy-ir---llvm-ir的c接口) +[通过助教提供的C++例子,了解SysY IR的C++接口及实现](#例子-利用sysy-ir--cpp-生成ll) +[根据c程序手写C++文件调用SysY IR的API生成相同功能的.ll文件](#你需要做-利用sysy-ir--c编写生成ll的程序) + +## 实验内容 +### SysY IR - LLVM IR的C++接口 +由于LLVM IR官方的C++接口的文档同样过于冗长,助教提供了SysY IR这一C++接口库。你需要阅读[SysY IR核心类的介绍](./SysYIR.md)。 +本关会要求大家通过SysY IR根据AST构建生成LLVM IR。所以你需要仔细阅读文档了解其接口的设计。 + +### 例子: 利用SysY IR + C++ 生成.ll +为了让大家更直观地感受并学会LightIR接口的使用,助教提供了`SysYF_Student/SysYF_Task2/ta_demo/go_upstairs_gen.cpp`。 +该C++程序会生成与go_upstairs.c逻辑相同的LLVM IR文件。助教提供了详尽的注释,一定要好好利用! + +### 你需要做: 利用SysY IR + C++编写生成.ll的程序 +你需要在`SysYF_Student/SysYF_Task2/student_cpp/`文件夹中,调用SysY IR接口,编写自己的assign_gen.cpp,func_gen.cpp,if_gen.cpp,while_gen.cpp程序,以生成与phase1的四个sy程序相同逻辑功能的`.ll`文件。 + +### 编译、运行和验证 +在 `SysYF_Student/SysYF_Task2/build/` 下执行: +``` shell +# 如果存在 CMakeCache.txt 要先删除 +# rm CMakeCache.txt +cmake .. +make +``` +你可以得到对应`gcd_array_generator.cpp`的可执行文件。 +``` shell +./go_upstairs_generator +``` +即可执行所得到的可执行文件, 打印出与go_upstairs.c逻辑相同的LLVM IR代码 \ No newline at end of file diff --git a/doc/phase3.md b/doc/phase3.md new file mode 100644 index 0000000..5c5a5a4 --- /dev/null +++ b/doc/phase3.md @@ -0,0 +1,80 @@ +# IR实验阶段三 +本实验由黄庄湫、吴毓辰助教设计 + +## 前言 +本次实验我们要使用访问者模式来实现 IR 自动生成。 +对于产生的IR, 我们可以调用 clang 生成可执行文件,这样一个初级的 SysYF 编译器就完成啦! + +## 任务描述 + +阅读[SysYF 的语义规则](../SysYF语言定义.pdf),注意本次实验必做部分语言可能与前几次实验有不同 +阅读[SysY IR 核心类介绍](./SysYIR.md) +阅读[实验框架](#实验框架),理解如何使用框架以及注意事项 + +修改 `src/SysYBuilder/SysYBuilder.cpp` 来实现自动 IR 产生的算法,使得它能正确编译任何合法的 SysYF 程序 +注: 本次实验不需要实现多维数组 + +## 实验框架 + +本次实验使用了由C++编写的 SysY IR 来生成 LLVM IR。为了便于大家进行实验,该框架自动完成了语法树到 C++ 上的抽象语法树的转换。 + +在SysYBuilder.hpp中,我们还定义了一个用于存储作用域的类`Scope`。它的作用是辅助我们在遍历语法树时,管理不同作用域中的变量。它提供了以下接口: +```cpp +// 进入一个新的作用域 +void enter(); +// 退出一个作用域 +void exit(); +// 往当前作用域插入新的名字->值映射 +bool push(std::string name, Value *val); +// 根据名字,以及是否为函数的bool值寻找到对应值 +// isfunc 为 true 时为寻找函数,否则为寻找其他变量对应的值 +// 思考:将函数单独处理的目的 +Value* find(std::string name, bool isfunc); +// 判断当前是否在全局作用域内 +bool in_global(); +``` +你们需要根据语义合理调用`enter`与`exit`,并且在变量声明和使用时正确调用`push`与`find`。在类`SysYfBuilder`中,有一个`Scope`类型的成员变量`scope`,它在初始化时已经将特殊函数加入了作用域中。因此,你们在进行名字查找时不需要顾虑是否需要对特殊函数进行特殊操作。 + +## 运行与调试 + +### 运行 SysYCompiler + +```sh +mkdir build +cd build +cmake .. +make +``` + +编译后会产生 `SysYCompiler` 程序,它能将`.sy`文件输出为LLVM IR,可以利用clang将IR编译成二进制文件。 + +当需要对 `.sy` 文件测试时,可以这样使用: + +```sh +SysYCompiler test.sy -emit-ir -o test.ll +``` + +### 自动测试 + +助教提供了自动评测脚本, 在`SysYF_Student/SysYF_Task3/Test_H/`目录下执行`python3 test_H.py`, 即可得到评测信息 + +### Bonus + +对于学有余力的小组, 我们提供了Bonus环节, 若小组能完成Bonus部分, 将会有额外加分(仅针对本次实验的团队代码得分, 并且分数不能超过该部分得分上限) + +Bonus部分说明如下: + - H班: + - 多维数组 + - 网安班: + - 将一维数组指针作为参数 + - 逻辑运算(\&\&, \|\|, \!), 重点考察短路计算 + - 多维数组 + +Bonus部分得分标准: 每个部分单独给分, 每个部分需要通过全部对应测例并在线下检查时给助教讲清思路才能得分 + +若小组完成了Bonus部分, 需在线下检查时向助教提出, 并让助教当场检查. 若在统一线下检查过后自行找助教检查, 该Bonus不算分 + +### 备注 + +测试样例并不止公开的20个样例, 助教准备了许多隐藏测例来考验大家:), 隐藏测例并不会放在平台上 +平台上第三部分的分数并不具有参考性, 第三部分的分数由助教线下检查后确定 diff --git a/include/ASTBuilder/SyntaxTree.h b/include/ASTBuilder/SyntaxTree.h new file mode 100644 index 0000000..57eb0f4 --- /dev/null +++ b/include/ASTBuilder/SyntaxTree.h @@ -0,0 +1,333 @@ +#ifndef _SYSY_SYNTAX_TREE_H_ +#define _SYSY_SYNTAX_TREE_H_ + +#include +#include +#include + +#include "location.hh" + +namespace SyntaxTree +{ +// Use unique postd::stringtype to reference stored objects +template +using Ptr = std::shared_ptr; + +// List of reference of type +template +using PtrList = std::vector>; + +using Position = yy::location; + +// Enumerations +enum class Type +{ + INT = 0, + VOID, + STRING, + BOOL, + FLOAT +}; + +enum class BinOp +{ + PLUS = 0, + MINUS, + MULTIPLY, + DIVIDE, + MODULO +}; + +enum class UnaryOp +{ + PLUS = 0, + MINUS +}; + +enum class UnaryCondOp +{ + NOT = 0 +}; + +enum class BinaryCondOp +{ + LT = 0, + LTE, + GT, + GTE, + EQ, + NEQ, + LAND, + LOR +}; + +// Forward declaration +struct Node; +struct Assembly; +struct GlobalDef; +struct FuncDef; + +struct Expr; +struct CondExpr; +struct AddExpr; +struct BinaryExpr; +struct BinaryCondExpr; +struct UnaryCondExpr; +struct UnaryExpr; +struct LVal; +struct Literal; + +struct Stmt; +struct VarDef; +struct AssignStmt; +struct FuncCallStmt; +struct ReturnStmt; +struct BlockStmt; +struct EmptyStmt; +struct ExprStmt; + +struct FuncParam; +struct FuncFParamList; + +struct IfStmt; +struct WhileStmt; +struct BreakStmt; +struct ContinueStmt; +struct InitVal; + +class Visitor; + +// Virtual base of all kinds of syntax tree nodes. +struct Node +{ + Position loc; + // Used in Visitor. Irrelevant to syntax tree generation. + virtual void accept(Visitor &visitor) = 0; +}; + +//node for initial value +struct InitVal: Node{ + bool isExp; + PtrList elementList; + //std::vector> elementList; + Ptr expr; + void accept(Visitor &visitor) final; +}; + +// Root node of an ordinary syntax tree. +struct Assembly : Node +{ + PtrList global_defs; + void accept(Visitor &visitor) final; +}; + +// Virtual base of global definitions, function or variable one. +struct GlobalDef : virtual Node +{ + void accept(Visitor &visitor) override = 0; +}; + +// Function definition. +struct FuncDef : GlobalDef +{ + Type ret_type; + Ptr param_list; + std::string name; + Ptr body; + void accept(Visitor &visitor) final; +}; + +// Virtual base for statements. +struct Stmt : virtual Node +{ + void accept(Visitor &visitor) override = 0; +}; + +// Variable definition. Multiple of this would be both a statement and a global definition; however, itself only +// represents a single variable definition. +struct VarDef : Stmt, GlobalDef +{ + bool is_constant; + Type btype; + std::string name; + bool is_inited; // This is used to verify `{}` + PtrList array_length; // empty for non-array variables + Ptr initializers; + void accept(Visitor &visitor) final; +}; + +// Assignment statement. +struct AssignStmt : Stmt +{ + Ptr target; + Ptr value; + void accept(Visitor &visitor) final; +}; + +// Return statement. +struct ReturnStmt : Stmt +{ + Ptr ret; // nullptr for void return + void accept(Visitor &visitor) final; +}; + +// BlockStmt statement. +struct BlockStmt : Stmt +{ + PtrList body; + void accept(Visitor &visitor) final; +}; + +// Empty statement (aka a single ';'). +struct EmptyStmt : Stmt +{ + void accept(Visitor &visitor) final; +}; + +struct ExprStmt : Stmt +{ + Ptr exp; + void accept(Visitor &visitor) final; +}; + +// Virtual base of expressions. +struct Expr : Node +{ + void accept(Visitor &visitor) override = 0; +}; + +struct CondExpr : Expr +{ + void accept(Visitor &visitor) override = 0; +}; + +struct AddExpr : Expr +{ + void accept(Visitor &visitor) override = 0; +}; + + +struct UnaryCondExpr : CondExpr{ + UnaryCondOp op; + Ptr rhs; + void accept(Visitor &visitor) final; +}; + +struct BinaryCondExpr : CondExpr{ + BinaryCondOp op; + Ptr lhs,rhs; + void accept(Visitor &visitor) final; +}; + +// Expression like `lhs op rhs`. +struct BinaryExpr : AddExpr +{ + BinOp op; + Ptr lhs, rhs; + void accept(Visitor &visitor) final; +}; + +// Expression like `op rhs`. +struct UnaryExpr : AddExpr +{ + UnaryOp op; + Ptr rhs; + void accept(Visitor &visitor) final; +}; + +// Expression like `ident` or `ident[exp]`. +struct LVal : AddExpr +{ + std::string name; + PtrList array_index; // nullptr if not indexed as array + void accept(Visitor &visitor) final; +}; + +// Expression constructed by a literal number. +struct Literal : AddExpr +{ + Type literal_type; + int int_const; + // std::string str; + double float_const; + void accept(Visitor &visitor) final; +}; + +// Function call statement. +struct FuncCallStmt : AddExpr +{ + std::string name; + PtrList params; + void accept(Visitor &visitor) final; +}; + +struct FuncParam : Node +{ + std::string name; + Type param_type; + PtrList array_index; // nullptr if not indexed as array + void accept(Visitor &visitor) final; +}; + +struct FuncFParamList : Node +{ + PtrList params; + void accept(Visitor &visitor) final; +}; + +struct IfStmt : Stmt +{ + Ptr cond_exp; + Ptr if_statement; + Ptr else_statement; + void accept(Visitor &visitor) final; +}; + +struct WhileStmt : Stmt +{ + Ptr cond_exp; + Ptr statement; + void accept(Visitor &visitor) final; +}; + +struct BreakStmt : Stmt +{ + void accept(Visitor &visitor) final; +}; + +struct ContinueStmt : Stmt +{ + void accept(Visitor &visitor) final; +}; + +// Visitor base type +class Visitor +{ +public: + virtual void visit(Assembly &node) = 0; + virtual void visit(FuncDef &node) = 0; + virtual void visit(BinaryExpr &node) = 0; + virtual void visit(UnaryExpr &node) = 0; + virtual void visit(LVal &node) = 0; + virtual void visit(Literal &node) = 0; + virtual void visit(ReturnStmt &node) = 0; + virtual void visit(VarDef &node) = 0; + virtual void visit(AssignStmt &node) = 0; + virtual void visit(FuncCallStmt &node) = 0; + virtual void visit(BlockStmt &node) = 0; + virtual void visit(EmptyStmt &node) = 0; + virtual void visit(ExprStmt &node) = 0; + virtual void visit(FuncParam &node) = 0; + virtual void visit(FuncFParamList &node) = 0; + virtual void visit(IfStmt &node) = 0; + virtual void visit(WhileStmt &node) = 0; + virtual void visit(BreakStmt &node) = 0; + virtual void visit(ContinueStmt &node) = 0; + virtual void visit(UnaryCondExpr &node) = 0; + virtual void visit(BinaryCondExpr &node) = 0; + virtual void visit(InitVal &node) = 0; +}; +} +// end namespace SyntaxTree + +#endif // _SYSY_SYNTAX_TREE_H_ diff --git a/include/ASTPrinter/SyntaxTreePrinter.h b/include/ASTPrinter/SyntaxTreePrinter.h new file mode 100644 index 0000000..c2f008e --- /dev/null +++ b/include/ASTPrinter/SyntaxTreePrinter.h @@ -0,0 +1,36 @@ +#ifndef _SYSY_SYNTAX_TREE_PRINTER_H_ +#define _SYSY_SYNTAX_TREE_PRINTER_H_ + +#include "SyntaxTree.h" + +class SyntaxTreePrinter : public SyntaxTree::Visitor +{ +public: + virtual void visit(SyntaxTree::Assembly &node) override; + virtual void visit(SyntaxTree::FuncDef &node) override; + virtual void visit(SyntaxTree::BinaryExpr &node) override; + virtual void visit(SyntaxTree::UnaryExpr &node) override; + virtual void visit(SyntaxTree::LVal &node) override; + virtual void visit(SyntaxTree::Literal &node) override; + virtual void visit(SyntaxTree::ReturnStmt &node) override; + virtual void visit(SyntaxTree::VarDef &node) override; + virtual void visit(SyntaxTree::AssignStmt &node) override; + virtual void visit(SyntaxTree::FuncCallStmt &node) override; + virtual void visit(SyntaxTree::BlockStmt &node) override; + virtual void visit(SyntaxTree::EmptyStmt &node) override; + virtual void visit(SyntaxTree::ExprStmt &node) override; + virtual void visit(SyntaxTree::FuncParam &node) override; + virtual void visit(SyntaxTree::FuncFParamList &node) override; + virtual void visit(SyntaxTree::BinaryCondExpr &node) override; + virtual void visit(SyntaxTree::UnaryCondExpr &node) override; + virtual void visit(SyntaxTree::IfStmt &node) override; + virtual void visit(SyntaxTree::WhileStmt &node) override; + virtual void visit(SyntaxTree::BreakStmt &node) override; + virtual void visit(SyntaxTree::ContinueStmt &node) override; + virtual void visit(SyntaxTree::InitVal &node) override; + void print_indent(); +private: + int indent = 0; +}; + +#endif // _SYSY_SYNTAX_TREE_PRINTER_H_ diff --git a/include/ErrorReporter/ErrorReporter.h b/include/ErrorReporter/ErrorReporter.h new file mode 100644 index 0000000..99a2795 --- /dev/null +++ b/include/ErrorReporter/ErrorReporter.h @@ -0,0 +1,27 @@ + +#ifndef _SYSY_ERROR_REPORTER_H_ +#define _SYSY_ERROR_REPORTER_H_ + +#include +#include +#include +#include +#include "SyntaxTree.h" + +class ErrorReporter +{ +public: + using Position = SyntaxTree::Position; + explicit ErrorReporter(std::ostream &error_stream); + + void error(Position pos, const std::string &msg); + void warn(Position pos, const std::string &msg); + +protected: + virtual void report(Position pos, const std::string &msg, const std::string &prefix); + +private: + std::ostream &err; +}; + +#endif // _SYSY_ERROR_REPORTER_H_ diff --git a/include/Grammar/FlexLexer.h b/include/Grammar/FlexLexer.h new file mode 100644 index 0000000..b725b1f --- /dev/null +++ b/include/Grammar/FlexLexer.h @@ -0,0 +1,225 @@ +// -*-C++-*- +// FlexLexer.h -- define interfaces for lexical analyzer classes generated +// by flex + +// Copyright (c) 1993 The Regents of the University of California. +// All rights reserved. +// +// This code is derived from software contributed to Berkeley by +// Kent Williams and Tom Epperly. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: + +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. + +// Neither the name of the University nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. + +// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR +// IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE. + +// This file defines FlexLexer, an abstract class which specifies the +// external interface provided to flex C++ lexer objects, and yyFlexLexer, +// which defines a particular lexer class. +// +// If you want to create multiple lexer classes, you use the -P flag +// to rename each yyFlexLexer to some other xxFlexLexer. You then +// include in your other sources once per lexer class: +// +// #undef yyFlexLexer +// #define yyFlexLexer xxFlexLexer +// #include +// +// #undef yyFlexLexer +// #define yyFlexLexer zzFlexLexer +// #include +// ... + +#ifndef __FLEX_LEXER_H +// Never included before - need to define base class. +#define __FLEX_LEXER_H + +#include +# ifndef FLEX_STD +# define FLEX_STD std:: +# endif + +extern "C++" { + +struct yy_buffer_state; +typedef int yy_state_type; + +class FlexLexer { +public: + virtual ~FlexLexer() { } + + const char* YYText() const { return yytext; } + int YYLeng() const { return yyleng; } + + virtual void + yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0; + virtual struct yy_buffer_state* + yy_create_buffer( FLEX_STD istream* s, int size ) = 0; + virtual struct yy_buffer_state* + yy_create_buffer( FLEX_STD istream& s, int size ) = 0; + virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0; + virtual void yyrestart( FLEX_STD istream* s ) = 0; + virtual void yyrestart( FLEX_STD istream& s ) = 0; + + virtual int yylex() = 0; + + // Call yylex with new input/output sources. + int yylex( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ) + { + switch_streams( new_in, new_out ); + return yylex(); + } + + int yylex( FLEX_STD istream* new_in, FLEX_STD ostream* new_out = 0) + { + switch_streams( new_in, new_out ); + return yylex(); + } + + // Switch to new input/output streams. A nil stream pointer + // indicates "keep the current one". + virtual void switch_streams( FLEX_STD istream* new_in, + FLEX_STD ostream* new_out ) = 0; + virtual void switch_streams( FLEX_STD istream& new_in, + FLEX_STD ostream& new_out ) = 0; + + int lineno() const { return yylineno; } + + int debug() const { return yy_flex_debug; } + void set_debug( int flag ) { yy_flex_debug = flag; } + +protected: + char* yytext; + int yyleng; + int yylineno; // only maintained if you use %option yylineno + int yy_flex_debug; // only has effect with -d or "%option debug" +}; + +} +#endif // FLEXLEXER_H + +#if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce) +// Either this is the first time through (yyFlexLexerOnce not defined), +// or this is a repeated include to define a different flavor of +// yyFlexLexer, as discussed in the flex manual. +#define yyFlexLexerOnce + +extern "C++" { + +class yyFlexLexer : public FlexLexer { +public: + // arg_yyin and arg_yyout default to the cin and cout, but we + // only make that assignment when initializing in yylex(). + yyFlexLexer( FLEX_STD istream& arg_yyin, FLEX_STD ostream& arg_yyout ); + yyFlexLexer( FLEX_STD istream* arg_yyin = 0, FLEX_STD ostream* arg_yyout = 0 ); +private: + void ctor_common(); + +public: + + virtual ~yyFlexLexer(); + + void yy_switch_to_buffer( struct yy_buffer_state* new_buffer ); + struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size ); + struct yy_buffer_state* yy_create_buffer( FLEX_STD istream& s, int size ); + void yy_delete_buffer( struct yy_buffer_state* b ); + void yyrestart( FLEX_STD istream* s ); + void yyrestart( FLEX_STD istream& s ); + + void yypush_buffer_state( struct yy_buffer_state* new_buffer ); + void yypop_buffer_state(); + + virtual int yylex(); + virtual void switch_streams( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ); + virtual void switch_streams( FLEX_STD istream* new_in = 0, FLEX_STD ostream* new_out = 0 ); + virtual int yywrap(); + +protected: + virtual int LexerInput( char* buf, int max_size ); + virtual void LexerOutput( const char* buf, int size ); + virtual void LexerError( const char* msg ); + + void yyunput( int c, char* buf_ptr ); + int yyinput(); + + void yy_load_buffer_state(); + void yy_init_buffer( struct yy_buffer_state* b, FLEX_STD istream& s ); + void yy_flush_buffer( struct yy_buffer_state* b ); + + int yy_start_stack_ptr; + int yy_start_stack_depth; + int* yy_start_stack; + + void yy_push_state( int new_state ); + void yy_pop_state(); + int yy_top_state(); + + yy_state_type yy_get_previous_state(); + yy_state_type yy_try_NUL_trans( yy_state_type current_state ); + int yy_get_next_buffer(); + + FLEX_STD istream yyin; // input source for default LexerInput + FLEX_STD ostream yyout; // output sink for default LexerOutput + + // yy_hold_char holds the character lost when yytext is formed. + char yy_hold_char; + + // Number of characters read into yy_ch_buf. + int yy_n_chars; + + // Points to current character in buffer. + char* yy_c_buf_p; + + int yy_init; // whether we need to initialize + int yy_start; // start state number + + // Flag which is used to allow yywrap()'s to do buffer switches + // instead of setting up a fresh yyin. A bit of a hack ... + int yy_did_buffer_switch_on_eof; + + + size_t yy_buffer_stack_top; /**< index of top of stack. */ + size_t yy_buffer_stack_max; /**< capacity of stack. */ + struct yy_buffer_state ** yy_buffer_stack; /**< Stack as an array. */ + void yyensure_buffer_stack(void); + + // The following are not always needed, but may be depending + // on use of certain flex features (like REJECT or yymore()). + + yy_state_type yy_last_accepting_state; + char* yy_last_accepting_cpos; + + yy_state_type* yy_state_buf; + yy_state_type* yy_state_ptr; + + char* yy_full_match; + int* yy_full_state; + int yy_full_lp; + + int yy_lp; + int yy_looking_for_trail_begin; + + int yy_more_flag; + int yy_more_len; + int yy_more_offset; + int yy_prev_more_offset; +}; + +} + +#endif // yyFlexLexer || ! yyFlexLexerOnce + diff --git a/include/Grammar/SysYDriver.h b/include/Grammar/SysYDriver.h new file mode 100644 index 0000000..f7f00c5 --- /dev/null +++ b/include/Grammar/SysYDriver.h @@ -0,0 +1,50 @@ +#ifndef _SYSY_DRIVER_H_ +#define _SYSY_DRIVER_H_ + +#include +#include +#include + +// Generated by bison: +#include "SysYParser.h" + +#include "SysYFlexLexer.h" + +// Conducting the whole scanning and parsing of SysY. +class SysYDriver +{ +public: + SysYDriver(); + virtual ~SysYDriver(); + + std::map variables; + + int result; + + // SysY lexer + SysYFlexLexer lexer; + + std::ifstream instream; + + // Handling the SysY scanner. + void scan_begin(); + void scan_end(); + bool trace_scanning; + + // Run the parser on file F. + // Return 0 on success. + SyntaxTree::Node* parse(const std::string& f); + // The name of the file being parsed. + // Used later to pass the file name to the location tracker. + std::string file; + // Whether parser traces should be generated. + bool trace_parsing; + + // Error handling. + void error(const yy::location& l, const std::string& m); + void error(const std::string& m); + + SyntaxTree::Node* root = nullptr; +}; + +#endif // _SYSY_DRIVER_H_ diff --git a/include/Grammar/SysYFlexLexer.h b/include/Grammar/SysYFlexLexer.h new file mode 100644 index 0000000..502c69d --- /dev/null +++ b/include/Grammar/SysYFlexLexer.h @@ -0,0 +1,37 @@ +#ifndef _SYSY_FLEX_LEXER_H_ +#define _SYSY_FLEX_LEXER_H_ + +#ifndef YY_DECL +#define YY_DECL \ + yy::SysYParser::symbol_type SysYFlexLexer::yylex(SysYDriver& driver) +#endif + +// We need this for yyFlexLexer. If we don't #undef yyFlexLexer, the +// preprocessor chokes on the line `#define yyFlexLexer yyFlexLexer` +// in `FlexLexer.h`: +#undef yyFlexLexer +#include + +// We need this for the yy::SysYParser::symbol_type: +#include "SysYParser.h" + +// We need this for the yy::location type: +#include "location.hh" + +class SysYFlexLexer : public yyFlexLexer { +public: + // Use the superclass's constructor: + using yyFlexLexer::yyFlexLexer; + + // Provide the interface to `yylex`; `flex` will emit the + // definition into `SysYScanner.cpp`: + yy::SysYParser::symbol_type yylex(SysYDriver& driver); + + // This seems like a reasonable place to put the location object + // rather than it being static (in the sense of having internal + // linkage at translation unit scope, not in the sense of being a + // class variable): + yy::location loc; +}; + +#endif // _SYSY_FLEX_LEXER_H_ diff --git a/include/Grammar/SysYParser.h b/include/Grammar/SysYParser.h new file mode 100644 index 0000000..09c6e86 --- /dev/null +++ b/include/Grammar/SysYParser.h @@ -0,0 +1,2881 @@ +// A Bison parser, made by GNU Bison 3.7.6. + +// Skeleton interface for Bison LALR(1) parsers in C++ + +// Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// As a special exception, you may create a larger work that contains +// part or all of the Bison parser skeleton and distribute that work +// under terms of your choice, so long as that work isn't itself a +// parser generator using the skeleton or a modified version thereof +// as a parser skeleton. Alternatively, if you modify or redistribute +// the parser skeleton itself, you may (at your option) remove this +// special exception, which will cause the skeleton and the resulting +// Bison output files to be licensed under the GNU General Public +// License without this special exception. + +// This special exception was added by the Free Software Foundation in +// version 2.2 of Bison. + + +/** + ** \file /home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.h + ** Define the yy::parser class. + */ + +// C++ LALR(1) parser skeleton written by Akim Demaille. + +// DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, +// especially those whose name start with YY_ or yy_. They are +// private implementation details that can be changed or removed. + +#ifndef YY_YY_HOME_HZQ_SYSYF_IR_LAB_2021_SYSYCOMPILER_IR_LAB_BUILD_SYSYPARSER_H_INCLUDED +# define YY_YY_HOME_HZQ_SYSYF_IR_LAB_2021_SYSYCOMPILER_IR_LAB_BUILD_SYSYPARSER_H_INCLUDED +// "%code requires" blocks. +#line 12 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + +#include +#include "SyntaxTree.h" +class SysYDriver; + +#line 55 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.h" + +# include +# include // std::abort +# include +# include +# include +# include + +#if defined __cplusplus +# define YY_CPLUSPLUS __cplusplus +#else +# define YY_CPLUSPLUS 199711L +#endif + +// Support move semantics when possible. +#if 201103L <= YY_CPLUSPLUS +# define YY_MOVE std::move +# define YY_MOVE_OR_COPY move +# define YY_MOVE_REF(Type) Type&& +# define YY_RVREF(Type) Type&& +# define YY_COPY(Type) Type +#else +# define YY_MOVE +# define YY_MOVE_OR_COPY copy +# define YY_MOVE_REF(Type) Type& +# define YY_RVREF(Type) const Type& +# define YY_COPY(Type) const Type& +#endif + +// Support noexcept when possible. +#if 201103L <= YY_CPLUSPLUS +# define YY_NOEXCEPT noexcept +# define YY_NOTHROW +#else +# define YY_NOEXCEPT +# define YY_NOTHROW throw () +#endif + +// Support constexpr when possible. +#if 201703 <= YY_CPLUSPLUS +# define YY_CONSTEXPR constexpr +#else +# define YY_CONSTEXPR +#endif +# include "location.hh" +#include +#ifndef YY_ASSERT +# include +# define YY_ASSERT assert +#endif + + +#ifndef YY_ATTRIBUTE_PURE +# if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) +# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) +# else +# define YY_ATTRIBUTE_PURE +# endif +#endif + +#ifndef YY_ATTRIBUTE_UNUSED +# if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) +# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) +# else +# define YY_ATTRIBUTE_UNUSED +# endif +#endif + +/* Suppress unused-variable warnings by "using" E. */ +#if ! defined lint || defined __GNUC__ +# define YY_USE(E) ((void) (E)) +#else +# define YY_USE(E) /* empty */ +#endif + +#if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ +/* Suppress an incorrect diagnostic about yylval being uninitialized. */ +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ + _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") +# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ + _Pragma ("GCC diagnostic pop") +#else +# define YY_INITIAL_VALUE(Value) Value +#endif +#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_END +#endif +#ifndef YY_INITIAL_VALUE +# define YY_INITIAL_VALUE(Value) /* Nothing. */ +#endif + +#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ +# define YY_IGNORE_USELESS_CAST_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") +# define YY_IGNORE_USELESS_CAST_END \ + _Pragma ("GCC diagnostic pop") +#endif +#ifndef YY_IGNORE_USELESS_CAST_BEGIN +# define YY_IGNORE_USELESS_CAST_BEGIN +# define YY_IGNORE_USELESS_CAST_END +#endif + +# ifndef YY_CAST +# ifdef __cplusplus +# define YY_CAST(Type, Val) static_cast (Val) +# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast (Val) +# else +# define YY_CAST(Type, Val) ((Type) (Val)) +# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) +# endif +# endif +# ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# else +# define YY_NULLPTR ((void*)0) +# endif +# endif + +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 1 +#endif + +namespace yy { +#line 189 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.h" + + + + + /// A Bison parser. + class SysYParser + { + public: +#ifndef YYSTYPE + /// A buffer to store and retrieve objects. + /// + /// Sort of a variant, but does not keep track of the nature + /// of the stored data, since that knowledge is available + /// via the current parser state. + class semantic_type + { + public: + /// Type of *this. + typedef semantic_type self_type; + + /// Empty construction. + semantic_type () YY_NOEXCEPT + : yybuffer_ () + , yytypeid_ (YY_NULLPTR) + {} + + /// Construct and fill. + template + semantic_type (YY_RVREF (T) t) + : yytypeid_ (&typeid (T)) + { + YY_ASSERT (sizeof (T) <= size); + new (yyas_ ()) T (YY_MOVE (t)); + } + +#if 201103L <= YY_CPLUSPLUS + /// Non copyable. + semantic_type (const self_type&) = delete; + /// Non copyable. + self_type& operator= (const self_type&) = delete; +#endif + + /// Destruction, allowed only if empty. + ~semantic_type () YY_NOEXCEPT + { + YY_ASSERT (!yytypeid_); + } + +# if 201103L <= YY_CPLUSPLUS + /// Instantiate a \a T in here from \a t. + template + T& + emplace (U&&... u) + { + YY_ASSERT (!yytypeid_); + YY_ASSERT (sizeof (T) <= size); + yytypeid_ = & typeid (T); + return *new (yyas_ ()) T (std::forward (u)...); + } +# else + /// Instantiate an empty \a T in here. + template + T& + emplace () + { + YY_ASSERT (!yytypeid_); + YY_ASSERT (sizeof (T) <= size); + yytypeid_ = & typeid (T); + return *new (yyas_ ()) T (); + } + + /// Instantiate a \a T in here from \a t. + template + T& + emplace (const T& t) + { + YY_ASSERT (!yytypeid_); + YY_ASSERT (sizeof (T) <= size); + yytypeid_ = & typeid (T); + return *new (yyas_ ()) T (t); + } +# endif + + /// Instantiate an empty \a T in here. + /// Obsolete, use emplace. + template + T& + build () + { + return emplace (); + } + + /// Instantiate a \a T in here from \a t. + /// Obsolete, use emplace. + template + T& + build (const T& t) + { + return emplace (t); + } + + /// Accessor to a built \a T. + template + T& + as () YY_NOEXCEPT + { + YY_ASSERT (yytypeid_); + YY_ASSERT (*yytypeid_ == typeid (T)); + YY_ASSERT (sizeof (T) <= size); + return *yyas_ (); + } + + /// Const accessor to a built \a T (for %printer). + template + const T& + as () const YY_NOEXCEPT + { + YY_ASSERT (yytypeid_); + YY_ASSERT (*yytypeid_ == typeid (T)); + YY_ASSERT (sizeof (T) <= size); + return *yyas_ (); + } + + /// Swap the content with \a that, of same type. + /// + /// Both variants must be built beforehand, because swapping the actual + /// data requires reading it (with as()), and this is not possible on + /// unconstructed variants: it would require some dynamic testing, which + /// should not be the variant's responsibility. + /// Swapping between built and (possibly) non-built is done with + /// self_type::move (). + template + void + swap (self_type& that) YY_NOEXCEPT + { + YY_ASSERT (yytypeid_); + YY_ASSERT (*yytypeid_ == *that.yytypeid_); + std::swap (as (), that.as ()); + } + + /// Move the content of \a that to this. + /// + /// Destroys \a that. + template + void + move (self_type& that) + { +# if 201103L <= YY_CPLUSPLUS + emplace (std::move (that.as ())); +# else + emplace (); + swap (that); +# endif + that.destroy (); + } + +# if 201103L <= YY_CPLUSPLUS + /// Move the content of \a that to this. + template + void + move (self_type&& that) + { + emplace (std::move (that.as ())); + that.destroy (); + } +#endif + + /// Copy the content of \a that to this. + template + void + copy (const self_type& that) + { + emplace (that.as ()); + } + + /// Destroy the stored \a T. + template + void + destroy () + { + as ().~T (); + yytypeid_ = YY_NULLPTR; + } + + private: +#if YY_CPLUSPLUS < 201103L + /// Non copyable. + semantic_type (const self_type&); + /// Non copyable. + self_type& operator= (const self_type&); +#endif + + /// Accessor to raw memory as \a T. + template + T* + yyas_ () YY_NOEXCEPT + { + void *yyp = yybuffer_.yyraw; + return static_cast (yyp); + } + + /// Const accessor to raw memory as \a T. + template + const T* + yyas_ () const YY_NOEXCEPT + { + const void *yyp = yybuffer_.yyraw; + return static_cast (yyp); + } + + /// An auxiliary type to compute the largest semantic type. + union union_type + { + // CompUnit + char dummy1[sizeof (SyntaxTree::Assembly*)]; + + // Block + char dummy2[sizeof (SyntaxTree::BlockStmt*)]; + + // OptionRet + // Exp + // RelExp + // EqExp + // LAndExp + // LOrExp + // CondExp + char dummy3[sizeof (SyntaxTree::Expr*)]; + + // FuncDef + char dummy4[sizeof (SyntaxTree::FuncDef*)]; + + // FuncFParam + char dummy5[sizeof (SyntaxTree::FuncParam*)]; + + // InitVal + // InitValList + // CommaInitValList + char dummy6[sizeof (SyntaxTree::InitVal*)]; + + // LVal + char dummy7[sizeof (SyntaxTree::LVal*)]; + + // Number + char dummy8[sizeof (SyntaxTree::Literal*)]; + + // ArrayExpList + // ExpList + // CommaExpList + char dummy9[sizeof (SyntaxTree::PtrList)]; + + // FParamList + // CommaFParamList + char dummy10[sizeof (SyntaxTree::PtrList)]; + + // GlobalDecl + char dummy11[sizeof (SyntaxTree::PtrList)]; + + // BlockItemList + // BlockItem + char dummy12[sizeof (SyntaxTree::PtrList)]; + + // ConstDecl + // ConstDefList + // VarDecl + // VarDefList + char dummy13[sizeof (SyntaxTree::PtrList)]; + + // Stmt + // IfStmt + char dummy14[sizeof (SyntaxTree::Stmt*)]; + + // BType + char dummy15[sizeof (SyntaxTree::Type)]; + + // ConstDef + // VarDef + char dummy16[sizeof (SyntaxTree::VarDef*)]; + + // FLOATCONST + char dummy17[sizeof (float)]; + + // INTCONST + char dummy18[sizeof (int)]; + + // IDENTIFIER + // STRINGCONST + char dummy19[sizeof (std::string)]; + }; + + /// The size of the largest semantic type. + enum { size = sizeof (union_type) }; + + /// A buffer to store semantic values. + union + { + /// Strongest alignment constraints. + long double yyalign_me; + /// A buffer large enough to store any of the semantic values. + char yyraw[size]; + } yybuffer_; + + /// Whether the content is built: if defined, the name of the stored type. + const std::type_info *yytypeid_; + }; + +#else + typedef YYSTYPE semantic_type; +#endif + /// Symbol locations. + typedef location location_type; + + /// Syntax errors thrown from user actions. + struct syntax_error : std::runtime_error + { + syntax_error (const location_type& l, const std::string& m) + : std::runtime_error (m) + , location (l) + {} + + syntax_error (const syntax_error& s) + : std::runtime_error (s.what ()) + , location (s.location) + {} + + ~syntax_error () YY_NOEXCEPT YY_NOTHROW; + + location_type location; + }; + + /// Token kinds. + struct token + { + enum token_kind_type + { + TOK_YYEMPTY = -2, + TOK_YYEOF = 0, // "end of file" + TOK_YYerror = 256, // error + TOK_YYUNDEF = 304, // "invalid token" + TOK_END = 305, // END + TOK_ERROR = 258, // ERROR + TOK_PLUS = 259, // PLUS + TOK_MINUS = 260, // MINUS + TOK_MULTIPLY = 261, // MULTIPLY + TOK_DIVIDE = 262, // DIVIDE + TOK_MODULO = 263, // MODULO + TOK_LTE = 264, // LTE + TOK_GT = 265, // GT + TOK_GTE = 266, // GTE + TOK_EQ = 267, // EQ + TOK_NEQ = 268, // NEQ + TOK_ASSIGN = 269, // ASSIGN + TOK_SEMICOLON = 270, // SEMICOLON + TOK_COMMA = 271, // COMMA + TOK_LPARENTHESE = 272, // LPARENTHESE + TOK_RPARENTHESE = 273, // RPARENTHESE + TOK_LBRACKET = 274, // LBRACKET + TOK_RBRACKET = 275, // RBRACKET + TOK_LBRACE = 276, // LBRACE + TOK_RBRACE = 277, // RBRACE + TOK_ELSE = 278, // ELSE + TOK_IF = 279, // IF + TOK_INT = 280, // INT + TOK_RETURN = 281, // RETURN + TOK_VOID = 282, // VOID + TOK_WHILE = 283, // WHILE + TOK_IDENTIFIER = 284, // IDENTIFIER + TOK_FLOATCONST = 285, // FLOATCONST + TOK_INTCONST = 286, // INTCONST + TOK_LETTER = 287, // LETTER + TOK_EOL = 288, // EOL + TOK_COMMENT = 289, // COMMENT + TOK_BLANK = 290, // BLANK + TOK_CONST = 291, // CONST + TOK_BREAK = 292, // BREAK + TOK_CONTINUE = 293, // CONTINUE + TOK_NOT = 294, // NOT + TOK_AND = 295, // AND + TOK_OR = 296, // OR + TOK_MOD = 297, // MOD + TOK_FLOAT = 298, // FLOAT + TOK_LOGICAND = 299, // LOGICAND + TOK_LOGICOR = 300, // LOGICOR + TOK_LT = 301, // LT + TOK_STRINGCONST = 302, // STRINGCONST + TOK_LRBRACKET = 303, // LRBRACKET + TOK_UPLUS = 306, // UPLUS + TOK_UMINUS = 307, // UMINUS + TOK_UNOT = 308 // UNOT + }; + /// Backward compatibility alias (Bison 3.6). + typedef token_kind_type yytokentype; + }; + + /// Token kind, as returned by yylex. + typedef token::yytokentype token_kind_type; + + /// Backward compatibility alias (Bison 3.6). + typedef token_kind_type token_type; + + /// Symbol kinds. + struct symbol_kind + { + enum symbol_kind_type + { + YYNTOKENS = 53, ///< Number of tokens. + S_YYEMPTY = -2, + S_YYEOF = 0, // "end of file" + S_YYerror = 1, // error + S_YYUNDEF = 2, // "invalid token" + S_END = 3, // END + S_ERROR = 4, // ERROR + S_PLUS = 5, // PLUS + S_MINUS = 6, // MINUS + S_MULTIPLY = 7, // MULTIPLY + S_DIVIDE = 8, // DIVIDE + S_MODULO = 9, // MODULO + S_LTE = 10, // LTE + S_GT = 11, // GT + S_GTE = 12, // GTE + S_EQ = 13, // EQ + S_NEQ = 14, // NEQ + S_ASSIGN = 15, // ASSIGN + S_SEMICOLON = 16, // SEMICOLON + S_COMMA = 17, // COMMA + S_LPARENTHESE = 18, // LPARENTHESE + S_RPARENTHESE = 19, // RPARENTHESE + S_LBRACKET = 20, // LBRACKET + S_RBRACKET = 21, // RBRACKET + S_LBRACE = 22, // LBRACE + S_RBRACE = 23, // RBRACE + S_ELSE = 24, // ELSE + S_IF = 25, // IF + S_INT = 26, // INT + S_RETURN = 27, // RETURN + S_VOID = 28, // VOID + S_WHILE = 29, // WHILE + S_IDENTIFIER = 30, // IDENTIFIER + S_FLOATCONST = 31, // FLOATCONST + S_INTCONST = 32, // INTCONST + S_LETTER = 33, // LETTER + S_EOL = 34, // EOL + S_COMMENT = 35, // COMMENT + S_BLANK = 36, // BLANK + S_CONST = 37, // CONST + S_BREAK = 38, // BREAK + S_CONTINUE = 39, // CONTINUE + S_NOT = 40, // NOT + S_AND = 41, // AND + S_OR = 42, // OR + S_MOD = 43, // MOD + S_FLOAT = 44, // FLOAT + S_LOGICAND = 45, // LOGICAND + S_LOGICOR = 46, // LOGICOR + S_LT = 47, // LT + S_STRINGCONST = 48, // STRINGCONST + S_LRBRACKET = 49, // LRBRACKET + S_UPLUS = 50, // UPLUS + S_UMINUS = 51, // UMINUS + S_UNOT = 52, // UNOT + S_YYACCEPT = 53, // $accept + S_Begin = 54, // Begin + S_CompUnit = 55, // CompUnit + S_GlobalDecl = 56, // GlobalDecl + S_ConstDecl = 57, // ConstDecl + S_ConstDefList = 58, // ConstDefList + S_BType = 59, // BType + S_ConstDef = 60, // ConstDef + S_VarDecl = 61, // VarDecl + S_VarDefList = 62, // VarDefList + S_VarDef = 63, // VarDef + S_ArrayExpList = 64, // ArrayExpList + S_InitVal = 65, // InitVal + S_InitValList = 66, // InitValList + S_CommaInitValList = 67, // CommaInitValList + S_ExpList = 68, // ExpList + S_CommaExpList = 69, // CommaExpList + S_FuncFParam = 70, // FuncFParam + S_FParamList = 71, // FParamList + S_CommaFParamList = 72, // CommaFParamList + S_FuncDef = 73, // FuncDef + S_Block = 74, // Block + S_BlockItemList = 75, // BlockItemList + S_BlockItem = 76, // BlockItem + S_Stmt = 77, // Stmt + S_IfStmt = 78, // IfStmt + S_OptionRet = 79, // OptionRet + S_LVal = 80, // LVal + S_Exp = 81, // Exp + S_RelExp = 82, // RelExp + S_EqExp = 83, // EqExp + S_LAndExp = 84, // LAndExp + S_LOrExp = 85, // LOrExp + S_CondExp = 86, // CondExp + S_Number = 87 // Number + }; + }; + + /// (Internal) symbol kind. + typedef symbol_kind::symbol_kind_type symbol_kind_type; + + /// The number of tokens. + static const symbol_kind_type YYNTOKENS = symbol_kind::YYNTOKENS; + + /// A complete symbol. + /// + /// Expects its Base type to provide access to the symbol kind + /// via kind (). + /// + /// Provide access to semantic value and location. + template + struct basic_symbol : Base + { + /// Alias to Base. + typedef Base super_type; + + /// Default constructor. + basic_symbol () + : value () + , location () + {} + +#if 201103L <= YY_CPLUSPLUS + /// Move constructor. + basic_symbol (basic_symbol&& that) + : Base (std::move (that)) + , value () + , location (std::move (that.location)) + { + switch (this->kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SyntaxTree::Assembly* > (std::move (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.move< SyntaxTree::BlockStmt* > (std::move (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SyntaxTree::Expr* > (std::move (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SyntaxTree::FuncDef* > (std::move (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SyntaxTree::FuncParam* > (std::move (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SyntaxTree::InitVal* > (std::move (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SyntaxTree::LVal* > (std::move (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.move< SyntaxTree::Literal* > (std::move (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SyntaxTree::PtrList > (std::move (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SyntaxTree::PtrList > (std::move (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SyntaxTree::PtrList > (std::move (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SyntaxTree::PtrList > (std::move (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SyntaxTree::PtrList > (std::move (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SyntaxTree::Stmt* > (std::move (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.move< SyntaxTree::Type > (std::move (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SyntaxTree::VarDef* > (std::move (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (std::move (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (std::move (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (std::move (that.value)); + break; + + default: + break; + } + + } +#endif + + /// Copy constructor. + basic_symbol (const basic_symbol& that); + + /// Constructors for typed symbols. +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, location_type&& l) + : Base (t) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const location_type& l) + : Base (t) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::Assembly*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::Assembly*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::BlockStmt*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::BlockStmt*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::Expr*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::Expr*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::FuncDef*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::FuncDef*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::FuncParam*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::FuncParam*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::InitVal*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::InitVal*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::LVal*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::LVal*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::Literal*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::Literal*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::PtrList&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::PtrList& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::PtrList&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::PtrList& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::PtrList&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::PtrList& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::PtrList&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::PtrList& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::PtrList&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::PtrList& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::Stmt*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::Stmt*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::Type&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::Type& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SyntaxTree::VarDef*&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SyntaxTree::VarDef*& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, float&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const float& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, int&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const int& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, std::string&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const std::string& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + + /// Destroy the symbol. + ~basic_symbol () + { + clear (); + } + + /// Destroy contents, and record that is empty. + void clear () YY_NOEXCEPT + { + // User destructor. + symbol_kind_type yykind = this->kind (); + basic_symbol& yysym = *this; + (void) yysym; + switch (yykind) + { + default: + break; + } + + // Value type destructor. +switch (yykind) + { + case symbol_kind::S_CompUnit: // CompUnit + value.template destroy< SyntaxTree::Assembly* > (); + break; + + case symbol_kind::S_Block: // Block + value.template destroy< SyntaxTree::BlockStmt* > (); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.template destroy< SyntaxTree::Expr* > (); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.template destroy< SyntaxTree::FuncDef* > (); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.template destroy< SyntaxTree::FuncParam* > (); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.template destroy< SyntaxTree::InitVal* > (); + break; + + case symbol_kind::S_LVal: // LVal + value.template destroy< SyntaxTree::LVal* > (); + break; + + case symbol_kind::S_Number: // Number + value.template destroy< SyntaxTree::Literal* > (); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.template destroy< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.template destroy< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.template destroy< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.template destroy< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.template destroy< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.template destroy< SyntaxTree::Stmt* > (); + break; + + case symbol_kind::S_BType: // BType + value.template destroy< SyntaxTree::Type > (); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.template destroy< SyntaxTree::VarDef* > (); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.template destroy< float > (); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.template destroy< int > (); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.template destroy< std::string > (); + break; + + default: + break; + } + + Base::clear (); + } + + /// The user-facing name of this symbol. + std::string name () const YY_NOEXCEPT + { + return SysYParser::symbol_name (this->kind ()); + } + + /// Backward compatibility (Bison 3.6). + symbol_kind_type type_get () const YY_NOEXCEPT; + + /// Whether empty. + bool empty () const YY_NOEXCEPT; + + /// Destructive move, \a s is emptied into this. + void move (basic_symbol& s); + + /// The semantic value. + semantic_type value; + + /// The location. + location_type location; + + private: +#if YY_CPLUSPLUS < 201103L + /// Assignment operator. + basic_symbol& operator= (const basic_symbol& that); +#endif + }; + + /// Type access provider for token (enum) based symbols. + struct by_kind + { + /// Default constructor. + by_kind (); + +#if 201103L <= YY_CPLUSPLUS + /// Move constructor. + by_kind (by_kind&& that); +#endif + + /// Copy constructor. + by_kind (const by_kind& that); + + /// The symbol kind as needed by the constructor. + typedef token_kind_type kind_type; + + /// Constructor from (external) token numbers. + by_kind (kind_type t); + + /// Record that this symbol is empty. + void clear () YY_NOEXCEPT; + + /// Steal the symbol kind from \a that. + void move (by_kind& that); + + /// The (internal) type number (corresponding to \a type). + /// \a empty when empty. + symbol_kind_type kind () const YY_NOEXCEPT; + + /// Backward compatibility (Bison 3.6). + symbol_kind_type type_get () const YY_NOEXCEPT; + + /// The symbol kind. + /// \a S_YYEMPTY when empty. + symbol_kind_type kind_; + }; + + /// Backward compatibility for a private implementation detail (Bison 3.6). + typedef by_kind by_type; + + /// "External" symbols: returned by the scanner. + struct symbol_type : basic_symbol + { + /// Superclass. + typedef basic_symbol super_type; + + /// Empty symbol. + symbol_type () {} + + /// Constructor for valueless symbols, and symbols from each type. +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, location_type l) + : super_type(token_type (tok), std::move (l)) +#else + symbol_type (int tok, const location_type& l) + : super_type(token_type (tok), l) +#endif + { + YY_ASSERT (tok == token::TOK_YYEOF + || tok == token::TOK_YYerror + || (token::TOK_YYUNDEF <= tok && tok <= token::TOK_END) + || (token::TOK_ERROR <= tok && tok <= token::TOK_WHILE) + || (token::TOK_LETTER <= tok && tok <= token::TOK_LT) + || tok == token::TOK_LRBRACKET + || (token::TOK_UPLUS <= tok && tok <= token::TOK_UNOT)); + } +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, float v, location_type l) + : super_type(token_type (tok), std::move (v), std::move (l)) +#else + symbol_type (int tok, const float& v, const location_type& l) + : super_type(token_type (tok), v, l) +#endif + { + YY_ASSERT (tok == token::TOK_FLOATCONST); + } +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, int v, location_type l) + : super_type(token_type (tok), std::move (v), std::move (l)) +#else + symbol_type (int tok, const int& v, const location_type& l) + : super_type(token_type (tok), v, l) +#endif + { + YY_ASSERT (tok == token::TOK_INTCONST); + } +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, std::string v, location_type l) + : super_type(token_type (tok), std::move (v), std::move (l)) +#else + symbol_type (int tok, const std::string& v, const location_type& l) + : super_type(token_type (tok), v, l) +#endif + { + YY_ASSERT (tok == token::TOK_IDENTIFIER + || tok == token::TOK_STRINGCONST); + } + }; + + /// Build a parser object. + SysYParser (SysYDriver& driver_yyarg); + virtual ~SysYParser (); + +#if 201103L <= YY_CPLUSPLUS + /// Non copyable. + SysYParser (const SysYParser&) = delete; + /// Non copyable. + SysYParser& operator= (const SysYParser&) = delete; +#endif + + /// Parse. An alias for parse (). + /// \returns 0 iff parsing succeeded. + int operator() (); + + /// Parse. + /// \returns 0 iff parsing succeeded. + virtual int parse (); + +#if YYDEBUG + /// The current debugging stream. + std::ostream& debug_stream () const YY_ATTRIBUTE_PURE; + /// Set the current debugging stream. + void set_debug_stream (std::ostream &); + + /// Type for debugging levels. + typedef int debug_level_type; + /// The current debugging level. + debug_level_type debug_level () const YY_ATTRIBUTE_PURE; + /// Set the current debugging level. + void set_debug_level (debug_level_type l); +#endif + + /// Report a syntax error. + /// \param loc where the syntax error is found. + /// \param msg a description of the syntax error. + virtual void error (const location_type& loc, const std::string& msg); + + /// Report a syntax error. + void error (const syntax_error& err); + + /// The user-facing name of the symbol whose (internal) number is + /// YYSYMBOL. No bounds checking. + static std::string symbol_name (symbol_kind_type yysymbol); + + // Implementation of make_symbol for each symbol type. +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_YYEOF (location_type l) + { + return symbol_type (token::TOK_YYEOF, std::move (l)); + } +#else + static + symbol_type + make_YYEOF (const location_type& l) + { + return symbol_type (token::TOK_YYEOF, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_YYerror (location_type l) + { + return symbol_type (token::TOK_YYerror, std::move (l)); + } +#else + static + symbol_type + make_YYerror (const location_type& l) + { + return symbol_type (token::TOK_YYerror, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_YYUNDEF (location_type l) + { + return symbol_type (token::TOK_YYUNDEF, std::move (l)); + } +#else + static + symbol_type + make_YYUNDEF (const location_type& l) + { + return symbol_type (token::TOK_YYUNDEF, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_END (location_type l) + { + return symbol_type (token::TOK_END, std::move (l)); + } +#else + static + symbol_type + make_END (const location_type& l) + { + return symbol_type (token::TOK_END, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_ERROR (location_type l) + { + return symbol_type (token::TOK_ERROR, std::move (l)); + } +#else + static + symbol_type + make_ERROR (const location_type& l) + { + return symbol_type (token::TOK_ERROR, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_PLUS (location_type l) + { + return symbol_type (token::TOK_PLUS, std::move (l)); + } +#else + static + symbol_type + make_PLUS (const location_type& l) + { + return symbol_type (token::TOK_PLUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MINUS (location_type l) + { + return symbol_type (token::TOK_MINUS, std::move (l)); + } +#else + static + symbol_type + make_MINUS (const location_type& l) + { + return symbol_type (token::TOK_MINUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MULTIPLY (location_type l) + { + return symbol_type (token::TOK_MULTIPLY, std::move (l)); + } +#else + static + symbol_type + make_MULTIPLY (const location_type& l) + { + return symbol_type (token::TOK_MULTIPLY, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_DIVIDE (location_type l) + { + return symbol_type (token::TOK_DIVIDE, std::move (l)); + } +#else + static + symbol_type + make_DIVIDE (const location_type& l) + { + return symbol_type (token::TOK_DIVIDE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MODULO (location_type l) + { + return symbol_type (token::TOK_MODULO, std::move (l)); + } +#else + static + symbol_type + make_MODULO (const location_type& l) + { + return symbol_type (token::TOK_MODULO, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LTE (location_type l) + { + return symbol_type (token::TOK_LTE, std::move (l)); + } +#else + static + symbol_type + make_LTE (const location_type& l) + { + return symbol_type (token::TOK_LTE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_GT (location_type l) + { + return symbol_type (token::TOK_GT, std::move (l)); + } +#else + static + symbol_type + make_GT (const location_type& l) + { + return symbol_type (token::TOK_GT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_GTE (location_type l) + { + return symbol_type (token::TOK_GTE, std::move (l)); + } +#else + static + symbol_type + make_GTE (const location_type& l) + { + return symbol_type (token::TOK_GTE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_EQ (location_type l) + { + return symbol_type (token::TOK_EQ, std::move (l)); + } +#else + static + symbol_type + make_EQ (const location_type& l) + { + return symbol_type (token::TOK_EQ, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_NEQ (location_type l) + { + return symbol_type (token::TOK_NEQ, std::move (l)); + } +#else + static + symbol_type + make_NEQ (const location_type& l) + { + return symbol_type (token::TOK_NEQ, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_ASSIGN (location_type l) + { + return symbol_type (token::TOK_ASSIGN, std::move (l)); + } +#else + static + symbol_type + make_ASSIGN (const location_type& l) + { + return symbol_type (token::TOK_ASSIGN, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_SEMICOLON (location_type l) + { + return symbol_type (token::TOK_SEMICOLON, std::move (l)); + } +#else + static + symbol_type + make_SEMICOLON (const location_type& l) + { + return symbol_type (token::TOK_SEMICOLON, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_COMMA (location_type l) + { + return symbol_type (token::TOK_COMMA, std::move (l)); + } +#else + static + symbol_type + make_COMMA (const location_type& l) + { + return symbol_type (token::TOK_COMMA, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LPARENTHESE (location_type l) + { + return symbol_type (token::TOK_LPARENTHESE, std::move (l)); + } +#else + static + symbol_type + make_LPARENTHESE (const location_type& l) + { + return symbol_type (token::TOK_LPARENTHESE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RPARENTHESE (location_type l) + { + return symbol_type (token::TOK_RPARENTHESE, std::move (l)); + } +#else + static + symbol_type + make_RPARENTHESE (const location_type& l) + { + return symbol_type (token::TOK_RPARENTHESE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LBRACKET (location_type l) + { + return symbol_type (token::TOK_LBRACKET, std::move (l)); + } +#else + static + symbol_type + make_LBRACKET (const location_type& l) + { + return symbol_type (token::TOK_LBRACKET, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RBRACKET (location_type l) + { + return symbol_type (token::TOK_RBRACKET, std::move (l)); + } +#else + static + symbol_type + make_RBRACKET (const location_type& l) + { + return symbol_type (token::TOK_RBRACKET, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LBRACE (location_type l) + { + return symbol_type (token::TOK_LBRACE, std::move (l)); + } +#else + static + symbol_type + make_LBRACE (const location_type& l) + { + return symbol_type (token::TOK_LBRACE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RBRACE (location_type l) + { + return symbol_type (token::TOK_RBRACE, std::move (l)); + } +#else + static + symbol_type + make_RBRACE (const location_type& l) + { + return symbol_type (token::TOK_RBRACE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_ELSE (location_type l) + { + return symbol_type (token::TOK_ELSE, std::move (l)); + } +#else + static + symbol_type + make_ELSE (const location_type& l) + { + return symbol_type (token::TOK_ELSE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_IF (location_type l) + { + return symbol_type (token::TOK_IF, std::move (l)); + } +#else + static + symbol_type + make_IF (const location_type& l) + { + return symbol_type (token::TOK_IF, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_INT (location_type l) + { + return symbol_type (token::TOK_INT, std::move (l)); + } +#else + static + symbol_type + make_INT (const location_type& l) + { + return symbol_type (token::TOK_INT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RETURN (location_type l) + { + return symbol_type (token::TOK_RETURN, std::move (l)); + } +#else + static + symbol_type + make_RETURN (const location_type& l) + { + return symbol_type (token::TOK_RETURN, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_VOID (location_type l) + { + return symbol_type (token::TOK_VOID, std::move (l)); + } +#else + static + symbol_type + make_VOID (const location_type& l) + { + return symbol_type (token::TOK_VOID, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_WHILE (location_type l) + { + return symbol_type (token::TOK_WHILE, std::move (l)); + } +#else + static + symbol_type + make_WHILE (const location_type& l) + { + return symbol_type (token::TOK_WHILE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_IDENTIFIER (std::string v, location_type l) + { + return symbol_type (token::TOK_IDENTIFIER, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_IDENTIFIER (const std::string& v, const location_type& l) + { + return symbol_type (token::TOK_IDENTIFIER, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_FLOATCONST (float v, location_type l) + { + return symbol_type (token::TOK_FLOATCONST, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_FLOATCONST (const float& v, const location_type& l) + { + return symbol_type (token::TOK_FLOATCONST, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_INTCONST (int v, location_type l) + { + return symbol_type (token::TOK_INTCONST, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_INTCONST (const int& v, const location_type& l) + { + return symbol_type (token::TOK_INTCONST, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LETTER (location_type l) + { + return symbol_type (token::TOK_LETTER, std::move (l)); + } +#else + static + symbol_type + make_LETTER (const location_type& l) + { + return symbol_type (token::TOK_LETTER, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_EOL (location_type l) + { + return symbol_type (token::TOK_EOL, std::move (l)); + } +#else + static + symbol_type + make_EOL (const location_type& l) + { + return symbol_type (token::TOK_EOL, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_COMMENT (location_type l) + { + return symbol_type (token::TOK_COMMENT, std::move (l)); + } +#else + static + symbol_type + make_COMMENT (const location_type& l) + { + return symbol_type (token::TOK_COMMENT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_BLANK (location_type l) + { + return symbol_type (token::TOK_BLANK, std::move (l)); + } +#else + static + symbol_type + make_BLANK (const location_type& l) + { + return symbol_type (token::TOK_BLANK, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_CONST (location_type l) + { + return symbol_type (token::TOK_CONST, std::move (l)); + } +#else + static + symbol_type + make_CONST (const location_type& l) + { + return symbol_type (token::TOK_CONST, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_BREAK (location_type l) + { + return symbol_type (token::TOK_BREAK, std::move (l)); + } +#else + static + symbol_type + make_BREAK (const location_type& l) + { + return symbol_type (token::TOK_BREAK, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_CONTINUE (location_type l) + { + return symbol_type (token::TOK_CONTINUE, std::move (l)); + } +#else + static + symbol_type + make_CONTINUE (const location_type& l) + { + return symbol_type (token::TOK_CONTINUE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_NOT (location_type l) + { + return symbol_type (token::TOK_NOT, std::move (l)); + } +#else + static + symbol_type + make_NOT (const location_type& l) + { + return symbol_type (token::TOK_NOT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_AND (location_type l) + { + return symbol_type (token::TOK_AND, std::move (l)); + } +#else + static + symbol_type + make_AND (const location_type& l) + { + return symbol_type (token::TOK_AND, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_OR (location_type l) + { + return symbol_type (token::TOK_OR, std::move (l)); + } +#else + static + symbol_type + make_OR (const location_type& l) + { + return symbol_type (token::TOK_OR, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MOD (location_type l) + { + return symbol_type (token::TOK_MOD, std::move (l)); + } +#else + static + symbol_type + make_MOD (const location_type& l) + { + return symbol_type (token::TOK_MOD, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_FLOAT (location_type l) + { + return symbol_type (token::TOK_FLOAT, std::move (l)); + } +#else + static + symbol_type + make_FLOAT (const location_type& l) + { + return symbol_type (token::TOK_FLOAT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LOGICAND (location_type l) + { + return symbol_type (token::TOK_LOGICAND, std::move (l)); + } +#else + static + symbol_type + make_LOGICAND (const location_type& l) + { + return symbol_type (token::TOK_LOGICAND, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LOGICOR (location_type l) + { + return symbol_type (token::TOK_LOGICOR, std::move (l)); + } +#else + static + symbol_type + make_LOGICOR (const location_type& l) + { + return symbol_type (token::TOK_LOGICOR, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LT (location_type l) + { + return symbol_type (token::TOK_LT, std::move (l)); + } +#else + static + symbol_type + make_LT (const location_type& l) + { + return symbol_type (token::TOK_LT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_STRINGCONST (std::string v, location_type l) + { + return symbol_type (token::TOK_STRINGCONST, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_STRINGCONST (const std::string& v, const location_type& l) + { + return symbol_type (token::TOK_STRINGCONST, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LRBRACKET (location_type l) + { + return symbol_type (token::TOK_LRBRACKET, std::move (l)); + } +#else + static + symbol_type + make_LRBRACKET (const location_type& l) + { + return symbol_type (token::TOK_LRBRACKET, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_UPLUS (location_type l) + { + return symbol_type (token::TOK_UPLUS, std::move (l)); + } +#else + static + symbol_type + make_UPLUS (const location_type& l) + { + return symbol_type (token::TOK_UPLUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_UMINUS (location_type l) + { + return symbol_type (token::TOK_UMINUS, std::move (l)); + } +#else + static + symbol_type + make_UMINUS (const location_type& l) + { + return symbol_type (token::TOK_UMINUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_UNOT (location_type l) + { + return symbol_type (token::TOK_UNOT, std::move (l)); + } +#else + static + symbol_type + make_UNOT (const location_type& l) + { + return symbol_type (token::TOK_UNOT, l); + } +#endif + + + class context + { + public: + context (const SysYParser& yyparser, const symbol_type& yyla); + const symbol_type& lookahead () const YY_NOEXCEPT { return yyla_; } + symbol_kind_type token () const YY_NOEXCEPT { return yyla_.kind (); } + const location_type& location () const YY_NOEXCEPT { return yyla_.location; } + + /// Put in YYARG at most YYARGN of the expected tokens, and return the + /// number of tokens stored in YYARG. If YYARG is null, return the + /// number of expected tokens (guaranteed to be less than YYNTOKENS). + int expected_tokens (symbol_kind_type yyarg[], int yyargn) const; + + private: + const SysYParser& yyparser_; + const symbol_type& yyla_; + }; + + private: +#if YY_CPLUSPLUS < 201103L + /// Non copyable. + SysYParser (const SysYParser&); + /// Non copyable. + SysYParser& operator= (const SysYParser&); +#endif + + + /// Stored state numbers (used for stacks). + typedef unsigned char state_type; + + /// The arguments of the error message. + int yy_syntax_error_arguments_ (const context& yyctx, + symbol_kind_type yyarg[], int yyargn) const; + + /// Generate an error message. + /// \param yyctx the context in which the error occurred. + virtual std::string yysyntax_error_ (const context& yyctx) const; + /// Compute post-reduction state. + /// \param yystate the current state + /// \param yysym the nonterminal to push on the stack + static state_type yy_lr_goto_state_ (state_type yystate, int yysym); + + /// Whether the given \c yypact_ value indicates a defaulted state. + /// \param yyvalue the value to check + static bool yy_pact_value_is_default_ (int yyvalue); + + /// Whether the given \c yytable_ value indicates a syntax error. + /// \param yyvalue the value to check + static bool yy_table_value_is_error_ (int yyvalue); + + static const signed char yypact_ninf_; + static const signed char yytable_ninf_; + + /// Convert a scanner token kind \a t to a symbol kind. + /// In theory \a t should be a token_kind_type, but character literals + /// are valid, yet not members of the token_type enum. + static symbol_kind_type yytranslate_ (int t); + + /// Convert the symbol name \a n to a form suitable for a diagnostic. + static std::string yytnamerr_ (const char *yystr); + + /// For a symbol, its name in clear. + static const char* const yytname_[]; + + + // Tables. + // YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing + // STATE-NUM. + static const short yypact_[]; + + // YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. + // Performed when YYTABLE does not specify something else to do. Zero + // means the default is an error. + static const signed char yydefact_[]; + + // YYPGOTO[NTERM-NUM]. + static const short yypgoto_[]; + + // YYDEFGOTO[NTERM-NUM]. + static const signed char yydefgoto_[]; + + // YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If + // positive, shift that token. If negative, reduce the rule whose + // number is the opposite. If YYTABLE_NINF, syntax error. + static const short yytable_[]; + + static const unsigned char yycheck_[]; + + // YYSTOS[STATE-NUM] -- The (internal number of the) accessing + // symbol of state STATE-NUM. + static const signed char yystos_[]; + + // YYR1[YYN] -- Symbol number of symbol that rule YYN derives. + static const signed char yyr1_[]; + + // YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. + static const signed char yyr2_[]; + + +#if YYDEBUG + // YYRLINE[YYN] -- Source line where rule number YYN was defined. + static const short yyrline_[]; + /// Report on the debug stream that the rule \a r is going to be reduced. + virtual void yy_reduce_print_ (int r) const; + /// Print the state stack on the debug stream. + virtual void yy_stack_print_ () const; + + /// Debugging level. + int yydebug_; + /// Debug stream. + std::ostream* yycdebug_; + + /// \brief Display a symbol kind, value and location. + /// \param yyo The output stream. + /// \param yysym The symbol. + template + void yy_print_ (std::ostream& yyo, const basic_symbol& yysym) const; +#endif + + /// \brief Reclaim the memory associated to a symbol. + /// \param yymsg Why this token is reclaimed. + /// If null, print nothing. + /// \param yysym The symbol. + template + void yy_destroy_ (const char* yymsg, basic_symbol& yysym) const; + + private: + /// Type access provider for state based symbols. + struct by_state + { + /// Default constructor. + by_state () YY_NOEXCEPT; + + /// The symbol kind as needed by the constructor. + typedef state_type kind_type; + + /// Constructor. + by_state (kind_type s) YY_NOEXCEPT; + + /// Copy constructor. + by_state (const by_state& that) YY_NOEXCEPT; + + /// Record that this symbol is empty. + void clear () YY_NOEXCEPT; + + /// Steal the symbol kind from \a that. + void move (by_state& that); + + /// The symbol kind (corresponding to \a state). + /// \a symbol_kind::S_YYEMPTY when empty. + symbol_kind_type kind () const YY_NOEXCEPT; + + /// The state number used to denote an empty symbol. + /// We use the initial state, as it does not have a value. + enum { empty_state = 0 }; + + /// The state. + /// \a empty when empty. + state_type state; + }; + + /// "Internal" symbol: element of the stack. + struct stack_symbol_type : basic_symbol + { + /// Superclass. + typedef basic_symbol super_type; + /// Construct an empty symbol. + stack_symbol_type (); + /// Move or copy construction. + stack_symbol_type (YY_RVREF (stack_symbol_type) that); + /// Steal the contents from \a sym to build this. + stack_symbol_type (state_type s, YY_MOVE_REF (symbol_type) sym); +#if YY_CPLUSPLUS < 201103L + /// Assignment, needed by push_back by some old implementations. + /// Moves the contents of that. + stack_symbol_type& operator= (stack_symbol_type& that); + + /// Assignment, needed by push_back by other implementations. + /// Needed by some other old implementations. + stack_symbol_type& operator= (const stack_symbol_type& that); +#endif + }; + + /// A stack with random access from its top. + template > + class stack + { + public: + // Hide our reversed order. + typedef typename S::iterator iterator; + typedef typename S::const_iterator const_iterator; + typedef typename S::size_type size_type; + typedef typename std::ptrdiff_t index_type; + + stack (size_type n = 200) + : seq_ (n) + {} + +#if 201103L <= YY_CPLUSPLUS + /// Non copyable. + stack (const stack&) = delete; + /// Non copyable. + stack& operator= (const stack&) = delete; +#endif + + /// Random access. + /// + /// Index 0 returns the topmost element. + const T& + operator[] (index_type i) const + { + return seq_[size_type (size () - 1 - i)]; + } + + /// Random access. + /// + /// Index 0 returns the topmost element. + T& + operator[] (index_type i) + { + return seq_[size_type (size () - 1 - i)]; + } + + /// Steal the contents of \a t. + /// + /// Close to move-semantics. + void + push (YY_MOVE_REF (T) t) + { + seq_.push_back (T ()); + operator[] (0).move (t); + } + + /// Pop elements from the stack. + void + pop (std::ptrdiff_t n = 1) YY_NOEXCEPT + { + for (; 0 < n; --n) + seq_.pop_back (); + } + + /// Pop all elements from the stack. + void + clear () YY_NOEXCEPT + { + seq_.clear (); + } + + /// Number of elements on the stack. + index_type + size () const YY_NOEXCEPT + { + return index_type (seq_.size ()); + } + + /// Iterator on top of the stack (going downwards). + const_iterator + begin () const YY_NOEXCEPT + { + return seq_.begin (); + } + + /// Bottom of the stack. + const_iterator + end () const YY_NOEXCEPT + { + return seq_.end (); + } + + /// Present a slice of the top of a stack. + class slice + { + public: + slice (const stack& stack, index_type range) + : stack_ (stack) + , range_ (range) + {} + + const T& + operator[] (index_type i) const + { + return stack_[range_ - i]; + } + + private: + const stack& stack_; + index_type range_; + }; + + private: +#if YY_CPLUSPLUS < 201103L + /// Non copyable. + stack (const stack&); + /// Non copyable. + stack& operator= (const stack&); +#endif + /// The wrapped container. + S seq_; + }; + + + /// Stack type. + typedef stack stack_type; + + /// The stack. + stack_type yystack_; + + /// Push a new state on the stack. + /// \param m a debug message to display + /// if null, no trace is output. + /// \param sym the symbol + /// \warning the contents of \a s.value is stolen. + void yypush_ (const char* m, YY_MOVE_REF (stack_symbol_type) sym); + + /// Push a new look ahead token on the state on the stack. + /// \param m a debug message to display + /// if null, no trace is output. + /// \param s the state + /// \param sym the symbol (for its value and location). + /// \warning the contents of \a sym.value is stolen. + void yypush_ (const char* m, state_type s, YY_MOVE_REF (symbol_type) sym); + + /// Pop \a n symbols from the stack. + void yypop_ (int n = 1); + + /// Constants. + enum + { + yylast_ = 194, ///< Last index in yytable_. + yynnts_ = 35, ///< Number of nonterminal symbols. + yyfinal_ = 14 ///< Termination state number. + }; + + + // User arguments. + SysYDriver& driver; + + }; + + inline + SysYParser::symbol_kind_type + SysYParser::yytranslate_ (int t) + { + // YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to + // TOKEN-NUM as returned by yylex. + static + const signed char + translate_table[] = + { + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 1, 2, 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, 2, 3, 50, 51, 52 + }; + // Last valid token kind. + const int code_max = 308; + + if (t <= 0) + return symbol_kind::S_YYEOF; + else if (t <= code_max) + return YY_CAST (symbol_kind_type, translate_table[t]); + else + return symbol_kind::S_YYUNDEF; + } + + // basic_symbol. + template + SysYParser::basic_symbol::basic_symbol (const basic_symbol& that) + : Base (that) + , value () + , location (that.location) + { + switch (this->kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.copy< SyntaxTree::Assembly* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.copy< SyntaxTree::BlockStmt* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.copy< SyntaxTree::Expr* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.copy< SyntaxTree::FuncDef* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.copy< SyntaxTree::FuncParam* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.copy< SyntaxTree::InitVal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.copy< SyntaxTree::LVal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.copy< SyntaxTree::Literal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.copy< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.copy< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.copy< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.copy< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.copy< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.copy< SyntaxTree::Stmt* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.copy< SyntaxTree::Type > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.copy< SyntaxTree::VarDef* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.copy< float > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.copy< int > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.copy< std::string > (YY_MOVE (that.value)); + break; + + default: + break; + } + + } + + + + template + SysYParser::symbol_kind_type + SysYParser::basic_symbol::type_get () const YY_NOEXCEPT + { + return this->kind (); + } + + template + bool + SysYParser::basic_symbol::empty () const YY_NOEXCEPT + { + return this->kind () == symbol_kind::S_YYEMPTY; + } + + template + void + SysYParser::basic_symbol::move (basic_symbol& s) + { + super_type::move (s); + switch (this->kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SyntaxTree::Assembly* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_Block: // Block + value.move< SyntaxTree::BlockStmt* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SyntaxTree::Expr* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SyntaxTree::FuncDef* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SyntaxTree::FuncParam* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SyntaxTree::InitVal* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SyntaxTree::LVal* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_Number: // Number + value.move< SyntaxTree::Literal* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SyntaxTree::PtrList > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SyntaxTree::PtrList > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SyntaxTree::PtrList > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SyntaxTree::PtrList > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SyntaxTree::PtrList > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SyntaxTree::Stmt* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_BType: // BType + value.move< SyntaxTree::Type > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SyntaxTree::VarDef* > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (YY_MOVE (s.value)); + break; + + default: + break; + } + + location = YY_MOVE (s.location); + } + + // by_kind. + inline + SysYParser::by_kind::by_kind () + : kind_ (symbol_kind::S_YYEMPTY) + {} + +#if 201103L <= YY_CPLUSPLUS + inline + SysYParser::by_kind::by_kind (by_kind&& that) + : kind_ (that.kind_) + { + that.clear (); + } +#endif + + inline + SysYParser::by_kind::by_kind (const by_kind& that) + : kind_ (that.kind_) + {} + + inline + SysYParser::by_kind::by_kind (token_kind_type t) + : kind_ (yytranslate_ (t)) + {} + + inline + void + SysYParser::by_kind::clear () YY_NOEXCEPT + { + kind_ = symbol_kind::S_YYEMPTY; + } + + inline + void + SysYParser::by_kind::move (by_kind& that) + { + kind_ = that.kind_; + that.clear (); + } + + inline + SysYParser::symbol_kind_type + SysYParser::by_kind::kind () const YY_NOEXCEPT + { + return kind_; + } + + inline + SysYParser::symbol_kind_type + SysYParser::by_kind::type_get () const YY_NOEXCEPT + { + return this->kind (); + } + +} // yy +#line 2877 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.h" + + + + +#endif // !YY_YY_HOME_HZQ_SYSYF_IR_LAB_2021_SYSYCOMPILER_IR_LAB_BUILD_SYSYPARSER_H_INCLUDED diff --git a/include/Grammar/location.hh b/include/Grammar/location.hh new file mode 100644 index 0000000..f171cd1 --- /dev/null +++ b/include/Grammar/location.hh @@ -0,0 +1,304 @@ +// A Bison parser, made by GNU Bison 3.7.6. + +// Locations for Bison parsers in C++ + +// Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// As a special exception, you may create a larger work that contains +// part or all of the Bison parser skeleton and distribute that work +// under terms of your choice, so long as that work isn't itself a +// parser generator using the skeleton or a modified version thereof +// as a parser skeleton. Alternatively, if you modify or redistribute +// the parser skeleton itself, you may (at your option) remove this +// special exception, which will cause the skeleton and the resulting +// Bison output files to be licensed under the GNU General Public +// License without this special exception. + +// This special exception was added by the Free Software Foundation in +// version 2.2 of Bison. + +/** + ** \file /home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/location.hh + ** Define the yy::location class. + */ + +#ifndef YY_YY_HOME_HZQ_SYSYF_IR_LAB_2021_SYSYCOMPILER_IR_LAB_BUILD_LOCATION_HH_INCLUDED +# define YY_YY_HOME_HZQ_SYSYF_IR_LAB_2021_SYSYCOMPILER_IR_LAB_BUILD_LOCATION_HH_INCLUDED + +# include +# include + +# ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# else +# define YY_NULLPTR ((void*)0) +# endif +# endif + +namespace yy { +#line 58 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/location.hh" + + /// A point in a source file. + class position + { + public: + /// Type for file name. + typedef const std::string filename_type; + /// Type for line and column numbers. + typedef int counter_type; + + /// Construct a position. + explicit position (filename_type* f = YY_NULLPTR, + counter_type l = 1, + counter_type c = 1) + : filename (f) + , line (l) + , column (c) + {} + + + /// Initialization. + void initialize (filename_type* fn = YY_NULLPTR, + counter_type l = 1, + counter_type c = 1) + { + filename = fn; + line = l; + column = c; + } + + /** \name Line and Column related manipulators + ** \{ */ + /// (line related) Advance to the COUNT next lines. + void lines (counter_type count = 1) + { + if (count) + { + column = 1; + line = add_ (line, count, 1); + } + } + + /// (column related) Advance to the COUNT next columns. + void columns (counter_type count = 1) + { + column = add_ (column, count, 1); + } + /** \} */ + + /// File name to which this position refers. + filename_type* filename; + /// Current line number. + counter_type line; + /// Current column number. + counter_type column; + + private: + /// Compute max (min, lhs+rhs). + static counter_type add_ (counter_type lhs, counter_type rhs, counter_type min) + { + return lhs + rhs < min ? min : lhs + rhs; + } + }; + + /// Add \a width columns, in place. + inline position& + operator+= (position& res, position::counter_type width) + { + res.columns (width); + return res; + } + + /// Add \a width columns. + inline position + operator+ (position res, position::counter_type width) + { + return res += width; + } + + /// Subtract \a width columns, in place. + inline position& + operator-= (position& res, position::counter_type width) + { + return res += -width; + } + + /// Subtract \a width columns. + inline position + operator- (position res, position::counter_type width) + { + return res -= width; + } + + /** \brief Intercept output stream redirection. + ** \param ostr the destination output stream + ** \param pos a reference to the position to redirect + */ + template + std::basic_ostream& + operator<< (std::basic_ostream& ostr, const position& pos) + { + if (pos.filename) + ostr << *pos.filename << ':'; + return ostr << pos.line << '.' << pos.column; + } + + /// Two points in a source file. + class location + { + public: + /// Type for file name. + typedef position::filename_type filename_type; + /// Type for line and column numbers. + typedef position::counter_type counter_type; + + /// Construct a location from \a b to \a e. + location (const position& b, const position& e) + : begin (b) + , end (e) + {} + + /// Construct a 0-width location in \a p. + explicit location (const position& p = position ()) + : begin (p) + , end (p) + {} + + /// Construct a 0-width location in \a f, \a l, \a c. + explicit location (filename_type* f, + counter_type l = 1, + counter_type c = 1) + : begin (f, l, c) + , end (f, l, c) + {} + + + /// Initialization. + void initialize (filename_type* f = YY_NULLPTR, + counter_type l = 1, + counter_type c = 1) + { + begin.initialize (f, l, c); + end = begin; + } + + /** \name Line and Column related manipulators + ** \{ */ + public: + /// Reset initial location to final location. + void step () + { + begin = end; + } + + /// Extend the current location to the COUNT next columns. + void columns (counter_type count = 1) + { + end += count; + } + + /// Extend the current location to the COUNT next lines. + void lines (counter_type count = 1) + { + end.lines (count); + } + /** \} */ + + + public: + /// Beginning of the located region. + position begin; + /// End of the located region. + position end; + }; + + /// Join two locations, in place. + inline location& + operator+= (location& res, const location& end) + { + res.end = end.end; + return res; + } + + /// Join two locations. + inline location + operator+ (location res, const location& end) + { + return res += end; + } + + /// Add \a width columns to the end position, in place. + inline location& + operator+= (location& res, location::counter_type width) + { + res.columns (width); + return res; + } + + /// Add \a width columns to the end position. + inline location + operator+ (location res, location::counter_type width) + { + return res += width; + } + + /// Subtract \a width columns to the end position, in place. + inline location& + operator-= (location& res, location::counter_type width) + { + return res += -width; + } + + /// Subtract \a width columns to the end position. + inline location + operator- (location res, location::counter_type width) + { + return res -= width; + } + + /** \brief Intercept output stream redirection. + ** \param ostr the destination output stream + ** \param loc a reference to the location to redirect + ** + ** Avoid duplicate information. + */ + template + std::basic_ostream& + operator<< (std::basic_ostream& ostr, const location& loc) + { + location::counter_type end_col + = 0 < loc.end.column ? loc.end.column - 1 : 0; + ostr << loc.begin; + if (loc.end.filename + && (!loc.begin.filename + || *loc.begin.filename != *loc.end.filename)) + ostr << '-' << loc.end.filename << ':' << loc.end.line << '.' << end_col; + else if (loc.begin.line < loc.end.line) + ostr << '-' << loc.end.line << '.' << end_col; + else if (loc.begin.column < end_col) + ostr << '-' << end_col; + return ostr; + } + +} // yy +#line 303 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/location.hh" + +#endif // !YY_YY_HOME_HZQ_SYSYF_IR_LAB_2021_SYSYCOMPILER_IR_LAB_BUILD_LOCATION_HH_INCLUDED diff --git a/include/Grammar/position.hh b/include/Grammar/position.hh new file mode 100644 index 0000000..6575075 --- /dev/null +++ b/include/Grammar/position.hh @@ -0,0 +1,11 @@ +// A Bison parser, made by GNU Bison 3.7.6. + +// Starting with Bison 3.2, this file is useless: the structure it +// used to define is now defined in "location.hh". +// +// To get rid of this file: +// 1. add '%require "3.2"' (or newer) to your grammar file +// 2. remove references to this file from your build system +// 3. if you used to include it, include "location.hh" instead. + +#include "location.hh" diff --git a/include/Grammar/stack.hh b/include/Grammar/stack.hh new file mode 100644 index 0000000..e6c46cc --- /dev/null +++ b/include/Grammar/stack.hh @@ -0,0 +1,8 @@ +// A Bison parser, made by GNU Bison 3.7.6. + +// Starting with Bison 3.2, this file is useless: the structure it +// used to define is now defined with the parser itself. +// +// To get rid of this file: +// 1. add '%require "3.2"' (or newer) to your grammar file +// 2. remove references to this file from your build system. diff --git a/include/SysYBuilder/SysYBuilder.hpp b/include/SysYBuilder/SysYBuilder.hpp new file mode 100644 index 0000000..8848367 --- /dev/null +++ b/include/SysYBuilder/SysYBuilder.hpp @@ -0,0 +1,217 @@ +#ifndef _SYSY_IR_BUILDER_HPP_ +#define _SYSY_IR_BUILDER_HPP_ +#include "BasicBlock.h" +#include "Constant.h" +#include "Function.h" +#include "IRBuilder.h" +#include "Module.h" +#include "Type.h" +#include +#include "SyntaxTree.h" + + +class Scope { +public: + // enter a new scope + void enter() { + name2var.push_back({}); + name2func.push_back({}); + } + + // exit a scope + void exit() { + name2var.pop_back(); + name2func.pop_back(); + } + + bool in_global() { + return name2var.size() == 1; + } + + // push a name to scope + // return true if successful + // return false if this name already exits + // but func name could be same with variable name + bool push(std::string name, Value *val) { + bool result; + if (dynamic_cast(val)){ + result = (name2func[name2func.size() - 1].insert({name, val})).second; + } + else{ + result = (name2var[name2var.size() - 1].insert({name, val})).second; + } + return result; + } + + Value* find(std::string name, bool isfunc) { + if (isfunc){ + for (auto s = name2func.rbegin(); s!= name2func.rend();s++) { + auto iter = s->find(name); + if (iter != s->end()) { + return iter->second; + } + } + } + else{ + for (auto s = name2var.rbegin(); s!= name2var.rend();s++) { + auto iter = s->find(name); + if (iter != s->end()) { + return iter->second; + } + } + } + return nullptr; + } + + +private: + std::vector> name2var; + std::vector> name2func; +}; + +class SysYBuilder: public SyntaxTree::Visitor +{ +private: + virtual void visit(SyntaxTree::InitVal &) override final; + virtual void visit(SyntaxTree::Assembly &) override final; + virtual void visit(SyntaxTree::FuncDef &) override final; + virtual void visit(SyntaxTree::VarDef &) override final; + virtual void visit(SyntaxTree::AssignStmt &) override final; + virtual void visit(SyntaxTree::ReturnStmt &) override final; + virtual void visit(SyntaxTree::BlockStmt &) override final; + virtual void visit(SyntaxTree::EmptyStmt &) override final; + virtual void visit(SyntaxTree::ExprStmt &) override final; + virtual void visit(SyntaxTree::UnaryCondExpr &) override final; + virtual void visit(SyntaxTree::BinaryCondExpr &) override final; + virtual void visit(SyntaxTree::BinaryExpr &) override final; + virtual void visit(SyntaxTree::UnaryExpr &) override final; + virtual void visit(SyntaxTree::LVal &) override final; + virtual void visit(SyntaxTree::Literal &) override final; + virtual void visit(SyntaxTree::FuncCallStmt &) override final; + virtual void visit(SyntaxTree::FuncParam &) override final; + virtual void visit(SyntaxTree::FuncFParamList &) override final; + virtual void visit(SyntaxTree::IfStmt &) override final; + virtual void visit(SyntaxTree::WhileStmt &) override final; + virtual void visit(SyntaxTree::BreakStmt &) override final; + virtual void visit(SyntaxTree::ContinueStmt &) override final; + + IRBuilder *builder; + Scope scope; + std::unique_ptr module; +public: + SysYBuilder(){ + module = std::unique_ptr(new Module("SysY code")); + builder = new IRBuilder(nullptr, module.get()); + auto TyVoid = Type::get_void_type(module.get()); + auto TyInt32 = Type::get_int32_type(module.get()); + auto TyInt32Ptr = Type::get_int32_ptr_type(module.get()); + auto TyFloat = Type::get_float_type(module.get()); + auto TyFloatPtr = Type::get_float_ptr_type(module.get()); + + auto input_type = FunctionType::get(TyInt32, {}); + auto get_int = + Function::create( + input_type, + "get_int", + module.get()); + + input_type = FunctionType::get(TyFloat, {}); + auto get_float = + Function::create( + input_type, + "get_float", + module.get()); + + input_type = FunctionType::get(TyInt32, {}); + auto get_char = + Function::create( + input_type, + "get_char", + module.get()); + + std::vector input_params; + std::vector().swap(input_params); + input_params.push_back(TyInt32Ptr); + input_type = FunctionType::get(TyInt32, input_params); + auto get_int_array = + Function::create( + input_type, + "get_int_array", + module.get()); + + std::vector().swap(input_params); + input_params.push_back(TyFloatPtr); + input_type = FunctionType::get(TyInt32, input_params); + auto get_float_array = + Function::create( + input_type, + "get_float_array", + module.get()); + + std::vector output_params; + std::vector().swap(output_params); + output_params.push_back(TyInt32); + auto output_type = FunctionType::get(TyVoid, output_params); + auto put_int = + Function::create( + output_type, + "put_int", + module.get()); + + std::vector().swap(output_params); + output_params.push_back(TyFloat); + output_type = FunctionType::get(TyVoid, output_params); + auto put_float = + Function::create( + output_type, + "put_float", + module.get()); + + std::vector().swap(output_params); + output_params.push_back(TyInt32); + output_type = FunctionType::get(TyVoid, output_params); + auto put_char = + Function::create( + output_type, + "put_char", + module.get()); + + std::vector().swap(output_params); + output_params.push_back(TyInt32); + output_params.push_back(TyInt32Ptr); + output_type = FunctionType::get(TyVoid, output_params); + auto put_int_array = + Function::create( + output_type, + "put_int_array", + module.get()); + + std::vector().swap(output_params); + output_params.push_back(TyInt32); + output_params.push_back(TyFloatPtr); + output_type = FunctionType::get(TyVoid, output_params); + auto put_float_array = + Function::create( + output_type, + "put_float_array", + module.get()); + + scope.enter(); + scope.push("getint", get_int); + scope.push("getfloat", get_float); + scope.push("getch", get_char); + scope.push("getarray", get_int_array); + scope.push("get_float_array", get_float_array); + scope.push("putint", put_int); + scope.push("putfloat", put_float); + scope.push("putch", put_char); + scope.push("putarray", put_int_array); + scope.push("putfloatarray", put_float_array); + } + std::unique_ptr getModule() { + return std::move(module); + } +}; + + +#endif // _SYSY_IR_BUILDER_HPP_ diff --git a/include/SysYIR/BasicBlock.h b/include/SysYIR/BasicBlock.h new file mode 100644 index 0000000..aa1fe26 --- /dev/null +++ b/include/SysYIR/BasicBlock.h @@ -0,0 +1,77 @@ +#ifndef _SYSY_BASICBLOCK_H_ +#define _SYSY_BASICBLOCK_H_ + +#include "Value.h" +#include "Instruction.h" +#include "Module.h" +#include "Function.h" + +#include +#include +#include + +class Function; +class Instruction; +class Module; + +class BasicBlock : public Value +{ +public: + static BasicBlock *create(Module *m, const std::string &name , + Function *parent ) { + auto prefix = name.empty() ? "" : "label_"; + return new BasicBlock(m, prefix + name, parent); + } + + // return parent, or null if none. + Function *get_parent() { return parent_; } + + Module *get_module(); + + /****************api about cfg****************/ + + std::list &get_pre_basic_blocks() { return pre_bbs_; } + std::list &get_succ_basic_blocks() { return succ_bbs_; } + void add_pre_basic_block(BasicBlock *bb) { pre_bbs_.push_back(bb); } + void add_succ_basic_block(BasicBlock *bb) { succ_bbs_.push_back(bb); } + + void remove_pre_basic_block(BasicBlock *bb) { pre_bbs_.remove(bb); } + void remove_succ_basic_block(BasicBlock *bb) { succ_bbs_.remove(bb); } + + /****************api about cfg****************/ + + /// Returns the terminator instruction if the block is well formed or null + /// if the block is not well formed. + const Instruction *get_terminator() const; + Instruction *get_terminator() { + return const_cast( + static_cast(this)->get_terminator()); + } + + void add_instruction(Instruction *instr); + void add_instruction(std::list::iterator instr_pos, Instruction *instr); + void add_instr_begin(Instruction *instr); + + std::list::iterator find_instruction(Instruction *instr); + + void delete_instr(Instruction *instr); + + bool empty() { return instr_list_.empty(); } + + int get_num_of_instr() { return instr_list_.size(); } + std::list &get_instructions() { return instr_list_; } + + void erase_from_parent(); + + virtual std::string print() override; + +private: + explicit BasicBlock(Module *m, const std::string &name , + Function *parent ); + std::list pre_bbs_; + std::list succ_bbs_; + std::list instr_list_; + Function *parent_; +}; + +#endif // _SYSY_BASICBLOCK_H_ \ No newline at end of file diff --git a/include/SysYIR/Constant.h b/include/SysYIR/Constant.h new file mode 100644 index 0000000..41b3e52 --- /dev/null +++ b/include/SysYIR/Constant.h @@ -0,0 +1,75 @@ +#ifndef _SYSY_CONSTANT_H_ +#define _SYSY_CONSTANT_H_ +#include "User.h" +#include "Value.h" +#include "Type.h" + +class Constant : public User +{ +private: + // int value; +public: + Constant(Type *ty, const std::string &name = "", unsigned num_ops = 0) + : User(ty, name, num_ops) {} + ~Constant() = default; +}; + +class ConstantInt : public Constant +{ +private: + int value_; + ConstantInt(Type* ty,int val) + : Constant(ty,"",0),value_(val) {} +public: + + static int get_value(ConstantInt *const_val) { return const_val->value_; } + int get_value() { return value_; } + static ConstantInt *get(int val, Module *m); + static ConstantInt *get(bool val, Module *m); + virtual std::string print() override; +}; + +class ConstantFloat : public Constant +{ +private: + float value_; + ConstantFloat(Type* ty,float val) + : Constant(ty,"",0),value_(val) {} +public: + + static float get_value(ConstantFloat *const_val) { return const_val->value_; } + float get_value() { return value_; } + static ConstantFloat *get(float val, Module *m); + virtual std::string print() override; +}; + +class ConstantArray : public Constant +{ +private: + std::vector const_array; + + ConstantArray(ArrayType *ty, const std::vector &val); +public: + + ~ConstantArray()=default; + + Constant* get_element_value(int index); + + unsigned get_size_of_array() { return const_array.size(); } + + static ConstantArray *get(ArrayType *ty, const std::vector &val); + + virtual std::string print() override; +}; + +class ConstantZero : public Constant +{ +private: + ConstantZero(Type *ty) + : Constant(ty,"",0) {} +public: + static ConstantZero *get(Type *ty, Module *m); + virtual std::string print() override; +}; + +#endif //_SYSY_CONSTANT_H_ diff --git a/include/SysYIR/Function.h b/include/SysYIR/Function.h new file mode 100644 index 0000000..106b5a8 --- /dev/null +++ b/include/SysYIR/Function.h @@ -0,0 +1,101 @@ +#ifndef _SYSY_FUNCTION_H_ +#define _SYSY_FUNCTION_H_ + +#include +#include +#include +#include +#ifdef DEBUG +#include +#endif +#include + +#include "User.h" +#include "Module.h" +#include "BasicBlock.h" +#include "Type.h" + +class Module; +class Argument; +class BasicBlock; +class Type; +class FunctionType; + +class Function : public Value +{ +public: + Function(FunctionType *ty, const std::string &name, Module *parent); + ~Function(); + static Function *create(FunctionType *ty, const std::string &name, Module *parent); + + FunctionType *get_function_type() const; + + Type *get_return_type() const; + + void add_basic_block(BasicBlock *bb); + + unsigned get_num_of_args() const; + unsigned get_num_basic_blocks() const; + + Module *get_parent() const; + + std::list::iterator arg_begin() { return arguments_.begin(); } + std::list::iterator arg_end() { return arguments_.end(); } + + void remove(BasicBlock* bb); + BasicBlock *get_entry_block() { return *basic_blocks_.begin(); } + + std::list &get_basic_blocks() { return basic_blocks_; } + std::list &get_args() { return arguments_; } + std::vector> &get_vreg_set(){ return vreg_set_;} + + bool is_declaration() { return basic_blocks_.empty(); } + void set_unused_reg_num(std::set& set){unused_reg_num_ = set;} + std::set& get_unused_reg_num(){return unused_reg_num_;} + + void set_instr_name(); + std::string print(); + +private: + void build_args(); + +private: + std::list basic_blocks_; // basic blocks + std::list arguments_; // arguments + std::vector> vreg_set_; + Module *parent_; + std::set unused_reg_num_; + unsigned seq_cnt_; + // unsigned num_args_; + // We don't need this, all value inside function should be unnamed + // std::map sym_table_; // Symbol table of args/instructions +}; + +// Argument of Function, does not contain actual value +class Argument : public Value +{ +public: + /// Argument constructor. + explicit Argument(Type *ty, const std::string &name = "", Function *f = nullptr, + unsigned arg_no = 0) + : Value(ty, name), parent_(f), arg_no_(arg_no) {} + ~Argument() {} + + inline const Function *get_parent() const { return parent_; } + inline Function *get_parent() { return parent_; } + + /// For example in "void foo(int a, float b)" a is 0 and b is 1. + unsigned get_arg_no() const { +#ifdef DEBUG + assert(parent_ && "can't get number of unparented arg"); +#endif + return arg_no_; + } + + virtual std::string print() override ; +private: + Function *parent_; + unsigned arg_no_; // argument No. +}; + +#endif // _SYSY_FUNCTION_H_ diff --git a/include/SysYIR/GlobalVariable.h b/include/SysYIR/GlobalVariable.h new file mode 100644 index 0000000..6c7e578 --- /dev/null +++ b/include/SysYIR/GlobalVariable.h @@ -0,0 +1,22 @@ +#ifndef _SYSY_GLOBALVARIABLE_H_ +#define _SYSY_GLOBALVARIABLE_H_ + +#include "Module.h" +#include "User.h" +#include "Constant.h" + +class GlobalVariable : public User +{ +private: + bool is_const_ ; + Constant* init_val_; + GlobalVariable(std::string name, Module *m, Type* ty, bool is_const, Constant* init = nullptr); +public: + static GlobalVariable *create(std::string name, Module *m, Type* ty, bool is_const, + Constant* init ); + + Constant *get_init() { return init_val_; } + bool is_const() { return is_const_; } + std::string print(); +}; +#endif //_SYSY_GLOBALVARIABLE_H_ diff --git a/include/SysYIR/IRBuilder.h b/include/SysYIR/IRBuilder.h new file mode 100644 index 0000000..45764e6 --- /dev/null +++ b/include/SysYIR/IRBuilder.h @@ -0,0 +1,75 @@ +#ifndef _SYSY_IRBUILDER_H_ +#define _SYSY_IRBUILDER_H_ + +#include "BasicBlock.h" +#include "Instruction.h" +#include "Value.h" + +class IRBuilder { +private: + BasicBlock *BB_; + Module *m_; +public: + IRBuilder(BasicBlock *bb, Module *m) : BB_(bb), m_(m) {}; + ~IRBuilder() = default; + Module *get_module(){return m_;} + BasicBlock *get_insert_block() { return this->BB_; } + void set_insert_point(BasicBlock *bb) { this->BB_ = bb; } //在某个基本块中插入指令 + BinaryInst *create_iadd( Value *lhs, Value *rhs){ return BinaryInst::create_add( lhs, rhs, this->BB_, m_);} //创建加法指令(以及其他算术指令) + BinaryInst *create_isub( Value *lhs, Value *rhs){ return BinaryInst::create_sub( lhs, rhs, this->BB_, m_);} + BinaryInst *create_imul( Value *lhs, Value *rhs){ return BinaryInst::create_mul( lhs, rhs, this->BB_, m_);} + BinaryInst *create_isdiv( Value *lhs, Value *rhs){ return BinaryInst::create_sdiv( lhs, rhs, this->BB_, m_);} + BinaryInst *create_isrem( Value *lhs, Value *rhs){ return BinaryInst::create_srem( lhs, rhs, this->BB_, m_);} + + CmpInst *create_icmp_eq( Value *lhs, Value *rhs){ return CmpInst::create_cmp(CmpInst::EQ, lhs, rhs, this->BB_, m_); } + CmpInst *create_icmp_ne( Value *lhs, Value *rhs){ return CmpInst::create_cmp(CmpInst::NE, lhs, rhs, this->BB_, m_); } + CmpInst *create_icmp_gt( Value *lhs, Value *rhs){ return CmpInst::create_cmp(CmpInst::GT, lhs, rhs, this->BB_, m_); } + CmpInst *create_icmp_ge( Value *lhs, Value *rhs){ return CmpInst::create_cmp(CmpInst::GE, lhs, rhs, this->BB_, m_); } + CmpInst *create_icmp_lt( Value *lhs, Value *rhs){ return CmpInst::create_cmp(CmpInst::LT, lhs, rhs, this->BB_, m_); } + CmpInst *create_icmp_le( Value *lhs, Value *rhs){ return CmpInst::create_cmp(CmpInst::LE, lhs, rhs, this->BB_, m_); } + + BinaryInst *create_fadd( Value *lhs, Value *rhs){ return BinaryInst::create_fadd( lhs, rhs, this->BB_, m_);} + BinaryInst *create_fsub( Value *lhs, Value *rhs){ return BinaryInst::create_fsub( lhs, rhs, this->BB_, m_);} + BinaryInst *create_fmul( Value *lhs, Value *rhs){ return BinaryInst::create_fmul( lhs, rhs, this->BB_, m_);} + BinaryInst *create_fdiv( Value *lhs, Value *rhs){ return BinaryInst::create_fdiv( lhs, rhs, this->BB_, m_);} + + FCmpInst *create_fcmp_eq( Value *lhs, Value *rhs){ return FCmpInst::create_fcmp(FCmpInst::EQ, lhs, rhs, this->BB_, m_); } + FCmpInst *create_fcmp_ne( Value *lhs, Value *rhs){ return FCmpInst::create_fcmp(FCmpInst::NE, lhs, rhs, this->BB_, m_); } + FCmpInst *create_fcmp_gt( Value *lhs, Value *rhs){ return FCmpInst::create_fcmp(FCmpInst::GT, lhs, rhs, this->BB_, m_); } + FCmpInst *create_fcmp_ge( Value *lhs, Value *rhs){ return FCmpInst::create_fcmp(FCmpInst::GE, lhs, rhs, this->BB_, m_); } + FCmpInst *create_fcmp_lt( Value *lhs, Value *rhs){ return FCmpInst::create_fcmp(FCmpInst::LT, lhs, rhs, this->BB_, m_); } + FCmpInst *create_fcmp_le( Value *lhs, Value *rhs){ return FCmpInst::create_fcmp(FCmpInst::LE, lhs, rhs, this->BB_, m_); } + + CallInst *create_call(Value *func, std::vector args) + { +#ifdef DEBUG + assert( dynamic_cast(func) && "func must be Function * type"); +#endif + return CallInst::create(static_cast(func) ,args, this->BB_); + } + + BranchInst *create_br(BasicBlock *if_true){ return BranchInst::create_br(if_true, this->BB_); } + BranchInst *create_cond_br(Value *cond, BasicBlock *if_true, BasicBlock *if_false){ return BranchInst::create_cond_br(cond, if_true, if_false,this->BB_); } + + ReturnInst *create_ret(Value *val) { return ReturnInst::create_ret(val,this->BB_); } + ReturnInst *create_void_ret() { return ReturnInst::create_void_ret(this->BB_); } + + GetElementPtrInst *create_gep(Value *ptr, std::vector idxs) { return GetElementPtrInst::create_gep(ptr, idxs, this->BB_); } + + StoreInst *create_store(Value *val, Value *ptr) { return StoreInst::create_store(val, ptr, this->BB_ ); } + LoadInst * create_load(Type *ty, Value *ptr) { return LoadInst::create_load(ty, ptr, this->BB_); } + LoadInst * create_load(Value *ptr) + { +#ifdef DEBUG + assert( ptr->get_type()->is_pointer_type() && "ptr must be pointer type" ); +#endif + return LoadInst::create_load(ptr->get_type()->get_pointer_element_type(), ptr, this->BB_); + } + + AllocaInst *create_alloca(Type *ty) { return AllocaInst::create_alloca(ty, this->BB_); } + ZextInst *create_zext(Value *val, Type *ty) { return ZextInst::create_zext(val, ty, this->BB_); } + FpToSiInst *create_fptosi(Value *val, Type *ty) { return FpToSiInst::create_fptosi(val, ty, this->BB_); } + SiToFpInst *create_sitofp(Value *val, Type *ty) { return SiToFpInst::create_sitofp(val, ty, this->BB_); } +}; + +#endif // _SYSY_IRBUILDER_H_ diff --git a/include/SysYIR/IRprinter.h b/include/SysYIR/IRprinter.h new file mode 100644 index 0000000..1f7b082 --- /dev/null +++ b/include/SysYIR/IRprinter.h @@ -0,0 +1,13 @@ +#include "Value.h" +#include "Module.h" +#include "Function.h" +#include "GlobalVariable.h" +#include "Constant.h" +#include "BasicBlock.h" +#include "Instruction.h" +#include "User.h" +#include "Type.h" + +std::string print_as_op( Value *v, bool print_ty ); +std::string print_cmp_type( CmpInst::CmpOp op); +std::string print_fcmp_type( FCmpInst::CmpOp op); \ No newline at end of file diff --git a/include/SysYIR/Instruction.h b/include/SysYIR/Instruction.h new file mode 100644 index 0000000..b93dcf0 --- /dev/null +++ b/include/SysYIR/Instruction.h @@ -0,0 +1,405 @@ +#ifndef _SYSY_INSTRUCTION_H_ +#define _SYSY_INSTRUCTION_H_ + +#include "User.h" +#include "Type.h" +#include "Constant.h" +#include "BasicBlock.h" + +class BasicBlock; +class Function; + +class Instruction : public User +{ +public: + enum OpID + { + // Terminator Instructions + ret, + br, + // Standard binary operators + add, + sub, + mul, + sdiv, + srem, + // Float binaru opeartors + fadd, + fsub, + fmul, + fdiv, + // Memory operators + alloca, + load, + store, + // Other operators + cmp, + fcmp, + phi, + call, + getelementptr, + // Zero extend + zext, + // type cast bewteen float and singed integer + fptosi, + sitofp, + }; + // create instruction, auto insert to bb + // ty here is result type + Instruction(Type *ty, OpID id, unsigned num_ops, + BasicBlock *parent); + Instruction(Type *ty, OpID id, unsigned num_ops); + inline const BasicBlock *get_parent() const { return parent_; } + inline BasicBlock *get_parent() { return parent_; } + void set_parent(BasicBlock *parent) { this->parent_ = parent; } + // Return the function this instruction belongs to. + Function *get_function(); + Module *get_module(); + + OpID get_instr_type() { return op_id_; } + std::string get_instr_op_name() { + switch (op_id_) + { + case ret: return "ret"; break; + case br: return "br"; break; + case add: return "add"; break; + case sub: return "sub"; break; + case mul: return "mul"; break; + case sdiv: return "sdiv"; break; + case srem: return "srem"; break; + case fadd: return "fadd"; break; + case fsub: return "fsub"; break; + case fmul: return "fmul"; break; + case fdiv: return "fdiv"; break; + case alloca: return "alloca"; break; + case load: return "load"; break; + case store: return "store"; break; + case cmp: return "cmp"; break; + case fcmp: return "fcmp"; break; + case phi: return "phi"; break; + case call: return "call"; break; + case getelementptr: return "getelementptr"; break; + case zext: return "zext"; break; + case fptosi: return "fptosi"; break; + case sitofp: return "sitofp"; break; + + default: return ""; break; + } + } + + + + bool is_void() { return ((op_id_ == ret) || (op_id_ == br) || (op_id_ == store) || (op_id_ == call && this->get_type()->is_void_type())); } + + bool is_phi() { return op_id_ == phi; } + bool is_store() { return op_id_ == store; } + bool is_alloca() { return op_id_ == alloca; } + bool is_ret() { return op_id_ == ret; } + bool is_load() { return op_id_ == load; } + bool is_br() { return op_id_ == br; } + + bool is_add() { return op_id_ == add; } + bool is_sub() { return op_id_ == sub; } + bool is_mul() { return op_id_ == mul; } + bool is_div() { return op_id_ == sdiv; } + bool is_rem() { return op_id_ == srem; } + + bool is_fadd() { return op_id_ == fadd; } + bool is_fsub() { return op_id_ == fsub; } + bool is_fmul() { return op_id_ == fmul; } + bool is_fdiv() { return op_id_ == fdiv; } + + bool is_cmp() { return op_id_ == cmp; } + bool is_fcmp() { return op_id_ == fcmp; } + + bool is_call() { return op_id_ == call; } + bool is_gep() { return op_id_ == getelementptr; } + bool is_zext() { return op_id_ == zext; } + bool is_fptosi() { return op_id_ == fptosi; } + bool is_sitofp() { return op_id_ == sitofp; } + + bool isBinary() + { + return (is_add() || is_sub() || is_mul() || is_div() || is_rem() || + is_fadd() || is_fsub() || is_fmul() || is_fdiv()) && + (get_num_operand() == 2); + } + + bool isTerminator() { return is_br() || is_ret(); } + + void set_id(int id){id_ = id;} + int get_id() const{return id_;} + +private: + BasicBlock *parent_; + OpID op_id_; + int id_; + unsigned num_ops_; +}; + +class BinaryInst : public Instruction +{ +private: + BinaryInst(Type *ty, OpID id, Value *v1, Value *v2, + BasicBlock *bb); + +public: + static BinaryInst *create_add(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_sub(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_mul(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_sdiv(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_srem(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_fadd(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_fsub(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_fmul(Value *v1, Value *v2, BasicBlock *bb, Module *m); + static BinaryInst *create_fdiv(Value *v1, Value *v2, BasicBlock *bb, Module *m); + + virtual std::string print() override; + +private: + void assertValid(); +}; + +class CmpInst : public Instruction +{ +public: + enum CmpOp + { + EQ, // == + NE, // != + GT, // > + GE, // >= + LT, // < + LE // <= + }; + +private: + CmpInst(Type *ty, CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb); + +public: + static CmpInst *create_cmp(CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb, Module *m); + + CmpOp get_cmp_op() { return cmp_op_; } + + virtual std::string print() override; + +private: + CmpOp cmp_op_; + + void assertValid(); +}; + +class FCmpInst : public Instruction +{ +public: + enum CmpOp + { + EQ, // == + NE, // != + GT, // > + GE, // >= + LT, // < + LE // <= + }; + +private: + FCmpInst(Type *ty, CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb); + +public: + static FCmpInst *create_fcmp(CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb, Module *m); + + CmpOp get_cmp_op() { return cmp_op_; } + + virtual std::string print() override; + +private: + CmpOp cmp_op_; + + void assertValid(); +}; + +class CallInst : public Instruction +{ +protected: + CallInst(Function *func, std::vector args, BasicBlock *bb); + CallInst(Type *ret_ty, std::vector args, BasicBlock *bb); + +public: + static CallInst *create(Function *func, std::vector args, BasicBlock *bb); + FunctionType *get_function_type() const; + + virtual std::string print() override; + +}; + +class BranchInst : public Instruction +{ +private: + BranchInst(Value *cond, BasicBlock *if_true, BasicBlock *if_false, + BasicBlock *bb); + BranchInst(Value *cond, BasicBlock *bb); + BranchInst(BasicBlock *if_true, BasicBlock *bb); + BranchInst(BasicBlock *bb); + +public: + static BranchInst *create_cond_br(Value *cond, BasicBlock *if_true, BasicBlock *if_false, + BasicBlock *bb); + static BranchInst *create_br(BasicBlock *if_true, BasicBlock *bb); + + bool is_cond_br() const; + + virtual std::string print() override; + +}; + +class ReturnInst : public Instruction +{ +private: + ReturnInst(Value *val, BasicBlock *bb); + ReturnInst(BasicBlock *bb); + +public: + static ReturnInst *create_ret(Value *val, BasicBlock *bb); + static ReturnInst *create_void_ret(BasicBlock *bb); + bool is_void_ret() const; + + virtual std::string print() override; + +}; + +class GetElementPtrInst : public Instruction +{ +private: + GetElementPtrInst(Value *ptr, std::vector idxs, BasicBlock *bb); + +public: + static Type *get_element_type(Value *ptr, std::vector idxs); + static GetElementPtrInst *create_gep(Value *ptr, std::vector idxs, BasicBlock *bb); + Type *get_element_type() const; + + virtual std::string print() override; + +private: + Type *element_ty_; +}; + +class StoreInst : public Instruction +{ +private: + StoreInst(Value *val, Value *ptr, BasicBlock *bb); + +public: + static StoreInst *create_store(Value *val, Value *ptr, BasicBlock *bb); + + Value *get_rval() { return this->get_operand(0); } + Value *get_lval() { return this->get_operand(1); } + + virtual std::string print() override; + +}; + +class LoadInst : public Instruction +{ +private: + LoadInst(Type *ty, Value *ptr, BasicBlock *bb); + +public: + static LoadInst *create_load(Type *ty, Value *ptr, BasicBlock *bb); + Value *get_lval() { return this->get_operand(0); } + + Type *get_load_type() const; + + virtual std::string print() override; + +}; + +class AllocaInst : public Instruction +{ +private: + AllocaInst(Type *ty, BasicBlock *bb); + +public: + static AllocaInst *create_alloca(Type *ty, BasicBlock *bb); + + Type *get_alloca_type() const; + + virtual std::string print() override; + +private: + Type *alloca_ty_; +}; + +class ZextInst : public Instruction +{ +private: + ZextInst(OpID op, Value *val, Type *ty, BasicBlock *bb); + +public: + static ZextInst *create_zext(Value *val, Type *ty, BasicBlock *bb); + + Type *get_dest_type() const; + + virtual std::string print() override; + +private: + Type *dest_ty_; +}; + +class FpToSiInst : public Instruction +{ +private: + FpToSiInst(OpID op, Value *val, Type *ty, BasicBlock *bb); + +public: + static FpToSiInst *create_fptosi(Value *val, Type *ty, BasicBlock *bb); + + Type *get_dest_type() const; + + virtual std::string print() override; + +private: + Type *dest_ty_; +}; + +class SiToFpInst : public Instruction +{ +private: + SiToFpInst(OpID op, Value *val, Type *ty, BasicBlock *bb); + +public: + static SiToFpInst *create_sitofp(Value *val, Type *ty, BasicBlock *bb); + + Type *get_dest_type() const; + + virtual std::string print() override; + +private: + Type *dest_ty_; +}; + +class PhiInst : public Instruction +{ +private: + PhiInst(OpID op, std::vector vals, std::vector val_bbs, Type *ty, BasicBlock *bb); + +public: + static PhiInst *create_phi(Type *ty, BasicBlock *bb); + Value *get_lval() { return l_val_; } + void set_lval(Value *l_val) { l_val_ = l_val; } + void add_phi_pair_operand(Value *val, Value *pre_bb) + { + this->add_operand(val); + this->add_operand(pre_bb); + } + virtual std::string print() override; + +private: + Value *l_val_; + +}; + +#endif // _SYSY_INSTRUCTION_H_ diff --git a/include/SysYIR/Module.h b/include/SysYIR/Module.h new file mode 100644 index 0000000..f9e2f67 --- /dev/null +++ b/include/SysYIR/Module.h @@ -0,0 +1,61 @@ +#ifndef _SYSY_MODULE_H_ +#define _SYSY_MODULE_H_ + +#include +#include +#include + +#include "Type.h" +#include "GlobalVariable.h" +#include "Value.h" +#include "Function.h" + +class GlobalVariable; + +class Module +{ +public: + explicit Module(std::string name); + ~Module(); + + Type *get_void_type(); + Type *get_label_type(); + IntegerType *get_int1_type(); + IntegerType *get_int32_type(); + FloatType *get_float_type(); + PointerType *get_int32_ptr_type(); + PointerType *get_float_ptr_type(); + + PointerType *get_pointer_type(Type *contained); + ArrayType *get_array_type(Type *contained, unsigned num_elements); + + void add_function(Function *f); + std::list &get_functions(); + void add_global_variable(GlobalVariable* g); + std::list &get_global_variable(); + std::string get_instr_op_name( Instruction::OpID instr ) { return instr_id2string_[instr]; } + void set_print_name(); + void set_file_name(std::string name){source_file_name_ = name;} + std::string get_file_name(){return source_file_name_;} + virtual std::string print(); +private: + std::list global_list_; // The Global Variables in the module + std::list function_list_; // The Functions in the module + std::map value_sym_; // Symbol table for values + std::map instr_id2string_; // Instruction from opid to string + + std::string module_name_; // Human readable identifier for the module + std::string source_file_name_; // Original source file name for module, for test and debug + +private: + IntegerType *int1_ty_; + IntegerType *int32_ty_; + FloatType *float32_ty_; + Type *label_ty_; + Type *void_ty_; + + std::map pointer_map_; + std::map, ArrayType *> array_map_; +}; + +#endif // _SYSY_MODULE_H_ \ No newline at end of file diff --git a/include/SysYIR/Type.h b/include/SysYIR/Type.h new file mode 100644 index 0000000..ecc067b --- /dev/null +++ b/include/SysYIR/Type.h @@ -0,0 +1,146 @@ +#ifndef _SYSY_TYPE_H_ +#define _SYSY_TYPE_H_ + +#include +#include + +class Module; +class IntegerType; +class FloatType; +class FunctionType; +class ArrayType; +class PointerType; + +class Type +{ +public: + enum TypeID { + VoidTyID, // Void + LabelTyID, // Labels, e.g., BasicBlock + IntegerTyID, // Integers, include 32 bits and 1 bit + FloatTyID, // Floats, only 32 bits + FunctionTyID, // Functions + ArrayTyID, // Arrays + PointerTyID, // Pointer + }; + + explicit Type(TypeID tid, Module *m); + ~Type() = default; + + TypeID get_type_id() const { return tid_; } + + bool is_void_type() const { return get_type_id() == VoidTyID; } + + bool is_label_type() const { return get_type_id() == LabelTyID; } + + bool is_integer_type() const { return get_type_id() == IntegerTyID; } + + bool is_float_type() const { return get_type_id() == FloatTyID; } + + bool is_function_type() const { return get_type_id() == FunctionTyID; } + + bool is_array_type() const { return get_type_id() == ArrayTyID; } + + bool is_pointer_type() const { return get_type_id() == PointerTyID; } + + static bool is_eq_type(Type *ty1, Type *ty2); + + static Type *get_void_type(Module *m); + + static Type *get_label_type(Module *m); + + static IntegerType *get_int1_type(Module *m); + + static IntegerType *get_int32_type(Module *m); + + static FloatType *get_float_type(Module *m); + + static PointerType *get_int32_ptr_type(Module *m); + + static PointerType *get_float_ptr_type(Module *m); + + static PointerType *get_pointer_type(Type *contained); + + static ArrayType *get_array_type(Type *contained, unsigned num_elements); + + Type *get_pointer_element_type(); + + Type *get_array_element_type(); + + int get_size(); + + Module *get_module(); + + std::string print(); + +private: + TypeID tid_; + Module *m_; +}; + +class IntegerType : public Type { +public: + explicit IntegerType(unsigned num_bits ,Module *m); + + static IntegerType *get(unsigned num_bits, Module *m ); + + unsigned get_num_bits(); +private: + unsigned num_bits_; +}; + +class FloatType : public Type { +public: + FloatType(Module *m); + static FloatType *get(Module *m ); +}; + +class FunctionType : public Type { +public: + FunctionType(Type *result, std::vector params); + + static bool is_valid_return_type(Type *ty); + static bool is_valid_argument_type(Type *ty); + + static FunctionType *get(Type *result, + std::vector params); + + unsigned get_num_of_args() const; + + Type *get_param_type(unsigned i) const; + std::vector::iterator param_begin() { return args_.begin(); } + std::vector::iterator param_end() { return args_.end(); } + Type *get_return_type() const; +private: + Type *result_; + std::vector args_; +}; + +class ArrayType : public Type { +public: + ArrayType(Type *contained, unsigned num_elements); + + static bool is_valid_element_type(Type *ty); + + static ArrayType *get(Type *contained, unsigned num_elements); + + Type *get_element_type() const { return contained_; } + unsigned get_num_of_elements() const { return num_elements_; } + +private: + Type *contained_; // The element type of the array. + unsigned num_elements_; // Number of elements in the array. +}; + +class PointerType : public Type { +public: + PointerType(Type *contained); + Type *get_element_type() const { return contained_; } + + static PointerType *get(Type *contained); + +private: + Type *contained_; // The element type of the ptr. +}; + +#endif // _SYSY_TYPE_H_ \ No newline at end of file diff --git a/include/SysYIR/User.h b/include/SysYIR/User.h new file mode 100644 index 0000000..b4e0167 --- /dev/null +++ b/include/SysYIR/User.h @@ -0,0 +1,34 @@ +#ifndef _SYSY_USER_H_ +#define _SYSY_USER_H_ + +#include "Value.h" +#include +// #include + +class User : public Value +{ +public: + User(Type *ty, const std::string &name = "", unsigned num_ops = 0); + ~User() = default; + + std::vector& get_operands(); + + // start from 0 + Value *get_operand(unsigned i) const; + + // start from 0 + void set_operand(unsigned i, Value *v); + void add_operand( Value *v); + + unsigned get_num_operand() const; + + void remove_use_of_ops(); + void remove_operands(int index1,int index2); + +private: + // std::unique_ptr< std::list > operands_; // operands of this value + std::vector operands_; // operands of this value + unsigned num_ops_; +}; + +#endif // _SYSY_USER_H_ diff --git a/include/SysYIR/Value.h b/include/SysYIR/Value.h new file mode 100644 index 0000000..752b8e6 --- /dev/null +++ b/include/SysYIR/Value.h @@ -0,0 +1,50 @@ +#ifndef _SYSY_VALUE_H_ +#define _SYSY_VALUE_H_ + +#include +#include +#include + +class Type; +class Value; + +struct Use +{ + Value *val_; + unsigned arg_no_; // the no. of operand, e.g., func(a, b), a is 0, b is 1 + Use(Value *val, unsigned no) : val_(val), arg_no_(no) {} +}; + +class Value +{ +public: + explicit Value(Type *ty, const std::string &name = ""); + ~Value() = default; + + Type *get_type() const { return type_; } + + std::list &get_use_list() { return use_list_; } + + void add_use(Value *val, unsigned arg_no = 0); + + bool set_name(std::string name) { + if (name_ == "") + { + name_=name; + return true; + } + return false; + } + std::string get_name() const; + + void replace_all_use_with(Value *new_val); + void remove_use(Value *val); + + virtual std::string print() = 0; +private: + Type *type_; + std::list use_list_; // who use this value + std::string name_; // should we put name field here ? +}; + +#endif // _SYSY_VALUE_H_ diff --git a/lib/lib.c b/lib/lib.c new file mode 100644 index 0000000..1231b17 --- /dev/null +++ b/lib/lib.c @@ -0,0 +1,30 @@ +#include +/* Input & output functions */ +int get_int(){int t; scanf("%d",&t); return t; } +int get_float(){float t; scanf("%f",&t); return t; } +int get_char(){char c; scanf("%c",&c); return (int)c; } +int get_int_array(int a[]){ + int n; + scanf("%d",&n); + for(int i=0;i +#include +#include + +using namespace SyntaxTree; + +std::map type2str = { + {Type::INT, "int"}, + {Type::VOID, "void"}, + {Type::FLOAT, "float"} +}; + +std::map bincondop2str = { + {BinaryCondOp::EQ,"=="}, + {BinaryCondOp::NEQ,"!="}, + {BinaryCondOp::GT,">"}, + {BinaryCondOp::GTE,">="}, + {BinaryCondOp::LT,"<"}, + {BinaryCondOp::LTE,"<="}, + {BinaryCondOp::LAND,"&&"}, + {BinaryCondOp::LOR,"||"} +}; + +std::map binop2str = { + {BinOp::PLUS, "+"}, + {BinOp::MINUS, "-"}, + {BinOp::MULTIPLY, "*"}, + {BinOp::DIVIDE, "/"}, + {BinOp::MODULO, "%"} +}; + +std::map unarycondop2str = { + {UnaryCondOp::NOT,"!"} +}; + +std::map unaryop2str = { + {UnaryOp::PLUS, "+"}, + {UnaryOp::MINUS, "-"} +}; + +void SyntaxTreePrinter::print_indent() +{ + for (int i = 0; i < indent; i++) + std::cout << " "; +} + +void SyntaxTreePrinter::visit(Assembly &node) +{ + indent = 0; + for (auto def : node.global_defs) { + def->accept(*this); + } +} + +void SyntaxTreePrinter::visit(FuncDef &node) +{ + std::cout << type2str[node.ret_type] << " " + << node.name << "("; + node.param_list->accept(*this); + std::cout << ")" << std::endl; + node.body->accept(*this); + indent = 0; +} + +void SyntaxTreePrinter::visit(BlockStmt &node) +{ + print_indent(); + std::cout << "{" << std::endl; + indent += 4; + for (auto stmt : node.body) { + stmt->accept(*this); + } + indent -= 4; + print_indent(); + std::cout << "}" << std::endl; +} + +void SyntaxTreePrinter::visit(VarDef &node) +{ + print_indent(); + bool is_array = false; + if (node.is_constant) + std::cout << "const "; + std::cout << type2str[node.btype] << " " << node.name; + for (auto length : node.array_length) { + std::cout << "["; + length->accept(*this); + std::cout << "]"; + is_array = true; + } + if (node.is_inited) { + int tmp = indent; + indent = 0; + std::cout << " = "; + // if (is_array) + // std::cout << "{"; + // size_t num = 0; + // for (auto init : node.initializers) { + // init->accept(*this); + // if (num < node.initializers.size() - 1) + // std::cout << ", "; + // num++; + // } + // if (is_array) + // std::cout << "}"; + node.initializers->accept(*this); + indent = tmp; + } + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(InitVal &node){ + if(node.isExp){ + node.expr->accept(*this); + } + else{ + std::cout << "{"; + int i = 0; + int num = node.elementList.size(); + for(auto item: node.elementList){ + item->accept(*this); + i++; + if(i < num) std::cout << ", "; + } + std::cout << "}"; + } + return; +} + +void SyntaxTreePrinter::visit(BinaryExpr &node) +{ + std::cout << "("; + node.lhs->accept(*this); + std::cout << binop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(UnaryExpr &node) +{ + std::cout << "("; + std::cout << unaryop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(LVal &node) +{ + std::cout << node.name; + for (auto index : node.array_index) { + std::cout << "["; + index->accept(*this); + std::cout << "]"; + } +} + +void SyntaxTreePrinter::visit(Literal &node) +{ + if (node.literal_type == Type::INT) + std::cout << node.int_const; + else if(node.literal_type == Type::FLOAT) + std::cout << node.float_const; + else { + ErrorReporter error(std::cerr); + error.error(node.loc,"unsupported literal type!"); + abort(); + } +} + +void SyntaxTreePrinter::visit(ReturnStmt &node) +{ + print_indent(); + std::cout << "return"; + //indent = 0; + if (node.ret.get()) { + std::cout << " "; + node.ret->accept(*this); + } + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(AssignStmt &node) +{ + print_indent(); + node.target->accept(*this); + std::cout << " = "; + node.value->accept(*this); + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(FuncCallStmt &node) +{ + //print_indent(); + std::cout << node.name << "("; + size_t num = 0; + for(auto exp:node.params) + { + exp->accept(*this); + if(num < node.params.size() - 1) + { + std::cout <<", "; + } + num++; + } + std::cout <<")"; +} + +void SyntaxTreePrinter::visit(EmptyStmt &) +{ + print_indent(); + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(ExprStmt &node) +{ + print_indent(); + node.exp->accept(*this); + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(FuncParam &node) +{ + std::cout << type2str[node.param_type] << " " << node.name; + for(auto exp:node.array_index) + { + std::cout << "["; + if (exp != nullptr) + exp->accept(*this); + std::cout << "]"; + } +} + +void SyntaxTreePrinter::visit(FuncFParamList &node) +{ + size_t num = 0; + for(auto param:node.params) + { + param->accept(*this); + if(num < node.params.size() - 1) + { + std::cout << ", "; + } + num++; + } +} + +void SyntaxTreePrinter::visit(BinaryCondExpr &node) +{ + std::cout << "("; + node.lhs->accept(*this); + std::cout << bincondop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(UnaryCondExpr &node) +{ + std::cout <<"("; + std::cout << unarycondop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(IfStmt &node) +{ + print_indent(); + std::cout << "if"; + std::cout << " "; + std::cout << "("; + node.cond_exp->accept(*this); + std::cout << ")" << std::endl; + if(dynamic_cast(node.if_statement.get())){ + node.if_statement->accept(*this); + } + else{ + indent+=4; + node.if_statement->accept(*this); + indent-=4; + } + if (node.else_statement != nullptr) { + print_indent(); + std::cout << "else" << std::endl; + if(dynamic_cast(node.else_statement.get())){ + node.else_statement->accept(*this); + }else { + indent+=4; + node.else_statement->accept(*this); + indent-=4; + } + } +} + +void SyntaxTreePrinter::visit(WhileStmt &node) +{ + print_indent(); + std::cout << "while"; + std::cout << " "; + std::cout << "("; + node.cond_exp->accept(*this); + std::cout << ")"<< std::endl; + if(dynamic_cast(node.statement.get())){ + node.statement->accept(*this); + } + else{ + indent+=4; + node.statement->accept(*this); + indent-=4; + } +} + +void SyntaxTreePrinter::visit(BreakStmt &node) +{ + print_indent(); + std::cout << "break"; + std::cout << ";" <root; +} + +void SysYDriver::error(const yy::location& l, const std::string& m) +{ + std::cerr << l << ": " << m << std::endl; +} + +void SysYDriver::error(const std::string& m) +{ + std::cerr << m << std::endl; +} + + +void SysYDriver::scan_begin() +{ + lexer.set_debug(trace_scanning); + + // Try to open the file: + instream.open(file); + + if(instream.good()) { + lexer.switch_streams(&instream, 0); + } + else if(file == "-") { + lexer.switch_streams(&std::cin, 0); + } + else { + error("Cannot open file '" + file + "'."); + exit(EXIT_FAILURE); + } +} + +void SysYDriver::scan_end() +{ + instream.close(); +} diff --git a/src/Grammar/SysYParser.cpp b/src/Grammar/SysYParser.cpp new file mode 100644 index 0000000..c1450e8 --- /dev/null +++ b/src/Grammar/SysYParser.cpp @@ -0,0 +1,2476 @@ +// A Bison parser, made by GNU Bison 3.7.6. + +// Skeleton implementation for Bison LALR(1) parsers in C++ + +// Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// As a special exception, you may create a larger work that contains +// part or all of the Bison parser skeleton and distribute that work +// under terms of your choice, so long as that work isn't itself a +// parser generator using the skeleton or a modified version thereof +// as a parser skeleton. Alternatively, if you modify or redistribute +// the parser skeleton itself, you may (at your option) remove this +// special exception, which will cause the skeleton and the resulting +// Bison output files to be licensed under the GNU General Public +// License without this special exception. + +// This special exception was added by the Free Software Foundation in +// version 2.2 of Bison. + +// DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, +// especially those whose name start with YY_ or yy_. They are +// private implementation details that can be changed or removed. + + + + + +#include "SysYParser.h" + + +// Unqualified %code blocks. +#line 35 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + +#include "SysYDriver.h" +#define yylex driver.lexer.yylex + +#line 51 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + + +#ifndef YY_ +# if defined YYENABLE_NLS && YYENABLE_NLS +# if ENABLE_NLS +# include // FIXME: INFRINGES ON USER NAME SPACE. +# define YY_(msgid) dgettext ("bison-runtime", msgid) +# endif +# endif +# ifndef YY_ +# define YY_(msgid) msgid +# endif +#endif + + +// Whether we are compiled with exception support. +#ifndef YY_EXCEPTIONS +# if defined __GNUC__ && !defined __EXCEPTIONS +# define YY_EXCEPTIONS 0 +# else +# define YY_EXCEPTIONS 1 +# endif +#endif + +#define YYRHSLOC(Rhs, K) ((Rhs)[K].location) +/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. + If N is 0, then set CURRENT to the empty location which ends + the previous symbol: RHS[0] (always defined). */ + +# ifndef YYLLOC_DEFAULT +# define YYLLOC_DEFAULT(Current, Rhs, N) \ + do \ + if (N) \ + { \ + (Current).begin = YYRHSLOC (Rhs, 1).begin; \ + (Current).end = YYRHSLOC (Rhs, N).end; \ + } \ + else \ + { \ + (Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \ + } \ + while (false) +# endif + + +// Enable debugging if requested. +#if YYDEBUG + +// A pseudo ostream that takes yydebug_ into account. +# define YYCDEBUG if (yydebug_) (*yycdebug_) + +# define YY_SYMBOL_PRINT(Title, Symbol) \ + do { \ + if (yydebug_) \ + { \ + *yycdebug_ << Title << ' '; \ + yy_print_ (*yycdebug_, Symbol); \ + *yycdebug_ << '\n'; \ + } \ + } while (false) + +# define YY_REDUCE_PRINT(Rule) \ + do { \ + if (yydebug_) \ + yy_reduce_print_ (Rule); \ + } while (false) + +# define YY_STACK_PRINT() \ + do { \ + if (yydebug_) \ + yy_stack_print_ (); \ + } while (false) + +#else // !YYDEBUG + +# define YYCDEBUG if (false) std::cerr +# define YY_SYMBOL_PRINT(Title, Symbol) YY_USE (Symbol) +# define YY_REDUCE_PRINT(Rule) static_cast (0) +# define YY_STACK_PRINT() static_cast (0) + +#endif // !YYDEBUG + +#define yyerrok (yyerrstatus_ = 0) +#define yyclearin (yyla.clear ()) + +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab +#define YYRECOVERING() (!!yyerrstatus_) + +namespace yy { +#line 143 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + + /// Build a parser object. + SysYParser::SysYParser (SysYDriver& driver_yyarg) +#if YYDEBUG + : yydebug_ (false), + yycdebug_ (&std::cerr), +#else + : +#endif + driver (driver_yyarg) + {} + + SysYParser::~SysYParser () + {} + + SysYParser::syntax_error::~syntax_error () YY_NOEXCEPT YY_NOTHROW + {} + + /*---------------. + | symbol kinds. | + `---------------*/ + + + + // by_state. + SysYParser::by_state::by_state () YY_NOEXCEPT + : state (empty_state) + {} + + SysYParser::by_state::by_state (const by_state& that) YY_NOEXCEPT + : state (that.state) + {} + + void + SysYParser::by_state::clear () YY_NOEXCEPT + { + state = empty_state; + } + + void + SysYParser::by_state::move (by_state& that) + { + state = that.state; + that.clear (); + } + + SysYParser::by_state::by_state (state_type s) YY_NOEXCEPT + : state (s) + {} + + SysYParser::symbol_kind_type + SysYParser::by_state::kind () const YY_NOEXCEPT + { + if (state == empty_state) + return symbol_kind::S_YYEMPTY; + else + return YY_CAST (symbol_kind_type, yystos_[+state]); + } + + SysYParser::stack_symbol_type::stack_symbol_type () + {} + + SysYParser::stack_symbol_type::stack_symbol_type (YY_RVREF (stack_symbol_type) that) + : super_type (YY_MOVE (that.state), YY_MOVE (that.location)) + { + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.YY_MOVE_OR_COPY< SyntaxTree::Assembly* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.YY_MOVE_OR_COPY< SyntaxTree::BlockStmt* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.YY_MOVE_OR_COPY< SyntaxTree::Expr* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.YY_MOVE_OR_COPY< SyntaxTree::FuncDef* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.YY_MOVE_OR_COPY< SyntaxTree::FuncParam* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.YY_MOVE_OR_COPY< SyntaxTree::InitVal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.YY_MOVE_OR_COPY< SyntaxTree::LVal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.YY_MOVE_OR_COPY< SyntaxTree::Literal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.YY_MOVE_OR_COPY< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.YY_MOVE_OR_COPY< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.YY_MOVE_OR_COPY< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.YY_MOVE_OR_COPY< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.YY_MOVE_OR_COPY< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.YY_MOVE_OR_COPY< SyntaxTree::Stmt* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.YY_MOVE_OR_COPY< SyntaxTree::Type > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.YY_MOVE_OR_COPY< SyntaxTree::VarDef* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.YY_MOVE_OR_COPY< float > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.YY_MOVE_OR_COPY< int > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.YY_MOVE_OR_COPY< std::string > (YY_MOVE (that.value)); + break; + + default: + break; + } + +#if 201103L <= YY_CPLUSPLUS + // that is emptied. + that.state = empty_state; +#endif + } + + SysYParser::stack_symbol_type::stack_symbol_type (state_type s, YY_MOVE_REF (symbol_type) that) + : super_type (s, YY_MOVE (that.location)) + { + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SyntaxTree::Assembly* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.move< SyntaxTree::BlockStmt* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SyntaxTree::Expr* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SyntaxTree::FuncDef* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SyntaxTree::FuncParam* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SyntaxTree::InitVal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SyntaxTree::LVal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.move< SyntaxTree::Literal* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SyntaxTree::PtrList > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SyntaxTree::Stmt* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.move< SyntaxTree::Type > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SyntaxTree::VarDef* > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (YY_MOVE (that.value)); + break; + + default: + break; + } + + // that is emptied. + that.kind_ = symbol_kind::S_YYEMPTY; + } + +#if YY_CPLUSPLUS < 201103L + SysYParser::stack_symbol_type& + SysYParser::stack_symbol_type::operator= (const stack_symbol_type& that) + { + state = that.state; + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.copy< SyntaxTree::Assembly* > (that.value); + break; + + case symbol_kind::S_Block: // Block + value.copy< SyntaxTree::BlockStmt* > (that.value); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.copy< SyntaxTree::Expr* > (that.value); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.copy< SyntaxTree::FuncDef* > (that.value); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.copy< SyntaxTree::FuncParam* > (that.value); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.copy< SyntaxTree::InitVal* > (that.value); + break; + + case symbol_kind::S_LVal: // LVal + value.copy< SyntaxTree::LVal* > (that.value); + break; + + case symbol_kind::S_Number: // Number + value.copy< SyntaxTree::Literal* > (that.value); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.copy< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.copy< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.copy< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.copy< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.copy< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.copy< SyntaxTree::Stmt* > (that.value); + break; + + case symbol_kind::S_BType: // BType + value.copy< SyntaxTree::Type > (that.value); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.copy< SyntaxTree::VarDef* > (that.value); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.copy< float > (that.value); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.copy< int > (that.value); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.copy< std::string > (that.value); + break; + + default: + break; + } + + location = that.location; + return *this; + } + + SysYParser::stack_symbol_type& + SysYParser::stack_symbol_type::operator= (stack_symbol_type& that) + { + state = that.state; + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SyntaxTree::Assembly* > (that.value); + break; + + case symbol_kind::S_Block: // Block + value.move< SyntaxTree::BlockStmt* > (that.value); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SyntaxTree::Expr* > (that.value); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SyntaxTree::FuncDef* > (that.value); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SyntaxTree::FuncParam* > (that.value); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SyntaxTree::InitVal* > (that.value); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SyntaxTree::LVal* > (that.value); + break; + + case symbol_kind::S_Number: // Number + value.move< SyntaxTree::Literal* > (that.value); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SyntaxTree::PtrList > (that.value); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SyntaxTree::Stmt* > (that.value); + break; + + case symbol_kind::S_BType: // BType + value.move< SyntaxTree::Type > (that.value); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SyntaxTree::VarDef* > (that.value); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (that.value); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (that.value); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (that.value); + break; + + default: + break; + } + + location = that.location; + // that is emptied. + that.state = empty_state; + return *this; + } +#endif + + template + void + SysYParser::yy_destroy_ (const char* yymsg, basic_symbol& yysym) const + { + if (yymsg) + YY_SYMBOL_PRINT (yymsg, yysym); + } + +#if YYDEBUG + template + void + SysYParser::yy_print_ (std::ostream& yyo, const basic_symbol& yysym) const + { + std::ostream& yyoutput = yyo; + YY_USE (yyoutput); + if (yysym.empty ()) + yyo << "empty symbol"; + else + { + symbol_kind_type yykind = yysym.kind (); + yyo << (yykind < YYNTOKENS ? "token" : "nterm") + << ' ' << yysym.name () << " (" + << yysym.location << ": "; + YY_USE (yykind); + yyo << ')'; + } + } +#endif + + void + SysYParser::yypush_ (const char* m, YY_MOVE_REF (stack_symbol_type) sym) + { + if (m) + YY_SYMBOL_PRINT (m, sym); + yystack_.push (YY_MOVE (sym)); + } + + void + SysYParser::yypush_ (const char* m, state_type s, YY_MOVE_REF (symbol_type) sym) + { +#if 201103L <= YY_CPLUSPLUS + yypush_ (m, stack_symbol_type (s, std::move (sym))); +#else + stack_symbol_type ss (s, sym); + yypush_ (m, ss); +#endif + } + + void + SysYParser::yypop_ (int n) + { + yystack_.pop (n); + } + +#if YYDEBUG + std::ostream& + SysYParser::debug_stream () const + { + return *yycdebug_; + } + + void + SysYParser::set_debug_stream (std::ostream& o) + { + yycdebug_ = &o; + } + + + SysYParser::debug_level_type + SysYParser::debug_level () const + { + return yydebug_; + } + + void + SysYParser::set_debug_level (debug_level_type l) + { + yydebug_ = l; + } +#endif // YYDEBUG + + SysYParser::state_type + SysYParser::yy_lr_goto_state_ (state_type yystate, int yysym) + { + int yyr = yypgoto_[yysym - YYNTOKENS] + yystate; + if (0 <= yyr && yyr <= yylast_ && yycheck_[yyr] == yystate) + return yytable_[yyr]; + else + return yydefgoto_[yysym - YYNTOKENS]; + } + + bool + SysYParser::yy_pact_value_is_default_ (int yyvalue) + { + return yyvalue == yypact_ninf_; + } + + bool + SysYParser::yy_table_value_is_error_ (int yyvalue) + { + return yyvalue == yytable_ninf_; + } + + int + SysYParser::operator() () + { + return parse (); + } + + int + SysYParser::parse () + { + int yyn; + /// Length of the RHS of the rule being reduced. + int yylen = 0; + + // Error handling. + int yynerrs_ = 0; + int yyerrstatus_ = 0; + + /// The lookahead symbol. + symbol_type yyla; + + /// The locations where the error started and ended. + stack_symbol_type yyerror_range[3]; + + /// The return value of parse (). + int yyresult; + +#if YY_EXCEPTIONS + try +#endif // YY_EXCEPTIONS + { + YYCDEBUG << "Starting parse\n"; + + + // User initialization code. +#line 24 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" +{ +// Initialize the initial location. +yyla.location.begin.filename = yyla.location.end.filename = &driver.file; +} + +#line 785 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + + + /* Initialize the stack. The initial state will be set in + yynewstate, since the latter expects the semantical and the + location values to have been already stored, initialize these + stacks with a primary value. */ + yystack_.clear (); + yypush_ (YY_NULLPTR, 0, YY_MOVE (yyla)); + + /*-----------------------------------------------. + | yynewstate -- push a new symbol on the stack. | + `-----------------------------------------------*/ + yynewstate: + YYCDEBUG << "Entering state " << int (yystack_[0].state) << '\n'; + YY_STACK_PRINT (); + + // Accept? + if (yystack_[0].state == yyfinal_) + YYACCEPT; + + goto yybackup; + + + /*-----------. + | yybackup. | + `-----------*/ + yybackup: + // Try to take a decision without lookahead. + yyn = yypact_[+yystack_[0].state]; + if (yy_pact_value_is_default_ (yyn)) + goto yydefault; + + // Read a lookahead token. + if (yyla.empty ()) + { + YYCDEBUG << "Reading a token\n"; +#if YY_EXCEPTIONS + try +#endif // YY_EXCEPTIONS + { + symbol_type yylookahead (yylex (driver)); + yyla.move (yylookahead); + } +#if YY_EXCEPTIONS + catch (const syntax_error& yyexc) + { + YYCDEBUG << "Caught exception: " << yyexc.what() << '\n'; + error (yyexc); + goto yyerrlab1; + } +#endif // YY_EXCEPTIONS + } + YY_SYMBOL_PRINT ("Next token is", yyla); + + if (yyla.kind () == symbol_kind::S_YYerror) + { + // The scanner already issued an error message, process directly + // to error recovery. But do not keep the error token as + // lookahead, it is too special and may lead us to an endless + // loop in error recovery. */ + yyla.kind_ = symbol_kind::S_YYUNDEF; + goto yyerrlab1; + } + + /* If the proper action on seeing token YYLA.TYPE is to reduce or + to detect an error, take that action. */ + yyn += yyla.kind (); + if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yyla.kind ()) + { + goto yydefault; + } + + // Reduce or error. + yyn = yytable_[yyn]; + if (yyn <= 0) + { + if (yy_table_value_is_error_ (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + // Count tokens shifted since error; after three, turn off error status. + if (yyerrstatus_) + --yyerrstatus_; + + // Shift the lookahead token. + yypush_ ("Shifting", state_type (yyn), YY_MOVE (yyla)); + goto yynewstate; + + + /*-----------------------------------------------------------. + | yydefault -- do the default action for the current state. | + `-----------------------------------------------------------*/ + yydefault: + yyn = yydefact_[+yystack_[0].state]; + if (yyn == 0) + goto yyerrlab; + goto yyreduce; + + + /*-----------------------------. + | yyreduce -- do a reduction. | + `-----------------------------*/ + yyreduce: + yylen = yyr2_[yyn]; + { + stack_symbol_type yylhs; + yylhs.state = yy_lr_goto_state_ (yystack_[yylen].state, yyr1_[yyn]); + /* Variants are always initialized to an empty instance of the + correct type. The default '$$ = $1' action is NOT applied + when using variants. */ + switch (yyr1_[yyn]) + { + case symbol_kind::S_CompUnit: // CompUnit + yylhs.value.emplace< SyntaxTree::Assembly* > (); + break; + + case symbol_kind::S_Block: // Block + yylhs.value.emplace< SyntaxTree::BlockStmt* > (); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + yylhs.value.emplace< SyntaxTree::Expr* > (); + break; + + case symbol_kind::S_FuncDef: // FuncDef + yylhs.value.emplace< SyntaxTree::FuncDef* > (); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + yylhs.value.emplace< SyntaxTree::FuncParam* > (); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + yylhs.value.emplace< SyntaxTree::InitVal* > (); + break; + + case symbol_kind::S_LVal: // LVal + yylhs.value.emplace< SyntaxTree::LVal* > (); + break; + + case symbol_kind::S_Number: // Number + yylhs.value.emplace< SyntaxTree::Literal* > (); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + yylhs.value.emplace< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + yylhs.value.emplace< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + yylhs.value.emplace< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + yylhs.value.emplace< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + yylhs.value.emplace< SyntaxTree::PtrList > (); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + yylhs.value.emplace< SyntaxTree::Stmt* > (); + break; + + case symbol_kind::S_BType: // BType + yylhs.value.emplace< SyntaxTree::Type > (); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + yylhs.value.emplace< SyntaxTree::VarDef* > (); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + yylhs.value.emplace< float > (); + break; + + case symbol_kind::S_INTCONST: // INTCONST + yylhs.value.emplace< int > (); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + yylhs.value.emplace< std::string > (); + break; + + default: + break; + } + + + // Default location. + { + stack_type::slice range (yystack_, yylen); + YYLLOC_DEFAULT (yylhs.location, range, yylen); + yyerror_range[1].location = yylhs.location; + } + + // Perform the reduction. + YY_REDUCE_PRINT (yyn); +#if YY_EXCEPTIONS + try +#endif // YY_EXCEPTIONS + { + switch (yyn) + { + case 2: // Begin: CompUnit END +#line 106 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[1].value.as < SyntaxTree::Assembly* > ()->loc = yylhs.location; + driver.root = yystack_[1].value.as < SyntaxTree::Assembly* > (); + return 0; + } +#line 1021 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 3: // CompUnit: CompUnit GlobalDecl +#line 113 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[1].value.as < SyntaxTree::Assembly* > ()->global_defs.insert(yystack_[1].value.as < SyntaxTree::Assembly* > ()->global_defs.end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + yylhs.value.as < SyntaxTree::Assembly* > ()=yystack_[1].value.as < SyntaxTree::Assembly* > (); + } +#line 1030 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 4: // CompUnit: GlobalDecl +#line 117 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Assembly* > ()=new SyntaxTree::Assembly(); + yylhs.value.as < SyntaxTree::Assembly* > ()->global_defs.insert(yylhs.value.as < SyntaxTree::Assembly* > ()->global_defs.end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + } +#line 1039 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 5: // GlobalDecl: ConstDecl +#line 123 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().insert(yylhs.value.as < SyntaxTree::PtrList > ().end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + } +#line 1048 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 6: // GlobalDecl: VarDecl +#line 127 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().insert(yylhs.value.as < SyntaxTree::PtrList > ().end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + } +#line 1057 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 7: // GlobalDecl: FuncDef +#line 131 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::FuncDef* > ())); + } +#line 1066 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 8: // ConstDecl: CONST BType ConstDefList SEMICOLON +#line 137 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=yystack_[1].value.as < SyntaxTree::PtrList > (); + for (auto &node : yylhs.value.as < SyntaxTree::PtrList > ()) { + node->btype = yystack_[2].value.as < SyntaxTree::Type > (); + } + } +#line 1077 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 9: // ConstDefList: ConstDefList COMMA ConstDef +#line 144 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[2].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::VarDef* > ())); + yylhs.value.as < SyntaxTree::PtrList > ()=yystack_[2].value.as < SyntaxTree::PtrList > (); + } +#line 1086 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 10: // ConstDefList: ConstDef +#line 148 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::VarDef* > ())); + } +#line 1095 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 11: // BType: INT +#line 154 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Type > ()=SyntaxTree::Type::INT; + } +#line 1103 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 12: // BType: FLOAT +#line 157 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Type > ()=SyntaxTree::Type::FLOAT; + } +#line 1111 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 13: // ConstDef: IDENTIFIER ArrayExpList ASSIGN InitVal +#line 163 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::VarDef* > ()=new SyntaxTree::VarDef(); + yylhs.value.as < SyntaxTree::VarDef* > ()->is_constant = true; + yylhs.value.as < SyntaxTree::VarDef* > ()->is_inited = true; + yylhs.value.as < SyntaxTree::VarDef* > ()->name=yystack_[3].value.as < std::string > (); + yylhs.value.as < SyntaxTree::VarDef* > ()->array_length = yystack_[2].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::VarDef* > ()->initializers = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::InitVal* > ()); + yylhs.value.as < SyntaxTree::VarDef* > ()->loc = yylhs.location; + } +#line 1125 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 14: // VarDecl: BType VarDefList SEMICOLON +#line 174 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=yystack_[1].value.as < SyntaxTree::PtrList > (); + for (auto &node : yylhs.value.as < SyntaxTree::PtrList > ()) { + node->btype = yystack_[2].value.as < SyntaxTree::Type > (); + } + } +#line 1136 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 15: // VarDefList: VarDefList COMMA VarDef +#line 182 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[2].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::VarDef* > ())); + yylhs.value.as < SyntaxTree::PtrList > ()=yystack_[2].value.as < SyntaxTree::PtrList > (); + } +#line 1145 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 16: // VarDefList: VarDef +#line 186 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::VarDef* > ())); + } +#line 1154 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 17: // VarDef: IDENTIFIER ArrayExpList +#line 192 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::VarDef* > ()=new SyntaxTree::VarDef(); + yylhs.value.as < SyntaxTree::VarDef* > ()->name=yystack_[1].value.as < std::string > (); + yylhs.value.as < SyntaxTree::VarDef* > ()->array_length = yystack_[0].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::VarDef* > ()->is_inited = false; + yylhs.value.as < SyntaxTree::VarDef* > ()->loc = yylhs.location; + } +#line 1166 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 18: // VarDef: IDENTIFIER ArrayExpList ASSIGN InitVal +#line 199 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::VarDef* > () = new SyntaxTree::VarDef(); + yylhs.value.as < SyntaxTree::VarDef* > ()->name = yystack_[3].value.as < std::string > (); + yylhs.value.as < SyntaxTree::VarDef* > ()->array_length = yystack_[2].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::VarDef* > ()->initializers = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::InitVal* > ()); + yylhs.value.as < SyntaxTree::VarDef* > ()->is_inited = true; + yylhs.value.as < SyntaxTree::VarDef* > ()->loc = yylhs.location; + } +#line 1179 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 19: // ArrayExpList: ArrayExpList LBRACKET Exp RBRACKET +#line 209 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[3].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::Expr* > ())); + yylhs.value.as < SyntaxTree::PtrList > ()=yystack_[3].value.as < SyntaxTree::PtrList > (); + } +#line 1188 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 20: // ArrayExpList: %empty +#line 213 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > ()=SyntaxTree::PtrList(); + } +#line 1196 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 21: // InitVal: Exp +#line 218 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::InitVal* > () = new SyntaxTree::InitVal(); + yylhs.value.as < SyntaxTree::InitVal* > ()->isExp = true; + yylhs.value.as < SyntaxTree::InitVal* > ()->elementList = SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::InitVal* > ()->expr = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::InitVal* > ()->loc = yylhs.location; + } +#line 1208 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 22: // InitVal: LBRACE InitValList RBRACE +#line 225 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::InitVal* > () = yystack_[1].value.as < SyntaxTree::InitVal* > (); + } +#line 1216 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 23: // InitValList: CommaInitValList InitVal +#line 230 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[1].value.as < SyntaxTree::InitVal* > ()->elementList.push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::InitVal* > ())); + yylhs.value.as < SyntaxTree::InitVal* > () = yystack_[1].value.as < SyntaxTree::InitVal* > (); + } +#line 1225 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 24: // InitValList: %empty +#line 234 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::InitVal* > () = new SyntaxTree::InitVal(); + yylhs.value.as < SyntaxTree::InitVal* > ()->isExp = false; + yylhs.value.as < SyntaxTree::InitVal* > ()->elementList = SyntaxTree::PtrList(); + //$$->elementList = std::vector>(); + yylhs.value.as < SyntaxTree::InitVal* > ()->expr = nullptr; + yylhs.value.as < SyntaxTree::InitVal* > ()->loc = yylhs.location; + } +#line 1238 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 25: // CommaInitValList: CommaInitValList InitVal COMMA +#line 244 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[2].value.as < SyntaxTree::InitVal* > ()->elementList.push_back(SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::InitVal* > ())); + yylhs.value.as < SyntaxTree::InitVal* > () = yystack_[2].value.as < SyntaxTree::InitVal* > (); + } +#line 1247 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 26: // CommaInitValList: %empty +#line 248 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::InitVal* > () = new SyntaxTree::InitVal(); + yylhs.value.as < SyntaxTree::InitVal* > ()->isExp = false; + yylhs.value.as < SyntaxTree::InitVal* > ()->elementList = SyntaxTree::PtrList(); + //$$->elementList = std::vector>(); + yylhs.value.as < SyntaxTree::InitVal* > ()->expr = nullptr; + yylhs.value.as < SyntaxTree::InitVal* > ()->loc = yylhs.location; + } +#line 1260 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 27: // ExpList: CommaExpList Exp +#line 258 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[1].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ())); + yylhs.value.as < SyntaxTree::PtrList > () = yystack_[1].value.as < SyntaxTree::PtrList > (); + } +#line 1269 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 28: // ExpList: %empty +#line 262 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); + } +#line 1277 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 29: // CommaExpList: CommaExpList Exp COMMA +#line 267 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[2].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::Expr* > ())); + yylhs.value.as < SyntaxTree::PtrList > () = yystack_[2].value.as < SyntaxTree::PtrList > (); + } +#line 1286 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 30: // CommaExpList: %empty +#line 271 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); + } +#line 1294 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 31: // FuncFParam: BType IDENTIFIER ArrayExpList +#line 277 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::FuncParam* > () = new SyntaxTree::FuncParam(); + yylhs.value.as < SyntaxTree::FuncParam* > ()->param_type = yystack_[2].value.as < SyntaxTree::Type > (); + yylhs.value.as < SyntaxTree::FuncParam* > ()->name = yystack_[1].value.as < std::string > (); + yylhs.value.as < SyntaxTree::FuncParam* > ()->array_index = yystack_[0].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::FuncParam* > ()->loc = yylhs.location; +} +#line 1306 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 32: // FuncFParam: BType IDENTIFIER LRBRACKET ArrayExpList +#line 284 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::FuncParam* > () = new SyntaxTree::FuncParam(); + yylhs.value.as < SyntaxTree::FuncParam* > ()->param_type = yystack_[3].value.as < SyntaxTree::Type > (); + yylhs.value.as < SyntaxTree::FuncParam* > ()->name = yystack_[2].value.as < std::string > (); + yylhs.value.as < SyntaxTree::FuncParam* > ()->array_index = yystack_[0].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::FuncParam* > ()->array_index.insert(yylhs.value.as < SyntaxTree::FuncParam* > ()->array_index.begin(),nullptr); + yylhs.value.as < SyntaxTree::FuncParam* > ()->loc = yylhs.location; +} +#line 1319 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 33: // FParamList: CommaFParamList FuncFParam +#line 294 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[1].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::FuncParam* > ())); + yylhs.value.as < SyntaxTree::PtrList > () = yystack_[1].value.as < SyntaxTree::PtrList > (); +} +#line 1328 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 34: // FParamList: %empty +#line 298 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); +} +#line 1336 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 35: // CommaFParamList: CommaFParamList FuncFParam COMMA +#line 303 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[2].value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::FuncParam* > ())); + yylhs.value.as < SyntaxTree::PtrList > () = yystack_[2].value.as < SyntaxTree::PtrList > (); +} +#line 1345 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 36: // CommaFParamList: %empty +#line 307 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); +} +#line 1353 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 37: // FuncDef: BType IDENTIFIER LPARENTHESE FParamList RPARENTHESE Block +#line 311 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::FuncDef* > () = new SyntaxTree::FuncDef(); + yylhs.value.as < SyntaxTree::FuncDef* > ()->ret_type = yystack_[5].value.as < SyntaxTree::Type > (); + yylhs.value.as < SyntaxTree::FuncDef* > ()->name = yystack_[4].value.as < std::string > (); + auto tmp = new SyntaxTree::FuncFParamList(); + tmp->params = yystack_[2].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::FuncDef* > ()->param_list = SyntaxTree::Ptr(tmp); + yylhs.value.as < SyntaxTree::FuncDef* > ()->body = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::BlockStmt* > ()); + yylhs.value.as < SyntaxTree::FuncDef* > ()->loc = yylhs.location; + } +#line 1368 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 38: // FuncDef: VOID IDENTIFIER LPARENTHESE FParamList RPARENTHESE Block +#line 321 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::FuncDef* > () = new SyntaxTree::FuncDef(); + yylhs.value.as < SyntaxTree::FuncDef* > ()->ret_type = SyntaxTree::Type::VOID; + yylhs.value.as < SyntaxTree::FuncDef* > ()->name = yystack_[4].value.as < std::string > (); + auto tmp = new SyntaxTree::FuncFParamList(); + tmp->params = yystack_[2].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::FuncDef* > ()->param_list = SyntaxTree::Ptr(tmp); + yylhs.value.as < SyntaxTree::FuncDef* > ()->body = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::BlockStmt* > ()); + yylhs.value.as < SyntaxTree::FuncDef* > ()->loc = yylhs.location; + } +#line 1383 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 39: // Block: LBRACE BlockItemList RBRACE +#line 333 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::BlockStmt* > () = new SyntaxTree::BlockStmt(); + yylhs.value.as < SyntaxTree::BlockStmt* > ()->body = yystack_[1].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::BlockStmt* > ()->loc = yylhs.location; + } +#line 1393 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 40: // BlockItemList: BlockItemList BlockItem +#line 340 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yystack_[1].value.as < SyntaxTree::PtrList > ().insert(yystack_[1].value.as < SyntaxTree::PtrList > ().end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + yylhs.value.as < SyntaxTree::PtrList > () = yystack_[1].value.as < SyntaxTree::PtrList > (); + } +#line 1402 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 41: // BlockItemList: %empty +#line 344 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); + } +#line 1410 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 42: // BlockItem: VarDecl +#line 349 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().insert(yylhs.value.as < SyntaxTree::PtrList > ().end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + } +#line 1419 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 43: // BlockItem: ConstDecl +#line 353 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().insert(yylhs.value.as < SyntaxTree::PtrList > ().end(), yystack_[0].value.as < SyntaxTree::PtrList > ().begin(), yystack_[0].value.as < SyntaxTree::PtrList > ().end()); + } +#line 1428 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 44: // BlockItem: Stmt +#line 357 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::PtrList > () = SyntaxTree::PtrList(); + yylhs.value.as < SyntaxTree::PtrList > ().push_back(SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Stmt* > ())); + } +#line 1437 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 45: // Stmt: LVal ASSIGN Exp SEMICOLON +#line 363 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::AssignStmt(); + temp->target = SyntaxTree::Ptr(yystack_[3].value.as < SyntaxTree::LVal* > ()); + temp->value = SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Stmt* > () = temp; + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1449 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 46: // Stmt: Exp SEMICOLON +#line 370 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::ExprStmt(); + temp->exp = SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Stmt* > () = temp; + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1460 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 47: // Stmt: RETURN OptionRet SEMICOLON +#line 376 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::ReturnStmt(); + temp->ret = SyntaxTree::Ptr(yystack_[1].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Stmt* > () = temp; + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1471 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 48: // Stmt: Block +#line 382 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Stmt* > () = yystack_[0].value.as < SyntaxTree::BlockStmt* > (); + } +#line 1479 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 49: // Stmt: WHILE LPARENTHESE CondExp RPARENTHESE Stmt +#line 385 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::WhileStmt(); + temp->cond_exp = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->statement = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Stmt* > ()); + yylhs.value.as < SyntaxTree::Stmt* > () = temp; + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1491 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 50: // Stmt: IfStmt +#line 392 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Stmt* > () = yystack_[0].value.as < SyntaxTree::Stmt* > (); + } +#line 1499 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 51: // Stmt: BREAK SEMICOLON +#line 395 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Stmt* > () = new SyntaxTree::BreakStmt(); + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1508 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 52: // Stmt: CONTINUE SEMICOLON +#line 399 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Stmt* > () = new SyntaxTree::ContinueStmt(); + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1517 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 53: // Stmt: SEMICOLON +#line 403 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Stmt* > () = new SyntaxTree::EmptyStmt(); + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1526 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 54: // IfStmt: IF LPARENTHESE CondExp RPARENTHESE Stmt +#line 409 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::IfStmt(); + temp->cond_exp = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->if_statement = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Stmt* > ()); + temp->else_statement = nullptr; + yylhs.value.as < SyntaxTree::Stmt* > () = temp; + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1539 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 55: // IfStmt: IF LPARENTHESE CondExp RPARENTHESE Stmt ELSE Stmt +#line 417 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::IfStmt(); + temp->cond_exp = SyntaxTree::Ptr(yystack_[4].value.as < SyntaxTree::Expr* > ()); + temp->if_statement = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Stmt* > ()); + temp->else_statement = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Stmt* > ()); + yylhs.value.as < SyntaxTree::Stmt* > () = temp; + yylhs.value.as < SyntaxTree::Stmt* > ()->loc = yylhs.location; + } +#line 1552 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 56: // OptionRet: Exp +#line 427 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Expr* > (); + } +#line 1560 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 57: // OptionRet: %empty +#line 430 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = nullptr; + } +#line 1568 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 58: // LVal: IDENTIFIER ArrayExpList +#line 435 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::LVal* > () = new SyntaxTree::LVal(); + yylhs.value.as < SyntaxTree::LVal* > ()->name = yystack_[1].value.as < std::string > (); + yylhs.value.as < SyntaxTree::LVal* > ()->array_index = yystack_[0].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::LVal* > ()->loc = yylhs.location; + } +#line 1579 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 59: // Exp: PLUS Exp +#line 447 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::UnaryExpr(); + temp->op = SyntaxTree::UnaryOp::PLUS; + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1591 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 60: // Exp: MINUS Exp +#line 454 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::UnaryExpr(); + temp->op = SyntaxTree::UnaryOp::MINUS; + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1603 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 61: // Exp: NOT Exp +#line 461 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::UnaryCondExpr(); + temp->op = SyntaxTree::UnaryCondOp::NOT; + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1615 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 62: // Exp: Exp PLUS Exp +#line 468 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryExpr(); + temp->op = SyntaxTree::BinOp::PLUS; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1628 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 63: // Exp: Exp MINUS Exp +#line 476 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryExpr(); + temp->op = SyntaxTree::BinOp::MINUS; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1641 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 64: // Exp: Exp MULTIPLY Exp +#line 484 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryExpr(); + temp->op = SyntaxTree::BinOp::MULTIPLY; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1654 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 65: // Exp: Exp DIVIDE Exp +#line 492 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryExpr(); + temp->op = SyntaxTree::BinOp::DIVIDE; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1667 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 66: // Exp: Exp MODULO Exp +#line 500 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryExpr(); + temp->op = SyntaxTree::BinOp::MODULO; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1680 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 67: // Exp: LPARENTHESE Exp RPARENTHESE +#line 508 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[1].value.as < SyntaxTree::Expr* > (); + } +#line 1688 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 68: // Exp: IDENTIFIER LPARENTHESE ExpList RPARENTHESE +#line 511 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::FuncCallStmt(); + temp->name = yystack_[3].value.as < std::string > (); + temp->params = yystack_[1].value.as < SyntaxTree::PtrList > (); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1700 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 69: // Exp: LVal +#line 518 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::LVal* > (); + } +#line 1708 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 70: // Exp: Number +#line 521 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Literal* > (); + } +#line 1716 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 71: // RelExp: RelExp LT Exp +#line 526 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::LT; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1729 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 72: // RelExp: RelExp LTE Exp +#line 534 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::LTE; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1742 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 73: // RelExp: RelExp GT Exp +#line 542 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::GT; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1755 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 74: // RelExp: RelExp GTE Exp +#line 550 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::GTE; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1768 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 75: // RelExp: Exp +#line 558 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Expr* > (); + } +#line 1776 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 76: // EqExp: EqExp EQ RelExp +#line 563 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::EQ; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1789 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 77: // EqExp: EqExp NEQ RelExp +#line 571 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::NEQ; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1802 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 78: // EqExp: RelExp +#line 579 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Expr* > (); + } +#line 1810 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 79: // LAndExp: LAndExp LOGICAND EqExp +#line 584 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::LAND; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1823 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 80: // LAndExp: EqExp +#line 592 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Expr* > (); + } +#line 1831 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 81: // LOrExp: LOrExp LOGICOR LAndExp +#line 597 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + auto temp = new SyntaxTree::BinaryCondExpr(); + temp->op = SyntaxTree::BinaryCondOp::LOR; + temp->lhs = SyntaxTree::Ptr(yystack_[2].value.as < SyntaxTree::Expr* > ()); + temp->rhs = SyntaxTree::Ptr(yystack_[0].value.as < SyntaxTree::Expr* > ()); + yylhs.value.as < SyntaxTree::Expr* > () = temp; + yylhs.value.as < SyntaxTree::Expr* > ()->loc = yylhs.location; + } +#line 1844 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 82: // LOrExp: LAndExp +#line 605 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Expr* > (); + } +#line 1852 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 83: // CondExp: LOrExp +#line 610 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Expr* > () = yystack_[0].value.as < SyntaxTree::Expr* > (); + } +#line 1860 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 84: // Number: INTCONST +#line 615 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Literal* > () = new SyntaxTree::Literal(); + yylhs.value.as < SyntaxTree::Literal* > ()->literal_type = SyntaxTree::Type::INT; + yylhs.value.as < SyntaxTree::Literal* > ()->int_const = yystack_[0].value.as < int > (); + yylhs.value.as < SyntaxTree::Literal* > ()->loc = yylhs.location; + } +#line 1871 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + case 85: // Number: FLOATCONST +#line 621 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + { + yylhs.value.as < SyntaxTree::Literal* > () = new SyntaxTree::Literal(); + yylhs.value.as < SyntaxTree::Literal* > ()->literal_type = SyntaxTree::Type::FLOAT; + yylhs.value.as < SyntaxTree::Literal* > ()->float_const = yystack_[0].value.as < float > (); + yylhs.value.as < SyntaxTree::Literal* > ()->loc = yylhs.location; + } +#line 1882 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + break; + + +#line 1886 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + + default: + break; + } + } +#if YY_EXCEPTIONS + catch (const syntax_error& yyexc) + { + YYCDEBUG << "Caught exception: " << yyexc.what() << '\n'; + error (yyexc); + YYERROR; + } +#endif // YY_EXCEPTIONS + YY_SYMBOL_PRINT ("-> $$ =", yylhs); + yypop_ (yylen); + yylen = 0; + + // Shift the result of the reduction. + yypush_ (YY_NULLPTR, YY_MOVE (yylhs)); + } + goto yynewstate; + + + /*--------------------------------------. + | yyerrlab -- here on detecting error. | + `--------------------------------------*/ + yyerrlab: + // If not already recovering from an error, report this error. + if (!yyerrstatus_) + { + ++yynerrs_; + context yyctx (*this, yyla); + std::string msg = yysyntax_error_ (yyctx); + error (yyla.location, YY_MOVE (msg)); + } + + + yyerror_range[1].location = yyla.location; + if (yyerrstatus_ == 3) + { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + // Return failure if at end of input. + if (yyla.kind () == symbol_kind::S_YYEOF) + YYABORT; + else if (!yyla.empty ()) + { + yy_destroy_ ("Error: discarding", yyla); + yyla.clear (); + } + } + + // Else will try to reuse lookahead token after shifting the error token. + goto yyerrlab1; + + + /*---------------------------------------------------. + | yyerrorlab -- error raised explicitly by YYERROR. | + `---------------------------------------------------*/ + yyerrorlab: + /* Pacify compilers when the user code never invokes YYERROR and + the label yyerrorlab therefore never appears in user code. */ + if (false) + YYERROR; + + /* Do not reclaim the symbols of the rule whose action triggered + this YYERROR. */ + yypop_ (yylen); + yylen = 0; + YY_STACK_PRINT (); + goto yyerrlab1; + + + /*-------------------------------------------------------------. + | yyerrlab1 -- common code for both syntax error and YYERROR. | + `-------------------------------------------------------------*/ + yyerrlab1: + yyerrstatus_ = 3; // Each real token shifted decrements this. + // Pop stack until we find a state that shifts the error token. + for (;;) + { + yyn = yypact_[+yystack_[0].state]; + if (!yy_pact_value_is_default_ (yyn)) + { + yyn += symbol_kind::S_YYerror; + if (0 <= yyn && yyn <= yylast_ + && yycheck_[yyn] == symbol_kind::S_YYerror) + { + yyn = yytable_[yyn]; + if (0 < yyn) + break; + } + } + + // Pop the current state because it cannot handle the error token. + if (yystack_.size () == 1) + YYABORT; + + yyerror_range[1].location = yystack_[0].location; + yy_destroy_ ("Error: popping", yystack_[0]); + yypop_ (); + YY_STACK_PRINT (); + } + { + stack_symbol_type error_token; + + yyerror_range[2].location = yyla.location; + YYLLOC_DEFAULT (error_token.location, yyerror_range, 2); + + // Shift the error token. + error_token.state = state_type (yyn); + yypush_ ("Shifting", YY_MOVE (error_token)); + } + goto yynewstate; + + + /*-------------------------------------. + | yyacceptlab -- YYACCEPT comes here. | + `-------------------------------------*/ + yyacceptlab: + yyresult = 0; + goto yyreturn; + + + /*-----------------------------------. + | yyabortlab -- YYABORT comes here. | + `-----------------------------------*/ + yyabortlab: + yyresult = 1; + goto yyreturn; + + + /*-----------------------------------------------------. + | yyreturn -- parsing is finished, return the result. | + `-----------------------------------------------------*/ + yyreturn: + if (!yyla.empty ()) + yy_destroy_ ("Cleanup: discarding lookahead", yyla); + + /* Do not reclaim the symbols of the rule whose action triggered + this YYABORT or YYACCEPT. */ + yypop_ (yylen); + YY_STACK_PRINT (); + while (1 < yystack_.size ()) + { + yy_destroy_ ("Cleanup: popping", yystack_[0]); + yypop_ (); + } + + return yyresult; + } +#if YY_EXCEPTIONS + catch (...) + { + YYCDEBUG << "Exception caught: cleaning lookahead and stack\n"; + // Do not try to display the values of the reclaimed symbols, + // as their printers might throw an exception. + if (!yyla.empty ()) + yy_destroy_ (YY_NULLPTR, yyla); + + while (1 < yystack_.size ()) + { + yy_destroy_ (YY_NULLPTR, yystack_[0]); + yypop_ (); + } + throw; + } +#endif // YY_EXCEPTIONS + } + + void + SysYParser::error (const syntax_error& yyexc) + { + error (yyexc.location, yyexc.what ()); + } + + /* Return YYSTR after stripping away unnecessary quotes and + backslashes, so that it's suitable for yyerror. The heuristic is + that double-quoting is unnecessary unless the string contains an + apostrophe, a comma, or backslash (other than backslash-backslash). + YYSTR is taken from yytname. */ + std::string + SysYParser::yytnamerr_ (const char *yystr) + { + if (*yystr == '"') + { + std::string yyr; + char const *yyp = yystr; + + for (;;) + switch (*++yyp) + { + case '\'': + case ',': + goto do_not_strip_quotes; + + case '\\': + if (*++yyp != '\\') + goto do_not_strip_quotes; + else + goto append; + + append: + default: + yyr += *yyp; + break; + + case '"': + return yyr; + } + do_not_strip_quotes: ; + } + + return yystr; + } + + std::string + SysYParser::symbol_name (symbol_kind_type yysymbol) + { + return yytnamerr_ (yytname_[yysymbol]); + } + + + + // SysYParser::context. + SysYParser::context::context (const SysYParser& yyparser, const symbol_type& yyla) + : yyparser_ (yyparser) + , yyla_ (yyla) + {} + + int + SysYParser::context::expected_tokens (symbol_kind_type yyarg[], int yyargn) const + { + // Actual number of expected tokens + int yycount = 0; + + int yyn = yypact_[+yyparser_.yystack_[0].state]; + if (!yy_pact_value_is_default_ (yyn)) + { + /* Start YYX at -YYN if negative to avoid negative indexes in + YYCHECK. In other words, skip the first -YYN actions for + this state because they are default actions. */ + int yyxbegin = yyn < 0 ? -yyn : 0; + // Stay within bounds of both yycheck and yytname. + int yychecklim = yylast_ - yyn + 1; + int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; + for (int yyx = yyxbegin; yyx < yyxend; ++yyx) + if (yycheck_[yyx + yyn] == yyx && yyx != symbol_kind::S_YYerror + && !yy_table_value_is_error_ (yytable_[yyx + yyn])) + { + if (!yyarg) + ++yycount; + else if (yycount == yyargn) + return 0; + else + yyarg[yycount++] = YY_CAST (symbol_kind_type, yyx); + } + } + + if (yyarg && yycount == 0 && 0 < yyargn) + yyarg[0] = symbol_kind::S_YYEMPTY; + return yycount; + } + + + + int + SysYParser::yy_syntax_error_arguments_ (const context& yyctx, + symbol_kind_type yyarg[], int yyargn) const + { + /* There are many possibilities here to consider: + - If this state is a consistent state with a default action, then + the only way this function was invoked is if the default action + is an error action. In that case, don't check for expected + tokens because there are none. + - The only way there can be no lookahead present (in yyla) is + if this state is a consistent state with a default action. + Thus, detecting the absence of a lookahead is sufficient to + determine that there is no unexpected or expected token to + report. In that case, just report a simple "syntax error". + - Don't assume there isn't a lookahead just because this state is + a consistent state with a default action. There might have + been a previous inconsistent state, consistent state with a + non-default action, or user semantic action that manipulated + yyla. (However, yyla is currently not documented for users.) + - Of course, the expected token list depends on states to have + correct lookahead information, and it depends on the parser not + to perform extra reductions after fetching a lookahead from the + scanner and before detecting a syntax error. Thus, state merging + (from LALR or IELR) and default reductions corrupt the expected + token list. However, the list is correct for canonical LR with + one exception: it will still contain any token that will not be + accepted due to an error action in a later state. + */ + + if (!yyctx.lookahead ().empty ()) + { + if (yyarg) + yyarg[0] = yyctx.token (); + int yyn = yyctx.expected_tokens (yyarg ? yyarg + 1 : yyarg, yyargn - 1); + return yyn + 1; + } + return 0; + } + + // Generate an error message. + std::string + SysYParser::yysyntax_error_ (const context& yyctx) const + { + // Its maximum. + enum { YYARGS_MAX = 5 }; + // Arguments of yyformat. + symbol_kind_type yyarg[YYARGS_MAX]; + int yycount = yy_syntax_error_arguments_ (yyctx, yyarg, YYARGS_MAX); + + char const* yyformat = YY_NULLPTR; + switch (yycount) + { +#define YYCASE_(N, S) \ + case N: \ + yyformat = S; \ + break + default: // Avoid compiler warnings. + YYCASE_ (0, YY_("syntax error")); + YYCASE_ (1, YY_("syntax error, unexpected %s")); + YYCASE_ (2, YY_("syntax error, unexpected %s, expecting %s")); + YYCASE_ (3, YY_("syntax error, unexpected %s, expecting %s or %s")); + YYCASE_ (4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); + YYCASE_ (5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); +#undef YYCASE_ + } + + std::string yyres; + // Argument number. + std::ptrdiff_t yyi = 0; + for (char const* yyp = yyformat; *yyp; ++yyp) + if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount) + { + yyres += symbol_name (yyarg[yyi++]); + ++yyp; + } + else + yyres += *yyp; + return yyres; + } + + + const signed char SysYParser::yypact_ninf_ = -116; + + const signed char SysYParser::yytable_ninf_ = -35; + + const short + SysYParser::yypact_[] = + { + -8, -116, -25, -18, -116, 9, 20, -116, -116, -3, + -116, -116, -5, 5, -116, -116, -116, 27, 136, -116, + 28, -116, 138, -116, 28, 10, -116, 30, 39, -18, + 29, -116, 5, 46, 116, 119, -116, -116, 52, 48, + 63, 116, -116, 52, 119, 119, 119, 62, 71, -116, + -116, 119, -116, -116, 172, -116, 47, -116, -116, 55, + -116, -116, -116, -116, -116, 155, 85, 116, 95, 96, + -116, 119, 119, 119, 119, 119, -116, 61, -116, 96, + -116, -116, 110, 99, 119, 135, 135, -116, -116, -116, + -116, -116, 111, 119, 127, 154, 156, -116, 30, -116, + -116, -116, -116, -116, 158, 104, 96, -116, -116, 64, + 119, 159, 172, 119, -116, -116, 119, -116, -116, 172, + 4, 122, 126, 137, 163, -116, 165, 160, 119, 119, + 119, 119, 119, 119, 119, 119, 101, 101, -116, 172, + 172, 172, 172, 4, 4, 122, 126, 161, -116, 101, + -116 + }; + + const signed char + SysYParser::yydefact_[] = + { + 0, 11, 0, 0, 12, 0, 0, 4, 5, 0, + 6, 7, 0, 0, 1, 2, 3, 20, 0, 16, + 36, 20, 0, 10, 36, 17, 14, 0, 0, 0, + 0, 8, 0, 0, 0, 0, 20, 15, 0, 0, + 33, 0, 9, 0, 0, 0, 0, 26, 20, 85, + 84, 0, 18, 69, 21, 70, 0, 41, 38, 20, + 35, 13, 37, 59, 60, 0, 0, 0, 30, 58, + 61, 0, 0, 0, 0, 0, 19, 0, 20, 31, + 67, 22, 23, 0, 0, 62, 63, 64, 65, 66, + 53, 39, 0, 57, 0, 0, 0, 43, 0, 42, + 48, 40, 44, 50, 69, 0, 32, 25, 68, 27, + 0, 0, 56, 0, 51, 52, 0, 46, 29, 75, + 78, 80, 82, 83, 0, 47, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 45, 72, + 73, 74, 71, 76, 77, 79, 81, 54, 49, 0, + 55 + }; + + const short + SysYParser::yypgoto_[] = + { + -116, -116, -116, 180, 112, -116, -1, 162, 113, -116, + 164, -17, -35, -116, -116, -116, -116, -116, 168, -116, + -116, -19, -116, -116, -115, -116, -116, -74, -34, 25, + 53, 58, -116, 75, -116 + }; + + const signed char + SysYParser::yydefgoto_[] = + { + 0, 5, 6, 7, 8, 22, 9, 23, 10, 18, + 19, 25, 52, 66, 67, 83, 84, 40, 28, 29, + 11, 100, 77, 101, 102, 103, 111, 53, 119, 120, + 121, 122, 123, 124, 55 + }; + + const short + SysYParser::yytable_[] = + { + 54, 56, 13, 104, 30, 12, 61, 54, 1, 14, + 63, 64, 65, 20, 128, 129, 130, 70, 1, 58, + 2, 147, 148, 15, 62, 34, 4, 17, 39, 3, + 35, 69, 82, 54, 150, 21, 4, 85, 86, 87, + 88, 89, 79, 105, 41, 24, 1, -34, 2, 35, + 109, 131, 71, 72, 73, 74, 75, 3, 38, 112, + 36, 106, 104, 104, 4, 43, 44, 45, 76, 71, + 72, 73, 74, 75, 57, 104, 98, 90, 59, 46, + 60, 118, 127, 57, 91, -24, 92, 1, 93, 68, + 94, 48, 49, 50, 139, 140, 141, 142, 3, 95, + 96, 51, 105, 105, 78, 4, 44, 45, 81, 71, + 72, 73, 74, 75, -28, 105, 35, 90, 108, 46, + 117, 44, 45, 57, 44, 45, 92, 107, 93, 110, + 94, 48, 49, 50, 46, 132, 133, 46, 47, 95, + 96, 51, 73, 74, 75, 113, 48, 49, 50, 48, + 49, 50, 26, 27, 31, 32, 51, 143, 144, 51, + 71, 72, 73, 74, 75, 71, 72, 73, 74, 75, + 114, 134, 115, 116, 80, 125, 138, 71, 72, 73, + 74, 75, 136, 135, 137, 149, 16, 145, 126, 97, + 99, 37, 33, 146, 42 + }; + + const unsigned char + SysYParser::yycheck_[] = + { + 34, 35, 3, 77, 21, 30, 41, 41, 26, 0, + 44, 45, 46, 18, 10, 11, 12, 51, 26, 38, + 28, 136, 137, 3, 43, 15, 44, 30, 29, 37, + 20, 48, 67, 67, 149, 30, 44, 71, 72, 73, + 74, 75, 59, 77, 15, 18, 26, 19, 28, 20, + 84, 47, 5, 6, 7, 8, 9, 37, 19, 93, + 30, 78, 136, 137, 44, 19, 5, 6, 21, 5, + 6, 7, 8, 9, 22, 149, 77, 16, 30, 18, + 17, 17, 116, 22, 23, 23, 25, 26, 27, 18, + 29, 30, 31, 32, 128, 129, 130, 131, 37, 38, + 39, 40, 136, 137, 49, 44, 5, 6, 23, 5, + 6, 7, 8, 9, 19, 149, 20, 16, 19, 18, + 16, 5, 6, 22, 5, 6, 25, 17, 27, 18, + 29, 30, 31, 32, 18, 13, 14, 18, 22, 38, + 39, 40, 7, 8, 9, 18, 30, 31, 32, 30, + 31, 32, 16, 17, 16, 17, 40, 132, 133, 40, + 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, + 16, 45, 16, 15, 19, 16, 16, 5, 6, 7, + 8, 9, 19, 46, 19, 24, 6, 134, 113, 77, + 77, 27, 24, 135, 32 + }; + + const signed char + SysYParser::yystos_[] = + { + 0, 26, 28, 37, 44, 54, 55, 56, 57, 59, + 61, 73, 30, 59, 0, 3, 56, 30, 62, 63, + 18, 30, 58, 60, 18, 64, 16, 17, 71, 72, + 64, 16, 17, 71, 15, 20, 30, 63, 19, 59, + 70, 15, 60, 19, 5, 6, 18, 22, 30, 31, + 32, 40, 65, 80, 81, 87, 81, 22, 74, 30, + 17, 65, 74, 81, 81, 81, 66, 67, 18, 64, + 81, 5, 6, 7, 8, 9, 21, 75, 49, 64, + 19, 23, 65, 68, 69, 81, 81, 81, 81, 81, + 16, 23, 25, 27, 29, 38, 39, 57, 59, 61, + 74, 76, 77, 78, 80, 81, 64, 17, 19, 81, + 18, 79, 81, 18, 16, 16, 15, 16, 17, 81, + 82, 83, 84, 85, 86, 16, 86, 81, 10, 11, + 12, 47, 13, 14, 45, 46, 19, 19, 16, 81, + 81, 81, 81, 82, 82, 83, 84, 77, 77, 24, + 77 + }; + + const signed char + SysYParser::yyr1_[] = + { + 0, 53, 54, 55, 55, 56, 56, 56, 57, 58, + 58, 59, 59, 60, 61, 62, 62, 63, 63, 64, + 64, 65, 65, 66, 66, 67, 67, 68, 68, 69, + 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, + 75, 75, 76, 76, 76, 77, 77, 77, 77, 77, + 77, 77, 77, 77, 78, 78, 79, 79, 80, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 82, 82, 82, 82, 82, 83, 83, 83, 84, + 84, 85, 85, 86, 87, 87 + }; + + const signed char + SysYParser::yyr2_[] = + { + 0, 2, 2, 2, 1, 1, 1, 1, 4, 3, + 1, 1, 1, 4, 3, 3, 1, 2, 4, 4, + 0, 1, 3, 2, 0, 3, 0, 2, 0, 3, + 0, 3, 4, 2, 0, 3, 0, 6, 6, 3, + 2, 0, 1, 1, 1, 4, 2, 3, 1, 5, + 1, 2, 2, 1, 5, 7, 1, 0, 2, 2, + 2, 2, 3, 3, 3, 3, 3, 3, 4, 1, + 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, + 1, 3, 1, 1, 1, 1 + }; + + +#if YYDEBUG || 1 + // YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. + // First, the terminals, then, starting at \a YYNTOKENS, nonterminals. + const char* + const SysYParser::yytname_[] = + { + "\"end of file\"", "error", "\"invalid token\"", "END", "ERROR", "PLUS", + "MINUS", "MULTIPLY", "DIVIDE", "MODULO", "LTE", "GT", "GTE", "EQ", "NEQ", + "ASSIGN", "SEMICOLON", "COMMA", "LPARENTHESE", "RPARENTHESE", "LBRACKET", + "RBRACKET", "LBRACE", "RBRACE", "ELSE", "IF", "INT", "RETURN", "VOID", + "WHILE", "IDENTIFIER", "FLOATCONST", "INTCONST", "LETTER", "EOL", + "COMMENT", "BLANK", "CONST", "BREAK", "CONTINUE", "NOT", "AND", "OR", + "MOD", "FLOAT", "LOGICAND", "LOGICOR", "LT", "STRINGCONST", "LRBRACKET", + "UPLUS", "UMINUS", "UNOT", "$accept", "Begin", "CompUnit", "GlobalDecl", + "ConstDecl", "ConstDefList", "BType", "ConstDef", "VarDecl", + "VarDefList", "VarDef", "ArrayExpList", "InitVal", "InitValList", + "CommaInitValList", "ExpList", "CommaExpList", "FuncFParam", + "FParamList", "CommaFParamList", "FuncDef", "Block", "BlockItemList", + "BlockItem", "Stmt", "IfStmt", "OptionRet", "LVal", "Exp", "RelExp", + "EqExp", "LAndExp", "LOrExp", "CondExp", "Number", YY_NULLPTR + }; +#endif + + +#if YYDEBUG + const short + SysYParser::yyrline_[] = + { + 0, 106, 106, 113, 117, 123, 127, 131, 137, 144, + 148, 154, 157, 163, 174, 182, 186, 192, 199, 209, + 213, 218, 225, 230, 234, 244, 248, 258, 262, 267, + 271, 277, 284, 294, 298, 303, 307, 311, 321, 333, + 340, 344, 349, 353, 357, 363, 370, 376, 382, 385, + 392, 395, 399, 403, 409, 417, 427, 430, 435, 447, + 454, 461, 468, 476, 484, 492, 500, 508, 511, 518, + 521, 526, 534, 542, 550, 558, 563, 571, 579, 584, + 592, 597, 605, 610, 615, 621 + }; + + void + SysYParser::yy_stack_print_ () const + { + *yycdebug_ << "Stack now"; + for (stack_type::const_iterator + i = yystack_.begin (), + i_end = yystack_.end (); + i != i_end; ++i) + *yycdebug_ << ' ' << int (i->state); + *yycdebug_ << '\n'; + } + + void + SysYParser::yy_reduce_print_ (int yyrule) const + { + int yylno = yyrline_[yyrule]; + int yynrhs = yyr2_[yyrule]; + // Print the symbols being reduced, and their result. + *yycdebug_ << "Reducing stack by rule " << yyrule - 1 + << " (line " << yylno << "):\n"; + // The symbols being reduced. + for (int yyi = 0; yyi < yynrhs; yyi++) + YY_SYMBOL_PRINT (" $" << yyi + 1 << " =", + yystack_[(yynrhs) - (yyi + 1)]); + } +#endif // YYDEBUG + + +} // yy +#line 2467 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYParser.cpp" + +#line 629 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYParser.yy" + + +// Register errors to the driver: +void yy::SysYParser::error (const location_type& l, + const std::string& m) +{ + driver.error(l, m); +} diff --git a/src/Grammar/SysYScanner.cpp b/src/Grammar/SysYScanner.cpp new file mode 100644 index 0000000..003b9b8 --- /dev/null +++ b/src/Grammar/SysYScanner.cpp @@ -0,0 +1,2361 @@ +#line 2 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYScanner.cpp" + +#line 4 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYScanner.cpp" + +#define YY_INT_ALIGNED short int + +/* A lexical scanner generated by flex */ + +/* %not-for-header */ + +/* %if-c-only */ +/* %if-not-reentrant */ +/* %endif */ +/* %endif */ +/* %ok-for-header */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 0 +#if YY_FLEX_SUBMINOR_VERSION > 0 +#define FLEX_BETA +#endif + +/* %if-c++-only */ + /* The c++ scanner is a mess. The FlexLexer.h header file relies on the + * following macro. This is required in order to pass the c++-multiple-scanners + * test in the regression suite. We get reports that it breaks inheritance. + * We will address this in a future release of flex, or omit the C++ scanner + * altogether. + */ + #define yyFlexLexer yyFlexLexer +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* First, we deal with platform-specific or compiler-specific issues. */ + +/* begin standard C headers. */ +/* %if-c-only */ +/* %endif */ + +/* %if-tables-serialization */ +/* %endif */ +/* end standard C headers. */ + +/* %if-c-or-c++ */ +/* flex integer type definitions */ + +#ifndef FLEXINT_H +#define FLEXINT_H + +/* C99 systems have . Non-C99 systems may or may not. */ + +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + +/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, + * if you want the limit (max/min) macros for int types. + */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS 1 +#endif + +#include +typedef int8_t flex_int8_t; +typedef uint8_t flex_uint8_t; +typedef int16_t flex_int16_t; +typedef uint16_t flex_uint16_t; +typedef int32_t flex_int32_t; +typedef uint32_t flex_uint32_t; +#else +typedef signed char flex_int8_t; +typedef short int flex_int16_t; +typedef int flex_int32_t; +typedef unsigned char flex_uint8_t; +typedef unsigned short int flex_uint16_t; +typedef unsigned int flex_uint32_t; + +/* Limits of integral types. */ +#ifndef INT8_MIN +#define INT8_MIN (-128) +#endif +#ifndef INT16_MIN +#define INT16_MIN (-32767-1) +#endif +#ifndef INT32_MIN +#define INT32_MIN (-2147483647-1) +#endif +#ifndef INT8_MAX +#define INT8_MAX (127) +#endif +#ifndef INT16_MAX +#define INT16_MAX (32767) +#endif +#ifndef INT32_MAX +#define INT32_MAX (2147483647) +#endif +#ifndef UINT8_MAX +#define UINT8_MAX (255U) +#endif +#ifndef UINT16_MAX +#define UINT16_MAX (65535U) +#endif +#ifndef UINT32_MAX +#define UINT32_MAX (4294967295U) +#endif + +#endif /* ! C99 */ + +#endif /* ! FLEXINT_H */ + +/* %endif */ + +/* %if-c++-only */ +/* begin standard C++ headers. */ +#include +#include +#include +#include +#include +/* end standard C++ headers. */ +/* %endif */ + +#ifdef __cplusplus + +/* The "const" storage-class-modifier is valid. */ +#define YY_USE_CONST + +#else /* ! __cplusplus */ + +/* C99 requires __STDC__ to be defined as 1. */ +#if defined (__STDC__) + +#define YY_USE_CONST + +#endif /* defined (__STDC__) */ +#endif /* ! __cplusplus */ + +#ifdef YY_USE_CONST +#define yyconst const +#else +#define yyconst +#endif + +/* %not-for-header */ + +/* Returned upon end-of-file. */ +#define YY_NULL 0 +/* %ok-for-header */ + +/* %not-for-header */ + +/* Promotes a possibly negative, possibly signed char to an unsigned + * integer for use as an array index. If the signed char is negative, + * we want to instead treat it as an 8-bit unsigned char, hence the + * double cast. + */ +#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) +/* %ok-for-header */ + +/* %if-reentrant */ +/* %endif */ + +/* %if-not-reentrant */ + +/* %endif */ + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN (yy_start) = 1 + 2 * + +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START (((yy_start) - 1) / 2) +#define YYSTATE YY_START + +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) + +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE yyrestart( yyin ) + +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else +#define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ +#endif + +/* The state buf must be large enough to hold one state per character in the main buffer. + */ +#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) + +#ifndef YY_TYPEDEF_YY_BUFFER_STATE +#define YY_TYPEDEF_YY_BUFFER_STATE +typedef struct yy_buffer_state *YY_BUFFER_STATE; +#endif + +#ifndef YY_TYPEDEF_YY_SIZE_T +#define YY_TYPEDEF_YY_SIZE_T +typedef size_t yy_size_t; +#endif + +/* %if-not-reentrant */ +extern yy_size_t yyleng; +/* %endif */ + +/* %if-c-only */ +/* %if-not-reentrant */ +/* %endif */ +/* %endif */ + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + + #define YY_LESS_LINENO(n) + #define YY_LINENO_REWIND_TO(ptr) + +/* Return all but the first "n" matched characters back to the input stream. */ +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + *yy_cp = (yy_hold_char); \ + YY_RESTORE_YY_MORE_OFFSET \ + (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } \ + while ( 0 ) + +#define unput(c) yyunput( c, (yytext_ptr) ) + +#ifndef YY_STRUCT_YY_BUFFER_STATE +#define YY_STRUCT_YY_BUFFER_STATE +struct yy_buffer_state + { +/* %if-c-only */ +/* %endif */ + +/* %if-c++-only */ + std::streambuf* yy_input_file; +/* %endif */ + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + yy_size_t yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + int yy_bs_lineno; /**< The line count. */ + int yy_bs_column; /**< The column count. */ + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; + +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + + }; +#endif /* !YY_STRUCT_YY_BUFFER_STATE */ + +/* %if-c-only Standard (non-C++) definition */ +/* %not-for-header */ + +/* %if-not-reentrant */ +/* %endif */ +/* %ok-for-header */ + +/* %endif */ + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + * + * Returns the top of the stack, or NULL. + */ +#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ + ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ + : NULL) + +/* Same as previous macro, but useful when we know that the buffer stack is not + * NULL or when we need an lvalue. For internal use only. + */ +#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] + +/* %if-c-only Standard (non-C++) definition */ +/* %if-not-reentrant */ +/* %not-for-header */ + +/* %ok-for-header */ + +/* %endif */ +/* %endif */ + +void *yyalloc (yy_size_t ); +void *yyrealloc (void *,yy_size_t ); +void yyfree (void * ); + +#define yy_new_buffer yy_create_buffer + +#define yy_set_interactive(is_interactive) \ + { \ + if ( ! YY_CURRENT_BUFFER ){ \ + yyensure_buffer_stack (); \ + YY_CURRENT_BUFFER_LVALUE = \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ + } + +#define yy_set_bol(at_bol) \ + { \ + if ( ! YY_CURRENT_BUFFER ){\ + yyensure_buffer_stack (); \ + YY_CURRENT_BUFFER_LVALUE = \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ + } + +#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) + +/* %% [1.0] yytext/yyin/yyout/yy_state_type/yylineno etc. def's & init go here */ +/* Begin user sect3 */ +#define YY_SKIP_YYWRAP + +#define FLEX_DEBUG + +typedef unsigned char YY_CHAR; + +#define yytext_ptr yytext + +#include + +int yyFlexLexer::yywrap() { return 1; } + +/* %% [1.5] DFA */ + +/* %if-c-only Standard (non-C++) definition */ +/* %endif */ + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up yytext. + */ +#define YY_DO_BEFORE_ACTION \ + (yytext_ptr) = yy_bp; \ +/* %% [2.0] code to fiddle yytext and yyleng for yymore() goes here \ */\ + yyleng = (size_t) (yy_cp - yy_bp); \ + (yy_hold_char) = *yy_cp; \ + *yy_cp = '\0'; \ +/* %% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \ */\ + (yy_c_buf_p) = yy_cp; + +/* %% [4.0] data tables for the DFA and the user's section 1 definitions go here */ +#define YY_NUM_RULES 45 +#define YY_END_OF_BUFFER 46 +/* This struct is not used in this scanner, + but its presence is necessary. */ +struct yy_trans_info + { + flex_int32_t yy_verify; + flex_int32_t yy_nxt; + }; +static yyconst flex_int16_t yy_accept[113] = + { 0, + 0, 0, 46, 44, 35, 36, 17, 24, 44, 28, + 29, 22, 20, 27, 21, 44, 23, 41, 39, 26, + 11, 25, 13, 42, 30, 31, 42, 42, 42, 42, + 42, 42, 42, 42, 32, 44, 33, 35, 36, 16, + 18, 43, 0, 0, 43, 41, 0, 0, 0, 39, + 12, 15, 14, 42, 0, 0, 34, 42, 42, 42, + 42, 9, 42, 42, 42, 42, 19, 0, 0, 0, + 0, 0, 38, 0, 43, 40, 0, 0, 42, 42, + 42, 42, 2, 42, 42, 42, 0, 43, 37, 0, + 0, 0, 0, 42, 42, 42, 10, 42, 42, 4, + + 42, 6, 5, 42, 1, 42, 8, 42, 3, 42, + 7, 0 + } ; + +static yyconst YY_CHAR yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, + 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 5, 1, 1, 1, 6, 7, 1, 8, + 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, + 17, 17, 17, 17, 17, 18, 18, 1, 19, 20, + 21, 22, 1, 1, 23, 23, 23, 23, 24, 23, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 25, 26, 25, 25, + 27, 1, 28, 1, 25, 1, 29, 30, 31, 32, + + 33, 34, 25, 35, 36, 25, 37, 38, 25, 39, + 40, 25, 25, 41, 42, 43, 44, 45, 46, 26, + 25, 25, 47, 48, 49, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static yyconst YY_CHAR yy_meta[50] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, + 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, + 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 1, 1, 1 + } ; + +static yyconst flex_uint16_t yy_base[121] = + { 0, + 0, 0, 222, 223, 48, 218, 199, 223, 212, 223, + 223, 223, 223, 223, 223, 37, 41, 43, 48, 223, + 197, 196, 195, 0, 71, 223, 174, 174, 175, 174, + 24, 178, 170, 174, 223, 160, 223, 66, 204, 223, + 223, 61, 72, 80, 72, 84, 95, 105, 0, 113, + 223, 223, 223, 0, 130, 82, 223, 173, 166, 162, + 163, 0, 159, 158, 164, 163, 223, 125, 100, 110, + 125, 100, 223, 131, 134, 0, 129, 103, 169, 111, + 164, 167, 0, 151, 162, 155, 139, 143, 223, 152, + 153, 154, 162, 155, 148, 154, 0, 83, 83, 0, + + 81, 0, 0, 56, 0, 54, 0, 47, 0, 47, + 0, 223, 168, 171, 174, 69, 177, 180, 183, 186 + } ; + +static yyconst flex_int16_t yy_def[121] = + { 0, + 112, 1, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 113, 112, 112, 113, 113, 113, 113, + 113, 113, 113, 113, 112, 112, 112, 112, 112, 112, + 112, 112, 114, 115, 112, 112, 112, 112, 116, 112, + 112, 112, 112, 113, 112, 112, 112, 113, 113, 113, + 113, 113, 113, 113, 113, 113, 112, 112, 114, 117, + 114, 115, 112, 112, 112, 116, 118, 119, 113, 113, + 113, 113, 113, 113, 113, 113, 112, 112, 112, 118, + 120, 118, 119, 113, 113, 113, 113, 113, 113, 113, + + 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, + 113, 0, 112, 112, 112, 112, 112, 112, 112, 112 + } ; + +static yyconst flex_uint16_t yy_nxt[273] = + { 0, + 4, 5, 6, 5, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, + 22, 23, 24, 24, 24, 24, 25, 26, 24, 27, + 28, 24, 29, 30, 24, 31, 24, 24, 24, 24, + 32, 24, 24, 24, 33, 34, 35, 36, 37, 38, + 43, 38, 42, 42, 42, 44, 45, 62, 46, 46, + 47, 45, 63, 50, 50, 50, 48, 38, 49, 38, + 76, 48, 55, 55, 55, 48, 42, 42, 42, 111, + 48, 70, 73, 73, 68, 56, 71, 42, 42, 42, + 110, 77, 109, 68, 108, 68, 78, 45, 57, 46, + + 46, 47, 73, 73, 68, 55, 55, 48, 45, 70, + 47, 47, 47, 107, 71, 74, 48, 74, 48, 70, + 75, 75, 75, 106, 89, 105, 45, 48, 50, 50, + 50, 55, 55, 55, 70, 87, 48, 87, 91, 71, + 88, 88, 88, 92, 56, 48, 75, 75, 75, 75, + 75, 75, 95, 96, 88, 88, 88, 57, 88, 88, + 88, 91, 91, 91, 55, 55, 92, 55, 92, 54, + 54, 69, 69, 69, 72, 72, 72, 71, 71, 71, + 90, 90, 90, 93, 93, 93, 92, 92, 92, 104, + 103, 102, 101, 100, 99, 98, 97, 94, 86, 85, + + 84, 83, 82, 81, 80, 79, 39, 67, 66, 65, + 64, 61, 60, 59, 58, 53, 52, 51, 41, 40, + 39, 112, 3, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112 + } ; + +static yyconst flex_int16_t yy_chk[273] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, + 17, 5, 16, 16, 16, 17, 18, 31, 18, 18, + 18, 19, 31, 19, 19, 19, 18, 38, 18, 38, + 116, 19, 25, 25, 25, 18, 42, 42, 42, 110, + 19, 43, 44, 44, 42, 25, 43, 45, 45, 45, + 108, 56, 106, 42, 104, 45, 56, 46, 25, 46, + + 46, 46, 72, 72, 45, 78, 78, 46, 47, 69, + 47, 47, 47, 101, 69, 48, 46, 48, 47, 70, + 48, 48, 48, 99, 70, 98, 50, 47, 50, 50, + 50, 55, 55, 55, 71, 68, 50, 68, 77, 71, + 68, 68, 68, 77, 55, 50, 74, 74, 74, 75, + 75, 75, 80, 80, 87, 87, 87, 55, 88, 88, + 88, 90, 91, 92, 93, 93, 90, 91, 92, 113, + 113, 114, 114, 114, 115, 115, 115, 117, 117, 117, + 118, 118, 118, 119, 119, 119, 120, 120, 120, 96, + 95, 94, 86, 85, 84, 82, 81, 79, 66, 65, + + 64, 63, 61, 60, 59, 58, 39, 36, 34, 33, + 32, 30, 29, 28, 27, 23, 22, 21, 9, 7, + 6, 3, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112 + } ; + +static yyconst flex_int16_t yy_rule_linenum[45] = + { 0, + 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, + 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 167, 168, 169, 170, 173, 174, 182, + 190, 198, 199, 201 + } ; + +/* The intent behind this definition is that it'll catch + * any uses of REJECT which flex missed. + */ +#define REJECT reject_used_but_not_detected +#define yymore() yymore_used_but_not_detected +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET +#line 1 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +#line 2 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +# include +# include +# include +# include // strerror +# include +# include +# include +# include +std::map ch2int = { + {'0',0}, + {'1',1}, + {'2',2}, + {'3',3}, + {'4',4}, + {'5',5}, + {'6',6}, + {'7',7}, + {'8',8}, + {'9',9}, + {'a',10}, + {'b',11}, + {'c',12}, + {'d',13}, + {'e',14}, + {'f',15}, + {'A',10}, + {'B',11}, + {'C',12}, + {'D',13}, + {'E',14}, + {'F',15} +}; +# include "SysYDriver.h" +# include "SysYParser.h" +# define RET_NOTYPE_TOKEN(name) \ + auto mytoken = yy::SysYParser::make_##name(loc);\ + loc.step();\ + return mytoken; + +# define RET_TYPE_TOKEN(name, value) \ + auto mytoken = yy::SysYParser::make_##name(value, loc);\ + loc.step();\ + return mytoken; +#line 48 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +#if defined __clang__ +# define CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#endif + +// Clang and ICC like to pretend they are GCC. +#if defined __GNUC__ && !defined __clang__ && !defined __ICC +# define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#endif + +// Pacify warnings in yy_init_buffer (observed with Flex 2.6.4) +// and GCC 6.4.0, 7.3.0 with -O3. +#if defined GCC_VERSION && 600 <= GCC_VERSION +# pragma GCC diagnostic ignored "-Wnull-dereference" +#endif + +// This code uses Flex's C backend, yet compiles it as C++. +// So expect warnings about C style casts and NULL. +#if defined CLANG_VERSION && 500 <= CLANG_VERSION +# pragma clang diagnostic ignored "-Wold-style-cast" +# pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#elif defined GCC_VERSION && 407 <= GCC_VERSION +# pragma GCC diagnostic ignored "-Wold-style-cast" +# pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif + +#define FLEX_VERSION (YY_FLEX_MAJOR_VERSION * 100 + YY_FLEX_MINOR_VERSION) + +// Old versions of Flex (2.5.35) generate an incomplete documentation comment. +// +// In file included from src/scan-code-c.c:3: +// src/scan-code.c:2198:21: error: empty paragraph passed to '@param' command +// [-Werror,-Wdocumentation] +// * @param line_number +// ~~~~~~~~~~~~~~~~~^ +// 1 error generated. +#if FLEX_VERSION < 206 && defined CLANG_VERSION +# pragma clang diagnostic ignored "-Wdocumentation" +#endif + +// Old versions of Flex (2.5.35) use 'register'. Warnings introduced in +// GCC 7 and Clang 6. +#if FLEX_VERSION < 206 +# if defined CLANG_VERSION && 600 <= CLANG_VERSION +# pragma clang diagnostic ignored "-Wdeprecated-register" +# elif defined GCC_VERSION && 700 <= GCC_VERSION +# pragma GCC diagnostic ignored "-Wregister" +# endif +#endif + +#if FLEX_VERSION < 206 +# if defined CLANG_VERSION +# pragma clang diagnostic ignored "-Wconversion" +# pragma clang diagnostic ignored "-Wdocumentation" +# pragma clang diagnostic ignored "-Wshorten-64-to-32" +# pragma clang diagnostic ignored "-Wsign-conversion" +# elif defined GCC_VERSION +# pragma GCC diagnostic ignored "-Wconversion" +# pragma GCC diagnostic ignored "-Wsign-conversion" +# endif +#endif +#define YY_NO_INPUT 1 +#line 113 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" + // Code run each time a pattern is matched. + # define YY_USER_ACTION loc.columns(yyleng); +/* Regex abbreviations: */ +#line 712 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYScanner.cpp" + +#define INITIAL 0 + +#ifndef YY_NO_UNISTD_H +/* Special case for "unistd.h", since it is non-ANSI. We include it way + * down here because we want the user's section 1 to have been scanned first. + * The user has a chance to override it with an option. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +#include +/* %endif */ +#endif + +#ifndef YY_EXTRA_TYPE +#define YY_EXTRA_TYPE void * +#endif + +/* %if-c-only Reentrant structure and macros (non-C++). */ +/* %if-reentrant */ +/* %if-c-only */ +/* %endif */ +/* %if-reentrant */ +/* %endif */ +/* %endif End reentrant structures and macros. */ +/* %if-bison-bridge */ +/* %endif */ +/* %not-for-header */ + +/* %ok-for-header */ + +/* %endif */ + +#ifndef yytext_ptr +static void yy_flex_strncpy (char *,yyconst char *,int ); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (yyconst char * ); +#endif + +#ifndef YY_NO_INPUT +/* %if-c-only Standard (non-C++) definition */ +/* %not-for-header */ + +/* %ok-for-header */ + +/* %endif */ +#endif + +/* %if-c-only */ +/* %endif */ + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else +#define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ +#endif + +/* Copy whatever the last rule matched to the standard output. */ +#ifndef ECHO +/* %if-c-only Standard (non-C++) definition */ +/* %endif */ +/* %if-c++-only C++ definition */ +#define ECHO LexerOutput( yytext, yyleng ) +/* %endif */ +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ +/* %% [5.0] fread()/read() definition of YY_INPUT goes here unless we're doing C++ \ */\ +\ +/* %if-c++-only C++ definition \ */\ + if ( (int)(result = LexerInput( (char *) buf, max_size )) < 0 ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); +/* %endif */ + +#endif + +/* No semi-colon after return; correct usage is to write "yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef yyterminate +#define yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +#define YY_FATAL_ERROR(msg) LexerError( msg ) +/* %endif */ +#endif + +/* %if-tables-serialization structures and prototypes */ +/* %not-for-header */ + +/* %ok-for-header */ + +/* %not-for-header */ + +/* %tables-yydmap generated elements */ +/* %endif */ +/* end tables serialization structures and prototypes */ + +/* %ok-for-header */ + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL_IS_OURS 1 +/* %if-c-only Standard (non-C++) definition */ +/* %endif */ +/* %if-c++-only C++ definition */ +#define YY_DECL int yyFlexLexer::yylex() +/* %endif */ +#endif /* !YY_DECL */ + +/* Code executed at the beginning of each rule, after yytext and yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK /*LINTED*/break; +#endif + +/* %% [6.0] YY_RULE_SETUP definition goes here */ +#define YY_RULE_SETUP \ + YY_USER_ACTION + +/* %not-for-header */ + +/** The main scanner function which does all the work. + */ +YY_DECL +{ + yy_state_type yy_current_state; + char *yy_cp, *yy_bp; + int yy_act; + + if ( !(yy_init) ) + { + (yy_init) = 1; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! (yy_start) ) + (yy_start) = 1; /* first start state */ + + if ( ! yyin ) +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yyin.rdbuf(std::cin.rdbuf()); +/* %endif */ + + if ( ! yyout ) +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yyout.rdbuf(std::cout.rdbuf()); +/* %endif */ + + if ( ! YY_CURRENT_BUFFER ) { + yyensure_buffer_stack (); + YY_CURRENT_BUFFER_LVALUE = + yy_create_buffer( yyin, YY_BUF_SIZE ); + } + + yy_load_buffer_state( ); + } + + { +/* %% [7.0] user's declarations go here */ +#line 129 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" + + /* keyword */ +#line 912 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYScanner.cpp" + + while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ + { +/* %% [8.0] yymore()-related code goes here */ + yy_cp = (yy_c_buf_p); + + /* Support of yytext. */ + *yy_cp = (yy_hold_char); + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + +/* %% [9.0] code to set up and find next match goes here */ + yy_current_state = (yy_start); +yy_match: + do + { + YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 113 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + ++yy_cp; + } + while ( yy_current_state != 112 ); + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + +yy_find_action: +/* %% [10.0] code to find the action number goes here */ + yy_act = yy_accept[yy_current_state]; + + YY_DO_BEFORE_ACTION; + +/* %% [11.0] code for yylineno update goes here */ + +do_action: /* This label is used only to access EOF actions. */ + +/* %% [12.0] debug code goes here */ + if ( yy_flex_debug ) + { + if ( yy_act == 0 ) + std::cerr << "--scanner backing up\n"; + else if ( yy_act < 45 ) + std::cerr << "--accepting rule at line " << yy_rule_linenum[yy_act] << + "(\"" << yytext << "\")\n"; + else if ( yy_act == 45 ) + std::cerr << "--accepting default rule (\"" << yytext << "\")\n"; + else if ( yy_act == 46 ) + std::cerr << "--(end of buffer or a NUL)\n"; + else + std::cerr << "--EOF (start condition " << YY_START << ")\n"; + } + + switch ( yy_act ) + { /* beginning of action switch */ +/* %% [13.0] actions go here */ + case 0: /* must back up */ + /* undo the effects of YY_DO_BEFORE_ACTION */ + *yy_cp = (yy_hold_char); + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + goto yy_find_action; + +case 1: +YY_RULE_SETUP +#line 131 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(FLOAT);} + YY_BREAK +case 2: +YY_RULE_SETUP +#line 132 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(INT);} + YY_BREAK +case 3: +YY_RULE_SETUP +#line 133 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(RETURN);} + YY_BREAK +case 4: +YY_RULE_SETUP +#line 134 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(VOID);} + YY_BREAK +case 5: +YY_RULE_SETUP +#line 135 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(CONST);} + YY_BREAK +case 6: +YY_RULE_SETUP +#line 136 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(BREAK);} + YY_BREAK +case 7: +YY_RULE_SETUP +#line 137 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(CONTINUE);} + YY_BREAK +case 8: +YY_RULE_SETUP +#line 138 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(WHILE);} + YY_BREAK +case 9: +YY_RULE_SETUP +#line 139 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(IF);} + YY_BREAK +case 10: +YY_RULE_SETUP +#line 140 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(ELSE);} + YY_BREAK +case 11: +YY_RULE_SETUP +#line 142 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LT);} + YY_BREAK +case 12: +YY_RULE_SETUP +#line 143 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LTE);} + YY_BREAK +case 13: +YY_RULE_SETUP +#line 144 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(GT);} + YY_BREAK +case 14: +YY_RULE_SETUP +#line 145 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(GTE);} + YY_BREAK +case 15: +YY_RULE_SETUP +#line 146 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(EQ);} + YY_BREAK +case 16: +YY_RULE_SETUP +#line 147 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(NEQ);} + YY_BREAK +case 17: +YY_RULE_SETUP +#line 148 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(NOT);} + YY_BREAK +case 18: +YY_RULE_SETUP +#line 149 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LOGICAND);} + YY_BREAK +case 19: +YY_RULE_SETUP +#line 150 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LOGICOR);} + YY_BREAK +case 20: +YY_RULE_SETUP +#line 151 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(PLUS);} + YY_BREAK +case 21: +YY_RULE_SETUP +#line 152 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(MINUS);} + YY_BREAK +case 22: +YY_RULE_SETUP +#line 153 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(MULTIPLY);} + YY_BREAK +case 23: +YY_RULE_SETUP +#line 154 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(DIVIDE);} + YY_BREAK +case 24: +YY_RULE_SETUP +#line 155 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(MODULO);} + YY_BREAK +case 25: +YY_RULE_SETUP +#line 156 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(ASSIGN);} + YY_BREAK +case 26: +YY_RULE_SETUP +#line 157 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(SEMICOLON);} + YY_BREAK +case 27: +YY_RULE_SETUP +#line 158 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(COMMA);} + YY_BREAK +case 28: +YY_RULE_SETUP +#line 159 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LPARENTHESE);} + YY_BREAK +case 29: +YY_RULE_SETUP +#line 160 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(RPARENTHESE);} + YY_BREAK +case 30: +YY_RULE_SETUP +#line 161 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LBRACKET);} + YY_BREAK +case 31: +YY_RULE_SETUP +#line 162 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(RBRACKET);} + YY_BREAK +case 32: +YY_RULE_SETUP +#line 163 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LBRACE);} + YY_BREAK +case 33: +YY_RULE_SETUP +#line 164 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(RBRACE);} + YY_BREAK +case 34: +/* rule 34 can match eol */ +YY_RULE_SETUP +#line 167 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(LRBRACKET);} + YY_BREAK +case 35: +YY_RULE_SETUP +#line 168 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{loc.step();} + YY_BREAK +case 36: +/* rule 36 can match eol */ +YY_RULE_SETUP +#line 169 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{loc.lines(yyleng); loc.step();} + YY_BREAK +case 37: +/* rule 37 can match eol */ +YY_RULE_SETUP +#line 170 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{std::string s = yytext; + size_t n = std::count(s.begin(), s.end(), '\n'); + for (size_t i = 0; i < n; i++) loc.lines(1);} + YY_BREAK +case 38: +/* rule 38 can match eol */ +YY_RULE_SETUP +#line 173 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{loc.lines(1);loc.step();} + YY_BREAK +case 39: +YY_RULE_SETUP +#line 174 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{std::string dec = yytext; + unsigned sum = 0; + int len = dec.size(); + for(int i = 0;i < len;i++){ + auto a = dec[i]; + sum = sum * 10 + a - 48; + } + RET_TYPE_TOKEN(INTCONST, int(sum));} + YY_BREAK +case 40: +YY_RULE_SETUP +#line 182 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{std::string hex = yytext; + unsigned sum = 0; + int len = hex.size(); + for(int i = 2;i < len;i++){ + auto a = hex[i]; + sum = sum * 16 + ch2int[a]; + } + RET_TYPE_TOKEN(INTCONST, int(sum));} + YY_BREAK +case 41: +YY_RULE_SETUP +#line 190 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{std::string oct = yytext; + unsigned sum = 0; + int len = oct.size(); + for(int i = 1;i < len;i++){ + auto a = oct[i]; + sum = sum * 8 + ch2int[a]; + } + RET_TYPE_TOKEN(INTCONST, int(sum));} + YY_BREAK +case 42: +YY_RULE_SETUP +#line 198 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_TYPE_TOKEN(IDENTIFIER, yytext);} + YY_BREAK +case 43: +YY_RULE_SETUP +#line 199 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_TYPE_TOKEN(FLOATCONST, std::stod(yytext));} + YY_BREAK +case YY_STATE_EOF(INITIAL): +#line 200 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{RET_NOTYPE_TOKEN(END);} + YY_BREAK +case 44: +YY_RULE_SETUP +#line 201 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +{std::cout << "Error in scanner!" << '\n'; exit(1);} + YY_BREAK +case 45: +YY_RULE_SETUP +#line 202 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" +ECHO; + YY_BREAK +#line 1243 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/build/SysYScanner.cpp" + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = (yy_hold_char); + YY_RESTORE_YY_MORE_OFFSET + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * yylex(). If so, then we have to assure + * consistency between YY_CURRENT_BUFFER and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin.rdbuf(); +/* %endif */ + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) + { /* This was really a NUL. */ + yy_state_type yy_next_state; + + (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( ); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans( yy_current_state ); + + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + + if ( yy_next_state ) + { + /* Consume the NUL. */ + yy_cp = ++(yy_c_buf_p); + yy_current_state = yy_next_state; + goto yy_match; + } + + else + { +/* %% [14.0] code to do back-up for compressed tables and set up yy_cp goes here */ + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + goto yy_find_action; + } + } + + else switch ( yy_get_next_buffer( ) ) + { + case EOB_ACT_END_OF_FILE: + { + (yy_did_buffer_switch_on_eof) = 0; + + if ( yywrap( ) ) + { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! (yy_did_buffer_switch_on_eof) ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = + (yytext_ptr) + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( ); + + yy_cp = (yy_c_buf_p); + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + (yy_c_buf_p) = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; + + yy_current_state = yy_get_previous_state( ); + + yy_cp = (yy_c_buf_p); + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of user's declarations */ +} /* end of yylex */ +/* %ok-for-header */ + +/* %if-c++-only */ +/* %not-for-header */ + +/* The contents of this function are C++ specific, so the () macro is not used. + * This constructor simply maintains backward compatibility. + * DEPRECATED + */ +yyFlexLexer::yyFlexLexer( FLEX_STD istream* arg_yyin, FLEX_STD ostream* arg_yyout ): + yyin(arg_yyin ? arg_yyin->rdbuf() : std::cin.rdbuf()), + yyout(arg_yyout ? arg_yyout->rdbuf() : std::cout.rdbuf()) +{ + ctor_common(); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +yyFlexLexer::yyFlexLexer( std::istream& arg_yyin, std::ostream& arg_yyout ): + yyin(arg_yyin.rdbuf()), + yyout(arg_yyout.rdbuf()) +{ + ctor_common(); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +void yyFlexLexer::ctor_common() +{ + yy_c_buf_p = 0; + yy_init = 0; + yy_start = 0; + yy_flex_debug = 0; + yylineno = 1; // this will only get updated if %option yylineno + + yy_did_buffer_switch_on_eof = 0; + + yy_looking_for_trail_begin = 0; + yy_more_flag = 0; + yy_more_len = 0; + yy_more_offset = yy_prev_more_offset = 0; + + yy_start_stack_ptr = yy_start_stack_depth = 0; + yy_start_stack = NULL; + + yy_buffer_stack = 0; + yy_buffer_stack_top = 0; + yy_buffer_stack_max = 0; + + yy_state_buf = 0; + +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +yyFlexLexer::~yyFlexLexer() +{ + delete [] yy_state_buf; + yyfree(yy_start_stack ); + yy_delete_buffer( YY_CURRENT_BUFFER ); + yyfree(yy_buffer_stack ); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +void yyFlexLexer::switch_streams( std::istream& new_in, std::ostream& new_out ) +{ + // was if( new_in ) + yy_delete_buffer( YY_CURRENT_BUFFER ); + yy_switch_to_buffer( yy_create_buffer( new_in, YY_BUF_SIZE ) ); + + // was if( new_out ) + yyout.rdbuf(new_out.rdbuf()); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +void yyFlexLexer::switch_streams( std::istream* new_in, std::ostream* new_out ) +{ + if( ! new_in ) { + new_in = &yyin; + } + + if ( ! new_out ) { + new_out = &yyout; + } + + switch_streams(*new_in, *new_out); +} + +#ifdef YY_INTERACTIVE +int yyFlexLexer::LexerInput( char* buf, int /* max_size */ ) +#else +int yyFlexLexer::LexerInput( char* buf, int max_size ) +#endif +{ + if ( yyin.eof() || yyin.fail() ) + return 0; + +#ifdef YY_INTERACTIVE + yyin.get( buf[0] ); + + if ( yyin.eof() ) + return 0; + + if ( yyin.bad() ) + return -1; + + return 1; + +#else + (void) yyin.read( buf, max_size ); + + if ( yyin.bad() ) + return -1; + else + return yyin.gcount(); +#endif +} + +void yyFlexLexer::LexerOutput( const char* buf, int size ) +{ + (void) yyout.write( buf, size ); +} +/* %ok-for-header */ + +/* %endif */ + +/* yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +int yyFlexLexer::yy_get_next_buffer() +/* %endif */ +{ + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *source = (yytext_ptr); + yy_size_t number_to_move, i; + int ret_val; + + if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (yy_size_t) ((yy_c_buf_p) - (yytext_ptr)) - 1; + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; + + else + { + yy_size_t num_to_read = + YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; + + int yy_c_buf_p_offset = + (int) ((yy_c_buf_p) - b->yy_ch_buf); + + if ( b->yy_is_our_buffer ) + { + yy_size_t new_size = b->yy_buf_size * 2; + + if ( new_size <= 0 ) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; + + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); + } + else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = 0; + + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; + + num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - + number_to_move - 1; + + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), + (yy_n_chars), num_to_read ); + + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + if ( (yy_n_chars) == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + yyrestart( yyin ); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + if ((int) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { + /* Extend the array by 50%, plus the number we really need. */ + int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); + if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); + } + + (yy_n_chars) += number_to_move; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; + + (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; + + return ret_val; +} + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + +/* %if-c-only */ +/* %not-for-header */ + +/* %endif */ +/* %if-c++-only */ + yy_state_type yyFlexLexer::yy_get_previous_state() +/* %endif */ +{ + yy_state_type yy_current_state; + char *yy_cp; + +/* %% [15.0] code to get the start state into yy_current_state goes here */ + yy_current_state = (yy_start); + + for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) + { +/* %% [16.0] code to find the next state goes here */ + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 113 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + } + + return yy_current_state; +} + +/* yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = yy_try_NUL_trans( current_state ); + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yy_state_type yyFlexLexer::yy_try_NUL_trans( yy_state_type yy_current_state ) +/* %endif */ +{ + int yy_is_jam; + /* %% [17.0] code to find the next state, and perhaps do backing up, goes here */ + char *yy_cp = (yy_c_buf_p); + + YY_CHAR yy_c = 1; + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 113 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_is_jam = (yy_current_state == 112); + + return yy_is_jam ? 0 : yy_current_state; +} + +#ifndef YY_NO_UNPUT +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yyunput( int c, char* yy_bp) +/* %endif */ +{ + char *yy_cp; + + yy_cp = (yy_c_buf_p); + + /* undo effects of setting up yytext */ + *yy_cp = (yy_hold_char); + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + yy_size_t number_to_move = (yy_n_chars) + 2; + char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; + char *source = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; + + while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + *--dest = *--source; + + yy_cp += (int) (dest - source); + yy_bp += (int) (dest - source); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--yy_cp = (char) c; + +/* %% [18.0] update yylineno here */ + + (yytext_ptr) = yy_bp; + (yy_hold_char) = *yy_cp; + (yy_c_buf_p) = yy_cp; +} +/* %if-c-only */ +/* %endif */ +#endif + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + int yyFlexLexer::yyinput() +/* %endif */ +{ + int c; + + *(yy_c_buf_p) = (yy_hold_char); + + if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) + { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) + /* This was really a NUL. */ + *(yy_c_buf_p) = '\0'; + + else + { /* need more input */ + yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); + ++(yy_c_buf_p); + + switch ( yy_get_next_buffer( ) ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + yyrestart( yyin ); + + /*FALLTHROUGH*/ + + case EOB_ACT_END_OF_FILE: + { + if ( yywrap( ) ) + return EOF; + + if ( ! (yy_did_buffer_switch_on_eof) ) + YY_NEW_FILE; +#ifdef __cplusplus + return yyinput(); +#else + return input(); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr) + offset; + break; + } + } + } + + c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ + *(yy_c_buf_p) = '\0'; /* preserve yytext */ + (yy_hold_char) = *++(yy_c_buf_p); + +/* %% [19.0] update BOL and yylineno */ + + return c; +} +/* %if-c-only */ +/* %endif */ + +/** Immediately switch to a different input stream. + * @param input_file A readable stream. + * + * @note This function does not reset the start condition to @c INITIAL . + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yyrestart( std::istream& input_file ) +/* %endif */ +{ + + if ( ! YY_CURRENT_BUFFER ){ + yyensure_buffer_stack (); + YY_CURRENT_BUFFER_LVALUE = + yy_create_buffer( yyin, YY_BUF_SIZE ); + } + + yy_init_buffer( YY_CURRENT_BUFFER, input_file ); + yy_load_buffer_state( ); +} + +/* %if-c++-only */ +/** Delegate to the new version that takes an istream reference. + * @param input_file A readable stream. + * + * @note This function does not reset the start condition to @c INITIAL . + */ +void yyFlexLexer::yyrestart( std::istream* input_file ) +{ + yyrestart( *input_file ); +} +/* %endif */ + +/** Switch to a different input buffer. + * @param new_buffer The new input buffer. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) +/* %endif */ +{ + + /* TODO. We should be able to replace this entire function body + * with + * yypop_buffer_state(); + * yypush_buffer_state(new_buffer); + */ + yyensure_buffer_stack (); + if ( YY_CURRENT_BUFFER == new_buffer ) + return; + + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *(yy_c_buf_p) = (yy_hold_char); + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + YY_CURRENT_BUFFER_LVALUE = new_buffer; + yy_load_buffer_state( ); + + /* We don't actually know whether we did this switch during + * EOF (yywrap()) processing, but the only time this flag + * is looked at is after yywrap() is called, so it's safe + * to go ahead and always set it. + */ + (yy_did_buffer_switch_on_eof) = 1; +} + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_load_buffer_state() +/* %endif */ +{ + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; + (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yyin.rdbuf(YY_CURRENT_BUFFER_LVALUE->yy_input_file); +/* %endif */ + (yy_hold_char) = *(yy_c_buf_p); +} + +/** Allocate and initialize an input buffer state. + * @param file A readable stream. + * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. + * + * @return the allocated buffer state. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream& file, int size ) +/* %endif */ +{ + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_buf_size = (yy_size_t)size; + + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_is_our_buffer = 1; + + yy_init_buffer( b, file ); + + return b; +} + +/* %if-c++-only */ +/** Delegate creation of buffers to the new version that takes an istream reference. + * @param file A readable stream. + * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. + * + * @return the allocated buffer state. + */ + YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream* file, int size ) +{ + return yy_create_buffer( *file, size ); +} +/* %endif */ + +/** Destroy the buffer. + * @param b a buffer created with yy_create_buffer() + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_delete_buffer( YY_BUFFER_STATE b ) +/* %endif */ +{ + + if ( ! b ) + return; + + if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ + YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; + + if ( b->yy_is_our_buffer ) + yyfree((void *) b->yy_ch_buf ); + + yyfree((void *) b ); +} + +/* Initializes or reinitializes a buffer. + * This function is sometimes called more than once on the same buffer, + * such as during a yyrestart() or at EOF. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_init_buffer( YY_BUFFER_STATE b, std::istream& file ) +/* %endif */ + +{ + int oerrno = errno; + + yy_flush_buffer( b ); + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + b->yy_input_file = file.rdbuf(); +/* %endif */ + b->yy_fill_buffer = 1; + + /* If b is the current buffer, then yy_init_buffer was _probably_ + * called from yyrestart() or through yy_get_next_buffer. + * In that case, we don't want to reset the lineno or column. + */ + if (b != YY_CURRENT_BUFFER){ + b->yy_bs_lineno = 1; + b->yy_bs_column = 0; + } + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + b->yy_is_interactive = 0; +/* %endif */ + errno = oerrno; +} + +/** Discard all buffered characters. On the next scan, YY_INPUT will be called. + * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_flush_buffer( YY_BUFFER_STATE b ) +/* %endif */ +{ + if ( ! b ) + return; + + b->yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->yy_buf_pos = &b->yy_ch_buf[0]; + + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + + if ( b == YY_CURRENT_BUFFER ) + yy_load_buffer_state( ); +} + +/* %if-c-or-c++ */ +/** Pushes the new state onto the stack. The new state becomes + * the current state. This function will allocate the stack + * if necessary. + * @param new_buffer The new state. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::yypush_buffer_state (YY_BUFFER_STATE new_buffer) +/* %endif */ +{ + if (new_buffer == NULL) + return; + + yyensure_buffer_stack(); + + /* This block is copied from yy_switch_to_buffer. */ + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *(yy_c_buf_p) = (yy_hold_char); + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + /* Only push if top exists. Otherwise, replace top. */ + if (YY_CURRENT_BUFFER) + (yy_buffer_stack_top)++; + YY_CURRENT_BUFFER_LVALUE = new_buffer; + + /* copied from yy_switch_to_buffer. */ + yy_load_buffer_state( ); + (yy_did_buffer_switch_on_eof) = 1; +} +/* %endif */ + +/* %if-c-or-c++ */ +/** Removes and deletes the top of the stack, if present. + * The next element becomes the new top. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::yypop_buffer_state (void) +/* %endif */ +{ + if (!YY_CURRENT_BUFFER) + return; + + yy_delete_buffer(YY_CURRENT_BUFFER ); + YY_CURRENT_BUFFER_LVALUE = NULL; + if ((yy_buffer_stack_top) > 0) + --(yy_buffer_stack_top); + + if (YY_CURRENT_BUFFER) { + yy_load_buffer_state( ); + (yy_did_buffer_switch_on_eof) = 1; + } +} +/* %endif */ + +/* %if-c-or-c++ */ +/* Allocates the stack if it does not exist. + * Guarantees space for at least one push. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::yyensure_buffer_stack(void) +/* %endif */ +{ + yy_size_t num_to_alloc; + + if (!(yy_buffer_stack)) { + + /* First allocation is just for 2 elements, since we don't know if this + * scanner will even need a stack. We use 2 instead of 1 to avoid an + * immediate realloc on the next call. + */ + num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ + (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc + (num_to_alloc * sizeof(struct yy_buffer_state*) + ); + if ( ! (yy_buffer_stack) ) + YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); + + memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); + + (yy_buffer_stack_max) = num_to_alloc; + (yy_buffer_stack_top) = 0; + return; + } + + if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ + + /* Increase the buffer to prepare for a possible push. */ + yy_size_t grow_size = 8 /* arbitrary grow size */; + + num_to_alloc = (yy_buffer_stack_max) + grow_size; + (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc + ((yy_buffer_stack), + num_to_alloc * sizeof(struct yy_buffer_state*) + ); + if ( ! (yy_buffer_stack) ) + YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); + + /* zero only the new slots.*/ + memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); + (yy_buffer_stack_max) = num_to_alloc; + } +} +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_push_state( int _new_state ) +/* %endif */ +{ + if ( (yy_start_stack_ptr) >= (yy_start_stack_depth) ) + { + yy_size_t new_size; + + (yy_start_stack_depth) += YY_START_STACK_INCR; + new_size = (yy_start_stack_depth) * sizeof( int ); + + if ( ! (yy_start_stack) ) + (yy_start_stack) = (int *) yyalloc(new_size ); + + else + (yy_start_stack) = (int *) yyrealloc((void *) (yy_start_stack),new_size ); + + if ( ! (yy_start_stack) ) + YY_FATAL_ERROR( "out of memory expanding start-condition stack" ); + } + + (yy_start_stack)[(yy_start_stack_ptr)++] = YY_START; + + BEGIN(_new_state); +} + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_pop_state() +/* %endif */ +{ + if ( --(yy_start_stack_ptr) < 0 ) + YY_FATAL_ERROR( "start-condition stack underflow" ); + + BEGIN((yy_start_stack)[(yy_start_stack_ptr)]); +} + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + int yyFlexLexer::yy_top_state() +/* %endif */ +{ + return (yy_start_stack)[(yy_start_stack_ptr) - 1]; +} + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::LexerError( yyconst char msg[] ) +{ + std::cerr << msg << std::endl; + exit( YY_EXIT_FAILURE ); +} +/* %endif */ + +/* Redefine yyless() so it works in section 3 code. */ + +#undef yyless +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + yytext[yyleng] = (yy_hold_char); \ + (yy_c_buf_p) = yytext + yyless_macro_arg; \ + (yy_hold_char) = *(yy_c_buf_p); \ + *(yy_c_buf_p) = '\0'; \ + yyleng = yyless_macro_arg; \ + } \ + while ( 0 ) + +/* Accessor methods (get/set functions) to struct members. */ + +/* %if-c-only */ +/* %if-reentrant */ +/* %endif */ +/* %if-reentrant */ +/* %endif */ +/* %endif */ + +/* %if-reentrant */ +/* %if-bison-bridge */ +/* %endif */ +/* %endif if-c-only */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only SNIP! this currently causes conflicts with the c++ scanner */ +/* %if-reentrant */ +/* %endif */ +/* %endif */ + +/* + * Internal utility routines. + */ + +#ifndef yytext_ptr +static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) +{ + + int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; +} +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (yyconst char * s ) +{ + int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; +} +#endif + +void *yyalloc (yy_size_t size ) +{ + return (void *) malloc( size ); +} + +void *yyrealloc (void * ptr, yy_size_t size ) +{ + + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return (void *) realloc( (char *) ptr, size ); +} + +void yyfree (void * ptr ) +{ + free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ +} + +/* %if-tables-serialization definitions */ +/* %define-yytables The name for this specific scanner's tables. */ +#define YYTABLES_NAME "yytables" +/* %endif */ + +/* %ok-for-header */ + +#line 202 "/home/hzq/SysYF_IR_Lab/2021_sysycompiler_ir_lab/grammar/SysYScanner.ll" + + + +int yyFlexLexer::yylex() { + std::cerr << "'int yyFlexLexer::yylex()' should never be called." << std::endl; + exit(1); +} + diff --git a/src/SysYBuilder/CMakeLists.txt b/src/SysYBuilder/CMakeLists.txt new file mode 100644 index 0000000..f167a15 --- /dev/null +++ b/src/SysYBuilder/CMakeLists.txt @@ -0,0 +1,4 @@ +add_library( + SysYBuilder STATIC + SysYBuilder.cpp +) diff --git a/src/SysYBuilder/SysYBuilder.cpp b/src/SysYBuilder/SysYBuilder.cpp new file mode 100644 index 0000000..8e8e4e5 --- /dev/null +++ b/src/SysYBuilder/SysYBuilder.cpp @@ -0,0 +1,110 @@ +#include "SysYBuilder.hpp" + +#define CONST_INT(num) ConstantInt::get(num, module.get()) +#define CONST_FLOAT(num) ConstantFloat::get(num, module.get()) + +// You can define global variables here +// to store state + +// store temporary value +Value *tmp_val = nullptr; + +// types +Type *VOID_T; +Type *INT1_T; +Type *INT32_T; +Type *FLOAT_T; +Type *INT32PTR_T; +Type *FLOATPTR_T; + +void SysYBuilder::visit(SyntaxTree::Assembly &node) { + VOID_T = Type::get_void_type(module.get()); + INT1_T = Type::get_int1_type(module.get()); + INT32_T = Type::get_int32_type(module.get()); + FLOAT_T = Type::get_float_type(module.get()); + INT32PTR_T = Type::get_int32_ptr_type(module.get()); + FLOATPTR_T = Type::get_float_ptr_type(module.get()); + for (const auto &def : node.global_defs) { + def->accept(*this); + } +} + +void SysYBuilder::visit(SyntaxTree::InitVal &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::FuncDef &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::FuncFParamList &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::FuncParam &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::VarDef &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::AssignStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::Literal &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::ReturnStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::BlockStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::EmptyStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::ExprStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::UnaryCondExpr &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::BinaryCondExpr &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::BinaryExpr &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::UnaryExpr &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::FuncCallStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::IfStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::WhileStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::BreakStmt &node) { + return; +} + +void SysYBuilder::visit(SyntaxTree::ContinueStmt &node) { + return; +} diff --git a/src/SysYIR/BasicBlock.cpp b/src/SysYIR/BasicBlock.cpp new file mode 100644 index 0000000..4736c45 --- /dev/null +++ b/src/SysYIR/BasicBlock.cpp @@ -0,0 +1,109 @@ +#include "Module.h" +#include "BasicBlock.h" +#include "Function.h" +#include "IRprinter.h" +#ifdef DEBUG +#include +#endif +#include + +BasicBlock::BasicBlock(Module *m, const std::string &name = "", + Function *parent = nullptr) + : Value(Type::get_label_type(m), name), parent_(parent) +{ +#ifdef DEBUG + assert(parent && "currently parent should not be nullptr"); +#endif + parent_->add_basic_block(this); +} + +Module *BasicBlock::get_module() +{ + return get_parent()->get_parent(); +} + +void BasicBlock::add_instruction(Instruction *instr) +{ + instr_list_.push_back(instr); +} + +void BasicBlock::add_instruction(std::list::iterator instr_pos, Instruction *instr) +{ + instr_list_.insert(instr_pos, instr); +} + +void BasicBlock::add_instr_begin(Instruction *instr) +{ + instr_list_.push_front(instr); +} + +std::list::iterator BasicBlock::find_instruction(Instruction *instr) +{ + return std::find(instr_list_.begin(), instr_list_.end(), instr); +} + +void BasicBlock::delete_instr( Instruction *instr ) +{ + instr_list_.remove(instr); + instr->remove_use_of_ops(); +} + +const Instruction *BasicBlock::get_terminator() const +{ + if (instr_list_.empty()){ + return nullptr; + } + switch (instr_list_.back()->get_instr_type()) + { + case Instruction::ret: + return instr_list_.back(); + break; + + case Instruction::br: + return instr_list_.back(); + break; + + default: + return nullptr; + break; + } +} + +void BasicBlock::erase_from_parent() +{ + this->get_parent()->remove(this); +} + +std::string BasicBlock::print() +{ + std::string bb_ir; + bb_ir += this->get_name(); + bb_ir += ":"; + // print prebb + if(!this->get_pre_basic_blocks().empty()) + { + bb_ir += " ; preds = "; + } + for (auto bb : this->get_pre_basic_blocks() ) + { + if( bb != *this->get_pre_basic_blocks().begin() ) + bb_ir += ", "; + bb_ir += print_as_op(bb, false); + } + + // print prebb + if ( !this->get_parent() ) + { + bb_ir += "\n"; + bb_ir += "; Error: Block without parent!"; + } + bb_ir += "\n"; + for ( auto instr : this->get_instructions() ) + { + bb_ir += " "; + bb_ir += instr->print(); + bb_ir += "\n"; + } + + return bb_ir; +} \ No newline at end of file diff --git a/src/SysYIR/CMakeLists.txt b/src/SysYIR/CMakeLists.txt new file mode 100644 index 0000000..3aa03e7 --- /dev/null +++ b/src/SysYIR/CMakeLists.txt @@ -0,0 +1,13 @@ +add_library( + IRLib STATIC + Type.cpp + User.cpp + Value.cpp + BasicBlock.cpp + Constant.cpp + Function.cpp + GlobalVariable.cpp + Instruction.cpp + Module.cpp + IRprinter.cpp +) diff --git a/src/SysYIR/Constant.cpp b/src/SysYIR/Constant.cpp new file mode 100644 index 0000000..ff30cbd --- /dev/null +++ b/src/SysYIR/Constant.cpp @@ -0,0 +1,87 @@ +#include "Constant.h" +#include "Module.h" +#include +#include + +ConstantInt *ConstantInt::get(int val, Module *m) +{ + return new ConstantInt(Type::get_int32_type(m), val); +} +ConstantInt *ConstantInt::get(bool val, Module *m) +{ + return new ConstantInt(Type::get_int1_type(m),val?1:0); +} +std::string ConstantInt::print() +{ + std::string const_ir; + Type *ty = this->get_type(); + if ( ty->is_integer_type() && static_cast(ty)->get_num_bits() == 1 ) + { + //int1 + const_ir += (this->get_value() == 0) ? "false" : "true"; + } + else + { + //int32 + const_ir += std::to_string(this->get_value()); + } + return const_ir; +} + +ConstantFloat *ConstantFloat::get(float val, Module *m) +{ + return new ConstantFloat(Type::get_float_type(m), val); +} +std::string ConstantFloat::print() +{ + std::stringstream fp_ir_ss; + std::string fp_ir; + double val = this->get_value(); + fp_ir_ss << "0x"<< std::hex << *(uint64_t *)&val << std::endl; + fp_ir_ss >> fp_ir; + return fp_ir; +} + +ConstantArray::ConstantArray(ArrayType *ty, const std::vector &val) + : Constant(ty, "", val.size()) +{ + for (int i = 0; i < val.size(); i++) + set_operand(i, val[i]); + this->const_array.assign(val.begin(),val.end()); +} + +Constant *ConstantArray::get_element_value(int index) { + return this->const_array[index]; +} + +ConstantArray *ConstantArray::get(ArrayType *ty, const std::vector &val) +{ + return new ConstantArray(ty, val); +} + +std::string ConstantArray::print() +{ + std::string const_ir; + const_ir += "["; + const_ir += this->get_type()->get_array_element_type()->print(); + const_ir += " "; + const_ir += get_element_value(0)->print(); + for ( int i = 1 ; i < this->get_size_of_array() ; i++ ){ + const_ir += ", "; + const_ir += this->get_type()->get_array_element_type()->print(); + const_ir += " "; + const_ir += get_element_value(i)->print(); + } + const_ir += "]"; + return const_ir; +} + +ConstantZero *ConstantZero::get(Type *ty, Module *m) +{ + return new ConstantZero(ty); +} + +std::string ConstantZero::print() +{ + return "zeroinitializer"; +} diff --git a/src/SysYIR/Function.cpp b/src/SysYIR/Function.cpp new file mode 100644 index 0000000..db82526 --- /dev/null +++ b/src/SysYIR/Function.cpp @@ -0,0 +1,175 @@ +#include "Module.h" +#include "Function.h" +#include "IRprinter.h" + +Function::Function(FunctionType *ty, const std::string &name, Module *parent) + : Value(ty, name), parent_(parent), seq_cnt_(0) +{ + // num_args_ = ty->getNumParams(); + parent->add_function(this); + build_args(); +} + +Function *Function::create(FunctionType *ty, const std::string &name, Module *parent) +{ + return new Function(ty, name, parent); +} + +FunctionType *Function::get_function_type() const +{ + return static_cast(get_type()); +} + +Type *Function::get_return_type() const +{ + return get_function_type()->get_return_type(); +} + +unsigned Function::get_num_of_args() const +{ + return get_function_type()->get_num_of_args(); +} + +unsigned Function::get_num_basic_blocks() const +{ + return basic_blocks_.size(); +} + +Module *Function::get_parent() const +{ + return parent_; +} + +void Function::remove(BasicBlock* bb) +{ + basic_blocks_.remove(bb); + for (auto pre : bb->get_pre_basic_blocks()) + { + pre->remove_succ_basic_block(bb); + } + for (auto succ : bb->get_succ_basic_blocks()) + { + succ->remove_pre_basic_block(bb); + } +} + +void Function::build_args() +{ + auto *func_ty = get_function_type(); + unsigned num_args = get_num_of_args(); + for (int i = 0; i < num_args; i++) { + arguments_.push_back(new Argument(func_ty->get_param_type(i), "", this, i)); + } +} + +void Function::add_basic_block(BasicBlock *bb) +{ + basic_blocks_.push_back(bb); +} + +void Function::set_instr_name() +{ + std::map seq; + for (auto arg : this->get_args()) + { + if ( seq.find(arg) == seq.end()) + { + auto seq_num = seq.size() + seq_cnt_; + if ( arg->set_name("arg"+std::to_string(seq_num) )) + { + seq.insert( {arg, seq_num} ); + } + } + } + for (auto bb : basic_blocks_) + { + if ( seq.find(bb) == seq.end()) + { + auto seq_num = seq.size() + seq_cnt_; + if ( bb->set_name("label"+std::to_string(seq_num) )) + { + seq.insert( {bb, seq_num} ); + } + } + for (auto instr : bb->get_instructions()) + { + if ( !instr->is_void() && seq.find(instr) == seq.end()) + { + auto seq_num = seq.size() + seq_cnt_; + if ( instr->set_name("op"+std::to_string(seq_num) )) + { + seq.insert( {instr, seq_num} ); + } + } + } + } + seq_cnt_ += seq.size(); +} + +std::string Function::print() +{ + set_instr_name(); + std::string func_ir; + if ( this->is_declaration() ) + { + func_ir += "declare "; + } + else + { + func_ir += "define "; + } + + func_ir += this->get_return_type()->print(); + func_ir += " "; + func_ir += print_as_op(this, false); + func_ir += "("; + + //print arg + if ( this->is_declaration() ) + { + for ( int i = 0 ; i < this->get_num_of_args() ; i++) + { + if(i) + func_ir += ", "; + func_ir += static_cast(this->get_type())->get_param_type(i)->print(); + } + } + else + { + for ( auto arg = this->arg_begin(); arg != arg_end() ; arg++ ) + { + if( arg != this->arg_begin() ) + { + func_ir += ", "; + } + func_ir += static_cast(*arg)->print(); + } + } + func_ir += ")"; + + //print bb + if( this->is_declaration() ) { + func_ir += "\n"; + } + else + { + func_ir += " {"; + func_ir += "\n"; + for ( auto bb : this->get_basic_blocks() ) + { + func_ir += bb->print(); + } + func_ir += "}"; + } + + return func_ir; +} + +std::string Argument::print() +{ + std::string arg_ir; + arg_ir += this->get_type()->print(); + arg_ir += " %"; + arg_ir += this->get_name(); + return arg_ir; +} \ No newline at end of file diff --git a/src/SysYIR/GlobalVariable.cpp b/src/SysYIR/GlobalVariable.cpp new file mode 100644 index 0000000..9cd8f83 --- /dev/null +++ b/src/SysYIR/GlobalVariable.cpp @@ -0,0 +1,29 @@ +#include "GlobalVariable.h" +#include "IRprinter.h" + +GlobalVariable::GlobalVariable( std::string name, Module *m, Type* ty, bool is_const, Constant* init) + : User(ty, name, init != nullptr), is_const_(is_const), init_val_(init) +{ + m->add_global_variable(this); + if (init) { + this->set_operand(0, init); + } +}//global操作数为initval + +GlobalVariable *GlobalVariable::create(std::string name, Module *m, Type* ty, bool is_const, + Constant* init = nullptr) +{ + return new GlobalVariable(name, m, PointerType::get(ty), is_const, init); +} + +std::string GlobalVariable::print() +{ + std::string global_val_ir; + global_val_ir += print_as_op(this, false); + global_val_ir += " = "; + global_val_ir += (this->is_const() ? "constant " : "global "); + global_val_ir += this->get_type()->get_pointer_element_type()->print(); + global_val_ir += " "; + global_val_ir += this->get_init()->print(); + return global_val_ir; +} \ No newline at end of file diff --git a/src/SysYIR/IRprinter.cpp b/src/SysYIR/IRprinter.cpp new file mode 100644 index 0000000..6134e31 --- /dev/null +++ b/src/SysYIR/IRprinter.cpp @@ -0,0 +1,86 @@ +#include "IRprinter.h" + +std::string print_as_op( Value *v, bool print_ty ) +{ + std::string op_ir; + if( print_ty ) + { + op_ir += v->get_type()->print(); + op_ir += " "; + } + + if (dynamic_cast(v)) + { + op_ir += "@"+v->get_name(); + } + else if ( dynamic_cast(v) ) + { + op_ir += "@"+v->get_name(); + } + else if ( dynamic_cast(v)) + { + op_ir += v->print(); + } + else + { + op_ir += "%"+v->get_name(); + } + + return op_ir; +} + +std::string print_cmp_type( CmpInst::CmpOp op ) +{ + switch (op) + { + case CmpInst::GE: + return "sge"; + break; + case CmpInst::GT: + return "sgt"; + break; + case CmpInst::LE: + return "sle"; + break; + case CmpInst::LT: + return "slt"; + break; + case CmpInst::EQ: + return "eq"; + break; + case CmpInst::NE: + return "ne"; + break; + default: + break; + } + return "wrong cmpop"; +} + +std::string print_fcmp_type( FCmpInst::CmpOp op ) +{ + switch (op) + { + case FCmpInst::GE: + return "uge"; + break; + case FCmpInst::GT: + return "ugt"; + break; + case FCmpInst::LE: + return "ule"; + break; + case FCmpInst::LT: + return "ult"; + break; + case FCmpInst::EQ: + return "ueq"; + break; + case FCmpInst::NE: + return "une"; + break; + default: + break; + } + return "wrong fcmpop"; +} diff --git a/src/SysYIR/Instruction.cpp b/src/SysYIR/Instruction.cpp new file mode 100644 index 0000000..18983e2 --- /dev/null +++ b/src/SysYIR/Instruction.cpp @@ -0,0 +1,670 @@ +#include "Type.h" +#include "Module.h" +#include "Function.h" +#include "BasicBlock.h" +#include "Instruction.h" +#include "IRprinter.h" +#ifdef DEBUG +#include +#endif +#include +#include + +Instruction::Instruction(Type *ty, OpID id, unsigned num_ops, + BasicBlock *parent) + : User(ty, "", num_ops), op_id_(id), num_ops_(num_ops), parent_(parent) +{ + parent_->add_instruction(this); +} + +Instruction::Instruction(Type *ty, OpID id, unsigned num_ops) + : User(ty, "", num_ops), op_id_(id), num_ops_(num_ops), parent_(nullptr) +{ + +} + +Function *Instruction::get_function() +{ + return parent_->get_parent(); +} + +Module *Instruction::get_module() +{ + return parent_->get_module(); +} + +BinaryInst::BinaryInst(Type *ty, OpID id, Value *v1, Value *v2, + BasicBlock *bb) + : Instruction(ty, id, 2, bb) +{ + set_operand(0, v1); + set_operand(1, v2); +} + +BinaryInst *BinaryInst::create_add(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(v1->get_type()->is_pointer_type() ? v1->get_type() : v2->get_type(), Instruction::add, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_sub(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_int32_type(m), Instruction::sub, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_mul(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_int32_type(m), Instruction::mul, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_sdiv(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_int32_type(m), Instruction::sdiv, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_srem(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_int32_type(m), Instruction::srem, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_fadd(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_float_type(m), Instruction::fadd, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_fsub(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_float_type(m), Instruction::fsub, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_fmul(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_float_type(m), Instruction::fmul, v1, v2, bb); +} + +BinaryInst *BinaryInst::create_fdiv(Value *v1, Value *v2, BasicBlock *bb, Module *m) +{ + return new BinaryInst(Type::get_float_type(m), Instruction::fdiv, v1, v2, bb); +} + +std::string BinaryInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type())) + { + instr_ir += print_as_op(this->get_operand(1), false); + } + else + { + instr_ir += print_as_op(this->get_operand(1), true); + } + return instr_ir; +} + +CmpInst::CmpInst(Type *ty, CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb) + : Instruction(ty, Instruction::cmp, 2, bb), cmp_op_(op) +{ + set_operand(0, lhs); + set_operand(1, rhs); +} + +CmpInst *CmpInst::create_cmp(CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb, Module *m) +{ + return new CmpInst(m->get_int1_type(), op, lhs, rhs, bb); +} + +std::string CmpInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += print_cmp_type(this->cmp_op_); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type())) + { + instr_ir += print_as_op(this->get_operand(1), false); + } + else + { + instr_ir += print_as_op(this->get_operand(1), true); + } + return instr_ir; +} + +FCmpInst::FCmpInst(Type *ty, CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb) + : Instruction(ty, Instruction::fcmp, 2, bb), cmp_op_(op) +{ + set_operand(0, lhs); + set_operand(1, rhs); +} + +FCmpInst *FCmpInst::create_fcmp(CmpOp op, Value *lhs, Value *rhs, + BasicBlock *bb, Module *m) +{ + return new FCmpInst(m->get_int1_type(), op, lhs, rhs, bb); +} + +std::string FCmpInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += print_fcmp_type(this->cmp_op_); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type())) + { + instr_ir += print_as_op(this->get_operand(1), false); + } + else + { + instr_ir += print_as_op(this->get_operand(1), true); + } + return instr_ir; +} + +CallInst::CallInst(Function *func, std::vector args, BasicBlock *bb) + : Instruction(func->get_return_type(), Instruction::call, args.size() + 1, bb) +{ +#ifdef DEBUG + assert(func->get_num_of_args() == args.size()); +#endif + int num_ops = args.size() + 1; + set_operand(0, func); + for (int i = 1; i < num_ops; i++) { + set_operand(i, args[i-1]); + } +} + +CallInst::CallInst(Type *ret_ty, std::vector args, BasicBlock *bb) + : Instruction(ret_ty, Instruction::call, args.size() + 1, bb) +{ + int num_ops = args.size() + 1; + for (int i = 1; i < num_ops; i++) { + set_operand(i, args[i-1]); + } +} + +CallInst *CallInst::create(Function *func, std::vector args, BasicBlock *bb) +{ + return new CallInst(func, args, bb); +} + +FunctionType *CallInst::get_function_type() const +{ + return static_cast(get_operand(0)->get_type()); +} + +std::string CallInst::print() +{ + std::string instr_ir; + if( !this->is_void() ) + { + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + } + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_function_type()->get_return_type()->print(); + + instr_ir += " "; +#ifdef DEBUG + assert(dynamic_cast(this->get_operand(0)) && "Wrong call operand function"); +#endif + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += "("; + for (int i = 1; i < this->get_num_operand(); i++) + { + if( i > 1 ) + instr_ir += ", "; + instr_ir += this->get_operand(i)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(i), false); + } + instr_ir += ")"; + return instr_ir; +} + +BranchInst::BranchInst(Value *cond, BasicBlock *if_true, BasicBlock *if_false, + BasicBlock *bb) + : Instruction(Type::get_void_type(if_true->get_module()), Instruction::br, 3, bb) +{ + set_operand(0, cond); + set_operand(1, if_true); + set_operand(2, if_false); +} + +BranchInst::BranchInst(Value *cond, BasicBlock *bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::br, 3, bb) +{ + set_operand(0, cond); +} + +BranchInst::BranchInst(BasicBlock *if_true, BasicBlock *bb) + : Instruction(Type::get_void_type(if_true->get_module()), Instruction::br, 1, bb) +{ + set_operand(0, if_true); +} + +BranchInst::BranchInst(BasicBlock *bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::br, 1, bb) +{ + +} + +BranchInst *BranchInst::create_cond_br(Value *cond, BasicBlock *if_true, BasicBlock *if_false, + BasicBlock *bb) +{ + if_true->add_pre_basic_block(bb); + if_false->add_pre_basic_block(bb); + bb->add_succ_basic_block(if_false); + bb->add_succ_basic_block(if_true); + + return new BranchInst(cond, if_true, if_false, bb); +} + +BranchInst *BranchInst::create_br(BasicBlock *if_true, BasicBlock *bb) +{ + if_true->add_pre_basic_block(bb); + bb->add_succ_basic_block(if_true); + + return new BranchInst(if_true, bb); +} + +bool BranchInst::is_cond_br() const +{ + return get_num_operand() == 3; +} + +std::string BranchInst::print() +{ + std::string instr_ir; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), true); + if( is_cond_br() ) + { + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(1), true); + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(2), true); + } + return instr_ir; +} + +ReturnInst::ReturnInst(Value *val, BasicBlock *bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::ret, 1, bb) +{ + set_operand(0, val); +} + +ReturnInst::ReturnInst(BasicBlock *bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::ret, 0, bb) +{ + +} + +ReturnInst *ReturnInst::create_ret(Value *val, BasicBlock *bb) +{ + return new ReturnInst(val, bb); +} + +ReturnInst *ReturnInst::create_void_ret(BasicBlock *bb) +{ + return new ReturnInst(bb); +} + +bool ReturnInst::is_void_ret() const +{ + return get_num_operand() == 0; +} + +std::string ReturnInst::print() +{ + std::string instr_ir; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + if ( !is_void_ret() ) + { + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + } + else + { + instr_ir += "void"; + } + + return instr_ir; +} + +GetElementPtrInst::GetElementPtrInst(Value *ptr, std::vector idxs, BasicBlock *bb) + : Instruction(PointerType::get(get_element_type(ptr, idxs)), Instruction::getelementptr, + 1 + idxs.size(), bb) +{ + set_operand(0, ptr); + for (int i = 0; i < idxs.size(); i++) { + set_operand(i + 1, idxs[i]); + } + element_ty_ = get_element_type(ptr, idxs); +} + +Type *GetElementPtrInst::get_element_type(Value *ptr, std::vector idxs) +{ + + Type *ty = ptr->get_type()->get_pointer_element_type(); + if (ty->is_array_type()) + { + ArrayType *arr_ty = static_cast(ty); + for (int i = 1; i < idxs.size(); i++) { + ty = arr_ty->get_element_type(); + if (i < idxs.size() - 1) { +#ifdef DEBUG + assert(ty->is_array_type() && "Index error!"); +#endif + } + if (ty->is_array_type()) { + arr_ty = static_cast(ty); + } + } + } + return ty; +} + +Type *GetElementPtrInst::get_element_type() const +{ + return element_ty_; +} + +GetElementPtrInst *GetElementPtrInst::create_gep(Value *ptr, std::vector idxs, BasicBlock *bb) +{ + return new GetElementPtrInst(ptr, idxs, bb); +} + +std::string GetElementPtrInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; +#ifdef DEBUG + assert(this->get_operand(0)->get_type()->is_pointer_type()); +#endif + instr_ir += this->get_operand(0)->get_type()->get_pointer_element_type()->print(); + instr_ir += ", "; + for (int i = 0; i < this->get_num_operand(); i++) + { + if( i > 0 ) + instr_ir += ", "; + instr_ir += this->get_operand(i)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(i), false); + } + return instr_ir; +} + +StoreInst::StoreInst(Value *val, Value *ptr, BasicBlock *bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::store, 2, bb) +{ + set_operand(0, val); + set_operand(1, ptr); +} + +StoreInst *StoreInst::create_store(Value *val, Value *ptr, BasicBlock *bb) +{ + return new StoreInst(val, ptr, bb); +} + +std::string StoreInst::print() +{ + std::string instr_ir; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(1), true); + return instr_ir; +} + +LoadInst::LoadInst(Type *ty, Value *ptr, BasicBlock *bb) + : Instruction(ty, Instruction::load, 1, bb) +{ +#ifdef DEBUG + assert(ptr->get_type()->is_pointer_type()); + assert(ty == static_cast(ptr->get_type())->get_element_type()); +#endif + set_operand(0, ptr); +} + +LoadInst *LoadInst::create_load(Type *ty, Value *ptr, BasicBlock *bb) +{ + return new LoadInst(ty, ptr, bb); +} + +Type *LoadInst::get_load_type() const +{ + return static_cast(get_operand(0)->get_type())->get_element_type(); +} + +std::string LoadInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; +#ifdef DEBUG + assert(this->get_operand(0)->get_type()->is_pointer_type()); +#endif + instr_ir += this->get_operand(0)->get_type()->get_pointer_element_type()->print(); + instr_ir += ","; + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), true); + return instr_ir; +} + +AllocaInst::AllocaInst(Type *ty, BasicBlock *bb) + : Instruction(PointerType::get(ty), Instruction::alloca, 0, bb), alloca_ty_(ty) +{ + +} + +AllocaInst *AllocaInst::create_alloca(Type *ty, BasicBlock *bb) +{ + return new AllocaInst(ty, bb); +} + +Type *AllocaInst::get_alloca_type() const +{ + return alloca_ty_; +} + +std::string AllocaInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += get_alloca_type()->print(); + return instr_ir; +} + +ZextInst::ZextInst(OpID op, Value *val, Type *ty, BasicBlock *bb) + : Instruction(ty, op, 1, bb), dest_ty_(ty) +{ + set_operand(0, val); +} + +ZextInst *ZextInst::create_zext(Value *val, Type *ty, BasicBlock *bb) +{ + return new ZextInst(Instruction::zext, val, ty, bb); +} + +Type *ZextInst::get_dest_type() const +{ + return dest_ty_; +} + +std::string ZextInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += " to "; + instr_ir += this->get_dest_type()->print(); + return instr_ir; +} + +FpToSiInst::FpToSiInst(OpID op, Value *val, Type *ty, BasicBlock *bb) + : Instruction(ty, op, 1, bb), dest_ty_(ty) +{ + set_operand(0, val); +} + +FpToSiInst *FpToSiInst::create_fptosi(Value *val, Type *ty, BasicBlock *bb) +{ + return new FpToSiInst(Instruction::fptosi, val, ty, bb); +} + +Type *FpToSiInst::get_dest_type() const +{ + return dest_ty_; +} + +std::string FpToSiInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += " to "; + instr_ir += this->get_dest_type()->print(); + return instr_ir; +} + +SiToFpInst::SiToFpInst(OpID op, Value *val, Type *ty, BasicBlock *bb) + : Instruction(ty, op, 1, bb), dest_ty_(ty) +{ + set_operand(0, val); +} + +SiToFpInst *SiToFpInst::create_sitofp(Value *val, Type *ty, BasicBlock *bb) +{ + return new SiToFpInst(Instruction::sitofp, val, ty, bb); +} + +Type *SiToFpInst::get_dest_type() const +{ + return dest_ty_; +} + +std::string SiToFpInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += " to "; + instr_ir += this->get_dest_type()->print(); + return instr_ir; +} + +PhiInst::PhiInst(OpID op, std::vector vals, std::vector val_bbs, Type *ty, BasicBlock *bb) + : Instruction(ty, op, 2*vals.size() ) +{ + for ( int i = 0; i < vals.size(); i++) + { + set_operand(2*i, vals[i]); + set_operand(2*i+1, val_bbs[i]); + } + this->set_parent(bb); +} + +PhiInst *PhiInst::create_phi( Type *ty, BasicBlock *bb) +{ + std::vector vals; + std::vector val_bbs; + return new PhiInst(Instruction::phi, vals, val_bbs, ty, bb); +} + +std::string PhiInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + for (int i = 0; i < this->get_num_operand()/2; i++) + { + if( i > 0 ) + instr_ir += ", "; + instr_ir += "[ "; + instr_ir += print_as_op(this->get_operand(2*i), false); + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(2*i+1), false); + instr_ir += " ]"; + } + if ( this->get_num_operand()/2 < this->get_parent()->get_pre_basic_blocks().size() ) + { + for ( auto pre_bb : this->get_parent()->get_pre_basic_blocks() ) + { + if (std::find(this->get_operands().begin(), this->get_operands().end(), static_cast(pre_bb)) == this->get_operands().end()) + { + // find a pre_bb is not in phi + instr_ir += ", [ undef, " +print_as_op(pre_bb, false)+" ]"; + } + } + } + return instr_ir; +} \ No newline at end of file diff --git a/src/SysYIR/Module.cpp b/src/SysYIR/Module.cpp new file mode 100644 index 0000000..b8e4263 --- /dev/null +++ b/src/SysYIR/Module.cpp @@ -0,0 +1,139 @@ +#include "Module.h" + +Module::Module(std::string name) + : module_name_(name) +{ + void_ty_ = new Type(Type::VoidTyID, this); + label_ty_ = new Type(Type::LabelTyID, this); + int1_ty_ = new IntegerType(1, this); + int32_ty_ = new IntegerType(32, this); + float32_ty_ = new FloatType(this); + // init instr_id2string + instr_id2string_.insert({ Instruction::ret, "ret" }); + instr_id2string_.insert({ Instruction::br, "br" }); + + instr_id2string_.insert({ Instruction::add, "add" }); + instr_id2string_.insert({ Instruction::sub, "sub" }); + instr_id2string_.insert({ Instruction::mul, "mul" }); + instr_id2string_.insert({ Instruction::sdiv, "sdiv" }); + instr_id2string_.insert({ Instruction::srem, "srem" }); + + instr_id2string_.insert({ Instruction::fadd, "fadd" }); + instr_id2string_.insert({ Instruction::fsub, "fsub" }); + instr_id2string_.insert({ Instruction::fmul, "fmul" }); + instr_id2string_.insert({ Instruction::fdiv, "fdiv" }); + + instr_id2string_.insert({ Instruction::alloca, "alloca" }); + instr_id2string_.insert({ Instruction::load, "load" }); + instr_id2string_.insert({ Instruction::store, "store" }); + instr_id2string_.insert({ Instruction::cmp, "icmp" }); + instr_id2string_.insert({ Instruction::fcmp, "fcmp" }); + instr_id2string_.insert({ Instruction::phi, "phi" }); + instr_id2string_.insert({ Instruction::call, "call" }); + instr_id2string_.insert({ Instruction::getelementptr, "getelementptr" }); + instr_id2string_.insert({ Instruction::zext, "zext" }); + instr_id2string_.insert({ Instruction::fptosi, "fptosi" }); + instr_id2string_.insert({ Instruction::sitofp, "sitofp" }); +} + +Module::~Module() +{ + delete void_ty_; + delete label_ty_; + delete int1_ty_; + delete int32_ty_; + delete float32_ty_; +} + +Type *Module::get_void_type() +{ + return void_ty_; +} + +Type *Module::get_label_type() +{ + return label_ty_; +} + +IntegerType *Module::get_int1_type() +{ + return int1_ty_; +} + +IntegerType *Module::get_int32_type() +{ + return int32_ty_; +} + +FloatType *Module::get_float_type() +{ + return float32_ty_; +} + +PointerType *Module::get_pointer_type(Type *contained) +{ + if( pointer_map_.find(contained) == pointer_map_.end() ) + { + pointer_map_[contained] = new PointerType(contained); + } + return pointer_map_[contained]; +} + +ArrayType *Module::get_array_type(Type *contained, unsigned num_elements) +{ + if( array_map_.find({contained, num_elements}) == array_map_.end() ) + { + array_map_[{contained, num_elements}] = new ArrayType(contained, num_elements); + } + return array_map_[{contained, num_elements}]; +} + +PointerType *Module::get_int32_ptr_type() +{ + return get_pointer_type(int32_ty_); +} + +PointerType *Module::get_float_ptr_type() +{ + return get_pointer_type(float32_ty_); +} + +void Module::add_function(Function *f) +{ + function_list_.push_back(f); +} +std::list &Module::get_functions(){ + return function_list_; +} +void Module::add_global_variable(GlobalVariable* g) +{ + global_list_.push_back(g); +} +std::list &Module::get_global_variable(){ + return global_list_; +} + +void Module::set_print_name() +{ + for (auto func : this->get_functions()) + { + func->set_instr_name(); + } + return ; +} + +std::string Module::print() +{ + std::string module_ir; + for ( auto global_val : this->global_list_) + { + module_ir += global_val->print(); + module_ir += "\n"; + } + for ( auto func : this->function_list_) + { + module_ir += func->print(); + module_ir += "\n"; + } + return module_ir; +} diff --git a/src/SysYIR/Type.cpp b/src/SysYIR/Type.cpp new file mode 100644 index 0000000..8a5af15 --- /dev/null +++ b/src/SysYIR/Type.cpp @@ -0,0 +1,260 @@ +#include "Type.h" +#include "Module.h" + +#ifdef DEBUG +#include +#endif + +Type::Type(TypeID tid, Module *m) +{ + tid_ = tid; + m_ = m; +} + +Module *Type::get_module() +{ + return m_; +} + +bool Type::is_eq_type(Type *ty1, Type *ty2) +{ + return ty1 == ty2; +} + +Type *Type::get_void_type(Module *m) +{ + return m->get_void_type(); +} + +Type *Type::get_label_type(Module *m) +{ + return m->get_label_type(); +} + +IntegerType *Type::get_int1_type(Module *m) +{ + return m->get_int1_type(); +} + +IntegerType *Type::get_int32_type(Module *m) +{ + return m->get_int32_type(); +} + +FloatType *Type::get_float_type(Module *m) +{ + return m->get_float_type(); +} + +PointerType *Type::get_pointer_type(Type *contained) +{ + return PointerType::get(contained); +} + +ArrayType *Type::get_array_type(Type *contained, unsigned num_elements) +{ + return ArrayType::get(contained, num_elements); +} + +PointerType *Type::get_int32_ptr_type(Module *m) +{ + return m->get_int32_ptr_type(); +} + +PointerType *Type::get_float_ptr_type(Module *m) +{ + return m->get_float_ptr_type(); +} + +Type *Type::get_pointer_element_type(){ + if( this->is_pointer_type() ) + return static_cast(this)->get_element_type(); + else + return nullptr; +} + +Type *Type::get_array_element_type(){ + if( this->is_array_type() ) + return static_cast(this)->get_element_type(); + else + return nullptr; +} + +int Type::get_size() +{ + if (this->is_integer_type()) + { + auto bits = static_cast(this)->get_num_bits() / 8; + return bits > 0 ? bits : 1; + } + if (this->is_float_type()) + { + return 4; + } + if (this->is_array_type()) + { + auto element_size = static_cast(this)->get_element_type()->get_size(); + auto num_elements = static_cast(this)->get_num_of_elements(); + return element_size * num_elements; + } + if (this->is_pointer_type()) + { + if (this->get_pointer_element_type()->is_array_type()) + { + return this->get_pointer_element_type()->get_size(); + } + else + { + return 4; + } + } + return 0; +} + +std::string Type::print(){ + std::string type_ir; + switch (this->get_type_id()) + { + case VoidTyID: + type_ir += "void"; + break; + case LabelTyID: + type_ir += "label"; + break; + case IntegerTyID: + type_ir += "i"; + type_ir += std::to_string( static_cast(this)->get_num_bits()); + break; + case FloatTyID: + type_ir += "float"; + break; + case FunctionTyID: + type_ir += static_cast(this)->get_return_type()->print(); + type_ir += " ("; + for( int i = 0 ; i < static_cast(this)->get_num_of_args() ; i++) + { + if(i) + type_ir += ", "; + type_ir += static_cast(this)->get_param_type(i)->print(); + } + type_ir += ")"; + break; + case PointerTyID: + type_ir += this->get_pointer_element_type()->print(); + type_ir += "*"; + break; + case ArrayTyID: + type_ir += "["; + type_ir += std::to_string( static_cast(this)->get_num_of_elements()); + type_ir += " x "; + type_ir += static_cast(this)->get_element_type()->print(); + type_ir += "]"; + break; + default: + break; + } + return type_ir; +} + +IntegerType::IntegerType(unsigned num_bits , Module *m) + : Type(Type::IntegerTyID, m), num_bits_(num_bits) +{ +} + +IntegerType *IntegerType::get(unsigned num_bits, Module *m ) +{ + return new IntegerType(num_bits, m); +} + +unsigned IntegerType::get_num_bits() +{ + return num_bits_; +} + +FloatType::FloatType(Module *m) + : Type(Type::FloatTyID, m) +{ +} + +FloatType *FloatType::get(Module *m ) +{ + return new FloatType(m); +} + +FunctionType::FunctionType(Type *result, std::vector params) + : Type(Type::FunctionTyID, nullptr) +{ +#ifdef DEBUG + assert(is_valid_return_type(result) && "Invalid return type for function!"); +#endif + result_ = result; + + for (auto p : params) { +#ifdef DEBUG + assert(is_valid_argument_type(p) && + "Not a valid type for function argument!"); +#endif + args_.push_back(p); + } +} + +bool FunctionType::is_valid_return_type(Type *ty) +{ + return ty->is_integer_type() || ty->is_void_type(); +} + +bool FunctionType::is_valid_argument_type(Type *ty) +{ + return ty->is_integer_type() || ty->is_pointer_type(); +} + +FunctionType *FunctionType::get(Type *result, + std::vector params) +{ + return new FunctionType(result, params); +} + +unsigned FunctionType::get_num_of_args() const +{ + return args_.size(); +} + +Type *FunctionType::get_param_type(unsigned i) const +{ + return args_[i]; +} + +Type *FunctionType::get_return_type() const +{ + return result_; +} + +ArrayType::ArrayType(Type *contained, unsigned num_elements) + : Type(Type::ArrayTyID, contained->get_module()), num_elements_(num_elements) +{ +#ifdef DEBUG + assert(is_valid_element_type(contained) && "Not a valid type for array element!"); +#endif + contained_ = contained; +} + +bool ArrayType::is_valid_element_type(Type *ty) +{ + return ty->is_integer_type()||ty->is_array_type(); +} + +ArrayType *ArrayType::get(Type *contained, unsigned num_elements) +{ + return contained->get_module()->get_array_type(contained, num_elements); +} + +PointerType::PointerType(Type *contained) + : Type(Type::PointerTyID, contained->get_module()), contained_(contained) +{ + +} + +PointerType *PointerType::get(Type *contained) +{ + return contained->get_module()->get_pointer_type(contained); +} diff --git a/src/SysYIR/User.cpp b/src/SysYIR/User.cpp new file mode 100644 index 0000000..c896e9f --- /dev/null +++ b/src/SysYIR/User.cpp @@ -0,0 +1,60 @@ +#include "User.h" +#ifdef DEBUG +#include +#endif + +User::User(Type *ty, const std::string &name , unsigned num_ops ) + : Value(ty, name), num_ops_(num_ops) +{ + // if (num_ops_ > 0) + // operands_.reset(new std::list()); + operands_.resize(num_ops_, nullptr); +} + +std::vector& User::get_operands() +{ + return operands_; +} + +Value *User::get_operand(unsigned i) const +{ + return operands_[i]; +} + +void User::set_operand(unsigned i, Value *v) +{ +#ifdef DEBUG + assert(i < num_ops_ && "set_operand out of index"); +#endif + // assert(operands_[i] == nullptr && "ith operand is not null"); + operands_[i] = v; + v->add_use(this, i); +} + +void User::add_operand( Value *v) +{ + operands_.push_back(v); + v->add_use(this, num_ops_); + num_ops_++; +} + +unsigned User::get_num_operand() const +{ + return num_ops_; +} + +void User::remove_use_of_ops() +{ + for (auto op : operands_) { + op->remove_use(this); + } +} + +void User::remove_operands(int index1,int index2){ + for(int i=index1;i<=index2;i++){ + operands_[i]->remove_use(this); + } + operands_.erase(operands_.begin()+index1,operands_.begin()+index2+1); + // std::cout< +#endif + +Value::Value(Type *ty, const std::string &name ) + : type_(ty), name_(name) +{ + +} + +void Value::add_use(Value *val, unsigned arg_no ) +{ + use_list_.push_back(Use(val, arg_no)); +} + +std::string Value::get_name() const +{ + return name_; +} + +void Value::replace_all_use_with(Value *new_val) +{ + for (auto use : use_list_) { + auto val = dynamic_cast(use.val_); +#ifdef DEBUG + assert(val && "new_val is not a user"); +#endif + val->set_operand(use.arg_no_, new_val); + } +} + +void Value::remove_use(Value *val) +{ + auto is_val = [val] (const Use &use) { return use.val_ == val; }; + use_list_.remove_if(is_val); +} \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..7890d7a --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,62 @@ +#include +#include "SysYBuilder.hpp" +#include "SysYDriver.h" +#include "SyntaxTreePrinter.h" +#include "ErrorReporter.h" + + +void print_help(const std::string& exe_name) { + std::cout << "Usage: " << exe_name + << " [ -h | --help ] [ -p | --trace_parsing ] [ -s | --trace_scanning ] [ -emit-ast ] [ -emit-ir ] [ -o ]" + << " " + << std::endl; +} + +int main(int argc, char *argv[]) +{ + SysYBuilder builder; + SysYDriver driver; + SyntaxTreePrinter printer; + ErrorReporter reporter(std::cerr); + + bool print_ast = false; + bool print_ir = false; + + std::string filename = "testcase.sy"; + std::string output_llvm_file = "testcase.ll"; + for (int i = 1; i < argc; ++i) { + if (argv[i] == std::string("-h") || argv[i] == std::string("--help")) { + print_help(argv[0]); + return 0; + } + else if (argv[i] == std::string("-p") || argv[i] == std::string("--trace_parsing")) + driver.trace_parsing = true; + else if (argv[i] == std::string("-s") || argv[i] == std::string("--trace_scanning")) + driver.trace_scanning = true; + else if (argv[i] == std::string("-emit-ast")) + print_ast = true; + else if (argv[i] == std::string("-emit-ir")) + print_ir = true; + else if (argv[i] == std::string("-o")){ + output_llvm_file = argv[++i]; + } + else { + filename = argv[i]; + } + } + auto root = driver.parse(filename); + if (print_ast) + root->accept(printer); + if (print_ir) { + root->accept(builder); + auto m = builder.getModule(); + m->set_file_name(filename); + m->set_print_name(); + auto IR = m->print(); + std::ofstream output_stream; + output_stream.open(output_llvm_file, std::ios::out); + output_stream << IR; + output_stream.close(); + } + return 0; +} diff --git a/test.c b/test.c deleted file mode 100644 index 5a8392b..0000000 --- a/test.c +++ /dev/null @@ -1 +0,0 @@ - //test git \ No newline at end of file