Research portable Memory game | Исследовать портируемую игру Память
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

194 lines
4.8KB

  1. from Function import *
  2. def includes():
  3. return """#include <map>
  4. #include <string>
  5. #include <vector>
  6. #include "cli.h"
  7. #include "cli_Context.h"
  8. #include "memory.h"
  9. #include "memory_Context.h"
  10. #include "shell.h"
  11. """
  12. def replaceAnd(s):
  13. return s.replace(" and", " &&")
  14. def replaceAppend(s):
  15. return s.replace(".append(", ".push_back(")
  16. def replaceComment(s):
  17. return s.replace("#", "//")
  18. def replaceLen(s):
  19. posLen = s.find("len(")
  20. posEnd = s.find(")", posLen)
  21. if (
  22. posLen == -1 or
  23. posEnd == -1
  24. ):
  25. return s
  26. before = s[:posLen]
  27. name = s[posLen + len("len("):posEnd]
  28. after = s[posEnd + len(")"):]
  29. return f"{before}{name}.size(){after}"
  30. def replaceOr(s):
  31. return s.replace(" or", " ||")
  32. def replaceTrue(s):
  33. return s.replace("True", "true")
  34. def translateParameter(s):
  35. # name: type -> type name
  36. parts = s.split(": ")
  37. indent = len(s) - len(s.lstrip())
  38. name = parts[0].lstrip()
  39. t = translateType(parts[1])
  40. indentation = "".join(" " * indent)
  41. return f"{indentation}{t} {name}"
  42. def translateStatement(s, state):
  43. indent = len(s) - len(s.lstrip())
  44. indentation = "".join(" " * indent)
  45. ss = s.lstrip()
  46. posColon = ss.find(": ")
  47. posComma = ss.find(", ")
  48. posComment = ss.find("# ")
  49. posCtx = ss.find("c.")
  50. posEqual = ss.find(" = ")
  51. posFor = ss.find("for ")
  52. posIn = ss.find(" in ")
  53. posRange = ss.find("range(")
  54. posRangeEnd = ss.find("):")
  55. posClosingScope = ss.find("#}")
  56. posOpenSquareBracket = ss.find("[")
  57. # # -> //
  58. if posComment != -1:
  59. return replaceComment(s)
  60. # #} -> }
  61. if posClosingScope != -1:
  62. return f"{indentation}}}"
  63. # for name in range(x, y): -> for (auto name = x; name < y; ++name) {
  64. if (
  65. posFor >= 0 and
  66. posIn >= 0 and
  67. posRange >= 0
  68. ):
  69. name = ss[posFor + len("for "):posIn]
  70. x = ss[posRange + len("range("):posComma]
  71. y = ss[posComma + len(", "):posRangeEnd]
  72. return f"{indentation}for (auto {name} = {x}; {name} < {y}; ++{name}) {{"
  73. # name: type = value -> type name = value
  74. if (
  75. posColon >= 0 and
  76. posEqual >= 0
  77. ):
  78. name = ss[:posColon]
  79. type = ss[posColon + len(": "):posEqual]
  80. t = translateType(type)
  81. value = ss[posEqual + len(" = "):]
  82. return f"{indentation}{t} {name} = {value};"
  83. # name = value -> auto name = value
  84. if (
  85. posCtx == -1 and
  86. posColon == -1 and
  87. posOpenSquareBracket == -1 and
  88. posEqual >= 0
  89. ):
  90. name = ss[:posEqual]
  91. # Skip prepending 'auto' each time variable is assigned,
  92. # only do it the first time
  93. if name not in state.varNames:
  94. state.varNames[name] = True
  95. value = ss[posEqual + len(" = "):]
  96. return f"{indentation}auto {name} = {value};"
  97. # Keep "if ("
  98. if ss == "if (":
  99. state.isIf = True
  100. return s
  101. # Keep "if not ("
  102. if ss == "if not (":
  103. state.isIfNot = True
  104. return f"{indentation}if (!("
  105. # ): -> }
  106. if ss == "):":
  107. # if
  108. if state.isIf:
  109. state.isIf = False
  110. return f"{indentation}) {{"
  111. # if not
  112. state.isIfNot = False
  113. return f"{indentation})) {{"
  114. ending = ";"
  115. if state.isIf or state.isIfNot:
  116. ending = ""
  117. # Unknown.
  118. return f"{s}{ending}"
  119. def translateType(s):
  120. # dict[X, Y] -> std::map<X, Y>
  121. if s.startswith("dict["):
  122. kv = s[len("dict["):-len("]")]
  123. parts = kv.split(", ")
  124. return f"std::map<{parts[0]}, {parts[1]}>"
  125. # str -> std::string
  126. if s == "str":
  127. return "std::string"
  128. # Unknown. Return as is.
  129. return s
  130. class CPP:
  131. def __init__(self, fn):
  132. self.fn = fn
  133. self.isIf = False
  134. self.isIfNot = False
  135. self.varNames = {}
  136. def translate(self):
  137. returnType = translateType(self.fn.returnType)
  138. # Parameters.
  139. params = []
  140. for i in range(0, len(self.fn.parameters)):
  141. p = translateParameter(self.fn.parameters[i])
  142. # Make Context passed by reference.
  143. #if "Context" in p:
  144. # p = p.replace("Context", "Context&")
  145. params.append(p)
  146. strparams = "\n".join(params)
  147. if (len(strparams) > 0):
  148. strparams += "\n"
  149. # Statements.
  150. sts = []
  151. for i in range(0, len(self.fn.statements)):
  152. s = translateStatement(self.fn.statements[i], self)
  153. s = replaceAnd(s)
  154. s = replaceOr(s)
  155. s = replaceAppend(s)
  156. # Replace len twice to account for double invocation.
  157. s = replaceLen(s)
  158. s = replaceLen(s)
  159. s = replaceTrue(s)
  160. sts.append(s)
  161. strstatements = "\n".join(sts)
  162. return f"""{returnType} {self.fn.name}(
  163. {strparams}) {{
  164. {strstatements}
  165. }}
  166. """