Bison: How $ variables ($1 $2 etc) work with non-tokens?

百般思念 提交于 2019-12-13 02:42:27

问题


I'm wondering how $ variables work with non-tokens, like blocks of code. And my question can be reduced to this:

I have a rule like this, with a block of code in the middle of it. In this case who is $3 and $4?

func-header: ret-type ID { strcpy(func_id,current_id); } LPAREN params RPAREN

回答1:


In the rule shown:

  • ret-type is $1.
  • ID is $2.
  • The code block is $3.
  • LPAREN is $4.
  • params is $5.
  • RPAREN is $6.

In other words, code blocks act as non-terminals.




回答2:


Mid-rule actions (MRA) are implemented as non-terminals which match an empty sequence. (Such non-terminals are sometimes called "markers".) The mid-rule action is the semantic action of the generated non-terminal.

Like any non-terminal, these automatically-generated markers have a semantic value, which is set by assigning $$ inside the action. However, the numbering of $n inside a MRA differ slightly from the numbering in normal actions. Inside a MRA, each n in $n is translated to a negative index, representing values on the top of the stack when the marker is reduced, by subtracting the MRA's iwn index.

Negative indices are always allowed by yacc/bison, but as the manual states they are quite dangerous and should only be used if you can prove that an appropriately typed value is necessarily at the indicated point on the stack. In the case of automatically-generated markers, yacc/bison can prove this because the marker is only used in a single production and the generated negative indices always fall into the part of the stack occupied by the right-hand side containing the MRA.



来源:https://stackoverflow.com/questions/56619522/bison-how-variables-1-2-etc-work-with-non-tokens

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!