Implemente um analisador sintáctico para reconhecimento duma expressão aritmética, utilizando o bison. A gramática é a seguinte:
S → ID '=' E | E
E → E '+' E | E '-' E | E '*' E | E '/' E | '-' E | ( E ) | ID | INT | REAL
onde ID é um identificador (letra de 'a' a 'z'), INT um número inteiro e REAL um número real.
O parser deve analisar múltiplas expressões e obter resultados, apresentando-os. Sempre que haja uma atribuição esse valor deve ser guardado para ser utilizado com o identificador
respectivo.
Para se implementar o parser no bison é necessário rescrever a gramática para obedecer às precedências entre os operadores..
S → ID '=' E
S → E
E → E '+' T
E → E '-' T
E → T
T → T '*' F
T → T '/' F
T → F
F → '-' F
F → '(' E ')'
F → ID
F → INT
F → REAL
%{ #include"exercicio8.tab.h" #include<math.h> extern double tabelasimb[26]; %} digito [0-9] letra [A-Za-z] %% [ \t]+ <<EOF>> return 0; {digito}+ yylval.valint=atoi(yytext);return INT; ({digito}*\.)?{digito}+([eE][-+]?{digito}+)? yylval.valreal=atof(yytext);return REAL; [a-z] yylval.valint= yytext[0] - 'a'; return ID; "("|")"|"+"|"-"|"*"|"/"|"="|\n return yytext[0]; [a-z]{2,}|. printf("erro lexico: %s\n",yytext); %% int yywrap () { }
%{ double tabelasimb[26]; %} %union { double valreal; int valint; } %left '+' '-' %left '*' '/' %nonassoc UMENOS %token <valint> INT ID %token <valreal> REAL %type <valreal> termo %% calculadora: /* vazio */ | calculadora expressao '\n' ; expressao: termo {printf("resultado %f\n", $1);} | ID '=' termo {printf("guardado %f\n", $3); tabelasimb[$1]=$3; } ; termo: termo '+' termo {$$=$1+$3;} | termo '-' termo {$$=$1-$3;} | termo '*' termo {$$=$1*$3;} | termo '/' termo {if ($3==0) yyerror("divisao por zero"); else $$=$1/$3; } | '-' termo %prec UMENOS {$$=-$2;} | '(' termo ')' {$$=$2;} | REAL {$$=$1;} | INT {$$=$1;} | ID {$$=tabelasimb[$1];} ; %% void main(){ yyparse(); } int yyerror(char *s){ printf("erro sintatico/semantico: %s\n",s); }
Ultima alteração: quinta-feira, 30 de Novembro de 2000 às 23:01