def _create_return_frame(self, space): from rsqueakvm.storage_contexts import ContextPartShadow log('Language has finished and returned a result.') # we want evalInThread and resumePython to return new frames, # so we don't build up stack, but we also don't raise to the # top-level loop all the time. # For resuming, we obviously need a new frame, because that's # how the Smalltalk scheduler knows how to continue back to Python. # Unfortunately, a primitive can only EITHER always return a new # frame OR a result. So when we get a result, we cannot simply # return it. Instead, we need to build a frame that simply returns # the result if space.is_spur.is_set(): w_cm = objectmodel.instantiate(W_SpurCompiledMethod) else: w_cm = objectmodel.instantiate(W_PreSpurCompiledMethod) w_resume_class = self.foreign_process_class() w_cm.header = 0 w_cm._primitive = 0 w_cm.literalsize = 3 w_cm.islarge = False w_cm._tempsize = 0 w_cm.argsize = 0 w_cm.compiledin_class = w_resume_class.getclass(space) w_cm.lookup_selector = 'fakeReturnResult' w_cm.bytes = [ chr(b) for b in [ 0x20, # push constant 0x7C, # return stack top ] ] w_cm.literals = [self.get_result(), space.w_nil, w_cm.compiledin_class] return ContextPartShadow.build_method_context(space, w_cm, w_resume_class)
def _create_return_frame(self, space): from rsqueakvm.storage_contexts import ContextPartShadow log('Language has finished and returned a result.') # we want evalInThread and resumePython to return new frames, # so we don't build up stack, but we also don't raise to the # top-level loop all the time. # For resuming, we obviously need a new frame, because that's # how the Smalltalk scheduler knows how to continue back to Python. # Unfortunately, a primitive can only EITHER always return a new # frame OR a result. So when we get a result, we cannot simply # return it. Instead, we need to build a frame that simply returns # the result if space.is_spur.is_set(): w_cm = objectmodel.instantiate(W_SpurCompiledMethod) else: w_cm = objectmodel.instantiate(W_PreSpurCompiledMethod) w_resume_class = self.foreign_process_class() w_cm.header = 0 w_cm._primitive = 0 w_cm.literalsize = 3 w_cm.islarge = False w_cm._tempsize = 0 w_cm.argsize = 0 w_cm.compiledin_class = w_resume_class.getclass(space) w_cm.lookup_selector = 'fakeReturnResult' w_cm.bytes = [chr(b) for b in [ 0x20, # push constant 0x7C, # return stack top ]] w_cm.literals = [self.get_result(), space.w_nil, w_cm.compiledin_class] return ContextPartShadow.build_method_context( space, w_cm, w_resume_class)
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 (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 oefmt(self.w_TypeError, "%N.__new__(%N): only for the type %N", w_type, w_subtype, w_type) return instance
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 (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.layout.nslots != 0, w_subtype.needsdel, w_subtype.weakrefable) instance = instantiate(subcls) assert isinstance(instance, cls) instance.user_setup(self, w_subtype) else: raise oefmt(self.w_TypeError, "%N.__new__(%N): only for the type %N", w_type, w_subtype, w_type) return instance
def make_method(self, w_selector): if self.space.is_spur.is_set(): w_cm = objectmodel.instantiate(W_SpurCompiledMethod) else: w_cm = objectmodel.instantiate(W_PreSpurCompiledMethod) w_cm.header = 0 w_cm._primitive = EXTERNAL_CALL w_cm.literalsize = 2 w_cm.islarge = False w_cm._tempsize = 0 w_cm.argsize = 0 w_cm.compiledin_class = self.w_foreign_class.get() w_cm.bytes = [] w_cm.literals = [self.w_plugin_send.get(), w_selector] return w_cm
def ll_matches(MATCHTYPE, MATCH_INIT, MATCH_CONTEXTTYPE, MATCH_CONTEXT_INIT, MATCH_CONTEXT, ll_rule, s, pos): s = hlstr(s) assert pos >= 0 ctx = instantiate(MATCH_CONTEXTTYPE) hlinvoke(MATCH_CONTEXT_INIT, rsre_core.StrMatchContext.__init__, ctx, ll_rule.code, hlstr(s), pos, len(s), 0) matched = hlinvoke(MATCH_CONTEXT, rsre_core.match_context, ctx) if matched: match = instantiate(MATCHTYPE) hlinvoke(MATCH_INIT, Match.__init__, match, ctx.match_start, ctx.match_end) return match else: return None
def _clone(self): # Allocate and fill in small list values result = objectmodel.instantiate(newcls) for _, attr in unrolling_enumerate_attrs: value = getattr(self, attr) setattr(result, attr, value) return result
def bootstrap_class(space, instsize, w_superclass=None, w_metaclass=None, name='?', format=shadow.POINTERS, varsized=False): from spyvm import model w_class = model.W_PointersObject(space, w_metaclass, 0) # a dummy placeholder for testing # XXX s = instantiate(shadow.ClassShadow) s.space = space s.version = shadow.Version() s._w_self = w_class s.subclass_s = {} s._s_superclass = None s.store_w_superclass(w_superclass) s.name = name s._instance_size = instsize s.instance_kind = format s._s_methoddict = None s.instance_varsized = varsized or format != shadow.POINTERS w_class.store_shadow(s) return w_class
def make1(elem, *args): if not classes: # no type specialization return make([elem], *args) result = objectmodel.instantiate(classes[1]) result._set_list(0, elem) cls.__init__(result, *args) return result
def from_size(size): self = instantiate(_PartiallyEmptyStrategy) self.storage = [nilObject] * size self.size = size self.empty_elements = size self.type = None return self
def from_size(size, strategy = _empty_strategy): self = instantiate(Array) # self = Array() self._strategy = strategy self._storage = strategy.new_storage_for(size) self._meta_object_environment = None return self
def _from_storage_and_strategy(storage, strategy): self = instantiate(Array) # self = Array() self._strategy = strategy self._storage = storage self._meta_object_environment = None return self
def _clone(self): result = objectmodel.instantiate(cls_arbitrary) values = getattr(self, attrname) if not immutable: # Only copy if the storage is mutable values = values[:] setattr(result, attrname, values) return result
def make2(elem1, elem2, *args): if not classes: # no type specialization return make([elem1, elem2], *args) result = objectmodel.instantiate(classes[2]) result._set_list(0, elem1) result._set_list(1, elem2) cls.__init__(result, *args) return result
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 make_callback(space, ctype, w_callable, w_error, w_onerror): # Allocate a callback as a nonmovable W_CDataCallback instance, which # we can cast to a plain VOIDP. As long as the object is not freed, # we can cast the VOIDP back to a W_CDataCallback in reveal_callback(). cdata = objectmodel.instantiate(W_CDataCallback, nonmovable=True) W_CDataCallback.__init__(cdata, space, ctype, w_callable, w_error, w_onerror) return cdata
def fn(): a1 = A() a = objectmodel.instantiate(A, nonmovable=True) a.next = a1 # 'a' is known young here, so no write barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res
def copied_str(w_original_string): w_s = instantiate(pie.objects.string.W_String) from pie.objects.strategy.reference import StringCopyStrategy strategy = get_string_strategy(StringCopyStrategy) w_s.storage = strategy.erase(w_original_string) w_s.strategy = strategy w_s.copies = None return w_s
def mutable_str(strval): w_s = instantiate(pie.objects.string.W_String) from pie.objects.strategy.general import MutableStringStrategy strategy = get_string_strategy(MutableStringStrategy) w_s.storage = strategy.erase(strval) w_s.strategy = strategy w_s.copies = None return w_s
def ll_matches(MATCHTYPE, MATCH_INIT, MATCH_CONTEXTTYPE, MATCH_CONTEXT_INIT, MATCH_CONTEXT, ll_rule, s, pos): s = hlstr(s) assert pos >= 0 ctx = instantiate(MATCH_CONTEXTTYPE) hlinvoke(MATCH_CONTEXT_INIT, rsre_core.StrMatchContext.__init__, ctx, ll_rule.code, hlstr(s), pos, len(s), 0 ) matched = hlinvoke(MATCH_CONTEXT, rsre_core.match_context, ctx) if matched: match = instantiate(MATCHTYPE) hlinvoke(MATCH_INIT, Match.__init__, match, ctx.match_start, ctx.match_end ) return match else: return None
def from_values(values, strategy = None): self = instantiate(Array) # self = Array() if strategy is None: self._strategy = self._determine_strategy(values) else: self._strategy = strategy self._storage = self._strategy.new_storage_with_values(values) return self
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, track_allocation=False) result.setdata(sin, sizeof(_c.sockaddr_in6)) rffi.setintfield(sin, "c_sin6_family", AF_INET6) rffi.structcopy(sin.c_sin6_addr, in6_addr) return result
def reverseseqiter_new(space, w_seq, w_index): w_rev = instantiate(W_ReverseSeqIterObject) if space.is_w(w_seq, space.w_None): w_rev.w_seq = None w_rev.index = -1 else: w_rev.w_seq = w_seq w_rev.index = space.int_w(w_index) return w_rev
def _newp_handle(space, w_ctype, w_x): # Allocate a handle as a nonmovable W_CDataHandle instance, which # we can cast to a plain CCHARP. As long as the object is not freed, # we can cast the CCHARP back to a W_CDataHandle with reveal_gcref(). new_cdataobj = objectmodel.instantiate(cdataobj.W_CDataHandle, nonmovable=True) _cdata = hide_reveal2().hide_object(rffi.CCHARP, new_cdataobj) cdataobj.W_CDataHandle.__init__(new_cdataobj, space, _cdata, w_ctype, w_x) return new_cdataobj
def from_values(values, strategy=None): self = instantiate(Array) # self = Array() if strategy is None: self._strategy = self._determine_strategy(values) else: self._strategy = strategy self._storage = self._strategy.new_storage_with_values(values) return self
def copy_for_type(self, w_objclass): if self.objclass_getter is None: new = instantiate(GetSetProperty) new._init(self.fget, self.fset, self.fdel, self.doc, self.reqcls, None, self.use_closure, self.name) new.w_objclass = w_objclass return new else: return self
def make_method(self, w_selector): if self.space.is_spur.is_set(): w_cm = objectmodel.instantiate(W_SpurCompiledMethod) else: w_cm = objectmodel.instantiate(W_PreSpurCompiledMethod) w_cm.header = 0 w_cm._primitive = EXTERNAL_CALL w_cm.literalsize = 2 w_cm.islarge = False w_cm._tempsize = 0 w_cm.argsize = 0 w_cm.compiledin_class = self.w_foreign_class.get() w_cm.bytes = [] w_cm.literals = [ self.w_plugin_send.get(), w_selector ] return w_cm
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, track_allocation=False) 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_null_address(family): klass = familyclass(family) result = instantiate(klass) buf = lltype.malloc(rffi.CCHARP.TO, klass.maxlen, flavor="raw", zero=True, track_allocation=False) # Initialize the family to the correct value. Avoids surprizes on # Windows when calling a function that unexpectedly does not set # the output address (e.g. recvfrom() on a connected IPv4 socket). rffi.setintfield(rffi.cast(_c.sockaddr_ptr, buf), "c_sa_family", family) result.setdata(buf, 0) return result, klass.maxlen
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, track_allocation=False) result.setdata(sin, sizeof(_c.sockaddr_in6)) rffi.setintfield(sin, 'c_sin6_family', AF_INET6) 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, track_allocation=False) 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 from_obj_values(storage): # Currently, we support only the direct transition from empty # to partially empty assert isinstance(storage, list) assert isinstance(storage[0], AbstractObject) self = instantiate(_PartiallyEmptyStrategy) self.storage = storage self.size = len(storage) self.empty_elements = self.size self.type = None return self
def make_n(size, *args): if sizemin <= size < sizemax: subcls = classes[size - sizemin] else: subcls = cls_arbitrary result = objectmodel.instantiate(subcls) if subcls is cls_arbitrary: assert isinstance(result, subcls) setattr(result, attrname, [None] * size) cls.__init__(result, *args) return result
def _newp_handle(space, w_ctype, w_x): # Allocate a handle as a nonmovable W_CDataHandle instance, which # we can cast to a plain CCHARP. As long as the object is not freed, # we can cast the CCHARP back to a W_CDataHandle with reveal_gcref(). new_cdataobj = objectmodel.instantiate(cdataobj.W_CDataHandle, nonmovable=True) gcref = rgc.cast_instance_to_gcref(new_cdataobj) _cdata = rgc.hide_nonmovable_gcref(gcref) _cdata = rffi.cast(rffi.CCHARP, _cdata) cdataobj.W_CDataHandle.__init__(new_cdataobj, space, _cdata, w_ctype, w_x) return new_cdataobj
def make_null_address(family): klass = familyclass(family) result = instantiate(klass) buf = lltype.malloc(rffi.CCHARP.TO, klass.maxlen, flavor='raw', zero=True, track_allocation=False) # Initialize the family to the correct value. Avoids surprizes on # Windows when calling a function that unexpectedly does not set # the output address (e.g. recvfrom() on a connected IPv4 socket). rffi.setintfield(rffi.cast(_c.sockaddr_ptr, buf), 'c_sa_family', family) result.setdata(buf, 0) return result, klass.maxlen
def concat_str(w_left, w_right): w_string = instantiate(pie.objects.string.W_String) from pie.objects.strategy.reference import StringConcatStrategy strategy = get_string_strategy(StringConcatStrategy) w_string.storage = strategy.erase((w_left, w_right, w_left.strlen() + w_right.strlen())) w_string.strategy = strategy w_string.copies = None w_left.add_copy(w_string) w_right.add_copy(w_string) return w_string
def unpickle_block(space, w_tup): w_opname, w_handlerposition, w_valuestackdepth = space.unpackiterable(w_tup) opname = space.text_w(w_opname) handlerposition = space.int_w(w_handlerposition) valuestackdepth = space.int_w(w_valuestackdepth) assert valuestackdepth >= 0 assert handlerposition >= 0 blk = instantiate(get_block_class(opname)) blk.handlerposition = handlerposition blk.valuestackdepth = valuestackdepth return blk
def descr__setstate__(self, space, w_args): from rpython.rlib.objectmodel import instantiate args_w = space.unpackiterable(w_args) w_framestate, w_running = args_w if space.is_w(w_framestate, space.w_None): self.frame = None else: frame = instantiate(space.FrameClass) # XXX fish frame.descr__setstate__(space, w_framestate) GeneratorIterator.__init__(self, frame) self.running = self.space.is_true(w_running)
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 assert handlerposition >= 0 blk = instantiate(get_block_class(opname)) blk.handlerposition = handlerposition blk.valuestackdepth = valuestackdepth return blk
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 reader_mock_spur(monkeypatch, space): from rsqueakvm.squeakimage import GenericObject, SpurReader from rsqueakvm.model import W_PointersObject from rpython.rlib import objectmodel class FakeVersion: is_big_endian = True reader_mock = SpurReader(imageReader=None, version=FakeVersion(), stream=None, space=space) fake_g_class = GenericObject() fake_g_class.w_object = objectmodel.instantiate(W_PointersObject) monkeypatch.setattr(reader_mock, 'g_class_of', lambda chunk: fake_g_class) return reader_mock
def func(interp, s_frame, argcount): # pragma: no cover from rpython.memory.lltypelayout import sizeof from rsqueakvm.storage_classes import POINTERS,\ WEAK_POINTERS, WORDS, BYTES, COMPILED_METHOD,\ FLOAT, LARGE_INTEGER # This does not count shadows and the memory required for storage or any of # that "meta-info", but only the size of the types struct and the requested # fields. if argcount == 1: size = interp.space.unwrap_int(s_frame.pop()) else: size = 0 w_rcvr = s_frame.pop() if argcount > 1: raise PrimitiveFailedError s_class = w_rcvr.as_class_get_shadow(interp.space) instance_kind = s_class.get_instance_kind() if instance_kind in [POINTERS, WEAK_POINTERS]: r = model_sizeof(objectmodel.instantiate(W_PointersObject)) + (s_class.instsize() + size) * constants.BYTES_PER_WORD elif instance_kind == WORDS: r = model_sizeof(objectmodel.instantiate(W_WordsObject)) + size * constants.BYTES_PER_WORD elif instance_kind == BYTES: r = model_sizeof(objectmodel.instantiate(W_BytesObject)) + size elif instance_kind == COMPILED_METHOD: r = model_sizeof(objectmodel.instantiate(W_CompiledMethod)) elif instance_kind == FLOAT: r = model_sizeof(objectmodel.instantiate(W_Float)) elif instance_kind == LARGE_INTEGER: r = model_sizeof(objectmodel.instantiate(W_LargeIntegerBig)) else: raise PrimitiveFailedError return interp.space.wrap_int(r)
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, cls) instance = instantiate(subcls) assert isinstance(instance, cls) instance.user_setup(self, w_subtype) if w_subtype.hasuserdel: self.finalizer_queue.register_finalizer(instance) else: raise oefmt(self.w_TypeError, "%N.__new__(%N): only for the type %N", w_type, w_subtype, w_type) return instance
def make_method(self, w_selector): methodname = self.space.unwrap_string(w_selector) idx = methodname.find(":") if idx > 0: methodname = methodname[0:idx] ruby_method = self.wr_class.find_method(ruby_space, methodname) if ruby_method is None: return None if self.space.is_spur.is_set(): w_cm = objectmodel.instantiate(W_SpurCompiledMethod) else: w_cm = objectmodel.instantiate(W_PreSpurCompiledMethod) w_cm.header = 0 w_cm._primitive = EXTERNAL_CALL w_cm.literalsize = 2 w_cm.islarge = False w_cm._tempsize = 0 w_cm.argsize = 0 w_cm.bytes = [] w_cm.literals = [ plugin.w_ruby_plugin_send.get(), w_selector ] return w_cm