parser.c
来自「将简单中缀算术表达式变换成: (1)后缀形式 (2)生成书上描述的抽象堆栈机」· C语言 代码 · 共 88 行
C
88 行
#include "global.h"
int lookahead;
parse()
{
int t;
lookahead = lexan();
while (lookahead != DONE)
{
expr();
if(flag==0) //欲进行求值操作
{
if(wflag!=1) //不含标志符的表达式
fprintf(fp2,"%d",pop());
fprintf(fp2,"\n");
}
else
fprintf(fp2,"\n");
initstack();
wflag=0;
}
}
expr()
{
int t;
term();
while(1)
switch (lookahead)
{
case'+':case '-':
t=lookahead;
match(lookahead);
term();
emit(t,NONE);
continue;
default:
return;
}
}
term()
{
int t;
factor();
while(1)
switch (lookahead)
{
case '*':case '/':case DIV: case MOD:
t=lookahead;
match(lookahead);
factor();
emit(t,NONE);
continue;
default:
return;
}
}
factor()
{
switch(lookahead)
{
case'(':
match('(');expr();match(')');break;
case NUM:
emit(NUM,tokenval);
match(NUM);
break;
case ID:
emit(ID,tokenval);match(ID);break;
default:
error("syntax error");
}
}
match(t)
int t;
{
if(lookahead== t)
{
lookahead = lexan();
}
else error("syntax error");
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?