Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
WIP: fix all the things
Browse files Browse the repository at this point in the history
  • Loading branch information
iopapamanoglou committed Nov 5, 2024
1 parent f800a73 commit d2d29d2
Show file tree
Hide file tree
Showing 85 changed files with 501 additions and 411 deletions.
5 changes: 5 additions & 0 deletions src/faebryk/core/cpp/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ class GraphInterfaceModuleSibling(GraphInterfaceHierarchical):

class GraphInterfaceReference(GraphInterface):
def __init__(self) -> None: ...
def get_referenced_gif(self) -> GraphInterfaceSelf: ...
def get_reference(self) -> Node: ...

class GraphInterfaceReferenceUnboundError(Exception):
pass

class GraphInterfaceSelf(GraphInterface):
def __init__(self) -> None: ...
Expand Down
6 changes: 3 additions & 3 deletions src/faebryk/core/cpp/include/nano.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ template <typename Func, typename Return> struct new__<Func, Return()> {

auto wrapper_cls = [func =
(nb::detail::forward_t<Func>)func](nb::type_object h) {
printf("Called wrapper_cls with %s\n", nb::type_name(h).c_str());
// printf("Called wrapper_cls with %s\n", nb::type_name(h).c_str());
return func();
};
auto wrapper = [func = (nb::detail::forward_t<Func>)func]() {
Expand Down Expand Up @@ -65,7 +65,7 @@ struct new__<Func, Return(FirstArg, Args...)> {
if constexpr (is_first_arg_type_object) {
auto wrapper = [func = (nb::detail::forward_t<Func>)func](nb::type_object h,
Args... args) {
printf("Called wrapper with %s\n", nb::type_name(h).c_str());
// printf("Called wrapper with %s\n", nb::type_name(h).c_str());
return func(h, (nb::detail::forward_t<Args>)args...);
};
auto wrapper_nocls = [func =
Expand All @@ -85,7 +85,7 @@ struct new__<Func, Return(FirstArg, Args...)> {
// function that does not need cls as first argument
auto wrapper_cls = [func = (nb::detail::forward_t<Func>)func](
nb::type_object h, FirstArg arg1, Args... args) {
printf("Called wrapper_cls with %s\n", nb::type_name(h).c_str());
// printf("Called wrapper_cls with %s\n", nb::type_name(h).c_str());
return func(arg1, (nb::detail::forward_t<Args>)args...);
};
auto wrapper = [func = (nb::detail::forward_t<Func>)func](FirstArg arg1,
Expand Down
7 changes: 6 additions & 1 deletion src/faebryk/core/cpp/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,13 @@ PYMOD(m) {
FACTORY((nb::class_<GraphInterfaceSelf, GI>(m, "GraphInterfaceSelf")),
&GraphInterfaceSelf::factory<GraphInterfaceSelf>);

FACTORY((nb::class_<GraphInterfaceReference, GI>(m, "GraphInterfaceReference")),
FACTORY((nb::class_<GraphInterfaceReference, GI>(m, "GraphInterfaceReference")
.def("get_referenced_gif", &GraphInterfaceReference::get_referenced_gif,
nb::rv_policy::reference)
.def("get_reference", &GraphInterfaceReference::get_reference)),
&GraphInterfaceReference::factory<GraphInterfaceReference>);
nb::exception<GraphInterfaceReference::UnboundError>(
m, "GraphInterfaceReferenceUnboundError");

FACTORY(
(nb::class_<GraphInterfaceHierarchical, GI>(m, "GraphInterfaceHierarchical")
Expand Down
1 change: 1 addition & 0 deletions src/faebryk/core/graphinterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
GraphInterface,
GraphInterfaceHierarchical,
GraphInterfaceReference,
GraphInterfaceReferenceUnboundError,
GraphInterfaceSelf,
)
5 changes: 4 additions & 1 deletion src/faebryk/core/moduleinterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@

from typing_extensions import Self

from faebryk.core.cpp import GraphInterfaceModuleConnection
from faebryk.core.cpp import ( # noqa: F401
GraphInterfaceModuleConnection,
GraphInterfaceModuleSibling,
)
from faebryk.core.graphinterface import GraphInterface
from faebryk.core.link import (
Link,
Expand Down
90 changes: 58 additions & 32 deletions src/faebryk/core/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
Any,
Callable,
Iterable,
Self,
Type,
cast,
get_args,
Expand Down Expand Up @@ -188,6 +189,9 @@ class Node(CNode):

_init: bool = False

class _Skipped(Exception):
pass

def __hash__(self) -> int:
# TODO proper hash
return hash(id(self))
Expand Down Expand Up @@ -216,17 +220,28 @@ def add[T: Node | GraphInterface](
raise FieldContainerError(f"Expected dict got {type(container)}")
if name in container:
raise FieldExistsError(name)
container[name] = obj
# TODO consider setting name for non runtime container
# if container is not self.runtime:
# name = f"{container_name}[{name}]"
pass
else:
if not isinstance(container, list):
raise FieldContainerError(f"Expected list got {type(container)}")
container.append(obj)
name = f"{container_name}[{len(container) - 1}]"

if isinstance(obj, GraphInterface):
self._handle_add_gif(name, obj)
try:
if isinstance(obj, GraphInterface):
self._handle_add_gif(name, obj)
else:
self._handle_add_node(name, obj)
except Node._Skipped:
return obj

# add to container
if isinstance(container, dict):
container[name] = obj
else:
self._handle_add_node(name, obj)
container.append(obj)

return obj

Expand Down Expand Up @@ -372,15 +387,18 @@ def _setup_fields(self, cls):

def handle_add(name, obj):
del objects[name]
try:
if isinstance(obj, GraphInterface):
self._handle_add_gif(name, obj)
elif isinstance(obj, Node):
self._handle_add_node(name, obj)
else:
raise TypeError(
f"Cannot handle adding field {name=} of type {type(obj)}"
)
except Node._Skipped:
return
added_objects[name] = obj
if isinstance(obj, GraphInterface):
self._handle_add_gif(name, obj)
elif isinstance(obj, Node):
self._handle_add_node(name, obj)
else:
raise TypeError(
f"Cannot handle adding field {name=} of type {type(obj)}"
)

def append(name, inst):
if isinstance(inst, LL_Types):
Expand Down Expand Up @@ -456,7 +474,7 @@ def __new__(cls, *args, **kwargs):
out = super().__new__(cls)
return out

def _setup(self) -> None:
def _setup(self, *args, **kwargs) -> None:
cls = type(self)
# print(f"Called Node init {cls.__qualname__:<20} {'-' * 80}")

Expand All @@ -473,13 +491,13 @@ def _setup(self) -> None:
_, _ = self._setup_fields(cls)

# Call 2-stage constructors

if self._init:
for base in reversed(type(self).mro()):
if hasattr(base, "__preinit__"):
base.__preinit__(self)
for base in reversed(type(self).mro()):
if hasattr(base, "__postinit__"):
base.__postinit__(self)
for f_name in ("__preinit__", "__postinit__"):
for base in reversed(type(self).mro()):
if hasattr(base, f_name):
f = getattr(base, f_name)
f(self)

def __init__(self):
super().__init__()
Expand All @@ -488,12 +506,12 @@ def __init__(self):
assert not hasattr(self, "_is_setup")
self._is_setup = True

def __preinit__(self): ...
def __preinit__(self, *args, **kwargs) -> None: ...

def __postinit__(self): ...
def __postinit__(self, *args, **kwargs) -> None: ...

def __post_init__(self, *args, **kwargs):
self._setup()
self._setup(*args, **kwargs)

def __init_subclass__(cls, *, init: bool = True) -> None:
cls._init = init
Expand All @@ -510,12 +528,12 @@ def _handle_add_node(self, name: str, node: "Node"):

from faebryk.core.trait import TraitImpl

if isinstance(node, TraitImpl):
if TraitImpl.is_traitimpl(node):
if self.has_trait(node.__trait__):
if not node.handle_duplicate(
cast_assert(TraitImpl, self.get_trait(node.__trait__)), self
cast(TraitImpl, self.get_trait(node.__trait__)), self
):
return
raise Node._Skipped()

node.parent.connect(self.children, LinkNamedParent(name))
node._handle_added_to_parent()
Expand All @@ -525,6 +543,10 @@ def _remove_child(self, node: "Node"):

def _handle_added_to_parent(self): ...

def builder(self, op: Callable[[Self], Any]) -> Self:
op(self)
return self

# printing -------------------------------------------------------------------------

@try_avoid_endless_recursion
Expand All @@ -551,9 +573,13 @@ def add_trait[_TImpl: "TraitImpl"](self, trait: _TImpl) -> _TImpl:
def _find_trait_impl[V: "Trait | TraitImpl"](
self, trait: type[V], only_implemented: bool
) -> V | None:
from faebryk.core.trait import TraitImpl, TraitImplementationConfusedWithTrait
from faebryk.core.trait import (
Trait,
TraitImpl,
TraitImplementationConfusedWithTrait,
)

if issubclass(trait, TraitImpl):
if TraitImpl.is_traitimpl_type(trait):
if not trait.__trait__.__decless_trait__:
raise TraitImplementationConfusedWithTrait(
self, cast(type[Trait], trait)
Expand All @@ -562,9 +588,9 @@ def _find_trait_impl[V: "Trait | TraitImpl"](

out = self.get_children(
direct_only=True,
types=TraitImpl,
f_filter=lambda impl: impl.implements(trait)
and (impl.is_implemented() or not only_implemented),
types=Trait,
f_filter=lambda impl: trait.is_traitimpl(impl)
and (cast(TraitImpl, impl).is_implemented() or not only_implemented),
)

assert len(out) <= 1
Expand All @@ -583,7 +609,7 @@ def has_trait(self, trait: type["Trait | TraitImpl"]) -> bool:
return self.try_get_trait(trait) is not None

def get_trait[V: "Trait | TraitImpl"](self, trait: Type[V]) -> V:
from faebryk.core.trait import TraitNotFound
from faebryk.core.trait import Trait, TraitNotFound

impl = self.try_get_trait(trait)
if not impl:
Expand Down
Loading

0 comments on commit d2d29d2

Please sign in to comment.