On 23 Nov 2006, at 00:13, Paul Eggert wrote:
Hans Aberg <[EMAIL PROTECTED]> writes:
This can become cumbersome when writing:
OK, thanks, I now understand the problem better: the nonterminal names
can be quite long, and you want a shorter name in the action (which is
typically small, so it's ok to have short local names). In that case,
the syntax could have an identifier after the '#', as you suggested,
and this identifier would supersede the nonterminal's identifier
within the action.
One is really identifying a parser stack location, from which
semantic value, location, and possibly more is extracted, like
perhaps token names (for, among other things, error messages) and
token values (needed when implementing language definitions). This is
why I am thinking in terms of OO like a 'struct' or 'class'.
One might extend the # notation to indicate actions. Then one might
simplify
expression:
INTEGRAL_NUMBER#x { $$ = $x; }
| '-' expression#x %prec NEGATION { $$ = -$x; }
| '(' expression#x ')' { $$ = $x; }
| expression#x '+' expression#y { $$ = $x + $y; }
| expression#x '-' expression#y { $$ = $x - $y; }
| expression#x '*' expression#y { $$ = $x * $y; }
| expression#x '/' expression#y { $$ = $x / $y; }
| expression#x '^' expression#y { $$ = pow($x, $y); }
;
to
expression:
INTEGRAL_NUMBER#x ##identity
| '-' expression#x %prec NEGATION ##neg
| '(' expression#x ')' ##identity
| expression#x '+' expression#y ##add
| expression#x '-' expression#y ##sub
| expression#x '*' expression#y ##mul
| expression#x '/' expression#y ##div
| expression#x '^' expression#y ##pow
;
identity { $$ = $x; }
neg { $$ = -$x; }
add { $$ = $x + $y; }
sub { $$ = $x - $y; }
mul { $$ = $x * $y; }
div { $$ = $x / $y; }
pow { $$ = pow($x, $y); }
The idea is to put the action definitions, at need, somewhere where
they do not make the grammar rules hard to read. In addition, action
definitions used more than once, like "identity" above, need not be
repeated in the grammar.
One must use a double hash "##", or another token than "#", as
a # b
is ambiguous: it can mean either a variable with a parser stack
(semantic) variable, or a variable with nothing followed by a named
action.
Hans Aberg