Example #1
0
        v0 = argv[0]
        v1 = argv[1]
        v2 = space.null
    else:
        assert len(argv) == 3
        v0 = argv[0]
        v1 = argv[1]
        v2 = argv[2]
    assert isinstance(v0, Dict)
    try:
        return v0.data[v1]
    except KeyError as error:
        return v2


@Dict.method(u"pop", signature(Dict, Object))
def Dict_pop(self, key):
    try:
        return self.data.pop(key)
    except KeyError as error:
        raise space.unwind(space.LKeyError(self, key))


@Dict.builtin_method
@signature(Dict)
def keys(self):
    return KeyIterator(self.data.iterkeys())


@Dict.builtin_method
@signature(Dict)
Example #2
0
 def _impl_(fn):
     self.multimethod(*spec)(signature(*spec)(fn))
     return fn
Example #3
0
        self.uint8data[index.value] = rffi.r_uchar(value.value)
        return value

    def to_str(self):
        return rffi.charpsize2str(rffi.cast(rffi.CCHARP, self.uint8data),
                                  int(self.length))

    def iter(self):
        return Uint8Iterator(self.uint8data, self.length)

    def subslice(self, length):
        return Uint8Slice(self.uint8data, length, self)


@Uint8Data.method(u'memcpy',
                  signature(Uint8Data, Uint8Data, numbers.Integer, optional=1))
def Uint8Data_memcpy(self, src, size):
    size = src.length if size is None else size.value
    if size > self.length or size > src.length:
        raise space.unwind(space.LError(u"memcpy range error"))
    rffi.c_memcpy(rffi.cast(rffi.VOIDP, self.uint8data),
                  rffi.cast(rffi.VOIDP, src.uint8data), size)
    return space.null


class Uint8Array(Uint8Data):
    _immutable_fields_ = ['uint8data', 'length']
    __slots__ = ['uint8data', 'length']

    def repr(self):  # Add hexadecimal formatting later..
        return u"<uint8array>"
Example #4
0
        self.number = number

    def repr(self):
        return float_to_string(self.number)

    def hash(self):
        return compute_hash(self.number)

    def eq(self, other):
        if isinstance(other, Float):
            return self.number == other.number
        return False

# There is potentially a lot more to consider on generic case of
# stringifying floats, but we get ahead with this for a while.
@Float.method(u"to_string", signature(Float))
def Float_to_string(self):
    return space.String(float_to_string(self.number))

def float_to_string(x, code='g', precision=DTSF_STR_PRECISION):
    if isfinite(x):
        s = formatd(x, code, precision, DTSF_ADD_DOT_0)
    elif isinf(x):
        if x > 0.0:
            s = "inf"
        else:
            s = "-inf"
    else:  # isnan(x):
        s = "nan"
    return s.decode('utf-8')
Example #5
0
    def repr(self):
        cellnames = u""
        for cellname in self.map.attribute_indexes:
            if len(cellnames) > 0:
                cellnames += u", "
            cellnames += cellname

        return u"<object %s>" % cellnames


# Exnihilo doesn't exist for the user. He only sees an object.
Exnihilo.interface = Object.interface


@Object.instantiator2(signature(Object, optional=1))
def instantiate(obj):
    res = Exnihilo()
    if obj is not None:
        obj = space.cast(obj, space.Dict, u"object instantiation")
        for key, value in obj.data.items():
            key = space.cast(key, space.String, u"setattr")
            res.setattr(key.string, value)
    return res


# Attribute optimization for exnihilo objects.
class Map(object):
    def __init__(self):
        self.attribute_indexes = {}
        self.other_maps = {}
Example #6
0
            return String(u"".join(result))
        index = space.cast(index, Integer, u"index not an integer")
        if not 0 <= index.value < len(self.string):
            raise space.unwind(space.LKeyError(self, index))
        return String(self.string[index.value])

    def contains(self, item):
        if isinstance(item, String):
            return item.string in self.string
        return False

    def iter(self):
        return StringIterator(iter(self.string))
String.interface.name = u"str"

@String.instantiator2(signature(Object))
def String_init_is_cast(obj):
    return space.cast(obj, String, u"str()")

@String.method(u"count", signature(String, String))
def String_count(self, ch):
    if len(ch.string) != 1:
        raise space.unwind(space.LError(u"str.count expected char"))
    count = 0
    x = ch.string[0]
    for ch in self.string:
        if ch == x:
            count += 1
    return Integer(count)

