int expr(void) { expr() while(1) { do something ... } } |
/* <syntax rule> expr := expr oper_level_2 term | term term := term oper_level_1 factor | factor oper_level_2 := +|- oper_level_1 := *|/ factor := 0|1|2|3|4|5|6|7|8|9|(expr) */ #define LENGTH 1000 int i = 0; char buf[LENGTH]; char token; void error(char *str) { printf("\n error: %s\n", str); exit(1); } void next_token(void) { token = buf[i++]; if (i > LENGTH) error("The length of buffer is overflow"); } void match(ch) { if (token == ch) next_token(); else error("syntax error"); } int ctoi(char ch) { return ch - 48; } int isdigital(char d) { if ((ctoi(d) >= 0) && (ctoi(d) <= 9)) return 0; else return -1; } int factor(void) { int tmp; if (token == '(') { match('('); printf("%c", '('); tmp = expr(); match(')'); printf("%c", ')'); return tmp; } else if (isdigital(token) == 0) { printf("%c", token); tmp = token; next_token(); return ctoi(tmp); } else error("lexical error"); } int term(void) { int tmp; tmp = factor(); while (1) { if (token == '*' ) { match('*'); printf("%c", '*'); tmp = tmp * factor(); } else if (token == '/' ) { match('/'); printf("%c", '/'); tmp = tmp / factor(); } else break; } return tmp; } int expr(void) { int tmp; tmp = term(); while (1) { if (token == '+' ) { match('+'); printf("%c", '+'); tmp = tmp + term(); } else if (token == '-' ) { match('-'); printf("%c", '-'); tmp = tmp - term(); } else break; } return tmp; } int main(void) { int tmp; while(1) { memset(buf, 0, LENGTH); i = 0; printf("plese input the expression:\n"); gets(buf); if (strcmp(buf, "quit") == 0) break; printf("start to parse\n"); next_token(); tmp = expr(); printf(" = %d", tmp); printf("\n"); } return 0; } |
原帖由 rocenting 于 2009-3-21 23:59 发表
程序本身没有问题的,但感觉自己就是没有完全掌握,所以想找人指点一下呵呵。
mik是珠海的啊,好像记忆中建荣要做自己的编译器的,用于一个单片机,莫非。。。。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/) | Powered by Discuz! X3.2 |