|
|
@@ -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} |
|
|
|
}} |
|
|
|
""" |
|
|
|