/vendor/peg/examples/dcv.peg

http://github.com/feyeleanor/RubyGoLightly · Unknown · 34 lines · 26 code · 8 blank · 0 comment · 0 complexity · 87b31f461d5060c1e620b154e5b65ef9 MD5 · raw file

  1. # Grammar
  2. Stmt <- SPACE Expr EOL { printf("%d\n", pop()); }
  3. / (!EOL .)* EOL { printf("error\n"); }
  4. Expr <- ID { var= yytext[0] } ASSIGN Sum { vars[var - 'a']= top(); }
  5. / Sum
  6. Sum <- Product ( PLUS Product { int r= pop(), l= pop(); push(l + r); }
  7. / MINUS Product { int r= pop(), l= pop(); push(l - r); }
  8. )*
  9. Product <- Value ( TIMES Value { int r= pop(), l= pop(); push(l * r); }
  10. / DIVIDE Value { int r= pop(), l= pop(); push(l / r); }
  11. )*
  12. Value <- NUMBER { push(atoi(yytext)); }
  13. / < ID > !ASSIGN { push(vars[yytext[0] - 'a']); }
  14. / OPEN Expr CLOSE
  15. # Lexemes
  16. NUMBER <- < [0-9]+ > SPACE
  17. ID <- < [a-z] > SPACE
  18. ASSIGN <- '=' SPACE
  19. PLUS <- '+' SPACE
  20. MINUS <- '-' SPACE
  21. TIMES <- '*' SPACE
  22. DIVIDE <- '/' SPACE
  23. OPEN <- '(' SPACE
  24. CLOSE <- ')' SPACE
  25. SPACE <- [ \t]*
  26. EOL <- '\n' / '\r\n' / '\r' / ';'