问题
In larger program I have given the following (flex/bison)
In flex:
pn [\+|\-]
dig [0-9]+
exp [e|E]{dig}+
.
.
.
"+" {printf("+ detected\n");
return PLUS_SIGN;}
{pn}?{dig}+ { printf("digit detected - %s\n",yytext);
sscanf(yytext, "%d", (int*)&yylval);
return TYPE_INT;}
In Bison:
expr:
expr PLUS_SIGN expr
{
$$ = $1 + $3;
printf(" $$=%f\n",$$);
}
| TYPE_INT
{
$$ = (int)$1;
printf(" $$=%f\n",$$);
}
;
The problem is:
When I give 2+2 it recognizes 2 and +2 instead of 2 , + , 2
How can I get it to do the addition?
回答1:
{pn}?{dig}+
Don't make the plus or minus sign ({pn?}
) part of the number token. Treat them as two separate tokens, +
and 2
. Then flex won't have any ambiguity to resolve.
{dig}+
Instead, have bison handle the unary plus and minus operators. Make it the parser's job, not the lexer's.
| PLUS_SIGN expr
{
$$ = +$2;
printf(" $$=%f\n",$$);
}
| MINUS_SIGN expr
{
$$ = -$2;
printf(" $$=%f\n",$$);
}
回答2:
The grammar shows the left part and the right part of PLUS_SIGN has same priority when reducing symbol.The PLUS_SIGN is left combination, so the new grammar is below:
expr: expr PLUS_SIGN expr2
{
$$ = $1 + $3;
printf("$$=%f\n", $$);
}
| expr2
{
$$ = $1;
}
;
expr2: TYPE_INT
{
$$ = (int)$1;
printf(" $$=%f\n",$$);
}
;
来源:https://stackoverflow.com/questions/12540757/how-to-resolve-22-and-22-conflict