/* Compilation d'expressions arithme'tiques on genere le code correspond au nombre minimal de registres a utiliser avec exo1.lex qui reconnait les differents terminaux PARO PARF: parentheses, MULT PLUS multiplication addition, MOINS DIV soustraction division (non utilisés ici), EGAL egalite (non utilisés ici), POINTV point virgule, ID identificateur */ %{ struct info { char *expr; int nbRegistres; }; trans (char *u){ /* ajoute 1 a tous les numeros de registres */ int i; for (i = 0; u[i] != '\0'; i++) if(isdigit(u[i])) u[i]++; } #define LMAX 1000 #define YYSTYPE struct info %} %token NUMBER PLUS POINTV MULT PARO PARF ID EGAL MOINS DIV %% statement : expression POINTV { printf("\n%s\n", $1.expr); printf("Nombre de registres nécessaires : %d\n", $1.nbRegistres); } ; expression : expression PLUS terme { if ($1.nbRegistres < $3.nbRegistres) { trans($1.expr); strcat(strcat($3.expr, $1.expr), "add R1 R2\n") ; $$ = $3; } else if ($1.nbRegistres > $3.nbRegistres) { trans($3.expr); strcat(strcat($1.expr, $3.expr), "add R1 R2\n") ; $$ = $1; } else { trans($3.expr); strcat(strcat($1.expr, $3.expr), "add R1 R2\n") ; $$ = $1; $$.nbRegistres++; } } | terme { $$ = $1; } ; terme : terme MULT facteur { if ($1.nbRegistres < $3.nbRegistres) { trans($1.expr); strcat(strcat($3.expr, $1.expr), "mult R1 R2\n") ; $$ = $3; } else if ($1.nbRegistres > $3.nbRegistres) { trans($3.expr); strcat(strcat($1.expr, $3.expr), "mult R1 R2\n") ; $$ = $1; } else { trans($3.expr); strcat(strcat($1.expr, $3.expr), "add R1 R2\n") ; $$ = $1; $$.nbRegistres++; } } | facteur { $$ = $1; } ; facteur : ID { $$.expr = (char *) malloc(LMAX); strcpy($$.expr,"load "); strcat($$.expr, $1.expr); strcat($$.expr ," R1 \n"); $$.nbRegistres = 1; } | PARO expression PARF { $$ = $2; } ; %% #include "lex.yy.c" main() { yyparse(); } yyerror(char *s) { printf ("%s\n",s); }