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

2019-08-25 14:16发布

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

标签: c parsing bison
2条回答
劫难
2楼-- · 2019-08-25 15:01

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.

查看更多
老娘就宠你
3楼-- · 2019-08-25 15:05

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.

查看更多
登录 后发表回答