Next: , Previous: , Up: Bison Declarations   [Contents][Index]


3.7.8 Printing Semantic Values

When run-time traces are enabled (see Tracing Your Parser), the parser reports its actions, such as reductions. When a symbol involved in an action is reported, only its kind is displayed, as the parser cannot know how semantic values should be formatted.

The %printer directive defines code that is called when a symbol is reported. Its syntax is the same as %destructor (see Freeing Discarded Symbols).

Directive: %printer { code } symbols

Invoke the braced code whenever the parser displays one of the symbols. Within code, yyo denotes the output stream (a FILE* in C, an std::ostream& in C++, and stdout in D), $$ (or $<tag>$) designates the semantic value associated with the symbol, and @$ its location. The additional parser parameters are also available (see The Parser Function yyparse).

The symbols are defined as for %destructor (see Freeing Discarded Symbols.): they can be per-type (e.g., ‘<ival>’), per-symbol (e.g., ‘exp’, ‘NUM’, ‘"float"’), typed per-default (i.e., ‘<*>’, or untyped per-default (i.e., ‘<>’).

For example:

%union { char *string; }
%token <string> STRING1 STRING2
%nterm <string> string1 string2
%union { char character; }
%token <character> CHR
%nterm <character> chr
%token TAGLESS

%printer { fprintf (yyo, "'%c'", $$); } <character>
%printer { fprintf (yyo, "&%p", $$); } <*>
%printer { fprintf (yyo, "\"%s\"", $$); } STRING1 string1
%printer { fprintf (yyo, "<>"); } <>

guarantees that, when the parser print any symbol that has a semantic type tag other than <character>, it display the address of the semantic value by default. However, when the parser displays a STRING1 or a string1, it formats it as a string in double quotes. It performs only the second %printer in this case, so it prints only once. Finally, the parser print ‘<>’ for any symbol, such as TAGLESS, that has no semantic type tag. See Enabling Debug Traces for mfcalc, for a complete example.


Next: Suppressing Conflict Warnings, Previous: Freeing Discarded Symbols, Up: Bison Declarations   [Contents][Index]