def init_w_object(self): """ 0 no fields 1 fixed fields only (all containing pointers) 2 indexable fields only (all containing pointers) 3 both fixed and indexable fields (all containing pointers) 4 both fixed and indexable weak fields (all containing pointers). 5 unused 6 indexable word fields only (no pointers) 7 indexable long (64-bit) fields (only in 64-bit images) 8-11 indexable byte fields only (no pointers) (low 2 bits are low 2 bits of size) 12-15 compiled methods: # of literal oops specified in method header, followed by indexable bytes (same interpretation of low 2 bits as above) """ if self.w_object is None: if self.format < 5: # XXX self.format == 4 is weak self.w_object = objectmodel.instantiate(model.W_PointersObject) elif self.format == 5: raise CorruptImageError("Unknown format 5") elif self.format == 6: self.w_object = objectmodel.instantiate(model.W_WordsObject) elif self.format == 7: raise CorruptImageError("Unknown format 7, no 64-bit support yet :-)") elif 8 <= self.format <= 11: self.w_object = objectmodel.instantiate(model.W_BytesObject) elif 12 <= self.format <= 15: self.w_object = objectmodel.instantiate(model.W_CompiledMethod) else: assert 0, "not reachable" return self.w_object
def allocate_instance(self, cls, w_subtype): """Allocate the memory needed for an instance of an internal or user-defined type, without actually __init__ializing the instance.""" w_type = self.gettypeobject(cls.typedef) if self.is_w(w_type, w_subtype): instance = instantiate(cls) elif cls.typedef.acceptable_as_base_class: # the purpose of the above check is to avoid the code below # to be annotated at all for 'cls' if it is not necessary w_subtype = w_type.check_user_subclass(w_subtype) if cls.typedef.applevel_subclasses_base is not None: cls = cls.typedef.applevel_subclasses_base subcls = get_unique_interplevel_subclass(self.config, cls, w_subtype.hasdict, w_subtype.nslots != 0, w_subtype.needsdel, w_subtype.weakrefable) instance = instantiate(subcls) assert isinstance(instance, cls) instance.user_setup(self, w_subtype) else: raise operationerrfmt(self.w_TypeError, "%s.__new__(%s): only for the type %s", w_type.name, w_subtype.getname(self, '?'), w_type.name) return instance
def init_w_object(self): """ 0 no fields 1 fixed fields only (all containing pointers) 2 indexable fields only (all containing pointers) 3 both fixed and indexable fields (all containing pointers) 4 both fixed and indexable weak fields (all containing pointers). 5 unused 6 indexable word fields only (no pointers) 7 indexable long (64-bit) fields (only in 64-bit images) 8-11 indexable byte fields only (no pointers) (low 2 bits are low 2 bits of size) 12-15 compiled methods: # of literal oops specified in method header, followed by indexable bytes (same interpretation of low 2 bits as above) """ if self.w_object is None: if self.format < 5: # XXX self.format == 4 is weak self.w_object = objectmodel.instantiate(model.W_PointersObject) elif self.format == 5: raise CorruptImageError("Unknown format 5") elif self.format == 6: self.w_object = objectmodel.instantiate(model.W_WordsObject) elif self.format == 7: raise CorruptImageError( "Unknown format 7, no 64-bit support yet :-)") elif 8 <= self.format <= 11: self.w_object = objectmodel.instantiate(model.W_BytesObject) elif 12 <= self.format <= 15: self.w_object = objectmodel.instantiate(model.W_CompiledMethod) else: assert 0, "not reachable" return self.w_object
def next(self, shapelen): offset = self.offset first_line = self.first_line indices = [0] * shapelen for i in range(shapelen): indices[i] = self.indices[i] done = False for i in range(shapelen - 1, -1, -1): if indices[i] < self.res_shape[i] - 1: if i == self.dim: first_line = False indices[i] += 1 offset += self.strides[i] break else: if i == self.dim: first_line = True indices[i] = 0 offset -= self.backstrides[i] else: done = True res = instantiate(AxisIterator) res.offset = offset res.indices = indices res.strides = self.strides res.backstrides = self.backstrides res.res_shape = self.res_shape res._done = done res.first_line = first_line res.dim = self.dim return res
def frame_new(space, __args__): args_w, kwds_w = __args__.unpack() w_pycode, = args_w pycode = space.interp_w(PyCode, w_pycode) w = space.wrap new_frame = instantiate(space.FrameClass) # XXX fish return space.wrap(new_frame)
def f(i): if i == 1: cls = A else: cls = B do_stuff(cls) return instantiate(cls)
def wrapint(space, x, w_symbolic=False, w_s=''): if space.config.objspace.std.withsmallint: from pypy.objspace.std.smallintobject import W_SmallIntObject try: return W_SmallIntObject(x) except OverflowError: from pypy.objspace.std.intobject import W_IntObject return W_IntObject(x, w_symbolic, w_s) elif space.config.objspace.std.withprebuiltint: from pypy.objspace.std.intobject import W_IntObject lower = space.config.objspace.std.prebuiltintfrom upper = space.config.objspace.std.prebuiltintto # use r_uint to perform a single comparison (this whole function # is getting inlined into every caller so keeping the branching # to a minimum is a good idea) index = r_uint(x - lower) if index >= r_uint(upper - lower): w_res = instantiate(W_IntObject) else: w_res = W_IntObject.PREBUILT[index] # obscure hack to help the CPU cache: we store 'x' even into # a prebuilt integer's intval. This makes sure that the intval # field is present in the cache in the common case where it is # quickly reused. (we could use a prefetch hint if we had that) w_res.intval = x return w_res else: from pypy.objspace.std.intobject import W_IntObject return W_IntObject(x, w_symbolic, w_s)
def next(self, shapelen): shapelen = jit.promote(len(self.res_shape)) offset = self.offset indices = [0] * shapelen for i in range(shapelen): indices[i] = self.indices[i] done = False for i in range(shapelen - 1, -1, -1): if indices[i] < self.res_shape[i] - 1: indices[i] += 1 offset += self.strides[i] break else: indices[i] = 0 offset -= self.backstrides[i] else: done = True res = instantiate(ViewIterator) res.offset = offset res.indices = indices res.strides = self.strides res.backstrides = self.backstrides res.res_shape = self.res_shape res._done = done return res
def next_skip_x(self, shapelen, step): shapelen = jit.promote(len(self.res_shape)) offset = self.offset indices = [0] * shapelen for i in range(shapelen): indices[i] = self.indices[i] done = False for i in range(shapelen - 1, -1, -1): if indices[i] < self.res_shape[i] - step: indices[i] += step offset += self.strides[i] * step break else: remaining_step = (indices[i] + step) // self.res_shape[i] this_i_step = step - remaining_step * self.res_shape[i] offset += self.strides[i] * this_i_step indices[i] = indices[i] + this_i_step step = remaining_step else: done = True res = instantiate(ViewIterator) res.offset = offset res.indices = indices res.strides = self.strides res.backstrides = self.backstrides res.res_shape = self.res_shape res._done = done return res
def make_socket(fd, family, type, proto, SocketClass=RSocket): result = instantiate(SocketClass) result.fd = fd result.family = family result.type = type result.proto = proto result.timeout = defaults.timeout return result
def from_in6_addr(in6_addr): sin = _c.sockaddr_in6(sin6_family = AF_INET) # PLAT sin_len sin.sin6_addr = in6_addr paddr = cast(pointer(sin), _c.sockaddr_ptr) result = instantiate(INET6Address) result.addr = paddr.contents result.addrlen = sizeof(_c.sockaddr_in6) return result
def from_storage_and_strategy(space, storage, strategy): w_self = instantiate(W_ListObject) w_self.space = space w_self.strategy = strategy w_self.lstorage = storage if not space.config.objspace.std.withliststrategies: w_self.switch_to_object_strategy() return w_self
def make_null_address(family): klass = familyclass(family) buf = create_string_buffer(klass.maxlen) result = instantiate(klass) result._addr_keepalive2 = buf result.addr = cast(buf, _c.sockaddr_ptr).contents result.addrlen = 0 return result, len(buf)
def from_in6_addr(in6_addr): result = instantiate(INET6Address) # store the malloc'ed data into 'result' as soon as possible # to avoid leaks if an exception occurs inbetween sin = lltype.malloc(_c.sockaddr_in6, flavor='raw', zero=True) result.setdata(sin, sizeof(_c.sockaddr_in6)) rffi.setintfield(sin, 'c_sin6_family', AF_INET) rffi.structcopy(sin.c_sin6_addr, in6_addr) return result
def makeipv4addr(s_addr, result=None): if result is None: result = instantiate(INETAddress) elif result.family != AF_INET: raise RSocketError("address family mismatched") sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True) result.setdata(sin, sizeof(_c.sockaddr_in)) rffi.setintfield(sin, 'c_sin_family', AF_INET) # PLAT sin_len rffi.setintfield(sin.c_sin_addr, 'c_s_addr', s_addr) return result
def make_address(addrptr, addrlen, result=None): family = addrptr.contents.sa_family if result is None: result = instantiate(familyclass(family)) elif result.family != family: raise RSocketError("address family mismatched") paddr = result._addr_keepalive0 = copy_buffer(cast(addrptr, POINTER(c_char)), addrlen) result.addr = cast(paddr, _c.sockaddr_ptr).contents result.addrlen = addrlen return result
def unpickle_block(space, w_tup): w_opname, w_handlerposition, w_valuestackdepth = space.unpackiterable(w_tup) opname = space.str_w(w_opname) handlerposition = space.int_w(w_handlerposition) valuestackdepth = space.int_w(w_valuestackdepth) assert valuestackdepth >= 0 blk = instantiate(get_block_class(opname)) blk.handlerposition = handlerposition blk.valuestackdepth = valuestackdepth return blk
def allocate_instance(self, cls, w_subtype): """Allocate the memory needed for an instance of an internal or user-defined type, without actually __init__ializing the instance.""" w_type = self.gettypeobject(cls.typedef) if self.is_w(w_type, w_subtype): instance = instantiate(cls) elif cls.typedef.acceptable_as_base_class: # the purpose of the above check is to avoid the code below # to be annotated at all for 'cls' if it is not necessary w_subtype = w_type.check_user_subclass(w_subtype) subcls = get_unique_interplevel_subclass(cls, w_subtype.hasdict, w_subtype.nslots != 0, w_subtype.needsdel, w_subtype.weakrefable) instance = instantiate(subcls) instance.user_setup(self, w_subtype) else: raise OperationError(self.w_TypeError, self.wrap("%s.__new__(%s): only for the type %s" % ( w_type.name, w_subtype.getname(self, '?'), w_type.name))) assert isinstance(instance, cls) return instance
def add_offset(self, ofs): result = instantiate(AddressLoc) result._location_code = self._location_code if self._location_code == 'm': result.loc_m = (self.loc_m[0], self.loc_m[1] + ofs) elif self._location_code == 'a': result.loc_a = self.loc_a[:3] + (self.loc_a[3] + ofs,) elif self._location_code == 'j': result.value = self.value + ofs else: raise AssertionError(self._location_code) return result
def add_offset(self, ofs): result = instantiate(AddressLoc) result._location_code = self._location_code if self._location_code == 'm': result.loc_m = (self.loc_m[0], self.loc_m[1] + ofs) elif self._location_code == 'a': result.loc_a = self.loc_a[:3] + (self.loc_a[3] + ofs, ) elif self._location_code == 'j': result.value = self.value + ofs else: raise AssertionError(self._location_code) return result
def makeipv4addr(s_addr, result=None): if result is None: result = instantiate(INETAddress) elif result.family != AF_INET: raise RSocketError("address family mismatched") sin = _c.sockaddr_in(sin_family = AF_INET) # PLAT sin_len sin.sin_addr.s_addr = s_addr paddr = cast(pointer(sin), _c.sockaddr_ptr) result._addr_keepalive1 = sin result.addr = paddr.contents result.addrlen = sizeof(_c.sockaddr_in) return result
def copy(self): from pypy.rlib.objectmodel import instantiate result = instantiate(SmartResizableListImplementation) result._length = self._length result.size_superblock = self.size_superblock result.size_datablock = self.size_datablock result.num_superblocks = self.num_superblocks result.num_datablocks = self.num_datablocks result.last_superblock_filled = self.last_superblock_filled result.index_last = self.index_last result.data_blocks = [l[:] for l in self.data_blocks] result.space = self.space return result
def make_address(addrptr, addrlen, result=None): family = rffi.cast(lltype.Signed, addrptr.c_sa_family) if result is None: result = instantiate(familyclass(family)) elif result.family != family: raise RSocketError("address family mismatched") # copy into a new buffer the address that 'addrptr' points to addrlen = rffi.cast(lltype.Signed, addrlen) buf = lltype.malloc(rffi.CCHARP.TO, addrlen, flavor='raw') src = rffi.cast(rffi.CCHARP, addrptr) for i in range(addrlen): buf[i] = src[i] result.setdata(buf, addrlen) return result
def allocate_instance(self, cls, w_subtype): """Allocate the memory needed for an instance of an internal or user-defined type, without actually __init__ializing the instance.""" w_type = self.gettypeobject(cls.typedef) if self.is_w(w_type, w_subtype): instance = instantiate(cls) elif cls.typedef.acceptable_as_base_class: # the purpose of the above check is to avoid the code below # to be annotated at all for 'cls' if it is not necessary w_subtype = w_type.check_user_subclass(w_subtype) if cls.typedef.applevel_subclasses_base is not None: cls = cls.typedef.applevel_subclasses_base # if not we_are_translated(): if issubclass(cls, model.W_Object): # If cls is missing from model.typeorder, then you # need to add it there (including the inheritance # relationship, if any) assert cls in self.model.typeorder, repr(cls) # if (self.config.objspace.std.withmapdict and cls is W_ObjectObject and not w_subtype.needsdel): from pypy.objspace.std.mapdict import get_subclass_of_correct_size subcls = get_subclass_of_correct_size(self, cls, w_subtype) else: subcls = get_unique_interplevel_subclass( self.config, cls, w_subtype.hasdict, w_subtype.nslots != 0, w_subtype.needsdel, w_subtype.weakrefable) instance = instantiate(subcls) assert isinstance(instance, cls) instance.user_setup(self, w_subtype) else: raise operationerrfmt(self.w_TypeError, "%s.__new__(%s): only for the type %s", w_type.name, w_subtype.getname(self), w_type.name) return instance
def bootstrap_class( space, instsize, w_superclass=None, w_metaclass=None, name="?", format=shadow.POINTERS, varsized=False ): from pypy.lang.smalltalk import model w_class = model.W_PointersObject(w_metaclass, 0) # a dummy placeholder for testing # XXX s = instantiate(shadow.ClassShadow) s.space = space s._w_self = w_class s.w_superclass = w_superclass s.name = name s.instance_size = instsize s.instance_kind = format s.w_methoddict = None s.instance_varsized = varsized or format != shadow.POINTERS s.invalid = False w_class.store_shadow(s) return w_class
def next(self, shapelen): offset = self.offset indices = [0] * shapelen for i in range(shapelen): indices[i] = self.indices[i] done = False for i in range(shapelen - 1, -1, -1): if indices[i] < self.arr.shape[i] - 1: indices[i] += 1 offset += self.arr.strides[i] break else: indices[i] = 0 offset -= self.arr.backstrides[i] else: done = True res = instantiate(ViewIterator) res.offset = offset res.indices = indices res.arr = self.arr res._done = done return res
def bootstrap_class(space, instsize, w_superclass=None, w_metaclass=None, name='?', format=shadow.POINTERS, varsized=False): from pypy.lang.smalltalk import model w_class = model.W_PointersObject(w_metaclass, 0) # a dummy placeholder for testing # XXX s = instantiate(shadow.ClassShadow) s.space = space s._w_self = w_class s.w_superclass = w_superclass s.name = name s.instance_size = instsize s.instance_kind = format s.w_methoddict = None s.instance_varsized = varsized or format != shadow.POINTERS s.invalid = False w_class.store_shadow(s) return w_class
def next(self, shapelen): offset = self.offset indices = [0] * shapelen _done = False for i in range(shapelen): indices[i] = self.indices[i] for i in range(shapelen - 1, -1, -1): if indices[i] < self.res_shape[i] - 1: indices[i] += 1 offset += self.strides[i] break else: indices[i] = 0 offset -= self.backstrides[i] else: _done = True res = instantiate(BroadcastIterator) res.indices = indices res.offset = offset res._done = _done res.strides = self.strides res.backstrides = self.backstrides res.res_shape = self.res_shape return res
def f(i): if i == 1: cls = A else: cls = B return instantiate(cls)
def f(): return instantiate(A)
def allocate_instance(self, cls, w_subtype): is_root(w_subtype) return instantiate(cls)
def g(x): if x: C = A else: C = B a = instantiate(C)
def cell_new(space): return space.wrap(instantiate(Cell))
def func_new(space): fu = instantiate(Function) fu.w_func_dict = space.newdict() return space.wrap(fu)
def traceback_new(space): tb = instantiate(PyTraceback) return space.wrap(tb)
def next_skip_x(self, x): arr = instantiate(ArrayIterator) arr.size = self.size arr.offset = self.offset + x * self.element_size arr.element_size = self.element_size return arr
def next(self, shapelen): arr = instantiate(OneDimIterator) arr.size = self.size arr.step = self.step arr.offset = self.offset + self.step return arr
# The literal count indicates the size of the # CompiledMethod's literal frame. # This, in turn, indicates where the # CompiledMethod's bytecodes start. index0 = index0 - self.getliteralsize() - self.headersize() assert index0 < len(self.bytes) return space.wrap_int(ord(self.bytes[index0])) def atput0(self, space, index0, w_value): if index0 <= self.getliteralsize(): self.literalatput0(space, index0 / constants.BYTES_PER_WORD, w_value) else: # XXX use to-be-written unwrap_char index0 = index0 - self.getliteralsize() - self.headersize() assert index0 < len(self.bytes) self.setchar(index0, chr(space.unwrap_int(w_value))) def setchar(self, index0, character): assert index0 >= 0 self.bytes = (self.bytes[:index0] + character + self.bytes[index0 + 1:]) # Use black magic to create w_nil without running the constructor, # thus allowing it to be used even in the constructor of its own # class. Note that we patch its class in the space # YYY there should be no global w_nil w_nil = instantiate(W_PointersObject) w_nil._vars = []
def make_bootstrap_classes(self): def define_core_cls(name, w_superclass, w_metaclass): assert name.startswith('w_') w_class = bootstrap_class( self, instsize=0, # XXX w_superclass=w_superclass, w_metaclass=w_metaclass, name=name[2:]) self.classtable[name] = w_class return w_class # A complete minimal setup (including Behavior) would look like this # # class: superclass: metaclass: # ------------------- ------------------- ------------------- # Object *nil Object class # Behavior Object Behavior class # ClassDescription Behavior ClassDescription class # Class ClassDescription Class class # Metaclass ClassDescription Metaclass class # Object class *Class *Metaclass # Behavior class Object class *Metaclass # ClassDescription cl Behavior class *Metaclass # Class class ClassDescription cl *Metaclass # Metaclass class ClassDescription cl *Metaclass # Class Name Super class name cls_nm_tbl = [ ["w_Object", "w_ProtoObject"], # there is not ProtoObject in mini.image ["w_Behavior", "w_Object"], ["w_ClassDescription", "w_Behavior"], ["w_Class", "w_ClassDescription"], ["w_Metaclass", "w_ClassDescription"], ] define_core_cls("w_ProtoObjectClass", None, None) w_ProtoObjectClass = self.classtable["w_ProtoObjectClass"] define_core_cls("w_ProtoObject", None, w_ProtoObjectClass) for (cls_nm, super_cls_nm) in cls_nm_tbl: meta_nm = cls_nm + "Class" meta_super_nm = super_cls_nm + "Class" w_metacls = define_core_cls(meta_nm, self.classtable[meta_super_nm], None) define_core_cls(cls_nm, self.classtable[super_cls_nm], w_metacls) w_Class = self.classtable["w_Class"] w_Metaclass = self.classtable["w_Metaclass"] # XXX proto_shadow = instantiate(shadow.ClassShadow) proto_shadow.space = self proto_shadow.invalid = False proto_shadow.w_superclass = w_Class w_ProtoObjectClass.store_shadow(proto_shadow) # at this point, all classes that still lack a w_class are themselves # metaclasses for nm, w_cls_obj in self.classtable.items(): if w_cls_obj.w_class is None: w_cls_obj.w_class = w_Metaclass def define_cls(cls_nm, supercls_nm, instvarsize=0, format=shadow.POINTERS, varsized=False): assert cls_nm.startswith("w_") meta_nm = cls_nm + "Class" meta_super_nm = supercls_nm + "Class" w_Metaclass = self.classtable["w_Metaclass"] w_meta_cls = self.classtable[meta_nm] = \ bootstrap_class(self, 0, # XXX self.classtable[meta_super_nm], w_Metaclass, name=meta_nm[2:]) w_cls = self.classtable[cls_nm] = \ bootstrap_class(self, instvarsize, self.classtable[supercls_nm], w_meta_cls, format=format, varsized=varsized, name=cls_nm[2:]) define_cls("w_Magnitude", "w_Object") define_cls("w_Character", "w_Magnitude", instvarsize=1) define_cls("w_Number", "w_Magnitude") define_cls("w_Integer", "w_Number") define_cls("w_SmallInteger", "w_Integer") define_cls("w_LargePositiveInteger", "w_Integer", format=shadow.BYTES) define_cls("w_Float", "w_Number", format=shadow.BYTES) define_cls("w_Collection", "w_Object") define_cls("w_SequenceableCollection", "w_Collection") define_cls("w_ArrayedCollection", "w_SequenceableCollection") define_cls("w_Array", "w_ArrayedCollection", varsized=True) define_cls("w_String", "w_ArrayedCollection", format=shadow.BYTES) define_cls("w_UndefinedObject", "w_Object") define_cls("w_Boolean", "w_Object") define_cls("w_True", "w_Boolean") define_cls("w_False", "w_Boolean") define_cls("w_ByteArray", "w_ArrayedCollection", format=shadow.BYTES) define_cls("w_MethodDict", "w_Object", instvarsize=2, varsized=True) define_cls("w_CompiledMethod", "w_ByteArray", format=shadow.COMPILED_METHOD) define_cls("w_ContextPart", "w_Object") define_cls("w_MethodContext", "w_ContextPart") define_cls("w_Link", "w_Object") define_cls("w_Process", "w_Link") define_cls("w_Point", "w_Object") define_cls("w_LinkedList", "w_SequenceableCollection") define_cls("w_Semaphore", "w_LinkedList") define_cls("w_BlockContext", "w_ContextPart", instvarsize=constants.BLKCTX_STACK_START) # make better accessors for classes that can be found in special object # table for name in constants.classes_in_special_object_table.keys(): name = 'w_' + name setattr(self, name, self.classtable.get(name))
return self.is_valid_for_map(map) @jit.dont_look_inside def is_valid_for_map(self, map): # note that 'map' can be None here mymap = self.map_wref() if mymap is not None and mymap is map: version_tag = map.terminator.w_cls.version_tag() if version_tag is self.version_tag: # everything matches, it's incredibly fast if map.space.config.objspace.std.withmethodcachecounter: self.success_counter += 1 return True return False _invalid_cache_entry_map = objectmodel.instantiate(AbstractAttribute) _invalid_cache_entry_map.terminator = None INVALID_CACHE_ENTRY = CacheEntry() INVALID_CACHE_ENTRY.map_wref = weakref.ref(_invalid_cache_entry_map) # different from any real map ^^^ def init_mapdict_cache(pycode): num_entries = len(pycode.co_names_w) pycode._mapdict_caches = [INVALID_CACHE_ENTRY] * num_entries @jit.dont_look_inside def _fill_cache(pycode, nameindex, map, version_tag, index, w_method=None): entry = pycode._mapdict_caches[nameindex] if entry is INVALID_CACHE_ENTRY: entry = CacheEntry() pycode._mapdict_caches[nameindex] = entry
def f(i): if i: klass = A else: klass = B a = instantiate(klass)
def frame_new(space): new_frame = instantiate(space.FrameClass) # XXX fish return space.wrap(new_frame)