Manual
Manual
Manual
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
52 Bison 2.3<br />
3.6.2 Actions and Locations<br />
Actions are not only useful for defining language semantics, but also for describing the<br />
behavior of the output parser with locations.<br />
The most obvious way for building locations of syntactic groupings is very similar to<br />
the way semantic values are computed. In a given rule, several constructs can be used to<br />
access the locations of the elements being matched. The location of the nth component of<br />
the right hand side is @n, while the location of the left hand side grouping is @$.<br />
Here is a basic example using the default data type for locations:<br />
exp: ...<br />
| exp ’/’ exp<br />
{<br />
@$.first_column = @1.first_column;<br />
@$.first_line = @1.first_line;<br />
@$.last_column = @3.last_column;<br />
@$.last_line = @3.last_line;<br />
if ($3)<br />
$$ = $1 / $3;<br />
else<br />
{<br />
$$ = 1;<br />
fprintf (stderr,<br />
"Division by zero, l%d,c%d-l%d,c%d",<br />
@3.first_line, @3.first_column,<br />
@3.last_line, @3.last_column);<br />
}<br />
}<br />
As for semantic values, there is a default action for locations that is run each time a rule<br />
is matched. It sets the beginning of @$ to the beginning of the first symbol, and the end of<br />
@$ to the end of the last symbol.<br />
With this default action, the location tracking can be fully automatic. The example<br />
above simply rewrites this way:<br />
exp: ...<br />
| exp ’/’ exp<br />
{<br />
if ($3)<br />
$$ = $1 / $3;<br />
else<br />
{<br />
$$ = 1;<br />
fprintf (stderr,<br />
"Division by zero, l%d,c%d-l%d,c%d",<br />
@3.first_line, @3.first_column,<br />
@3.last_line, @3.last_column);<br />
}<br />
}