@String.method(u"join", signature(String, Object))
Example #7
0
        if not 0 <= index.value < len(self.contents):
            raise space.unwind(space.LKeyError(self, index))
        self.contents[index.value] = value
        return value

    def iter(self):
        return ListIterator(iter(self.contents))

    def repr(self):
        out = []
        for item in self.contents:
            out.append(item.repr())
        return u'[' + u', '.join(out) + u']'


@List.method(u"append", signature(List, Object))
def List_append(self, other):
    self.contents.append(other)
    return null


@List.method(u"extend", signature(List, Object))
def List_extend(self, iterable):
    it = iterable.iter()
    try:
        while True:
            self.contents.append(it.callattr(u"next", []))
    except StopIteration as stop:
        return space.null
    return space.null
Example #8
0
 def _impl_(fn):
     self.multimethod(*spec)(signature(*spec)(fn))
     return fn
Example #9
0
            pass  # TODO: pass only LAttributeError


class DocRef(Object):
    def __init__(self, doc, name, parent):
        self.doc = doc
        self.name = name
        self.parent = parent

    def getattr(self, name):
        if name == u"link":
            return self.doc
        if name == u"name":
            return self.name
        if name == u"parent":
            return self.parent
        return Object.getattr(self, name)

    def listattr(self):
        listing = Object.listattr(self)
        listing.append(space.String(u"link"))
        listing.append(space.String(u"name"))
        listing.append(space.String(u"parent"))
        return listing


@DocRef.instantiator2(signature(Object, Object, Object, optional=1))
def DocRef_init(doc, name, parent):
    parent = null if parent is None else parent
    return DocRef(doc, name, parent)
Example #10
0
        if name == u"get":
            return self.getter
        if name == u"set":
            return self.setter
        return Object.getattr(self, name)

    def setattr(self, name, value):
        if name == u"get":
            self.getter = value
            return value
        if name == u"set":
            self.setter = value
            return value
        return Object.setattr(self, name, value)

@Property.instantiator2(signature())
def Property_instantiate():
    return Property()

# Id is for situations when you'd want to compare or
# hash things by identity. Or when you want to access
# a custom object directly.
class Id(Object):
    def __init__(self, ref):
        self.ref = ref

    def getattr(self, name):
        if name == u"ref":
            return self.ref
        return Object.getattr(self, name)
Example #11
0
        pass
    else:
        method.call([obj] + argv)
    return obj
CustomObject.interface.instantiate = instantiate

class Property(Object):
    def __init__(self):
        self.getter = null
        self.setter = null

    def getattr(self, name):
        if name == u"get":
            return self.getter
        if name == u"set":
            return self.setter
        return Object.getattr(self, name)

    def setattr(self, name, value):
        if name == u"get":
            self.getter = value
            return value
        if name == u"set":
            self.setter = value
            return value
        return Object.setattr(self, name, value)

@Property.instantiator2(signature())
def Property_instantiate():
    return Property()
Example #12
0
def hate_them(argv):
    raise space.unwind(space.LError(u"no"))


#expose_internal_methods(Interface)
#expose_internal_methods(Object) # if I do this,
# every method will have internal_methods
# Besides, Object methods are placeholders.

# I doubt we miss these.
#expose_internal_methods(BoundMethod)
#expose_internal_methods(builtin.Builtin)


# When your good names are your best.
@Interface.instantiator2(builtin.signature(Object))
def Interface_init_is_cast(obj):
    return space.get_interface(obj)


# Id is for situations when you'd want to compare or
# hash things by identity.


class Id(Object):
    def __init__(self, ref):
        self.ref = ref

    def getattr(self, name):
        if name == u"ref":
            return self.ref
Example #13
0
            else:
                a = start
        else:
            a = space.to_int(self.start)
            a = max(start, min(stop-1, a))
        if self.stop is null:
            if step < 0:
                b = start - 1 
            else:
                b = stop
        else:
            b = space.to_int(self.stop)
            b = max(start-1, min(stop, b))
        return (a, b, step)

@Slice.instantiator2(signature(Object, Object, Object, optional=1))
def Slice_inst(start, stop, step):
    if step is None:
        step = space.Integer(1)
    return Slice(start, stop, step)

class SliceRange(Object):
    def __init__(self, start, stop, step):
        self.current = start
        self.stop = stop
        self.step = step
        self.sign = +1 if step >= 0 else -1

    def iter(self):
        return self
Example #14
0
    def hash(self):
        multi = r_uint(1822399083) + r_uint(1822399083) + 1
        hash = r_uint(1927868237)
        hash *= r_uint(len(self._set) + 1)
        for w_item in self._set.iterkeys():
            h = w_item.hash()
            value = (r_uint(h ^ (h << 16) ^ 89869747) * multi)
            hash = hash ^ value
        hash = hash * 69069 + 907133923
        if hash == 0:
            hash = 590923713
        return intmask(hash)


