Михаил Капелько 7 months ago
parent
commit
fb1eb55faf
5 changed files with 171 additions and 2 deletions
  1. +5
    -2
      main.py
  2. +44
    -0
      tr-Python-C++/CPP.py
  3. +76
    -0
      tr-Python-C++/Function.py
  4. +29
    -0
      tr-Python-C++/process.py
  5. +17
    -0
      tr-Python-C++/translate

+ 5
- 2
main.py View File

@@ -3,7 +3,9 @@

# L4: Function.

def memory_generateConstPlayfield(n: int) -> dict[int, int]:
def memory_generateConstPlayfield(
n: int
) -> dict[int, int]:
idGroups: dict[int, int] = { }
id = 0
for gid in range(0, n):
@@ -17,7 +19,8 @@ def memory_generateConstPlayfield(n: int) -> dict[int, int]:

# L20: Test.

def test_memory_generateConstPlayfield() -> str:
def test_memory_generateConstPlayfield(
) -> str:
idGroups = memory_generateConstPlayfield(2)
if (
len(idGroups) == 4 and


+ 44
- 0
tr-Python-C++/CPP.py View File

@@ -0,0 +1,44 @@
from Function import *

def translateParameter(s):
# name: type -> type name
parts = s.split(": ")
indent = len(s) - len(s.lstrip())
name = parts[0].lstrip()
t = translateType(parts[1])
indentation = "".join(" " * indent)
return f"{indentation}{t} {name}"

def translateType(s):
# dict[X, Y] -> std::map<X, Y>
if s.startswith("dict["):
kv = s[len("dict["):-len("]")]
parts = kv.split(", ")
return f"std::map<{parts[0]}, {parts[1]}>"

# Unknown. Return as is.
return s

class CPP:
def __init__(self, fn):
self.fn = fn

def translate(self):
returnType = translateType(self.fn.returnType)
# Parameters.
params = []
for i in range(0, len(self.fn.parameters)):
p = translateParameter(self.fn.parameters[i])
params.append(p)
strparams = "\n".join(params)
# Statements.
sts = self.fn.statements
strstatements = "\n".join(sts)

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


+ 76
- 0
tr-Python-C++/Function.py View File

@@ -0,0 +1,76 @@
class Function:
def __init__(self):
self.isBody = False
self.isComplete = False
self.isSignature = False
self.name = None
self.parameters = []
self.returnType = None
self.statements = []

def parseLine(self, ln):
parts = ln.split(" ")
count = len(parts)
lastPart = parts[count - 1]

# Complete.
if (
self.isBody and
ln.startswith("#}")
):
self.isComplete = True

# Statements.
if (
self.isBody and
not ln.startswith("#}")
):
self.statements.append(ln)

# Parameters.
if (
self.isSignature and
not ln.endswith(":")
):
p = ln
# Remove comma if present.
if p.endswith(","):
p = p[:-1]
self.parameters.append(p)

# Beginning of signature.
if (
self.returnType is None and
self.name is None
and lastPart.endswith("(")
):
self.isSignature = True

# Return type.
if (
self.isSignature and
ln.startswith(") -> ") and
ln.endswith(":")
):
self.returnType = ln[len(") -> "):-len(":")]

# End of parameters/signature.
if (
self.isSignature and
ln.startswith(") -> ") and
ln.endswith(":")
):
self.isSignature = False
self.isBody = True

# Name.
if (
self.isSignature and
lastPart.endswith("(")
):
self.name = lastPart[:-1]

def __repr__(self):
return self.__str__()
def __str__(self):
return f"Function(name/returnT/parameters/statements: '{self.name}'/'{self.returnType}'/'{self.parameters}'/'{self.statements}')"

+ 29
- 0
tr-Python-C++/process.py View File

@@ -0,0 +1,29 @@
from CPP import *
from Function import *

def process(FILE_IN):
# Read file.
lines_in = []
with open(FILE_IN) as file:
for line in file:
lines_in.append(line.rstrip())

f = Function()

# 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(f"Debug: {f}")

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

+ 17
- 0
tr-Python-C++/translate View File

@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import os
import sys
from process import *

DIR = os.path.dirname(os.path.realpath(sys.argv[0]))

# Demand file as input
if len(sys.argv) < 2:
print("Usage: /path/to/translate PYTHON_FILE")
sys.exit(1)

FILE_IN = sys.argv[1]

# Translate file.
out = process(FILE_IN)
print(out)

Loading…
Cancel
Save