Skip to content

Commit

Permalink
add slice evaluate() and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
iFrostizz committed Nov 10, 2023
1 parent 4dd47e3 commit 71d3618
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
41 changes: 41 additions & 0 deletions tests/functional/builtins/codegen/test_slice.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,3 +432,44 @@ def test_slice_bytes32_calldata_extended(get_contract, code, result):
c.bar(3, "0x0001020304050607080910111213141516171819202122232425262728293031", 5).hex()
== result
)


code_comptime = [
(
"""
@external
@view
def baz() -> Bytes[16]:
return slice(0x1234567891234567891234567891234567891234567891234567891234567891, 0, 16)
""",
"12345678912345678912345678912345",
),
(
"""
@external
@view
def baz() -> String[5]:
return slice("why hello! how are you?", 4, 5)
""",
"hello",
),
(
"""
@external
@view
def baz() -> Bytes[6]:
return slice(b'gm sir, how are you ?', 0, 6)
""",
"gm sir".encode("utf-8").hex(),
),
]


@pytest.mark.parametrize("code,result", code_comptime)
def test_comptime(get_contract, code, result):
c = get_contract(code)
ret = c.baz()
if hasattr(ret, "hex"):
assert ret.hex() == result
else:
assert ret == result
19 changes: 19 additions & 0 deletions vyper/builtins/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,25 @@ class Slice(BuiltinFunction):
]
_return_type = None

def evaluate(self, node):
(lit, st, le) = node.args[:3]
(st_val, le_val) = (st.value, le.value)
if isinstance(lit, vy_ast.Bytes):
sublit = lit.value[st_val : (st_val + le_val)]
return vy_ast.Bytes.from_node(node, value=sublit)
elif isinstance(lit, vy_ast.Str):
sublit = lit.value[st_val : (st_val + le_val)]
return vy_ast.Str.from_node(node, value=sublit)
elif isinstance(lit, vy_ast.Hex):
length = len(lit.value) // 2 - 1
if length != 32:
# TODO unreachable?
raise UnfoldableNode
sublit = lit.value[st_val : (2 + st_val + (le_val * 2))]
return vy_ast.Bytes.from_node(node, value=sublit)
else:
raise UnfoldableNode

def fetch_call_return(self, node):
arg_type, _, _ = self.infer_arg_types(node)

Expand Down

0 comments on commit 71d3618

Please sign in to comment.