] > Lexical and Semantics Information

9.3 Lexical and Semantics Information

<..expr.y..>
 %{
 int yylex();
 void yyerror( char * );
 %}
 
 %token NUM
 
 %%
 input:  expr ’\n’         { printf ("%d\n", $1); }
 ;
 expr:     expr ’+’ term   { $$ = $1 + $3; }
         | term
 ;
 term:     term ’*’ factor { $$ = $1 * $3; }
         | factor
 ;
 factor:   ’(’ expr ’)’    { $$ = $2; }
         | NUM
 ;
 %%
 int main ()
 {
    yyparse ();
    return 0;
 }
 
 int c = ’ ’;
 
 int yylex ()
 {
    while( c== ’ ’ )
    {
       c = getchar();
    }
    if( (c >= ’0’) && (c <= ’9’) )
    {
       yylval = 0;
       do
       {
          yylval = yylval * 10 + c - ’0’;
          c = getchar();
       }
       while ( (c >= ’0’) && (c <= ’9’) );
       return NUM;
     }
     if (c == EOF){ return 0; }
     int type = c;
     c = getchar();
     return type;
 }
 
 void yyerror(char * e)
 {
    printf ("--- Error --- %s\n", e);
 }
-_-_-