title: unclear how to add extra productions to bison grammar to create error messages
body: <p>This is not homework, but it is from a book.</p>
  
  <p>I'm given a following <code>bison</code> spec file:</p>
  
  <pre><code>%{
  #include &lt;stdio.h&gt;
  #include &lt;ctype.h&gt;
  
  int yylex();
  int yyerror();
  %}
  
  %token NUMBER
  
  %%
  
  command : exp { printf("%d\n", $1); }
          ; /* allows printing of the result */
  
  exp : exp '+' term { $$ = $1 + $3; }
      | exp '-' term { $$ = $1 - $3; }
      | term { $$ = $1; }
      ;
  
  term : term '*' factor { $$ = $1 * $3; }
       | factor { $$ = $1; }
       ;
  
  factor : NUMBER { $$ = $1; }
         | '(' exp ')' { $$ = $2; }
         ;
  
  %%
  
  int main() {
    return yyparse();
  }
  
  int yylex() {
    int c;
  
    /* eliminate blanks*/
    while((c = getchar()) == ' ');
  
    if (isdigit(c)) {
      ungetc(c, stdin);
      scanf("%d", &amp;yylval);
      return (NUMBER);
    }
  
    /* makes the parse stop */
    if (c == '\n') return 0;
  
    return (c);
  }
  
  int yyerror(char * s) {
    fprintf(stderr, "%s\n", s);
    return 0;
  } /* allows for printing of an error message */
  </code></pre>
  
  <p>The task is to do the following:</p>
  
  <blockquote>
    <p>Rewrite the spec to add the following useful error messages: 
    <br/>"missing right parenthesis," generated by the string <strong>(2+3</strong> 
    <br/>"missing left parenthesis," generated by the string <strong>2+3)</strong> 
    <br/>"missing operator," generated by the string <strong>2 3</strong> 
    <br/>"missing operand," generated by the string <strong>(2+)</strong></p>
  </blockquote>
  
  <p>The simplest solution that I was able to come up with is to do the following:</p>
  
  <pre><code>half_exp : exp '+' { $$ = $1; }
           | exp '-' { $$ = $1; }
           | exp '*' { $$ = $1; }
           ;
  
  
  factor : NUMBER { $$ = $1; }
         | '(' exp '\n' { yyerror("missing right parenthesis"); }
         |  exp ')' { yyerror("missing left parenthesis"); }
         | '(' exp '\n' { yyerror("missing left parenthesis"); }
         | '(' exp ')' { $$ = $2; }
         | '(' half_exp ')' { yyerror("missing operand"); exit(0); }
         ;
  
  exp : exp '+' term { $$ = $1 + $3; }
      | exp '-' term { $$ = $1 - $3; }
      | term { $$ = $1; }
      | exp exp { yyerror("missing operator"); }
      ;
  </code></pre>
  
  <p>These changes work, however they lead to a lot of conflicts.</p>
  
  <p>Here is my question. </p>
  
  <p>Is there a way to rewrite this grammar in such a way so that it wouldn't generate conflicts? </p>
  
  <p>Any help is appreciated.</p>