Skip to content

Commit 413831d

Browse files
committed
add unparse and first simple Cython backend
1 parent fd91713 commit 413831d

File tree

4 files changed

+1030
-10
lines changed

4 files changed

+1030
-10
lines changed

Diff for: epython/cython_backend.py

+41-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,43 @@
1-
from astor import SourceGenerator
1+
from .unparse import Unparser
22

3-
# For the Cython generator we re-use the astor code generator
3+
4+
# For the Cython generator we re-use the Unparser code generator
45
# and generate Cython code instead for nodes that have type information
5-
class CythonGenerator(SourceGenerator):
6-
7-
pass
6+
class CythonGenerator(Unparser):
7+
8+
def get_type_comment(self, node):
9+
comment = self._type_ignores.get(node.lineno) or node.type_comment
10+
if comment is not None:
11+
return comment
12+
13+
def visit_Assign(self, node):
14+
self.fill()
15+
for target in node.targets:
16+
if type_comment := self.get_type_comment(node):
17+
self.write(f"cdef {type_comment} ")
18+
self.traverse(target)
19+
self.write(" = ")
20+
self.traverse(node.value)
21+
22+
def _function_helper(self, node, fill_suffix):
23+
self.maybe_newline()
24+
for deco in node.decorator_list:
25+
self.fill("@")
26+
self.traverse(deco)
27+
if node.returns:
28+
self.fill("cdef ")
29+
self.traverse(node.returns)
30+
self.write(" " + node.name)
31+
else:
32+
def_str = fill_suffix + " " + node.name
33+
self.fill(def_str)
34+
with self.delimit("(", ")"):
35+
self.traverse(node.args)
36+
with self.block(extra=self.get_type_comment(node)):
37+
self._write_docstring_and_traverse_body(node)
38+
39+
def visit_arg(self, node):
40+
if node.annotation:
41+
self.traverse(node.annotation)
42+
self.write(" ")
43+
self.write(node.arg)

Diff for: epython/epython.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,6 @@ def validate(code):
6464
return None
6565

6666
def main():
67-
import astor
68-
6967
find_backends()
7068
parser = argparse.ArgumentParser(prog='epython',
7169
description="Compile statically typed subset of Python to a backend.")
@@ -94,8 +92,10 @@ def main():
9492

9593
output = transformer(code, name)
9694

97-
print(astor.to_source(code))
98-
return code
95+
from .cython_backend import CythonGenerator
96+
translator = CythonGenerator()
97+
print(translator.visit(code))
98+
9999

100100
# importing the backend should be sufficient to call the decorator(s)
101101
# that registers the function in _registry which is why the

0 commit comments

Comments
 (0)