arro.plcc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. skip WHITESPACE '\s+'
  2. token NUM '[0-9]+'
  3. token VAR '[A-Za-z_][A-Za-z0-9_]*'
  4. token OP '\+|-'
  5. token MOP '\*|/'
  6. token IN '==>'
  7. token OUT '<=='
  8. token ASSIGN '->'
  9. token SEMI ';'
  10. %
  11. <program> ::= <stmtlist>
  12. <stmtlist> **= <stmt>
  13. <stmt>InputStmt ::= <IN> <VAR> <SEMI>
  14. <stmt>OutputStmt ::= <OUT> <exp> <SEMI>
  15. <stmt>AssignStmt ::= <VAR> <ASSIGN> <exp> <SEMI>
  16. <exp> ::= <mult> <exprest>
  17. <exprest> **= <OP> <mult>
  18. <mult> ::= <value> <multrest>
  19. <multrest> **= <MOP> <value>
  20. <value>NUMValue ::= <NUM>
  21. <value>VARValue ::= <VAR>
  22. %
  23. Program:import
  24. %%%
  25. import java.util.*;
  26. %%%
  27. Program
  28. %%%
  29. public static Map<String, Integer> hshmap = new HashMap<>();
  30. public static Scanner scanner = new Scanner(System.in);
  31. public void $run() { stmtlist.execute(); }
  32. %%%
  33. Stmtlist
  34. %%%
  35. public void execute() {
  36. for (Stmt s : stmtList) s.execute();
  37. }
  38. %%%
  39. Stmt
  40. %%%
  41. abstract public void execute();
  42. %%%
  43. InputStmt
  44. %%%
  45. public void execute() {
  46. System.out.print("? ");
  47. Program.hshmap.put(var.toString(), Program.scanner.nextInt());
  48. }
  49. %%%
  50. OutputStmt
  51. %%%
  52. public void execute() { System.out.println(exp.compute()); }
  53. %%%
  54. AssignStmt
  55. %%%
  56. public void execute() { Program.hshmap.put(var.toString(), exp.compute()); }
  57. %%%
  58. Exp
  59. %%%
  60. public int compute() {
  61. int v = mult.compute();
  62. for (int i = 0; i < exprest.opList.size(); i++)
  63. v += exprest.opList.get(i).toString().equals("+")
  64. ? exprest.multList.get(i).compute()
  65. : -exprest.multList.get(i).compute();
  66. return v;
  67. }
  68. %%%
  69. Mult
  70. %%%
  71. public int compute() {
  72. int v = value.compute();
  73. for (int i = 0; i < multrest.mopList.size(); i++)
  74. v = multrest.mopList.get(i).toString().equals("*")
  75. ? v * multrest.valueList.get(i).compute()
  76. : v / multrest.valueList.get(i).compute();
  77. return v;
  78. }
  79. %%%
  80. Value
  81. %%%
  82. abstract public int compute();
  83. %%%
  84. NUMValue
  85. %%%
  86. public int compute() { return Integer.parseInt(num.toString()); }
  87. %%%
  88. VARValue
  89. %%%
  90. public int compute() {
  91. if (!Program.hshmap.containsKey(var.toString()))
  92. throw new RuntimeException("Undefined variable: " + var);
  93. return Program.hshmap.get(var.toString());
  94. }
  95. %%%