代码拉取完成,页面将自动刷新
同步操作将从 zren/compiler-homework3 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。