代码拉取完成,页面将自动刷新
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char lookahead;
enum TERMINAL {
ID,
ADD,
MUL,
LBR,
RBR,
END,
ERR
};
enum NON_TERMINAL {
E,
T,
F
};
enum ACTION_TYPE {
SHIFT,
REDUCE,
ERROR,
ACC
};
#define NUM_TERMINAL 6
#define NUM_NONTERMINAL 3
#define NUM_STATES 12
struct action{
enum ACTION_TYPE type;
int id;
} actionTable[NUM_STATES][NUM_TERMINAL];
int gotoTable[NUM_STATES][NUM_NONTERMINAL];
int stackPtr;
int stack[1024];
void push(int state) {
stack[stackPtr] = state;
stackPtr ++;
}
void pop() {
stackPtr --;
}
int top() {
return stack[stackPtr - 1];
}
void init() {
int i, j;
//stack
stackPtr = 0;
push(0);
//action and goto tables
for(i = 0; i < NUM_STATES; i ++) {
for(j = 0; j < NUM_TERMINAL; j ++) {
actionTable[i][j].type = ERROR;
}
for(j = 0; j < NUM_NONTERMINAL; j ++) {
gotoTable[i][j] = -1;
}
}
//fill in the goto table
gotoTable[0][E] = 1;
gotoTable[0][T] = 2;
gotoTable[0][F] = 3;
//... your turn
//fill in the action table
actionTable[2][ADD].type = REDUCE;
actionTable[2][ADD].id = 2;
actionTable[2][MUL].type = SHIFT;
actionTable[2][MUL].id = 7;
actionTable[2][RBR].type = REDUCE;
actionTable[2][RBR].id = 2;
actionTable[2][END].type = REDUCE;
actionTable[2][END].id = 2;
//... your turn
}
enum TERMINAL lexical(FILE *fp) {
lookahead = getc(fp);
while(lookahead == ' ' || lookahead == '\t' || lookahead == '\n') {
lookahead = getc(fp);
}
if(isdigit(lookahead)) {
while(isdigit(lookahead)) {
lookahead = getc(fp);
}
ungetc(lookahead, fp);
return ID;
} else if (lookahead == '+') {
return ADD;
} else if (lookahead == '*') {
return MUL;
} else if(lookahead == EOF) {
return END;
}else if(lookahead == '(') {
return LBR;
} else if(lookahead == ')') {
return RBR;
} else {
return ERR;
}
}
void parse(enum TERMINAL *input) {
int currentState = 0;
int index = 0;
while(1) {
printf("currentState: %d\n", currentState);
switch(actionTable[currentState][input[index]].type) {
case SHIFT:
//how to shift
break;
case REDUCE:
switch(actionTable[currentState][input[index]].id) {
case 1:
//reduce by production 1
break;
case 2:
//reduce by production 2
break;
case 3:
//reduce by production 3
break;
case 4:
//reduce by production 4
break;
case 5:
//reduce by production 5
break;
case 6:
//reduce by production 6
break;
default:
printf("ERROR REDUCE\n");
exit(-1);
break;
}
break;
case ERROR:
printf("ERROR ACTION\n");
exit(-1);
break;
case ACC:
if(input[index] == END) {
printf("ACC\n");
return;
} else {
printf("ERROR ACC\n");
exit(-1);
}
break;
}
}
}
int main(int argc, char **argv) {
enum TERMINAL input[1024];
int inputIndex = 0;
FILE *fp;
enum TERMINAL temp;
if(argc < 2) {
printf("insufficient arguments");
return 1;
}
fp = fopen(argv[1], "r");
while((temp = lexical(fp)) != END) {
input[inputIndex++] = temp;
}
input[inputIndex] = END;
fclose(fp);
init();
parse(input);
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。