質問

I'm using jison (a javascript equivalent of Bison) and I'm having the following precedence problem. I'll illustrate it using the calculator demo http://zaach.github.com/jison/try/

It works fine as is. The precedence is

%left '+' '-'
%left '*' '/'
%left '^'
%left UMINUS

and the grammar is

e
    : e '+' e
        {$$ = $1+$3;}
    | e '-' e
        {$$ = $1-$3;}
    | e '*' e
        {$$ = $1*$3;}
    | e '/' e
        {$$ = $1/$3;}
    | e '^' e
        {$$ = Math.pow($1, $3);}
    | '-' e %prec UMINUS
        {$$ = -$2;}

If I change the '*' line to be

    | e '*' e %prec TIMESPREC
        {$$ = $1*$3;}

and change the precedence to

%left '+' '-'
%left TIMESPREC '/'
%left '^'
%left UMINUS

it doesn't work any more. Isn't it supposed to work the same? This could be useful, e.g., if one wanted to eventually have an algebra syntax where 2 x + 3 is parsed as (2x)+3.

Thanks!

役に立ちましたか?

解決

The reason for this is because %prec will only set the precedence of the rule, not on all the individual tokens. So, the individual precedence of the tokens on the RHS of the rule still matters.

So, setting %prec on your multiplication rule will not alter the precedence of the '*' symbol. When precedence tries to resolve conflicts it will compare the reduce actions priority with the priority of the token that is to be shifted. Since * has no priority, the grammar becomes ambiguous with your change.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top