I'm learning Lex and Yacc and I'm tryng to do this exercise.
I've to implement a Yacc for a language formed by arithmetic expressions built starting from:
identifiers, numerical constants: natural numbers, the 4 arithmetic operations, exponent: **, the analytic functions: sin, cos, tan, brackets. The order of priority between the various operators is defined in this way: for arithmetic operations the usual order applies, the exponent has priority over the trigonometric functions which in turn have priority over the product. All operations are associative on the left, minus the exponent that associates on the right.
The analyzer must return the tree of the syntactic structure of the expression received at the input.
This is my Lex code:
%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
[ \t]+ ; // ignore all whitespace
[a-z]+ { return ID;}
[0-9]+ { yylval = atoi(yytext); return NUMBER;}
%%
and this is my Yacc:
%{
#include "lex.yy.c"
void yyerror(const char *str){
fprintf(stderr,"errore: %s\n",str);}
int yywrap() {return 1;}
int main() { yyparse();}
%}
/* DEF*/
%token NUMBER ID
%left '-' '+'
%left '*' '/'
%left 'sin' 'cos' 'tan'
%right '**'
%% /* RULES */
%%
E : T {
printf("Result = %d\n", $$);
return 0;
}
T:
T '+' T{$$=$1+$3; }
| T '-' T {$$=$1-$3; }
| T '*' T{$$=$1*$3; }
| T '/' T{$$=$1/$3; }
| '(' T ')' { $$ = $2; }
| T '**' T {$$=$1*$3; }
| 'sin' T
| 'cos' T
| 'tan' T
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%
int main() {
printf("Enter the expression\n");
yyparse();
}
/* For printing error messages */
int yyerror(char* s) {
printf("\nExpression is invalid\n");
}
I don't know how to calculate the trigonometric functions, I don't know if is correct how I handle priority between the various operators and the brackets.
Can somebody help me ? I'm just learning sorry for stupid errors