Previous: %define Summary, Up: Bison Declarations [Contents][Index]
The %code
directive inserts code verbatim into the output
parser source at any of a predefined set of locations. It thus serves
as a flexible and user-friendly alternative to the traditional Yacc
prologue, %{code%}
. This section summarizes the
functionality of %code
for the various target languages
supported by Bison. For a detailed discussion of how to use
%code
in place of %{code%}
for C/C++ and why it
is advantageous to do so, see Prologue Alternatives.
This is the unqualified form of the %code
directive. It
inserts code verbatim at a language-dependent default location
in the parser implementation.
For C/C++, the default location is the parser implementation file
after the usual contents of the parser header file. Thus, the
unqualified form replaces %{code%}
for most purposes.
For D and Java, the default location is inside the parser class.
This is the qualified form of the %code
directive.
qualifier identifies the purpose of code and thus the
location(s) where Bison should insert it. That is, if you need to
specify location-sensitive code that does not belong at the
default location selected by the unqualified %code
form, use
this form instead.
For any particular qualifier or for the unqualified form, if there are
multiple occurrences of the %code
directive, Bison concatenates
the specified code in the order in which it appears in the grammar
file.
Not all qualifiers are accepted for all target languages. Unaccepted qualifiers produce an error. Some of the accepted qualifiers are:
requires
¶YYSTYPE
and YYLTYPE
in C). In other words,
it’s the best place to define types referenced in %union
directives.
In C, if you use #define
to override Bison’s default YYSTYPE
and YYLTYPE
definitions, then it is also the best place. However you
should rather %define
api.value.type
and
api.location.type
.
YYSTYPE
and YYLTYPE
in C).
provides
¶YYSTYPE
and YYLTYPE
in C), and token definitions.
top
¶%code
or %code requires
should usually be more appropriate than %code top
. However,
occasionally it is necessary to insert code much nearer the top of the
parser implementation file. For example:
%code top { #define _GNU_SOURCE #include <stdio.h> }
imports
¶Though we say the insertion locations are language-dependent, they are technically skeleton-dependent. Writers of non-standard skeletons however should choose their locations consistently with the behavior of the standard Bison skeletons.
Previous: %define Summary, Up: Bison Declarations [Contents][Index]