parse.cpp
来自「一个简单的词法分析器」· C++ 代码 · 共 70 行
CPP
70 行
#include "global.h"
#include "lexer.h"
#include "emit.h"
#include "error.h"
#include "parse.h"
int lookahead;
void parse(){
lookahead=lexan();
while(lookahead!=DONE){
expr();printf(";\n");match(';');
}
}
void expr(){
int t;
term();
while(1)
switch(lookahead){
case '+':case '-':
t=lookahead;
match(lookahead);emit(t,NONE);term();
continue;
default:
return;
}
}
void term(){
int t;
factor();
while(1)
switch(lookahead){
case '*':case '/':case DIV:case MOD:case '=':
t=lookahead;
match(lookahead);emit(t,NONE);factor();
continue;
case '(':
printf("(\n");
match('(');expr();match(')');
printf(")\n");
break;
continue;
default:
return;
}
}
void factor(){
switch(lookahead){
case '(':
printf("(\n");
match('(');expr();match(')');
printf(")\n");
break;
case NUM:
emit(NUM,tokenval);match(NUM);break;
case ID:
emit(ID,tokenval);match(ID);break;
case SIN:
emit(SIN,NONE);match(SIN);break;
default:
error("syntax error");
}
}
void match(int t){
if(lookahead==t)
lookahead=lexan();
else
error("syntax error");
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?