-
Notifications
You must be signed in to change notification settings - Fork 16
/
arc4.py
1608 lines (1466 loc) · 57.3 KB
/
arc4.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections.abc import Sequence
import attrs
from puya.arc4_util import (
determine_arc4_tuple_head_size,
get_arc4_fixed_bit_size,
is_arc4_dynamic_size,
is_arc4_static_size,
)
from puya.avm_type import AVMType
from puya.awst import (
nodes as awst_nodes,
wtypes,
)
from puya.errors import CodeError, InternalError
from puya.ir.avm_ops import AVMOp
from puya.ir.builder._utils import (
assert_value,
assign,
assign_intrinsic_op,
assign_targets,
assign_temp,
invoke_puya_lib_subroutine,
mktemp,
)
from puya.ir.builder.assignment import handle_assignment
from puya.ir.context import IRFunctionBuildContext
from puya.ir.models import (
BytesConstant,
Intrinsic,
Register,
UInt64Constant,
Value,
ValueProvider,
ValueTuple,
)
from puya.ir.types_ import AVMBytesEncoding, IRType, get_wtype_arity
from puya.ir.utils import format_tuple_index
from puya.parse import SourceLocation, sequential_source_locations_merge
from puya.utils import bits_to_bytes
@attrs.frozen(kw_only=True)
class ArrayIterator:
context: IRFunctionBuildContext
array_wtype: wtypes.ARC4Array
array: Value
array_length: Value
source_location: SourceLocation
def get_value_at_index(self, index: Value) -> ValueProvider:
return arc4_array_index(
self.context,
array_wtype=self.array_wtype,
array=self.array,
index=index,
source_location=self.source_location,
assert_bounds=False, # iteration is always within bounds
)
def decode_expr(context: IRFunctionBuildContext, expr: awst_nodes.ARC4Decode) -> ValueProvider:
value = context.visitor.visit_and_materialise_single(expr.value)
return _decode_arc4_value(context, value, expr.value.wtype, expr.wtype, expr.source_location)
def _decode_arc4_value(
context: IRFunctionBuildContext,
value: Value,
arc4_wtype: wtypes.WType,
target_wtype: wtypes.WType,
loc: SourceLocation,
) -> ValueProvider:
match arc4_wtype:
case wtypes.ARC4UIntN(n=scale) | wtypes.ARC4UFixedNxM(n=scale):
if scale > 64:
return value
else:
return Intrinsic(
op=AVMOp.btoi,
args=[value],
source_location=loc,
)
case wtypes.arc4_bool_wtype:
return Intrinsic(
op=AVMOp.getbit,
args=[value, UInt64Constant(value=0, source_location=None)],
source_location=loc,
types=(IRType.bool,),
)
case wtypes.ARC4DynamicArray(element_type=wtypes.ARC4UIntN(n=8)):
return Intrinsic(
op=AVMOp.extract,
immediates=[2, 0],
args=[value],
source_location=loc,
)
case wtypes.ARC4Tuple() as arc4_tuple:
return _visit_arc4_tuple_decode(
context, arc4_tuple, value, target_wtype=target_wtype, source_location=loc
)
case _:
raise InternalError(
f"Unsupported wtype for ARC4Decode: {arc4_wtype}",
location=loc,
)
def encode_arc4_struct(
context: IRFunctionBuildContext, expr: awst_nodes.NewStruct, wtype: wtypes.ARC4Struct
) -> ValueProvider:
assert expr.wtype == wtype
elements = [
context.visitor.visit_and_materialise_single(expr.values[field_name])
for field_name in expr.wtype.fields
]
return _visit_arc4_tuple_encode(context, elements, wtype.types, expr.source_location)
def encode_expr(context: IRFunctionBuildContext, expr: awst_nodes.ARC4Encode) -> ValueProvider:
value = context.visitor.visit_expr(expr.value)
return _encode_expr(context, value, expr.value.wtype, expr.wtype, expr.source_location)
def _encode_expr(
context: IRFunctionBuildContext,
value_provider: ValueProvider,
value_wtype: wtypes.WType,
arc4_wtype: wtypes.ARC4Type,
loc: SourceLocation,
) -> ValueProvider:
match arc4_wtype:
case wtypes.arc4_bool_wtype:
(value,) = context.visitor.materialise_value_provider(
value_provider, description="to_encode"
)
return _encode_arc4_bool(context, value, loc)
case wtypes.ARC4UIntN(n=bits):
(value,) = context.visitor.materialise_value_provider(
value_provider, description="to_encode"
)
num_bytes = bits // 8
return _itob_fixed(context, value, num_bytes, loc)
case wtypes.ARC4Tuple(types=arc4_item_types):
assert isinstance(
value_wtype, wtypes.WTuple
), f"expected WTuple argument, got {value_wtype.name}"
elements = context.visitor.materialise_value_provider(
value_provider, description="elements_to_encode"
)
arc4_items = _encode_arc4_tuple_items(
context, elements, value_wtype.types, arc4_item_types, loc
)
return _visit_arc4_tuple_encode(context, arc4_items, arc4_item_types, loc)
case wtypes.ARC4DynamicArray(element_type=wtypes.ARC4UIntN(n=8)):
(value,) = context.visitor.materialise_value_provider(
value_provider, description="to_encode"
)
factory = _OpFactory(context, loc)
length = factory.len(value, "length")
length_uint16 = factory.as_u16_bytes(length, "length_uint16")
return factory.concat(length_uint16, value, "encoded_value")
case wtypes.ARC4DynamicArray() | wtypes.ARC4StaticArray():
raise InternalError(
"NewArray should be used instead of ARC4Encode for arrays",
loc,
)
case _:
raise InternalError(
f"Unsupported wtype for ARC4Encode: {value_wtype}",
location=loc,
)
def _encode_arc4_tuple_items(
context: IRFunctionBuildContext,
elements: list[Value],
item_wtypes: Sequence[wtypes.WType],
arc4_item_wtypes: Sequence[wtypes.ARC4Type],
loc: SourceLocation,
) -> Sequence[Value]:
arc4_items = []
for item_wtype, arc4_item_wtype in zip(item_wtypes, arc4_item_wtypes, strict=True):
item_arity = get_wtype_arity(item_wtype)
item_elements = elements[:item_arity]
elements = elements[item_arity:]
if item_wtype == arc4_item_wtype:
arc4_items.extend(item_elements)
continue
item_value_provider = (
item_elements[0]
if item_arity == 1
else ValueTuple(
values=item_elements,
source_location=sequential_source_locations_merge(
[e.source_location for e in item_elements]
),
)
)
arc4_item_vp = _encode_expr(
context,
item_value_provider,
item_wtype,
arc4_item_wtype,
item_value_provider.source_location or loc,
)
(arc4_item,) = context.visitor.materialise_value_provider(arc4_item_vp, "arc4_item")
arc4_items.append(arc4_item)
return arc4_items
def encode_arc4_array(context: IRFunctionBuildContext, expr: awst_nodes.NewArray) -> ValueProvider:
if not isinstance(expr.wtype, wtypes.ARC4Array):
raise InternalError("Expected ARC4 Array expression", expr.source_location)
len_prefix = (
len(expr.values).to_bytes(2, "big")
if isinstance(expr.wtype, wtypes.ARC4DynamicArray)
else b""
)
factory = _OpFactory(context, expr.source_location)
elements = [context.visitor.visit_and_materialise_single(value) for value in expr.values]
element_type = expr.wtype.element_type
if element_type == wtypes.arc4_bool_wtype:
array_head_and_tail = factory.constant(b"")
for index, el in enumerate(elements):
if index % 8 == 0:
array_head_and_tail = factory.concat(
array_head_and_tail, el, temp_desc="array_head_and_tail"
)
else:
is_true = factory.get_bit(el, 0, "is_true")
array_head_and_tail = factory.set_bit(
value=array_head_and_tail,
index=index,
bit=is_true,
temp_desc="array_head_and_tail",
)
else:
array_head_and_tail = _arc4_items_as_arc4_tuple(
context, element_type, elements, expr.source_location
)
return factory.concat(len_prefix, array_head_and_tail, "array_data")
def arc4_array_index(
context: IRFunctionBuildContext,
*,
array_wtype: wtypes.ARC4Array,
array: Value,
index: Value,
source_location: SourceLocation,
assert_bounds: bool = True,
) -> ValueProvider:
factory = _OpFactory(context, source_location)
array_length_vp = _get_arc4_array_length(array_wtype, array, source_location)
array_head_and_tail_vp = _get_arc4_array_head_and_tail(array_wtype, array, source_location)
array_head_and_tail = factory.assign(array_head_and_tail_vp, "array_head_and_tail")
item_wtype = array_wtype.element_type
if is_arc4_dynamic_size(item_wtype):
inner_element_size = _maybe_get_inner_element_size(item_wtype)
if inner_element_size is not None:
if assert_bounds:
_assert_index_in_bounds(context, index, array_length_vp, source_location)
return _read_dynamic_item_using_length_from_arc4_container(
context,
array_head_and_tail=array_head_and_tail,
inner_element_size=inner_element_size,
index=index,
source_location=source_location,
)
else:
# no _assert_index_in_bounds here as end offset calculation implicitly checks
return _read_dynamic_item_using_end_offset_from_arc4_container(
context,
array_length_vp=array_length_vp,
array_head_and_tail=array_head_and_tail,
index=index,
source_location=source_location,
)
if item_wtype == wtypes.arc4_bool_wtype:
if assert_bounds:
# this catches the edge case of bit arrays that are not a multiple of 8
# e.g. reading index 6 & 7 of an array that has a length of 6
_assert_index_in_bounds(context, index, array_length_vp, source_location)
return _read_nth_bool_from_arc4_container(
context,
data=array_head_and_tail,
index=index,
source_location=source_location,
)
else:
item_bit_size = get_arc4_fixed_bit_size(item_wtype)
# no _assert_index_in_bounds here as static items will error on read if past end of array
return _read_static_item_from_arc4_container(
data=array_head_and_tail,
offset=factory.mul(index, item_bit_size // 8, "item_offset"),
item_wtype=item_wtype,
source_location=source_location,
)
def arc4_tuple_index(
context: IRFunctionBuildContext,
base: Value,
index: int,
wtype: wtypes.ARC4Tuple | wtypes.ARC4Struct,
source_location: SourceLocation,
) -> ValueProvider:
return _read_nth_item_of_arc4_heterogeneous_container(
context,
array_head_and_tail=base,
index=index,
tuple_type=wtype,
source_location=source_location,
)
def build_for_in_array(
context: IRFunctionBuildContext,
array_wtype: wtypes.ARC4Array,
array_expr: awst_nodes.Expression,
source_location: SourceLocation,
) -> ArrayIterator:
if not array_wtype.element_type.immutable:
raise InternalError(
"Attempted iteration of an ARC4 array of mutable objects", source_location
)
array = context.visitor.visit_and_materialise_single(array_expr)
length_vp = _get_arc4_array_length(array_wtype, array, source_location)
array_length = assign_temp(
context,
length_vp,
temp_description="array_length",
source_location=source_location,
)
return ArrayIterator(
context=context,
array=array,
array_length=array_length,
array_wtype=array_wtype,
source_location=source_location,
)
def handle_arc4_assign(
context: IRFunctionBuildContext,
target: awst_nodes.Expression,
value: ValueProvider,
source_location: SourceLocation,
*,
is_mutation: bool = False,
) -> Value:
result: Value
match target:
case awst_nodes.IndexExpression(
base=awst_nodes.Expression(
wtype=wtypes.ARC4DynamicArray() | wtypes.ARC4StaticArray() as array_wtype
) as base_expr,
index=index_value,
):
return handle_arc4_assign(
context,
target=base_expr,
value=_arc4_replace_array_item(
context,
base_expr=base_expr,
index_value_expr=index_value,
wtype=array_wtype,
value=value,
source_location=source_location,
),
source_location=source_location,
is_mutation=True,
)
case awst_nodes.FieldExpression(
base=awst_nodes.Expression(wtype=wtypes.ARC4Struct() as struct_wtype) as base_expr,
name=field_name,
):
return handle_arc4_assign(
context,
target=base_expr,
value=_arc4_replace_struct_item(
context,
base_expr=base_expr,
field_name=field_name,
wtype=struct_wtype,
value=value,
source_location=source_location,
),
source_location=source_location,
is_mutation=True,
)
case awst_nodes.TupleItemExpression(
base=awst_nodes.Expression(wtype=wtypes.ARC4Tuple() as tuple_wtype) as base_expr,
index=index_value,
):
return handle_arc4_assign(
context,
target=base_expr,
value=_arc4_replace_tuple_item(
context,
base_expr=base_expr,
index_int=index_value,
wtype=tuple_wtype,
value=value,
source_location=source_location,
),
source_location=source_location,
is_mutation=True,
)
# this function is sometimes invoked outside an assignment expr/stmt, which
# is how a non l-value expression can be possible
# TODO: refactor this so that this special case is handled where it originates
case awst_nodes.TupleItemExpression(
wtype=item_wtype,
) as ti_expr if not item_wtype.immutable:
result = assign(
context=context,
name=_get_tuple_var_name(ti_expr),
source=value,
register_location=ti_expr.source_location,
assignment_location=source_location,
)
return result
case _:
(result,) = handle_assignment(
context,
target,
value=value,
assignment_location=source_location,
is_mutation=is_mutation,
)
return result
def _get_tuple_var_name(expr: awst_nodes.TupleItemExpression) -> str:
if isinstance(expr.base.wtype, wtypes.WTuple):
if isinstance(expr.base, awst_nodes.TupleItemExpression):
return format_tuple_index(expr.base.wtype, _get_tuple_var_name(expr.base), expr.index)
if isinstance(expr.base, awst_nodes.VarExpression):
return format_tuple_index(expr.base.wtype, expr.base.name, expr.index)
raise CodeError("invalid assignment target", expr.base.source_location)
def concat_values(
context: IRFunctionBuildContext,
left_expr: awst_nodes.Expression,
right_expr: awst_nodes.Expression,
source_location: SourceLocation,
) -> Value:
factory = _OpFactory(context, source_location)
# check left is a valid ARC4 array to concat with
left_wtype = left_expr.wtype
if not isinstance(left_wtype, wtypes.ARC4DynamicArray):
raise InternalError("Expected left expression to be a dynamic ARC4 array", source_location)
left_element_type = left_wtype.element_type
# check right is a valid type to concat
right_wtype = right_expr.wtype
if isinstance(right_wtype, wtypes.ARC4Array):
right_element_type = right_wtype.element_type
elif isinstance(right_wtype, wtypes.WTuple) and all(
t == left_element_type for t in right_wtype.types
):
right_element_type = left_element_type
else:
right_element_type = None
if left_element_type != right_element_type:
raise CodeError(
f"Unexpected operand types or order for concatenation:"
f" {left_wtype} and {right_wtype}",
source_location,
)
if left_element_type == wtypes.arc4_bool_wtype:
left = context.visitor.visit_and_materialise_single(left_expr)
(r_data, r_length) = _get_arc4_array_tail_data_and_item_count(
context, right_expr, source_location
)
is_packed = UInt64Constant(
value=1 if isinstance(right_wtype, wtypes.ARC4Array) else 0,
source_location=source_location,
)
return factory.assign(
invoke_puya_lib_subroutine(
context,
full_name="_puya_lib.arc4.dynamic_array_concat_bits",
args=[left, r_data, r_length, is_packed],
source_location=source_location,
),
"concat_result",
)
if is_arc4_static_size(left_element_type):
element_size = get_arc4_fixed_bit_size(left_element_type)
return _concat_dynamic_array_fixed_size(
context,
left=left_expr,
right=right_expr,
source_location=source_location,
byte_size=element_size // 8,
)
if _is_byte_length_header(left_element_type):
left = context.visitor.visit_and_materialise_single(left_expr)
(r_data, r_length) = _get_arc4_array_tail_data_and_item_count(
context, right_expr, source_location
)
return factory.assign(
invoke_puya_lib_subroutine(
context,
full_name="_puya_lib.arc4.dynamic_array_concat_byte_length_head",
args=[left, r_data, r_length],
source_location=source_location,
),
"concat_result",
)
if is_arc4_dynamic_size(left_element_type):
assert isinstance(left_wtype, wtypes.ARC4DynamicArray)
left = context.visitor.visit_and_materialise_single(left_expr)
if isinstance(right_wtype, wtypes.WTuple):
right_values = context.visitor.visit_and_materialise(right_expr)
r_count_vp: ValueProvider = UInt64Constant(
value=len(right_wtype.types), source_location=source_location
)
r_head_and_tail_vp: ValueProvider = _arc4_items_as_arc4_tuple(
context, left_element_type, right_values, source_location
)
elif isinstance(right_wtype, wtypes.ARC4Array):
right = context.visitor.visit_and_materialise_single(right_expr)
r_count_vp = _get_arc4_array_length(right_wtype, right, source_location)
r_head_and_tail_vp = _get_arc4_array_head_and_tail(right_wtype, right, source_location)
else:
raise InternalError("Expected array", source_location)
args = factory.assign_multiple(
l_count=_get_arc4_array_length(left_wtype, left, source_location),
l_head_and_tail=_get_arc4_array_head_and_tail(left_wtype, left, source_location),
r_count=r_count_vp,
r_head_and_tail=r_head_and_tail_vp,
)
return factory.assign(
invoke_puya_lib_subroutine(
context,
full_name="_puya_lib.arc4.dynamic_array_concat_dynamic_element",
args=list(args),
source_location=source_location,
),
"concat_result",
)
raise InternalError("Unexpected element type", source_location)
def pop_arc4_array(
context: IRFunctionBuildContext,
expr: awst_nodes.ArrayPop,
array_wtype: wtypes.ARC4DynamicArray,
) -> ValueProvider:
source_location = expr.source_location
base = context.visitor.visit_and_materialise_single(expr.base)
args: list[Value | int | bytes] = [base]
if array_wtype.element_type == wtypes.arc4_bool_wtype:
method_name = "dynamic_array_pop_bit"
elif _is_byte_length_header(array_wtype.element_type): # TODO: multi_byte_length prefix?
method_name = "dynamic_array_pop_byte_length_head"
elif is_arc4_dynamic_size(array_wtype.element_type):
method_name = "dynamic_array_pop_dynamic_element"
else:
fixed_size = get_arc4_fixed_bit_size(array_wtype.element_type)
method_name = "dynamic_array_pop_fixed_size"
args.append(fixed_size // 8)
popped = mktemp(context, IRType.bytes, source_location, description="popped")
data = mktemp(context, IRType.bytes, source_location, description="data")
assign_targets(
context,
targets=[popped, data],
source=invoke_puya_lib_subroutine(
context,
full_name=f"_puya_lib.arc4.{method_name}",
args=args,
source_location=source_location,
),
assignment_location=source_location,
)
handle_arc4_assign(context, target=expr.base, value=data, source_location=source_location)
return popped
def _encode_arc4_bool(
context: IRFunctionBuildContext, bit: Value, source_location: SourceLocation
) -> Value:
factory = _OpFactory(context, source_location)
value = factory.constant(0x00.to_bytes(1, "big"))
return factory.set_bit(value=value, index=0, bit=bit, temp_desc="encoded_bool")
def _visit_arc4_tuple_decode(
context: IRFunctionBuildContext,
wtype: wtypes.ARC4Tuple,
value: Value,
target_wtype: wtypes.WType,
source_location: SourceLocation,
) -> ValueProvider:
items = list[Value]()
if not isinstance(target_wtype, wtypes.WTuple):
raise InternalError("expected ARC4Decode of a tuple to target a WTuple", source_location)
for index, (target_item_wtype, item_wtype) in enumerate(
zip(target_wtype.types, wtype.types, strict=True)
):
item_value = _read_nth_item_of_arc4_heterogeneous_container(
context,
array_head_and_tail=value,
tuple_type=wtype,
index=index,
source_location=source_location,
)
item = assign_temp(
context,
temp_description=f"item{index}",
source=item_value,
source_location=source_location,
)
if target_item_wtype != item_wtype:
decoded_item = _decode_arc4_value(
context, item, item_wtype, target_item_wtype, source_location
)
items.extend(context.visitor.materialise_value_provider(decoded_item, item.name))
else:
items.append(item)
return ValueTuple(source_location=source_location, values=items)
def _is_byte_length_header(wtype: wtypes.ARC4Type) -> bool:
return (
isinstance(wtype, wtypes.ARC4DynamicArray)
and is_arc4_static_size(wtype.element_type)
and get_arc4_fixed_bit_size(wtype.element_type) == 8
)
def _maybe_get_inner_element_size(item_wtype: wtypes.ARC4Type) -> int | None:
match item_wtype:
case wtypes.ARC4Array(element_type=inner_static_element_type) if is_arc4_static_size(
inner_static_element_type
):
pass
case _:
return None
return get_arc4_fixed_bit_size(inner_static_element_type) // 8
def _read_dynamic_item_using_length_from_arc4_container(
context: IRFunctionBuildContext,
*,
array_head_and_tail: Value,
inner_element_size: int,
index: Value,
source_location: SourceLocation,
) -> ValueProvider:
factory = _OpFactory(context, source_location)
item_offset_offset = factory.mul(index, 2, "item_offset_offset")
item_start_offset = factory.extract_uint16(
array_head_and_tail, item_offset_offset, "item_offset"
)
item_length = factory.extract_uint16(array_head_and_tail, item_start_offset, "item_length")
item_length_in_bytes = factory.mul(item_length, inner_element_size, "item_length_in_bytes")
item_total_length = factory.add(item_length_in_bytes, 2, "item_head_tail_length")
return Intrinsic(
op=AVMOp.extract3,
args=[array_head_and_tail, item_start_offset, item_total_length],
source_location=source_location,
)
def _read_dynamic_item_using_end_offset_from_arc4_container(
context: IRFunctionBuildContext,
*,
array_length_vp: ValueProvider,
array_head_and_tail: Value,
index: Value,
source_location: SourceLocation,
) -> ValueProvider:
factory = _OpFactory(context, source_location)
item_offset_offset = factory.mul(index, 2, "item_offset_offset")
item_start_offset = factory.extract_uint16(
array_head_and_tail, item_offset_offset, "item_offset"
)
array_length = factory.assign(array_length_vp, "array_length")
next_item_index = factory.add(index, 1, "next_index")
# three possible outcomes of this op will determine the end offset
# next_item_index < array_length -> has_next is true, use next_item_offset
# next_item_index == array_length -> has_next is false, use array_length
# next_item_index > array_length -> op will fail, comment provides context to error
has_next = factory.assign(
Intrinsic(
op=AVMOp.sub,
args=[array_length, next_item_index],
source_location=source_location,
comment="on error: Index access is out of bounds",
),
"has_next",
)
end_of_array = factory.len(array_head_and_tail, "end_of_array")
next_item_offset_offset = factory.mul(next_item_index, 2, "next_item_offset_offset")
# next_item_offset_offset will be past the array head when has_next is false, but this is ok as
# the value will not be used. Additionally, next_item_offset_offset will always be a valid
# offset in the overall array, because there will be at least 1 element (due to has_next
# checking out of bounds) and this element will be dynamically sized,
# which means it's data has at least one u16 in its header
# e.g. reading here... has at least one u16 ........
# v v
# ArrayHead(u16, u16) ArrayTail(DynamicItemHead(... u16, ...), ..., DynamicItemTail, ...)
next_item_offset = factory.extract_uint16(
array_head_and_tail, next_item_offset_offset, "next_item_offset"
)
item_end_offset = factory.select(end_of_array, next_item_offset, has_next, "end_offset")
return Intrinsic(
op=AVMOp.substring3,
args=[array_head_and_tail, item_start_offset, item_end_offset],
source_location=source_location,
)
def _visit_arc4_tuple_encode(
context: IRFunctionBuildContext,
elements: Sequence[Value],
tuple_items: Sequence[wtypes.ARC4Type],
expr_loc: SourceLocation,
) -> ValueProvider:
header_size = determine_arc4_tuple_head_size(tuple_items, round_end_result=True)
factory = _OpFactory(context, expr_loc)
current_tail_offset = factory.assign(factory.constant(header_size // 8), "current_tail_offset")
encoded_tuple_buffer = factory.assign(factory.constant(b""), "encoded_tuple_buffer")
for index, (element, el_wtype) in enumerate(zip(elements, tuple_items, strict=True)):
if el_wtype == wtypes.arc4_bool_wtype:
# Pack boolean
before_header = determine_arc4_tuple_head_size(
tuple_items[0:index], round_end_result=False
)
if before_header % 8 == 0:
encoded_tuple_buffer = factory.concat(
encoded_tuple_buffer, element, "encoded_tuple_buffer"
)
else:
is_true = factory.get_bit(element, 0, "is_true")
encoded_tuple_buffer = factory.set_bit(
value=encoded_tuple_buffer,
index=before_header,
bit=is_true,
temp_desc="encoded_tuple_buffer",
)
elif not is_arc4_dynamic_size(el_wtype):
# Append value
encoded_tuple_buffer = factory.concat(
encoded_tuple_buffer, element, "encoded_tuple_buffer"
)
else:
# Append pointer
offset_as_uint16 = factory.as_u16_bytes(current_tail_offset, "offset_as_uint16")
encoded_tuple_buffer = factory.concat(
encoded_tuple_buffer, offset_as_uint16, "encoded_tuple_buffer"
)
# Update Pointer
data_length = factory.len(element, "data_length")
current_tail_offset = factory.add(
current_tail_offset, data_length, "current_tail_offset"
)
for element, el_wtype in zip(elements, tuple_items, strict=True):
if is_arc4_dynamic_size(el_wtype):
encoded_tuple_buffer = factory.concat(
encoded_tuple_buffer, element, "encoded_tuple_buffer"
)
return encoded_tuple_buffer
def _arc4_replace_struct_item(
context: IRFunctionBuildContext,
base_expr: awst_nodes.Expression,
field_name: str,
wtype: wtypes.ARC4Struct,
value: ValueProvider,
source_location: SourceLocation,
) -> Value:
if not isinstance(wtype, wtypes.ARC4Struct):
raise InternalError("Unsupported indexed assignment target", source_location)
try:
index_int = wtype.names.index(field_name)
except ValueError:
raise CodeError(f"Invalid arc4.Struct field name {field_name}", source_location) from None
return _arc4_replace_tuple_item(context, base_expr, index_int, wtype, value, source_location)
def _arc4_replace_tuple_item(
context: IRFunctionBuildContext,
base_expr: awst_nodes.Expression,
index_int: int,
wtype: wtypes.ARC4Struct | wtypes.ARC4Tuple,
value: ValueProvider,
source_location: SourceLocation,
) -> Value:
factory = _OpFactory(context, source_location)
base = context.visitor.visit_and_materialise_single(base_expr)
value = factory.assign(value, "assigned_value")
element_type = wtype.types[index_int]
header_up_to_item = determine_arc4_tuple_head_size(
wtype.types[0:index_int],
round_end_result=element_type != wtypes.arc4_bool_wtype,
)
if element_type == wtypes.arc4_bool_wtype:
# Use Set bit
is_true = factory.get_bit(value, 0, "is_true")
return factory.set_bit(
value=base,
index=header_up_to_item,
bit=is_true,
temp_desc="updated_data",
)
elif is_arc4_static_size(element_type):
return factory.replace(
base,
header_up_to_item // 8,
value,
"updated_data",
)
else:
dynamic_indices = [index for index, t in enumerate(wtype.types) if is_arc4_dynamic_size(t)]
item_offset = factory.extract_uint16(base, header_up_to_item // 8, "item_offset")
data_up_to_item = factory.extract3(base, 0, item_offset, "data_up_to_item")
dynamic_indices_after_item = [i for i in dynamic_indices if i > index_int]
if not dynamic_indices_after_item:
# This is the last dynamic type in the tuple
# No need to update headers - just replace the data
return factory.concat(data_up_to_item, value, "updated_data")
header_up_to_next_dynamic_item = determine_arc4_tuple_head_size(
types=wtype.types[0 : dynamic_indices_after_item[0]],
round_end_result=True,
)
# update tail portion with new item
next_item_offset = factory.extract_uint16(
base,
header_up_to_next_dynamic_item // 8,
"next_item_offset",
)
total_data_length = factory.len(base, "total_data_length")
data_beyond_item = factory.substring3(
base,
next_item_offset,
total_data_length,
"data_beyond_item",
)
updated_data = factory.concat(data_up_to_item, value, "updated_data")
updated_data = factory.concat(updated_data, data_beyond_item, "updated_data")
# loop through head and update any offsets after modified item
item_length = factory.sub(next_item_offset, item_offset, "item_length")
new_value_length = factory.len(value, "new_value_length")
for dynamic_index in dynamic_indices_after_item:
header_up_to_dynamic_item = determine_arc4_tuple_head_size(
types=wtype.types[0:dynamic_index],
round_end_result=True,
)
tail_offset = factory.extract_uint16(
updated_data, header_up_to_dynamic_item // 8, "tail_offset"
)
# have to add the new length and then subtract the original to avoid underflow
tail_offset = factory.add(tail_offset, new_value_length, "tail_offset")
tail_offset = factory.sub(tail_offset, item_length, "tail_offset")
tail_offset_bytes = factory.as_u16_bytes(tail_offset, "tail_offset_bytes")
updated_data = factory.replace(
updated_data, header_up_to_dynamic_item // 8, tail_offset_bytes, "updated_data"
)
return updated_data
def _read_nth_item_of_arc4_heterogeneous_container(
context: IRFunctionBuildContext,
*,
array_head_and_tail: Value,
tuple_type: wtypes.ARC4Tuple | wtypes.ARC4Struct,
index: int,
source_location: SourceLocation,
) -> ValueProvider:
tuple_item_types = tuple_type.types
item_wtype = tuple_item_types[index]
head_up_to_item = determine_arc4_tuple_head_size(
tuple_item_types[:index], round_end_result=False
)
if item_wtype == wtypes.arc4_bool_wtype:
return _read_nth_bool_from_arc4_container(
context,
data=array_head_and_tail,
index=UInt64Constant(
value=head_up_to_item,
source_location=source_location,
),
source_location=source_location,
)
head_offset = UInt64Constant(
value=bits_to_bytes(head_up_to_item), source_location=source_location
)
if is_arc4_dynamic_size(item_wtype):
item_start_offset = assign_intrinsic_op(
context,
target="item_start_offset",
op=AVMOp.extract_uint16,
args=[array_head_and_tail, head_offset],
source_location=source_location,
)
next_index = index + 1
for tuple_item_index, tuple_item_type in enumerate(
tuple_item_types[next_index:], start=next_index
):
if is_arc4_dynamic_size(tuple_item_type):
head_up_to_next_dynamic_item = determine_arc4_tuple_head_size(
tuple_item_types[:tuple_item_index], round_end_result=False
)
next_dynamic_head_offset = UInt64Constant(
value=bits_to_bytes(head_up_to_next_dynamic_item),
source_location=source_location,
)
item_end_offset = assign_intrinsic_op(
context,
target="item_end_offset",
op=AVMOp.extract_uint16,
args=[array_head_and_tail, next_dynamic_head_offset],
source_location=source_location,
)
break
else:
item_end_offset = assign_intrinsic_op(
context,
target="item_end_offset",
op=AVMOp.len_,
args=[array_head_and_tail],
source_location=source_location,
)
return Intrinsic(
op=AVMOp.substring3,
args=[array_head_and_tail, item_start_offset, item_end_offset],
source_location=source_location,
)
else:
return _read_static_item_from_arc4_container(
data=array_head_and_tail,
offset=head_offset,
item_wtype=item_wtype,
source_location=source_location,
)
def _read_nth_bool_from_arc4_container(
context: IRFunctionBuildContext,
*,
data: Value,
index: Value,
source_location: SourceLocation,
) -> ValueProvider:
# index is the bit position
is_true = assign_temp(
context,
temp_description="is_true",
source=Intrinsic(op=AVMOp.getbit, args=[data, index], source_location=source_location),
source_location=source_location,
)
return _encode_arc4_bool(context, is_true, source_location)
def _read_static_item_from_arc4_container(
*,
data: Value,
offset: Value,
item_wtype: wtypes.ARC4Type,
source_location: SourceLocation,
) -> ValueProvider:
item_bit_size = get_arc4_fixed_bit_size(item_wtype)
item_length = UInt64Constant(value=item_bit_size // 8, source_location=source_location)
return Intrinsic(
op=AVMOp.extract3,