Skip to content

Instantly share code, notes, and snippets.

@kdevo
Last active April 15, 2019 13:14
Show Gist options
  • Save kdevo/e9c1567c0abebd440c5a898d172a4d49 to your computer and use it in GitHub Desktop.
Save kdevo/e9c1567c0abebd440c5a898d172a4d49 to your computer and use it in GitHub Desktop.
Transform LOOP0 language to Python code and execute it.
import re
class Loop0Transformer:
rules = {
r'(?P<indent>\s*)(?P<var1>\w+)\s*=\s*0': '{indent}{var1} = 0\n', # v = 0
r'(?P<indent>\s*)(?P<var1>\w+)\s*=\s*(?P<var2>\w+)\s*\+\s*1': '{indent}{var1} = {var2} + 1\n', # v = w + 1
r'(?P<indent>\s*)loop\s+(?P<var>\w+)(\s+begin)*': '{indent}for _ in range({var}):\n', # loop v begin a
r'(?P<indent>\s*)end': '{indent}# end for\n' # This "transformation" is not really needed results in a comment
}
def __init__(self, loop_code: str):
"""
Constructs the incomplete but sufficient minimal LOOP0 to Python translator.
:param loop_code: The LOOP0 code *must* be indented accordingly,
because indentations will be retained for the sake of simplicity.
"""
self._py_code = Loop0Transformer.transform(loop_code)
print("-----------------\n"
"Transformed code:\n"
"-----------------\n", self._py_code, sep='')
@staticmethod
def transform(loop0_code: str):
py_code = ''
for (idx, line) in enumerate([line.rstrip() for line in loop0_code.splitlines() if line.strip() != '']):
found_line_match = False
for (rule, transformation) in Loop0Transformer.rules.items():
match = re.match(rule, line, re.IGNORECASE | re.ASCII)
if match:
py_code += transformation.format(**match.groupdict())
found_line_match = True
break
if not found_line_match:
print('[WARNING] Ignoring line (#{no}): "{content}"'.format(no=idx, content=line))
return py_code
def exec(self, initial_variables: {}):
exec(self._py_code, {}, initial_variables)
initial_variables.pop('_', None)
return initial_variables
transformer = Loop0Transformer("""F(X1, X2) = X1 * X2 = Y:
Y = 0;
loop X1 begin
loop X2 begin
Y = Y + 1
end
end
""")
print("=> Results: ", transformer.exec({'X1': 4, 'X2': 20}), '\n')
transformer = Loop0Transformer("""F(X1) = 2 ** X1 = Y:
Y = 0;
Y = Y + 1;
loop X1 begin
loop Y begin }
Y = Y + 1 }-> Y = Y + Y <=> Y = Y * 2
end }
end
""")
print("=> Results: ", transformer.exec({'X1': 10}), '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment