Skip to content
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
24 changes: 24 additions & 0 deletions docs/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,30 @@ The following code uses bitwise operations to add and revoke permissions from a
ret ^= Roles.USER # flip the user bit between 0 and 1
return ret

Iteration
^^^^^^^^^

You can iterate over all members of a flag type via the special type member ``__values__``. The loop variable must be annotated with the same flag type.

The iteration order follows the declaration order (i.e. ascending bit index from left to right), and the number of iterations is statically bounded by the number of members in the flag.

.. code-block:: vyper

flag Permission:
READ
WRITE
EXECUTE

@external
@pure
def all_mask() -> uint256:
acc: uint256 = 0
for p: Permission in Permission.__values__:
acc = acc | convert(p, uint256)
return acc # 1 | 2 | 4 == 7

Attempting to iterate a flag type with a loop variable of a different type is a type error.

.. index:: !reference

Reference Types
Expand Down
159 changes: 159 additions & 0 deletions tests/functional/codegen/features/test_flag_iteration_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
def test_iterate_over_flag_type(get_contract):
code = """
flag Permission:
A
B
C

@pure
@external
def sum_mask() -> uint256:
acc: uint256 = 0
for p: Permission in Permission.__values__:
acc = acc | convert(p, uint256)
return acc
"""
c = get_contract(code)
# 1 | 2 | 4 = 7
assert c.sum_mask() == 7


def test_iterate_over_flag_type_count(get_contract):
code = """
flag Permission:
A
B
C
D

@pure
@external
def count() -> uint256:
cnt: uint256 = 0
for p: Permission in Permission.__values__:
cnt += 1
return cnt
"""
c = get_contract(code)
assert c.count() == 4


def test_iterate_over_flag_type_order(get_contract):
code = """
flag Permission:
A
B
C
D

@pure
@external
def order_sum() -> uint256:
acc: uint256 = 0
idx: uint256 = 0
for p: Permission in Permission.__values__:
acc = acc + (convert(p, uint256) << idx)
idx += 1
return acc
"""
c = get_contract(code)
# 1 + (2<<1) + (4<<2) + (8<<3) = 1 + 4 + 16 + 64 = 85
assert c.order_sum() == 85


def test_flag_iter_target_type_mismatch(assert_compile_failed, get_contract):
from vyper.exceptions import TypeMismatch

code = """
flag A:
X
flag B:
Y

@pure
@external
def f() -> uint256:
s: uint256 = 0
for p: B in A.__values__:
s += convert(p, uint256)
return s
"""
assert_compile_failed(lambda: get_contract(code), TypeMismatch)


def test_flag_iter_invalid_iterator(assert_compile_failed, get_contract):
from vyper.exceptions import InvalidType

code = """
flag P:
A

@pure
@external
def f() -> uint256:
s: uint256 = 0
for p: P in 5:
s += 1
return s
"""
assert_compile_failed(lambda: get_contract(code), InvalidType)


def test_flag_iter_wrong_target_type(assert_compile_failed, get_contract):
from vyper.exceptions import TypeMismatch

code = """
flag P:
A
B

@pure
@external
def f() -> uint256:
s: uint256 = 0
for p: uint256 in P.__values__:
s += p # wrong type; loop var must be P
return s
"""
assert_compile_failed(lambda: get_contract(code), TypeMismatch)


def test_flag_instance_member_access(assert_compile_failed, get_contract):
from vyper.exceptions import UnknownAttribute

code = """
flag P:
A
B

@pure
@external
def f(p: P) -> uint256:
return convert(p.A, uint256)
"""
assert_compile_failed(lambda: get_contract(code), UnknownAttribute)


