-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy patharray.py
289 lines (254 loc) · 9.6 KB
/
array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import abc
import typing
from collections.abc import Sequence
import mypy.nodes
from puya import log
from puya.awst import wtypes
from puya.awst.nodes import (
ArrayConcat,
ArrayExtend,
ArrayLength,
ArrayPop,
Expression,
ExpressionStatement,
IndexExpression,
NewArray,
Statement,
TupleExpression,
)
from puya.errors import CodeError
from puya.parse import SourceLocation
from puyapy.awst_build import pytypes
from puyapy.awst_build.eb import _expect as expect
from puyapy.awst_build.eb._base import (
FunctionBuilder,
GenericTypeBuilder,
InstanceExpressionBuilder,
)
from puyapy.awst_build.eb._utils import (
dummy_statement,
dummy_value,
resolve_negative_literal_index,
)
# TODO: move these out of ARC4 ?
from puyapy.awst_build.eb.arc4._base import CopyBuilder
from puyapy.awst_build.eb.factories import builder_for_instance
from puyapy.awst_build.eb.interface import (
BuilderBinaryOp,
InstanceBuilder,
NodeBuilder,
TypeBuilder,
)
from puyapy.awst_build.eb.none import NoneExpressionBuilder
from puyapy.awst_build.eb.uint64 import UInt64ExpressionBuilder
logger = log.get_logger(__name__)
class ArrayGenericTypeBuilder(GenericTypeBuilder):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
if not args:
raise CodeError("empty arrays require a type annotation to be instantiated", location)
element_type = expect.instance_builder(args[0], default=expect.default_raise).pytype
typ = pytypes.GenericArrayType.parameterise([element_type], location)
return ArrayTypeBuilder(typ, self.source_location).call(
args, arg_kinds, arg_names, location
)
class ArrayTypeBuilder(TypeBuilder[pytypes.ArrayType]):
def __init__(self, typ: pytypes.PyType, location: SourceLocation):
assert isinstance(typ, pytypes.ArrayType)
assert typ.generic == pytypes.GenericArrayType
wtype = typ.wtype
assert isinstance(wtype, wtypes.WArray)
self._wtype = wtype
super().__init__(typ, location)
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
typ = self.produces()
values = tuple(expect.argument_of_type_else_dummy(a, typ.items).resolve() for a in args)
wtype = typ.wtype
assert isinstance(wtype, wtypes.WArray)
return ArrayExpressionBuilder(
NewArray(values=values, wtype=wtype, source_location=location), self._pytype
)
class ArrayExpressionBuilder(InstanceExpressionBuilder[pytypes.ArrayType]):
def __init__(self, expr: Expression, typ: pytypes.PyType):
assert isinstance(typ, pytypes.ArrayType)
super().__init__(typ, expr)
@typing.override
def contains(self, item: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:
logger.error("item containment with arrays is currently unsupported", location=location)
return dummy_value(pytypes.BoolType, location)
@typing.override
def iterate(self) -> Expression:
return self.resolve()
@typing.override
def iterable_item_type(self) -> pytypes.PyType:
return self.pytype.items
@typing.override
def index(self, index: InstanceBuilder, location: SourceLocation) -> InstanceBuilder:
array_length = self.length(index.source_location)
index = resolve_negative_literal_index(index, array_length, location)
result_expr = IndexExpression(
base=self.resolve(),
index=index.resolve(),
wtype=self.pytype.items_wtype,
source_location=location,
)
return builder_for_instance(self.pytype.items, result_expr)
@typing.override
def slice_index(
self,
begin_index: InstanceBuilder | None,
end_index: InstanceBuilder | None,
stride: InstanceBuilder | None,
location: SourceLocation,
) -> InstanceBuilder:
raise CodeError("slicing arrays is currently unsupported", location)
@typing.override
@typing.final
def to_bytes(self, location: SourceLocation) -> Expression:
raise CodeError("cannot serialize array", location)
def length(self, location: SourceLocation) -> InstanceBuilder:
return UInt64ExpressionBuilder(ArrayLength(array=self.resolve(), source_location=location))
@typing.override
def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:
match name:
case "length":
return self.length(location)
case "append":
return _Append(self.resolve(), self.pytype, location)
case "extend":
return _Extend(self.resolve(), self.pytype, location)
case "pop":
return _Pop(self.resolve(), self.pytype, location)
case "freeze":
return _Freeze(self.resolve(), self.pytype, location)
case "copy":
return CopyBuilder(self.resolve(), location, self.pytype)
case _:
return super().member_access(name, location)
@typing.override
def augmented_assignment(
self, op: BuilderBinaryOp, rhs: InstanceBuilder, location: SourceLocation
) -> Statement:
if op != BuilderBinaryOp.add:
logger.error(f"unsupported operator for type: {op.value!r}", location=location)
return dummy_statement(location)
rhs = _match_array_concat_arg(rhs, self.pytype)
extend = ArrayExtend(
base=self.resolve(),
other=rhs.resolve(),
wtype=wtypes.void_wtype,
source_location=location,
)
return ExpressionStatement(expr=extend)
@typing.override
def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:
return self.length(location).bool_eval(location, negate=negate)
class _ArrayFunc(FunctionBuilder, abc.ABC):
def __init__(self, expr: Expression, typ: pytypes.ArrayType, location: SourceLocation):
super().__init__(location)
self.expr = expr
self.typ = typ
class _Append(_ArrayFunc):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
arg = expect.exactly_one_arg_of_type_else_dummy(args, self.typ.items, location)
args_expr = arg.resolve()
args_tuple = TupleExpression.from_items([args_expr], arg.source_location)
return NoneExpressionBuilder(
ArrayExtend(
base=self.expr, other=args_tuple, wtype=wtypes.void_wtype, source_location=location
)
)
class _Pop(_ArrayFunc):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
expect.no_args(args, location)
result_expr = ArrayPop(
base=self.expr, wtype=self.typ.items_wtype, source_location=location
)
return builder_for_instance(self.typ.items, result_expr)
class _Extend(_ArrayFunc):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
arg = expect.exactly_one_arg(args, location, default=expect.default_none)
if arg is None:
other = dummy_value(self.typ, location)
else:
other = _match_array_concat_arg(arg, self.typ)
return NoneExpressionBuilder(
ArrayExtend(
base=self.expr,
other=other.resolve(),
wtype=wtypes.void_wtype,
source_location=location,
)
)
class _Freeze(_ArrayFunc):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
expect.no_args(args, location)
imm_type = pytypes.GenericImmutableArrayType.parameterise([self.typ.items], location)
imm_wtype = imm_type.wtype
assert isinstance(imm_wtype, wtypes.WArray)
return builder_for_instance(
imm_type,
ArrayConcat(
left=NewArray(wtype=imm_wtype, values=[], source_location=location),
right=self.expr,
wtype=imm_type.wtype,
source_location=location,
),
)
def _check_array_concat_arg(arg: InstanceBuilder, arr_type: pytypes.ArrayType) -> bool:
match arg:
case InstanceBuilder(pytype=pytypes.ArrayType(items=arr_type.items)):
return True
case InstanceBuilder(pytype=pytypes.TupleLikeType(items=tup_items)) if all(
ti == arr_type.items for ti in tup_items
):
return True
return False
def _match_array_concat_arg(arg: InstanceBuilder, arr_type: pytypes.ArrayType) -> InstanceBuilder:
if _check_array_concat_arg(arg, arr_type):
return arg
logger.error(
"expected an array or tuple of the same element type", location=arg.source_location
)
return dummy_value(arr_type, arg.source_location)