practica 08 bison
TRANSCRIPT
PRACTICA 08 : ANALISIS SINTACTICA CON BISON
EJEMPLO 2: CALCULADORA DE SUMAS Y RESTAS.
%{#include "calculadora.tab.h"%}NUM [0-9]+
%%
{NUM} { yylval = atoi(yytext);return (ENTERO); }
"+"|"-" { return (yytext[0]); }"\n" { return (yytext[0]); }. ;%%
Calculadora.l
Calculadora.y
%{#define YYSTYPE int#include <math.h>#include <stdio.h>%}
/* Declaraciones de BISON*/%token ENTERO%left '-' '+'
/* Gramatica*/%%
input : /*Cadena Vacia*/| input line
;line : '\n'
| exp '\n' { printf ("\t%d\n", $1); };exp : ENTERO { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }| exp '-' exp { $$ = $1 - $3; }
;
%%
int main() {yyparse();
}
yyerror (char *s) {printf ("%s\n", s);
}
int yywrap() {return 1;
}
Las pruebas del programa se ven en la captura siguiente:
EJEMPLO 3: CALCULADORA CON EXPRESIONES ARITMETICAS COMPLEJAS
Ejemplo3.l
%{#include "ejemplo3.tab.h"#include <stdlib.h>#include <stdio.h>%}white [ \t]+digit [0-9]integer {digit}+%%{white} { /* Ignoramos espacios en blanco */ }"exit"|"quit"|"bye" {printf("Terminando programa\n");exit(0);}{integer} {
yylval.dval=atof(yytext);return(NUMBER);}
"+" return(SUMA);"-" return(RESTA);"*" return(MULTI);"/" return(DIVIDE);"^" return(EXPO);"(" return(IZQ_PAREN);")" return(DERE_PAREN);"\n" return(END);%%
Ejemplo3.y
%{#include <stdio.h>#include <math.h>%}%union {
double dval;}%token <dval> NUMBER%token SUMA RESTA MULTI DIVIDE EXPO%token IZQ_PAREN DERE_PAREN%token END%left SUMA RESTA%left MULTI DIVIDE%left NEG%right EXPO%type <dval> Expression%start Input%%Input : Line
| Input Line;Line : END
| Expression END { printf("Result: %f\n",$1); };Expression : NUMBER { $$=$1; }
| Expression SUMA Expression { $$=$1+$3; }| Expression RESTA Expression { $$=$1-$3; }| Expression MULTI Expression { $$=$1*$3; }| Expression DIVIDE Expression { $$=$1/$3; }| RESTA Expression %prec NEG { $$=-$2; }| Expression EXPO Expression { $$=pow($1,$3); }| IZQ_PAREN Expression DERE_PAREN { $$=$2; }
;%%int yyerror(char *s) {
printf("%s\n",s);}int main(void) {
yyparse();}
Las pruebas del programa se ven en la captura siguiente: