1

我正在使用 Antlr4。这是我的语法:

assign : id '=' expr ;
    id : 'A' | 'B' | 'C' ;
  expr : expr '+' term
       | expr '-' term
       | term ;
  term : term '*' factor
       | term '/' factor
       | factor ;
factor : expr '**' factor
       | '(' expr ')'
       | id ;
    WS : [ \t\r\n]+ -> skip ;

我知道这个语法是模棱两可的,而且我知道我应该在语法中添加一个元素,但我不知道如何使语法明确。

4

1 回答 1

1
factor : expr '**' factor

Consider the input

A + B ** C

A + B is an expr so we could analyse that as a factor, semantically (A+B)C

But the other, more conventional interpretation (A + (BC)) is also possible:

<expr>                   => 
<expr> + <term>          =>
<term> + <term>          =>
<factor> + <term>        =>
A        + <term>        =>
A        + <factor>      =>
A + <expr> ** <factor>   =>
A + <term> ** <factor>   =>
A + <factor> ** <factor> =>
A + B ** <factor>        =>
A + B ** C
于 2017-11-05T16:32:01.980 回答