calc.y 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. %{
  2. #include <ctype.h>
  3. int regs[26];
  4. int base;
  5. int val;
  6. int printflag;
  7. %}
  8. %start stmt
  9. %token DIGIT LETTER EXIT
  10. %left '|'
  11. %left '&'
  12. %left '+' '-'
  13. %left '*' '/' '%'
  14. %left UMINUS
  15. %%
  16. stmt : expr
  17. { val = $1; printflag = 1; }
  18. | LETTER '=' expr
  19. { regs[$1] = $3; }
  20. | EXIT
  21. { exit(0); }
  22. ;
  23. expr : '(' expr ')'
  24. { $$ = $2; }
  25. | expr '+' expr
  26. { if ($1 == 69)
  27. {
  28. $$ = 2;
  29. printf ("$1 became %d\n", $1);
  30. $1 = 69;
  31. }
  32. $$ = $1 + $3; }
  33. | expr '-' expr
  34. { $$ = $1 - $3; }
  35. | expr '*' expr
  36. { $$ = $1 * $3; }
  37. | expr '/' expr
  38. { $$ = $1 / $3; }
  39. | expr '%' expr
  40. { $$ = $1 % $3; }
  41. | expr '|' expr
  42. { $$ = $1 | $3; }
  43. | expr '&' expr
  44. { $$ = $1 & $3; }
  45. | '-' expr %prec UMINUS
  46. { $$ = - $2; }
  47. | LETTER
  48. { $$ = regs[$1]; }
  49. | number
  50. /* | '?'
  51. { yydebug = !yydebug; }
  52. */ ;
  53. number : DIGIT
  54. { $$ = $1; base = ($1 == 0) ? 8 : 10; }
  55. | number DIGIT
  56. { $$ = base * $1 + $2; }
  57. ;
  58. %%
  59. static int eol;
  60. int
  61. yylex()
  62. {
  63. int c;
  64. while ( (c=getchar()) == ' ') {}
  65. if (c == '\n')
  66. { eol = 1;
  67. return 0; }
  68. if (c == 'Q' || c == EOF)
  69. return(EXIT);
  70. if (islower(c))
  71. {
  72. yylval = c - 'a';
  73. return (LETTER);
  74. }
  75. if (isdigit(c))
  76. {
  77. yylval = c - '0';
  78. return (DIGIT);
  79. }
  80. return (c);
  81. }
  82. yyerror(s)
  83. char *s;
  84. {
  85. printf("%s\n", s);
  86. }
  87. main()
  88. {
  89. for (;;)
  90. {
  91. eol = 0;
  92. printflag = 0;
  93. if (yyparse()) printflag = 0;
  94. if (printflag) printf("%d\n", val);
  95. while (!eol)
  96. if (yylex() == EOF)
  97. exit(0);
  98. }
  99. }