forked from APrioriInvestments/typed_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_wrapper.py
More file actions
237 lines (194 loc) · 9.33 KB
/
Copy pathclass_wrapper.py
File metadata and controls
237 lines (194 loc) · 9.33 KB
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
# Copyright 2018 Braxton Mckee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from nativepython.type_wrappers.refcounted_wrapper import RefcountedWrapper
from nativepython.type_wrappers.exceptions import generateThrowException
import nativepython.type_wrappers.runtime_functions as runtime_functions
from typed_python import NoneType, _types
import nativepython.native_ast as native_ast
import nativepython
typeWrapper = lambda x: nativepython.python_object_representation.typedPythonTypeToTypeWrapper(x)
class ClassWrapper(RefcountedWrapper):
is_pod = False
is_empty = False
is_pass_by_ref = True
def __init__(self, t):
super().__init__(t)
self.nameToIndex = {}
self.indexToByteOffset = {}
self.classType = t
element_types = [('refcount', native_ast.Int64), ('data', native_ast.UInt8)]
# this follows the general layout of 'held class' which is 1 bit per field for initialization and then
# each field packed directly according to byte size
byteOffset = 8 + (len(self.classType.MemberNames) // 8 + 1)
self.bytesOfInitBits = byteOffset - 8
for i, name in enumerate(self.classType.MemberNames):
self.nameToIndex[name] = i
self.indexToByteOffset[i] = byteOffset
byteOffset += _types.bytecount(self.classType.MemberTypes[i])
self.layoutType = native_ast.Type.Struct(element_types=element_types, name=t.__qualname__+"Layout").pointer()
def getNativeLayoutType(self):
return self.layoutType
def on_refcount_zero(self, context, instance):
return (
context.converter.defineNativeFunction(
"destructor_" + str(self.typeRepresentation),
('destructor', self),
[self],
typeWrapper(NoneType),
self.generateNativeDestructorFunction
)
.call(instance)
)
def generateNativeDestructorFunction(self, context, out, instance):
for i in range(len(self.typeRepresentation.MemberTypes)):
if not typeWrapper(self.typeRepresentation.MemberTypes[i]).is_pod:
with context.ifelse(context.pushPod(bool, self.isInitializedNativeExpr(instance, i))) as (true_block, false_block):
with true_block:
context.pushEffect(
self.convert_attribute(context, instance, i, nocheck=True).convert_destroy()
)
context.pushEffect(runtime_functions.free.call(instance.nonref_expr.cast(native_ast.UInt8Ptr)))
def memberPtr(self, instance, ix):
return (
instance
.nonref_expr.cast(native_ast.UInt8.pointer())
.ElementPtrIntegers(self.indexToByteOffset[ix])
.cast(
typeWrapper(self.typeRepresentation.MemberTypes[ix])
.getNativeLayoutType()
.pointer()
)
)
def isInitializedNativeExpr(self, instance, ix):
byte = ix // 8
bit = ix % 8
return (
instance.nonref_expr
.cast(native_ast.UInt8.pointer())
.ElementPtrIntegers(8 + byte)
.load()
.rshift(native_ast.const_uint8_expr(bit))
.bitand(native_ast.const_uint8_expr(1))
)
def setIsInitializedExpr(self, instance, ix):
byte = ix // 8
bit = ix % 8
bytePtr = (
instance.nonref_expr
.cast(native_ast.UInt8.pointer())
.ElementPtrIntegers(8 + byte)
)
return bytePtr.store(bytePtr.load().bitor(native_ast.const_uint8_expr(1 << bit)))
def convert_attribute(self, context, instance, attribute, nocheck=False):
if attribute in self.typeRepresentation.MemberFunctions:
methodType = typeWrapper(_types.BoundMethod(self.typeRepresentation, self.typeRepresentation.MemberFunctions[attribute]))
return instance.changeType(methodType)
if not isinstance(attribute, int):
ix = self.nameToIndex.get(attribute)
else:
ix = attribute
if ix is None:
return context.pushTerminal(
generateThrowException(context, AttributeError("Attribute %s doesn't exist in %s" % (attribute, self.typeRepresentation)))
)
if nocheck:
return context.pushReference(
self.typeRepresentation.MemberTypes[ix],
self.memberPtr(instance, ix)
)
return context.pushReference(
self.typeRepresentation.MemberTypes[ix],
native_ast.Expression.Branch(
cond=self.isInitializedNativeExpr(instance, ix),
false=generateThrowException(context, AttributeError("Attribute %s is not initialized" % attribute)),
true=self.memberPtr(instance, ix)
)
)
def convert_set_attribute(self, context, instance, attribute, value):
if not isinstance(attribute, int):
ix = self.nameToIndex.get(attribute)
else:
ix = attribute
if ix is None:
return context.pushTerminal(
generateThrowException(context, AttributeError("Attribute %s doesn't exist in %s" % (attribute, self.typeRepresentation)))
)
attr_type = typeWrapper(self.typeRepresentation.MemberTypes[ix])
if attr_type.is_pod:
return context.pushEffect(
self.memberPtr(instance, ix).store(value.nonref_expr)
>> self.setIsInitializedExpr(instance, ix)
)
else:
member = context.pushReference(attr_type, self.memberPtr(instance, ix))
with context.ifelse(context.pushPod(bool, self.isInitializedNativeExpr(instance, ix))) as (true_block, false_block):
with true_block:
member.convert_assign(value)
with false_block:
member.convert_copy_initialize(value)
context.pushEffect(
self.setIsInitializedExpr(instance, ix)
)
return native_ast.nullExpr
def convert_type_call(self, context, typeInst, args, kwargs):
if kwargs:
raise NotImplementedError("can't kwargs-initialize a class yet")
return context.push(
self,
lambda new_class:
context.converter.defineNativeFunction(
'construct(' + self.typeRepresentation.__name__ + ")(" + ",".join([a.expr_type.typeRepresentation.__name__ for a in args]) + ")",
('util', self, 'construct', tuple([a.expr_type for a in args])),
[a.expr_type for a in args],
self,
self.generateConstructor
).call(new_class, *args)
)
def generateConstructor(self, context, out, *args):
context.pushEffect(
out.expr.store(
runtime_functions.malloc.call(native_ast.const_int_expr(_types.bytecount(self.typeRepresentation.HeldClass) + 8))
.cast(self.getNativeLayoutType())
) >>
# store a refcount
out.expr.load().ElementPtrIntegers(0, 0).store(native_ast.const_int_expr(1))
)
# clear bits of init flags
for byteOffset in range(self.bytesOfInitBits):
context.pushEffect(
out.nonref_expr
.cast(native_ast.UInt8.pointer())
.ElementPtrIntegers(8 + byteOffset).store(native_ast.const_uint8_expr(0))
)
for i in range(len(self.classType.MemberTypes)):
if _types.wantsToDefaultConstruct(self.classType.MemberTypes[i]):
name = self.classType.MemberNames[i]
if name in self.classType.MemberDefaultValues:
defVal = self.classType.MemberDefaultValues.get(name)
context.pushReference(self.classType.MemberTypes[i], self.memberPtr(out, i)).convert_copy_initialize(
nativepython.python_object_representation.pythonObjectRepresentation(context, defVal)
)
else:
context.pushReference(self.classType.MemberTypes[i], self.memberPtr(out, i)).convert_default_initialize()
context.pushEffect(self.setIsInitializedExpr(out, i))
if '__init__' in self.typeRepresentation.MemberFunctions:
initFuncType = typeWrapper(self.typeRepresentation.MemberFunctions['__init__'])
initFuncType.convert_call(context, context.pushVoid(initFuncType), (out,) + args, {})
else:
if len(args):
context.pushException(
TypeError,
"Can't construct a " + self.typeRepresentation.__qualname__ +
" with positional arguments because it doesn't have an __init__"
)