Debian Codegraph @

rpython/rtyper/rclass.py

raw symbols SCIP
1 import sys
2 import types
3
4 from rpython.flowspace.model import Constant
5 from rpython.annotator import description, model as annmodel
6 from rpython.rlib.objectmodel import UnboxedValue
7 from rpython.tool.pairtype import pairtype, pair
8 from rpython.tool.identity_dict import identity_dict
9 from rpython.tool.flattenrec import FlattenRecursion
10 from rpython.rtyper.extregistry import ExtRegistryEntry
11 from rpython.rtyper.error import TyperError
12 from rpython.rtyper.lltypesystem import lltype
13 from rpython.rtyper.lltypesystem.lltype import (
14 Ptr, Struct, GcStruct, malloc, cast_pointer, castable, nullptr,
15 RuntimeTypeInfo, getRuntimeTypeInfo, typeOf, Void, FuncType, Bool, Signed,
16 functionptr, attachRuntimeTypeInfo)
17 from rpython.rtyper.lltypesystem.lloperation import llop
18 from rpython.rtyper.llannotation import lltype_to_annotation
19 from rpython.rtyper.llannotation import SomePtr
20 from rpython.rtyper.lltypesystem import rstr
21 from rpython.rtyper.rmodel import (
22 Repr, getgcflavor, inputconst, warning, mangle)
23
24
25 class FieldListAccessor(object):
26
27 def initialize(self, TYPE, fields):
28 assert type(fields) is dict
29 self.TYPE = TYPE
30 self.fields = fields
31 for x in fields.itervalues():
32 assert isinstance(x, ImmutableRanking)
33
34 def all_immutable_fields(self):
35 result = set()
36 for key, value in self.fields.iteritems():
37 if value in (IR_IMMUTABLE, IR_IMMUTABLE_ARRAY):
38 result.add(key)
39 return result
40
41 def __repr__(self):
42 return '<FieldListAccessor for %s>' % getattr(self, 'TYPE', '?')
43
44
45 class ImmutableRanking(object):
46 def __init__(self, name, is_immutable):
47 self.name = name
48 self.is_immutable = is_immutable
49
50 def __nonzero__(self):
51 return self.is_immutable
52
53 def __repr__(self):
54 return '<%s>' % self.name
55
56 IR_MUTABLE = ImmutableRanking('mutable', False)
57 IR_IMMUTABLE = ImmutableRanking('immutable', True)
58 IR_IMMUTABLE_ARRAY = ImmutableRanking('immutable_array', True)
59 IR_QUASIIMMUTABLE = ImmutableRanking('quasiimmutable', False)
60 IR_QUASIIMMUTABLE_ARRAY = ImmutableRanking('quasiimmutable_array', False)
61
62 class ImmutableConflictError(Exception):
63 """Raised when the _immutable_ or _immutable_fields_ hints are
64 not consistent across a class hierarchy."""
65
66
67 def getclassrepr(rtyper, classdef):
68 if classdef is None:
69 return rtyper.rootclass_repr
70 result = classdef.repr
71 if result is None:
72 result = classdef.repr = ClassRepr(rtyper, classdef)
73 rtyper.add_pendingsetup(result)
74 return result
75
76 def getinstancerepr(rtyper, classdef, default_flavor='gc'):
77 if classdef is None:
78 flavor = default_flavor
79 else:
80 flavor = getgcflavor(classdef)
81 try:
82 result = rtyper.instance_reprs[classdef, flavor]
83 except KeyError:
84 result = buildinstancerepr(rtyper, classdef, gcflavor=flavor)
85
86 rtyper.instance_reprs[classdef, flavor] = result
87 rtyper.add_pendingsetup(result)
88 return result
89
90
91 def buildinstancerepr(rtyper, classdef, gcflavor='gc'):
92 from rpython.rtyper.rvirtualizable import VirtualizableInstanceRepr
93
94 if classdef is None:
95 unboxed = []
96 virtualizable = False
97 else:
98 unboxed = [subdef for subdef in classdef.getallsubdefs() if
99 subdef.classdesc.pyobj is not None and
100 issubclass(subdef.classdesc.pyobj, UnboxedValue)]
101 virtualizable = classdef.classdesc.get_param('_virtualizable_', False)
102 config = rtyper.annotator.translator.config
103 usetagging = len(unboxed) != 0 and config.translation.taggedpointers
104
105 if virtualizable:
106 assert len(unboxed) == 0
107 assert gcflavor == 'gc'
108 return VirtualizableInstanceRepr(rtyper, classdef)
109 elif usetagging:
110 # the UnboxedValue class and its parent classes need a
111 # special repr for their instances
112 if len(unboxed) != 1:
113 raise TyperError("%r has several UnboxedValue subclasses" % (
114 classdef,))
115 assert gcflavor == 'gc'
116 from rpython.rtyper.lltypesystem import rtagged
117 return rtagged.TaggedInstanceRepr(rtyper, classdef, unboxed[0])
118 else:
119 return InstanceRepr(rtyper, classdef, gcflavor)
120
121
122 class MissingRTypeAttribute(TyperError):
123 pass
124
125 # ____________________________________________________________
126
127
128 #
129 # There is one "vtable" per user class, with the following structure:
130 # A root class "object" has:
131 #
132 # struct object_vtable {
133 # RuntimeTypeInfo * rtti;
134 # Signed subclassrange_min; //this is also the id of the class itself
135 # Signed subclassrange_max;
136 # RPyString * name;
137 # struct object * instantiate();
138 # }
139 #
140 # Every other class X, with parent Y, has the structure:
141 #
142 # struct vtable_X {
143 # struct vtable_Y super; // inlined
144 # ... // extra class attributes
145 # }
146
147 # The type of the instances is:
148 #
149 # struct object { // for the root class
150 # struct object_vtable* typeptr;
151 # }
152 #
153 # struct X {
154 # struct Y super; // inlined
155 # ... // extra instance attributes
156 # }
157 #
158 # there's also a nongcobject
159
160 OBJECT_VTABLE = lltype.ForwardReference()
161 CLASSTYPE = Ptr(OBJECT_VTABLE)
162 OBJECT = GcStruct('object', ('typeptr', CLASSTYPE),
163 hints={'immutable': True, 'shouldntbenull': True,
164 'typeptr': True},
165 rtti=True)
166 OBJECTPTR = Ptr(OBJECT)
167 OBJECT_VTABLE.become(Struct('object_vtable',
168 ('subclassrange_min', Signed),
169 ('subclassrange_max', Signed),
170 ('rtti', Ptr(RuntimeTypeInfo)),
171 ('name', Ptr(rstr.STR)),
172 ('instantiate', Ptr(FuncType([], OBJECTPTR))),
173 hints={'immutable': True,
174 'static_immutable': True}))
175 # non-gc case
176 NONGCOBJECT = Struct('nongcobject', ('typeptr', CLASSTYPE))
177 NONGCOBJECTPTR = Ptr(NONGCOBJECT)
178
179 OBJECT_BY_FLAVOR = {'gc': OBJECT, 'raw': NONGCOBJECT}
180 LLFLAVOR = {'gc': 'gc', 'raw': 'raw', 'stack': 'raw'}
181
182 def cast_vtable_to_typeptr(vtable):
183 while typeOf(vtable).TO != OBJECT_VTABLE:
184 vtable = vtable.super
185 return vtable
186
187 def alloc_array_name(name):
188 return rstr.string_repr.convert_const(name)
189
190
191 class ClassRepr(Repr):
192 def __init__(self, rtyper, classdef):
193 self.rtyper = rtyper
194 self.classdef = classdef
195 self.vtable_type = lltype.ForwardReference()
196 self.lowleveltype = Ptr(self.vtable_type)
197
198 def __repr__(self):
199 if self.classdef is None:
200 clsname = 'object'
201 else:
202 clsname = self.classdef.name
203 return '<ClassRepr for %s>' % (clsname,)
204
205 def compact_repr(self):
206 if self.classdef is None:
207 clsname = 'object'
208 else:
209 clsname = self.classdef.name
210 return 'ClassR %s' % (clsname,)
211
212 def convert_desc(self, desc):
213 subclassdef = desc.getuniqueclassdef()
214 if self.classdef is not None:
215 if self.classdef.commonbase(subclassdef) != self.classdef:
216 raise TyperError("not a subclass of %r: %r" % (
217 self.classdef.name, desc))
218
219 r_subclass = getclassrepr(self.rtyper, subclassdef)
220 return r_subclass.getruntime(self.lowleveltype)
221
222 def convert_const(self, value):
223 if not isinstance(value, (type, types.ClassType)):
224 raise TyperError("not a class: %r" % (value,))
225 bk = self.rtyper.annotator.bookkeeper
226 return self.convert_desc(bk.getdesc(value))
227
228 def prepare_method(self, s_value):
229 # special-casing for methods:
230 # if s_value is SomePBC([MethodDescs...])
231 # return a PBC representing the underlying functions
232 if (isinstance(s_value, annmodel.SomePBC) and
233 s_value.getKind() == description.MethodDesc):
234 s_value = self.classdef.lookup_filter(s_value)
235 funcdescs = [mdesc.funcdesc for mdesc in s_value.descriptions]
236 return annmodel.SomePBC(funcdescs)
237 return None # not a method
238
239 def get_ll_eq_function(self):
240 return None
241
242 def _setup_repr(self):
243 # NOTE: don't store mutable objects like the dicts below on 'self'
244 # before they are fully built, to avoid strange bugs in case
245 # of recursion where other code would uses these
246 # partially-initialized dicts.
247 clsfields = {}
248 pbcfields = {}
249 allmethods = {}
250 # class attributes
251 llfields = []
252 for name, attrdef in self.classdef.attrs.items():
253 if attrdef.readonly:
254 s_value = attrdef.s_value
255 s_unboundmethod = self.prepare_method(s_value)
256 if s_unboundmethod is not None:
257 allmethods[name] = True
258 s_value = s_unboundmethod
259 r = self.rtyper.getrepr(s_value)
260 mangled_name = 'cls_' + name
261 clsfields[name] = mangled_name, r
262 llfields.append((mangled_name, r.lowleveltype))
263 # attributes showing up in getattrs done on the class as a PBC
264 extra_access_sets = self.classdef.extra_access_sets
265 for access_set, (attr, counter) in extra_access_sets.items():
266 r = self.rtyper.getrepr(access_set.s_value)
267 mangled_name = mangle('pbc%d' % counter, attr)
268 pbcfields[access_set, attr] = mangled_name, r
269 llfields.append((mangled_name, r.lowleveltype))
270 llfields.sort()
271 llfields.sort(key=attr_reverse_size)
272 #
273 self.rbase = getclassrepr(self.rtyper, self.classdef.basedef)
274 self.rbase.setup()
275 kwds = {'hints': {'immutable': True, 'static_immutable': True}}
276 vtable_type = Struct('%s_vtable' % self.classdef.name,
277 ('super', self.rbase.vtable_type),
278 *llfields, **kwds)
279 self.vtable_type.become(vtable_type)
280 allmethods.update(self.rbase.allmethods)
281 self.clsfields = clsfields
282 self.pbcfields = pbcfields
283 self.allmethods = allmethods
284 self.vtable = None
285
286 def getvtable(self):
287 """Return a ptr to the vtable of this type."""
288 if self.vtable is None:
289 self.init_vtable()
290 return cast_vtable_to_typeptr(self.vtable)
291
292 def getruntime(self, expected_type):
293 assert expected_type == CLASSTYPE
294 return self.getvtable()
295
296 def init_vtable(self):
297 """Create the actual vtable"""
298 self.vtable = malloc(self.vtable_type, immortal=True)
299 vtable_part = self.vtable
300 r_parentcls = self
301 while r_parentcls.classdef is not None:
302 self.setup_vtable(vtable_part, r_parentcls)
303 vtable_part = vtable_part.super
304 r_parentcls = r_parentcls.rbase
305 self.fill_vtable_root(vtable_part)
306
307 def setup_vtable(self, vtable, r_parentcls):
308 """Initialize the vtable portion corresponding to 'r_parentcls'."""
309 # setup class attributes: for each attribute name at the level
310 # of 'r_parentcls', look up its value in the class
311 def assign(mangled_name, value):
312 if value is None:
313 llvalue = r.special_uninitialized_value()
314 if llvalue is None:
315 return
316 else:
317 if (isinstance(value, Constant) and
318 isinstance(value.value, staticmethod)):
319 value = Constant(value.value.__get__(42)) # staticmethod => bare function
320 llvalue = r.convert_desc_or_const(value)
321 setattr(vtable, mangled_name, llvalue)
322
323 for fldname in r_parentcls.clsfields:
324 mangled_name, r = r_parentcls.clsfields[fldname]
325 if r.lowleveltype is Void:
326 continue
327 value = self.classdef.classdesc.read_attribute(fldname, None)
328 assign(mangled_name, value)
329 # extra PBC attributes
330 for (access_set, attr), (mangled_name, r) in r_parentcls.pbcfields.items():
331 if self.classdef.classdesc not in access_set.descs:
332 continue # only for the classes in the same pbc access set
333 if r.lowleveltype is Void:
334 continue
335 attrvalue = self.classdef.classdesc.read_attribute(attr, None)
336 assign(mangled_name, attrvalue)
337
338 def fill_vtable_root(self, vtable):
339 """Initialize the head of the vtable."""
340 # initialize the 'subclassrange_*' and 'name' fields
341 if self.classdef is not None:
342 vtable.subclassrange_min = self.classdef.minid
343 vtable.subclassrange_max = self.classdef.maxid
344 else: # for the root class
345 vtable.subclassrange_min = 0
346 vtable.subclassrange_max = sys.maxint
347 rinstance = getinstancerepr(self.rtyper, self.classdef)
348 rinstance.setup()
349 if rinstance.gcflavor == 'gc':
350 vtable.rtti = getRuntimeTypeInfo(rinstance.object_type)
351 if self.classdef is None:
352 name = 'object'
353 else:
354 name = self.classdef.shortname
355 vtable.name = alloc_array_name(name)
356 if hasattr(self.classdef, 'my_instantiate_graph'):
357 graph = self.classdef.my_instantiate_graph
358 vtable.instantiate = self.rtyper.getcallable(graph)
359 #else: the classdef was created recently, so no instantiate()
360 # could reach it
361
362 def fromtypeptr(self, vcls, llops):
363 """Return the type pointer cast to self's vtable type."""
364 self.setup()
365 castable(self.lowleveltype, vcls.concretetype) # sanity check
366 return llops.genop('cast_pointer', [vcls],
367 resulttype=self.lowleveltype)
368
369 fromclasstype = fromtypeptr
370
371 def getclsfield(self, vcls, attr, llops):
372 """Read the given attribute of 'vcls'."""
373 if attr in self.clsfields:
374 mangled_name, r = self.clsfields[attr]
375 v_vtable = self.fromtypeptr(vcls, llops)
376 cname = inputconst(Void, mangled_name)
377 return llops.genop('getfield', [v_vtable, cname], resulttype=r)
378 else:
379 if self.classdef is None:
380 raise MissingRTypeAttribute(attr)
381 return self.rbase.getclsfield(vcls, attr, llops)
382
383 def setclsfield(self, vcls, attr, vvalue, llops):
384 """Write the given attribute of 'vcls'."""
385 if attr in self.clsfields:
386 mangled_name, r = self.clsfields[attr]
387 v_vtable = self.fromtypeptr(vcls, llops)
388 cname = inputconst(Void, mangled_name)
389 llops.genop('setfield', [v_vtable, cname, vvalue])
390 else:
391 if self.classdef is None:
392 raise MissingRTypeAttribute(attr)
393 self.rbase.setclsfield(vcls, attr, vvalue, llops)
394
395 def getpbcfield(self, vcls, access_set, attr, llops):
396 if (access_set, attr) not in self.pbcfields:
397 raise TyperError("internal error: missing PBC field")
398 mangled_name, r = self.pbcfields[access_set, attr]
399 v_vtable = self.fromtypeptr(vcls, llops)
400 cname = inputconst(Void, mangled_name)
401 return llops.genop('getfield', [v_vtable, cname], resulttype=r)
402
403 def rtype_issubtype(self, hop):
404 class_repr = get_type_repr(self.rtyper)
405 v_cls1, v_cls2 = hop.inputargs(class_repr, class_repr)
406 if isinstance(v_cls2, Constant):
407 cls2 = v_cls2.value
408 minid = hop.inputconst(Signed, cls2.subclassrange_min)
409 maxid = hop.inputconst(Signed, cls2.subclassrange_max)
410 return hop.gendirectcall(ll_issubclass_const, v_cls1, minid,
411 maxid)
412 else:
413 v_cls1, v_cls2 = hop.inputargs(class_repr, class_repr)
414 return hop.gendirectcall(ll_issubclass, v_cls1, v_cls2)
415
416 def ll_str(self, cls):
417 return cls.name
418
419
420 class RootClassRepr(ClassRepr):
421 """ClassRepr for the root of the class hierarchy"""
422 classdef = None
423
424 def __init__(self, rtyper):
425 self.rtyper = rtyper
426 self.vtable_type = OBJECT_VTABLE
427 self.lowleveltype = Ptr(self.vtable_type)
428
429 def _setup_repr(self):
430 self.clsfields = {}
431 self.pbcfields = {}
432 self.allmethods = {}
433 self.vtable = None
434
435 def init_vtable(self):
436 self.vtable = malloc(self.vtable_type, immortal=True)
437 self.fill_vtable_root(self.vtable)
438
439 def get_type_repr(rtyper):
440 return rtyper.rootclass_repr
441
442 # ____________________________________________________________
443
444
445 class __extend__(annmodel.SomeInstance):
446 def rtyper_makerepr(self, rtyper):
447 return getinstancerepr(rtyper, self.classdef)
448
449 def rtyper_makekey(self):
450 return self.__class__, self.classdef
451
452 class __extend__(annmodel.SomeException):
453 def rtyper_makerepr(self, rtyper):
454 return self.as_SomeInstance().rtyper_makerepr(rtyper)
455
456 def rtyper_makekey(self):
457 return self.__class__, frozenset(self.classdefs)
458
459 class __extend__(annmodel.SomeType):
460 def rtyper_makerepr(self, rtyper):
461 return get_type_repr(rtyper)
462
463 def rtyper_makekey(self):
464 return self.__class__,
465
466
467 class InstanceRepr(Repr):
468 def __init__(self, rtyper, classdef, gcflavor='gc'):
469 self.rtyper = rtyper
470 self.classdef = classdef
471 if classdef is None:
472 self.object_type = OBJECT_BY_FLAVOR[LLFLAVOR[gcflavor]]
473 else:
474 ForwardRef = lltype.FORWARDREF_BY_FLAVOR[LLFLAVOR[gcflavor]]
475 self.object_type = ForwardRef()
476 self.iprebuiltinstances = identity_dict()
477 self.lowleveltype = Ptr(self.object_type)
478 self.gcflavor = gcflavor
479
480 def has_special_memory_pressure(self, tp):
481 if 'special_memory_pressure' in tp._flds:
482 return True
483 if 'super' in tp._flds:
484 return self.has_special_memory_pressure(tp._flds['super'])
485 return False
486
487 def _setup_repr(self, llfields=None, hints=None, adtmeths=None):
488 # NOTE: don't store mutable objects like the dicts below on 'self'
489 # before they are fully built, to avoid strange bugs in case
490 # of recursion where other code would uses these
491 # partially-initialized dicts.
492 if self.classdef is None:
493 self.immutable_field_set = set()
494 self.rclass = getclassrepr(self.rtyper, self.classdef)
495 fields = {}
496 allinstancefields = {}
497 if self.classdef is None:
498 fields['__class__'] = 'typeptr', get_type_repr(self.rtyper)
499 else:
500 # instance attributes
501 attrs = self.classdef.attrs.items()
502 attrs.sort()
503 myllfields = []
504 for name, attrdef in attrs:
505 if not attrdef.readonly:
506 r = self.rtyper.getrepr(attrdef.s_value)
507 mangled_name = 'inst_' + name
508 fields[name] = mangled_name, r
509 myllfields.append((mangled_name, r.lowleveltype))
510
511 myllfields.sort(key=attr_reverse_size)
512 if llfields is None:
513 llfields = myllfields
514 else:
515 llfields = llfields + myllfields
516
517 self.rbase = getinstancerepr(self.rtyper, self.classdef.basedef,
518 self.gcflavor)
519 self.rbase.setup()
520
521 MkStruct = lltype.STRUCT_BY_FLAVOR[LLFLAVOR[self.gcflavor]]
522 if adtmeths is None:
523 adtmeths = {}
524 if hints is None:
525 hints = {}
526 hints = self._check_for_immutable_hints(hints)
527 if self.classdef.classdesc.get_param('_rpython_never_allocate_'):
528 hints['never_allocate'] = True
529
530 kwds = {}
531 if self.gcflavor == 'gc':
532 kwds['rtti'] = True
533
534 for name, attrdef in attrs:
535 if not attrdef.readonly and self.is_quasi_immutable(name):
536 llfields.append(('mutate_' + name, OBJECTPTR))
537
538 bookkeeper = self.rtyper.annotator.bookkeeper
539 if self.classdef in bookkeeper.memory_pressure_types:
540 # we don't need to add it if it's already there for some of
541 # the parent type
542 if not self.has_special_memory_pressure(self.rbase.object_type):
543 llfields.append(('special_memory_pressure', lltype.Signed))
544 fields['special_memory_pressure'] = (
545 'special_memory_pressure',
546 self.rtyper.getrepr(lltype_to_annotation(lltype.Signed)))
547
548 object_type = MkStruct(self.classdef.name,
549 ('super', self.rbase.object_type),
550 hints=hints,
551 adtmeths=adtmeths,
552 *llfields,
553 **kwds)
554 self.object_type.become(object_type)
555 allinstancefields.update(self.rbase.allinstancefields)
556 allinstancefields.update(fields)
557 self.fields = fields
558 self.allinstancefields = allinstancefields
559
560 def _check_for_immutable_hints(self, hints):
561 hints = hints.copy()
562 classdesc = self.classdef.classdesc
563 immut = classdesc.get_param('_immutable_', inherit=False)
564 if immut is None:
565 if classdesc.get_param('_immutable_', inherit=True):
566 raise ImmutableConflictError(
567 "class %r inherits from its parent _immutable_=True, "
568 "so it should also declare _immutable_=True" % (
569 self.classdef,))
570 elif immut is not True:
571 raise TyperError(
572 "class %r: _immutable_ = something else than True" % (
573 self.classdef,))
574 else:
575 hints['immutable'] = True
576 self.immutable_field_set = classdesc.immutable_fields
577 if (classdesc.immutable_fields or
578 'immutable_fields' in self.rbase.object_type._hints):
579 accessor = FieldListAccessor()
580 hints['immutable_fields'] = accessor
581 return hints
582
583 def __repr__(self):
584 if self.classdef is None:
585 clsname = 'object'
586 else:
587 clsname = self.classdef.name
588 return '<InstanceRepr for %s>' % (clsname,)
589
590 def compact_repr(self):
591 if self.classdef is None:
592 clsname = 'object'
593 else:
594 clsname = self.classdef.name
595 return 'InstanceR %s' % (clsname,)
596
597 def _setup_repr_final(self):
598 self._setup_immutable_field_list()
599 self._check_for_immutable_conflicts()
600 if self.gcflavor == 'gc':
601 if (self.classdef is not None and
602 self.classdef.classdesc.lookup('__del__') is not None):
603 s_func = self.classdef.classdesc.s_read_attribute('__del__')
604 source_desc = self.classdef.classdesc.lookup('__del__')
605 source_classdef = source_desc.getclassdef(None)
606 source_repr = getinstancerepr(self.rtyper, source_classdef)
607 assert len(s_func.descriptions) == 1
608 funcdesc, = s_func.descriptions
609 graph = funcdesc.getuniquegraph()
610 self.check_graph_of_del_does_not_call_too_much(self.rtyper,
611 graph)
612 FUNCTYPE = FuncType([Ptr(source_repr.object_type)], Void)
613 destrptr = functionptr(FUNCTYPE, graph.name,
614 graph=graph,
615 _callable=graph.func)
616 else:
617 destrptr = None
618 self.rtyper.call_all_setups() # compute ForwardReferences now
619 args_s = [SomePtr(Ptr(OBJECT))]
620 graph = self.rtyper.annotate_helper(ll_runtime_type_info, args_s)
621 s = self.rtyper.annotation(graph.getreturnvar())
622 if (not isinstance(s, SomePtr) or
623 s.ll_ptrtype != Ptr(RuntimeTypeInfo)):
624 raise TyperError("runtime type info function returns %r, "
625 "expected Ptr(RuntimeTypeInfo)" % (s))
626 funcptr = self.rtyper.getcallable(graph)
627 attachRuntimeTypeInfo(self.object_type, funcptr, destrptr)
628
629 vtable = self.rclass.getvtable()
630 self.rtyper.set_type_for_typeptr(vtable, self.lowleveltype.TO)
631
632 def _setup_immutable_field_list(self):
633 hints = self.object_type._hints
634 if "immutable_fields" in hints:
635 accessor = hints["immutable_fields"]
636 if not hasattr(accessor, 'fields'):
637 immutable_fields = set()
638 rbase = self
639 while rbase.classdef is not None:
640 immutable_fields.update(rbase.immutable_field_set)
641 rbase = rbase.rbase
642 self._parse_field_list(immutable_fields, accessor, hints)
643
644 def _parse_field_list(self, fields, accessor, hints):
645 ranking = {}
646 for fullname in fields:
647 name = fullname
648 quasi = False
649 if name.endswith('?[*]'): # a quasi-immutable field pointing to
650 name = name[:-4] # an immutable array
651 rank = IR_QUASIIMMUTABLE_ARRAY
652 quasi = True
653 elif name.endswith('[*]'): # for virtualizables' lists
654 name = name[:-3]
655 rank = IR_IMMUTABLE_ARRAY
656 elif name.endswith('?'): # a quasi-immutable field
657 name = name[:-1]
658 rank = IR_QUASIIMMUTABLE
659 quasi = True
660 else: # a regular immutable/green field
661 rank = IR_IMMUTABLE
662 try:
663 mangled_name, r = self._get_field(name)
664 except KeyError:
665 continue
666 if quasi and hints.get("immutable"):
667 raise TyperError(
668 "can't have _immutable_ = True and a quasi-immutable field "
669 "%s in class %s" % (name, self.classdef))
670 if rank in (IR_QUASIIMMUTABLE_ARRAY, IR_IMMUTABLE_ARRAY):
671 from rpython.rtyper.rlist import AbstractBaseListRepr
672 if not isinstance(r, AbstractBaseListRepr):
673 raise TyperError(
674 "_immutable_fields_ = [%r] in %r, but %r is not a list "
675 "(got %r)" % (fullname, self, name, r))
676 ranking[mangled_name] = rank
677 accessor.initialize(self.object_type, ranking)
678 return ranking
679
680 def _check_for_immutable_conflicts(self):
681 # check for conflicts, i.e. a field that is defined normally as
682 # mutable in some parent class but that is now declared immutable
683 is_self_immutable = "immutable" in self.object_type._hints
684 base = self
685 while base.classdef is not None:
686 base = base.rbase
687 for fieldname in base.fields:
688 if fieldname == 'special_memory_pressure':
689 continue
690 try:
691 mangled, r = base._get_field(fieldname)
692 except KeyError:
693 continue
694 if r.lowleveltype == Void:
695 continue
696 base._setup_immutable_field_list()
697 if base.object_type._immutable_field(mangled):
698 continue
699 # 'fieldname' is a mutable, non-Void field in the parent
700 if is_self_immutable:
701 raise ImmutableConflictError(
702 "class %r has _immutable_=True, but parent class %r "
703 "defines (at least) the mutable field %r" %
704 (self, base, fieldname))
705 if (fieldname in self.immutable_field_set or
706 (fieldname + '?') in self.immutable_field_set):
707 raise ImmutableConflictError(
708 "field %r is defined mutable in class %r, but "
709 "listed in _immutable_fields_ in subclass %r" %
710 (fieldname, base, self))
711
712 def hook_access_field(self, vinst, cname, llops, flags):
713 pass # for virtualizables; see rvirtualizable.py
714
715 def hook_setfield(self, vinst, fieldname, llops):
716 if self.is_quasi_immutable(fieldname):
717 c_fieldname = inputconst(Void, 'mutate_' + fieldname)
718 llops.genop('jit_force_quasi_immutable', [vinst, c_fieldname])
719
720 def is_quasi_immutable(self, fieldname):
721 search1 = fieldname + '?'
722 search2 = fieldname + '?[*]'
723 rbase = self
724 while rbase.classdef is not None:
725 if (search1 in rbase.immutable_field_set or
726 search2 in rbase.immutable_field_set):
727 return True
728 rbase = rbase.rbase
729 return False
730
731 def new_instance(self, llops, classcallhop=None, nonmovable=False):
732 """Build a new instance, without calling __init__."""
733 flavor = self.gcflavor
734 flags = {'flavor': flavor}
735 if nonmovable:
736 flags['nonmovable'] = True
737 ctype = inputconst(Void, self.object_type)
738 cflags = inputconst(Void, flags)
739 vlist = [ctype, cflags]
740 vptr = llops.genop('malloc', vlist,
741 resulttype=Ptr(self.object_type))
742 ctypeptr = inputconst(CLASSTYPE, self.rclass.getvtable())
743 self.setfield(vptr, '__class__', ctypeptr, llops)
744 if self.has_special_memory_pressure(self.object_type):
745 self.setfield(vptr, 'special_memory_pressure',
746 inputconst(lltype.Signed, 0), llops)
747 # initialize instance attributes from their defaults from the class
748 if self.classdef is not None:
749 flds = self.allinstancefields.keys()
750 flds.sort()
751 for fldname in flds:
752 if fldname == '__class__':
753 continue
754 mangled_name, r = self.allinstancefields[fldname]
755 if r.lowleveltype is Void:
756 continue
757 value = self.classdef.classdesc.read_attribute(fldname, None)
758 if value is not None:
759 ll_value = r.convert_desc_or_const(value)
760 # don't write NULL GC pointers: we know that the malloc
761 # done above initialized at least the GC Ptr fields to
762 # NULL already, and that's true for all our GCs
763 if (isinstance(r.lowleveltype, Ptr) and
764 r.lowleveltype.TO._gckind == 'gc' and
765 not ll_value):
766 continue
767 cvalue = inputconst(r.lowleveltype, ll_value)
768 self.setfield(vptr, fldname, cvalue, llops,
769 flags={'access_directly': True})
770 return vptr
771
772 def convert_const(self, value):
773 if value is None:
774 return self.null_instance()
775 if isinstance(value, types.MethodType):
776 value = value.im_self # bound method -> instance
777 bk = self.rtyper.annotator.bookkeeper
778 try:
779 classdef = bk.getuniqueclassdef(value.__class__)
780 except KeyError:
781 raise TyperError("no classdef: %r" % (value.__class__,))
782 if classdef != self.classdef:
783 # if the class does not match exactly, check that 'value' is an
784 # instance of a subclass and delegate to that InstanceRepr
785 if classdef.commonbase(self.classdef) != self.classdef:
786 raise TyperError("not an instance of %r: %r" % (
787 self.classdef.name, value))
788 rinstance = getinstancerepr(self.rtyper, classdef)
789 result = rinstance.convert_const(value)
790 return self.upcast(result)
791 # common case
792 return self.convert_const_exact(value)
793
794 def convert_const_exact(self, value):
795 try:
796 return self.iprebuiltinstances[value]
797 except KeyError:
798 self.setup()
799 result = self.create_instance()
800 self.iprebuiltinstances[value] = result
801 self.initialize_prebuilt_instance(value, self.classdef, result)
802 return result
803
804 def get_reusable_prebuilt_instance(self):
805 "Get a dummy prebuilt instance. Multiple calls reuse the same one."
806 try:
807 return self._reusable_prebuilt_instance
808 except AttributeError:
809 self.setup()
810 result = self.create_instance()
811 self._reusable_prebuilt_instance = result
812 self.initialize_prebuilt_data(Ellipsis, self.classdef, result)
813 return result
814
815 _initialize_data_flattenrec = FlattenRecursion()
816
817 def initialize_prebuilt_instance(self, value, classdef, result):
818 # must fill in the hash cache before the other ones
819 # (see test_circular_hash_initialization)
820 self._initialize_data_flattenrec(self.initialize_prebuilt_data,
821 value, classdef, result)
822
823 def get_ll_hash_function(self):
824 return ll_inst_hash
825
826 get_ll_fasthash_function = get_ll_hash_function
827
828 def rtype_type(self, hop):
829 if hop.s_result.is_constant():
830 return hop.inputconst(hop.r_result, hop.s_result.const)
831 instance_repr = self.common_repr()
832 vinst, = hop.inputargs(instance_repr)
833 if hop.args_s[0].can_be_none():
834 return hop.gendirectcall(ll_inst_type, vinst)
835 else:
836 return instance_repr.getfield(vinst, '__class__', hop.llops)
837
838 def rtype_getattr(self, hop):
839 if hop.s_result.is_constant():
840 return hop.inputconst(hop.r_result, hop.s_result.const)
841 attr = hop.args_s[1].const
842 vinst, vattr = hop.inputargs(self, Void)
843 if attr == '__class__' and hop.r_result.lowleveltype is Void:
844 # special case for when the result of '.__class__' is a constant
845 [desc] = hop.s_result.descriptions
846 return hop.inputconst(Void, desc.pyobj)
847 if attr in self.allinstancefields:
848 return self.getfield(vinst, attr, hop.llops,
849 flags=hop.args_s[0].flags)
850 elif attr in self.rclass.allmethods:
851 # special case for methods: represented as their 'self' only
852 # (see MethodsPBCRepr)
853 return hop.r_result.get_method_from_instance(self, vinst,
854 hop.llops)
855 else:
856 vcls = self.getfield(vinst, '__class__', hop.llops)
857 return self.rclass.getclsfield(vcls, attr, hop.llops)
858
859 def rtype_setattr(self, hop):
860 attr = hop.args_s[1].const
861 r_value = self.getfieldrepr(attr)
862 vinst, vattr, vvalue = hop.inputargs(self, Void, r_value)
863 self.setfield(vinst, attr, vvalue, hop.llops,
864 flags=hop.args_s[0].flags)
865
866 def rtype_bool(self, hop):
867 vinst, = hop.inputargs(self)
868 return hop.genop('ptr_nonzero', [vinst], resulttype=Bool)
869
870 def ll_str(self, i): # doesn't work for non-gc classes!
871 from rpython.rtyper.lltypesystem.ll_str import ll_int2hex
872 from rpython.rlib.rarithmetic import r_uint
873 if not i:
874 return rstr.conststr("NULL")
875 instance = cast_pointer(OBJECTPTR, i)
876 # Two choices: the first gives a fast answer but it can change
877 # (typically only once) during the life of the object.
878 #uid = r_uint(cast_ptr_to_int(i))
879 uid = r_uint(llop.gc_id(lltype.Signed, i))
880 #
881 res = rstr.conststr("<")
882 res = rstr.ll_strconcat(res, instance.typeptr.name)
883 res = rstr.ll_strconcat(res, rstr.conststr(" object at 0x"))
884 res = rstr.ll_strconcat(res, ll_int2hex(uid, False))
885 res = rstr.ll_strconcat(res, rstr.conststr(">"))
886 return res
887
888 def get_ll_eq_function(self):
889 return None # defaults to compare by identity ('==' on pointers)
890
891 def can_ll_be_null(self, s_value):
892 return s_value.can_be_none()
893
894 @staticmethod
895 def check_graph_of_del_does_not_call_too_much(rtyper, graph):
896 # RPython-level __del__() methods should not do "too much".
897 # In the PyPy Python interpreter, they usually do simple things
898 # like file.__del__() closing the file descriptor; or if they
899 # want to do more like call an app-level __del__() method, they
900 # enqueue the object instead, and the actual call is done later.
901 #
902 # Here, as a quick way to check "not doing too much", we check
903 # that from no RPython-level __del__() method we can reach a
904 # JitDriver.
905 #
906 # XXX wrong complexity, but good enough because the set of
907 # reachable graphs should be small
908 callgraph = rtyper.annotator.translator.callgraph.values()
909 seen = {graph: None}
910 while True:
911 oldlength = len(seen)
912 for caller, callee in callgraph:
913 if caller in seen and callee not in seen:
914 func = getattr(callee, 'func', None)
915 if getattr(func, '_dont_reach_me_in_del_', False):
916 lst = [str(callee)]
917 g = caller
918 while g:
919 lst.append(str(g))
920 g = seen.get(g)
921 lst.append('')
922 raise TyperError("the RPython-level __del__() method "
923 "in %r calls:%s" %
924 (graph, '\n\t'.join(lst[::-1])))
925 if getattr(func, '_cannot_really_call_random_things_',
926 False):
927 continue
928 seen[callee] = caller
929 if len(seen) == oldlength:
930 break
931
932 def common_repr(self): # -> object or nongcobject reprs
933 return getinstancerepr(self.rtyper, None, self.gcflavor)
934
935 def _get_field(self, attr):
936 return self.fields[attr]
937
938 def null_instance(self):
939 return nullptr(self.object_type)
940
941 def upcast(self, result):
942 return cast_pointer(self.lowleveltype, result)
943
944 def create_instance(self):
945 return malloc(self.object_type, flavor=self.gcflavor, immortal=True)
946
947 def initialize_prebuilt_data(self, value, classdef, result):
948 if self.classdef is not None:
949 # recursively build the parent part of the instance
950 self.rbase.initialize_prebuilt_data(value, classdef, result.super)
951 # then add instance attributes from this level
952 for name, (mangled_name, r) in self.fields.items():
953 if r.lowleveltype is Void:
954 llattrvalue = None
955 else:
956 try:
957 attrvalue = getattr(value, name)
958 except AttributeError:
959 attrvalue = self.classdef.classdesc.read_attribute(
960 name, None)
961 if attrvalue is None:
962 # Ellipsis from get_reusable_prebuilt_instance()
963 #if value is not Ellipsis:
964 #warning("prebuilt instance %r has no "
965 # "attribute %r" % (value, name))
966 llattrvalue = r.lowleveltype._defl()
967 else:
968 llattrvalue = r.convert_desc_or_const(attrvalue)
969 else:
970 llattrvalue = r.convert_const(attrvalue)
971 setattr(result, mangled_name, llattrvalue)
972 else:
973 # OBJECT part
974 rclass = getclassrepr(self.rtyper, classdef)
975 result.typeptr = rclass.getvtable()
976
977 def getfieldrepr(self, attr):
978 """Return the repr used for the given attribute."""
979 if attr in self.fields:
980 mangled_name, r = self.fields[attr]
981 return r
982 else:
983 if self.classdef is None:
984 raise MissingRTypeAttribute(attr)
985 return self.rbase.getfieldrepr(attr)
986
987 def getfield(self, vinst, attr, llops, force_cast=False, flags={}):
988 """Read the given attribute (or __class__ for the type) of 'vinst'."""
989 if attr in self.fields:
990 mangled_name, r = self.fields[attr]
991 cname = inputconst(Void, mangled_name)
992 if force_cast:
993 vinst = llops.genop('cast_pointer', [vinst], resulttype=self)
994 self.hook_access_field(vinst, cname, llops, flags)
995 return llops.genop('getfield', [vinst, cname], resulttype=r)
996 else:
997 if self.classdef is None:
998 raise MissingRTypeAttribute(attr)
999 return self.rbase.getfield(vinst, attr, llops, force_cast=True,
1000 flags=flags)
1001
1002 def setfield(self, vinst, attr, vvalue, llops, force_cast=False,
1003 flags={}):
1004 """Write the given attribute (or __class__ for the type) of 'vinst'."""
1005 if attr in self.fields:
1006 mangled_name, r = self.fields[attr]
1007 cname = inputconst(Void, mangled_name)
1008 if force_cast:
1009 vinst = llops.genop('cast_pointer', [vinst], resulttype=self)
1010 self.hook_access_field(vinst, cname, llops, flags)
1011 self.hook_setfield(vinst, attr, llops)
1012 llops.genop('setfield', [vinst, cname, vvalue])
1013 else:
1014 if self.classdef is None:
1015 raise MissingRTypeAttribute(attr)
1016 self.rbase.setfield(vinst, attr, vvalue, llops, force_cast=True,
1017 flags=flags)
1018
1019 def rtype_isinstance(self, hop):
1020 class_repr = get_type_repr(hop.rtyper)
1021 instance_repr = self.common_repr()
1022
1023 v_obj, v_cls = hop.inputargs(instance_repr, class_repr)
1024 if isinstance(v_cls, Constant):
1025 cls = v_cls.value
1026 llf, llf_nonnull = make_ll_isinstance(self.rtyper, cls)
1027 if hop.args_s[0].can_be_None:
1028 return hop.gendirectcall(llf, v_obj)
1029 else:
1030 return hop.gendirectcall(llf_nonnull, v_obj)
1031 else:
1032 return hop.gendirectcall(ll_isinstance, v_obj, v_cls)
1033
1034
1035 class __extend__(pairtype(InstanceRepr, InstanceRepr)):
1036 def convert_from_to((r_ins1, r_ins2), v, llops):
1037 # which is a subclass of which?
1038 if r_ins1.classdef is None or r_ins2.classdef is None:
1039 basedef = None
1040 else:
1041 basedef = r_ins1.classdef.commonbase(r_ins2.classdef)
1042 if basedef == r_ins2.classdef:
1043 # r_ins1 is an instance of the subclass: converting to parent
1044 v = llops.genop('cast_pointer', [v],
1045 resulttype=r_ins2.lowleveltype)
1046 return v
1047 elif basedef == r_ins1.classdef:
1048 # r_ins2 is an instance of the subclass: potentially unsafe
1049 # casting, but we do it anyway (e.g. the annotator produces
1050 # such casts after a successful isinstance() check)
1051 v = llops.genop('cast_pointer', [v],
1052 resulttype=r_ins2.lowleveltype)
1053 return v
1054 else:
1055 return NotImplemented
1056
1057 def rtype_is_((r_ins1, r_ins2), hop):
1058 if r_ins1.gcflavor != r_ins2.gcflavor:
1059 # obscure logic, the is can be true only if both are None
1060 v_ins1, v_ins2 = hop.inputargs(
1061 r_ins1.common_repr(), r_ins2.common_repr())
1062 return hop.gendirectcall(ll_both_none, v_ins1, v_ins2)
1063 if r_ins1.classdef is None or r_ins2.classdef is None:
1064 basedef = None
1065 else:
1066 basedef = r_ins1.classdef.commonbase(r_ins2.classdef)
1067 r_ins = getinstancerepr(r_ins1.rtyper, basedef, r_ins1.gcflavor)
1068 return pairtype(Repr, Repr).rtype_is_(pair(r_ins, r_ins), hop)
1069
1070 rtype_eq = rtype_is_
1071
1072 def rtype_ne(rpair, hop):
1073 v = rpair.rtype_eq(hop)
1074 return hop.genop("bool_not", [v], resulttype=Bool)
1075
1076 # ____________________________________________________________
1077
1078 def rtype_new_instance(rtyper, classdef, llops, classcallhop=None,
1079 nonmovable=False):
1080 rinstance = getinstancerepr(rtyper, classdef)
1081 return rinstance.new_instance(llops, classcallhop, nonmovable=nonmovable)
1082
1083 def ll_inst_hash(ins):
1084 if not ins:
1085 return 0 # for None
1086 else:
1087 return lltype.identityhash(ins)
1088
1089
1090 _missing = object()
1091
1092 def fishllattr(inst, name, default=_missing):
1093 p = widest = lltype.normalizeptr(inst)
1094 while True:
1095 try:
1096 return getattr(p, 'inst_' + name)
1097 except AttributeError:
1098 pass
1099 try:
1100 p = p.super
1101 except AttributeError:
1102 break
1103 if default is _missing:
1104 raise AttributeError("%s has no field %s" %
1105 (lltype.typeOf(widest), name))
1106 return default
1107
1108 def attr_reverse_size((_, T)):
1109 # This is used to sort the instance or class attributes by decreasing
1110 # "likely size", as reported by rffi.sizeof(), to minimize padding
1111 # holes in C. Fields should first be sorted by name, just to minimize
1112 # randomness, and then (stably) sorted by 'attr_reverse_size'.
1113 if T is lltype.Void:
1114 return None
1115 from rpython.rtyper.lltypesystem.rffi import sizeof
1116 try:
1117 return -sizeof(T)
1118 except StandardError:
1119 return None
1120
1121 # ____________________________________________________________
1122 #
1123 # Low-level implementation of operations on classes and instances
1124
1125 # doesn't work for non-gc stuff!
1126 def ll_cast_to_object(obj):
1127 return cast_pointer(OBJECTPTR, obj)
1128
1129 # doesn't work for non-gc stuff!
1130 def ll_type(obj):
1131 return cast_pointer(OBJECTPTR, obj).typeptr
1132
1133 def ll_issubclass(subcls, cls):
1134 return llop.int_between(Bool,
1135 cls.subclassrange_min,
1136 subcls.subclassrange_min,
1137 cls.subclassrange_max)
1138
1139 def ll_issubclass_const(subcls, minid, maxid):
1140 return llop.int_between(Bool, minid, subcls.subclassrange_min, maxid)
1141
1142
1143 def ll_isinstance(obj, cls): # obj should be cast to OBJECT or NONGCOBJECT
1144 if not obj:
1145 return False
1146 obj_cls = obj.typeptr
1147 return ll_issubclass(obj_cls, cls)
1148
1149 def make_ll_isinstance(rtyper, cls):
1150 try:
1151 return rtyper.isinstance_helpers[cls._obj]
1152 except KeyError:
1153 minid = cls.subclassrange_min
1154 maxid = cls.subclassrange_max
1155 if minid.number_with_subclasses():
1156 def ll_isinstance_const_nonnull(obj):
1157 objid = obj.typeptr.subclassrange_min
1158 return llop.int_between(Bool, minid, objid, maxid)
1159 else:
1160 def ll_isinstance_const_nonnull(obj):
1161 return obj.typeptr == cls
1162 def ll_isinstance_const(obj):
1163 if not obj:
1164 return False
1165 return ll_isinstance_const_nonnull(obj)
1166 result = (ll_isinstance_const, ll_isinstance_const_nonnull)
1167 rtyper.isinstance_helpers[cls._obj] = result
1168 return result
1169
1170 def ll_runtime_type_info(obj):
1171 return obj.typeptr.rtti
1172
1173 def ll_inst_type(obj):
1174 if obj:
1175 return obj.typeptr
1176 else:
1177 # type(None) -> NULL (for now)
1178 return nullptr(typeOf(obj).TO.typeptr.TO)
1179
1180 def ll_both_none(ins1, ins2):
1181 return not ins1 and not ins2
1182
1183 # ____________________________________________________________
1184
1185 def feedllattr(inst, name, llvalue):
1186 p = widest = lltype.normalizeptr(inst)
1187 while True:
1188 try:
1189 return setattr(p, 'inst_' + name, llvalue)
1190 except AttributeError:
1191 pass
1192 try:
1193 p = p.super
1194 except AttributeError:
1195 break
1196 raise AttributeError("%s has no field %s" % (lltype.typeOf(widest),
1197 name))
1198
1199 def declare_type_for_typeptr(vtable, TYPE):
1200 """Hack for custom low-level-only 'subclasses' of OBJECT:
1201 call this somewhere annotated, in order to declare that it is
1202 of the given TYPE and has got the corresponding vtable."""
1203
1204 class Entry(ExtRegistryEntry):
1205 _about_ = declare_type_for_typeptr
1206
1207 def compute_result_annotation(self, s_vtable, s_TYPE):
1208 assert s_vtable.is_constant()
1209 assert s_TYPE.is_constant()
1210 return annmodel.s_None
1211
1212 def specialize_call(self, hop):
1213 vtable = hop.args_v[0].value
1214 TYPE = hop.args_v[1].value
1215 assert lltype.typeOf(vtable) == CLASSTYPE
1216 assert isinstance(TYPE, GcStruct)
1217 assert lltype._castdepth(TYPE, OBJECT) > 0
1218 hop.rtyper.set_type_for_typeptr(vtable, TYPE)
1219 hop.exception_cannot_occur()
1220 return hop.inputconst(lltype.Void, None)