eval.y 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* -- eval.y --
  2. Evaluation d'une expression
  3. Partie analyseur grammatical.
  4. Utilisation : bison eval.y */
  5. %{
  6. #include <stdio.h>
  7. /* Pré-déclarations */
  8. int yylex (void);
  9. void yyerror (const char *);
  10. /* Variable définie dans un autre fichier */
  11. extern char* yytext;
  12. %}
  13. %defines /* Génère le fichier en-tête eval.tab.h */
  14. %token nombre
  15. %start EXPR_CALCS /* Axiome de la grammaire */
  16. %%
  17. EXPR_CALCS : EXPR_CALC
  18. | EXPR_CALCS EXPR_CALC
  19. ;
  20. EXPR_CALC : EXPR '=' { printf("%d\n", $1); }
  21. ;
  22. EXPR : FACTEUR
  23. | EXPR '+' FACTEUR {$$ = $1 + $3;}
  24. | EXPR '-' FACTEUR {$$ = $1 - $3;}
  25. ;
  26. FACTEUR : nombre {$$ = $1;}
  27. | '(' EXPR ')' {$$ = $2;}
  28. ;
  29. %%
  30. #include <stdio.h>
  31. #include "eval.tab.h"
  32. void yyerror (const char * error)
  33. {
  34. fprintf (stderr, "Erreur: %s sur l'expression %s\n", error, yytext);
  35. }
  36. int main() {
  37. if ( yyparse() != 0 ) {
  38. fprintf(stderr,"Syntaxe incorrecte\n"); return 1; }
  39. else
  40. return 0;
  41. }