Михаил Капелько 8 months ago
parent
commit
6ef6829fd3
2 changed files with 48 additions and 16 deletions
  1. +43
    -6
      tr-Python-C++/CPP.py
  2. +5
    -10
      tr-Python-C++/process.py

+ 43
- 6
tr-Python-C++/CPP.py View File

@@ -1,5 +1,21 @@
from Function import *

def replaceAnd(s):
return s.replace("and", "&&")

def replaceLen(s):
posLen = s.find("len(")
posEnd = s.find(")")
if (
posLen == -1 or
posEnd == -1
):
return s
before = s[:posLen]
name = s[posLen + len("len("):posEnd]
after = s[posEnd + len(")"):]
return f"{before}{name}.size(){after}"

def translateParameter(s):
# name: type -> type name
parts = s.split(": ")
@@ -9,7 +25,7 @@ def translateParameter(s):
indentation = "".join(" " * indent)
return f"{indentation}{t} {name}"

def translateStatement(s):
def translateStatement(s, state):
indent = len(s) - len(s.lstrip())
indentation = "".join(" " * indent)
ss = s.lstrip()
@@ -59,8 +75,22 @@ def translateStatement(s):
value = ss[posEqual + len(" = "):]
return f"{indentation}auto {name} = {value};"

# Unknown. Return with semicolon at the end.
return f"{s};"
# Keep "if ("
if ss == "if (":
state.isIf = True
return s

# ): -> }
if ss == "):":
state.isIf = False
return f"{indentation}) {{"

ending = ";"
if state.isIf:
ending = ""

# Unknown.
return f"{s}{ending}"

def translateType(s):
# dict[X, Y] -> std::map<X, Y>
@@ -68,6 +98,9 @@ def translateType(s):
kv = s[len("dict["):-len("]")]
parts = kv.split(", ")
return f"std::map<{parts[0]}, {parts[1]}>"
# str -> std::string
if s == "str":
return "std::string"

# Unknown. Return as is.
return s
@@ -75,6 +108,7 @@ def translateType(s):
class CPP:
def __init__(self, fn):
self.fn = fn
self.isIf = False

def translate(self):
returnType = translateType(self.fn.returnType)
@@ -85,17 +119,20 @@ class CPP:
p = translateParameter(self.fn.parameters[i])
params.append(p)
strparams = "\n".join(params)
if (len(strparams) > 0):
strparams += "\n"

# Statements.
sts = []
for i in range(0, len(self.fn.statements)):
s = translateStatement(self.fn.statements[i])
s = translateStatement(self.fn.statements[i], self)
s = replaceAnd(s)
s = replaceLen(s)
sts.append(s)
strstatements = "\n".join(sts)

return f"""{returnType} {self.fn.name}(
{strparams}
) {{
{strparams}) {{
{strstatements}
}}
"""


+ 5
- 10
tr-Python-C++/process.py View File

@@ -13,17 +13,12 @@ def process(FILE_IN):
# Parse.
for ln in lines_in:
ln = ln.rstrip()

# Ignore includes.
if "#include" in ln:
continue

f.parseLine(ln)
if f.isComplete:
print("Function ready!")
break
print("Function ready! Here it is in C++:")
cpp = CPP(f)
print(cpp.translate())
# Create new function instance.
f = Function()

print(f"Debug: {f}")

cpp = CPP(f)
return cpp.translate()

Loading…
Cancel
Save