野牛,@1 和 $1 之间的差异
Bison, difference between @1 and $1
我正在编写 Pascal 编译器并且已经有了可用的语法。现在我想从语义分析开始但实际上不明白它在bison中是如何工作的。我通过尝试每个选项以某种方式编写了一段工作代码,我想知道@1 和 $1 之间有什么区别。
uint_values_split_by_comma:
UINT {
pas::ic_label label = ctx->tab->new_label();
ctx->tab->add_label_entry(@1, , label);
}
| uint_values_split_by_comma COMMA UINT {}
;
还看了bison文档,还是没看懂。
写semantic action, $n
refer to a semantic value and @n
to a location.
时
这是来自 Bison documentation 的示例:
expr: expr '+' expr { $$ = + ; } ;
</code> 引用左侧表达式的值,<code>
引用右侧表达式的值。
关于位置,在documentation,我们可以读到:
Like semantic values, locations can be reached in actions using a dedicated set of constructs. In the example above, the location of the whole grouping is @$, while the locations of the subexpressions are @1 and @3.
这是语义位置用法的示例:
exp:
…
| exp '/' exp
{
@$.first_column = @1.first_column;
@$.first_line = @1.first_line;
@$.last_column = @3.last_column;
@$.last_line = @3.last_line;
if ()
$$ = / ;
else
{
$$ = 1;
fprintf (stderr, "%d.%d-%d.%d: division by zero",
@3.first_line, @3.first_column,
@3.last_line, @3.last_column);
}
}
在此示例中,使用位置允许打印详细的错误消息以及错误的准确位置。
我正在编写 Pascal 编译器并且已经有了可用的语法。现在我想从语义分析开始但实际上不明白它在bison中是如何工作的。我通过尝试每个选项以某种方式编写了一段工作代码,我想知道@1 和 $1 之间有什么区别。
uint_values_split_by_comma:
UINT {
pas::ic_label label = ctx->tab->new_label();
ctx->tab->add_label_entry(@1, , label);
}
| uint_values_split_by_comma COMMA UINT {}
;
还看了bison文档,还是没看懂。
写semantic action, $n
refer to a semantic value and @n
to a location.
这是来自 Bison documentation 的示例:
expr: expr '+' expr { $$ = + ; } ;
</code> 引用左侧表达式的值,<code>
引用右侧表达式的值。
关于位置,在documentation,我们可以读到:
Like semantic values, locations can be reached in actions using a dedicated set of constructs. In the example above, the location of the whole grouping is @$, while the locations of the subexpressions are @1 and @3.
这是语义位置用法的示例:
exp:
…
| exp '/' exp
{
@$.first_column = @1.first_column;
@$.first_line = @1.first_line;
@$.last_column = @3.last_column;
@$.last_line = @3.last_line;
if ()
$$ = / ;
else
{
$$ = 1;
fprintf (stderr, "%d.%d-%d.%d: division by zero",
@3.first_line, @3.first_column,
@3.last_line, @3.last_column);
}
}
在此示例中,使用位置允许打印详细的错误消息以及错误的准确位置。