CalcCompYacc

De DCA-Wiki

%{
#include <stdio.h>
#include <math.h>

#define YYSTYPE double

  int lineno = 0;
%}

%token REAL
%token SIN COS TAN

%left '+' '-'
%left '*' '/'
%nonassoc UMINUS

%%
lines:  /* nothing */
      | lines line
      ;

line: '\n'
     | expr '\n' {printf("%lf\n", $1);}
     | error '\n'  {yyerror("line error");}
     ;

expr: REAL {
     | SIN '(' expr ')' {$$ = sin($3);}
     | COS '(' expr ')' {$$ = cos($3);}
     | TAN '(' expr ')' {$$ = tan($3);}
     | expr '+' expr  {$$ = $1 + $3;}
     | expr '-' expr  {$$ = $1 - $3;}
     | expr '*' expr  {$$ = $1 * $3;}
     | expr '/' expr  {if($3) $$ = $1 / $3; 
                       else {
                             yyerror("divide by zero");
                            }
		      }
     | '(' expr ')' {$$ = $2;}
     | '-' expr %prec UMINUS {$$ = - $2;}
     ;


%%
main()
{
yyparse();
}

yyerror(s)
char *s;
{
printf("calc: %s", s);
printf("line %d\n", lineno);
}
Ferramentas pessoais