tqchen commented on code in PR #8:
URL: https://github.com/apache/tvm-ffi/pull/8#discussion_r2355232643


##########
python/tvm_ffi/experimental/type_info.py:
##########
@@ -0,0 +1,157 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import dataclasses
+import functools
+import sys
+from dataclasses import MISSING
+from typing import Any, Callable, ClassVar, TypeVar
+
+if sys.version_info >= (3, 10):
+    _DATACLASS_SLOTS_ON = {"slots": True}
+else:
+    _DATACLASS_SLOTS_ON = {}
+
+_InputClsType = TypeVar("_InputClsType")
+
+
[email protected](kw_only=True)
+class DataclassField:
+    """Produced by `tvm_ffi.dataclasses.field`."""
+
+    default_factory: Callable[[], Any]
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeField:
+    name: str
+    doc: str
+    size: int
+    offset: int
+    frozen: bool
+    getter: Any
+    setter: Any
+    dataclass_field: DataclassField | None = None
+
+    def create(self, cls: type) -> property:
+        name = self.name
+
+        def fget(this: Any, _name: str = name) -> Any:
+            return self.getter(this)  # type: ignore[misc]
+
+        def fset(this: Any, value: Any, _name: str = name) -> None:
+            self.setter(this, value)  # type: ignore[misc]
+
+        fget.__name__ = fset.__name__ = name
+        fget.__module__ = fset.__module__ = cls.__module__
+        fget.__qualname__ = fset.__qualname__ = f"{cls.__qualname__}.{name}"  
# type: ignore[attr-defined]
+        fget.__doc__ = fset.__doc__ = (
+            f"Property `{self.name}` of class `{cls.__qualname__}`"  # type: 
ignore[attr-defined]
+        )
+        return property(
+            fget=fget if self.getter else None,
+            fset=fset if (not self.frozen) and self.setter else None,
+            doc=f"{cls.__module__}.{cls.__qualname__}.{name}",
+        )
+
+    def set_dataclass_field(self, rhs: Any, parent_type_info: PyTypeInfo) -> 
None:
+        assert self.dataclass_field is None, "`dataclass_field` is already set"
+        if isinstance(rhs, property):
+            # `type_cls.{field_name}` is a property, i.e. has getter/setter.
+            # It means it's probably already defined in its parent class.
+            for parent_field in parent_type_info.fields:
+                if parent_field.name == self.name:
+                    rhs = parent_field.dataclass_field
+                    break
+        from .utils import field
+
+        if rhs is MISSING:
+            rhs = field()
+        elif isinstance(rhs, (int, float, str, bool, type(None))):
+            rhs = field(default=rhs)
+        elif isinstance(rhs, DataclassField):
+            rhs = rhs
+        else:
+            raise ValueError(f"Cannot recognize field: {self.name}: {rhs}")
+        self.dataclass_field = rhs
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeMethod:
+    name: str
+    doc: str
+    func: Any
+    is_static: bool
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeInfo:

Review Comment:
   does it have to be PyTypeInfo? maybe just TypeInfo? given we are already in 
python



##########
python/tvm_ffi/experimental/type_info.py:
##########
@@ -0,0 +1,157 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import dataclasses
+import functools
+import sys
+from dataclasses import MISSING
+from typing import Any, Callable, ClassVar, TypeVar
+
+if sys.version_info >= (3, 10):
+    _DATACLASS_SLOTS_ON = {"slots": True}
+else:
+    _DATACLASS_SLOTS_ON = {}
+
+_InputClsType = TypeVar("_InputClsType")
+
+
[email protected](kw_only=True)
+class DataclassField:
+    """Produced by `tvm_ffi.dataclasses.field`."""
+
+    default_factory: Callable[[], Any]
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeField:

Review Comment:
   Logically, TypeInfo and TypeField can belong to the core , given it is part 
of the c ABI. That does mean that we might want to split out some functions 
that are dataclass specific as functions that takes TypeField etc.
   
   The agnostic reflection setter can be reused in general



