Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tag decorator #85

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions peak/bitfield.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import typing as tp

from hwtypes.adt import Enum, Sum, Product
from hwtypes import AbstractBitVector

def tag(tags: tp.Mapping[type, int]):
def wrapper(sum: Sum):
if not issubclass(sum, Sum):
raise TypeError('tag can only be applied Sum')
if tags.keys() != sum.fields:
raise ValueError('tag must specificy an Option for each Sum option')
if not all(isinstance(t, int) for t in tags.values()):
raise TypeError('tags must be int')

setattr(sum, 'tags', tags)
return sum
return wrapper


def bitfield(i):
def wrap(klass):
klass.bitfield = i
Expand Down
31 changes: 31 additions & 0 deletions tests/test_tag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import pytest
from hwtypes.adt import Sum

from peak.bitfield import tag

def test_tag():
@tag({int : 0, str : 1})
class S(Sum[int ,str]): pass

assert S.tags[int] == 0
assert S.tags[str] == 1

with pytest.raises(TypeError):
@tag()
class S: pass

with pytest.raises(ValueError):
@tag({int : 0, str : 1, object : 2})
class S(Sum[int ,str]): pass

with pytest.raises(ValueError):
@tag({int : 0})
class S(Sum[int ,str]): pass

with pytest.raises(TypeError):
@tag({int : 'a', str : 1})
class S(Sum[int ,str]): pass