-
Notifications
You must be signed in to change notification settings - Fork 16
/
global_state.py
294 lines (260 loc) · 9.69 KB
/
global_state.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
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 (
AppStateExpression,
BytesConstant,
BytesEncoding,
Expression,
ExpressionStatement,
Not,
StateDelete,
StateExists,
StateGet,
StateGetEx,
Statement,
)
from puya.errors import CodeError
from puya.models import ContractReference
from puya.parse import SourceLocation
from puyapy.awst_build import pytypes
from puyapy.awst_build.contract_data import AppStorageDeclaration
from puyapy.awst_build.eb import _expect as expect
from puyapy.awst_build.eb._base import (
FunctionBuilder,
GenericTypeBuilder,
NotIterableInstanceExpressionBuilder,
)
from puyapy.awst_build.eb._bytes_backed import BytesBackedInstanceExpressionBuilder
from puyapy.awst_build.eb.bool import BoolExpressionBuilder
from puyapy.awst_build.eb.factories import builder_for_instance
from puyapy.awst_build.eb.interface import (
InstanceBuilder,
NodeBuilder,
StorageProxyConstructorResult,
TypeBuilder,
)
from puyapy.awst_build.eb.storage._storage import (
StorageProxyDefinitionBuilder,
extract_description,
extract_key_override,
)
from puyapy.awst_build.eb.storage._value_proxy import ValueProxyExpressionBuilder
from puyapy.awst_build.eb.tuple import TupleExpressionBuilder
from puyapy.awst_build.utils import get_arg_mapping
logger = log.get_logger(__name__)
class GlobalStateTypeBuilder(TypeBuilder[pytypes.StorageProxyType]):
def __init__(self, typ: pytypes.PyType, location: SourceLocation) -> None:
assert isinstance(typ, pytypes.StorageProxyType)
assert typ.generic == pytypes.GenericGlobalStateType
self._typ = typ
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:
return _init(args, arg_names, location, result_type=self._typ)
class GlobalStateGenericTypeBuilder(GenericTypeBuilder):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
return _init(args, arg_names, location, result_type=None)
def _init(
args: Sequence[NodeBuilder],
arg_names: list[str | None],
location: SourceLocation,
*,
result_type: pytypes.StorageProxyType | None,
) -> InstanceBuilder:
type_or_value_arg_name = "type_or_initial_value"
key_arg_name = "key"
descr_arg_name = "description"
arg_mapping, _ = get_arg_mapping(
required_positional_names=[type_or_value_arg_name],
optional_kw_only=[key_arg_name, descr_arg_name],
args=args,
arg_names=arg_names,
call_location=location,
raise_on_missing=True,
)
match arg_mapping[type_or_value_arg_name]:
case NodeBuilder(pytype=pytypes.TypeType(typ=content)):
iv_builder = None
case InstanceBuilder(pytype=content) as iv_builder:
pass
case _:
raise CodeError(
"first argument must be a type reference or an initial value", location
)
if result_type is None:
result_type = pytypes.GenericGlobalStateType.parameterise([content], location)
elif result_type.content != content:
logger.error(
"explicit type annotation does not match first argument"
" - suggest to remove the explicit type annotation, it shouldn't be required",
location=location,
)
key_arg = arg_mapping.get(key_arg_name)
key_override = extract_key_override(key_arg, location, typ=wtypes.state_key)
descr_arg = arg_mapping.get(descr_arg_name)
description = extract_description(descr_arg)
if key_override is None:
return StorageProxyDefinitionBuilder(
result_type, location=location, description=description, initial_value=iv_builder
)
return _GlobalStateExpressionBuilderFromConstructor(
key_override=key_override,
typ=result_type,
description=description,
initial_value=iv_builder,
)
class GlobalStateExpressionBuilder(
NotIterableInstanceExpressionBuilder[pytypes.StorageProxyType],
BytesBackedInstanceExpressionBuilder[pytypes.StorageProxyType],
bytes_member="key",
):
def __init__(self, expr: Expression, typ: pytypes.PyType, member_name: str | None = None):
assert isinstance(typ, pytypes.StorageProxyType)
assert typ.generic == pytypes.GenericGlobalStateType
self.member_name: typing.Final = member_name
super().__init__(typ, expr)
@typing.override
def bool_eval(self, location: SourceLocation, *, negate: bool = False) -> InstanceBuilder:
field = _build_field(self, location)
exists_expr = StateExists(field=field, source_location=location)
if negate:
expr: Expression = Not(location, exists_expr)
else:
expr = exists_expr
return BoolExpressionBuilder(expr)
@typing.override
def member_access(self, name: str, location: SourceLocation) -> NodeBuilder:
match name:
case "value":
field = _build_field(self, location)
return _Value(self.pytype.content, field)
case "get":
return _Get(self, location)
case "maybe":
return _Maybe(self, location)
case _:
return super().member_access(name, location)
def _build_field(
self: GlobalStateExpressionBuilder, location: SourceLocation
) -> AppStateExpression:
if self.member_name:
exists_assertion_message = f"check self.{self.member_name} exists"
else:
exists_assertion_message = "check GlobalState exists"
return AppStateExpression(
key=self.resolve(),
wtype=self.pytype.content.wtype,
exists_assertion_message=exists_assertion_message,
source_location=location,
)
class _GlobalStateExpressionBuilderFromConstructor(
GlobalStateExpressionBuilder, StorageProxyConstructorResult
):
def __init__(
self,
key_override: Expression,
typ: pytypes.StorageProxyType,
description: str | None,
initial_value: InstanceBuilder | None,
):
self._key_override = key_override
super().__init__(key_override, typ, member_name=None)
self.description = description
self._initial_value = initial_value
@typing.override
@property
def initial_value(self) -> InstanceBuilder | None:
return self._initial_value
@typing.override
def resolve(self) -> Expression:
if self._initial_value is not None:
logger.error(
"providing an initial value is only allowed when assigning to a member variable",
location=self.source_location,
)
return super().resolve()
@typing.override
def build_definition(
self,
member_name: str,
defined_in: ContractReference,
typ: pytypes.PyType,
location: SourceLocation,
) -> AppStorageDeclaration:
key_override = self._key_override
if not isinstance(key_override, BytesConstant):
logger.error(
f"assigning {typ} to a member variable requires a constant value for key",
location=location,
)
key_override = BytesConstant(
value=b"",
wtype=wtypes.box_key,
encoding=BytesEncoding.unknown,
source_location=key_override.source_location,
)
return AppStorageDeclaration(
description=self.description,
member_name=member_name,
key_override=key_override,
source_location=location,
typ=typ,
defined_in=defined_in,
)
class _MemberFunction(FunctionBuilder, abc.ABC):
def __init__(self, base: GlobalStateExpressionBuilder, location: SourceLocation):
super().__init__(location)
self._base = base
class _Maybe(_MemberFunction):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
content_typ = self._base.pytype.content
expect.no_args(args, location)
field = _build_field(self._base, self.source_location)
expr = StateGetEx(field=field, source_location=location)
result_typ = pytypes.GenericTupleType.parameterise(
[content_typ, pytypes.BoolType], location
)
return TupleExpressionBuilder(expr, result_typ)
class _Get(_MemberFunction):
@typing.override
def call(
self,
args: Sequence[NodeBuilder],
arg_kinds: list[mypy.nodes.ArgKind],
arg_names: list[str | None],
location: SourceLocation,
) -> InstanceBuilder:
content_typ = self._base.pytype.content
default_arg = expect.exactly_one_arg_of_type_else_dummy(args, content_typ, location)
default_expr = default_arg.resolve()
field = _build_field(self._base, self.source_location)
expr = StateGet(field=field, default=default_expr, source_location=location)
return builder_for_instance(content_typ, expr)
class _Value(ValueProxyExpressionBuilder[pytypes.PyType, AppStateExpression]):
@typing.override
def delete(self, location: SourceLocation) -> Statement:
return ExpressionStatement(StateDelete(field=self.resolve(), source_location=location))