- 论坛徽章:
- 0
|
我写了一个处理上述问题的flex和bison的语法文件:
cal.l- %{
- #include <stdio.h>
- #include <stdlib.h>
- void yyerror(char*);
- #include "cal.tab.h"
- char buf[1024];
- char* s;
- char* removequote(char* s);
- void substr(char *s, int pos, int count, char* substr);
- %}
- %x STRING
- %%
- "substr" return SUBSTR;
- \"(\\.|[^\\"])*\" { strcpy(buf, yytext); yylval = removequote(yytext); return STR;}
- [0-9]+ {yylval = strdup(yytext); return INT;}
- "," return (',');
- "(" return ('(');
- ")" return (')');
- "+" return ('+');
- [\n] return *yytext;
- [\t] ;
- . yyerror("invalid char\n");
- %%
- int yywrap(void)
- {
- return 1;
- }
- char* removequote(char* s)
- {
- char szValue[1024];
- char szLine[1024];
- int len;
-
- len = strlen(s);
- strcpy(szLine, s);
- strcpy(szValue, &szLine[1]);
- szValue[len - 2] = 0;
-
- s = szValue;
-
- return s;
- }
- void substr(char *s, int pos, int count, char* substr)
- {
- //printf("%s, %d, %d\n", s, pos, count);
- //return s;
- int len, i, j;
- len = strlen(s);
- for ( i = pos, j = 0; i < pos + count; )
- substr[j++] = s[i++];
-
- substr[j] = 0;
- }
复制代码 cal.y- %{
- int yylex(void);
- void yyerror(char*);
- char szTmp[1024];
- %}
- %token STR INT SUBSTR
- %left '+'
- %%
- program:
- program expr '\n' { printf("%s\n", $2); exit(0);}
- |
- ;
- expr:
- STR {$=$1;}
- | SUBSTR '(' STR ',' INT ',' INT ')'
- {
- printf("$3=%s,$5=%s,$7=%s\n", $3, $5, $7);
- substr($3, atoi($5), atoi($7), szTmp);
- $ = szTmp;
- }
- | expr '+' expr
- {
- printf("\n$1=%s, $3=%s\n", $1, $3);
- strcat(szTmp, $1);
- strcat(szTmp, $3);
- $ = szTmp;
- }
- ;
- %%
- void yyerror(char *s)
- {
- fprintf(stderr, "%s\n", s);
- return;
- }
- int main(void)
- {
- yyparse();
- return 0;
- }
复制代码 但问题是,当规约这个表达式expr '+' expr 的时候, 我打印出来的$1和$3的值总是有问题
$1的值被$3的值覆盖了
比如:
当输入: "abcd"+"efgh"的时候,得到的结果是efghefgh, 此时打印的$1和$3的值都是efgh
哪位高人给看看原因呀,谢谢 |
|