title: How to print a parse tree using Bison?
body: <p>I have implemented a parser but it does not print anything. If the given input is syntactically wrong, it does not print "Error" though I included it in the <code>yyerror()</code> routine. Also if the input is correct, it does not print the Parse tree. What might be the possible reason for this? I have put my <code>main()</code> in <code>.lex</code> file instead of in <code>.y</code> file. Is that the possible reason for that?
  This is the main method:</p>
  
  <pre><code>int main( argc, argv )
  int argc;
  char **argv;
  {
      ++argv, --argc; 
      if ( argc &gt; 0 )
      yyin = fopen( argv[0], "r" );
      else
      yyin = stdin;     
  
      yyparse();
  }
  </code></pre>
  
  <hr>
  
  <p>The grammar file is:</p>
  
  <pre><code>%{
  #include "parser.h"
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  %}
  
  %union {
    char* a_variable;
    tree* a_tree;
  }
  
  %start file
  %token &lt;a_variable&gt; TOKID TOKSEMICOLON TOLCOLON TOKCOMMA TOKUNRECOG TOKDOT TOKMINUS TOKCOLON
  %type &lt;a_tree&gt; field file obj ID
  %right TOKMINUS
  
  %%
  
  file      :     /*empty*/ { return NULL; }
        |     field file { printtree($1, 1);  }
    ;
  
  field     : ID TOKCOLON field {$$ = make_op($1, ':', $3); }
    | ID TOKCOMMA field {$$ = make_op($1, ',', $3); }
    | obj { $$ = $1; }
    ;
  
  obj       :     ID TOKSEMICOLON { $$ = make_op($1, ';', NULL); }
        ;
  
  ID        :     TOKID { $$ = $1; }
  
  %%
  
  #include &lt;stdio.h&gt;
  yyerror(char *str)
  {
    fprintf(stderr,"error FAIL: %s\n",str);
  }
  
  int yywrap()
  {
    return 1;
  }
  </code></pre>
  
  <hr>
  
  <p>This is how my <code>.lex</code> file looks:</p>
  
  <pre><code>%{
  /* need this for the call to atof() below */
  #include &lt;math.h&gt;
  #include "parser.h"
  #include "idf.tab.h"
  %}
  
  DIGIT    [0-9]
  ID       [a-zA-Z]*
  %option noyywrap
  
  %% 
  
  
  {ID} |  
  -?{DIGIT}+"."{DIGIT}* |    
  -?{DIGIT}+      { yylval.a_variable = findname(yytext); return TOKID; }
  
  ";"           return TOKSEMICOLON;
  ":"           return TOKCOLON;
  ","           return TOKCOMMA;
  "."           return TOKDOT;
  "-"           return TOKMINUS; 
  .           return TOKUNRECOG;
  %%
  
  int main( int argc, char** argv )
  {
  ++argv, --argc; 
  if ( argc &gt; 0 )
  yyin = fopen( argv[0], "r" );
  else
  yyin = stdin;
  
  yyparse();
  }
  </code></pre>