You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

antlr.g 619 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. class CalcParser extends Parser;
  2. options {
  3. buildAST = true; // uses CommonAST by default
  4. }
  5. expr
  6. : mexpr (PLUS^ mexpr)* SEMI!
  7. ;
  8. mexpr
  9. : atom (STAR^ atom)*
  10. ;
  11. atom: INT
  12. ;
  13. class CalcLexer extends Lexer;
  14. WS : (' '
  15. | '\t'
  16. | '\n'
  17. | '\r')
  18. { _ttype = Token.SKIP; }
  19. ;
  20. LPAREN: '('
  21. ;
  22. RPAREN: ')'
  23. ;
  24. STAR: '*'
  25. ;
  26. PLUS: '+'
  27. ;
  28. SEMI: ';'
  29. ;
  30. protected
  31. DIGIT
  32. : '0'..'9'
  33. ;
  34. INT : (DIGIT)+
  35. ;
  36. class CalcTreeWalker extends TreeParser;
  37. expr returns [float r]
  38. {
  39. float a,b;
  40. r=0;
  41. }
  42. : #(PLUS a=expr b=expr) {r = a+b;}
  43. | #(STAR a=expr b=expr) {r = a*b;}
  44. | i:INT {r = (float)Integer.parseInt(i.getText());}
  45. ;