@Set.method(u"copy", signature(Set))
def Set_copy(self):
    copy = Set()
    copy._set.update(self._set)
    return copy


@Set.method(u"clear", signature(Set))
def Set_clear(self):
    self._set = r_dict(eq_fn, hash_fn, force_non_null=True)
    return null


@Set.method(u"add", signature(Set, Object))
def Set_add(self, obj):
    self._set[obj] = None
Example #15
0

CustomObject.interface.instantiate = instantiate


class Property(Object):
    def __init__(self):
        self.getter = null
        self.setter = null

    def getattr(self, name):
        if name == u"get":
            return self.getter
        if name == u"set":
            return self.setter
        return Object.getattr(self, name)

    def setattr(self, name, value):
        if name == u"get":
            self.getter = value
            return value
        if name == u"set":
            self.setter = value
            return value
        return Object.setattr(self, name, value)


@Property.instantiator2(signature())
def Property_instantiate():
    return Property()
Example #16
0
        return _impl_

    def setitem(self, index, value):
        vec = []
        assert isinstance(index, space.List)
        for item in index.contents:
            assert isinstance(item, space.Interface)
            vec.append(item)
        self.methods[vec] = value
        return value

    def getattr(self, index):
        if index == u"default":
            return self.default
        return Object.getattr(self, index)

    def setattr(self, index, value):
        if index == u"default":
            self.default = value
            return value
        return Object.setattr(self, index, value)

@Multimethod.instantiator
@signature(Integer)
def _(arity):
    return Multimethod(arity.value)

@Multimethod.method(u"call_suppressed", signature(Multimethod, variadic=True))
def Multimethod_call_suppressed(mm, args):
    return mm.call_suppressed(args)
Example #17
0
        self._set = r_dict(eq_fn, hash_fn, force_non_null=True)

    def contains(self, index):
        if index in self._set:
            return True
        return False

    def getattr(self, name):
        if name == u'length':
            return Integer(len(self._set))
        return Object.getattr(self, name)

    def iter(self):
        return SetIterator(self._set.iterkeys())

@Set.method(u"copy", signature(Set))
def Set_copy(self):
    copy = Set()
    copy._set.update(self._set)
    return copy

@Set.method(u"clear", signature(Set))
def Set_clear(self):
    self._set = r_dict(eq_fn, hash_fn, force_non_null=True)
    return null

@Set.method(u"add", signature(Set, Object))
def Set_add(self, obj):
    self._set[obj] = None
    return null
Example #18
0
    if len(argv) == 2:
        v0 = argv[0]
        v1 = argv[1]
        v2 = space.null
    else:
        assert len(argv) == 3
        v0 = argv[0]
        v1 = argv[1]
        v2 = argv[2]
    assert isinstance(v0, Dict)
    try:
        return v0.data[v1]
    except KeyError as error:
        return v2

@Dict.method(u"pop", signature(Dict, Object))
def Dict_pop(self, key):
    try:
        return self.data.pop(key)
    except KeyError as error:
        raise space.unwind(space.LKeyError(self, key))

@Dict.builtin_method
@signature(Dict)
def keys(self):
    return KeyIterator(self.data.iterkeys())

@Dict.builtin_method
@signature(Dict)
def items(self):
    return ItemIterator(self.data.iteritems())
Example #19
0
                a = low
        else:
            a = space.to_int(self.start)
            a = max(low, min(high, a))
        if self.stop is null:
            if step < 0:
                b = low - 1
            else:
                b = high + 1
        else:
            b = space.to_int(self.stop)
            b = max(low - 1, min(high + 1, b))
        return (a, b, step)


@Slice.instantiator2(signature(Object, Object, Object, optional=1))
def Slice_inst(start, stop, step):
    if step is None:
        step = space.Integer(1)
    return Slice(start, stop, step)


class SliceRange(Object):
    def __init__(self, start, stop, step):
        self.current = start
        self.stop = stop
        self.step = step
        self.sign = +1 if step >= 0 else -1

    def iter(self):
        return self
Example #20
0
        source_location=builtin.get_source_location(fn))


# Internal methods help at documenting the system.
# TODO: rethink about lifting this eventually?
def hate_them(argv):
    raise space.unwind(space.LError(u"hate them"))


#expose_internal_methods(Interface)
#expose_internal_methods(Object) # if I do this,
# every method will have internal_methods
# Besides, Object methods are placeholders.

