Skip to content
Open
Show file tree
Hide file tree
Changes from 7 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
143 changes: 143 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,143 @@
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_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
9 changes: 9 additions & 0 deletions vyper/semantics/types/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@
self._helper._id = name

def get_type_member(self, key: str, node: vy_ast.VyperNode) -> "VyperType":
# Special iterator helper for flags: `Flag.__values__`
# Returns a static array type of all flag values in declaration order.
if key == "__values__":
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why don't we actually put it on the flag type?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just thought this syntax looked weird

for f: Foo in Foo:
    ...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no i'm not talking about the user-facing semantics, i'm saying why don't we add it to the members dict on the flag type?

from vyper.semantics.types.subscriptable import SArrayT

return SArrayT(self, len(self._flag_members))

# Regular flag member access (e.g., `Flag.FOO`) validates the member name
# and yields the flag type in expression position.
self._helper.get_member(key, node)
return self

Expand Down
Loading