def test_nested_flag_type_iteration(get_contract):
code = """
flag A:
X
Y
Z

flag B:
P
Q

@pure
@external
def product_sum() -> uint256:
s: uint256 = 0
for a: A in A.__values__:
for b: B in B.__values__:
s += convert(a, uint256) * convert(b, uint256)
return s
"""
c = get_contract(code)
# a in {1,2,4}, b in {1,2} => (1+2+4)*(1+2) = 7*3 = 21
assert c.product_sum() == 21
21 changes: 18 additions & 3 deletions vyper/codegen/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,20 @@ def parse_Name(self):
def parse_Attribute(self):
typ = self.expr._metadata["type"]

# Flag.__values__: materialize a static array of all flag values in order
# Left side must be a flag type expression.
if self.expr.attr == "__values__" and is_type_t(self.expr.value._metadata["type"], FlagT):
flag_t = self.expr.value._metadata["type"].typedef
# Build the list of constant IR nodes for each flag value
# using declaration order from `_flag_members`.
elements = []
for idx in flag_t._flag_members.values():
value = 2**idx
elements.append(IRnode.from_list(value, typ=flag_t))

arr_t = SArrayT(flag_t, len(elements))
return IRnode.from_list(["multi"] + elements, typ=arr_t)

# check if we have a flag constant, e.g.
# [lib1].MyFlag.FOO
if isinstance(typ, FlagT) and is_type_t(self.expr.value._metadata["type"], FlagT):
Expand Down Expand Up @@ -476,9 +490,10 @@ def build_in_comparator(self):

ret = ["seq"]

with left.cache_when_complex("needle") as (b1, left), right.cache_when_complex(
"haystack"
) as (b2, right):
with (
left.cache_when_complex("needle") as (b1, left),
right.cache_when_complex("haystack") as (b2, right),
):
# unroll the loop for compile-time list literals
if right.value == "multi":
# empty list literals should be rejected at typechecking time
Expand Down
1 change: 1 addition & 0 deletions vyper/semantics/analysis/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,7 @@ def visit_For(self, node):
# sanity check the postcondition of analyse_range_iter
assert isinstance(target_type, IntegerT)
else:
# Iterate over lists/arrays (including Flag.__values__)
# note: using `node.target` here results in bad source location.
iter_var = self._analyse_list_iter(node.target.target, node.iter, target_type)

Expand Down
30 changes: 22 additions & 8 deletions vyper/semantics/types/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
NamespaceCollision,
StructureException,
UnfoldableNode,
UnknownAttribute,
VariableDeclarationException,
)
from vyper.semantics.analysis.base import Modifiability
Expand Down Expand Up @@ -65,18 +66,27 @@

self._id = name

self._flag_members = members
self._flag_members = dict(members)

# use a VyperType for convenient access to the `get_member` function
# also conveniently checks well-formedness of the members namespace
self._helper = VyperType(members)
for member_name in self._flag_members:
self.add_member(member_name, self)

# set the name for exception handling in `get_member`
self._helper._id = name
from vyper.semantics.types.subscriptable import SArrayT

Check notice

Code scanning / CodeQL

Cyclic import Note

Import of module
vyper.semantics.types.subscriptable
begins an import cycle.

self.add_member("__values__", SArrayT(self, len(self._flag_members)))

def get_type_member(self, key: str, node: vy_ast.VyperNode) -> "VyperType":
self._helper.get_member(key, node)
return self
return super().get_member(key, node)

def get_member(self, key: str, node: vy_ast.VyperNode) -> "VyperType":
if key in self.members:
msg = (
f"{self} members are available on the type. "
f"Use {self.name}.{key} instead."
)
raise UnknownAttribute(msg, node)

return super().get_member(key, node)

def __str__(self):
return f"{self.name}"
Expand Down Expand Up @@ -135,6 +145,10 @@
raise FlagDeclarationException("Invalid syntax for flag member", node)

member_name = node.value.id
if member_name == "__values__":
raise FlagDeclarationException(
"Flag member '__values__' is reserved", node.value
)
if member_name in members:
raise FlagDeclarationException(
f"Flag member '{member_name}' has already been declared", node.value
Expand Down
Loading