Skip to content

Commit

Permalink
Extend nested coercing tests
Browse files Browse the repository at this point in the history
  • Loading branch information
etan-status committed Oct 2, 2024
1 parent 74fadc0 commit 5cad2b1
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 31 deletions.
22 changes: 13 additions & 9 deletions remerkleable/complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ def readonly_iter(self):
else:
return ComplexElemIter(backing, tree_depth, length, elem_type)

def check_backing(self):
for el in self:
if isinstance(el, BackedView):
el.check_backing()

@classmethod
def deserialize(cls: Type[M], stream: BinaryIO, scope: int) -> M:
elem_cls = cls.element_cls()
Expand Down Expand Up @@ -284,9 +289,7 @@ def __new__(cls, *args, backing: Optional[Node] = None, hook: Optional[ViewHook]
raise Exception(f"too many list inputs: {len(vals)}, limit is: {limit}")
input_views = []
for el in vals:
if isinstance(el, BackedView):
input_views.append(elem_cls(backing=el.get_backing()))
elif isinstance(el, View):
if isinstance(el, View):
input_views.append(el)
else:
input_views.append(elem_cls.coerce_view(el))
Expand Down Expand Up @@ -530,9 +533,7 @@ def __new__(cls, *args, backing: Optional[Node] = None, hook: Optional[ViewHook]
raise Exception(f"invalid inputs length: {len(vals)}, vector length is: {vector_length}")
input_views = []
for el in vals:
if isinstance(el, BackedView):
input_views.append(elem_cls(backing=el.get_backing()))
elif isinstance(el, View):
if isinstance(el, View):
input_views.append(el)
else:
input_views.append(elem_cls.coerce_view(el))
Expand Down Expand Up @@ -719,6 +720,11 @@ def __new__(cls, *args, backing: Optional[Node] = None, hook: Optional[ViewHook]
def fields(cls) -> Fields: # base condition for the subclasses deriving the fields
return {}

def check_backing(self):
for el in self:
if isinstance(el, BackedView):
el.check_backing()


class Container(_ContainerBase):
_field_indices: Dict[str, int]
Expand All @@ -736,9 +742,7 @@ def __new__(cls, *args, backing: Optional[Node] = None, hook: Optional[ViewHook]
fnode: Node
if fkey in kwargs:
finput = kwargs.pop(fkey)
if isinstance(finput, BackedView):
fnode = ftyp(backing=finput.get_backing()).get_backing()
elif isinstance(finput, View):
if isinstance(finput, View):
fnode = finput.get_backing()
else:
fnode = ftyp.coerce_view(finput).get_backing()
Expand Down
6 changes: 6 additions & 0 deletions remerkleable/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ def __new__(cls, backing: Optional[Node] = None, hook: Optional[ViewHook] = None
out._hook = hook
return out

def __init__(self, *args, **kwargs):
self.check_backing()

def get_backing(self) -> Node:
return self._backing

Expand All @@ -247,6 +250,9 @@ def set_backing(self, value):
if self._hook is not None:
self._hook(self)

def check_backing(self):
pass


BV = TypeVar('BV', bound="BasicView")

Expand Down
42 changes: 30 additions & 12 deletions remerkleable/stable_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,7 @@ def __new__(cls, backing: Optional[Node] = None, hook: Optional[ViewHook] = None
fnode = zero_node(0)
active_fields.set(findex, False)
else:
if isinstance(finput, BackedView):
fnode = ftyp(backing=finput.get_backing()).get_backing()
elif isinstance(finput, View):
if isinstance(finput, View):
fnode = finput.get_backing()
else:
fnode = ftyp.coerce_view(finput).get_backing()
Expand Down Expand Up @@ -190,6 +188,17 @@ def active_fields(self) -> Bitvector:
active_fields_node = super().get_backing().get_right()
return Bitvector[self.__class__.N].view_from_backing(active_fields_node)

def check_backing(self):
active_fields = self.active_fields()
for fkey, (findex, _) in self.__class__._field_indices.items():
if active_fields.get(findex):
value = getattr(self, fkey)
if isinstance(value, BackedView):
value.check_backing()
for findex in range(len(self.__class__._field_indices), self.__class__.N):
if active_fields.get(findex):
raise ValueError(f'`{self.__class__.__name__}` invalid: Unknown field {findex}')

def __getattribute__(self, item):
if item == 'N':
raise AttributeError(f'Use `.__class__.{item}` to access `{item}`')
Expand Down Expand Up @@ -332,15 +341,6 @@ def __new__(cls, backing: Optional[Node] = None, hook: Optional[ViewHook] = None
if backing is not None:
if len(kwargs) != 0:
raise Exception('Cannot have both a backing and elements to init fields')
active_fields = Bitvector[cls.B.N].view_from_backing(backing.get_right())
for fkey, (findex, _) in cls.B._field_indices.items():
if fkey not in cls._field_indices:
if active_fields.get(findex):
raise ValueError(f'Cannot convert to `{cls.__name__}`: {fkey} unsupported')
else:
(_, _, fopt) = cls._field_indices[fkey]
if not fopt and not active_fields.get(findex):
raise ValueError(f'Cannot convert to `{cls.__name__}`: {fkey} is required')
return super().__new__(cls, backing=backing, hook=hook, **kwargs)

extra_kw = kwargs.copy()
Expand Down Expand Up @@ -606,6 +606,24 @@ def optional_fields(self) -> Bitvector:
oindex += 1
return optional_fields

def check_backing(self):
active_fields = self.active_fields()
for fkey, (findex, _) in self.__class__.B._field_indices.items():
if fkey not in self.__class__._field_indices:
if active_fields.get(findex):
raise ValueError(f'`{self.__class__.__name__}` invalid: {fkey} unsupported')
elif active_fields.get(findex):
value = getattr(self, fkey)
if isinstance(value, BackedView):
value.check_backing()
else:
(_, _, fopt) = self.__class__._field_indices[fkey]
if not fopt:
raise ValueError(f'`{self.__class__.__name__}` invalid: {fkey} is required')
for findex in range(len(self.__class__.B._field_indices), self.__class__.B.N):
if active_fields.get(findex):
raise ValueError(f'`{self.__class__.__name__}` invalid: Unknown field {findex}')

def __getattribute__(self, item):
if item == 'B':
raise AttributeError(f'Use `.__class__.{item}` to access `{item}`')
Expand Down
29 changes: 19 additions & 10 deletions remerkleable/test_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -706,8 +706,6 @@ class ShapePairRepr(Container):
square = Square(radius=0x42, color=1)
with pytest.raises(Exception):
circle = Circle(side=0x42, color=1)
with pytest.raises(Exception):
square = Square.coerce_view(Shape(radius=0x42, color=1))
with pytest.raises(Exception):
square = Square(backing=Circle(radius=0x42, color=1).get_backing())

Expand Down Expand Up @@ -747,11 +745,11 @@ class ShapeContainerRepr(Container):

# Unsupported surrounding container tests
with pytest.raises(Exception):
shapes = List[Square, 5].coerce_view(
List[Circle, 5](Circle(radius=0x42, color=1)))
shapes = List[Square, 5](
backing=List[Circle, 5](Circle(radius=0x42, color=1)).get_backing())
with pytest.raises(Exception):
shapes = Vector[Square, 1].coerce_view(
Vector[Circle, 1](Circle(radius=0x42, color=1)))
shapes = Vector[Square, 1](
backing=Vector[Circle, 1](Circle(radius=0x42, color=1)).get_backing())

class SquareContainer(Container):
shape: Square
Expand All @@ -760,8 +758,8 @@ class CircleContainer(Container):
shape: Circle

with pytest.raises(Exception):
shape = SquareContainer.coerce_view(
CircleContainer(shape=Circle(radius=0x42, color=1)))
shape = SquareContainer(
backing=CircleContainer(shape=Circle(radius=0x42, color=1)).get_backing())

class SquareStableContainer(StableContainer[1]):
shape: Optional[Square]
Expand All @@ -770,8 +768,19 @@ class CircleStableContainer(StableContainer[1]):
shape: Optional[Circle]

with pytest.raises(Exception):
shape = SquareStableContainer.coerce_view(
CircleStableContainer(shape=Circle(radius=0x42, color=1)))
shape = SquareStableContainer(
backing=CircleStableContainer(shape=Circle(radius=0x42, color=1)).get_backing())

class NestedSquareContainer(Container):
item: SquareContainer

class NestedCircleContainer(Container):
item: CircleContainer

with pytest.raises(Exception):
shape = NestedSquareContainer(
backing=NestedCircleContainer(
item=CircleContainer(shape=Circle(radius=0x42, color=1))).get_backing())

# basic container
class Shape1(StableContainer[4]):
Expand Down

0 comments on commit 5cad2b1

Please sign in to comment.