自下而上分析.doc
文本预览下载声明
实验二 语法分析(自下而上分析)
实验目的
设计语法分析器
实验要求
掌握自下而上分语法分析思想
实现语法分析器和词法分析器的连接
编写语法分析器的程序
调试、运行程序,并结合调试实例进行分析
实验内容
通过分析栈和分析表实现句型分析,输入符号串从词法分析的结果文件中获取;通过栈顶的状态与当前输入符号匹配确定分析表部分的元素,当是移进动作时,把输入符号与状态推入栈中,当元素是归约动作时,把栈顶中形成的句柄部分按照规则归约;
对新栈状态与所归约的非终结符按照转移表部分进行状态转换,把转换成的状态与所归约成非终结符推入栈中。
其中特别注意的是记录分析过程和显示分析过程
本实验程序有以下几个方面;
文法输入
分析结果的输出
分析结果
源程序实现
#include stdio.h
#include malloc.h
#include string
struct stack
{
stack *top;
char value;
};
char pop(stack *pst)
{ char e;
if(pst-top==pst)
{
printf(The stack is null.);
return 0;
}
else
{
e=pst-top-value;
pst-top--;
return e;
}
}
void push(stack *pst,char e)
{
pst-top++;
pst-top-value=e;
}
void printstack(stack *pst)
{ stack *printtemp=pst;
while(printtemp=(pst-top))
{
printf(%c,printtemp-value);
printtemp++;
}
}
void printstring(stack *pst)
{
stack *printtemp=(pst-top);
while(printtemp=pst)
{
printf(%c,printtemp-value);
printtemp--;
}
}
void printSLR(int number,stack *status,stack *grammar,stack *string)
{
printf(%d ,number);
printstack(status);printf( );
printstack(grammar);printf( );
printstring(string);printf( );
number++;
}
int main()
{
stack *string=(stack *)malloc(40);
string-top=string;
string-top-value=#;
stack *status=(stack *)malloc(40);
status-top=status;
status-top-value=0;
stack *grammar=(stack *)malloc(40);
gr
显示全部