您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: