Guest User

Untitled

a guest
Feb 21st, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import std.stdio;
  2.  
  3. struct Token
  4. {
  5. string name;
  6. int type;
  7. }
  8.  
  9. class Node {}
  10.  
  11. class NumNode : Node
  12. {
  13. public:
  14. string v;
  15. this (string v)
  16. {
  17. this.v = v;
  18. }
  19. override string toString()
  20. {
  21. return this.v;
  22. }
  23. }
  24.  
  25. class OpNode : Node
  26. {
  27. public:
  28. string op;
  29. Node[] args;
  30. this (string op, Node[] args)
  31. {
  32. this.op = op;
  33. this.args = args;
  34. }
  35.  
  36. override string toString()
  37. {
  38. import std.array, std.algorithm, std.format, std.conv;
  39. return "(%s %s)".format(this.op, this.args.map!(to!string).join(" "));
  40. }
  41. }
  42.  
  43. import std.range;
  44. Node parseNum(ref Token[] tokens)
  45. {
  46. if (!tokens.empty && tokens.front.type == 0) {
  47. auto n = new NumNode(tokens.front.name);
  48. tokens.popFront();
  49. return n;
  50. }
  51. return null;
  52. }
  53.  
  54. Node parseMul(ref Token[] tokens)
  55. {
  56. Node left = tokens.parseNum();
  57. if (left is null) { return null; }
  58.  
  59. while (! tokens.empty()) {
  60. if (tokens.front.type != 1) { break; }
  61. auto op = tokens.front.name;
  62. tokens.popFront();
  63. auto right = tokens.parseNum();
  64. if (right is null) {
  65. writeln(left);
  66. throw new Exception("right hand operator is expected");
  67. }
  68. left = new OpNode(op, [left, right]);
  69. }
  70. return left;
  71. }
  72.  
  73. Node parseAdd(ref Token[] tokens)
  74. {
  75. Node left = tokens.parseMul();
  76. if (left is null) { return null; }
  77.  
  78. while (! tokens.empty()) {
  79. if (tokens.front.type != 2) { break; }
  80. auto op = tokens.front.name;
  81. tokens.popFront();
  82. auto right = tokens.parseMul();
  83. if (right is null) {
  84. throw new Exception("right hand operator is expected");
  85. }
  86. left = new OpNode(op, [left, right]);
  87. }
  88. return left;
  89. }
  90.  
  91. void main()
  92. {
  93. auto input = [Token("1", 0), Token("+", 2), Token("2", 0), Token("+", 2), Token("3", 0)];
  94. writeln(parseAdd(input));
  95. }
Add Comment
Please, Sign In to add comment