| 1 |
import weakref |
| 2 |
from types import MethodType, NoneType |
| 3 |
|
| 4 |
from rpython.annotator.bookkeeper import analyzer_for, immutablevalue |
| 5 |
from rpython.annotator.model import ( |
| 6 |
AnnotatorError, SomeBool, SomeInteger, SomeObject) |
| 7 |
from rpython.rlib.objectmodel import Symbolic |
| 8 |
from rpython.rlib.rarithmetic import ( |
| 9 |
base_int, intmask, is_emulated_long, is_valid_int, longlonglongmask, |
| 10 |
longlongmask, maxint, normalizedinttype, r_int, r_longfloat, r_longlong, |
| 11 |
r_longlonglong, r_singlefloat, r_uint, r_ulonglong, r_ulonglonglong) |
| 12 |
from rpython.rtyper.extregistry import ExtRegistryEntry |
| 13 |
from rpython.tool import leakfinder |
| 14 |
from rpython.tool.identity_dict import identity_dict |
| 15 |
|
| 16 |
class State(object): |
| 17 |
pass |
| 18 |
|
| 19 |
TLS = State() |
| 20 |
|
| 21 |
class WeakValueDictionary(weakref.WeakValueDictionary): |
| 22 |
"""A subclass of weakref.WeakValueDictionary |
| 23 |
which resets the 'nested_hash_level' when keys are being deleted. |
| 24 |
""" |
| 25 |
def __init__(self, *args, **kwargs): |
| 26 |
weakref.WeakValueDictionary.__init__(self, *args, **kwargs) |
| 27 |
remove_base = self._remove |
| 28 |
def remove(*args): |
| 29 |
if safe_equal is None: |
| 30 |
|
| 31 |
|
| 32 |
return |
| 33 |
if TLS is None: |
| 34 |
return remove_base(*args) |
| 35 |
nested_hash_level = TLS.nested_hash_level |
| 36 |
try: |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
TLS.nested_hash_level = 0 |
| 44 |
remove_base(*args) |
| 45 |
finally: |
| 46 |
TLS.nested_hash_level = nested_hash_level |
| 47 |
self._remove = remove |
| 48 |
|
| 49 |
class _uninitialized(object): |
| 50 |
def __init__(self, TYPE): |
| 51 |
|
| 52 |
self.TYPE = TYPE |
| 53 |
def __repr__(self): |
| 54 |
return '<Uninitialized %r>'%(self.TYPE,) |
| 55 |
|
| 56 |
|
| 57 |
def saferecursive(func, defl, TLS=TLS): |
| 58 |
def safe(*args): |
| 59 |
try: |
| 60 |
seeing = TLS.seeing |
| 61 |
except AttributeError: |
| 62 |
seeing = TLS.seeing = {} |
| 63 |
seeingkey = tuple([func] + [id(arg) for arg in args]) |
| 64 |
if seeingkey in seeing: |
| 65 |
return defl |
| 66 |
seeing[seeingkey] = True |
| 67 |
try: |
| 68 |
return func(*args) |
| 69 |
finally: |
| 70 |
del seeing[seeingkey] |
| 71 |
return safe |
| 72 |
|
| 73 |
|
| 74 |
def safe_equal(x, y, TLS=TLS): |
| 75 |
|
| 76 |
try: |
| 77 |
seeing = TLS.seeing_eq |
| 78 |
except AttributeError: |
| 79 |
seeing = TLS.seeing_eq = {} |
| 80 |
seeingkey = (id(x), id(y)) |
| 81 |
if seeingkey in seeing: |
| 82 |
return True |
| 83 |
seeing[seeingkey] = True |
| 84 |
try: |
| 85 |
return x == y |
| 86 |
finally: |
| 87 |
del seeing[seeingkey] |
| 88 |
|
| 89 |
|
| 90 |
class frozendict(dict): |
| 91 |
|
| 92 |
def __hash__(self): |
| 93 |
items = self.items() |
| 94 |
items.sort() |
| 95 |
return hash(tuple(items)) |
| 96 |
|
| 97 |
|
| 98 |
class LowLevelType(object): |
| 99 |
|
| 100 |
|
| 101 |
__slots__ = ['__dict__', '__cached_hash'] |
| 102 |
|
| 103 |
def __eq__(self, other): |
| 104 |
if isinstance(other, Typedef): |
| 105 |
return other.__eq__(self) |
| 106 |
return self.__class__ is other.__class__ and ( |
| 107 |
self is other or safe_equal(self.__dict__, other.__dict__)) |
| 108 |
|
| 109 |
def __ne__(self, other): |
| 110 |
return not (self == other) |
| 111 |
|
| 112 |
_is_compatible = __eq__ |
| 113 |
|
| 114 |
def __setattr__(self, attr, nvalue): |
| 115 |
try: |
| 116 |
LowLevelType.__cached_hash.__get__(self) |
| 117 |
except AttributeError: |
| 118 |
pass |
| 119 |
else: |
| 120 |
try: |
| 121 |
reprself = repr(self) |
| 122 |
except: |
| 123 |
try: |
| 124 |
reprself = str(self) |
| 125 |
except: |
| 126 |
reprself = object.__repr__(self) |
| 127 |
raise AssertionError("%s: changing the field %r but we already " |
| 128 |
"computed the hash" % (reprself, attr)) |
| 129 |
object.__setattr__(self, attr, nvalue) |
| 130 |
|
| 131 |
def _enforce(self, value): |
| 132 |
if typeOf(value) != self: |
| 133 |
raise TypeError |
| 134 |
return value |
| 135 |
|
| 136 |
def __hash__(self, TLS=TLS): |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
hash_level = 0 |
| 142 |
try: |
| 143 |
hash_level = TLS.nested_hash_level |
| 144 |
if hash_level == 0: |
| 145 |
return self.__cached_hash |
| 146 |
except AttributeError: |
| 147 |
pass |
| 148 |
if hash_level >= 3: |
| 149 |
return 0 |
| 150 |
items = self.__dict__.items() |
| 151 |
items.sort() |
| 152 |
TLS.nested_hash_level = hash_level + 1 |
| 153 |
try: |
| 154 |
result = hash((self.__class__,) + tuple(items)) |
| 155 |
finally: |
| 156 |
TLS.nested_hash_level = hash_level |
| 157 |
if hash_level == 0: |
| 158 |
self.__cached_hash = result |
| 159 |
return result |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
__hash_is_not_constant__ = True |
| 165 |
|
| 166 |
def __repr__(self): |
| 167 |
return '<%s>' % (self,) |
| 168 |
|
| 169 |
def __str__(self): |
| 170 |
return self.__class__.__name__ |
| 171 |
|
| 172 |
def _short_name(self): |
| 173 |
return str(self) |
| 174 |
|
| 175 |
def _defl(self, parent=None, parentindex=None): |
| 176 |
raise NotImplementedError |
| 177 |
|
| 178 |
def _allocate(self, initialization, parent=None, parentindex=None): |
| 179 |
assert initialization in ('raw', 'malloc', 'example') |
| 180 |
raise NotImplementedError |
| 181 |
|
| 182 |
def _freeze_(self): |
| 183 |
return True |
| 184 |
|
| 185 |
def _note_inlined_into(self, parent, first, last): |
| 186 |
"""Called when this type is being used inline in a container.""" |
| 187 |
|
| 188 |
def _is_atomic(self): |
| 189 |
return False |
| 190 |
|
| 191 |
def _is_varsize(self): |
| 192 |
return False |
| 193 |
|
| 194 |
def _contains_value(self, value): |
| 195 |
if self is Void: |
| 196 |
return True |
| 197 |
return isCompatibleType(typeOf(value), self) |
| 198 |
|
| 199 |
NFOUND = object() |
| 200 |
|
| 201 |
class ContainerType(LowLevelType): |
| 202 |
_adtmeths = {} |
| 203 |
|
| 204 |
def _note_inlined_into(self, parent, first, last): |
| 205 |
raise TypeError("%r cannot be inlined in %r" % ( |
| 206 |
self.__class__.__name__, parent.__class__.__name__)) |
| 207 |
|
| 208 |
def _install_extras(self, adtmeths={}, hints={}): |
| 209 |
self._adtmeths = frozendict(adtmeths) |
| 210 |
self._hints = frozendict(hints) |
| 211 |
|
| 212 |
def __getattr__(self, name): |
| 213 |
adtmeth = self._adtmeths.get(name, NFOUND) |
| 214 |
if adtmeth is not NFOUND: |
| 215 |
if getattr(adtmeth, '_type_method', False): |
| 216 |
return adtmeth.__get__(self) |
| 217 |
else: |
| 218 |
return adtmeth |
| 219 |
self._nofield(name) |
| 220 |
|
| 221 |
def _nofield(self, name): |
| 222 |
raise AttributeError("no field %r" % name) |
| 223 |
|
| 224 |
def _container_example(self): |
| 225 |
raise NotImplementedError |
| 226 |
|
| 227 |
|
| 228 |
class Typedef(LowLevelType): |
| 229 |
"""A typedef is just another name for an existing type""" |
| 230 |
def __init__(self, OF, c_name): |
| 231 |
""" |
| 232 |
@param OF: the equivalent rffi type |
| 233 |
@param c_name: the name we want in C code |
| 234 |
""" |
| 235 |
assert isinstance(OF, LowLevelType) |
| 236 |
|
| 237 |
if isinstance(OF, Typedef): |
| 238 |
OF = OF.OF |
| 239 |
self.OF = OF |
| 240 |
self.c_name = c_name |
| 241 |
|
| 242 |
def __repr__(self): |
| 243 |
return '<Typedef "%s" of %r>' % (self.c_name, self.OF) |
| 244 |
|
| 245 |
def __eq__(self, other): |
| 246 |
return other == self.OF |
| 247 |
|
| 248 |
def __getattr__(self, name): |
| 249 |
return self.OF.get(name) |
| 250 |
|
| 251 |
def _defl(self, parent=None, parentindex=None): |
| 252 |
return self.OF._defl() |
| 253 |
|
| 254 |
def _allocate(self, initialization, parent=None, parentindex=None): |
| 255 |
return self.OF._allocate(initialization, parent, parentindex) |
| 256 |
|
| 257 |
|
| 258 |
class Struct(ContainerType): |
| 259 |
_gckind = 'raw' |
| 260 |
|
| 261 |
def __init__(self, name, *fields, **kwds): |
| 262 |
self._name = self.__name__ = name |
| 263 |
flds = {} |
| 264 |
names = [] |
| 265 |
self._arrayfld = None |
| 266 |
for name, typ in fields: |
| 267 |
if name.startswith('_'): |
| 268 |
raise NameError("%s: field name %r should not start with " |
| 269 |
"an underscore" % (self._name, name,)) |
| 270 |
names.append(name) |
| 271 |
if name in flds: |
| 272 |
raise TypeError("%s: repeated field name" % self._name) |
| 273 |
flds[name] = typ |
| 274 |
if isinstance(typ, ContainerType) and typ._gckind != 'raw': |
| 275 |
if name == fields[0][0] and typ._gckind == self._gckind: |
| 276 |
pass |
| 277 |
else: |
| 278 |
raise TypeError("%s: cannot inline %s container %r" % ( |
| 279 |
self._name, typ._gckind, typ)) |
| 280 |
|
| 281 |
|
| 282 |
if fields: |
| 283 |
first = True |
| 284 |
for name, typ in fields[:-1]: |
| 285 |
typ._note_inlined_into(self, first=first, last=False) |
| 286 |
first = False |
| 287 |
name, typ = fields[-1] |
| 288 |
typ._note_inlined_into(self, first=first, last=True) |
| 289 |
if typ._is_varsize(): |
| 290 |
self._arrayfld = name |
| 291 |
self._flds = frozendict(flds) |
| 292 |
self._names = tuple(names) |
| 293 |
|
| 294 |
self._install_extras(**kwds) |
| 295 |
|
| 296 |
def _first_struct(self): |
| 297 |
if self._names: |
| 298 |
first = self._names[0] |
| 299 |
FIRSTTYPE = self._flds[first] |
| 300 |
if (isinstance(FIRSTTYPE, Struct) and |
| 301 |
self._gckind == FIRSTTYPE._gckind): |
| 302 |
return first, FIRSTTYPE |
| 303 |
return None, None |
| 304 |
|
| 305 |
def _note_inlined_into(self, parent, first, last): |
| 306 |
if self._arrayfld is not None: |
| 307 |
raise TypeError("cannot inline a var-sized struct " |
| 308 |
"inside another container") |
| 309 |
if self._gckind == 'gc': |
| 310 |
if not first or not isinstance(parent, GcStruct): |
| 311 |
raise TypeError("a GcStruct can only be inlined as the first " |
| 312 |
"field of another GcStruct") |
| 313 |
|
| 314 |
def _is_atomic(self): |
| 315 |
for typ in self._flds.values(): |
| 316 |
if not typ._is_atomic(): |
| 317 |
return False |
| 318 |
return True |
| 319 |
|
| 320 |
def _is_varsize(self): |
| 321 |
return self._arrayfld is not None |
| 322 |
|
| 323 |
def __getattr__(self, name): |
| 324 |
try: |
| 325 |
return self._flds[name] |
| 326 |
except KeyError: |
| 327 |
return ContainerType.__getattr__(self, name) |
| 328 |
|
| 329 |
def _nofield(self, name): |
| 330 |
raise AttributeError('struct %s has no field %r' % (self._name, |
| 331 |
name)) |
| 332 |
|
| 333 |
def _names_without_voids(self): |
| 334 |
return [name for name in self._names if self._flds[name] is not Void] |
| 335 |
|
| 336 |
def _str_fields_without_voids(self): |
| 337 |
return ', '.join(['%s: %s' % (name, self._flds[name]) |
| 338 |
for name in self._names_without_voids(False)]) |
| 339 |
_str_fields_without_voids = saferecursive(_str_fields_without_voids, '...') |
| 340 |
|
| 341 |
def _str_without_voids(self): |
| 342 |
return "%s %s { %s }" % (self.__class__.__name__, |
| 343 |
self._name, self._str_fields_without_voids()) |
| 344 |
|
| 345 |
def _str_fields(self): |
| 346 |
return ', '.join(['%s: %s' % (name, self._flds[name]) |
| 347 |
for name in self._names]) |
| 348 |
_str_fields = saferecursive(_str_fields, '...') |
| 349 |
|
| 350 |
def __str__(self): |
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
return "%s %s { %s }" % (self.__class__.__name__, self._name, |
| 356 |
', '.join(self._names)) |
| 357 |
|
| 358 |
def _short_name(self): |
| 359 |
return "%s %s" % (self.__class__.__name__, self._name) |
| 360 |
|
| 361 |
def _allocate(self, initialization, parent=None, parentindex=None): |
| 362 |
return _struct(self, initialization=initialization, |
| 363 |
parent=parent, parentindex=parentindex) |
| 364 |
|
| 365 |
def _container_example(self): |
| 366 |
if self._arrayfld is None: |
| 367 |
n = None |
| 368 |
else: |
| 369 |
n = 1 |
| 370 |
return _struct(self, n, initialization='example') |
| 371 |
|
| 372 |
def _immutable_field(self, field): |
| 373 |
if self._hints.get('immutable'): |
| 374 |
return True |
| 375 |
if 'immutable_fields' in self._hints: |
| 376 |
try: |
| 377 |
return self._hints['immutable_fields'].fields[field] |
| 378 |
except KeyError: |
| 379 |
pass |
| 380 |
return False |
| 381 |
|
| 382 |
class RttiStruct(Struct): |
| 383 |
_runtime_type_info = None |
| 384 |
|
| 385 |
def _install_extras(self, rtti=False, **kwds): |
| 386 |
if rtti: |
| 387 |
self._runtime_type_info = opaqueptr(RuntimeTypeInfo, |
| 388 |
name=self._name, |
| 389 |
about=self)._obj |
| 390 |
Struct._install_extras(self, **kwds) |
| 391 |
|
| 392 |
def _attach_runtime_type_info_funcptr(self, funcptr, destrptr): |
| 393 |
if self._runtime_type_info is None: |
| 394 |
raise TypeError("attachRuntimeTypeInfo: %r must have been built " |
| 395 |
"with the rtti=True argument" % (self,)) |
| 396 |
if funcptr is not None: |
| 397 |
T = typeOf(funcptr) |
| 398 |
if (not isinstance(T, Ptr) or |
| 399 |
not isinstance(T.TO, FuncType) or |
| 400 |
len(T.TO.ARGS) != 1 or |
| 401 |
T.TO.RESULT != Ptr(RuntimeTypeInfo) or |
| 402 |
castable(T.TO.ARGS[0], Ptr(self)) < 0): |
| 403 |
raise TypeError("expected a runtime type info function " |
| 404 |
"implementation, got: %s" % funcptr) |
| 405 |
self._runtime_type_info.query_funcptr = funcptr |
| 406 |
if destrptr is not None: |
| 407 |
T = typeOf(destrptr) |
| 408 |
if (not isinstance(T, Ptr) or |
| 409 |
not isinstance(T.TO, FuncType) or |
| 410 |
len(T.TO.ARGS) != 1 or |
| 411 |
T.TO.RESULT != Void or |
| 412 |
castable(T.TO.ARGS[0], Ptr(self)) < 0): |
| 413 |
raise TypeError("expected a destructor function " |
| 414 |
"implementation, got: %s" % destrptr) |
| 415 |
self._runtime_type_info.destructor_funcptr = destrptr |
| 416 |
|
| 417 |
class GcStruct(RttiStruct): |
| 418 |
_gckind = 'gc' |
| 419 |
|
| 420 |
STRUCT_BY_FLAVOR = {'raw': Struct, |
| 421 |
'gc': GcStruct} |
| 422 |
|
| 423 |
class Array(ContainerType): |
| 424 |
_gckind = 'raw' |
| 425 |
__name__ = 'array' |
| 426 |
_anonym_struct = False |
| 427 |
|
| 428 |
def __init__(self, *fields, **kwds): |
| 429 |
if len(fields) == 1 and isinstance(fields[0], LowLevelType): |
| 430 |
self.OF = fields[0] |
| 431 |
else: |
| 432 |
self.OF = Struct("<arrayitem>", *fields) |
| 433 |
self._anonym_struct = True |
| 434 |
if isinstance(self.OF, ContainerType) and self.OF._gckind != 'raw': |
| 435 |
raise TypeError("cannot have a %s container as array item type" |
| 436 |
% (self.OF._gckind,)) |
| 437 |
self.OF._note_inlined_into(self, first=False, last=False) |
| 438 |
|
| 439 |
self._install_extras(**kwds) |
| 440 |
|
| 441 |
def _note_inlined_into(self, parent, first, last): |
| 442 |
if not last or not isinstance(parent, Struct): |
| 443 |
raise TypeError("cannot inline an array in another container" |
| 444 |
" unless as the last field of a structure") |
| 445 |
if self._gckind == 'gc': |
| 446 |
raise TypeError("cannot inline a GC array inside a structure") |
| 447 |
if parent._gckind == 'gc' and self._hints.get('nolength', False): |
| 448 |
raise TypeError("cannot inline a no-length array inside a GcStruct") |
| 449 |
|
| 450 |
def _is_atomic(self): |
| 451 |
return self.OF._is_atomic() |
| 452 |
|
| 453 |
def _is_varsize(self): |
| 454 |
return True |
| 455 |
|
| 456 |
def _str_fields(self): |
| 457 |
if isinstance(self.OF, Struct): |
| 458 |
of = self.OF |
| 459 |
if self._anonym_struct: |
| 460 |
return "{ %s }" % of._str_fields() |
| 461 |
else: |
| 462 |
return "%s { %s }" % (of._name, of._str_fields()) |
| 463 |
elif self._hints.get('render_as_void'): |
| 464 |
return 'void' |
| 465 |
else: |
| 466 |
return str(self.OF) |
| 467 |
_str_fields = saferecursive(_str_fields, '...') |
| 468 |
|
| 469 |
def __str__(self): |
| 470 |
hints = (' ' + str(self._hints)) if self._hints else '' |
| 471 |
return "%s of %s%s " % (self.__class__.__name__, |
| 472 |
self._str_fields(), |
| 473 |
hints) |
| 474 |
|
| 475 |
def _short_name(self): |
| 476 |
hints = (' ' + str(self._hints)) if self._hints else '' |
| 477 |
return "%s %s%s" % (self.__class__.__name__, |
| 478 |
self.OF._short_name(), |
| 479 |
hints) |
| 480 |
_short_name = saferecursive(_short_name, '...') |
| 481 |
|
| 482 |
def _container_example(self): |
| 483 |
return _array(self, 1, initialization='example') |
| 484 |
|
| 485 |
def _immutable_field(self, index=None): |
| 486 |
return self._hints.get('immutable', False) |
| 487 |
|
| 488 |
class GcArray(Array): |
| 489 |
_gckind = 'gc' |
| 490 |
|
| 491 |
class FixedSizeArray(Struct): |
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
_cache = WeakValueDictionary() |
| 496 |
def __new__(cls, OF, length, **kwds): |
| 497 |
if length == 1 and not kwds: |
| 498 |
try: |
| 499 |
obj = FixedSizeArray._cache[OF] |
| 500 |
except KeyError: |
| 501 |
obj = FixedSizeArray._cache[OF] = Struct.__new__(cls) |
| 502 |
except TypeError: |
| 503 |
obj = Struct.__new__(cls) |
| 504 |
else: |
| 505 |
obj = Struct.__new__(cls) |
| 506 |
return obj |
| 507 |
|
| 508 |
def __init__(self, OF, length, **kwds): |
| 509 |
if '_name' in self.__dict__: |
| 510 |
assert self.OF == OF |
| 511 |
assert self.length == length |
| 512 |
return |
| 513 |
fields = [('item%d' % i, OF) for i in range(length)] |
| 514 |
super(FixedSizeArray, self).__init__('array%d' % length, *fields, |
| 515 |
**kwds) |
| 516 |
self.OF = OF |
| 517 |
self.length = length |
| 518 |
if isinstance(self.OF, ContainerType) and self.OF._gckind != 'raw': |
| 519 |
raise TypeError("cannot have a %s container as array item type" |
| 520 |
% (self.OF._gckind,)) |
| 521 |
self.OF._note_inlined_into(self, first=False, last=False) |
| 522 |
|
| 523 |
def _str_fields(self): |
| 524 |
return str(self.OF) |
| 525 |
_str_fields = saferecursive(_str_fields, '...') |
| 526 |
|
| 527 |
def __str__(self): |
| 528 |
return "%s of %d %s " % (self.__class__.__name__, |
| 529 |
self.length, |
| 530 |
self._str_fields(),) |
| 531 |
|
| 532 |
def _short_name(self): |
| 533 |
return "%s %d %s" % (self.__class__.__name__, |
| 534 |
self.length, |
| 535 |
self.OF._short_name(),) |
| 536 |
_short_name = saferecursive(_short_name, '...') |
| 537 |
|
| 538 |
def _first_struct(self): |
| 539 |
|
| 540 |
return None, None |
| 541 |
|
| 542 |
|
| 543 |
class FuncType(ContainerType): |
| 544 |
_gckind = 'raw' |
| 545 |
__name__ = 'func' |
| 546 |
def __init__(self, args, result, abi='FFI_DEFAULT_ABI'): |
| 547 |
for arg in args: |
| 548 |
assert isinstance(arg, LowLevelType) |
| 549 |
|
| 550 |
|
| 551 |
self.ARGS = tuple(args) |
| 552 |
assert isinstance(result, LowLevelType) |
| 553 |
if isinstance(result, ContainerType): |
| 554 |
raise TypeError("function result can only be primitive or pointer") |
| 555 |
self.RESULT = result |
| 556 |
self.ABI = abi |
| 557 |
|
| 558 |
def __str__(self): |
| 559 |
args = ', '.join(map(str, self.ARGS)) |
| 560 |
return "Func ( %s ) -> %s" % (args, self.RESULT) |
| 561 |
__str__ = saferecursive(__str__, '...') |
| 562 |
|
| 563 |
def _short_name(self): |
| 564 |
args = ', '.join([ARG._short_name() for ARG in self.ARGS]) |
| 565 |
return "Func(%s)->%s" % (args, self.RESULT._short_name()) |
| 566 |
_short_name = saferecursive(_short_name, '...') |
| 567 |
|
| 568 |
def _container_example(self): |
| 569 |
def ex(*args): |
| 570 |
return self.RESULT._defl() |
| 571 |
return _func(self, _callable=ex) |
| 572 |
|
| 573 |
def _trueargs(self): |
| 574 |
return [arg for arg in self.ARGS if arg is not Void] |
| 575 |
|
| 576 |
|
| 577 |
class OpaqueType(ContainerType): |
| 578 |
_gckind = 'raw' |
| 579 |
|
| 580 |
def __init__(self, tag, hints={}): |
| 581 |
"""If hints['render_structure'] is set, the type is internal and |
| 582 |
not considered to come from somewhere else (it should be |
| 583 |
rendered as a structure) |
| 584 |
""" |
| 585 |
self.tag = tag |
| 586 |
self.__name__ = tag |
| 587 |
self._hints = frozendict(hints) |
| 588 |
|
| 589 |
def __str__(self): |
| 590 |
return "%s (opaque)" % self.tag |
| 591 |
|
| 592 |
def _note_inlined_into(self, parent, first, last): |
| 593 |
|
| 594 |
if self._gckind == 'gc': |
| 595 |
raise TypeError("%r cannot be inlined in %r" % ( |
| 596 |
self.__class__.__name__, parent.__class__.__name__)) |
| 597 |
|
| 598 |
def _container_example(self): |
| 599 |
return _opaque(self) |
| 600 |
|
| 601 |
def _defl(self, parent=None, parentindex=None): |
| 602 |
return _opaque(self, parent=parent, parentindex=parentindex) |
| 603 |
|
| 604 |
def _allocate(self, initialization, parent=None, parentindex=None): |
| 605 |
return self._defl(parent=parent, parentindex=parentindex) |
| 606 |
|
| 607 |
RuntimeTypeInfo = OpaqueType("RuntimeTypeInfo") |
| 608 |
|
| 609 |
class GcOpaqueType(OpaqueType): |
| 610 |
_gckind = 'gc' |
| 611 |
|
| 612 |
def __str__(self): |
| 613 |
return "%s (gcopaque)" % self.tag |
| 614 |
|
| 615 |
class ForwardReference(ContainerType): |
| 616 |
_gckind = 'raw' |
| 617 |
def become(self, realcontainertype): |
| 618 |
if not isinstance(realcontainertype, ContainerType): |
| 619 |
raise TypeError("ForwardReference can only be to a container, " |
| 620 |
"not %r" % (realcontainertype,)) |
| 621 |
if realcontainertype._gckind != self._gckind: |
| 622 |
raise TypeError("become() gives conflicting gckind, use the " |
| 623 |
"correct XxForwardReference") |
| 624 |
self.__class__ = realcontainertype.__class__ |
| 625 |
self.__dict__ = realcontainertype.__dict__ |
| 626 |
|
| 627 |
def __hash__(self): |
| 628 |
raise TypeError("%r object is not hashable" % self.__class__.__name__) |
| 629 |
|
| 630 |
class GcForwardReference(ForwardReference): |
| 631 |
_gckind = 'gc' |
| 632 |
|
| 633 |
|
| 634 |
class FuncForwardReference(ForwardReference): |
| 635 |
_gckind = 'prebuilt' |
| 636 |
|
| 637 |
FORWARDREF_BY_FLAVOR = {'raw': ForwardReference, |
| 638 |
'gc': GcForwardReference, |
| 639 |
'prebuilt': FuncForwardReference} |
| 640 |
|
| 641 |
|
| 642 |
class Primitive(LowLevelType): |
| 643 |
def __init__(self, name, default): |
| 644 |
self._name = self.__name__ = name |
| 645 |
self._default = default |
| 646 |
|
| 647 |
def __str__(self): |
| 648 |
return self._name |
| 649 |
|
| 650 |
def _defl(self, parent=None, parentindex=None): |
| 651 |
return self._default |
| 652 |
|
| 653 |
def _allocate(self, initialization, parent=None, parentindex=None): |
| 654 |
if self is not Void and initialization != 'example': |
| 655 |
return _uninitialized(self) |
| 656 |
else: |
| 657 |
return self._default |
| 658 |
|
| 659 |
def _is_atomic(self): |
| 660 |
return True |
| 661 |
|
| 662 |
def _example(self, parent=None, parentindex=None): |
| 663 |
return self._default |
| 664 |
|
| 665 |
class Number(Primitive): |
| 666 |
|
| 667 |
def __init__(self, name, type, cast=None): |
| 668 |
Primitive.__init__(self, name, type()) |
| 669 |
self._type = type |
| 670 |
if cast is None: |
| 671 |
self._cast = type |
| 672 |
else: |
| 673 |
self._cast = cast |
| 674 |
|
| 675 |
def normalized(self): |
| 676 |
return build_number(None, normalizedinttype(self._type)) |
| 677 |
|
| 678 |
|
| 679 |
_numbertypes = {int: Number("Signed", int, intmask)} |
| 680 |
_numbertypes[r_int] = _numbertypes[int] |
| 681 |
_numbertypes[r_longlonglong] = Number("SignedLongLongLong", r_longlonglong, |
| 682 |
longlonglongmask) |
| 683 |
|
| 684 |
if r_longlong is not r_int: |
| 685 |
_numbertypes[r_longlong] = Number("SignedLongLong", r_longlong, |
| 686 |
longlongmask) |
| 687 |
|
| 688 |
def build_number(name, type): |
| 689 |
try: |
| 690 |
return _numbertypes[type] |
| 691 |
except KeyError: |
| 692 |
pass |
| 693 |
if name is None: |
| 694 |
raise ValueError('No matching lowlevel type for %r'%type) |
| 695 |
number = _numbertypes[type] = Number(name, type) |
| 696 |
return number |
| 697 |
|
| 698 |
if is_emulated_long: |
| 699 |
SignedFmt = 'q' |
| 700 |
else: |
| 701 |
SignedFmt = 'l' |
| 702 |
|
| 703 |
Signed = build_number("Signed", int) |
| 704 |
Unsigned = build_number("Unsigned", r_uint) |
| 705 |
SignedLongLong = build_number("SignedLongLong", r_longlong) |
| 706 |
SignedLongLongLong = build_number("SignedLongLongLong", r_longlonglong) |
| 707 |
UnsignedLongLong = build_number("UnsignedLongLong", r_ulonglong) |
| 708 |
UnsignedLongLongLong = build_number("UnsignedLongLongLong", r_ulonglonglong) |
| 709 |
|
| 710 |
Float = Primitive("Float", 0.0) |
| 711 |
SingleFloat = Primitive("SingleFloat", r_singlefloat(0.0)) |
| 712 |
LongFloat = Primitive("LongFloat", r_longfloat(0.0)) |
| 713 |
r_singlefloat._TYPE = SingleFloat |
| 714 |
|
| 715 |
Char = Primitive("Char", '\x00') |
| 716 |
Bool = Primitive("Bool", False) |
| 717 |
Void = Primitive("Void", None) |
| 718 |
UniChar = Primitive("UniChar", u'\x00') |
| 719 |
|
| 720 |
|
| 721 |
class Ptr(LowLevelType): |
| 722 |
__name__ = property(lambda self: '%sPtr' % self.TO.__name__) |
| 723 |
|
| 724 |
_cache = WeakValueDictionary() |
| 725 |
def __new__(cls, TO, use_cache=True): |
| 726 |
if not isinstance(TO, ContainerType): |
| 727 |
raise TypeError("can only point to a Container type, " |
| 728 |
"not to %s" % (TO,)) |
| 729 |
if not use_cache: |
| 730 |
obj = LowLevelType.__new__(cls) |
| 731 |
else: |
| 732 |
try: |
| 733 |
return Ptr._cache[TO] |
| 734 |
except KeyError: |
| 735 |
obj = Ptr._cache[TO] = LowLevelType.__new__(cls) |
| 736 |
except TypeError: |
| 737 |
obj = LowLevelType.__new__(cls) |
| 738 |
obj.TO = TO |
| 739 |
return obj |
| 740 |
|
| 741 |
def _needsgc(self): |
| 742 |
|
| 743 |
return self.TO._gckind not in ('raw', 'prebuilt') |
| 744 |
|
| 745 |
def __str__(self): |
| 746 |
return '* %s' % (self.TO, ) |
| 747 |
|
| 748 |
def _short_name(self): |
| 749 |
return 'Ptr %s' % (self.TO._short_name(), ) |
| 750 |
|
| 751 |
def _is_atomic(self): |
| 752 |
return self.TO._gckind == 'raw' |
| 753 |
|
| 754 |
def _defl(self, parent=None, parentindex=None): |
| 755 |
return _ptr(self, None) |
| 756 |
|
| 757 |
def _allocate(self, initialization, parent=None, parentindex=None): |
| 758 |
if initialization == 'example': |
| 759 |
return _ptr(self, None) |
| 760 |
elif initialization == 'malloc' and self._needsgc(): |
| 761 |
return _ptr(self, None) |
| 762 |
else: |
| 763 |
return _uninitialized(self) |
| 764 |
|
| 765 |
def _example(self): |
| 766 |
o = self.TO._container_example() |
| 767 |
return _ptr(self, o, solid=True) |
| 768 |
|
| 769 |
def _interior_ptr_type_with_index(self, TO): |
| 770 |
assert self.TO._gckind == 'gc' |
| 771 |
if isinstance(TO, Struct): |
| 772 |
R = GcStruct("Interior", ('ptr', self), ('index', Signed), |
| 773 |
hints={'interior_ptr_type':True}, |
| 774 |
adtmeths=TO._adtmeths) |
| 775 |
else: |
| 776 |
R = GcStruct("Interior", ('ptr', self), ('index', Signed), |
| 777 |
hints={'interior_ptr_type':True}) |
| 778 |
return R |
| 779 |
|
| 780 |
@analyzer_for(Ptr) |
| 781 |
def constPtr(T): |
| 782 |
assert T.is_constant() |
| 783 |
return immutablevalue(Ptr(T.const)) |
| 784 |
|
| 785 |
|
| 786 |
class InteriorPtr(LowLevelType): |
| 787 |
def __init__(self, PARENTTYPE, TO, offsets): |
| 788 |
self.PARENTTYPE = PARENTTYPE |
| 789 |
self.TO = TO |
| 790 |
self.offsets = tuple(offsets) |
| 791 |
def __str__(self): |
| 792 |
return '%s (%s).%s'%(self.__class__.__name__, |
| 793 |
self.PARENTTYPE._short_name(), |
| 794 |
'.'.join(map(str, self.offsets))) |
| 795 |
def _example(self): |
| 796 |
ob = Ptr(self.PARENTTYPE)._example() |
| 797 |
for o in self.offsets: |
| 798 |
if isinstance(o, str): |
| 799 |
ob = getattr(ob, o) |
| 800 |
else: |
| 801 |
ob = ob[0] |
| 802 |
return ob |
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
def typeOf(val): |
| 808 |
try: |
| 809 |
return val._TYPE |
| 810 |
except AttributeError: |
| 811 |
tp = type(val) |
| 812 |
if tp is _uninitialized: |
| 813 |
raise UninitializedMemoryAccess("typeOf uninitialized value") |
| 814 |
if tp is NoneType: |
| 815 |
return Void |
| 816 |
if tp is int: |
| 817 |
return Signed |
| 818 |
if tp is long: |
| 819 |
if -maxint-1 <= val <= maxint: |
| 820 |
return Signed |
| 821 |
elif longlongmask(val) == val: |
| 822 |
raise OverflowError("integer %r is out of bounds for Signed " |
| 823 |
"(it would fit SignedLongLong, but we " |
| 824 |
"won't implicitly return SignedLongLong " |
| 825 |
"for typeOf(%r) where type(%r) is long)" |
| 826 |
% (val, val, val)) |
| 827 |
else: |
| 828 |
raise OverflowError("integer %r is out of bounds" % (val,)) |
| 829 |
if tp is bool: |
| 830 |
return Bool |
| 831 |
if issubclass(tp, base_int): |
| 832 |
return build_number(None, tp) |
| 833 |
if tp is float: |
| 834 |
return Float |
| 835 |
if tp is r_longfloat: |
| 836 |
return LongFloat |
| 837 |
if tp is str: |
| 838 |
assert len(val) == 1 |
| 839 |
return Char |
| 840 |
if tp is unicode: |
| 841 |
assert len(val) == 1 |
| 842 |
return UniChar |
| 843 |
if issubclass(tp, Symbolic): |
| 844 |
return val.lltype() |
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
raise TypeError("typeOf(%r object)" % (tp.__name__,)) |
| 849 |
|
| 850 |
@analyzer_for(typeOf) |
| 851 |
def ann_typeOf(s_val): |
| 852 |
from rpython.rtyper.llannotation import annotation_to_lltype |
| 853 |
lltype = annotation_to_lltype(s_val, info="in typeOf(): ") |
| 854 |
return immutablevalue(lltype) |
| 855 |
|
| 856 |
|
| 857 |
_to_primitive = { |
| 858 |
Char: chr, |
| 859 |
UniChar: unichr, |
| 860 |
Float: float, |
| 861 |
Bool: bool, |
| 862 |
} |
| 863 |
|
| 864 |
def cast_primitive(TGT, value): |
| 865 |
ORIG = typeOf(value) |
| 866 |
if not isinstance(TGT, Primitive) or not isinstance(ORIG, Primitive): |
| 867 |
raise TypeError("can only primitive to primitive") |
| 868 |
if ORIG == TGT: |
| 869 |
return value |
| 870 |
if ORIG == Char or ORIG == UniChar: |
| 871 |
value = ord(value) |
| 872 |
elif ORIG == Float: |
| 873 |
if TGT == SingleFloat: |
| 874 |
return r_singlefloat(value) |
| 875 |
elif TGT == LongFloat: |
| 876 |
return r_longfloat(value) |
| 877 |
value = long(value) |
| 878 |
cast = _to_primitive.get(TGT) |
| 879 |
if cast is not None: |
| 880 |
return cast(value) |
| 881 |
if isinstance(TGT, Number): |
| 882 |
return TGT._cast(value) |
| 883 |
if ORIG == SingleFloat and TGT == Float: |
| 884 |
return float(value) |
| 885 |
if ORIG == LongFloat and TGT == Float: |
| 886 |
return float(value) |
| 887 |
raise TypeError("unsupported cast") |
| 888 |
|
| 889 |
@analyzer_for(cast_primitive) |
| 890 |
def ann_cast_primitive(T, s_v): |
| 891 |
from rpython.rtyper.llannotation import ( |
| 892 |
annotation_to_lltype, ll_to_annotation) |
| 893 |
assert T.is_constant() |
| 894 |
return ll_to_annotation(cast_primitive(T.const, |
| 895 |
annotation_to_lltype(s_v)._defl())) |
| 896 |
|
| 897 |
|
| 898 |
def _cast_whatever(TGT, value): |
| 899 |
from rpython.rtyper.lltypesystem import llmemory, rffi |
| 900 |
ORIG = typeOf(value) |
| 901 |
if ORIG == TGT: |
| 902 |
return value |
| 903 |
if (isinstance(TGT, Primitive) and |
| 904 |
isinstance(ORIG, Primitive)): |
| 905 |
return cast_primitive(TGT, value) |
| 906 |
elif isinstance(TGT, Ptr): |
| 907 |
if isinstance(ORIG, Ptr): |
| 908 |
if (isinstance(TGT.TO, OpaqueType) or |
| 909 |
isinstance(ORIG.TO, OpaqueType)): |
| 910 |
return cast_opaque_ptr(TGT, value) |
| 911 |
else: |
| 912 |
return cast_pointer(TGT, value) |
| 913 |
elif ORIG == llmemory.Address: |
| 914 |
return llmemory.cast_adr_to_ptr(value, TGT) |
| 915 |
elif TGT == rffi.VOIDP and ORIG == Unsigned: |
| 916 |
return rffi.cast(TGT, value) |
| 917 |
elif ORIG == Signed: |
| 918 |
return cast_int_to_ptr(TGT, value) |
| 919 |
elif TGT == llmemory.Address and isinstance(ORIG, Ptr): |
| 920 |
return llmemory.cast_ptr_to_adr(value) |
| 921 |
elif TGT == Signed and isinstance(ORIG, Ptr) and ORIG.TO._gckind == 'raw': |
| 922 |
return llmemory.cast_adr_to_int(llmemory.cast_ptr_to_adr(value), |
| 923 |
'symbolic') |
| 924 |
raise TypeError("don't know how to cast from %r to %r" % (ORIG, TGT)) |
| 925 |
|
| 926 |
|
| 927 |
class InvalidCast(TypeError): |
| 928 |
pass |
| 929 |
|
| 930 |
def _castdepth(OUTSIDE, INSIDE): |
| 931 |
if OUTSIDE == INSIDE: |
| 932 |
return 0 |
| 933 |
dwn = 0 |
| 934 |
while isinstance(OUTSIDE, Struct): |
| 935 |
first, FIRSTTYPE = OUTSIDE._first_struct() |
| 936 |
if first is None: |
| 937 |
break |
| 938 |
dwn += 1 |
| 939 |
if FIRSTTYPE == INSIDE: |
| 940 |
return dwn |
| 941 |
OUTSIDE = getattr(OUTSIDE, first) |
| 942 |
return -1 |
| 943 |
|
| 944 |
def castable(PTRTYPE, CURTYPE): |
| 945 |
if CURTYPE.TO._gckind != PTRTYPE.TO._gckind: |
| 946 |
raise TypeError("cast_pointer() cannot change the gc status: %s to %s" |
| 947 |
% (CURTYPE, PTRTYPE)) |
| 948 |
if CURTYPE == PTRTYPE: |
| 949 |
return 0 |
| 950 |
if (not isinstance(CURTYPE.TO, Struct) or |
| 951 |
not isinstance(PTRTYPE.TO, Struct)): |
| 952 |
raise InvalidCast(CURTYPE, PTRTYPE) |
| 953 |
CURSTRUC = CURTYPE.TO |
| 954 |
PTRSTRUC = PTRTYPE.TO |
| 955 |
d = _castdepth(CURSTRUC, PTRSTRUC) |
| 956 |
if d >= 0: |
| 957 |
return d |
| 958 |
u = _castdepth(PTRSTRUC, CURSTRUC) |
| 959 |
if u == -1: |
| 960 |
raise InvalidCast(CURTYPE, PTRTYPE) |
| 961 |
return -u |
| 962 |
|
| 963 |
|
| 964 |
def cast_pointer(PTRTYPE, ptr): |
| 965 |
CURTYPE = typeOf(ptr) |
| 966 |
if not isinstance(CURTYPE, Ptr) or not isinstance(PTRTYPE, Ptr): |
| 967 |
raise TypeError("can only cast pointers to other pointers") |
| 968 |
return ptr._cast_to(PTRTYPE) |
| 969 |
|
| 970 |
@analyzer_for(cast_pointer) |
| 971 |
def ann_cast_pointer(PtrT, s_p): |
| 972 |
assert isinstance(s_p, SomePtr), "casting of non-pointer: %r" % s_p |
| 973 |
assert PtrT.is_constant() |
| 974 |
cast_p = cast_pointer(PtrT.const, s_p.ll_ptrtype._defl()) |
| 975 |
return SomePtr(ll_ptrtype=typeOf(cast_p)) |
| 976 |
|
| 977 |
|
| 978 |
def cast_opaque_ptr(PTRTYPE, ptr): |
| 979 |
CURTYPE = typeOf(ptr) |
| 980 |
if not isinstance(CURTYPE, Ptr) or not isinstance(PTRTYPE, Ptr): |
| 981 |
raise TypeError("can only cast pointers to other pointers") |
| 982 |
if CURTYPE == PTRTYPE: |
| 983 |
return ptr |
| 984 |
if CURTYPE.TO._gckind != PTRTYPE.TO._gckind: |
| 985 |
raise TypeError("cast_opaque_ptr() cannot change the gc status: " |
| 986 |
"%s to %s" % (CURTYPE, PTRTYPE)) |
| 987 |
if (isinstance(CURTYPE.TO, OpaqueType) |
| 988 |
and not isinstance(PTRTYPE.TO, OpaqueType)): |
| 989 |
if hasattr(ptr._obj, '_cast_to_ptr'): |
| 990 |
return ptr._obj._cast_to_ptr(PTRTYPE) |
| 991 |
if not ptr: |
| 992 |
return nullptr(PTRTYPE.TO) |
| 993 |
try: |
| 994 |
container = ptr._obj.container |
| 995 |
except AttributeError: |
| 996 |
raise InvalidCast("%r does not come from a container" % (ptr,)) |
| 997 |
solid = getattr(ptr._obj, 'solid', False) |
| 998 |
if isinstance(container, int): |
| 999 |
return _ptr(PTRTYPE, container, solid=True) |
| 1000 |
p = _ptr(Ptr(typeOf(container)), container, solid) |
| 1001 |
return cast_pointer(PTRTYPE, p) |
| 1002 |
elif (not isinstance(CURTYPE.TO, OpaqueType) |
| 1003 |
and isinstance(PTRTYPE.TO, OpaqueType)): |
| 1004 |
if hasattr(ptr, '_cast_to_opaque'): |
| 1005 |
return ptr._cast_to_opaque(PTRTYPE) |
| 1006 |
if not ptr: |
| 1007 |
return nullptr(PTRTYPE.TO) |
| 1008 |
return opaqueptr(PTRTYPE.TO, 'hidden', container = ptr._obj, |
| 1009 |
ORIGTYPE = CURTYPE, |
| 1010 |
solid = ptr._solid) |
| 1011 |
elif (isinstance(CURTYPE.TO, OpaqueType) |
| 1012 |
and isinstance(PTRTYPE.TO, OpaqueType)): |
| 1013 |
if not ptr: |
| 1014 |
return nullptr(PTRTYPE.TO) |
| 1015 |
try: |
| 1016 |
container = ptr._obj.container |
| 1017 |
except AttributeError: |
| 1018 |
raise InvalidCast("%r does not come from a container" % (ptr,)) |
| 1019 |
return opaqueptr(PTRTYPE.TO, 'hidden', |
| 1020 |
container = container, |
| 1021 |
solid = ptr._obj.solid) |
| 1022 |
else: |
| 1023 |
raise TypeError("invalid cast_opaque_ptr(): %r -> %r" % |
| 1024 |
(CURTYPE, PTRTYPE)) |
| 1025 |
|
| 1026 |
@analyzer_for(cast_opaque_ptr) |
| 1027 |
def ann_cast_opaque_ptr(PtrT, s_p): |
| 1028 |
assert isinstance(s_p, SomePtr), "casting of non-pointer: %r" % s_p |
| 1029 |
assert PtrT.is_constant() |
| 1030 |
cast_p = cast_opaque_ptr(PtrT.const, s_p.ll_ptrtype._defl()) |
| 1031 |
return SomePtr(ll_ptrtype=typeOf(cast_p)) |
| 1032 |
|
| 1033 |
|
| 1034 |
def length_of_simple_gcarray_from_opaque(opaque_ptr): |
| 1035 |
CURTYPE = typeOf(opaque_ptr) |
| 1036 |
if not isinstance(CURTYPE, Ptr): |
| 1037 |
raise TypeError("can only cast pointers to other pointers") |
| 1038 |
if not isinstance(CURTYPE.TO, GcOpaqueType): |
| 1039 |
raise TypeError("expected a GcOpaqueType") |
| 1040 |
try: |
| 1041 |
c = opaque_ptr._obj.container |
| 1042 |
except AttributeError: |
| 1043 |
|
| 1044 |
|
| 1045 |
from rpython.rtyper.lltypesystem import rffi |
| 1046 |
p = rffi.cast(Ptr(GcArray(Signed)), opaque_ptr) |
| 1047 |
return len(p) |
| 1048 |
else: |
| 1049 |
return c.getlength() |
| 1050 |
|
| 1051 |
@analyzer_for(length_of_simple_gcarray_from_opaque) |
| 1052 |
def ann_length_of_simple_gcarray_from_opaque(s_p): |
| 1053 |
assert isinstance(s_p, SomePtr), "casting of non-pointer: %r" % s_p |
| 1054 |
assert isinstance(s_p.ll_ptrtype.TO, GcOpaqueType) |
| 1055 |
return SomeInteger(nonneg=True) |
| 1056 |
|
| 1057 |
|
| 1058 |
def direct_fieldptr(structptr, fieldname): |
| 1059 |
"""Get a pointer to a field in the struct. The resulting |
| 1060 |
pointer is actually of type Ptr(FixedSizeArray(FIELD, 1)). |
| 1061 |
It can be used in a regular getarrayitem(0) or setarrayitem(0) |
| 1062 |
to read or write to the field. |
| 1063 |
""" |
| 1064 |
CURTYPE = typeOf(structptr).TO |
| 1065 |
if not isinstance(CURTYPE, Struct): |
| 1066 |
raise TypeError("direct_fieldptr: not a struct") |
| 1067 |
if fieldname not in CURTYPE._flds: |
| 1068 |
raise TypeError("%s has no field %r" % (CURTYPE, fieldname)) |
| 1069 |
if not structptr: |
| 1070 |
raise RuntimeError("direct_fieldptr: NULL argument") |
| 1071 |
return _subarray._makeptr(structptr._obj, fieldname, structptr._solid) |
| 1072 |
|
| 1073 |
@analyzer_for(direct_fieldptr) |
| 1074 |
def ann_direct_fieldptr(s_p, s_fieldname): |
| 1075 |
assert isinstance(s_p, SomePtr), "direct_* of non-pointer: %r" % s_p |
| 1076 |
assert s_fieldname.is_constant() |
| 1077 |
cast_p = direct_fieldptr(s_p.ll_ptrtype._example(), |
| 1078 |
s_fieldname.const) |
| 1079 |
return SomePtr(ll_ptrtype=typeOf(cast_p)) |
| 1080 |
|
| 1081 |
|
| 1082 |
def direct_arrayitems(arrayptr): |
| 1083 |
"""Get a pointer to the first item of the array. The resulting |
| 1084 |
pointer is actually of type Ptr(FixedSizeArray(ITEM, 1)) but can |
| 1085 |
be used in a regular getarrayitem(n) or direct_ptradd(n) to access |
| 1086 |
further elements. |
| 1087 |
""" |
| 1088 |
CURTYPE = typeOf(arrayptr).TO |
| 1089 |
if not isinstance(CURTYPE, (Array, FixedSizeArray)): |
| 1090 |
raise TypeError("direct_arrayitems: not an array") |
| 1091 |
if not arrayptr: |
| 1092 |
raise RuntimeError("direct_arrayitems: NULL argument") |
| 1093 |
return _subarray._makeptr(arrayptr._obj, 0, arrayptr._solid) |
| 1094 |
|
| 1095 |
@analyzer_for(direct_arrayitems) |
| 1096 |
def ann_direct_arrayitems(s_p): |
| 1097 |
assert isinstance(s_p, SomePtr), "direct_* of non-pointer: %r" % s_p |
| 1098 |
cast_p = direct_arrayitems(s_p.ll_ptrtype._example()) |
| 1099 |
return SomePtr(ll_ptrtype=typeOf(cast_p)) |
| 1100 |
|
| 1101 |
|
| 1102 |
def direct_ptradd(ptr, n): |
| 1103 |
"""Shift a pointer forward or backward by n items. The pointer must |
| 1104 |
have been built by direct_arrayitems(), or it must be directly a |
| 1105 |
pointer to a raw array with no length (handled by emulation with ctypes). |
| 1106 |
""" |
| 1107 |
if not ptr: |
| 1108 |
raise RuntimeError("direct_ptradd: NULL argument") |
| 1109 |
if not isinstance(ptr._obj, _subarray): |
| 1110 |
|
| 1111 |
from rpython.rtyper.lltypesystem import rffi |
| 1112 |
return rffi.ptradd(ptr, n) |
| 1113 |
parent, base = parentlink(ptr._obj) |
| 1114 |
return _subarray._makeptr(parent, base + n, ptr._solid) |
| 1115 |
|
| 1116 |
@analyzer_for(direct_ptradd) |
| 1117 |
def ann_direct_ptradd(s_p, s_n): |
| 1118 |
assert isinstance(s_p, SomePtr), "direct_* of non-pointer: %r" % s_p |
| 1119 |
|
| 1120 |
return s_p |
| 1121 |
|
| 1122 |
|
| 1123 |
def parentlink(container): |
| 1124 |
parent = container._parentstructure() |
| 1125 |
if parent is not None: |
| 1126 |
return parent, container._parent_index |
| 1127 |
else: |
| 1128 |
return None, None |
| 1129 |
|
| 1130 |
def top_container(container): |
| 1131 |
top_parent = container |
| 1132 |
while True: |
| 1133 |
parent = top_parent._parentstructure() |
| 1134 |
if parent is None: |
| 1135 |
break |
| 1136 |
top_parent = parent |
| 1137 |
return top_parent |
| 1138 |
|
| 1139 |
def normalizeptr(p, check=True): |
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
assert not isinstance(p, _container) |
| 1144 |
T = typeOf(p) |
| 1145 |
if not isinstance(T, Ptr): |
| 1146 |
return p |
| 1147 |
obj = p._getobj(check) |
| 1148 |
if not obj: |
| 1149 |
return None |
| 1150 |
if type(p._obj0) is int: |
| 1151 |
return p |
| 1152 |
if getattr(p._obj0, '_carry_around_for_tests', False): |
| 1153 |
return p |
| 1154 |
container = obj._normalizedcontainer() |
| 1155 |
if type(container) is int: |
| 1156 |
|
| 1157 |
assert isinstance(obj, _opaque) |
| 1158 |
return cast_int_to_ptr(obj.ORIGTYPE, container) |
| 1159 |
if container is not obj: |
| 1160 |
p = _ptr(Ptr(typeOf(container)), container, p._solid) |
| 1161 |
return p |
| 1162 |
|
| 1163 |
class DelayedPointer(Exception): |
| 1164 |
pass |
| 1165 |
|
| 1166 |
class UninitializedMemoryAccess(Exception): |
| 1167 |
pass |
| 1168 |
|
| 1169 |
class _abstract_ptr(object): |
| 1170 |
__slots__ = ('_T',) |
| 1171 |
|
| 1172 |
|
| 1173 |
|
| 1174 |
def _set_T(self, T): |
| 1175 |
_ptr._T.__set__(self, T) |
| 1176 |
|
| 1177 |
def _togckind(self): |
| 1178 |
return self._T._gckind |
| 1179 |
|
| 1180 |
def _needsgc(self): |
| 1181 |
|
| 1182 |
return self._TYPE._needsgc() |
| 1183 |
|
| 1184 |
def __eq__(self, other): |
| 1185 |
if type(self) is not type(other): |
| 1186 |
raise TypeError("comparing pointer with %r object" % ( |
| 1187 |
type(other).__name__,)) |
| 1188 |
if self._TYPE != other._TYPE: |
| 1189 |
raise TypeError("comparing %r and %r" % (self._TYPE, other._TYPE)) |
| 1190 |
try: |
| 1191 |
return self._obj == other._obj |
| 1192 |
except DelayedPointer: |
| 1193 |
|
| 1194 |
|
| 1195 |
return self is other |
| 1196 |
|
| 1197 |
def __ne__(self, other): |
| 1198 |
return not (self == other) |
| 1199 |
|
| 1200 |
def _same_obj(self, other): |
| 1201 |
return self._obj == other._obj |
| 1202 |
|
| 1203 |
def __hash__(self): |
| 1204 |
raise TypeError("pointer objects are not hashable") |
| 1205 |
|
| 1206 |
def __nonzero__(self): |
| 1207 |
try: |
| 1208 |
return self._obj is not None |
| 1209 |
except DelayedPointer: |
| 1210 |
return True |
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
def _setobj(self, pointing_to, solid=False): |
| 1215 |
if pointing_to is None: |
| 1216 |
obj0 = None |
| 1217 |
elif (solid or self._T._gckind != 'raw' or |
| 1218 |
isinstance(self._T, FuncType)): |
| 1219 |
obj0 = pointing_to |
| 1220 |
else: |
| 1221 |
self._set_weak(True) |
| 1222 |
obj0 = weakref.ref(pointing_to) |
| 1223 |
self._set_solid(solid) |
| 1224 |
self._set_obj0(obj0) |
| 1225 |
|
| 1226 |
def _getobj(self, check=True): |
| 1227 |
obj = self._obj0 |
| 1228 |
if obj is not None: |
| 1229 |
if self._weak: |
| 1230 |
obj = obj() |
| 1231 |
if obj is None: |
| 1232 |
raise RuntimeError("accessing already garbage collected %r" |
| 1233 |
% (self._T,)) |
| 1234 |
if isinstance(obj, _container): |
| 1235 |
if check: |
| 1236 |
obj._check() |
| 1237 |
elif isinstance(obj, str) and obj.startswith("delayed!"): |
| 1238 |
raise DelayedPointer |
| 1239 |
return obj |
| 1240 |
_obj = property(_getobj) |
| 1241 |
|
| 1242 |
def _was_freed(self): |
| 1243 |
return (type(self._obj0) not in (type(None), int) and |
| 1244 |
self._getobj(check=False)._was_freed()) |
| 1245 |
|
| 1246 |
def _lookup_adtmeth(self, member_name): |
| 1247 |
if isinstance(self._T, ContainerType): |
| 1248 |
try: |
| 1249 |
adtmember = self._T._adtmeths[member_name] |
| 1250 |
except KeyError: |
| 1251 |
pass |
| 1252 |
else: |
| 1253 |
try: |
| 1254 |
getter = adtmember.__get__ |
| 1255 |
except AttributeError: |
| 1256 |
return adtmember |
| 1257 |
else: |
| 1258 |
return getter(self) |
| 1259 |
raise AttributeError |
| 1260 |
|
| 1261 |
def __getattr__(self, field_name): |
| 1262 |
if isinstance(self._T, Struct): |
| 1263 |
if field_name in self._T._flds: |
| 1264 |
o = self._obj._getattr(field_name) |
| 1265 |
return self._expose(field_name, o) |
| 1266 |
try: |
| 1267 |
return self._lookup_adtmeth(field_name) |
| 1268 |
except AttributeError: |
| 1269 |
raise AttributeError("%r instance has no field %r" % (self._T, |
| 1270 |
field_name)) |
| 1271 |
|
| 1272 |
def __setattr__(self, field_name, val): |
| 1273 |
if isinstance(self._T, Struct): |
| 1274 |
if field_name in self._T._flds: |
| 1275 |
T1 = self._T._flds[field_name] |
| 1276 |
T2 = typeOf(val) |
| 1277 |
if T1 == T2: |
| 1278 |
setattr(self._obj, field_name, val) |
| 1279 |
else: |
| 1280 |
raise TypeError( |
| 1281 |
"%r instance field %r:\nexpects %r\n got %r" % |
| 1282 |
(self._T, field_name, T1, T2)) |
| 1283 |
return |
| 1284 |
raise AttributeError("%r instance has no field %r" % |
| 1285 |
(self._T, field_name)) |
| 1286 |
|
| 1287 |
def __getitem__(self, i): |
| 1288 |
if isinstance(self._T, (Array, FixedSizeArray)): |
| 1289 |
start, stop = self._obj.getbounds() |
| 1290 |
if not (start <= i < stop): |
| 1291 |
if isinstance(i, slice): |
| 1292 |
raise TypeError("array slicing not supported") |
| 1293 |
raise IndexError("array index out of bounds") |
| 1294 |
o = self._obj.getitem(i) |
| 1295 |
return self._expose(i, o) |
| 1296 |
raise TypeError("%r instance is not an array" % (self._T,)) |
| 1297 |
|
| 1298 |
def __setitem__(self, i, val): |
| 1299 |
if isinstance(self._T, (Array, FixedSizeArray)): |
| 1300 |
T1 = self._T.OF |
| 1301 |
if isinstance(T1, ContainerType): |
| 1302 |
raise TypeError("cannot directly assign to container array " |
| 1303 |
"items") |
| 1304 |
T2 = typeOf(val) |
| 1305 |
if T2 != T1: |
| 1306 |
from rpython.rtyper.lltypesystem import rffi |
| 1307 |
if T1 is rffi.VOIDP and isinstance(T2, Ptr): |
| 1308 |
|
| 1309 |
val = rffi.cast(rffi.VOIDP, val) |
| 1310 |
else: |
| 1311 |
raise TypeError("%r items:\n" |
| 1312 |
"expect %r\n" |
| 1313 |
" got %r" % (self._T, T1, T2)) |
| 1314 |
start, stop = self._obj.getbounds() |
| 1315 |
if not (start <= i < stop): |
| 1316 |
if isinstance(i, slice): |
| 1317 |
raise TypeError("array slicing not supported") |
| 1318 |
raise IndexError("array index out of bounds") |
| 1319 |
self._obj.setitem(i, val) |
| 1320 |
return |
| 1321 |
raise TypeError("%r instance is not an array" % (self._T,)) |
| 1322 |
|
| 1323 |
def __len__(self): |
| 1324 |
if isinstance(self._T, (Array, FixedSizeArray)): |
| 1325 |
if self._T._hints.get('nolength', False): |
| 1326 |
raise TypeError("%r instance has no length attribute" % |
| 1327 |
(self._T,)) |
| 1328 |
return self._obj.getlength() |
| 1329 |
raise TypeError("%r instance is not an array" % (self._T,)) |
| 1330 |
|
| 1331 |
def _fixedlength(self): |
| 1332 |
length = len(self) |
| 1333 |
if isinstance(self._T, FixedSizeArray): |
| 1334 |
return length |
| 1335 |
else: |
| 1336 |
return None |
| 1337 |
|
| 1338 |
def __repr__(self): |
| 1339 |
return '<%s>' % (self,) |
| 1340 |
|
| 1341 |
def __str__(self): |
| 1342 |
try: |
| 1343 |
return '* %s' % (self._obj, ) |
| 1344 |
except RuntimeError: |
| 1345 |
return '* DEAD %s' % self._T |
| 1346 |
except DelayedPointer: |
| 1347 |
return '* %s' % (self._obj0,) |
| 1348 |
|
| 1349 |
def __call__(self, *args): |
| 1350 |
from rpython.rtyper.lltypesystem import rffi |
| 1351 |
if isinstance(self._T, FuncType): |
| 1352 |
if len(args) != len(self._T.ARGS): |
| 1353 |
raise TypeError("calling %r with wrong argument number: %r" % |
| 1354 |
(self._T, args)) |
| 1355 |
for i, a, ARG in zip(range(len(self._T.ARGS)), args, self._T.ARGS): |
| 1356 |
if typeOf(a) != ARG: |
| 1357 |
|
| 1358 |
if ARG == Void: |
| 1359 |
try: |
| 1360 |
value = getattr(self._obj, '_void' + str(i)) |
| 1361 |
except AttributeError: |
| 1362 |
pass |
| 1363 |
else: |
| 1364 |
assert a == value |
| 1365 |
|
| 1366 |
elif isinstance(ARG, Ptr) and a is None: |
| 1367 |
pass |
| 1368 |
|
| 1369 |
elif ARG is rffi.VOIDP and isinstance(typeOf(a), Ptr): |
| 1370 |
pass |
| 1371 |
|
| 1372 |
|
| 1373 |
|
| 1374 |
elif (isinstance(ARG, ContainerType) and |
| 1375 |
typeOf(a) == Ptr(ARG)): |
| 1376 |
pass |
| 1377 |
else: |
| 1378 |
args_repr = [typeOf(arg) for arg in args] |
| 1379 |
raise TypeError("calling %r with wrong argument " |
| 1380 |
"types: %r" % (self._T, args_repr)) |
| 1381 |
callb = self._obj._callable |
| 1382 |
if callb is None: |
| 1383 |
raise RuntimeError("calling undefined function") |
| 1384 |
return callb(*args) |
| 1385 |
raise TypeError("%r instance is not a function" % (self._T,)) |
| 1386 |
|
| 1387 |
def _identityhash(self): |
| 1388 |
p = normalizeptr(self) |
| 1389 |
assert self._T._gckind == 'gc' |
| 1390 |
assert self |
| 1391 |
return hash(p._obj) |
| 1392 |
|
| 1393 |
class _ptr(_abstract_ptr): |
| 1394 |
__slots__ = ('_TYPE', |
| 1395 |
'_weak', '_solid', |
| 1396 |
'_obj0', '__weakref__') |
| 1397 |
|
| 1398 |
def _set_TYPE(self, TYPE): |
| 1399 |
_ptr._TYPE.__set__(self, TYPE) |
| 1400 |
|
| 1401 |
def _set_weak(self, weak): |
| 1402 |
_ptr._weak.__set__(self, weak) |
| 1403 |
|
| 1404 |
def _set_solid(self, solid): |
| 1405 |
_ptr._solid.__set__(self, solid) |
| 1406 |
|
| 1407 |
def _set_obj0(self, obj): |
| 1408 |
_ptr._obj0.__set__(self, obj) |
| 1409 |
|
| 1410 |
def __init__(self, TYPE, pointing_to, solid=False): |
| 1411 |
self._set_TYPE(TYPE) |
| 1412 |
self._set_T(TYPE.TO) |
| 1413 |
self._set_weak(False) |
| 1414 |
self._setobj(pointing_to, solid) |
| 1415 |
|
| 1416 |
def _become(self, other): |
| 1417 |
assert self._TYPE == other._TYPE |
| 1418 |
assert not self._weak |
| 1419 |
self._setobj(other._obj, other._solid) |
| 1420 |
|
| 1421 |
def _cast_to(self, PTRTYPE): |
| 1422 |
CURTYPE = self._TYPE |
| 1423 |
down_or_up = castable(PTRTYPE, CURTYPE) |
| 1424 |
if down_or_up == 0: |
| 1425 |
return self |
| 1426 |
if not self: |
| 1427 |
return PTRTYPE._defl() |
| 1428 |
if isinstance(self._obj, int): |
| 1429 |
return _ptr(PTRTYPE, self._obj, solid=True) |
| 1430 |
if down_or_up > 0: |
| 1431 |
p = self |
| 1432 |
while down_or_up: |
| 1433 |
p = getattr(p, typeOf(p).TO._names[0]) |
| 1434 |
down_or_up -= 1 |
| 1435 |
return _ptr(PTRTYPE, p._obj, solid=self._solid) |
| 1436 |
u = -down_or_up |
| 1437 |
struc = self._obj |
| 1438 |
while u: |
| 1439 |
parent = struc._parentstructure() |
| 1440 |
if parent is None: |
| 1441 |
raise RuntimeError("widening to trash: %r" % self) |
| 1442 |
PARENTTYPE = struc._parent_type |
| 1443 |
if getattr(parent, PARENTTYPE._names[0]) != struc: |
| 1444 |
|
| 1445 |
raise InvalidCast(CURTYPE, PTRTYPE) |
| 1446 |
struc = parent |
| 1447 |
u -= 1 |
| 1448 |
if PARENTTYPE != PTRTYPE.TO: |
| 1449 |
raise RuntimeError("widening %r inside %r instead of %r" % |
| 1450 |
(CURTYPE, PARENTTYPE, PTRTYPE.TO)) |
| 1451 |
return _ptr(PTRTYPE, struc, solid=self._solid) |
| 1452 |
|
| 1453 |
def _cast_to_int(self, check=True): |
| 1454 |
obj = self._getobj(check) |
| 1455 |
if not obj: |
| 1456 |
return 0 |
| 1457 |
if isinstance(obj, int): |
| 1458 |
return obj |
| 1459 |
obj = normalizeptr(self, check)._getobj(check) |
| 1460 |
if isinstance(obj, int): |
| 1461 |
|
| 1462 |
|
| 1463 |
return obj |
| 1464 |
if getattr(obj, '_read_directly_intval', False): |
| 1465 |
return obj.intval |
| 1466 |
result = intmask(obj._getid()) |
| 1467 |
|
| 1468 |
|
| 1469 |
|
| 1470 |
|
| 1471 |
if self._T._gckind == 'gc': |
| 1472 |
assert result != 0 and (result & 3) == 0 |
| 1473 |
return result |
| 1474 |
|
| 1475 |
def _cast_to_adr(self): |
| 1476 |
from rpython.rtyper.lltypesystem import llmemory |
| 1477 |
if isinstance(self._T, FuncType): |
| 1478 |
return llmemory.fakeaddress(self) |
| 1479 |
elif self._was_freed(): |
| 1480 |
|
| 1481 |
from rpython.rtyper.lltypesystem import llarena |
| 1482 |
return llarena._oldobj_to_address(self._getobj(check=False)) |
| 1483 |
elif isinstance(self._obj, _subarray): |
| 1484 |
return llmemory.fakeaddress(self) |
| 1485 |
|
| 1486 |
|
| 1487 |
|
| 1488 |
|
| 1489 |
|
| 1490 |
|
| 1491 |
else: |
| 1492 |
|
| 1493 |
return llmemory.fakeaddress(normalizeptr(self)) |
| 1494 |
|
| 1495 |
def _as_ptr(self): |
| 1496 |
return self |
| 1497 |
def _as_obj(self, check=True): |
| 1498 |
return self._getobj(check=check) |
| 1499 |
|
| 1500 |
def _expose(self, offset, val): |
| 1501 |
"""XXX A nice docstring here""" |
| 1502 |
T = typeOf(val) |
| 1503 |
if isinstance(T, ContainerType): |
| 1504 |
if (self._T._gckind == 'gc' and T._gckind == 'raw' and |
| 1505 |
not isinstance(T, OpaqueType)): |
| 1506 |
val = _interior_ptr(T, self._obj, [offset]) |
| 1507 |
else: |
| 1508 |
val = _ptr(Ptr(T), val, solid=self._solid) |
| 1509 |
return val |
| 1510 |
|
| 1511 |
assert not '__dict__' in dir(_ptr) |
| 1512 |
|
| 1513 |
class _ptrEntry(ExtRegistryEntry): |
| 1514 |
_type_ = _ptr |
| 1515 |
|
| 1516 |
def compute_annotation(self): |
| 1517 |
from rpython.rtyper.llannotation import SomePtr |
| 1518 |
return SomePtr(typeOf(self.instance)) |
| 1519 |
|
| 1520 |
class SomePtr(SomeObject): |
| 1521 |
knowntype = _ptr |
| 1522 |
immutable = True |
| 1523 |
|
| 1524 |
def __init__(self, ll_ptrtype): |
| 1525 |
assert isinstance(ll_ptrtype, Ptr) |
| 1526 |
self.ll_ptrtype = ll_ptrtype |
| 1527 |
|
| 1528 |
def can_be_none(self): |
| 1529 |
return False |
| 1530 |
|
| 1531 |
def getattr(self, s_attr): |
| 1532 |
from rpython.rtyper.llannotation import SomeLLADTMeth, ll_to_annotation |
| 1533 |
if not s_attr.is_constant(): |
| 1534 |
raise AnnotatorError("getattr on ptr %r with non-constant " |
| 1535 |
"field-name" % self.ll_ptrtype) |
| 1536 |
example = self.ll_ptrtype._example() |
| 1537 |
try: |
| 1538 |
v = example._lookup_adtmeth(s_attr.const) |
| 1539 |
except AttributeError: |
| 1540 |
v = getattr(example, s_attr.const) |
| 1541 |
return ll_to_annotation(v) |
| 1542 |
else: |
| 1543 |
if isinstance(v, MethodType): |
| 1544 |
ll_ptrtype = typeOf(v.im_self) |
| 1545 |
assert isinstance(ll_ptrtype, (Ptr, InteriorPtr)) |
| 1546 |
return SomeLLADTMeth(ll_ptrtype, v.im_func) |
| 1547 |
return immutablevalue(v) |
| 1548 |
getattr.can_only_throw = [] |
| 1549 |
|
| 1550 |
def len(self): |
| 1551 |
length = self.ll_ptrtype._example()._fixedlength() |
| 1552 |
if length is None: |
| 1553 |
return SomeObject.len(self) |
| 1554 |
else: |
| 1555 |
return immutablevalue(length) |
| 1556 |
|
| 1557 |
def setattr(self, s_attr, s_value): |
| 1558 |
from rpython.rtyper.llannotation import annotation_to_lltype |
| 1559 |
if not s_attr.is_constant(): |
| 1560 |
raise AnnotatorError("setattr on ptr %r with non-constant " |
| 1561 |
"field-name" % self.ll_ptrtype) |
| 1562 |
example = self.ll_ptrtype._example() |
| 1563 |
if getattr(example, s_attr.const) is not None: |
| 1564 |
v_lltype = annotation_to_lltype(s_value) |
| 1565 |
setattr(example, s_attr.const, v_lltype._defl()) |
| 1566 |
|
| 1567 |
def call(self, args): |
| 1568 |
from rpython.rtyper.llannotation import ( |
| 1569 |
annotation_to_lltype, ll_to_annotation) |
| 1570 |
args_s, kwds_s = args.unpack() |
| 1571 |
if kwds_s: |
| 1572 |
raise Exception("keyword arguments to call to a low-level fn ptr") |
| 1573 |
info = 'argument to ll function pointer call' |
| 1574 |
llargs = [annotation_to_lltype(s_arg, info)._defl() |
| 1575 |
for s_arg in args_s] |
| 1576 |
v = self.ll_ptrtype._example()(*llargs) |
| 1577 |
return ll_to_annotation(v) |
| 1578 |
|
| 1579 |
def bool(self): |
| 1580 |
result = SomeBool() |
| 1581 |
if self.is_constant(): |
| 1582 |
result.const = bool(self.const) |
| 1583 |
return result |
| 1584 |
|
| 1585 |
|
| 1586 |
class _interior_ptr(_abstract_ptr): |
| 1587 |
__slots__ = ('_parent', '_offsets') |
| 1588 |
def _set_parent(self, _parent): |
| 1589 |
_interior_ptr._parent.__set__(self, _parent) |
| 1590 |
def _set_offsets(self, _offsets): |
| 1591 |
_interior_ptr._offsets.__set__(self, _offsets) |
| 1592 |
|
| 1593 |
def __init__(self, _T, _parent, _offsets): |
| 1594 |
self._set_T(_T) |
| 1595 |
|
| 1596 |
self._set_parent(_parent) |
| 1597 |
self._set_offsets(_offsets) |
| 1598 |
|
| 1599 |
def __nonzero__(self): |
| 1600 |
raise RuntimeError("do not test an interior pointer for nullity") |
| 1601 |
|
| 1602 |
def _get_obj(self): |
| 1603 |
ob = self._parent |
| 1604 |
if ob is None: |
| 1605 |
raise RuntimeError |
| 1606 |
if isinstance(ob, _container): |
| 1607 |
ob._check() |
| 1608 |
for o in self._offsets: |
| 1609 |
if isinstance(o, str): |
| 1610 |
ob = ob._getattr(o) |
| 1611 |
else: |
| 1612 |
ob = ob.getitem(o) |
| 1613 |
return ob |
| 1614 |
_obj = property(_get_obj) |
| 1615 |
|
| 1616 |
def _get_TYPE(self): |
| 1617 |
ob = self._parent |
| 1618 |
if ob is None: |
| 1619 |
raise RuntimeError |
| 1620 |
return InteriorPtr(typeOf(ob), self._T, self._offsets) |
| 1621 |
|
| 1622 |
|
| 1623 |
def _expose(self, offset, val): |
| 1624 |
"""XXX A nice docstring here""" |
| 1625 |
T = typeOf(val) |
| 1626 |
if isinstance(T, ContainerType): |
| 1627 |
assert T._gckind == 'raw' |
| 1628 |
val = _interior_ptr(T, self._parent, self._offsets + [offset]) |
| 1629 |
return val |
| 1630 |
|
| 1631 |
|
| 1632 |
assert not '__dict__' in dir(_interior_ptr) |
| 1633 |
|
| 1634 |
class _container(object): |
| 1635 |
__slots__ = () |
| 1636 |
def _parentstructure(self, check=True): |
| 1637 |
return None |
| 1638 |
def _check(self): |
| 1639 |
pass |
| 1640 |
def _as_ptr(self): |
| 1641 |
return _ptr(Ptr(self._TYPE), self, True) |
| 1642 |
def _as_obj(self, check=True): |
| 1643 |
return self |
| 1644 |
def _normalizedcontainer(self, check=True): |
| 1645 |
return self |
| 1646 |
def _getid(self): |
| 1647 |
return id(self) |
| 1648 |
def _was_freed(self): |
| 1649 |
return False |
| 1650 |
|
| 1651 |
class _parentable(_container): |
| 1652 |
_kind = "?" |
| 1653 |
|
| 1654 |
__slots__ = ('_TYPE', |
| 1655 |
'_parent_type', '_parent_index', '_keepparent', |
| 1656 |
'_wrparent', |
| 1657 |
'__weakref__', |
| 1658 |
'_storage') |
| 1659 |
|
| 1660 |
def __init__(self, TYPE): |
| 1661 |
self._wrparent = None |
| 1662 |
self._TYPE = TYPE |
| 1663 |
self._storage = True |
| 1664 |
|
| 1665 |
|
| 1666 |
|
| 1667 |
|
| 1668 |
def _free(self): |
| 1669 |
self._check() |
| 1670 |
self._storage = None |
| 1671 |
|
| 1672 |
def _protect(self): |
| 1673 |
result = self._storage |
| 1674 |
self._free() |
| 1675 |
return result |
| 1676 |
|
| 1677 |
def _unprotect(self, saved_storage): |
| 1678 |
assert self._storage is None |
| 1679 |
self._storage = saved_storage |
| 1680 |
|
| 1681 |
def _was_freed(self): |
| 1682 |
if self._storage is None: |
| 1683 |
return True |
| 1684 |
if self._wrparent is None: |
| 1685 |
return False |
| 1686 |
parent = self._wrparent() |
| 1687 |
if parent is None: |
| 1688 |
raise RuntimeError("accessing sub%s %r,\n" |
| 1689 |
"but already garbage collected parent %r" |
| 1690 |
% (self._kind, self, self._parent_type)) |
| 1691 |
return parent._was_freed() |
| 1692 |
|
| 1693 |
def _setparentstructure(self, parent, parentindex): |
| 1694 |
self._wrparent = weakref.ref(parent) |
| 1695 |
self._parent_type = typeOf(parent) |
| 1696 |
self._parent_index = parentindex |
| 1697 |
if (isinstance(self._parent_type, Struct) |
| 1698 |
and self._parent_type._names |
| 1699 |
and parentindex in (self._parent_type._names[0], 0) |
| 1700 |
and self._TYPE._gckind == typeOf(parent)._gckind): |
| 1701 |
|
| 1702 |
self._keepparent = parent |
| 1703 |
|
| 1704 |
def _parentstructure(self, check=True): |
| 1705 |
if self._wrparent is not None: |
| 1706 |
parent = self._wrparent() |
| 1707 |
if parent is None: |
| 1708 |
raise RuntimeError("accessing sub%s %r,\n" |
| 1709 |
"but already garbage collected parent %r" |
| 1710 |
% (self._kind, self, self._parent_type)) |
| 1711 |
if check: |
| 1712 |
parent._check() |
| 1713 |
return parent |
| 1714 |
return None |
| 1715 |
|
| 1716 |
def _check(self): |
| 1717 |
if self._storage is None: |
| 1718 |
raise RuntimeError("accessing freed %r" % self._TYPE) |
| 1719 |
self._parentstructure() |
| 1720 |
|
| 1721 |
def _normalizedcontainer(self, check=True): |
| 1722 |
|
| 1723 |
|
| 1724 |
container = self |
| 1725 |
while True: |
| 1726 |
parent = container._parentstructure(check=check) |
| 1727 |
if parent is None: |
| 1728 |
break |
| 1729 |
index = container._parent_index |
| 1730 |
T = typeOf(parent) |
| 1731 |
if (not isinstance(T, Struct) or T._first_struct()[0] != index |
| 1732 |
or isinstance(T, FixedSizeArray)): |
| 1733 |
break |
| 1734 |
container = parent |
| 1735 |
return container |
| 1736 |
|
| 1737 |
def _struct_variety(flds, cache={}): |
| 1738 |
flds = list(flds) |
| 1739 |
flds.sort() |
| 1740 |
tag = tuple(flds) |
| 1741 |
try: |
| 1742 |
return cache[tag] |
| 1743 |
except KeyError: |
| 1744 |
class _struct1(_struct): |
| 1745 |
__slots__ = tag + ('__arena_location__',) |
| 1746 |
cache[tag] = _struct1 |
| 1747 |
return _struct1 |
| 1748 |
|
| 1749 |
|
| 1750 |
def _get_empty_instance_of_struct_variety(flds): |
| 1751 |
cls = _struct_variety(flds) |
| 1752 |
return object.__new__(cls) |
| 1753 |
|
| 1754 |
class _struct(_parentable): |
| 1755 |
_kind = "structure" |
| 1756 |
|
| 1757 |
__slots__ = ('_compilation_info',) |
| 1758 |
|
| 1759 |
def __new__(self, TYPE, n=None, initialization=None, parent=None, |
| 1760 |
parentindex=None): |
| 1761 |
if isinstance(TYPE, FixedSizeArray): |
| 1762 |
my_variety = _fixedsizearray |
| 1763 |
else: |
| 1764 |
my_variety = _struct_variety(TYPE._names) |
| 1765 |
return object.__new__(my_variety) |
| 1766 |
|
| 1767 |
def __init__(self, TYPE, n=None, initialization=None, parent=None, |
| 1768 |
parentindex=None): |
| 1769 |
_parentable.__init__(self, TYPE) |
| 1770 |
if n is not None and TYPE._arrayfld is None: |
| 1771 |
raise TypeError("%r is not variable-sized" % (TYPE,)) |
| 1772 |
if n is None and TYPE._arrayfld is not None: |
| 1773 |
raise TypeError("%r is variable-sized" % (TYPE,)) |
| 1774 |
for fld, typ in TYPE._flds.items(): |
| 1775 |
if fld == TYPE._arrayfld: |
| 1776 |
value = _array(typ, n, initialization=initialization, |
| 1777 |
parent=self, parentindex=fld) |
| 1778 |
else: |
| 1779 |
value = typ._allocate(initialization=initialization, |
| 1780 |
parent=self, parentindex=fld) |
| 1781 |
setattr(self, fld, value) |
| 1782 |
if parent is not None: |
| 1783 |
self._setparentstructure(parent, parentindex) |
| 1784 |
|
| 1785 |
def __repr__(self): |
| 1786 |
return '<%s>' % (self,) |
| 1787 |
|
| 1788 |
def _str_fields(self): |
| 1789 |
fields = [] |
| 1790 |
names = self._TYPE._names |
| 1791 |
if len(names) > 10: |
| 1792 |
names = names[:5] + names[-1:] |
| 1793 |
skipped_after = 5 |
| 1794 |
else: |
| 1795 |
skipped_after = None |
| 1796 |
for name in names: |
| 1797 |
T = self._TYPE._flds[name] |
| 1798 |
if isinstance(T, Primitive): |
| 1799 |
reprvalue = repr(getattr(self, name, '<uninitialized>')) |
| 1800 |
else: |
| 1801 |
reprvalue = '...' |
| 1802 |
fields.append('%s=%s' % (name, reprvalue)) |
| 1803 |
if skipped_after: |
| 1804 |
fields.insert(skipped_after, '(...)') |
| 1805 |
return ', '.join(fields) |
| 1806 |
|
| 1807 |
def __str__(self): |
| 1808 |
return 'struct %s { %s }' % (self._TYPE._name, self._str_fields()) |
| 1809 |
|
| 1810 |
def _getattr(self, field_name, uninitialized_ok=False): |
| 1811 |
r = getattr(self, field_name) |
| 1812 |
if isinstance(r, _uninitialized) and not uninitialized_ok: |
| 1813 |
raise UninitializedMemoryAccess("%r.%s"%(self, field_name)) |
| 1814 |
return r |
| 1815 |
|
| 1816 |
|
| 1817 |
class _fixedsizearray(_struct): |
| 1818 |
def __init__(self, TYPE, n=None, initialization=None, parent=None, |
| 1819 |
parentindex=None): |
| 1820 |
_parentable.__init__(self, TYPE) |
| 1821 |
if n is not None: |
| 1822 |
raise TypeError("%r is not variable-sized" % (TYPE,)) |
| 1823 |
typ = TYPE.OF |
| 1824 |
storage = [] |
| 1825 |
for i, fld in enumerate(TYPE._names): |
| 1826 |
value = typ._allocate(initialization=initialization, |
| 1827 |
parent=self, parentindex=fld) |
| 1828 |
storage.append(value) |
| 1829 |
self._items = storage |
| 1830 |
if parent is not None: |
| 1831 |
self._setparentstructure(parent, parentindex) |
| 1832 |
|
| 1833 |
def getlength(self): |
| 1834 |
return self._TYPE.length |
| 1835 |
|
| 1836 |
def getbounds(self): |
| 1837 |
return 0, self.getlength() |
| 1838 |
|
| 1839 |
def getitem(self, index, uninitialized_ok=False): |
| 1840 |
assert 0 <= index < self.getlength() |
| 1841 |
return self._items[index] |
| 1842 |
|
| 1843 |
def setitem(self, index, value): |
| 1844 |
assert 0 <= index < self.getlength() |
| 1845 |
self._items[index] = value |
| 1846 |
|
| 1847 |
def __getattr__(self, name): |
| 1848 |
|
| 1849 |
if name.startswith("item"): |
| 1850 |
return self.getitem(int(name[len('item'):])) |
| 1851 |
return _struct.__getattr__(self, name) |
| 1852 |
|
| 1853 |
def __setattr__(self, name, value): |
| 1854 |
if name.startswith("item"): |
| 1855 |
self.setitem(int(name[len('item'):]), value) |
| 1856 |
return |
| 1857 |
_struct.__setattr__(self, name, value) |
| 1858 |
|
| 1859 |
class _array(_parentable): |
| 1860 |
_kind = "array" |
| 1861 |
|
| 1862 |
__slots__ = ('items', '__arena_location__',) |
| 1863 |
|
| 1864 |
def __init__(self, TYPE, n, initialization=None, parent=None, |
| 1865 |
parentindex=None): |
| 1866 |
if not is_valid_int(n): |
| 1867 |
raise TypeError("array length must be an int") |
| 1868 |
if n < 0: |
| 1869 |
raise ValueError("negative array length") |
| 1870 |
_parentable.__init__(self, TYPE) |
| 1871 |
myrange = self._check_range(n) |
| 1872 |
self.items = [TYPE.OF._allocate(initialization=initialization, |
| 1873 |
parent=self, parentindex=j) |
| 1874 |
for j in myrange] |
| 1875 |
if parent is not None: |
| 1876 |
self._setparentstructure(parent, parentindex) |
| 1877 |
|
| 1878 |
def __repr__(self): |
| 1879 |
return '<%s>' % (self,) |
| 1880 |
|
| 1881 |
def _check_range(self, n): |
| 1882 |
|
| 1883 |
|
| 1884 |
try: |
| 1885 |
|
| 1886 |
|
| 1887 |
if n > 2 ** 30: |
| 1888 |
raise MemoryError("8 GiB should be enough for tests") |
| 1889 |
return range(n) |
| 1890 |
except OverflowError: |
| 1891 |
raise MemoryError("definitely too many items") |
| 1892 |
|
| 1893 |
def _str_item(self, item): |
| 1894 |
if isinstance(item, _uninitialized): |
| 1895 |
return '#' |
| 1896 |
if isinstance(self._TYPE.OF, Struct): |
| 1897 |
of = self._TYPE.OF |
| 1898 |
if self._TYPE._anonym_struct: |
| 1899 |
return "{%s}" % item._str_fields() |
| 1900 |
else: |
| 1901 |
return "%s {%s}" % (of._name, item._str_fields()) |
| 1902 |
else: |
| 1903 |
return repr(item) |
| 1904 |
|
| 1905 |
def __str__(self): |
| 1906 |
items = self.items |
| 1907 |
if len(items) > 20: |
| 1908 |
items = items[:12] + items[-5:] |
| 1909 |
skipped_at = 12 |
| 1910 |
else: |
| 1911 |
skipped_at = None |
| 1912 |
items = [self._str_item(item) for item in items] |
| 1913 |
if skipped_at: |
| 1914 |
items.insert(skipped_at, '(...)') |
| 1915 |
return 'array [ %s ]' % (', '.join(items),) |
| 1916 |
|
| 1917 |
def getlength(self): |
| 1918 |
return len(self.items) |
| 1919 |
|
| 1920 |
def shrinklength(self, newlength): |
| 1921 |
del self.items[newlength:] |
| 1922 |
|
| 1923 |
def getbounds(self): |
| 1924 |
stop = len(self.items) |
| 1925 |
return 0, stop |
| 1926 |
|
| 1927 |
def getitem(self, index, uninitialized_ok=False): |
| 1928 |
try: |
| 1929 |
v = self.items[index] |
| 1930 |
except IndexError: |
| 1931 |
if (index == len(self.items) and uninitialized_ok == 2 and |
| 1932 |
self._TYPE._hints.get('extra_item_after_alloc')): |
| 1933 |
|
| 1934 |
|
| 1935 |
return _uninitialized(self._TYPE.OF) |
| 1936 |
raise |
| 1937 |
if isinstance(v, _uninitialized) and not uninitialized_ok: |
| 1938 |
raise UninitializedMemoryAccess("%r[%s]"%(self, index)) |
| 1939 |
return v |
| 1940 |
|
| 1941 |
def setitem(self, index, value): |
| 1942 |
assert typeOf(value) == self._TYPE.OF |
| 1943 |
try: |
| 1944 |
self.items[index] = value |
| 1945 |
except IndexError: |
| 1946 |
if (index == len(self.items) and value == '\x00' and |
| 1947 |
self._TYPE._hints.get('extra_item_after_alloc')): |
| 1948 |
|
| 1949 |
return |
| 1950 |
raise |
| 1951 |
|
| 1952 |
assert not '__dict__' in dir(_array) |
| 1953 |
assert not '__dict__' in dir(_struct) |
| 1954 |
|
| 1955 |
|
| 1956 |
class _subarray(_parentable): |
| 1957 |
|
| 1958 |
_kind = "subarray" |
| 1959 |
_cache = {} |
| 1960 |
|
| 1961 |
def __init__(self, TYPE, parent, baseoffset_or_fieldname): |
| 1962 |
_parentable.__init__(self, TYPE) |
| 1963 |
self._setparentstructure(parent, baseoffset_or_fieldname) |
| 1964 |
|
| 1965 |
|
| 1966 |
|
| 1967 |
if (typeOf(top_container(parent))._gckind == 'raw' or |
| 1968 |
hasattr(top_container(parent)._storage, 'contents')): |
| 1969 |
self._keepparent = parent |
| 1970 |
|
| 1971 |
def __str__(self): |
| 1972 |
parent = self._wrparent() |
| 1973 |
if parent is None: |
| 1974 |
return '_subarray at %s in already freed' % (self._parent_index,) |
| 1975 |
return '_subarray at %r in %s' % (self._parent_index, |
| 1976 |
parent._TYPE) |
| 1977 |
|
| 1978 |
def __repr__(self): |
| 1979 |
parent = self._wrparent() |
| 1980 |
if parent is None: |
| 1981 |
return '<_subarray at %s in already freed>' % (self._parent_index,) |
| 1982 |
return '<_subarray at %r in %r>' % (self._parent_index, |
| 1983 |
self._parentstructure(check=False)) |
| 1984 |
|
| 1985 |
def getlength(self): |
| 1986 |
assert isinstance(self._TYPE, FixedSizeArray) |
| 1987 |
return self._TYPE.length |
| 1988 |
|
| 1989 |
def getbounds(self): |
| 1990 |
baseoffset = self._parent_index |
| 1991 |
if isinstance(baseoffset, str): |
| 1992 |
return 0, 1 |
| 1993 |
start, stop = self._parentstructure().getbounds() |
| 1994 |
return start - baseoffset, stop - baseoffset |
| 1995 |
|
| 1996 |
def getitem(self, index, uninitialized_ok=False): |
| 1997 |
baseoffset = self._parent_index |
| 1998 |
if isinstance(baseoffset, str): |
| 1999 |
assert index == 0 |
| 2000 |
fieldname = baseoffset |
| 2001 |
return getattr(self._parentstructure(), fieldname) |
| 2002 |
else: |
| 2003 |
return self._parentstructure().getitem(baseoffset + index, |
| 2004 |
uninitialized_ok=uninitialized_ok) |
| 2005 |
|
| 2006 |
def setitem(self, index, value): |
| 2007 |
baseoffset = self._parent_index |
| 2008 |
if isinstance(baseoffset, str): |
| 2009 |
assert index == 0 |
| 2010 |
fieldname = baseoffset |
| 2011 |
setattr(self._parentstructure(), fieldname, value) |
| 2012 |
else: |
| 2013 |
self._parentstructure().setitem(baseoffset + index, value) |
| 2014 |
|
| 2015 |
def _makeptr(parent, baseoffset_or_fieldname, solid=False): |
| 2016 |
try: |
| 2017 |
d = _subarray._cache[parent._TYPE] |
| 2018 |
except KeyError: |
| 2019 |
d = _subarray._cache[parent._TYPE] = weakref.WeakKeyDictionary() |
| 2020 |
try: |
| 2021 |
cache = d.setdefault(parent, {}) |
| 2022 |
except RuntimeError: |
| 2023 |
_subarray._cleanup_cache() |
| 2024 |
|
| 2025 |
return _subarray._makeptr(parent, baseoffset_or_fieldname, solid) |
| 2026 |
try: |
| 2027 |
subarray = cache[baseoffset_or_fieldname] |
| 2028 |
except KeyError: |
| 2029 |
PARENTTYPE = typeOf(parent) |
| 2030 |
if isinstance(baseoffset_or_fieldname, str): |
| 2031 |
|
| 2032 |
ITEMTYPE = getattr(PARENTTYPE, baseoffset_or_fieldname) |
| 2033 |
else: |
| 2034 |
|
| 2035 |
ITEMTYPE = PARENTTYPE.OF |
| 2036 |
ARRAYTYPE = FixedSizeArray(ITEMTYPE, 1) |
| 2037 |
subarray = _subarray(ARRAYTYPE, parent, baseoffset_or_fieldname) |
| 2038 |
cache[baseoffset_or_fieldname] = subarray |
| 2039 |
return _ptr(Ptr(subarray._TYPE), subarray, solid) |
| 2040 |
_makeptr = staticmethod(_makeptr) |
| 2041 |
|
| 2042 |
def _getid(self): |
| 2043 |
raise NotImplementedError('_subarray._getid()') |
| 2044 |
|
| 2045 |
def _cleanup_cache(): |
| 2046 |
for T, d in _subarray._cache.items(): |
| 2047 |
newcache = weakref.WeakKeyDictionary() |
| 2048 |
for key, value in d.items(): |
| 2049 |
try: |
| 2050 |
if not key._was_freed(): |
| 2051 |
newcache[key] = value |
| 2052 |
except RuntimeError: |
| 2053 |
|
| 2054 |
pass |
| 2055 |
if newcache: |
| 2056 |
_subarray._cache[T] = newcache |
| 2057 |
else: |
| 2058 |
del _subarray._cache[T] |
| 2059 |
_cleanup_cache = staticmethod(_cleanup_cache) |
| 2060 |
|
| 2061 |
|
| 2062 |
class _arraylenref(_parentable): |
| 2063 |
"""Pseudo-reference to the length field of an array. |
| 2064 |
Only used internally by llmemory to implement ArrayLengthOffset. |
| 2065 |
""" |
| 2066 |
_kind = "arraylenptr" |
| 2067 |
_cache = weakref.WeakKeyDictionary() |
| 2068 |
|
| 2069 |
def __init__(self, array): |
| 2070 |
TYPE = FixedSizeArray(Signed, 1) |
| 2071 |
_parentable.__init__(self, TYPE) |
| 2072 |
self.array = array |
| 2073 |
|
| 2074 |
def getlength(self): |
| 2075 |
return 1 |
| 2076 |
|
| 2077 |
def getbounds(self): |
| 2078 |
return 0, 1 |
| 2079 |
|
| 2080 |
def getitem(self, index, uninitialized_ok=False): |
| 2081 |
assert index == 0 |
| 2082 |
return self.array.getlength() |
| 2083 |
|
| 2084 |
def setitem(self, index, value): |
| 2085 |
assert index == 0 |
| 2086 |
if value != self.array.getlength(): |
| 2087 |
if value > self.array.getlength(): |
| 2088 |
raise Exception("can't grow an array in-place") |
| 2089 |
self.array.shrinklength(value) |
| 2090 |
|
| 2091 |
def _makeptr(array, solid=False): |
| 2092 |
try: |
| 2093 |
lenref = _arraylenref._cache[array] |
| 2094 |
except KeyError: |
| 2095 |
lenref = _arraylenref(array) |
| 2096 |
_arraylenref._cache[array] = lenref |
| 2097 |
return _ptr(Ptr(lenref._TYPE), lenref, solid) |
| 2098 |
_makeptr = staticmethod(_makeptr) |
| 2099 |
|
| 2100 |
def _getid(self): |
| 2101 |
raise NotImplementedError('_arraylenref._getid()') |
| 2102 |
|
| 2103 |
|
| 2104 |
class _func(_container): |
| 2105 |
def __init__(self, TYPE, **attrs): |
| 2106 |
attrs.setdefault('_TYPE', TYPE) |
| 2107 |
attrs.setdefault('_name', '?') |
| 2108 |
attrs.setdefault('_callable', None) |
| 2109 |
self.__dict__.update(attrs) |
| 2110 |
if '_callable' in attrs and hasattr(attrs['_callable'], |
| 2111 |
'_compilation_info'): |
| 2112 |
self.__dict__['compilation_info'] = \ |
| 2113 |
attrs['_callable']._compilation_info |
| 2114 |
|
| 2115 |
def __repr__(self): |
| 2116 |
return '<%s>' % (self,) |
| 2117 |
|
| 2118 |
def __str__(self): |
| 2119 |
return "fn %s" % self._name |
| 2120 |
|
| 2121 |
def __eq__(self, other): |
| 2122 |
return (self.__class__ is other.__class__ and |
| 2123 |
self.__dict__ == other.__dict__) |
| 2124 |
|
| 2125 |
def __ne__(self, other): |
| 2126 |
return not (self == other) |
| 2127 |
|
| 2128 |
def __hash__(self): |
| 2129 |
return hash(frozendict(self.__dict__)) |
| 2130 |
|
| 2131 |
def _getid(self): |
| 2132 |
if hasattr(self, 'graph'): |
| 2133 |
return id(self.graph) |
| 2134 |
elif self._callable: |
| 2135 |
return id(self._callable) |
| 2136 |
else: |
| 2137 |
return id(self) |
| 2138 |
|
| 2139 |
def __setattr__(self, attr, value): |
| 2140 |
raise AttributeError("cannot change the attributes of %r" % (self,)) |
| 2141 |
|
| 2142 |
class _opaque(_parentable): |
| 2143 |
def __init__(self, TYPE, parent=None, parentindex=None, **attrs): |
| 2144 |
_parentable.__init__(self, TYPE) |
| 2145 |
self._name = "?" |
| 2146 |
self.__dict__.update(attrs) |
| 2147 |
if parent is not None: |
| 2148 |
self._setparentstructure(parent, parentindex) |
| 2149 |
|
| 2150 |
def __repr__(self): |
| 2151 |
return '<%s>' % (self,) |
| 2152 |
|
| 2153 |
def __str__(self): |
| 2154 |
return "%s %s" % (self._TYPE.__name__, self._name) |
| 2155 |
|
| 2156 |
def __eq__(self, other): |
| 2157 |
if self.__class__ is not other.__class__: |
| 2158 |
return NotImplemented |
| 2159 |
if hasattr(self, 'container') and hasattr(other, 'container'): |
| 2160 |
obj1 = self._normalizedcontainer() |
| 2161 |
obj2 = other._normalizedcontainer() |
| 2162 |
return obj1 == obj2 |
| 2163 |
else: |
| 2164 |
return self is other |
| 2165 |
|
| 2166 |
def __ne__(self, other): |
| 2167 |
if self.__class__ is not other.__class__: |
| 2168 |
return NotImplemented |
| 2169 |
return not (self == other) |
| 2170 |
|
| 2171 |
def __hash__(self): |
| 2172 |
if hasattr(self, 'container'): |
| 2173 |
obj = self.container._normalizedcontainer() |
| 2174 |
return hash(obj) |
| 2175 |
else: |
| 2176 |
return _parentable.__hash__(self) |
| 2177 |
|
| 2178 |
def _normalizedcontainer(self): |
| 2179 |
|
| 2180 |
|
| 2181 |
if hasattr(self, 'container'): |
| 2182 |
|
| 2183 |
if type(self.container) is int: |
| 2184 |
return self.container |
| 2185 |
if getattr(self.container, '_carry_around_for_tests', False): |
| 2186 |
return self.container |
| 2187 |
return self.container._normalizedcontainer() |
| 2188 |
else: |
| 2189 |
return _parentable._normalizedcontainer(self) |
| 2190 |
|
| 2191 |
|
| 2192 |
def malloc(T, n=None, flavor='gc', immortal=False, zero=False, |
| 2193 |
track_allocation=True, add_memory_pressure=False, |
| 2194 |
nonmovable=False): |
| 2195 |
assert flavor in ('gc', 'raw') |
| 2196 |
if zero or immortal: |
| 2197 |
initialization = 'example' |
| 2198 |
elif flavor == 'raw': |
| 2199 |
initialization = 'raw' |
| 2200 |
else: |
| 2201 |
initialization = 'malloc' |
| 2202 |
if isinstance(T, Struct): |
| 2203 |
o = _struct(T, n, initialization=initialization) |
| 2204 |
elif isinstance(T, Array): |
| 2205 |
o = _array(T, n, initialization=initialization) |
| 2206 |
elif isinstance(T, OpaqueType): |
| 2207 |
assert n is None |
| 2208 |
o = _opaque(T, initialization=initialization) |
| 2209 |
else: |
| 2210 |
raise TypeError("malloc: unmallocable type") |
| 2211 |
if flavor == 'gc' and T._gckind != 'gc' and not immortal: |
| 2212 |
raise TypeError("gc flavor malloc of a non-GC non-immortal structure") |
| 2213 |
if flavor == "raw" and not immortal and track_allocation: |
| 2214 |
leakfinder.remember_malloc(o, framedepth=2) |
| 2215 |
solid = immortal or flavor == 'raw' |
| 2216 |
return _ptr(Ptr(T), o, solid) |
| 2217 |
|
| 2218 |
@analyzer_for(malloc) |
| 2219 |
def ann_malloc(s_T, s_n=None, s_flavor=None, s_immortal=None, s_zero=None, |
| 2220 |
s_track_allocation=None, s_add_memory_pressure=None, |
| 2221 |
s_nonmovable=None): |
| 2222 |
assert (s_n is None or s_n.knowntype == int |
| 2223 |
or issubclass(s_n.knowntype, base_int)) |
| 2224 |
assert s_T.is_constant() |
| 2225 |
if s_n is not None: |
| 2226 |
n = 1 |
| 2227 |
else: |
| 2228 |
n = None |
| 2229 |
if s_zero: |
| 2230 |
assert s_zero.is_constant() |
| 2231 |
if s_flavor is None: |
| 2232 |
p = malloc(s_T.const, n) |
| 2233 |
r = SomePtr(typeOf(p)) |
| 2234 |
else: |
| 2235 |
assert s_flavor.is_constant() |
| 2236 |
assert s_track_allocation is None or s_track_allocation.is_constant() |
| 2237 |
assert (s_add_memory_pressure is None or |
| 2238 |
s_add_memory_pressure.is_constant()) |
| 2239 |
assert s_nonmovable is None or s_nonmovable.is_constant() |
| 2240 |
|
| 2241 |
|
| 2242 |
r = SomePtr(Ptr(s_T.const)) |
| 2243 |
return r |
| 2244 |
|
| 2245 |
|
| 2246 |
def free(p, flavor, track_allocation=True): |
| 2247 |
if flavor.startswith('gc'): |
| 2248 |
raise TypeError("gc flavor free") |
| 2249 |
T = typeOf(p) |
| 2250 |
if not isinstance(T, Ptr) or p._togckind() != 'raw': |
| 2251 |
raise TypeError("free(): only for pointers to non-gc containers") |
| 2252 |
if track_allocation: |
| 2253 |
leakfinder.remember_free(p._obj0) |
| 2254 |
p._obj0._free() |
| 2255 |
|
| 2256 |
@analyzer_for(free) |
| 2257 |
def ann_free(s_p, s_flavor, s_track_allocation=None): |
| 2258 |
assert s_flavor.is_constant() |
| 2259 |
assert s_track_allocation is None or s_track_allocation.is_constant() |
| 2260 |
|
| 2261 |
|
| 2262 |
|
| 2263 |
|
| 2264 |
|
| 2265 |
|
| 2266 |
|
| 2267 |
def render_immortal(p, track_allocation=True): |
| 2268 |
T = typeOf(p) |
| 2269 |
if not isinstance(T, Ptr) or p._togckind() != 'raw': |
| 2270 |
raise TypeError("free(): only for pointers to non-gc containers") |
| 2271 |
if track_allocation: |
| 2272 |
leakfinder.remember_free(p._obj0) |
| 2273 |
|
| 2274 |
@analyzer_for(render_immortal) |
| 2275 |
def ann_render_immortal(s_p, s_track_allocation=None): |
| 2276 |
assert s_track_allocation is None or s_track_allocation.is_constant() |
| 2277 |
|
| 2278 |
def _make_scoped_allocator(T, zero): |
| 2279 |
class ScopedAlloc: |
| 2280 |
def __init__(self, n=None): |
| 2281 |
if n is None: |
| 2282 |
self.buf = malloc(T, flavor='raw', zero=zero) |
| 2283 |
else: |
| 2284 |
self.buf = malloc(T, n, flavor='raw', zero=zero) |
| 2285 |
|
| 2286 |
def __enter__(self): |
| 2287 |
return self.buf |
| 2288 |
|
| 2289 |
def __exit__(self, *args): |
| 2290 |
free(self.buf, flavor='raw') |
| 2291 |
|
| 2292 |
ScopedAlloc.__name__ = 'ScopedAlloc_%s' % (T,) |
| 2293 |
return ScopedAlloc |
| 2294 |
_make_scoped_allocator._annspecialcase_ = 'specialize:memo' |
| 2295 |
|
| 2296 |
def scoped_alloc(T, n=None, zero=False): |
| 2297 |
"""Returns a context manager which handles allocation and |
| 2298 |
deallocation of temporary memory. Use it in a with statement:: |
| 2299 |
|
| 2300 |
with scoped_alloc(Array(Signed), 1) as array: |
| 2301 |
...use array... |
| 2302 |
...it's freed now. |
| 2303 |
""" |
| 2304 |
return _make_scoped_allocator(T, zero)(n=n) |
| 2305 |
scoped_alloc._annspecialcase_ = 'specialize:arg(0, 2)' |
| 2306 |
|
| 2307 |
def functionptr(TYPE, name, **attrs): |
| 2308 |
if not isinstance(TYPE, FuncType): |
| 2309 |
raise TypeError("functionptr() for FuncTypes only") |
| 2310 |
try: |
| 2311 |
hash(tuple(attrs.items())) |
| 2312 |
except TypeError: |
| 2313 |
raise TypeError("'%r' must be hashable"%attrs) |
| 2314 |
o = _func(TYPE, _name=name, **attrs) |
| 2315 |
return _ptr(Ptr(TYPE), o) |
| 2316 |
|
| 2317 |
def _getconcretetype(v): |
| 2318 |
return v.concretetype |
| 2319 |
|
| 2320 |
def getfunctionptr(graph, getconcretetype=_getconcretetype): |
| 2321 |
"""Return callable given a Python function.""" |
| 2322 |
llinputs = [getconcretetype(v) for v in graph.getargs()] |
| 2323 |
lloutput = getconcretetype(graph.getreturnvar()) |
| 2324 |
|
| 2325 |
FT = FuncType(llinputs, lloutput) |
| 2326 |
name = graph.name |
| 2327 |
if hasattr(graph, 'func') and callable(graph.func): |
| 2328 |
|
| 2329 |
|
| 2330 |
|
| 2331 |
|
| 2332 |
|
| 2333 |
if hasattr(graph.func, '_llfnobjattrs_'): |
| 2334 |
fnobjattrs = graph.func._llfnobjattrs_.copy() |
| 2335 |
|
| 2336 |
name = fnobjattrs.pop('_name', name) |
| 2337 |
else: |
| 2338 |
fnobjattrs = {} |
| 2339 |
|
| 2340 |
|
| 2341 |
_callable = fnobjattrs.pop('_callable', graph.func) |
| 2342 |
return functionptr(FT, name, graph=graph, _callable=_callable, |
| 2343 |
**fnobjattrs) |
| 2344 |
else: |
| 2345 |
return functionptr(FT, name, graph=graph) |
| 2346 |
|
| 2347 |
def nullptr(T): |
| 2348 |
return Ptr(T)._defl() |
| 2349 |
|
| 2350 |
@analyzer_for(nullptr) |
| 2351 |
def ann_nullptr(T): |
| 2352 |
assert T.is_constant() |
| 2353 |
p = nullptr(T.const) |
| 2354 |
return immutablevalue(p) |
| 2355 |
|
| 2356 |
|
| 2357 |
def opaqueptr(TYPE, name, **attrs): |
| 2358 |
if not isinstance(TYPE, OpaqueType): |
| 2359 |
raise TypeError("opaqueptr() for OpaqueTypes only") |
| 2360 |
o = _opaque(TYPE, _name=name, **attrs) |
| 2361 |
return _ptr(Ptr(TYPE), o, solid=True) |
| 2362 |
|
| 2363 |
|
| 2364 |
def cast_ptr_to_int(ptr): |
| 2365 |
return ptr._cast_to_int() |
| 2366 |
|
| 2367 |
@analyzer_for(cast_ptr_to_int) |
| 2368 |
def ann_cast_ptr_to_int(s_ptr): |
| 2369 |
return SomeInteger() |
| 2370 |
|
| 2371 |
|
| 2372 |
def cast_int_to_ptr(PTRTYPE, oddint): |
| 2373 |
if oddint == 0: |
| 2374 |
return nullptr(PTRTYPE.TO) |
| 2375 |
if not (oddint & 1): |
| 2376 |
raise ValueError("only odd integers can be cast back to ptr") |
| 2377 |
return _ptr(PTRTYPE, oddint, solid=True) |
| 2378 |
|
| 2379 |
@analyzer_for(cast_int_to_ptr) |
| 2380 |
def ann_cast_int_to_ptr(PtrT, s_int): |
| 2381 |
assert PtrT.is_constant() |
| 2382 |
return SomePtr(ll_ptrtype=PtrT.const) |
| 2383 |
|
| 2384 |
|
| 2385 |
def attachRuntimeTypeInfo(GCSTRUCT, funcptr=None, destrptr=None): |
| 2386 |
if not isinstance(GCSTRUCT, RttiStruct): |
| 2387 |
raise TypeError("expected a RttiStruct: %s" % GCSTRUCT) |
| 2388 |
GCSTRUCT._attach_runtime_type_info_funcptr(funcptr, destrptr) |
| 2389 |
return _ptr(Ptr(RuntimeTypeInfo), GCSTRUCT._runtime_type_info) |
| 2390 |
|
| 2391 |
def getRuntimeTypeInfo(GCSTRUCT): |
| 2392 |
if not isinstance(GCSTRUCT, RttiStruct): |
| 2393 |
raise TypeError("expected a RttiStruct: %s" % GCSTRUCT) |
| 2394 |
if GCSTRUCT._runtime_type_info is None: |
| 2395 |
raise ValueError("no attached runtime type info for GcStruct %s" % |
| 2396 |
GCSTRUCT._name) |
| 2397 |
return _ptr(Ptr(RuntimeTypeInfo), GCSTRUCT._runtime_type_info) |
| 2398 |
|
| 2399 |
@analyzer_for(getRuntimeTypeInfo) |
| 2400 |
def ann_getRuntimeTypeInfo(T): |
| 2401 |
assert T.is_constant() |
| 2402 |
return immutablevalue(getRuntimeTypeInfo(T.const)) |
| 2403 |
|
| 2404 |
|
| 2405 |
def runtime_type_info(p): |
| 2406 |
T = typeOf(p) |
| 2407 |
if not isinstance(T, Ptr) or not isinstance(T.TO, RttiStruct): |
| 2408 |
raise TypeError("runtime_type_info on non-RttiStruct pointer: %s" % p) |
| 2409 |
struct = p._obj |
| 2410 |
top_parent = top_container(struct) |
| 2411 |
result = getRuntimeTypeInfo(top_parent._TYPE) |
| 2412 |
static_info = getRuntimeTypeInfo(T.TO) |
| 2413 |
query_funcptr = getattr(static_info._obj, 'query_funcptr', None) |
| 2414 |
if query_funcptr is not None: |
| 2415 |
T = typeOf(query_funcptr).TO.ARGS[0] |
| 2416 |
result2 = query_funcptr(cast_pointer(T, p)) |
| 2417 |
if result != result2: |
| 2418 |
raise RuntimeError("runtime type-info function for %s:\n" |
| 2419 |
" returned: %s,\n" |
| 2420 |
"should have been: %s" % (p, result2, result)) |
| 2421 |
return result |
| 2422 |
|
| 2423 |
@analyzer_for(runtime_type_info) |
| 2424 |
def ann_runtime_type_info(s_p): |
| 2425 |
assert isinstance(s_p, SomePtr), \ |
| 2426 |
"runtime_type_info of non-pointer: %r" % s_p |
| 2427 |
return SomePtr(typeOf(runtime_type_info(s_p.ll_ptrtype._example()))) |
| 2428 |
|
| 2429 |
|
| 2430 |
def identityhash(p): |
| 2431 |
"""Returns the lltype-level hash of the given GcStruct. |
| 2432 |
Not for NULL. See rlib.objectmodel.compute_identity_hash() for more |
| 2433 |
information about the RPython-level meaning of this. |
| 2434 |
""" |
| 2435 |
assert p |
| 2436 |
return p._identityhash() |
| 2437 |
|
| 2438 |
@analyzer_for(identityhash) |
| 2439 |
def ann_identityhash(s_obj): |
| 2440 |
assert isinstance(s_obj, SomePtr) |
| 2441 |
return SomeInteger() |
| 2442 |
|
| 2443 |
|
| 2444 |
def isCompatibleType(TYPE1, TYPE2): |
| 2445 |
return TYPE1._is_compatible(TYPE2) |
| 2446 |
|
| 2447 |
def enforce(TYPE, value): |
| 2448 |
return TYPE._enforce(value) |
| 2449 |
|
| 2450 |
|
| 2451 |
|
| 2452 |
def typeMethod(func): |
| 2453 |
func._type_method = True |
| 2454 |
return func |
| 2455 |
|
| 2456 |
class staticAdtMethod(object): |
| 2457 |
|
| 2458 |
|
| 2459 |
def __init__(self, obj): |
| 2460 |
self.obj = obj |
| 2461 |
|
| 2462 |
def __get__(self, inst, typ=None): |
| 2463 |
return self.obj |
| 2464 |
|
| 2465 |
def __hash__(self): |
| 2466 |
return hash(self.obj) |
| 2467 |
|
| 2468 |
def __eq__(self, other): |
| 2469 |
if not isinstance(other, staticAdtMethod): |
| 2470 |
return NotImplemented |
| 2471 |
else: |
| 2472 |
return self.obj == other.obj |
| 2473 |
|
| 2474 |
def __ne__(self, other): |
| 2475 |
if not isinstance(other, staticAdtMethod): |
| 2476 |
return NotImplemented |
| 2477 |
else: |
| 2478 |
return self.obj != other.obj |
| 2479 |
|
| 2480 |
|
| 2481 |
def dissect_ll_instance(v, t=None, memo=None): |
| 2482 |
if memo is None: |
| 2483 |
memo = identity_dict() |
| 2484 |
if v in memo: |
| 2485 |
return |
| 2486 |
memo[v] = True |
| 2487 |
if t is None: |
| 2488 |
t = typeOf(v) |
| 2489 |
yield t, v |
| 2490 |
if isinstance(t, Ptr): |
| 2491 |
if v._obj: |
| 2492 |
for i in dissect_ll_instance(v._obj, t.TO, memo): |
| 2493 |
yield i |
| 2494 |
elif isinstance(t, Struct): |
| 2495 |
parent = v._parentstructure() |
| 2496 |
if parent: |
| 2497 |
for i in dissect_ll_instance(parent, typeOf(parent), memo): |
| 2498 |
yield i |
| 2499 |
for n in t._flds: |
| 2500 |
f = getattr(t, n) |
| 2501 |
for i in dissect_ll_instance(getattr(v, n), t._flds[n], memo): |
| 2502 |
yield i |
| 2503 |
elif isinstance(t, Array): |
| 2504 |
for item in v.items: |
| 2505 |
for i in dissect_ll_instance(item, t.OF, memo): |
| 2506 |
yield i |
| 2507 |
|
| 2508 |
|