Skip to content

Commit

Permalink
Add rebind_keep_modifier
Browse files Browse the repository at this point in the history
  • Loading branch information
cdonovick committed Aug 2, 2019
1 parent 692621c commit 41b0105
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions hwtypes/adt_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from .bit_vector_abc import AbstractBitVectorMeta, AbstractBitVector

from .util import _issubclass
from hwtypes.modifiers import get_all_modifiers

def rebind_bitvector(
adt,
Expand All @@ -20,3 +21,18 @@ def rebind_bitvector(
return new_adt
else:
return adt


def rebind_keep_modifiers(adt, A, B, rebind_sub_types=False):
if A is B or (rebind_sub_types and _issubclass(adt, B)):
for mod in get_all_modifiers(A):
B = mod(B)
return B
elif isinstance(adt, BoundMeta):
new_adt = adt
for field in adt.fields:
new_field = rebind_keep_modifiers(field, A, B, rebind_sub_types)
new_adt = new_adt.rebind(field, new_field)
return new_adt
else:
return adt
5 changes: 5 additions & 0 deletions hwtypes/modifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ def get_unmodified(T):
else:
raise TypeError(f'{T} has no modifiers')

def get_all_modifiers(T):
if is_modified(T):
yield from get_all_modifiers(get_unmodified(T))
yield get_modifier(T)

_mod_cache = weakref.WeakValueDictionary()
# This is a factory for type modifiers.
def make_modifier(name, cache=False):
Expand Down

0 comments on commit 41b0105

Please sign in to comment.