##########
src/ffi/extra/testing.cc:
##########
@@ -111,7 +137,23 @@ TVM_FFI_STATIC_INIT_BLOCK() {
       .def_ro("v_map", &TestObjectDerived::v_map)
       .def_ro("v_array", &TestObjectDerived::v_array);
 
+  refl::ObjectDef<TestCxxClassBase>()
+      .def_rw("v_i64", &TestCxxClassBase::v_i64)
+      .def_rw("v_i32", &TestCxxClassBase::v_i32);
+
+  refl::ObjectDef<TestCxxClassDerived>()
+      .def_rw("v_f64", &TestCxxClassDerived::v_f64)
+      .def_rw("v_f32", &TestCxxClassDerived::v_f32);
+
   refl::GlobalDef()
+      .def("testing.TestCxxClassBase",

Review Comment:
   can move these to def_static of the `refl::ObjectDef`



##########
python/tvm_ffi/experimental/c_class.py:
##########
@@ -0,0 +1,78 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from collections.abc import Callable
+from typing import ClassVar, get_origin, get_type_hints
+
+from . import utils
+from .type_info import DataclassField, PyTypeField, PyTypeInfo, _InputClsType
+
+try:
+    from typing import dataclass_transform
+except ImportError:
+    from typing_extensions import dataclass_transform
+
+
+@dataclass_transform(field_specifiers=(utils.field, DataclassField))
+def c_class(
+    type_key: str, init: bool = True
+) -> Callable[[type[_InputClsType]], type[_InputClsType]]:
+    def decorator(super_type_cls: type[_InputClsType]) -> type[_InputClsType]:
+        nonlocal init
+        init = init and "__init__" not in super_type_cls.__dict__
+        # Step 1. Retrieve `type_info` from registry
+        parent_type_info = utils.get_parent_type_info(super_type_cls)
+        type_info: PyTypeInfo = PyTypeInfo.lookup_type_info(type_key)
+        type_info.parent_type_info = parent_type_info
+        # Step 2. Reflect all the fields of the type
+        type_info.fields = inspect_c_class_fields(super_type_cls, type_info)
+        for type_field in type_info.fields:
+            utils.fill_dataclass_field(super_type_cls, type_field, 
parent_type_info)
+        # Step 3. Create the proxy class with the fields as properties
+        fn_init = utils.method_init(super_type_cls, type_info) if init else 
None
+        type_cls: type[_InputClsType] = type_info.create(
+            cls=super_type_cls, methods={"__init__": fn_init}
+        )
+        return type_cls
+
+    return decorator
+
+
+def inspect_c_class_fields(type_cls: type, type_info: PyTypeInfo) -> 
list[PyTypeField]:
+    type_hints_resolved = get_type_hints(type_cls, include_extras=True)
+    type_hints = {
+        name: type_hints_resolved[name]
+        for name in getattr(type_cls, "__annotations__", {}).keys()
+        if get_origin(type_hints_resolved[name]) is not ClassVar
+    }
+    type_fields_reflected: dict[str, PyTypeField] = {f.name: f for f in 
type_info.fields}
+    type_fields: list[PyTypeField] = []
+    for field_name, _field_ty_py in type_hints.items():
+        if field_name.startswith("_tvm_"):  # TVM's private fields - skip

Review Comment:
   `_tvm_ffi`



##########
python/tvm_ffi/experimental/type_info.py:
##########
@@ -0,0 +1,157 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import dataclasses
+import functools
+import sys
+from dataclasses import MISSING
+from typing import Any, Callable, ClassVar, TypeVar
+
+if sys.version_info >= (3, 10):
+    _DATACLASS_SLOTS_ON = {"slots": True}
+else:
+    _DATACLASS_SLOTS_ON = {}
+
+_InputClsType = TypeVar("_InputClsType")
+
+
[email protected](kw_only=True)
+class DataclassField:
+    """Produced by `tvm_ffi.dataclasses.field`."""
+
+    default_factory: Callable[[], Any]
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeField:
+    name: str
+    doc: str
+    size: int
+    offset: int
+    frozen: bool
+    getter: Any
+    setter: Any
+    dataclass_field: DataclassField | None = None
+
+    def create(self, cls: type) -> property:
+        name = self.name
+
+        def fget(this: Any, _name: str = name) -> Any:
+            return self.getter(this)  # type: ignore[misc]
+
+        def fset(this: Any, value: Any, _name: str = name) -> None:
+            self.setter(this, value)  # type: ignore[misc]
+
+        fget.__name__ = fset.__name__ = name
+        fget.__module__ = fset.__module__ = cls.__module__
+        fget.__qualname__ = fset.__qualname__ = f"{cls.__qualname__}.{name}"  
# type: ignore[attr-defined]
+        fget.__doc__ = fset.__doc__ = (
+            f"Property `{self.name}` of class `{cls.__qualname__}`"  # type: 
ignore[attr-defined]
+        )
+        return property(
+            fget=fget if self.getter else None,
+            fset=fset if (not self.frozen) and self.setter else None,
+            doc=f"{cls.__module__}.{cls.__qualname__}.{name}",
+        )
+
+    def set_dataclass_field(self, rhs: Any, parent_type_info: PyTypeInfo) -> 
None:
+        assert self.dataclass_field is None, "`dataclass_field` is already set"
+        if isinstance(rhs, property):
+            # `type_cls.{field_name}` is a property, i.e. has getter/setter.
+            # It means it's probably already defined in its parent class.
+            for parent_field in parent_type_info.fields:
+                if parent_field.name == self.name:
+                    rhs = parent_field.dataclass_field
+                    break
+        from .utils import field
+
+        if rhs is MISSING:
+            rhs = field()
+        elif isinstance(rhs, (int, float, str, bool, type(None))):
+            rhs = field(default=rhs)
+        elif isinstance(rhs, DataclassField):
+            rhs = rhs
+        else:
+            raise ValueError(f"Cannot recognize field: {self.name}: {rhs}")
+        self.dataclass_field = rhs
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeMethod:
+    name: str
+    doc: str
+    func: Any
+    is_static: bool
+
+
[email protected](eq=False, **_DATACLASS_SLOTS_ON)
+class PyTypeInfo:
+    _registry: ClassVar[dict[str, "PyTypeInfo"]] = {}
+
+    type_cls: type | None
+    type_index: int
+    type_key: str
+    fields: list[PyTypeField]
+    methods: list[PyTypeMethod]
+    parent_type_info: PyTypeInfo | None
+
+    @staticmethod
+    def lookup_type_info(type_key: str) -> "PyTypeInfo":
+        from ..core import _py_type_info_from_type_key  # type: ignore
+
+        info: PyTypeInfo = _py_type_info_from_type_key(
+            type_key, PyTypeInfo, PyTypeField, PyTypeMethod
+        )
+        PyTypeInfo._registry[type_key] = info
+        return info
+
+    def create(
+        self, cls: type[_InputClsType], methods: dict[str, Callable[..., Any] 
| None]
+    ) -> type[_InputClsType]:
+        assert self.type_cls is None, "Type class is already created"
+        # Step 1. Determine the base classes
+        cls_bases = cls.__bases__
+        if cls_bases == (object,):
+            # If the class inherits from `object`, we need to set the base 
class to `Object`
+            from ..core import Object  # type: ignore
+
+            cls_bases = (Object,)
+        # Step 2. Define the new class attributes
+        attrs = dict(cls.__dict__)
+        attrs.pop("__dict__", None)
+        attrs.pop("__weakref__", None)
+        attrs["__slots__"] = ()
+        attrs["_tvm_type_info"] = self

Review Comment:
   `__tvm_ffi_type_info__`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to