Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
17 changes: 17 additions & 0 deletions vyper/codegen/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,23 @@ 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 name, idx in flag_t._flag_members.items():
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
5 changes: 3 additions & 2 deletions vyper/codegen/stmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def parse_For(self):
with self.context.block_scope():
if self.stmt.get("iter.func.id") == "range":
return self._parse_For_range()
else:
return self._parse_For_list()
return self._parse_For_list()

def _parse_For_range(self):
assert "type" in self.stmt.target.target._metadata
Expand Down Expand Up @@ -279,6 +278,8 @@ def _parse_For_list(self):
del self.context.forvars[varname]
return b1.resolve(IRnode.from_list(ret))



def parse_AugAssign(self):
target = self._get_target(self.stmt.target)
right = Expr.parse_value_expr(self.stmt.value, self.context)
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
11 changes: 10 additions & 1 deletion vyper/semantics/types/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
)
from vyper.semantics.data_locations import DataLocation
from vyper.semantics.types.base import VyperType
from vyper.semantics.types.subscriptable import HashMapT
# Import moved to local scope to avoid circular dependency
from vyper.semantics.types.utils import type_from_abi, type_from_annotation
from vyper.utils import keccak256
from vyper.warnings import Deprecation, vyper_warn
Expand Down Expand Up @@ -75,6 +75,14 @@
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 Expand Up @@ -445,6 +453,7 @@
raise VariableDeclarationException(
"Struct values must be declared as kwargs e.g. Foo(a=1, b=2)", node.args[0]
)
from vyper.semantics.types.subscriptable import HashMapT
if next((i for i in self.member_types.values() if isinstance(i, HashMapT)), False):
raise VariableDeclarationException(
"Struct contains a mapping and so cannot be declared as a literal", node
Expand Down
Loading