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


3.7.7 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, yyoutput denotes the output stream (a FILE* in C, and an std::ostream& in C++), $$ (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
%type  <string> string1 string2
%union { char character; }
%token <character> CHR
%type  <character> chr
%token TAGLESS

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

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 also


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