calc.leg 800 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. %{
  2. #include <stdio.h>
  3. int vars[26];
  4. %}
  5. Stmt = - e:Expr EOL { printf("%d\n", e); }
  6. | ( !EOL . )* EOL { printf("error\n"); }
  7. Expr = i:ID ASSIGN s:Sum { $$= vars[i]= s; }
  8. | s:Sum { $$= s; }
  9. Sum = l:Product
  10. ( PLUS r:Product { l += r; }
  11. | MINUS r:Product { l -= r; }
  12. )* { $$= l; }
  13. Product = l:Value
  14. ( TIMES r:Value { l *= r; }
  15. | DIVIDE r:Value { l /= r; }
  16. )* { $$= l; }
  17. Value = i:NUMBER { $$= atoi(yytext); }
  18. | i:ID !ASSIGN { $$= vars[i]; }
  19. | OPEN i:Expr CLOSE { $$= i; }
  20. NUMBER = < [0-9]+ > - { $$= atoi(yytext); }
  21. ID = < [a-z] > - { $$= yytext[0] - 'a'; }
  22. ASSIGN = '=' -
  23. PLUS = '+' -
  24. MINUS = '-' -
  25. TIMES = '*' -
  26. DIVIDE = '/' -
  27. OPEN = '(' -
  28. CLOSE = ')' -
  29. - = [ \t]*
  30. EOL = '\n' | '\r\n' | '\r' | ';'
  31. %%
  32. int main()
  33. {
  34. while (yyparse());
  35. return 0;
  36. }