Commit 7eb96252 authored by Tom Niget's avatar Tom Niget

Add initial support for user types in Python

parent 0fa05177
import pyext import pyext
print("Imported:", pyext.add(5, 3), pyext.fibo(10), pyext.squares()) print("Imported:", pyext.add(5, 3), pyext.fibo(10), pyext.squares(), pyext.Person("jean", 123))
\ No newline at end of file \ No newline at end of file
...@@ -2,8 +2,17 @@ ...@@ -2,8 +2,17 @@
# extension # extension
import numpy as np import numpy as np
from dataclasses import dataclass
def add(x, y) -> int: @dataclass
class Person:
name: str
age: int
def afficher(self):
print(self.name, self.age)
def add(x, y):
return x + y return x + y
def fibo(n): def fibo(n):
...@@ -16,4 +25,4 @@ def squares() -> list[int]: ...@@ -16,4 +25,4 @@ def squares() -> list[int]:
return np.square([x for x in range(5)]) return np.square([x for x in range(5)])
if __name__ == "__main__": if __name__ == "__main__":
print("Python:", add(5, 3), fibo(10), squares()) print("Python:", add(5, 3), fibo(10), squares(), Person("jean", 123))
\ No newline at end of file \ No newline at end of file
...@@ -59,7 +59,7 @@ class ModuleVisitor(BlockVisitor): ...@@ -59,7 +59,7 @@ class ModuleVisitor(BlockVisitor):
yield f"> arg{i}" yield f"> arg{i}"
yield ") {" yield ") {"
yield "SubInterpreter lock{};" yield "InterpGuard guard{};"
yield f"return py::module_::import(\"{mod}\").attr(\"{name}\")(" yield f"return py::module_::import(\"{mod}\").attr(\"{name}\")("
for i, argty in enumerate(fty.parameters): for i, argty in enumerate(fty.parameters):
if i != 0: if i != 0:
...@@ -122,6 +122,21 @@ class ModuleVisitorExt(NodeVisitor): ...@@ -122,6 +122,21 @@ class ModuleVisitorExt(NodeVisitor):
#yield f'm.def("{node.name}", CoroWrapper(PROGRAMNS::{node.name}));' #yield f'm.def("{node.name}", CoroWrapper(PROGRAMNS::{node.name}));'
yield f'm.def("{node.name}", PROGRAMNS::{node.name});' yield f'm.def("{node.name}", PROGRAMNS::{node.name});'
def visit_ClassDef(self, node: ast.ClassDef) -> Iterable[str]:
yield f"py::class_<PROGRAMNS::{node.name}_s::py_type>(m, \"{node.name}\")"
init = node.type.fields["__init__"].type.resolve().remove_self()
init_params = init.parameters
yield ".def(py::init<"
for i, argty in enumerate(init_params):
if i != 0:
yield ", "
yield from self.visit(argty)
yield ">())"
yield f'.def("__repr__", [](const PROGRAMNS::{node.name}_s::py_type& self)'
yield "{ return repr(self); })"
yield ";"
pass
def visit_AST(self, node: ast.AST) -> Iterable[str]: def visit_AST(self, node: ast.AST) -> Iterable[str]:
yield from () yield from ()
pass pass
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment