Practica 08 bison1. PRACTICA 08 : ANALISIS SINTACTICA CON BISON
EJEMPLO 2: CALCULADORA DE SUMAS Y RESTAS.
Calculadora.l
Calculadora.y
%{
#include "calculadora.tab.h"
%}
NUM [0-9]+
%%
{NUM} { yylval = atoi(yytext);
return (ENTERO); }
"+"|"-" { return (yytext[0]); }
"n" { return (yytext[0]); }
. ;
%%
%{
#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%dn", $1); }
;
exp : ENTERO { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
;
%%
int main() {
yyparse();
}
yyerror (char *s) {
printf ("%sn", s);
2. Las pruebas del programa se ven en la captura siguiente:
}
int yywrap() {
return 1;
}
3. 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
programan");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
4. | Expression END { printf("Result: %fn",$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("%sn",s);
}
int main(void) {
yyparse();
}
Las pruebas del programa se ven en la captura siguiente: