Beispiel #1
0
class Object(W_Root):
    # mainly for tests
    objectmodel.import_from_mixin(MapdictStorageMixin)

    objectmodel.import_from_mixin(BaseUserClassMapdict)
    objectmodel.import_from_mixin(MapdictWeakrefSupport)
    objectmodel.import_from_mixin(MapdictDictSupport)
Beispiel #2
0
class ListStrategy(SimpleStorageStrategy):
    _attrs_ = []
    repr_classname = "ListStrategy"
    import_from_mixin(rstrat.GenericStrategy)
    import_from_mixin(OptimizedConvertFromAllNilMixin)

    def _wrap(self, w_value):
        if isinstance(w_value, W_SmallInteger):
            assert isinstance(w_value, W_MutableSmallInteger)
            return self.space.wrap_smallint_unsafe(w_value.value)
        else:
            return w_value

    def _unwrap(self, w_value):
        if isinstance(w_value, W_SmallInteger):
            return W_MutableSmallInteger(w_value.value)
        else:
            return w_value

    def store(self, w_self, index0, w_value):
        self.check_index_store(w_self, index0)
        storage = self.get_storage(w_self)
        if isinstance(w_value, W_SmallInteger):
            w_old = storage[index0]
            if isinstance(w_old, W_SmallInteger):
                assert isinstance(w_old, W_MutableSmallInteger)
                w_old.set_value(w_value.value)
            else:
                storage[index0] = W_MutableSmallInteger(w_value.value)
        else:
            storage[index0] = w_value
Beispiel #3
0
class AbstractStrategy(object):
    __metaclass__ = rs.StrategyMetaclass
    import_from_mixin(rs.AbstractStrategy)
    import_from_mixin(rs.SafeIndexingMixin)
    def __init__(self, factory, w_self=None, size=0):
        self.factory = factory
    def strategy_factory(self):
        return self.factory
Beispiel #4
0
class SmallIntegerOrNilStrategy(SimpleStorageStrategy):
    repr_classname = "SmallIntegerOrNilStrategy"
    import_from_mixin(rstrat.TaggingStrategy)
    import_from_mixin(OptimizedConvertFromAllNilMixin)
    contained_type = W_SmallInteger
    def wrap(self, val): return self.space.wrap_smallint_unsafe(val)
    def unwrap(self, w_val): return self.space.unwrap_int(w_val)
    def wrapped_tagged_value(self): return self.space.w_nil
    def unwrapped_tagged_value(self): return constants.MAXINT
Beispiel #5
0
class FloatOrNilStrategy(SimpleStorageStrategy):
    repr_classname = "FloatOrNilStrategy"
    import_from_mixin(rstrat.TaggingStrategy)
    import_from_mixin(OptimizedConvertFromAllNilMixin)
    contained_type = W_Float
    tag_float = sys.float_info.max
    def wrap(self, val): return self.space.wrap_float(val)
    def unwrap(self, w_val): return self.space.unwrap_float(w_val)
    def wrapped_tagged_value(self): return self.space.w_nil
    def unwrapped_tagged_value(self): return self.tag_float
Beispiel #6
0
class Strategy(object):
    """
    A plan for specializing storage.
    """

    __metaclass__ = rstrategies.StrategyMetaclass

    import_from_mixin(rstrategies.AbstractStrategy)
    import_from_mixin(rstrategies.SafeIndexingMixin)

    def strategy_factory(self):
        return strategyFactory
Beispiel #7
0
class CharacterOrNilStrategy(SimpleStorageStrategy):
    repr_classname = "CharacterOrNilStrategy"
    import_from_mixin(rstrat.TaggingStrategy)
    import_from_mixin(OptimizedConvertFromAllNilMixin)
    contained_type = W_Character
    def wrap(self, val): return W_Character(val)
    def unwrap(self, w_val):
        # XXX why would you think, this could be a W_Object?
        assert isinstance(w_val, W_Character)
        return w_val.value
    def wrapped_tagged_value(self): return self.space.w_nil
    def unwrapped_tagged_value(self): return constants.MAXINT
Beispiel #8
0
class W_OutputType(W_InputOutputType):
    import_from_mixin(RStringIO)

    def __init__(self, space):
        self.init()
        self.space = space

    def descr_truncate(self, w_size=None):
        self.check_closed()
        space = self.space
        if space.is_none(w_size):
            size = self.tell()
        else:
            size = space.int_w(w_size)
        if size < 0:
            raise OperationError(space.w_IOError, space.wrap("negative size"))
        self.truncate(size)

    def descr_write(self, space, w_buffer):
        buffer = space.getarg_w('s*', w_buffer)
        self.check_closed()
        self.write(buffer.as_str())

    def descr_writelines(self, w_lines):
        self.check_closed()
        space = self.space
        w_iterator = space.iter(w_lines)
        while True:
            try:
                w_line = space.next(w_iterator)
            except OperationError, e:
                if not e.match(space, space.w_StopIteration):
                    raise
                break  # done
            self.write(space.str_w(w_line))
Beispiel #9
0
class W_InterposeContinuationMarkKey(values.W_ContinuationMarkKey):
    import_from_mixin(ProxyMixin)

    errorname = "interpose-continuation-mark-key"
    _immutable_fields_ = ["inner", "get_proc", "set_proc", "properties"]
    def __init__(self, mark, get_proc, set_proc, prop_keys, prop_vals):
        assert get_proc.iscallable()
        assert set_proc.iscallable()
        assert not prop_keys and not prop_vals or len(prop_keys) == len(prop_vals)
        self.inner    = mark
        self.get_proc = get_proc
        self.set_proc = set_proc
        self.properties = {}
        if prop_vals is not None:
            for i, k in enumerate(prop_keys):
                assert isinstance(k, W_ImpPropertyDescriptor)
                self.properties[k] = prop_vals[i]

    def post_set_cont(self, body, value, env, cont):
        raise NotImplementedError("abstract method")

    def post_get_cont(self, value, env, cont):
        raise NotImplementedError("abstract method")

    @label
    def get_cmk(self, value, env, cont):
        return self.get_proc.call([value], env,
                self.post_get_cont(value, env, cont))

    @label
    def set_cmk(self, body, value, update, env, cont):
        return self.set_proc.call([value], env,
                self.post_set_cont(body, value, env, cont))
Beispiel #10
0
class DoubleFormStrategy(FormStrategy):
    import_from_mixin(CommonFormStrategy)

    def __init__(self):
        self.name = String(u"double")

    erase, unerase = rerased.new_erasing_pair("double_form")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def wrap(self, raw):
        return Float(raw)
    
    def unwrap(self, obj):
        return cast(obj, Float, u"numeric (double form strategy)").number

    def add(self, a_n, b_n):
        a = self.unerase(a_n.storage)
        b = self.unerase(b_n.storage)
        if len(a) != len(b):
            raise unwind(LError(u"incompatible numerics for arithmetic"))
        c = []
        for i in range(len(a)):
            c.append(a[i] + b[i])
        return Numeric(self, self.erase(c[:]))
Beispiel #11
0
class W_ChpProcedure(W_InterposeProcedure):
    import_from_mixin(ChaperoneMixin)

    errorname = "chp-procedure"

    def post_call_cont(self, args, env, cont, calling_app):
        return chp_proc_cont(args, self.inner, calling_app, env, cont)
Beispiel #12
0
class W_ImpProcedure(W_InterposeProcedure):
    import_from_mixin(ImpersonatorMixin)

    errorname = "imp-procedure"

    def post_call_cont(self, args, prop, env, cont, calling_app):
        return imp_proc_cont(len(args), self.inner, prop, calling_app, env, cont)
Beispiel #13
0
class W_InterposeBox(values.W_Box):
    errorname = "interpose-box"
    _immutable_fields_ = ["unboxh", "seth"]

    import_from_mixin(ProxyMixin)

    def __init__(self, box, unboxh, seth, prop_keys, prop_vals):
        assert isinstance(box, values.W_Box)
        self.unboxh = unboxh
        self.seth = seth
        self.init_proxy(box, prop_keys, prop_vals)

    def immutable(self):
        return self.inner.immutable()

    def post_unbox_cont(self, env, cont):
        raise NotImplementedError("abstract method")

    def post_set_box_cont(self, val, env, cont):
        raise NotImplementedError("abstract method")

    @jit.unroll_safe
    def unbox(self, env, cont):
        while isinstance(self, W_InterposeBox):
            cont = self.post_unbox_cont(env, cont)
            self = self.inner
        return self.unbox(env, cont)

    def set_box(self, val, env, cont):
        after = self.post_set_box_cont(val, env, cont)
        return self.seth.call([self.inner, val], env, after)
Beispiel #14
0
class W_InterposeContinuationMarkKey(values.W_ContinuationMarkKey):
    errorname = "interpose-continuation-mark-key"
    _immutable_fields_ = ["get_proc", "set_proc"]

    import_from_mixin(ProxyMixin)

    def __init__(self, mark, get_proc, set_proc, prop_keys, prop_vals):
        assert get_proc.iscallable()
        assert set_proc.iscallable()
        self.get_proc = get_proc
        self.set_proc = set_proc
        self.init_proxy(mark, prop_keys, prop_vals)

    def post_set_cont(self, body, value, env, cont):
        raise NotImplementedError("abstract method")

    def post_get_cont(self, value, env, cont):
        raise NotImplementedError("abstract method")

    @label
    def get_cmk(self, value, env, cont):
        return self.get_proc.call([value], env,
                                  self.post_get_cont(value, env, cont))

    @label
    def set_cmk(self, body, value, update, env, cont):
        return self.set_proc.call([value], env,
                                  self.post_set_cont(body, value, env, cont))
Beispiel #15
0
class FlonumVectorStrategy(VectorStrategy):
    import_from_mixin(UnwrappedVectorStrategyMixin)

    erase, unerase = rerased.new_erasing_pair("flonum-vector-strategy")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def is_correct_type(self, w_vector, w_obj):
        return isinstance(w_obj, W_Flonum)

    def wrap(self, val):
        assert isinstance(val, float)
        return W_Flonum(val)

    def unwrap(self, w_val):
        assert isinstance(w_val, W_Flonum)
        return w_val.value

    def immutable_variant(self):
        return FlonumImmutableVectorStrategy.singleton

    def dehomogenize(self, w_vector, hint):
        if type(hint) is W_Fixnum and can_encode_int32(hint.value):
            new_strategy = FlonumTaggedVectorStrategy.singleton
            w_vector.set_strategy(new_strategy)
            w_vector.set_len(0)
        else:
            VectorStrategy.dehomogenize(self, w_vector, hint)
Beispiel #16
0
class W_StructFieldMutator(values.W_Procedure):
    errorname = "struct-field-mutator"
    _attrs_ = _immutable_fields_ = ["mutator", "field", "field_name"]
    import_from_mixin(SingleResultMixin)

    def __init__(self, mutator, field, field_name):
        assert isinstance(mutator, W_StructMutator)
        self.mutator = mutator
        self.field = field
        self.field_name = field_name

    def get_arity(self, promote=False):
        return Arity.TWO

    def get_absolute_index(self, type):
        return type.get_offset(self.mutator.type) + self.field

    @make_call_method([values.W_Object, values.W_Object],
                      simple=False,
                      name="<struct-field-mutator-method>")
    def call_with_extra_info(self, struct, val, env, cont, app):
        return self.mutator.mutate(struct, self.field, val, env, cont, app)

    def tostring(self):
        return "#<procedure:%s-%s!>" % (self.mutator.type.name,
                                        self.field_name.variable_name())
Beispiel #17
0
class W_StructAccessor(values.W_Procedure):
    errorname = "struct-accessor"
    _attrs_ = _immutable_fields_ = ["type"]
    import_from_mixin(SingleResultMixin)

    def __init__(self, type):
        self.type = type

    def get_arity(self, promote=False):
        return Arity.TWO

    def access(self, struct, field, env, cont, app):
        self = jit.promote(self)
        st = jit.promote(struct.struct_type())
        if st is None:
            raise SchemeException("%s got %s" %
                                  (self.tostring(), struct.tostring()))
        offset = st.get_offset(self.type)
        if offset == -1:
            raise SchemeException(
                "cannot reference an identifier before its definition")
        return struct.ref_with_extra_info(field + offset, app, env, cont)

    @make_call_method([values.W_Object, values.W_Fixnum],
                      simple=False,
                      name="<struct-accessor-method>")
    def call_with_extra_info(self, struct, field, env, cont, app):
        return self.access(struct, field.value, env, cont, app)

    def tostring(self):
        return "#<procedure:%s-ref>" % self.type.name
Beispiel #18
0
class W_StructPredicate(values.W_Procedure):
    errorname = "struct-predicate"
    _attrs_ = _immutable_fields_ = ["type"]
    import_from_mixin(SingleResultMixin)

    def __init__(self, type):
        self.type = type

    @make_call_method([values.W_Object])
    @jit.unroll_safe
    def call(self, struct):
        from pycket.impersonators import get_base_object
        struct = get_base_object(struct)
        if isinstance(struct, W_RootStruct):
            struct_type = struct.struct_type()
            while isinstance(struct_type, W_StructType):
                if struct_type is self.type:
                    return values.w_true
                struct_type = struct_type.super
        return values.w_false

    def get_arity(self, promote=False):
        return Arity.ONE

    def tostring(self):
        return "#<procedure:%s?>" % self.type.name.variable_name()
Beispiel #19
0
class ObjectFormStrategy(FormStrategy):
    import_from_mixin(CommonFormStrategy)

    # I am planning to add shape of the numeric into the strategy and
    # store a table of used strategies with their associated shape.
    # That should allow JIT to optimize common shapes encountered?
    def __init__(self):
        self.name = String(u"object")

    erase, unerase = rerased.new_erasing_pair("object_form")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def wrap(self, raw):
        return raw

    def unwrap(self, obj):
        return obj

    def add(self, a_n, b_n):
        a = self.unerase(a_n.storage)
        b = self.unerase(b_n.storage)
        if len(a) != len(b):
            raise unwind(LError(u"incompatible numerics for arithmetic"))
        c = []
        for i in range(len(a)):
            c.append(operators.add.call([a[i], b[i]]))
        return Numeric(self, self.erase(c[:]))
Beispiel #20
0
class W_StructPropertyAccessor(values.W_Procedure):
    errorname = "struct-property-accessor"
    _immutable_fields_ = ["property"]
    import_from_mixin(SingleResultMixin)

    def __init__(self, prop):
        self.property = prop

    def get_arity(self):
        return Arity.ONE

    @make_call_method(
        [values.W_Object, default(values.W_Object, None)], simple=False)
    def call_with_extra_info(self, arg, fail, env, cont, app):
        from pycket.interpreter import return_value
        if isinstance(arg, W_StructType):
            w_val = arg.read_prop_precise(self.property)
            if w_val is not None:
                return return_value(w_val, env, cont)
        elif isinstance(arg, W_RootStruct):
            return arg.get_prop(self.property, env, cont)
        elif fail is not None:
            if fail.iscallable():
                return fail.call_with_extra_info([], env, cont, app)
            return return_value(fail, env, cont)
        raise SchemeException(
            "%s-accessor: expected %s? but got %s" %
            (self.property.name, self.property.name, arg.tostring()))
Beispiel #21
0
class ConstantString(object):
    import_from_mixin(ConstantMixin)
    default_value = ""

    def get(self):
        # Promoting does not work on strings...
        return self.value[0]
Beispiel #22
0
class W_StructMutator(values.W_Procedure):
    errorname = "struct-mutator"
    _immutable_fields_ = ["type"]
    import_from_mixin(SingleResultMixin)

    def __init__(self, type):
        self.type = type

    def get_arity(self):
        return Arity.THREE

    def mutate(self, struct, field, val, env, cont, app):
        assert isinstance(struct, W_RootStruct)
        jit.promote(self)
        offset = struct.struct_type().get_offset(self.type)
        if offset == -1:
            raise SchemeException(
                "cannot reference an identifier before its definition")
        return struct.set_with_extra_info(field + offset, val, app, env, cont)

    @make_call_method([W_RootStruct, values.W_Fixnum, values.W_Object],
                      simple=False,
                      name="<struct-mutator-method>")
    def call_with_extra_info(self, struct, field, val, env, cont, app):
        return self.mutate(struct, field.value, val, env, cont, app)

    def tostring(self):
        return "#<procedure:%s-set!>" % self.type.name
Beispiel #23
0
class SymbolHashmapStrategy(HashmapStrategy):
    import_from_mixin(UnwrappedHashmapStrategyMixin)

    erase, unerase = rerased.new_static_erasing_pair("symbol-hashmap-strategy")

    def is_correct_type(self, w_obj):
        return isinstance(w_obj, values.W_Symbol)

    def wrap(self, val):
        assert isinstance(val, values.W_Symbol)
        return val

    def unwrap(self, w_val):
        assert isinstance(w_val, values.W_Symbol)
        return w_val

    def rem(self, w_dict, w_key, env, cont):
        from pycket.interpreter import return_value
        if not w_dict.immutable():
            raise Exception("Expected an immutable hash table")

        new_keys = []
        new_vals = []
        for (k, v) in w_dict.hash_items():
            if k is w_key:
                continue
            new_keys.append(k)
            new_vals.append(v)

        assert isinstance(w_dict, W_EqualHashTable)
        new_table = W_EqualHashTable(new_keys, new_vals, True)
        return return_value(new_table, env, cont)
Beispiel #24
0
class W_BytesObject(W_AbstractBytesObject):
    import_from_mixin(StringMethods)
    _immutable_fields_ = ['_value']

    def __init__(self, str):
        assert str is not None
        self._value = str

    def __repr__(self):
        """representation for debugging purposes"""
        return "%s(%r)" % (self.__class__.__name__, self._value)

    def unwrap(self, space):
        return self._value

    def bytes_w(self, space):
        return self._value

    def buffer_w(self, space, flags):
        space.check_buf_flags(flags, True)
        return StringBuffer(self._value)

    def listview_int(self):
        return _create_list_from_bytes(self._value)

    def ord(self, space):
        if len(self._value) != 1:
            raise oefmt(
                space.w_TypeError,
                "ord() expected a character, but string of length %d "
                "found", len(self._value))
        return space.wrap(ord(self._value[0]))

    def _new(self, value):
        return W_BytesObject(value)

    def _new_from_list(self, value):
        return W_BytesObject(''.join(value))

    def _empty(self):
        return W_BytesObject.EMPTY

    def _len(self):
        return len(self._value)

    _val = bytes_w

    @staticmethod
    def _use_rstr_ops(space, w_other):
        return True

    @staticmethod
    def _op_val(space, w_other):
        try:
            return space.bytes_w(w_other)
        except OperationError, e:
            if not e.match(space, space.w_TypeError):
                raise
        return space.buffer_w(w_other, space.BUF_SIMPLE).as_str()
Beispiel #25
0
class W_InterposeProcedure(values.W_Procedure):
    import_from_mixin(ProxyMixin)

    errorname = "interpose-procedure"
    _immutable_fields_ = ["inner", "check", "properties"]

    @jit.unroll_safe
    def __init__(self, code, check, props):
        assert code.iscallable()
        assert check is values.w_false or check.iscallable()
        self.inner = code
        self.check = check
        self.properties = props

    @staticmethod
    def has_self_arg():
        return False

    def get_arity(self, promote=False):
        return self.inner.get_arity(promote)

    def post_call_cont(self, args, prop, env, cont, calling_app):
        raise NotImplementedError("abstract method")

    def safe_proxy(self):
        return True

    @label
    def call(self, args, env, cont):
        return self.call_with_extra_info(args, env, cont, None)

    def is_non_interposing_chaperone(self):
        return self.check is values.w_false

    def call_with_extra_info(self, args, env, cont, calling_app):
        if self.check is values.w_false:
            return self.inner.call_with_extra_info(args, env, cont, calling_app)
        if not self.safe_proxy():
            return self.check.call_with_extra_info(args, env, cont, calling_app)
        prop = self.get_property(w_impersonator_prop_application_mark)
        after = self.post_call_cont(args, prop, env, cont, calling_app)
        if self.has_self_arg():
            args = [self] + args
        return self.check.call_with_extra_info(args, env, after, calling_app)

    # XXX Tricksy bits ahead. Since structs can act like procedures, a struct
    # may be proxied by a procedure proxy, thus it supports struct type,
    # ref, set, and struct property access.
    def ref_with_extra_info(self, field, app, env, cont):
        return self.inner.ref_with_extra_info(field, app, env, cont)

    def set_with_extra_info(self, field, val, app, env, cont):
        return self.inner.set_with_extra_info(field, val, app, env, cont)

    def struct_type(self):
        return self.inner.struct_type()

    def get_prop(self, property, env, cont):
        return self.inner.get_prop(property, env, cont)
Beispiel #26
0
class W_ImpStruct(W_InterposeStructBase):
    import_from_mixin(ImpersonatorMixin)

    def post_ref_cont(self, interp, app, env, cont):
        return impersonate_reference_cont(interp, [self], app, env, cont)

    def post_set_cont(self, op, field, val, app, env, cont):
        return imp_struct_set_cont(self.inner, op, field, app, env, cont)
Beispiel #27
0
class W_ChpProcedure(W_InterposeProcedure):
    import_from_mixin(ChaperoneMixin)

    errorname = "chp-procedure"

    def post_call_cont(self, args, prop, env, cont, calling_app):
        orig = values.Values.make(args)
        return chp_proc_cont(orig, self.inner, prop, calling_app, env, cont)
Beispiel #28
0
class W_ImpContinuationMarkKey(W_InterposeContinuationMarkKey):
    import_from_mixin(ImpersonatorMixin)

    def post_get_cont(self, value, env, cont):
        return imp_cmk_post_get_cont(self.inner, env, cont)

    def post_set_cont(self, body, value, env, cont):
        return imp_cmk_post_set_cont(body, self.inner, env, cont)
Beispiel #29
0
class W_ImpHashTable(W_InterposeHashTable):
    import_from_mixin(ImpersonatorMixin)

    def post_set_cont(self, key, val, env, cont):
        pass

    def post_ref_cont(self, key, env, cont):
        return imp_hash_table_ref_cont(self.inner, key, env, cont)
Beispiel #30
0
class W_ChpHashTable(W_InterposeHashTable):
    import_from_mixin(ChaperoneMixin)

    def post_set_cont(self, key, val, env, cont):
        pass

    def post_ref_cont(self, key, env, cont):
        return chp_hash_table_ref_cont(self.inner, key, env, cont)