-
Notifications
You must be signed in to change notification settings - Fork 1
/
variables.py
293 lines (232 loc) · 9.9 KB
/
variables.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
from __future__ import annotations
import ctypes
import math
from dataclasses import dataclass
from typing import Any
from custom_exceptions import StackEmptyError, StackOverflowError, InvalidNumberTypeError
from enums import NumberType
from singleton import singleton
@dataclass
class NumberVariable:
number_type: NumberType
name: str | None
class VariableWatch:
_variable_counter: int = 0
_variables: dict[int | str, Any] = {}
def __init__(self):
self._variable_counter = 0
self._variables = {}
def __getitem__(self, item):
if isinstance(item, str) and not item.startswith('$'):
item = '$' + item
return self._variables[item]
def add_variable(self, value, name=None) -> None:
if not (name is not None and isinstance(name, str) and name.startswith('~')):
self._variables[self._variable_counter] = value
self._variable_counter += 1
if name is not None:
if isinstance(name, str) and not name.startswith('$'):
name = '$' + name
self._variables[name] = value
def __setitem__(self, key: str | int, value):
if isinstance(key, int):
self._variables[key] = value
else:
if key.startswith('$'):
key = key[1:]
self._variables['$' + key] = value
def __contains__(self, item: str | int) -> bool:
if isinstance(item, str) and not item.startswith('$'):
item = '$' + item
return item in self._variables
@singleton
class Stack:
_stacks: list[list[Any]] = [[]]
_stack_size: int = 1024
@property
def _current_stack(self) -> list[Any]:
return self._stacks[-1]
def init(self, stack_size: int = 1024):
self._stacks = [[]]
self._stack_size = stack_size
def pop(self) -> Any:
if self.get_total_size() == 0:
raise StackEmptyError()
if len(self._current_stack) == 0:
return self.get_previous_stack().pop()
return self._current_stack.pop()
def push(self, value: Any) -> None:
if self.get_total_size() == self._stack_size:
raise StackOverflowError(self._stack_size)
self._current_stack.append(value)
def __getitem__(self, item: int) -> Any:
return self._current_stack[-item - 1]
def __del__(self):
self._stacks = [[]]
def __len__(self):
return len(self._current_stack)
def expand(self, size: int):
self._current_stack += [None] * size
def contract(self, size: int):
self._current_stack = self._current_stack[:-size]
def size_to(self, size: int):
if len(self._current_stack) > size:
self.contract(len(self._current_stack) - size)
elif len(self._current_stack) < size:
self.expand(size - len(self._current_stack))
@_current_stack.setter
def _current_stack(self, value):
self._stacks[-1] = value
def push_stack(self):
self._stacks.append([])
def pop_stack(self):
old_stack = self._stacks.pop()
if len(self._stacks) != 0:
self._current_stack += old_stack
def get_previous_stack(self):
return self._stacks[-2]
def get_total_size(self) -> int:
return sum([len(stack) for stack in self._stacks])
@dataclass
class FixedNumber:
_value: int | float
number_type: NumberType
def __post_init__(self) -> None:
if self._value is not None:
self._value = assert_number_type(self._value, self.number_type)
@property
def value(self) -> int | float:
return self._value
@property
def unsigned_value(self) -> int:
if self.number_type in [NumberType.f32, NumberType.f64]:
return self._value
if self.number_type == NumberType.i32:
mask = 0x80000000
else:
mask = 0x8000000000000000
return (self._value & (mask - 1)) + (self._value & mask)
@value.setter
def value(self, new_value: int | float):
self._value = assert_number_type(new_value, self.number_type)
def __str__(self):
return str(self._value)
def __eq__(self, other: FixedNumber):
if not isinstance(other, FixedNumber):
raise TypeError(f"Cannot compare FixedNumber with {other.__class__.__name__}")
if self.number_type != other.number_type:
raise InvalidNumberTypeError(self, other.number_type)
return self.value == other.value
def __abs__(self) -> int | float:
return self.unsigned_value
@staticmethod
def can_be_reprezented_in_32_bits(number: int):
return -2147483648 <= number <= 2147483647
@staticmethod
def can_be_reprezented_in_64_bits(number: int):
return -9223372036854775808 <= number <= 9223372036854775807
def assert_number_type(number: int | float, number_type: NumberType) -> int | float:
def can_be_represented_in_32_bits(f: float):
numerator, denominator = f.as_integer_ratio()
gcd = math.gcd(numerator, denominator)
if gcd != 1:
return False
return -2147483648 <= numerator <= 2147483647 and -2147483648 <= denominator <= 2147483647
if number_type == NumberType.v128:
return number
# Type checking
if (number_type == NumberType.i32 or number_type == NumberType.i64) and not isinstance(number, int):
raise InvalidNumberTypeError(FixedNumber(number, None), number_type)
elif (number_type == NumberType.f32 or number_type == NumberType.f64) and not (
isinstance(number, float) or isinstance(number, int)):
raise InvalidNumberTypeError(FixedNumber(number, None), number_type)
# Overflow
if number_type == NumberType.i32:
number = (number & 0x7FFFFFFF) + (number & 0x80000000) * (1 if number > 0 else -1)
elif number_type == NumberType.i64:
number = (number & 0x7FFFFFFFFFFFFFFF) + (number & 0x8000000000000000) * (1 if number > 0 else -1)
elif number_type == NumberType.f32 and not can_be_represented_in_32_bits(number):
number = ctypes.c_float(number)
return number
@dataclass()
class GlobalVariable:
mutable: bool
value: FixedNumber
@singleton
class GlobalVariableWatch:
_variable_counter: int = 0
_variables: dict[int | str, GlobalVariable] = {}
def __init__(self):
self._variable_counter = 0
self._variables = {}
def __getitem__(self, item):
if isinstance(item, str) and not item.startswith('$'):
item = '$' + item
return self._variables[item]
def add_variable(self, value, mutable: bool, name=None) -> None:
self._variables[self._variable_counter] = GlobalVariable(mutable, value)
self._variable_counter += 1
if name is not None:
if isinstance(name, str) and not name.startswith('$'):
name = '$' + name
self._variables[name] = GlobalVariable(mutable, value)
def __setitem__(self, key: str | int, value):
if isinstance(key, int):
self._variables[key].value = value
else:
if key.startswith('$'):
key = key[1:]
self._variables['$' + key].value = value
def __contains__(self, item: str | int) -> bool:
if isinstance(item, str) and not item.startswith('$'):
item = '$' + item
return item in self._variables
@singleton
class Memory:
PAGE_SIZE = 65536
_memory: bytearray = bytearray()
def __init__(self, pages: int = 1):
super().__init__()
self._memory = bytearray(pages * self.PAGE_SIZE)
def grow(self, pages: int):
self._memory += bytearray(pages * self.PAGE_SIZE)
@property
def allocated(self):
return len(self._memory) // self.PAGE_SIZE
def __setitem__(self, index: int, value: FixedNumber):
if index < 0:
raise IndexError(f"Cannot access memory at negative index {index}")
if index >= len(self._memory):
raise IndexError(f"Cannot access memory at index {index} because it is out of bounds")
if value.number_type == NumberType.i32:
for byte_index in range(4):
self._memory[index + byte_index] = (value.unsigned_value >> (8 * byte_index)) & 0xFF
elif value.number_type == NumberType.i64:
for byte_index in range(8):
self._memory[index + byte_index] = (value.unsigned_value >> (8 * byte_index)) & 0xFF
elif value.number_type == NumberType.f32:
for byte_index in range(4):
self._memory[index + byte_index] = (value.value >> (8 * byte_index)) & 0xFF
elif value.number_type == NumberType.f64:
for byte_index in range(8):
self._memory[index + byte_index] = (value.value >> (8 * byte_index)) & 0xFF
def __getitem__(self, index_tuple: tuple[int, NumberType]) -> FixedNumber:
index, number_type = index_tuple
if index < 0:
raise IndexError(f"Cannot access memory at negative index {index}")
if index >= len(self._memory):
raise IndexError(f"Cannot access memory at index {index} because it is out of bounds")
if number_type == NumberType.i32:
return FixedNumber(int.from_bytes(self._memory[index:index + 4], byteorder='little', signed=True),
NumberType.i32)
elif number_type == NumberType.i64:
return FixedNumber(int.from_bytes(self._memory[index:index + 8], byteorder='little', signed=True),
NumberType.i64)
elif number_type == NumberType.f32:
return FixedNumber(
ctypes.c_float(int.from_bytes(self._memory[index:index + 4], byteorder='little', signed=True)).value,
NumberType.f32)
elif number_type == NumberType.f64:
return FixedNumber(
ctypes.c_double(int.from_bytes(self._memory[index:index + 8], byteorder='little', signed=True)).value,
NumberType.f64)