LR(1)表驱动语法分析程序
2013-08-31 17:15
274 查看
/* * LR(1) 语法分析 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Common.h" #include "LRCal.h" #include "LRMigrate.h" #include "Stack.h" #define NEXTWORD(s) ((*(s)==0)?SYM_EOF:*((s)++)) extern char *Grammer[]; void LRParse(struct LRElement **LRTable, unsigned char *InputString) { printf("-------- Parse --------\n"); struct Stack *SymbolStack = BuildStack(1024); Push(SymbolStack, 0); // push $; Push(SymbolStack, 0); // push start state s0; int Word = NEXTWORD(InputString); // word <- NextWord(); int State = 0; while (true) // while (true) { State = Top(SymbolStack); // state <- top of stack; printf("State: %d\tWord: %c \t", State, Word); if (LRTable[State][Word].Action == Reduce) // if (Action[state, word] = "reduce A->β") { printf("reduce %d", (int)LRTable[State][Word].ActionValue); char *Production = Grammer[LRTable[State][Word].ActionValue - 1]; int ProductSize = strlen(Production) - 1; // pop 2*|β| symbols; ProductSize *= 2; while (ProductSize--) { Pop(SymbolStack); } // state <- top of stack; State = Top(SymbolStack); // push A; int LeftUnterminal = (int)Production[0]; Push(SymbolStack, LeftUnterminal); // push Goto[State, A]; Push(SymbolStack, (int)LRTable[State][LeftUnterminal].ActionValue); } else if (LRTable[State][Word].Action == Shift) // else if (Action[state, word] = "shift si") { printf("shift %d", (int)LRTable[State][Word].ActionValue); // push word; Push(SymbolStack, Word); // push si; Push(SymbolStack, LRTable[State][Word].ActionValue); // word <- NextWord(); Word = NEXTWORD(InputString); } else if (LRTable[State][Word].Action == Accept) // else if (Action[state, word] = "accept") { printf("accept\n"); break; } else { printf("Syntax Error!\n"); exit(3); } printf("\n"); } printf("Grammer Parse Success!\n"); }
联动:LR(1)表生成算法演示程序
全部代码文件:http://files.cnblogs.com/rexfield/LR.zip
相关文章推荐
- 修改后的基于LL(1)文法的语法分析程序
- 编译原理语法分析对循环语句和条件判断语句编写词法分析编译程序,只能通过一遍扫描完成
- 输入输出LL(1)语法分析程序
- 递归下降语法分析程序设计
- 1217 递归下降语法分析程序设计
- C++:基于LL(1)方法的语法分析程序-1
- 递归下降语法分析程序设计
- 编译原理-用Bison构造语法分析程序-小小计算器
- 编译原理 实验3 递归下降语法分析程序设计
- 编译原理词法分析程序和语法分析程序
- 递归下降语法分析程序设计
- 1217 递归下降语法分析程序设计
- 1223 递归下降语法分析程序设计
- 语法分析程序
- 第四章 语法分析和语法分析程序(1)
- 实验四递归下降语法分析程序设计
- PL0语法分析程序(表达式部分)
- Tiny C语言编译程序之语法分析Parser
- 一个基于LL(1)文法的语法分析程序
- 编译原理:递归向下分析程序建立语法分析树的Java实现(二)