# I doubt we miss these.
#expose_internal_methods(BoundMethod)
#expose_internal_methods(builtin.Builtin)


# When your good names are your best.
@Interface.instantiator2(builtin.signature(Object))
def Interface_init_is_cast(obj):
    return space.get_interface(obj)


# Only active with the user-defined interfaces that may be 'lost'.
@Interface.method(u"+finalize", builtin.signature(Interface))
def Interface_finalize(self):
    for record in self.multimethods:
        record.multimethod.unregister_record(record)
Example #21
0
            for item in index.contents]
        self.multimethod_table[vec] = value
        return value

    def getattr(self, index):
        if index == u"default":
            return self.default
        return Object.getattr(self, index)

    def setattr(self, index, value):
        if index == u"default":
            self.default = value
            return value
        return Object.setattr(self, index, value)

@Multimethod.instantiator
@signature(Integer)
def _(arity):
    return Multimethod(arity.value)

@Multimethod.method(u"call_suppressed", signature(Multimethod, variadic=True))
def Multimethod_call_suppressed(mm, args):
    return mm.call_suppressed(args)

@Multimethod.method(u"keys", signature(Multimethod))
def Multimethod_keys(self):
    return space.List([
        space.List(list(vec))
        for vec in self.multimethod_table
    ])
Example #22
0
        return index - ord('0')
    if ord('A') <= index <= ord('Z'):
        return index - ord('A') + 10
    if ord('a') <= index <= ord('z'):
        return index - ord('a') + 10
    return -1

@String.builtin_method
@signature(String)
def is_space(string):
    for ch in string.string:
        if not unicodedb.isspace(ord(ch)):
            return space.false
    return space.true

@String.method(u"startswith", signature(String, String))
def String_startswith(self, prefix):
    return space.boolean(
        self.string.startswith(prefix.string))

@String.method(u"endswith", signature(String, String))
def String_endswith(self, postfix):
    return space.boolean(
        self.string.endswith(postfix.string))

class StringIterator(Object):
    _immutable_fields_ = ['iterator']
    def __init__(self, iterator):
        self.iterator = iterator

    def iter(self):
Example #23
0
        index = space.cast(index, Integer, u"index not an integer")
        if not 0 <= index.value < len(self.contents):
            raise space.unwind(space.LKeyError(self, index))
        self.contents[index.value] = value
        return value

    def iter(self):
        return ListIterator(iter(self.contents))

    def repr(self):
        out = []
        for item in self.contents:
            out.append(item.repr())
        return u'[' + u', '.join(out) + u']'

@List.method(u"append", signature(List, Object))
def List_append(self, other):
    self.contents.append(other)
    return null

@List.method(u"extend", signature(List, Object))
def List_extend(self, iterable):
    it = iterable.iter()
    try:
        while True:
            self.contents.append(it.callattr(u"next", []))
    except StopIteration as stop:
        return space.null
    return space.null

@List.method(u"insert", signature(List, Integer, Object))
Example #24
0
    def repr(self):
        return float_to_string(self.number)

    def hash(self):
        return compute_hash(self.number)

    def eq(self, other):
        if isinstance(other, Float):
            return self.number == other.number
        return False


# There is potentially a lot more to consider on generic case of
# stringifying floats, but we get ahead with this for a while.
@Float.method(u"to_string", signature(Float))
def Float_to_string(self):
    return space.String(float_to_string(self.number))


def float_to_string(x, code='g', precision=DTSF_STR_PRECISION):
    if isfinite(x):
        s = formatd(x, code, precision, DTSF_ADD_DOT_0)
    elif isinf(x):
        if x > 0.0:
            s = "inf"
        else:
            s = "-inf"
    else:  # isnan(x):
        s = "nan"
    return s.decode('utf-8')
Example #25
0
    return space.true

def as_alphadigit_i(index):
    if ord('0') <= index <= ord('9'):
        return index - ord('0')
    if ord('A') <= index <= ord('Z'):
        return index - ord('A') + 10
    if ord('a') <= index <= ord('z'):
        return index - ord('a') + 10
    return -1

@String.builtin_method
@signature(String)
def is_space(string):
    for ch in string.string:
        if not unicodedb.isspace(ord(ch)):
            return space.false
    return space.true

class StringIterator(Object):
    _immutable_fields_ = ['iterator']
    def __init__(self, iterator):
        self.iterator = iterator

    def iter(self):
        return self
    
@StringIterator.method(u"next", signature(StringIterator))
def StringIterator_next(self):
    return String(self.iterator.next())