0 Star 0 Fork 70

cherishxsy/compiler-homework3

forked from zren/compiler-homework3 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
calculator.c 3.30 KB
一键复制 编辑 原始数据 按行查看 历史
cherishxsy 提交于 2016-05-05 20:30 . 21
#include <stdio.h>
#include <ctype.h>
//E -> TE'
//E' -> +TE' | e
//T -> FT'
//T' -> *FT' | e
//F -> NUM | (E)
//FIRST(E) = {NUM, LEFTB}
//FIRST(E') = {PLUS, e}
//FIRST(T) = {NUM, LEFTB}
//FIRST(T') = {MULT, e}
//FIRST(F) = {NUM, LEFTB}
//FOLLOW(E) = {$, RIGHTB}
//FOLLOW(E') = {$, RIGHTB}
//FOLLOW(T) = {PLUS, RIGHTB, $}
//FOLLOW(T') = {PLUS, RIGHTB, $}
//FOLLOW(F) = {MULT, PLUS, RIGHTB, $}
enum TOKEN {PLUS, MULT, NUM, END, ERR, LEFTB, RIGHTB};
char lookahead;
enum TOKEN token;
int num;
int error = 0;
FILE *fp;
void lexical(FILE *fp);
int match(enum TOKEN x);
int E();
int E_();
int T();
int T_();
int F();
//return 0 if success, return 1 otherwise
int match(enum TOKEN x) {
if(token == x) {
lexical(fp);
return 0;
}
else {
error = 1;
return 1;
}
}
//E -> TE'
int E() {
if ((token ==LEFTB) || (token==NUM)) {
T();
E_();
}
else {
error = 1;
return 1;
}
return 0;
}
//E_ -> +TE'|e
int E_() {
if(token==PLUS){
match(PLUS);
T();
E_();
}
else if ((token == LEFTB) || (token==NUM) || (token == MULT) || (token == EOF) || (token == RIGHTB)){
}
else{
error = 1;
return 1;
}
return 0;
}
//T -> FT'
int T()
{
if ((token == LEFTB) || (token==NUM)){
F();
T_();
}
else{
error = 1;
return 1;
}
return 0;
}
//T' -> *FT' | e
int T_() {
if (token == MULT){
match(MULT);
F();
T_();
}
else if ((token == LEFTB) ||(token==NUM) || (token == PLUS) || (token == EOF) || (token == RIGHTB)){
}
else{
error = 1;
return 1;
}
return 0;
}
//F -> NUM | (E)
int F() {
if (token == LEFTB) {
match(LEFTB);
E();
match(RIGHTB);
if(!match(RIGHTB))
{
error = 2;
return 2;
}
}
else if (token==NUM){
match(num);
}
return 0;
}
void lexical(FILE *fp) {
lookahead = getc(fp);
num = 0;
while(lookahead == ' ' || lookahead == '\t' || lookahead == '\n') {
lookahead = getc(fp);
}
if(isdigit(lookahead)) {
num = 0;
while(isdigit(lookahead)) {
token = NUM;
num = num * 10 + lookahead - '0';
lookahead = getc(fp);
}
ungetc(lookahead, fp);
return;
} else if (lookahead == '+') {
token = PLUS;
return;
} else if (lookahead == '*') {
token = MULT;
return;
} else if(lookahead == EOF) {
token = END;
return;
}else if(lookahead == '(') {
token = LEFTB;
return;
} else if(lookahead == ')') {
token = RIGHTB;
return;
} else {
error = 1;
token = ERR;
return;
}
}
int main(int argc, char **argv) {
int res = 0;
if(argc < 2) {
printf("insufficient arguments");
return 1;
}
fp = fopen(argv[1], "r");
lexical(fp);
res = E();
if(!error){
printf("%d\n", res);
}
else if(error==2){
printf("unmatched bracket\n");
}
else if(error==1){
printf("error \n");
}
fclose(fp);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cherishxsy/compiler-homework3.git
git@gitee.com:cherishxsy/compiler-homework3.git
cherishxsy
compiler-homework3
compiler-homework3
master

搜索帮助