Debian Codegraph @

pypy/interpreter/typedef.py

raw symbols SCIP
1 import py
2
3 from pypy.interpreter.argument import Arguments
4 from pypy.interpreter.baseobjspace import W_Root, DescrMismatch
5 from pypy.interpreter.error import OperationError, oefmt
6 from pypy.interpreter.gateway import (interp2app, BuiltinCode, unwrap_spec,
7 WrappedDefault, descr_function_get)
8
9 from rpython.rlib.jit import promote
10 from rpython.rlib.objectmodel import compute_identity_hash, specialize
11 from rpython.rlib.objectmodel import instantiate, not_rpython, try_inline, dont_inline
12 from rpython.tool.sourcetools import compile2, func_with_new_name
13 from pypy.objspace.std.util import generic_alias_class_getitem
14
15
16 class TypeDef(object):
17 @not_rpython
18 def __init__(self, __name, __base=None, __total_ordering__=None,
19 __buffer=None, __confirm_applevel_del__=False,
20 _text_signature_=None, variable_sized=False,
21 __rpython_level_class__=None,
22 method_descriptor=False,
23 **rawdict):
24 "initialization-time only"
25 self.name = __name
26 if __base is None:
27 bases = []
28 elif isinstance(__base, tuple):
29 bases = list(__base)
30 else:
31 bases = [__base]
32 self.bases = bases
33 # Used in cpyext to fill tp_as_buffer slots
34 assert __buffer in {None, 'read-write', 'read'}, "Unknown value for __buffer"
35 for base in bases:
36 if __buffer is None:
37 __buffer = base.buffer
38 self.buffer = __buffer
39 self.heaptype = False
40 self.hasdict = '__dict__' in rawdict
41 # no __del__: use an RPython _finalize_() method and register_finalizer
42 if not __confirm_applevel_del__:
43 assert '__del__' not in rawdict
44 self.weakrefable = '__weakref__' in rawdict
45 doc_candidate = rawdict.get('__doc__', None)
46 if isinstance(doc_candidate, str):
47 self.doc = doc_candidate
48 else:
49 self.doc = None
50 self.text_signature = _text_signature_
51 for base in bases:
52 self.hasdict |= base.hasdict
53 self.weakrefable |= base.weakrefable
54 self.rawdict = {}
55 self.acceptable_as_base_class = '__new__' in rawdict
56 self.applevel_subclasses_base = None
57 self.add_entries(**rawdict)
58 assert __total_ordering__ in (None, ), "__total_ordering__ was buggy, mostly unused, and has been removed"
59 self.variable_sized = variable_sized
60 self.rpy_cls = __rpython_level_class__
61 self.method_descriptor = method_descriptor
62 self._install_shortcuts()
63
64 def add_entries(self, **rawdict):
65 # xxx fix the names of the methods to match what app-level expects
66 for key, value in rawdict.items():
67 if isinstance(value, (interp2app, GetSetProperty)):
68 value.name = key
69 if isinstance(value, interp2app):
70 # Mark as a type method so _generate_text_signature uses
71 # CPython-compatible $first_arg convention instead of
72 # $module + first_arg.
73 value._is_type_method = True
74 self.rawdict.update(rawdict)
75
76 def _freeze_(self):
77 # hint for the annotator: track individual constant instances of TypeDef
78 return True
79
80 def __repr__(self):
81 return "<%s name=%r>" % (self.__class__.__name__, self.name)
82
83 def _install_shortcuts(self):
84 rawdict = self.rawdict
85 # guess the class, if not given explicitly
86 rpy_cls = self.rpy_cls
87 for key, val in rawdict.iteritems():
88 ncls = None
89 if isinstance(val, interp2app):
90 ncls = val.self_type
91 if ncls:
92 if rpy_cls is None:
93 rpy_cls = ncls
94 else:
95 if issubclass(ncls, rpy_cls):
96 rpy_cls = ncls # use most specific class
97 else:
98 assert issubclass(rpy_cls, ncls)
99 if rpy_cls is None:
100 # safety check: if rpy_cls is unknown, and one of the SHORTCUTS is
101 # in rawdict, the shortcut could be wrong (if we have an
102 # intermediate class that's not W_Root).
103 names = [name for name, shortcut_name, fallback, checkerfunc in SHORTCUTS
104 if name in rawdict]
105 assert not names
106 return
107 self.rpy_cls = rpy_cls
108 if 'micronumpy' in rpy_cls.__module__:
109 return
110 if '_descroperation_shortcuts_installed' in rpy_cls.__dict__:
111 return
112 rpy_cls._descroperation_shortcuts_installed = True
113 for name, shortcut_name, fallback, checkerfunc in SHORTCUTS:
114 if name not in rawdict or rawdict[name]._staticdefs:
115 if W_Root not in rpy_cls.__bases__:
116
117 shortcut = getattr(rpy_cls, shortcut_name).im_func
118 if shortcut is not fallback:
119 assert shortcut.source_typedef in self.all_bases(), \
120 "getting a wrong shortcut %s for class %s from some base class that is not W_Root" % (name, rpy_cls)
121 continue
122 shortcut_func = rawdict[name]._make_descroperation_shortcut(
123 name, rpy_cls, checkerfunc)
124 shortcut_func.source_typedef = self
125 setattr(rpy_cls, shortcut_name, shortcut_func)
126
127 def all_bases(self):
128 for base in self.bases:
129 yield base
130 for up in base.all_bases():
131 yield up
132
133
134
135 # ____________________________________________________________
136 # Hash support
137
138 def default_identity_hash(space, w_obj):
139 w_unique_id = w_obj.immutable_unique_id(space)
140 if w_unique_id is None: # common case
141 return space.newint(compute_identity_hash(w_obj))
142 else:
143 return space.hash(w_unique_id)
144
145 # ____________________________________________________________
146 #
147 # For each built-in app-level type Xxx that can be subclassed at
148 # app-level, the corresponding interp-level W_XxxObject class cannot
149 # generally represent instances of app-level subclasses of Xxx. The
150 # reason is that it is missing a place to store the __dict__, the slots,
151 # the weakref lifeline, and it typically has no interp-level __del__.
152 # So we create a few interp-level subclasses of W_XxxObject, which add
153 # some combination of features. This is done using mapdict.
154
155 # Note that nowadays, we need not "a few" but only one subclass. It
156 # adds mapdict, which flexibly allows all features. We handle the
157 # presence or absence of an app-level '__del__' by calling
158 # register_finalizer() or not.
159
160 @specialize.memo()
161 @not_rpython
162 def get_unique_interplevel_subclass(space, cls):
163 "initialization-time only"
164 assert cls.typedef.acceptable_as_base_class
165 try:
166 return _unique_subclass_cache[cls]
167 except KeyError:
168 subcls = _getusercls(cls)
169 assert cls not in _unique_subclass_cache
170 _unique_subclass_cache[cls] = subcls
171 return subcls
172 _unique_subclass_cache = {}
173
174 def _getusercls(cls):
175 from rpython.rlib import objectmodel
176 from pypy.objspace.std.objectobject import W_ObjectObject
177 from pypy.objspace.std.mapdict import (BaseUserClassMapdict,
178 MapdictDictSupport, MapdictWeakrefSupport,
179 _make_storage_mixin_size_n, MapdictStorageMixin,
180 MapdictHPySupport)
181 # some subtleties here: We want w_obj.getclass to be a small func
182 # set, ie less than 5 different implementations. That way, it can be
183 # inlined into its callers. This means we cannot give every single
184 # user-defined subclass its own getclass, instead we use the same function
185 # for all of them. This has the effect that the call to
186 # w_obj._get_mapdict_map() in BaseUserClassMapdict.getclass is an
187 # *indirect* call. That's fine, however, we want the object subclasses to
188 # work somewhat better than the rest, so W_ObjectObjectUserDictWeakrefable
189 # should have a *copy* of getclass. This is all achieved by using
190 # _share_methods (which shares functions, does not create copies) instead of
191 # import_from_mixin, which *does* copy functions. There is a test for all
192 # of this in test_mapdict.py, test_correct_method_sharing
193 typedef = cls.typedef
194 name = cls.__name__ + "User"
195 isobjectsubclass = cls is W_ObjectObject
196
197 if isobjectsubclass:
198 base_mixin = _make_storage_mixin_size_n()
199 else:
200 base_mixin = MapdictStorageMixin
201 if not isobjectsubclass:
202 shared_methods = [BaseUserClassMapdict]
203 else:
204 shared_methods = []
205 if not typedef.hasdict:
206 # the type has no dict, mapdict to provide the dict
207 shared_methods.append(MapdictDictSupport)
208 name += "Dict"
209 if not typedef.weakrefable:
210 # the type does not support weakrefs yet, mapdict to provide weakref
211 # support
212 shared_methods.append(MapdictWeakrefSupport)
213 name += "Weakrefable"
214 shared_methods.append(MapdictHPySupport)
215
216 class subcls(cls):
217 user_overridden_class = True
218 objectmodel.import_from_mixin(base_mixin)
219 if isobjectsubclass:
220 objectmodel.import_from_mixin(BaseUserClassMapdict)
221
222 for _, shortcut_name, meth, _ in SHORTCUTS:
223 setattr(subcls, shortcut_name, meth)
224
225 for copycls in shared_methods:
226 _share_methods(copycls, subcls)
227 subcls.__name__ = name
228 return subcls
229
230 def _share_methods(copycls, subcls):
231 for key, value in copycls.__dict__.items():
232 if (not key.startswith('__') or key == '__del__'):
233 setattr(subcls, key, value)
234
235 # ____________________________________________________________
236 # descroperation shortcuts
237
238 SHORTCUTS = []
239
240 def use_special_method_shortcut(name, checkerfunc=None):
241 """
242 use a shortcut for implementations of the special method 'name' for
243 built-in types in the decorated descroperation function. The behaviour for
244 builtin types will be equivalent to:
245
246 w_descr = space.lookup(w_obj, name)
247 return space.get_and_call_function(w_descr, w_obj)
248
249 but only if the special method name exists in the type. Note that this
250 means if the descroperation method contains extra logic after the
251 get_and_call_function it will be ignored (which is often safe for built-in
252 types).
253
254 checkerfunc is a non-translation only safety: it's called with the space
255 and the result of the get_and_call_function call and must return True.
256 """
257 def wrapper(func):
258 @dont_inline
259 def shortcut_fallback(self, space, *args_w):
260 return func(space, self, *args_w)
261 shortcut_fallback.func_name = "shortcut_fallback_%s" % name
262 shortcut_name = "shortcut_%s" % name
263 SHORTCUTS.append((name, shortcut_name, shortcut_fallback, checkerfunc))
264 @try_inline
265 def call_shortcut(space, self, *args_w):
266 return getattr(self, shortcut_name)(space, *args_w)
267 setattr(W_Root, shortcut_name, shortcut_fallback)
268 return call_shortcut
269 return wrapper
270
271
272 # ____________________________________________________________
273
274 @specialize.arg(0)
275 def make_descr_typecheck_wrapper(tag, func, extraargs=(), cls=None,
276 use_closure=False):
277 if func is None:
278 return None
279 return _make_descr_typecheck_wrapper(tag, func, extraargs, cls, use_closure)
280
281 @specialize.memo()
282 def _make_descr_typecheck_wrapper(tag, func, extraargs, cls, use_closure):
283 from rpython.flowspace.bytecode import cpython_code_signature
284 # - if cls is None, the wrapped object is passed to the function
285 # - if cls is a class, an unwrapped instance is passed
286 if cls is None and use_closure:
287 return func
288 if hasattr(func, 'im_func'):
289 assert func.im_class is cls
290 func = func.im_func
291
292 miniglobals = {
293 func.__name__: func,
294 'OperationError': OperationError
295 }
296 if cls is None:
297 source = """
298 def descr_typecheck_%(name)s(closure, space, obj, %(extra)s):
299 return %(name)s(%(args)s, %(extra)s)
300 """
301 else:
302 cls_name = cls.__name__
303 assert issubclass(cls, W_Root)
304 source = """
305 def descr_typecheck_%(name)s(closure, space, w_obj, %(extra)s):
306 obj = space.descr_self_interp_w(%(cls_name)s, w_obj)
307 return %(name)s(%(args)s, %(extra)s)
308 """
309 miniglobals[cls_name] = cls
310
311 name = func.__name__
312 extra = ', '.join(extraargs)
313 sig = cpython_code_signature(func.func_code)
314 argnames = sig.argnames
315 if use_closure:
316 if argnames[1] == 'space':
317 args = "closure, space, obj"
318 else:
319 args = "closure, obj, space"
320 else:
321 if argnames[0] == 'space':
322 args = "space, obj"
323 else:
324 args = "obj, space"
325 source = py.code.Source(source % locals())
326 exec source.compile() in miniglobals
327 return miniglobals['descr_typecheck_%s' % func.__name__]
328
329 class GetSetProperty(W_Root):
330 _immutable_fields_ = ["fget", "fset", "fdel"]
331 w_objclass = None
332
333 @specialize.arg(7)
334 def __init__(self, fget, fset=None, fdel=None, doc=None,
335 cls=None, use_closure=False, tag=None, name=None):
336 if fget and hasattr(fget, 'im_func'):
337 assert not cls or cls is fget.im_class
338 cls = fget.im_class
339 fget = make_descr_typecheck_wrapper((tag, 0), fget,
340 cls=cls, use_closure=use_closure)
341 fset = make_descr_typecheck_wrapper((tag, 1), fset, ('w_value',),
342 cls=cls, use_closure=use_closure)
343 fdel = make_descr_typecheck_wrapper((tag, 2), fdel,
344 cls=cls, use_closure=use_closure)
345 self._init(fget, fset, fdel, doc, cls, use_closure,
346 name)
347
348 def _init(self, fget, fset, fdel, doc, cls, use_closure,
349 name):
350 self.fget = fget
351 self.fset = fset
352 self.fdel = fdel
353 self.doc = doc
354 self.reqcls = cls
355 self.w_qualname = None
356 self.use_closure = use_closure
357 self.name = name if name is not None else '<generic property>'
358
359 def copy_for_type(self, w_objclass):
360 if self.reqcls is None:
361 new = instantiate(GetSetProperty)
362 new._init(self.fget, self.fset, self.fdel, self.doc, self.reqcls,
363 self.use_closure, self.name)
364 new.w_objclass = w_objclass
365 return new
366 else:
367 return self
368
369 @unwrap_spec(w_cls = WrappedDefault(None))
370 def descr_property_get(self, space, w_obj, w_cls=None):
371 """property.__get__(obj[, type]) -> value
372 Read the value of the property of the given obj."""
373 # XXX HAAAAAAAAAAAACK (but possibly a good one)
374 if (space.is_w(w_obj, space.w_None)
375 and not space.is_w(w_cls, space.type(space.w_None))):
376 #print self, w_obj, w_cls
377 if space.is_w(w_cls, space.w_None):
378 raise oefmt(space.w_TypeError, "__get__(None, None) is invalid")
379 return self
380 else:
381 try:
382 return self.fget(self, space, w_obj)
383 except DescrMismatch:
384 return w_obj.descr_call_mismatch(
385 space, '__getattribute__',
386 self.reqcls, Arguments(space, [w_obj,
387 space.newtext(self.name)]))
388
389 def readonly_attribute(self, space): # overwritten in cpyext
390 if self.name == '<generic property>':
391 raise oefmt(space.w_AttributeError, "readonly attribute")
392 else:
393 raise oefmt(space.w_AttributeError, "readonly attribute '%s'", self.name)
394
395 def descr_property_set(self, space, w_obj, w_value):
396 """property.__set__(obj, value)
397 Change the value of the property of the given obj."""
398 fset = self.fset
399 if fset is None:
400 raise self.readonly_attribute(space)
401 try:
402 fset(self, space, w_obj, w_value)
403 except DescrMismatch:
404 w_obj.descr_call_mismatch(
405 space, '__setattr__',
406 self.reqcls, Arguments(space, [w_obj,
407 space.newtext(self.name),
408 w_value]))
409
410 def descr_property_del(self, space, w_obj):
411 """property.__delete__(obj)
412 Delete the value of the property from the given obj."""
413 fdel = self.fdel
414 if fdel is None:
415 raise oefmt(space.w_AttributeError,
416 "cannot delete '%s' attribute of immutable type '%N'", self.name, w_obj)
417 try:
418 fdel(self, space, w_obj)
419 except DescrMismatch:
420 w_obj.descr_call_mismatch(
421 space, '__delattr__',
422 self.reqcls, Arguments(space, [w_obj,
423 space.newtext(self.name)]))
424
425 def descr_get_objclass(self, space):
426 if self.w_objclass is not None:
427 return self.w_objclass
428 if self.reqcls is not None:
429 return space.gettypeobject(self.reqcls.typedef)
430
431 def descr_get_qualname(self, space):
432 if self.w_qualname is None:
433 self.w_qualname = self._calculate_qualname(space)
434 return self.w_qualname
435
436 def _calculate_qualname(self, space):
437 if self.reqcls is None:
438 type_qualname = '?'
439 else:
440 w_type = space.gettypeobject(self.reqcls.typedef)
441 type_qualname = space.text_w(
442 space.getattr(w_type, space.newtext('__qualname__')))
443 qualname = "%s.%s" % (type_qualname, self.name)
444 return space.newtext(qualname)
445
446 # NB. this is an AttributeError to make inspect.py happy
447 raise oefmt(space.w_AttributeError,
448 "generic self has no __objclass__")
449
450 def spacebind(self, space):
451 if hasattr(space, '_see_getsetproperty'):
452 space._see_getsetproperty(self) # only for fake/objspace.py
453 return self
454
455
456 @not_rpython
457 def interp_attrproperty(name, cls, doc=None, wrapfn=None):
458 "initialization-time only"
459 assert wrapfn is not None
460 def fget(space, obj):
461 return getattr(space, wrapfn)(getattr(obj, name))
462 return GetSetProperty(fget, cls=cls, doc=doc)
463
464 @not_rpython
465 def interp_attrproperty_w(name, cls, doc=None):
466 "initialization-time only"
467 def fget(space, obj):
468 w_value = getattr(obj, name)
469 if w_value is None:
470 return space.w_None
471 else:
472 return w_value
473
474 return GetSetProperty(fget, cls=cls, doc=doc)
475
476 GetSetProperty.typedef = TypeDef(
477 "getset_descriptor",
478 __get__ = interp2app(GetSetProperty.descr_property_get),
479 __set__ = interp2app(GetSetProperty.descr_property_set),
480 __delete__ = interp2app(GetSetProperty.descr_property_del),
481 __name__ = interp_attrproperty('name', cls=GetSetProperty, wrapfn="newtext_or_none"),
482 __qualname__ = GetSetProperty(GetSetProperty.descr_get_qualname),
483 __objclass__ = GetSetProperty(GetSetProperty.descr_get_objclass),
484 __doc__ = interp_attrproperty('doc', cls=GetSetProperty, wrapfn="newtext_or_none"),
485 )
486 assert not GetSetProperty.typedef.acceptable_as_base_class # no __new__
487
488
489 class Member(W_Root):
490 """For slots."""
491 _immutable_ = True
492
493 def __init__(self, index, name, w_cls):
494 self.index = index
495 self.name = name
496 self.w_cls = w_cls
497
498 def typecheck(self, space, w_obj):
499 if not space.isinstance_w(w_obj, self.w_cls):
500 raise oefmt(space.w_TypeError,
501 "descriptor '%N' for '%N' objects doesn't apply to "
502 "'%T' object", self, self.w_cls, w_obj)
503
504 def descr_member_get(self, space, w_obj, w_cls=None):
505 """member.__get__(obj[, type]) -> value
506 Read the slot 'member' of the given 'obj'."""
507 if space.is_w(w_obj, space.w_None):
508 return self
509 else:
510 self.typecheck(space, w_obj)
511 w_result = w_obj.getslotvalue(self.index)
512 if w_result is None:
513 raise oefmt(space.w_AttributeError,
514 "'%T' object has no attribute '%s'",
515 w_obj, self.name)
516 return w_result
517
518 def descr_member_set(self, space, w_obj, w_value):
519 """member.__set__(obj, value)
520 Write into the slot 'member' of the given 'obj'."""
521 self.typecheck(space, w_obj)
522 w_obj.setslotvalue(self.index, w_value)
523
524 def descr_member_del(self, space, w_obj):
525 """member.__delete__(obj)
526 Delete the value of the slot 'member' from the given 'obj'."""
527 self.typecheck(space, w_obj)
528 success = w_obj.delslotvalue(self.index)
529 if not success:
530 raise OperationError(space.w_AttributeError,
531 space.newtext(self.name)) # XXX better message
532
533 Member.typedef = TypeDef(
534 "member_descriptor",
535 __get__ = interp2app(Member.descr_member_get),
536 __set__ = interp2app(Member.descr_member_set),
537 __delete__ = interp2app(Member.descr_member_del),
538 __name__ = interp_attrproperty('name', cls=Member, wrapfn="newtext_or_none"),
539 __objclass__ = interp_attrproperty_w('w_cls', cls=Member),
540 )
541 assert not Member.typedef.acceptable_as_base_class # no __new__
542
543 # ____________________________________________________________
544
545 class ClassAttr(W_Root):
546 """For class-level attributes that need to be initialized
547 with some code. This code is provided as a callback function
548 invoked with the space.
549 """
550 def __init__(self, function):
551 self.function = function
552
553 def spacebind(self, space):
554 return self.function(space)
555
556 # ____________________________________________________________
557
558 def generic_new_descr(W_Type):
559 def descr_new(space, w_subtype, __args__):
560 self = space.allocate_instance(W_Type, w_subtype)
561 W_Type.__init__(self, space)
562 return self
563 descr_new = func_with_new_name(descr_new, 'descr_new_%s' % W_Type.__name__)
564 return interp2app(descr_new)
565
566 # ____________________________________________________________
567 #
568 # Definition of the type's descriptors for all the internal types
569
570 from pypy.interpreter.eval import Code
571 from pypy.interpreter.pycode import PyCode, CO_VARARGS, CO_VARKEYWORDS, W_LineIterator
572 from pypy.interpreter.pyframe import PyFrame
573 from pypy.interpreter.pyopcode import SApplicationException
574 from pypy.interpreter.module import Module
575 from pypy.interpreter.function import (Function, Method, StaticMethod,
576 ClassMethod, BuiltinFunction)
577 from pypy.interpreter.pytraceback import PyTraceback
578 from pypy.interpreter.nestedscope import Cell, descr_new_cell
579 from pypy.interpreter.special import NotImplemented, Ellipsis, DisallowNew
580
581
582 def descr_get_dict(space, w_obj):
583 w_dict = w_obj.getdict(space)
584 if w_dict is None:
585 raise oefmt(space.w_TypeError,
586 "descriptor '__dict__' doesn't apply to '%T' objects",
587 w_obj)
588 return w_dict
589
590 def descr_set_dict(space, w_obj, w_dict):
591 w_obj.setdict(space, w_dict)
592
593 def descr_del_dict(space, w_obj): # blame CPython for the existence of this one
594 w_obj.setdict(space, space.newdict())
595
596 def descr_get_weakref(space, w_obj):
597 lifeline = w_obj.getweakref()
598 if lifeline is None:
599 return space.w_None
600 return lifeline.get_any_weakref(space)
601
602 dict_descr = GetSetProperty(descr_get_dict, descr_set_dict, descr_del_dict,
603 doc="dictionary for instance variables")
604 dict_descr.name = '__dict__'
605
606
607 def generic_ne(space, w_obj1, w_obj2):
608 if space.eq_w(w_obj1, w_obj2):
609 return space.w_False
610 else:
611 return space.w_True
612 descr_generic_ne = interp2app(generic_ne)
613
614 # co_xxx interface emulation for built-in code objects
615 def fget_co_varnames(space, code): # unwrapping through unwrap_spec
616 return space.newtuple([space.newtext(name) for name in code.getvarnames()])
617
618 def fget_co_argcount(space, code): # unwrapping through unwrap_spec
619 return space.newint(code.signature().num_argnames())
620
621 def fget_co_posonlyargcount(space, code): # unwrapping through unwrap_spec
622 return space.newint(code.signature().num_posonlyargnames())
623
624 def fget_co_kwonlyargcount(space, code): # unwrapping through unwrap_spec
625 return space.newint(code.signature().num_kwonlyargnames())
626
627 def fget_zero(space, code):
628 return space.newint(0)
629
630 def fget_co_flags(space, code): # unwrapping through unwrap_spec
631 sig = code.signature()
632 flags = 0
633 if sig.has_vararg():
634 flags |= CO_VARARGS
635 if sig.has_kwarg():
636 flags |= CO_VARKEYWORDS
637 return space.newint(flags)
638
639 def fget_co_consts(space, code): # unwrapping through unwrap_spec
640 w_docstring = code.getdocstring(space)
641 return space.newtuple([w_docstring])
642
643 weakref_descr = GetSetProperty(descr_get_weakref,
644 doc="list of weak references to the object")
645 weakref_descr.name = '__weakref__'
646
647 def make_weakref_descr(cls):
648 """Make instances of the W_Root subclass 'cls' weakrefable.
649 This returns the '__weakref__' desctriptor to use for the TypeDef.
650 Note that if the class also defines a custom '__del__', the
651 __del__ should call self.clear_all_weakrefs() before it clears
652 the resources used by the object.
653 """
654 # force the interface into the given cls
655 def getweakref(self):
656 return self._lifeline_
657
658 def setweakref(self, space, weakreflifeline):
659 self._lifeline_ = weakreflifeline
660
661 def delweakref(self):
662 self._lifeline_ = None
663
664 cls._lifeline_ = None
665 cls.getweakref = getweakref
666 cls.setweakref = setweakref
667 cls.delweakref = delweakref
668 return weakref_descr
669
670
671 Code.typedef = TypeDef('internal-code',
672 co_name = interp_attrproperty('co_name', cls=Code, wrapfn="newtext_or_none"),
673 co_varnames = GetSetProperty(fget_co_varnames, cls=Code),
674 co_argcount = GetSetProperty(fget_co_argcount, cls=Code),
675 co_posonlyargcount = GetSetProperty(fget_zero, cls=Code),
676 co_kwonlyargcount = GetSetProperty(fget_zero, cls=Code),
677 co_flags = GetSetProperty(fget_co_flags, cls=Code),
678 co_consts = GetSetProperty(fget_co_consts, cls=Code),
679 )
680 assert not Code.typedef.acceptable_as_base_class # no __new__
681
682 BuiltinCode.typedef = TypeDef('builtin-code',
683 __reduce__ = interp2app(BuiltinCode.descr__reduce__),
684 co_name = interp_attrproperty('co_name', cls=BuiltinCode, wrapfn="newtext_or_none"),
685 co_varnames = GetSetProperty(fget_co_varnames, cls=BuiltinCode),
686 co_argcount = GetSetProperty(fget_co_argcount, cls=BuiltinCode),
687 co_posonlyargcount = GetSetProperty(fget_co_posonlyargcount, cls=BuiltinCode),
688 co_kwonlyargcount = GetSetProperty(fget_co_kwonlyargcount, cls=BuiltinCode),
689 co_flags = GetSetProperty(fget_co_flags, cls=BuiltinCode),
690 co_consts = GetSetProperty(fget_co_consts, cls=BuiltinCode),
691 )
692 assert not BuiltinCode.typedef.acceptable_as_base_class # no __new__
693
694
695 PyCode.typedef = TypeDef('code',
696 __new__ = interp2app(PyCode.descr_code__new__.im_func),
697 __eq__ = interp2app(PyCode.descr_code__eq__),
698 __ne__ = interp2app(PyCode.descr_code__ne__),
699 __hash__ = interp2app(PyCode.descr_code__hash__),
700 __reduce__ = interp2app(PyCode.descr__reduce__),
701 co_positions = interp2app(PyCode.descr_co_positions),
702 __repr__ = interp2app(PyCode.repr),
703 co_argcount = interp_attrproperty('co_argcount', cls=PyCode, wrapfn="newint"),
704 co_posonlyargcount = interp_attrproperty('co_posonlyargcount', cls=PyCode, wrapfn="newint"),
705 co_kwonlyargcount = interp_attrproperty('co_kwonlyargcount', cls=PyCode, wrapfn="newint"),
706 co_nlocals = interp_attrproperty('co_nlocals', cls=PyCode, wrapfn="newint"),
707 co_stacksize = interp_attrproperty('co_stacksize', cls=PyCode, wrapfn="newint"),
708 co_flags = interp_attrproperty('co_flags', cls=PyCode, wrapfn="newint"),
709 co_code = interp_attrproperty('co_code', cls=PyCode, wrapfn="newbytes"),
710 co_consts = GetSetProperty(PyCode.fget_co_consts),
711 co_names = GetSetProperty(PyCode.fget_co_names),
712 co_varnames = GetSetProperty(PyCode.fget_co_varnames),
713 co_freevars = GetSetProperty(PyCode.fget_co_freevars),
714 co_cellvars = GetSetProperty(PyCode.fget_co_cellvars),
715 co_filename = interp_attrproperty_w('w_filename', cls=PyCode),
716 co_name = interp_attrproperty('co_name', cls=PyCode, wrapfn="newtext"),
717 co_qualname = interp_attrproperty('co_qualname', cls=PyCode, wrapfn="newtext"),
718 co_firstlineno = interp_attrproperty('co_firstlineno', cls=PyCode, wrapfn="newint"),
719 co_linetable = interp_attrproperty('co_linetable', cls=PyCode, wrapfn="newbytes"),
720 co_exceptiontable = interp_attrproperty('co_exceptiontable', cls=PyCode, wrapfn="newbytes"),
721 co_lnotab = GetSetProperty(PyCode.fget_co_lnotab),
722 co_lines = interp2app(PyCode.co_lines),
723 replace = interp2app(PyCode.descr_replace),
724 _varname_from_oparg = interp2app(PyCode.descr__varname_from_oparg),
725 __weakref__ = make_weakref_descr(PyCode),
726 )
727 PyCode.typedef.acceptable_as_base_class = False
728
729 W_LineIterator.typedef = TypeDef('line_iterator',
730 __iter__ = interp2app(W_LineIterator.descr_iter),
731 __next__ = interp2app(W_LineIterator.descr_next),
732 )
733 W_LineIterator.typedef.acceptable_as_base_class = False
734
735
736 PyFrame.typedef = TypeDef('frame',
737 #__reduce__ = interp2app(PyFrame.descr__reduce__), --- logic not updated
738 #__setstate__ = interp2app(PyFrame.descr__setstate__),
739 clear = interp2app(PyFrame.descr_clear),
740 f_builtins = GetSetProperty(PyFrame.fget_f_builtins),
741 f_lineno = GetSetProperty(PyFrame.fget_f_lineno, PyFrame.fset_f_lineno),
742 f_back = GetSetProperty(PyFrame.fget_f_back),
743 f_lasti = GetSetProperty(PyFrame.fget_f_lasti),
744 f_trace = GetSetProperty(PyFrame.fget_f_trace, PyFrame.fset_f_trace,
745 PyFrame.fdel_f_trace),
746 f_trace_lines = GetSetProperty(PyFrame.fget_f_trace_lines, PyFrame.fset_f_trace_lines),
747 f_trace_opcodes = GetSetProperty(PyFrame.fget_f_trace_opcodes, PyFrame.fset_f_trace_opcodes),
748 f_code = GetSetProperty(PyFrame.fget_code),
749 f_locals = GetSetProperty(PyFrame.fget_getdictscope),
750 f_globals = GetSetProperty(PyFrame.fget_w_globals),
751 __repr__ = interp2app(PyFrame.descr_repr),
752 )
753 assert not PyFrame.typedef.acceptable_as_base_class # no __new__
754
755 Module.typedef = TypeDef("module",
756 __new__ = interp2app(Module.descr_module__new__.im_func),
757 __init__ = interp2app(Module.descr_module__init__),
758 __repr__ = interp2app(Module.descr_module__repr__),
759 __getattribute__=interp2app(Module.descr_getattribute),
760 __dir__ = interp2app(Module.descr_module__dir__),
761 __reduce__ = interp2app(Module.descr__reduce__),
762 __dict__ = GetSetProperty(descr_get_dict, cls=Module), # module dictionaries are readonly attributes
763 __doc__ = 'module(name[, doc])\n\nCreate a module object.\nThe name must be a string; the optional doc argument can have any type.',
764 __weakref__ = make_weakref_descr(Module),
765 __annotations__ = GetSetProperty(Module.descr_get_annotations,
766 Module.descr_set_annotations,
767 Module.descr_del_annotations),
768 )
769
770 getset_func_doc = GetSetProperty(Function.fget_func_doc,
771 Function.fset_func_doc,
772 Function.fdel_func_doc,
773 )
774
775 # __module__ attribute lazily gets its value from the w_globals
776 # at the time of first invocation. This is not 100% compatible but
777 # avoid problems at the time we construct the first functions when
778 # it's not really possible to do a get or getitem on dictionaries
779 # (mostly because wrapped exceptions don't exist at that time)
780 getset___module__ = GetSetProperty(Function.fget___module__,
781 Function.fset___module__,
782 Function.fdel___module__)
783
784 getset_func_defaults = GetSetProperty(Function.fget_func_defaults,
785 Function.fset_func_defaults,
786 Function.fdel_func_defaults)
787 getset_func_kwdefaults = GetSetProperty(Function.fget_func_kwdefaults,
788 Function.fset_func_kwdefaults,
789 Function.fdel_func_kwdefaults)
790 getset_func_code = GetSetProperty(Function.fget_func_code,
791 Function.fset_func_code)
792 getset_func_name = GetSetProperty(Function.fget_func_name,
793 Function.fset_func_name)
794 getset_func_qualname = GetSetProperty(Function.fget_func_qualname,
795 Function.fset_func_qualname)
796 getset_func_objclass = GetSetProperty(Function.fget_func_objclass)
797 getset_func_text_signature = GetSetProperty(Function.fget_func_text_signature,
798 Function.fset_func_text_signature)
799 getset_func_annotations = GetSetProperty(Function.fget_func_annotations,
800 Function.fset_func_annotations,
801 Function.fdel_func_annotations)
802
803 getset_func_dict = GetSetProperty(descr_get_dict, descr_set_dict, cls=Function)
804
805 Function.typedef = TypeDef("function",
806 _text_signature_="(code, globals, name=None, argdefs=None, closure=None)",
807 method_descriptor=True,
808 __new__ = interp2app(Function.descr_function__new__.im_func),
809 __call__ = interp2app(Function.descr_function_call,
810 descrmismatch='__call__'),
811 __get__ = interp2app(descr_function_get),
812 __repr__ = interp2app(Function.descr_function_repr, descrmismatch='__repr__'),
813 #__reduce__ = interp2app(Function.descr_function__reduce__),
814 #__setstate__ = interp2app(Function.descr_function__setstate__),
815 __code__ = getset_func_code,
816 __doc__ = getset_func_doc,
817 __name__ = getset_func_name,
818 __qualname__ = getset_func_qualname,
819 __objclass__ = getset_func_objclass,
820 __text_signature__ = getset_func_text_signature,
821 __dict__ = getset_func_dict,
822 __defaults__ = getset_func_defaults,
823 __defaults_count__ = GetSetProperty(Function.fget_defaults_count),
824 __kwdefaults__ = getset_func_kwdefaults,
825 __annotations__ = getset_func_annotations,
826 __globals__ = interp_attrproperty_w('w_func_globals', cls=Function),
827 __closure__ = GetSetProperty(Function.fget_func_closure),
828 __module__ = getset___module__,
829 __weakref__ = make_weakref_descr(Function),
830 )
831 Function.typedef.acceptable_as_base_class = False
832
833 Method.typedef = TypeDef(
834 "method",
835 __doc__ = GetSetProperty(Method.descr_get_doc),
836 __new__ = interp2app(Method.descr_method__new__.im_func),
837 __call__ = interp2app(Method.descr_method_call),
838 __get__ = interp2app(Method.descr_method_get),
839 __func__ = interp_attrproperty_w('w_function', cls=Method),
840 __self__ = interp_attrproperty_w('w_instance', cls=Method),
841 __getattribute__ = interp2app(Method.descr_method_getattribute),
842 __eq__ = interp2app(Method.descr_method_eq),
843 __ne__ = interp2app(Method.descr_method_ne),
844 __hash__ = interp2app(Method.descr_method_hash),
845 __repr__ = interp2app(Method.descr_method_repr),
846 __reduce__ = interp2app(Method.descr_method__reduce__),
847 __weakref__ = make_weakref_descr(Method),
848 )
849 Method.typedef.acceptable_as_base_class = False
850 Method.typedef.doc = Method.__doc__
851
852 StaticMethod.typedef = TypeDef("staticmethod",
853 __doc__ = """staticmethod(function) -> static method
854
855 Convert a function to be a static method.
856
857 A static method does not receive an implicit first argument.
858 To declare a static method, use this idiom:
859
860 class C:
861 def f(arg1, arg2, ...): ...
862 f = staticmethod(f)
863
864 It can be called either on the class (e.g. C.f()) or on an instance
865 (e.g. C().f()). The instance is ignored except for its class.""",
866 __get__ = interp2app(StaticMethod.descr_staticmethod_get),
867 __new__ = interp2app(StaticMethod.descr_staticmethod__new__.im_func),
868 __init__=interp2app(StaticMethod.descr_init),
869 __call__=interp2app(StaticMethod.descr_call),
870 __func__= interp_attrproperty_w('w_function', cls=StaticMethod),
871 __wrapped__= interp_attrproperty_w('w_function', cls=StaticMethod),
872 __isabstractmethod__ = GetSetProperty(StaticMethod.descr_isabstract),
873 __dict__ = GetSetProperty(descr_get_dict, descr_set_dict,
874 cls=StaticMethod),
875 __repr__ = interp2app(StaticMethod.descr_repr),
876 __reduce_ex__ = interp2app(StaticMethod.descr_reduce_ex),
877 )
878
879 ClassMethod.typedef = TypeDef(
880 'classmethod',
881 __new__=interp2app(ClassMethod.descr_classmethod__new__.im_func),
882 __init__=interp2app(ClassMethod.descr_init),
883 __get__=interp2app(ClassMethod.descr_classmethod_get),
884 __func__=interp_attrproperty_w('w_function', cls=ClassMethod),
885 __wrapped__=interp_attrproperty_w('w_function', cls=ClassMethod),
886 __isabstractmethod__=GetSetProperty(ClassMethod.descr_isabstract),
887 __dict__=GetSetProperty(descr_get_dict, descr_set_dict, cls=ClassMethod),
888 __reduce_ex__ = interp2app(ClassMethod.descr_reduce_ex),
889 __repr__ = interp2app(ClassMethod.descr_repr),
890 __doc__="""classmethod(function) -> class method
891
892 Convert a function to be a class method.
893
894 A class method receives the class as implicit first argument,
895 just like an instance method receives the instance.
896 To declare a class method, use this idiom:
897
898 class C:
899 def f(cls, arg1, arg2, ...): ...
900 f = classmethod(f)
901
902 It can be called either on the class (e.g. C.f()) or on an instance
903 (e.g. C().f()). The instance is ignored except for its class.
904 If a class method is called for a derived class, the derived class
905 object is passed as the implied first argument.""",
906 )
907
908 def always_none(self, obj):
909 return None
910 BuiltinFunction.typedef = TypeDef("builtin_function", **Function.typedef.rawdict)
911 BuiltinFunction.typedef.rawdict.update({
912 '__new__': interp2app(BuiltinFunction.descr_builtinfunction__new__.im_func),
913 '__self__': GetSetProperty(BuiltinFunction.descr_builtinfunction__self__, cls=BuiltinFunction),
914 '__repr__': interp2app(BuiltinFunction.descr_function_repr),
915 '__doc__': getset_func_doc,
916 '__reduce__': interp2app(BuiltinFunction.descr__reduce__),
917 })
918 del BuiltinFunction.typedef.rawdict['__get__']
919 BuiltinFunction.typedef.acceptable_as_base_class = False
920
921 PyTraceback.typedef = TypeDef("traceback",
922 __reduce__ = interp2app(PyTraceback.descr__reduce__),
923 __new__ = interp2app(PyTraceback.descr_new),
924 __setstate__ = interp2app(PyTraceback.descr__setstate__),
925 __dir__ = interp2app(PyTraceback.descr__dir__),
926 tb_frame = interp_attrproperty_w('frame', cls=PyTraceback),
927 tb_lasti = GetSetProperty(PyTraceback.descr_get_tb_lasti, PyTraceback.descr_set_tb_lasti),
928 tb_lineno = GetSetProperty(PyTraceback.descr_get_tb_lineno, PyTraceback.descr_set_tb_lineno),
929 tb_next = GetSetProperty(PyTraceback.descr_get_next, PyTraceback.descr_set_next),
930 )
931 PyTraceback.typedef.acceptable_as_base_class = False
932
933
934 Cell.typedef = TypeDef("cell",
935 __new__ = interp2app(descr_new_cell),
936 __eq__ = interp2app(Cell.descr_eq),
937 __ne__ = interp2app(Cell.descr_ne),
938 __lt__ = interp2app(Cell.descr_lt),
939 __gt__ = interp2app(Cell.descr_gt),
940 __le__ = interp2app(Cell.descr_le),
941 __ge__ = interp2app(Cell.descr_ge),
942 __hash__ = None,
943 __reduce__ = interp2app(Cell.descr__reduce__),
944 __repr__ = interp2app(Cell.descr__repr__),
945 __setstate__ = interp2app(Cell.descr__setstate__),
946 cell_contents= GetSetProperty(
947 Cell.descr__cell_contents,
948 Cell.descr_set_cell_contents,
949 Cell.descr_del_cell_contents,
950 cls=Cell),
951
952 )
953 Cell.typedef.acceptable_as_base_class = False
954
955 Ellipsis.typedef = TypeDef("ellipsis",
956 __new__ = interp2app(Ellipsis.descr_new_ellipsis),
957 __repr__ = interp2app(Ellipsis.descr__repr__),
958 __reduce__ = interp2app(Ellipsis.descr__reduce__),
959 )
960 Ellipsis.typedef.acceptable_as_base_class = False
961
962 NotImplemented.typedef = TypeDef("NotImplementedType",
963 __new__ = interp2app(NotImplemented.descr_new_notimplemented),
964 __repr__ = interp2app(NotImplemented.descr__repr__),
965 __reduce__ = interp2app(NotImplemented.descr__reduce__),
966 __bool__ = interp2app(NotImplemented.descr_bool),
967 )
968 NotImplemented.typedef.acceptable_as_base_class = False
969
970
971 DisallowNew.typedef = TypeDef("DisallowNewType",
972 __new__ = interp2app(DisallowNew.descr_new_disallow),
973 )
974 DisallowNew.typedef.acceptable_as_base_class = False
975
976 SApplicationException.typedef = TypeDef("SApplicationException")
977 SApplicationException.typedef.acceptable_as_base_class = False
978
979 ## W_OperationError.typedef = TypeDef("OperationError",
980 ## __reduce__ = interp2app(W_OperationError.descr_reduce),
981 ## __setstate__ = interp2app(W_OperationError.descr_setstate),
982 ## )
983 ## W_OperationError.typedef.acceptable_as_base_class = False