提问人: 提问时间:5/14/2023 更新时间:5/14/2023 访问量:72
野牛 %nonassoc 与 %token?
Bison %nonassoc vs %token?
问:
我读过很多资料,但还是不明白:和?%nonassoc
%token
我理解两者之间的区别,但对我来说,前两者听起来是一样的。%left
%right
我希望有人能给我几个例子来了解我什么时候需要使用以及何时使用?%nonassoc
%token
要使用 ?
要使用 ?
要使用 ?%token
%token
%token
答:
1赞
Chase LP
5/14/2023
#1
%token 是声明终端的基本方式。
如果存在任何优先级歧义,使用 %nonassoc 将引发语法错误。
根据我的经验,除了终端的 %token 之外,您不需要任何东西。
这是相关部分$ info bison
3.7.3 Operator Precedence
-------------------------
Use the ‘%left’, ‘%right’, ‘%nonassoc’, or ‘%precedence’ declaration to
declare a token and specify its precedence and associativity, all at
once. These are called “precedence declarations”. *Note Precedence::,
for general information on operator precedence.
The syntax of a precedence declaration is nearly the same as that of
‘%token’: either
%left SYMBOLS...
or
%left <TYPE> SYMBOLS...
And indeed any of these declarations serves the purposes of ‘%token’.
But in addition, they specify the associativity and relative precedence
for all the SYMBOLS:
• The associativity of an operator OP determines how repeated uses of
the operator nest: whether ‘X OP Y OP Z’ is parsed by grouping X
with Y first or by grouping Y with Z first. ‘%left’ specifies
left-associativity (grouping X with Y first) and ‘%right’ specifies
right-associativity (grouping Y with Z first). ‘%nonassoc’
specifies no associativity, which means that ‘X OP Y OP Z’ is
considered a syntax error.
‘%precedence’ gives only precedence to the SYMBOLS, and defines no
associativity at all. Use this to define precedence only, and
leave any potential conflict due to associativity enabled.
• The precedence of an operator determines how it nests with other
operators. All the tokens declared in a single precedence
declaration have equal precedence and nest together according to
their associativity. When two tokens declared in different
precedence declarations associate, the one declared later has the
higher precedence and is grouped first.
评论
0赞
Chase LP
5/14/2023
左/右可能有助于消除歧义;如果您想强制输入明确,nonassoc 可能很有用;很大程度上取决于你正在制作的语法
1赞
Chris Dodd
5/14/2023
#2
%token
声明令牌
%nonassoc
声明令牌并设置其优先级
%left
/%right
声明令牌并设置其优先级并设置其关联性
因此,使用哪种方法取决于您是根本不设置优先级,还是只设置优先级,或者同时设置优先级和关联性。
那么优先级和关联性有什么区别呢?它们都用于在转移令牌和减少包含具有掠夺性(以及可能的关联性)的令牌1 的规则之间存在冲突时解决移位/减少冲突。优先级适用于相关令牌不同(或至少具有不同的优先级)时,而关联性适用于令牌相同(或至少具有相同的优先级)时
1Yacc 实际上是将要减少的规则的优先级和关联性与要转移的令牌的优先级和关联性进行比较。只是规则总是从令牌(规则中的令牌,或用 %prec
指定的令牌)获得优先级/关联性
评论