Ejemplo n.º 1
0
    def recv(self, atom, args):
        if atom is RUN_1:
            return IntObject(int(unwrapStr(args[0]).encode('utf-8')))

        if atom is RUN_2:
            inp = unwrapStr(args[0])
            radix = unwrapInt(args[1])
            try:
                v = int(inp.encode("utf-8"), radix)
            except ValueError:
                raise userError(u"Invalid literal for base %d: %s" %
                                (radix, inp))
            return IntObject(v)

        if atom is FROMBYTES_1:
            return IntObject(int(unwrapBytes(args[0])))

        if atom is FROMBYTES_2:
            bs = unwrapBytes(args[0])
            radix = unwrapInt(args[1])
            try:
                v = int(bs, radix)
            except ValueError:
                raise userError(u"Invalid literal for base %d: %s" %
                                (radix, bytesToString(bs)))
            return IntObject(v)

        raise Refused(self, atom, args)
Ejemplo n.º 2
0
    def recv(self, atom, args):
        if atom is RUN_1:
            return IntObject(int(unwrapStr(args[0]).encode('utf-8')))

        if atom is RUN_2:
            inp = unwrapStr(args[0])
            radix = unwrapInt(args[1])
            try:
                v = int(inp.encode("utf-8"), radix)
            except ValueError:
                raise userError(u"Invalid literal for base %d: %s" % (
                        radix, inp))
            return IntObject(v)

        if atom is FROMBYTES_1:
            return IntObject(int(unwrapBytes(args[0])))

        if atom is FROMBYTES_2:
            bs = unwrapBytes(args[0])
            radix = unwrapInt(args[1])
            try:
                v = int(bs, radix)
            except ValueError:
                raise userError(u"Invalid literal for base %d: %s" % (
                        radix, bytesToString(bs)))
            return IntObject(v)

        raise Refused(self, atom, args)
Ejemplo n.º 3
0
def makeTCP4ClientEndpoint(host, port):
    """
    Make a TCPv4 client endpoint.
    """

    host = unwrapBytes(host)
    port = unwrapInt(port)
    return TCP4ClientEndpoint(host, port)
Ejemplo n.º 4
0
def makeTCP4ClientEndpoint(host, port):
    """
    Make a TCPv4 client endpoint.
    """

    host = unwrapBytes(host)
    port = unwrapInt(port)
    return TCP4ClientEndpoint(host, port)
Ejemplo n.º 5
0
    def recv(self, atom, args):
        # _makeIterator/0: Create an iterator for this collection's contents.
        if atom is _MAKEITERATOR_0:
            return self._makeIterator()

        if atom is _PRINTON_1:
            printer = args[0]
            self.printOn(printer)
            return NullObject

        # contains/1: Determine whether an element is in this collection.
        if atom is CONTAINS_1:
            return wrapBool(self.contains(args[0]))

        # size/0: Get the number of elements in the collection.
        if atom is SIZE_0:
            return IntObject(self.size())

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_1:
            start = unwrapInt(args[0])
            try:
                return self.slice(start)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_2:
            start = unwrapInt(args[0])
            stop = unwrapInt(args[1])
            try:
                return self.slice(start, stop)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # snapshot/0: Create a new constant collection with a copy of the
        # current collection's contents.
        if atom is SNAPSHOT_0:
            return self.snapshot()

        if atom is JOIN_1:
            l = unwrapList(args[0])
            return self.join(l)

        return self._recv(atom, args)
Ejemplo n.º 6
0
    def recv(self, atom, args):
        # _makeIterator/0: Create an iterator for this collection's contents.
        if atom is _MAKEITERATOR_0:
            return self._makeIterator()

        if atom is _PRINTON_1:
            printer = args[0]
            self.printOn(printer)
            return NullObject

        # contains/1: Determine whether an element is in this collection.
        if atom is CONTAINS_1:
            return wrapBool(self.contains(args[0]))

        # size/0: Get the number of elements in the collection.
        if atom is SIZE_0:
            return IntObject(self.size())

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_1:
            start = unwrapInt(args[0])
            try:
                return self.slice(start)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_2:
            start = unwrapInt(args[0])
            stop = unwrapInt(args[1])
            try:
                return self.slice(start, stop)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # snapshot/0: Create a new constant collection with a copy of the
        # current collection's contents.
        if atom is SNAPSHOT_0:
            return self.snapshot()

        if atom is JOIN_1:
            l = unwrapList(args[0])
            return self.join(l)

        return self._recv(atom, args)
Ejemplo n.º 7
0
 def cmp(self, other):
     for i, left in enumerate(self.strategy.fetch_all(self)):
         try:
             right = other[i]
         except IndexError:
             # They're shorter than us.
             return 1
         try:
             result = unwrapInt(left.call(u"op__cmp", [right]))
         except UserException:
             result = -unwrapInt(right.call(u"op__cmp", [left]))
         if result < 0:
             return -1
         if result > 0:
             return 1
     # They could be longer than us but we were equal up to this point.
     # Do a final length check.
     return 0 if self.size() == len(other) else -1
Ejemplo n.º 8
0
Archivo: lists.py Proyecto: dckc/typhon
 def op__cmp(self, other):
     for i, left in enumerate(self.objs):
         try:
             right = other[i]
         except IndexError:
             # They're shorter than us.
             return 1
         try:
             result = unwrapInt(left.call(u"op__cmp", [right]))
         except UserException:
             result = -unwrapInt(right.call(u"op__cmp", [left]))
         if result < 0:
             return -1
         if result > 0:
             return 1
     # They could be longer than us but we were equal up to this point.
     # Do a final length check.
     return 0 if len(self.objs) == len(other) else -1
Ejemplo n.º 9
0
    def recv(self, atom, args):
        if atom is FROMSTRING_1:
            return BytesObject("".join([chr(ord(c))
                                        for c in unwrapStr(args[0])]))

        if atom is FROMINTS_1:
            data = unwrapList(args[0])
            return BytesObject("".join([chr(unwrapInt(i)) for i in data]))

        raise Refused(self, atom, args)
Ejemplo n.º 10
0
    def recv(self, atom, args):
        if atom is FROMSTRING_1:
            return BytesObject("".join(
                [chr(ord(c)) for c in unwrapStr(args[0])]))

        if atom is FROMINTS_1:
            data = unwrapList(args[0])
            return BytesObject("".join([chr(unwrapInt(i)) for i in data]))

        raise Refused(self, atom, args)
Ejemplo n.º 11
0
    def recv(self, atom, args):
        if atom is RUN_1:
            return DoubleObject(float(unwrapStr(args[0]).encode('utf-8')))

        if atom is FROMBYTES_1:
            data = unwrapList(args[0])
            x = unpack_float("".join([chr(unwrapInt(byte)) for byte in data]),
                             True)
            return DoubleObject(x)

        raise Refused(self, atom, args)
Ejemplo n.º 12
0
    def recv(self, atom, args):
        if atom is RUN_1:
            return DoubleObject(float(unwrapStr(args[0]).encode('utf-8')))

        if atom is FROMBYTES_1:
            data = unwrapList(args[0])
            x = unpack_float("".join([chr(unwrapInt(byte)) for byte in data]),
                             True)
            return DoubleObject(x)

        raise Refused(self, atom, args)
Ejemplo n.º 13
0
    def mirandaMethods(self, atom, arguments, namedArgsMap):
        from typhon.objects.collections.maps import EMPTY_MAP
        if atom is _CONFORMTO_1:
            # Welcome to _conformTo/1.
            # to _conformTo(_): return self
            return self

        if atom is _GETALLEGEDINTERFACE_0:
            # Welcome to _getAllegedInterface/0.
            interface = self.optInterface()
            if interface is None:
                from typhon.objects.interfaces import ComputedInterface
                interface = ComputedInterface(self)
            return interface

        if atom is _PRINTON_1:
            # Welcome to _printOn/1.
            from typhon.objects.constants import NullObject
            self.printOn(arguments[0])
            return NullObject

        if atom is _RESPONDSTO_2:
            from typhon.objects.constants import wrapBool
            from typhon.objects.data import unwrapInt, unwrapStr
            verb = unwrapStr(arguments[0])
            arity = unwrapInt(arguments[1])
            atom = getAtom(verb, arity)
            result = (atom in self.respondingAtoms() or
                      atom in mirandaAtoms)
            return wrapBool(result)

        if atom is _SEALEDDISPATCH_1:
            # to _sealedDispatch(_): return null
            from typhon.objects.constants import NullObject
            return NullObject

        if atom is _UNCALL_0:
            from typhon.objects.constants import NullObject
            return NullObject

        if atom is _WHENMORERESOLVED_1:
            # Welcome to _whenMoreResolved.
            # This method's implementation, in Monte, should be:
            # to _whenMoreResolved(callback): callback<-(self)
            from typhon.vats import currentVat
            vat = currentVat.get()
            vat.sendOnly(arguments[0], RUN_1, [self], EMPTY_MAP)
            from typhon.objects.constants import NullObject
            return NullObject
        return None
Ejemplo n.º 14
0
    def mirandaMethods(self, atom, arguments, namedArgsMap):
        from typhon.objects.collections.maps import EMPTY_MAP
        if atom is _CONFORMTO_1:
            # Welcome to _conformTo/1.
            # to _conformTo(_): return self
            return self

        if atom is _GETALLEGEDINTERFACE_0:
            # Welcome to _getAllegedInterface/0.
            interface = self.optInterface()
            if interface is None:
                from typhon.objects.interfaces import ComputedInterface
                interface = ComputedInterface(self)
            return interface

        if atom is _PRINTON_1:
            # Welcome to _printOn/1.
            from typhon.objects.constants import NullObject
            self.printOn(arguments[0])
            return NullObject

        if atom is _RESPONDSTO_2:
            from typhon.objects.constants import wrapBool
            from typhon.objects.data import unwrapInt, unwrapStr
            verb = unwrapStr(arguments[0])
            arity = unwrapInt(arguments[1])
            atom = getAtom(verb, arity)
            result = (atom in self.respondingAtoms() or atom in mirandaAtoms)
            return wrapBool(result)

        if atom is _SEALEDDISPATCH_1:
            # to _sealedDispatch(_): return null
            from typhon.objects.constants import NullObject
            return NullObject

        if atom is _UNCALL_0:
            from typhon.objects.constants import NullObject
            return NullObject

        if atom is _WHENMORERESOLVED_1:
            # Welcome to _whenMoreResolved.
            # This method's implementation, in Monte, should be:
            # to _whenMoreResolved(callback): callback<-(self)
            from typhon.vats import currentVat
            vat = currentVat.get()
            vat.sendOnly(arguments[0], RUN_1, [self], EMPTY_MAP)
            from typhon.objects.constants import NullObject
            return NullObject
        return None
Ejemplo n.º 15
0
    def recv(self, atom, args):
        from typhon.objects.collections.maps import EMPTY_MAP
        if atom is SEED_1:
            f = args[0]
            if not f.auditedBy(deepFrozenStamp):
                self.log(u"seed/1: Warning: Seeded receiver is not DeepFrozen")
                self.log(u"seed/1: Warning: This is gonna be an error soon!")
            from typhon.objects.refs import packLocalRef
            return packLocalRef(self.send(f, RUN_0, [], EMPTY_MAP), self,
                                currentVat.get())

        if atom is SPROUT_2:
            name = unwrapStr(args[0])
            checkpoints = unwrapInt(args[1])
            vat = Vat(self._manager, self.uv_loop, name,
                      checkpoints=checkpoints)
            self._manager.vats.append(vat)
            return vat

        raise Refused(self, atom, args)
Ejemplo n.º 16
0
    def recv(self, atom, args):
        from typhon.objects.collections.maps import EMPTY_MAP
        if atom is SEED_1:
            f = args[0]
            if not f.auditedBy(deepFrozenStamp):
                self.log(u"seed/1: Warning: Seeded receiver is not DeepFrozen")
                self.log(u"seed/1: Warning: This is gonna be an error soon!")
            from typhon.objects.refs import packLocalRef
            return packLocalRef(self.send(f, RUN_0, [], EMPTY_MAP), self,
                                currentVat.get())

        if atom is SPROUT_2:
            name = unwrapStr(args[0])
            checkpoints = unwrapInt(args[1])
            vat = Vat(self._manager,
                      self.uv_loop,
                      name,
                      checkpoints=checkpoints)
            self._manager.vats.append(vat)
            return vat

        raise Refused(self, atom, args)
Ejemplo n.º 17
0
    def _recv(self, atom, args):
        if atom is ADD_1:
            other = unwrapList(args[0])
            if len(other):
                return ConstList(self.strategy.fetch_all(self) + other)
            else:
                return self

        if atom is ASMAP_0:
            from typhon.objects.collections.maps import ConstMap
            return ConstMap(self.asMap())

        if atom is ASSET_0:
            from typhon.objects.collections.sets import ConstSet
            return ConstSet(self.asSet())

        if atom is DIVERGE_0:
            return FlexList(self.strategy.fetch_all(self)[:])

        if atom is GET_1:
            # Lookup by index.
            index = unwrapInt(args[0])
            if index < 0:
                raise userError(u"Index %d cannot be negative" % index)
            if index >= self.strategy.size(self):
                raise userError(u"Index %d is out of bounds" % index)
            return self.strategy.fetch(self, index)

        if atom is INDEXOF_1:
            return IntObject(self.indexOf(args[0]))

        if atom is LAST_0:
            size = self.strategy.size(self)
            if size:
                return self.strategy.fetch(self, size - 1)
            raise userError(u"Empty list has no last element")

        if atom is MULTIPLY_1:
            # multiply/1: Create a new list by repeating this list's contents.
            count = unwrapInt(args[0])
            if count < 0:
                raise userError(u"Can't multiply list %d times" % count)
            elif count == 0:
                return ConstList([])
            return ConstList(self.strategy.fetch_all(self) * count)

        if atom is OP__CMP_1:
            other = unwrapList(args[0])
            return IntObject(self.cmp(other))

        if atom is REVERSE_0:
            # This might seem slightly inefficient, and it might be, but I
            # want to make it very clear to RPython that we are not mutating
            # the list after we assign it to the new object.
            new = self.strategy.fetch_all(self)[:]
            new.reverse()
            return ConstList(new)

        if atom is SORT_0:
            return self.sort()

        if atom is STARTOF_1:
            return IntObject(self.startOf(unwrapList(args[0])))

        if atom is STARTOF_2:
            start = unwrapInt(args[1])
            if start < 0:
                raise userError(u"startOf/2: Negative start %d not permitted"
                                % start)
            return IntObject(self.startOf(unwrapList(args[0]), start))

        if atom is WITH_1:
            # with/1: Create a new list with an appended object.
            return ConstList(self.strategy.fetch_all(self) + args)

        if atom is WITH_2:
            # Replace by index.
            index = unwrapInt(args[0])
            return self.put(index, args[1])

        if atom is _UNCALL_0:
            from typhon.scopes.safe import theMakeList
            from typhon.objects.collections.maps import EMPTY_MAP
            return ConstList([theMakeList, StrObject(u"run"), self, EMPTY_MAP])

        raise Refused(self, atom, args)
Ejemplo n.º 18
0
 def testUnwrapIntPromise(self):
     with scopedVat(testingVat()):
         p = makeNear(IntObject(42))
         self.assertEqual(unwrapInt(p), 42)
Ejemplo n.º 19
0
    def callAtom(self, atom, arguments, namedArgsMap):
        """
        This method is used to reuse atoms without having to rebuild them.
        """
        from typhon.objects.collections.maps import EMPTY_MAP
        # Promote the atom, on the basis that atoms are generally reused.
        atom = promote(atom)
        # Log the atom to the JIT log. Don't do this if the atom's not
        # promoted; it'll be slow.
        jit_debug(atom.repr)

        try:
            return self.recvNamed(atom, arguments, namedArgsMap)
        except Refused as r:
            # This block of method implementations is Typhon's Miranda
            # protocol. ~ C.

            if atom is _CONFORMTO_1:
                # Welcome to _conformTo/1.
                # to _conformTo(_): return self
                return self

            if atom is _GETALLEGEDINTERFACE_0:
                # Welcome to _getAllegedInterface/0.
                interface = self.optInterface()
                if interface is None:
                    from typhon.objects.interfaces import ComputedInterface
                    interface = ComputedInterface(self)
                return interface

            if atom is _PRINTON_1:
                # Welcome to _printOn/1.
                from typhon.objects.constants import NullObject
                self.printOn(arguments[0])
                return NullObject

            if atom is _RESPONDSTO_2:
                from typhon.objects.constants import wrapBool
                from typhon.objects.data import unwrapInt, unwrapStr
                verb = unwrapStr(arguments[0])
                arity = unwrapInt(arguments[1])
                atom = getAtom(verb, arity)
                result = (atom in self.respondingAtoms()
                          or atom in mirandaAtoms)
                return wrapBool(result)

            if atom is _SEALEDDISPATCH_1:
                # to _sealedDispatch(_): return null
                from typhon.objects.constants import NullObject
                return NullObject

            if atom is _UNCALL_0:
                from typhon.objects.constants import NullObject
                return NullObject

            if atom is _WHENMORERESOLVED_1:
                # Welcome to _whenMoreResolved.
                # This method's implementation, in Monte, should be:
                # to _whenMoreResolved(callback): callback<-(self)
                from typhon.vats import currentVat
                vat = currentVat.get()
                vat.sendOnly(arguments[0], RUN_1, [self], EMPTY_MAP)
                from typhon.objects.constants import NullObject
                return NullObject

            addTrail(r, self, atom, arguments)
            raise

        except UserException as ue:
            addTrail(ue, self, atom, arguments)
            raise
        except MemoryError:
            ue = userError(u"Memory corruption or exhausted heap")
            addTrail(ue, self, atom, arguments)
            raise ue
        except StackOverflow:
            check_stack_overflow()
            ue = userError(u"Stack overflow")
            addTrail(ue, self, atom, arguments)
            raise ue
Ejemplo n.º 20
0
def makeTCP4ServerEndpoint(port):
    """
    Make a TCPv4 server endpoint.
    """

    return TCP4ServerEndpoint(unwrapInt(port))
Ejemplo n.º 21
0
    def recv(self, atom, args):
        # _makeIterator/0: Create an iterator for this collection's contents.
        if atom is _MAKEITERATOR_0:
            return self._makeIterator()

        if atom is _PRINTON_1:
            printer = args[0]
            self.printOn(printer)
            return NullObject

        # contains/1: Determine whether an element is in this collection.
        if atom is CONTAINS_1:
            return wrapBool(self.contains(args[0]))

        # size/0: Get the number of elements in the collection.
        if atom is SIZE_0:
            return IntObject(self.size())

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_1:
            start = unwrapInt(args[0])
            try:
                return self.slice(start)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_2:
            start = unwrapInt(args[0])
            stop = unwrapInt(args[1])
            try:
                return self.slice(start, stop)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # snapshot/0: Create a new constant collection with a copy of the
        # current collection's contents.
        if atom is SNAPSHOT_0:
            return self.snapshot()

        from typhon.objects.collections.lists import ConstList

        if atom is _UNCALL_0:
            return ConstList(self._uncall())

        if atom is ASSET_0:
            from typhon.objects.collections.sets import ConstSet
            return ConstSet(self.objectMap)

        if atom is DIVERGE_0:
            return FlexMap(self.objectMap)

        if atom is FETCH_2:
            key = args[0]
            thunk = args[1]
            rv = self.objectMap.get(key, None)
            if rv is None:
                rv = thunk.call(u"run", [])
            return rv

        if atom is GETKEYS_0:
            return ConstList(self.objectMap.keys())

        if atom is GETVALUES_0:
            return ConstList(self.objectMap.values())

        if atom is GET_1:
            key = args[0]
            try:
                return self.objectMap[key]
            except KeyError:
                raise userError(u"Key not found: %s" % (key.toString(),))

        # or/1: Unify the elements of this collection with another.
        if atom is OR_1:
            return self._or(args[0])

        if atom is REVERSE_0:
            d = monteMap()
            l = [(k, v) for k, v in self.objectMap.iteritems()]
            # Reverse it!
            l.reverse()
            for k, v in l:
                d[k] = v
            return ConstMap(d)

        if atom is SORTKEYS_0:
            # Extract a list, sort it, pack it back into a dict.
            d = monteMap()
            l = [(k, v) for k, v in self.objectMap.iteritems()]
            KeySorter(l).sort()
            for k, v in l:
                d[k] = v
            return ConstMap(d)

        if atom is SORTVALUES_0:
            # Same as sortKeys/0.
            d = monteMap()
            l = [(k, v) for k, v in self.objectMap.iteritems()]
            ValueSorter(l).sort()
            for k, v in l:
                d[k] = v
            return ConstMap(d)

        if atom is WITH_2:
            # Replace by key.
            key = args[0]
            value = args[1]
            d = self.objectMap.copy()
            d[key] = value
            return ConstMap(d)

        if atom is WITHOUT_1:
            key = args[0]
            d = self.objectMap.copy()
            # Ignore the case where the key wasn't in the map.
            if key in d:
                del d[key]
            return ConstMap(d)

        if atom is PUT_2:
            key = args[0]
            value = args[1]
            self.put(key, value)
            return NullObject

        if atom is REMOVEKEY_1:
            key = args[0]
            self.removeKey(key)
            return NullObject

        if atom is POP_0:
            return self.pop()

        raise Refused(self, atom, args)
Ejemplo n.º 22
0
    def recv(self, atom, args):
        # _makeIterator/0: Create an iterator for this collection's contents.
        if atom is _MAKEITERATOR_0:
            return self._makeIterator()

        if atom is _PRINTON_1:
            printer = args[0]
            self.printOn(printer)
            return NullObject

        # contains/1: Determine whether an element is in this collection.
        if atom is CONTAINS_1:
            return wrapBool(self.contains(args[0]))

        # size/0: Get the number of elements in the collection.
        if atom is SIZE_0:
            return IntObject(self.size())

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_1:
            start = unwrapInt(args[0])
            try:
                return self.slice(start)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_2:
            start = unwrapInt(args[0])
            stop = unwrapInt(args[1])
            try:
                return self.slice(start, stop)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # snapshot/0: Create a new constant collection with a copy of the
        # current collection's contents.
        if atom is SNAPSHOT_0:
            return self.snapshot()

        from typhon.objects.collections.lists import ConstList

        if atom is _UNCALL_0:
            return ConstList(self._uncall())

        if atom is ASSET_0:
            from typhon.objects.collections.sets import ConstSet
            return ConstSet(self.objectMap)

        if atom is DIVERGE_0:
            return FlexMap(self.objectMap)

        if atom is FETCH_2:
            key = args[0]
            thunk = args[1]
            rv = self.objectMap.get(key, None)
            if rv is None:
                rv = thunk.call(u"run", [])
            return rv

        if atom is GETKEYS_0:
            return ConstList(self.objectMap.keys())

        if atom is GETVALUES_0:
            return ConstList(self.objectMap.values())

        if atom is GET_1:
            key = args[0]
            try:
                return self.objectMap[key]
            except KeyError:
                raise userError(u"Key not found: %s" % (key.toString(), ))

        # or/1: Unify the elements of this collection with another.
        if atom is OR_1:
            return self._or(args[0])

        if atom is REVERSE_0:
            d = monteMap()
            l = [(k, v) for k, v in self.objectMap.iteritems()]
            # Reverse it!
            l.reverse()
            for k, v in l:
                d[k] = v
            return ConstMap(d)

        if atom is SORTKEYS_0:
            # Extract a list, sort it, pack it back into a dict.
            d = monteMap()
            l = [(k, v) for k, v in self.objectMap.iteritems()]
            KeySorter(l).sort()
            for k, v in l:
                d[k] = v
            return ConstMap(d)

        if atom is SORTVALUES_0:
            # Same as sortKeys/0.
            d = monteMap()
            l = [(k, v) for k, v in self.objectMap.iteritems()]
            ValueSorter(l).sort()
            for k, v in l:
                d[k] = v
            return ConstMap(d)

        if atom is WITH_2:
            # Replace by key.
            key = args[0]
            value = args[1]
            d = self.objectMap.copy()
            d[key] = value
            return ConstMap(d)

        if atom is WITHOUT_1:
            key = args[0]
            d = self.objectMap.copy()
            # Ignore the case where the key wasn't in the map.
            if key in d:
                del d[key]
            return ConstMap(d)

        if atom is PUT_2:
            key = args[0]
            value = args[1]
            self.put(key, value)
            return NullObject

        if atom is REMOVEKEY_1:
            key = args[0]
            self.removeKey(key)
            return NullObject

        if atom is POP_0:
            return self.pop()

        raise Refused(self, atom, args)
Ejemplo n.º 23
0
    def callAtom(self, atom, arguments, namedArgsMap):
        """
        This method is used to reuse atoms without having to rebuild them.
        """
        from typhon.objects.collections.maps import EMPTY_MAP
        # Promote the atom, on the basis that atoms are generally reused.
        atom = promote(atom)
        # Log the atom to the JIT log. Don't do this if the atom's not
        # promoted; it'll be slow.
        jit_debug(atom.repr)

        try:
            return self.recvNamed(atom, arguments, namedArgsMap)
        except Refused as r:
            # This block of method implementations is Typhon's Miranda
            # protocol. ~ C.

            if atom is _CONFORMTO_1:
                # Welcome to _conformTo/1.
                # to _conformTo(_): return self
                return self

            if atom is _GETALLEGEDINTERFACE_0:
                # Welcome to _getAllegedInterface/0.
                interface = self.optInterface()
                if interface is None:
                    from typhon.objects.interfaces import ComputedInterface
                    interface = ComputedInterface(self)
                return interface

            if atom is _PRINTON_1:
                # Welcome to _printOn/1.
                from typhon.objects.constants import NullObject
                self.printOn(arguments[0])
                return NullObject

            if atom is _RESPONDSTO_2:
                from typhon.objects.constants import wrapBool
                from typhon.objects.data import unwrapInt, unwrapStr
                verb = unwrapStr(arguments[0])
                arity = unwrapInt(arguments[1])
                atom = getAtom(verb, arity)
                result = (atom in self.respondingAtoms() or
                          atom in mirandaAtoms)
                return wrapBool(result)

            if atom is _SEALEDDISPATCH_1:
                # to _sealedDispatch(_): return null
                from typhon.objects.constants import NullObject
                return NullObject

            if atom is _UNCALL_0:
                from typhon.objects.constants import NullObject
                return NullObject

            if atom is _WHENMORERESOLVED_1:
                # Welcome to _whenMoreResolved.
                # This method's implementation, in Monte, should be:
                # to _whenMoreResolved(callback): callback<-(self)
                from typhon.vats import currentVat
                vat = currentVat.get()
                vat.sendOnly(arguments[0], RUN_1, [self], EMPTY_MAP)
                from typhon.objects.constants import NullObject
                return NullObject

            addTrail(r, self, atom, arguments)
            raise

        except UserException as ue:
            addTrail(ue, self, atom, arguments)
            raise
        except MemoryError:
            ue = userError(u"Memory corruption or exhausted heap")
            addTrail(ue, self, atom, arguments)
            raise ue
        except StackOverflow:
            check_stack_overflow()
            ue = userError(u"Stack overflow")
            addTrail(ue, self, atom, arguments)
            raise ue
Ejemplo n.º 24
0
    def recv(self, atom, args):
        from typhon.objects.collections.lists import ConstList

        # _makeIterator/0: Create an iterator for this collection's contents.
        if atom is _MAKEITERATOR_0:
            return self._makeIterator()

        if atom is _PRINTON_1:
            printer = args[0]
            self.printOn(printer)
            return NullObject

        if atom is _UNCALL_0:
            from typhon.objects.collections.maps import EMPTY_MAP
            # [1,2,3].asSet() -> [[1,2,3], "asSet"]
            rv = ConstList(self.objectSet.keys())
            return ConstList([rv, StrObject(u"asSet"), ConstList([]),
                              EMPTY_MAP])

        # contains/1: Determine whether an element is in this collection.
        if atom is CONTAINS_1:
            return wrapBool(self.contains(args[0]))

        # size/0: Get the number of elements in the collection.
        if atom is SIZE_0:
            return IntObject(self.size())

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_1:
            start = unwrapInt(args[0])
            try:
                return self.slice(start)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_2:
            start = unwrapInt(args[0])
            stop = unwrapInt(args[1])
            try:
                return self.slice(start, stop)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # snapshot/0: Create a new constant collection with a copy of the
        # current collection's contents.
        if atom is SNAPSHOT_0:
            return self.snapshot()

        if atom is ASSET_0:
            return self

        if atom is DIVERGE_0:
            _flexSet = getGlobal(u"_flexSet").getValue()
            return _flexSet.call(u"run", [self])

        if atom is AND_1:
            return self._and(args[0])

        # or/1: Unify the elements of this collection with another.
        if atom is OR_1:
            return self._or(args[0])

        # XXX Decide if we follow python-style '-' or E-style '&!' here.
        if atom is SUBTRACT_1:
            return self.subtract(args[0])

        if atom is ASLIST_0:
            return ConstList(self.objectSet.keys())

        if atom is BUTNOT_1:
            return self.subtract(args[0])

        if atom is WITH_1:
            key = args[0]
            d = self.objectSet.copy()
            d[key] = None
            return ConstSet(d)

        if atom is WITHOUT_1:
            key = args[0]
            d = self.objectSet.copy()
            # Ignore the case where the key wasn't in the map.
            if key in d:
                del d[key]
            return ConstSet(d)

        if atom is INCLUDE_1:
            key = args[0]
            self.include(key)
            return NullObject

        if atom is REMOVE_1:
            key = args[0]
            self.remove(key)
            return NullObject

        if atom is POP_0:
            return self.pop()

        raise Refused(self, atom, args)
Ejemplo n.º 25
0
    def _recv(self, atom, args):
        if atom is ADD_1:
            other = unwrapList(args[0])
            if len(other):
                return ConstList(self.strategy.fetch_all(self) + other)
            else:
                return self

        if atom is ASMAP_0:
            from typhon.objects.collections.maps import ConstMap
            return ConstMap(self.asMap())

        if atom is ASSET_0:
            from typhon.objects.collections.sets import ConstSet
            return ConstSet(self.asSet())

        if atom is DIVERGE_0:
            return FlexList(self.strategy.fetch_all(self)[:])

        if atom is GET_1:
            # Lookup by index.
            index = unwrapInt(args[0])
            if index < 0:
                raise userError(u"Index %d cannot be negative" % index)
            if index >= self.strategy.size(self):
                raise userError(u"Index %d is out of bounds" % index)
            return self.strategy.fetch(self, index)

        if atom is INDEXOF_1:
            return IntObject(self.indexOf(args[0]))

        if atom is LAST_0:
            size = self.strategy.size(self)
            if size:
                return self.strategy.fetch(self, size - 1)
            raise userError(u"Empty list has no last element")

        if atom is MULTIPLY_1:
            # multiply/1: Create a new list by repeating this list's contents.
            count = unwrapInt(args[0])
            if count < 0:
                raise userError(u"Can't multiply list %d times" % count)
            elif count == 0:
                return ConstList([])
            return ConstList(self.strategy.fetch_all(self) * count)

        if atom is OP__CMP_1:
            other = unwrapList(args[0])
            return IntObject(self.cmp(other))

        if atom is REVERSE_0:
            # This might seem slightly inefficient, and it might be, but I
            # want to make it very clear to RPython that we are not mutating
            # the list after we assign it to the new object.
            new = self.strategy.fetch_all(self)[:]
            new.reverse()
            return ConstList(new)

        if atom is SORT_0:
            return self.sort()

        if atom is STARTOF_1:
            return IntObject(self.startOf(unwrapList(args[0])))

        if atom is STARTOF_2:
            start = unwrapInt(args[1])
            if start < 0:
                raise userError(u"startOf/2: Negative start %d not permitted" %
                                start)
            return IntObject(self.startOf(unwrapList(args[0]), start))

        if atom is WITH_1:
            # with/1: Create a new list with an appended object.
            return ConstList(self.strategy.fetch_all(self) + args)

        if atom is WITH_2:
            # Replace by index.
            index = unwrapInt(args[0])
            return self.put(index, args[1])

        if atom is _UNCALL_0:
            from typhon.scopes.safe import theMakeList
            from typhon.objects.collections.maps import EMPTY_MAP
            return ConstList([theMakeList, StrObject(u"run"), self, EMPTY_MAP])

        raise Refused(self, atom, args)
Ejemplo n.º 26
0
    def _recv(self, atom, args):
        if atom is _UNCALL_0:
            from typhon.objects.collections.maps import EMPTY_MAP
            return ConstList([
                self.snapshot(),
                StrObject(u"diverge"),
                ConstList([]), EMPTY_MAP
            ])

        if atom is ADD_1:
            other = args[0]
            return ConstList(self.strategy.fetch_all(self) + unwrapList(other))

        if atom is ASMAP_0:
            from typhon.objects.collections.maps import ConstMap
            return ConstMap(self.asMap())

        if atom is ASSET_0:
            from typhon.objects.collections.sets import ConstSet
            return ConstSet(self.asSet())

        if atom is DIVERGE_0:
            return FlexList(self.strategy.fetch_all(self))

        if atom is EXTEND_1:
            from typhon.objects.refs import resolution
            l = resolution(args[0])
            # The early exits are essential here; without them, we might pass
            # an empty list to strategy.append(), which causes a crash. ~ C.
            if isinstance(l, ConstList):
                if l.size() == 0:
                    return NullObject
                data = l.strategy.fetch_all(l)
            elif isinstance(l, FlexList):
                if l.size() == 0:
                    return NullObject
                data = l.strategy.fetch_all(l)
            else:
                data = listFromIterable(l)[:]
            self.strategy.append(self, data)
            return NullObject

        if atom is GET_1:
            # Lookup by index.
            index = unwrapInt(args[0])
            if index >= self.strategy.size(self) or index < 0:
                raise userError(u"Index %d is out of bounds" % index)
            return self.strategy.fetch(self, index)

        if atom is INDEXOF_1:
            return IntObject(self.indexOf(args[0]))

        if atom is INSERT_2:
            index = unwrapInt(args[0])
            value = args[1]
            if index < 0:
                raise userError(u"Index %d is out of bounds" % index)
            self.strategy.insert(self, index, [value])
            return NullObject

        if atom is LAST_0:
            size = self.strategy.size(self)
            if size:
                return self.strategy.fetch(self, size - 1)
            raise userError(u"Empty list has no last element")

        if atom is MULTIPLY_1:
            # multiply/1: Create a new list by repeating this list's contents.
            index = unwrapInt(args[0])
            return ConstList(self.strategy.fetch_all(self) * index)

        if atom is POP_0:
            try:
                return self.strategy.pop(self, self.strategy.size(self) - 1)
            except IndexError:
                raise userError(u"pop/0: Pop from empty list")

        if atom is PUSH_1:
            self.strategy.append(self, args)
            return NullObject

        if atom is PUT_2:
            # Replace by index.
            index = unwrapInt(args[0])
            return self.put(index, args[1])

        if atom is REVERSE_0:
            new = self.strategy.fetch_all(self)[:]
            new.reverse()
            return ConstList(new)

        if atom is REVERSEINPLACE_0:
            new = self.strategy.fetch_all(self)[:]
            new.reverse()
            self.strategy.store_all(self, new)
            return NullObject

        if atom is WITH_1:
            # with/1: Create a new list with an appended object.
            return ConstList(self.strategy.fetch_all(self) + args)

        if atom is WITH_2:
            # Make a new ConstList.
            return self.snapshot().put(unwrapInt(args[0]), args[1])

        raise Refused(self, atom, args)
Ejemplo n.º 27
0
    def _recv(self, atom, args):
        if atom is _UNCALL_0:
            from typhon.objects.collections.maps import EMPTY_MAP
            return ConstList([self.snapshot(), StrObject(u"diverge"),
                              ConstList([]), EMPTY_MAP])

        if atom is ADD_1:
            other = args[0]
            return ConstList(self.strategy.fetch_all(self) +
                             unwrapList(other))

        if atom is ASMAP_0:
            from typhon.objects.collections.maps import ConstMap
            return ConstMap(self.asMap())

        if atom is ASSET_0:
            from typhon.objects.collections.sets import ConstSet
            return ConstSet(self.asSet())

        if atom is DIVERGE_0:
            return FlexList(self.strategy.fetch_all(self))

        if atom is EXTEND_1:
            from typhon.objects.refs import resolution
            l = resolution(args[0])
            # The early exits are essential here; without them, we might pass
            # an empty list to strategy.append(), which causes a crash. ~ C.
            if isinstance(l, ConstList):
                if l.size() == 0:
                    return NullObject
                data = l.strategy.fetch_all(l)
            elif isinstance(l, FlexList):
                if l.size() == 0:
                    return NullObject
                data = l.strategy.fetch_all(l)
            else:
                data = listFromIterable(l)[:]
            self.strategy.append(self, data)
            return NullObject

        if atom is GET_1:
            # Lookup by index.
            index = unwrapInt(args[0])
            if index >= self.strategy.size(self) or index < 0:
                raise userError(u"Index %d is out of bounds" % index)
            return self.strategy.fetch(self, index)

        if atom is INDEXOF_1:
            return IntObject(self.indexOf(args[0]))

        if atom is INSERT_2:
            index = unwrapInt(args[0])
            value = args[1]
            if index < 0:
                raise userError(u"Index %d is out of bounds" % index)
            self.strategy.insert(self, index, [value])
            return NullObject

        if atom is LAST_0:
            size = self.strategy.size(self)
            if size:
                return self.strategy.fetch(self, size - 1)
            raise userError(u"Empty list has no last element")

        if atom is MULTIPLY_1:
            # multiply/1: Create a new list by repeating this list's contents.
            index = unwrapInt(args[0])
            return ConstList(self.strategy.fetch_all(self) * index)

        if atom is POP_0:
            try:
                return self.strategy.pop(self, self.strategy.size(self) - 1)
            except IndexError:
                raise userError(u"pop/0: Pop from empty list")

        if atom is PUSH_1:
            self.strategy.append(self, args)
            return NullObject

        if atom is PUT_2:
            # Replace by index.
            index = unwrapInt(args[0])
            return self.put(index, args[1])

        if atom is REVERSE_0:
            new = self.strategy.fetch_all(self)[:]
            new.reverse()
            return ConstList(new)

        if atom is REVERSEINPLACE_0:
            new = self.strategy.fetch_all(self)[:]
            new.reverse()
            self.strategy.store_all(self, new)
            return NullObject

        if atom is WITH_1:
            # with/1: Create a new list with an appended object.
            return ConstList(self.strategy.fetch_all(self) + args)

        if atom is WITH_2:
            # Make a new ConstList.
            return self.snapshot().put(unwrapInt(args[0]), args[1])

        raise Refused(self, atom, args)
Ejemplo n.º 28
0
    def recv(self, atom, args):
        from typhon.objects.collections.lists import ConstList

        # _makeIterator/0: Create an iterator for this collection's contents.
        if atom is _MAKEITERATOR_0:
            return self._makeIterator()

        if atom is _PRINTON_1:
            printer = args[0]
            self.printOn(printer)
            return NullObject

        if atom is _UNCALL_0:
            from typhon.objects.collections.maps import EMPTY_MAP
            # [1,2,3].asSet() -> [[1,2,3], "asSet"]
            rv = ConstList(self.objectSet.keys())
            return ConstList(
                [rv, StrObject(u"asSet"),
                 ConstList([]), EMPTY_MAP])

        # contains/1: Determine whether an element is in this collection.
        if atom is CONTAINS_1:
            return wrapBool(self.contains(args[0]))

        # size/0: Get the number of elements in the collection.
        if atom is SIZE_0:
            return IntObject(self.size())

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_1:
            start = unwrapInt(args[0])
            try:
                return self.slice(start)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # slice/1 and slice/2: Select a subrange of this collection.
        if atom is SLICE_2:
            start = unwrapInt(args[0])
            stop = unwrapInt(args[1])
            try:
                return self.slice(start, stop)
            except IndexError:
                raise userError(u"slice/1: Index out of bounds")

        # snapshot/0: Create a new constant collection with a copy of the
        # current collection's contents.
        if atom is SNAPSHOT_0:
            return self.snapshot()

        if atom is ASSET_0:
            return self

        if atom is DIVERGE_0:
            _flexSet = getGlobal(u"_flexSet").getValue()
            return _flexSet.call(u"run", [self])

        if atom is AND_1:
            return self._and(args[0])

        # or/1: Unify the elements of this collection with another.
        if atom is OR_1:
            return self._or(args[0])

        # XXX Decide if we follow python-style '-' or E-style '&!' here.
        if atom is SUBTRACT_1:
            return self.subtract(args[0])

        if atom is ASLIST_0:
            return ConstList(self.objectSet.keys())

        if atom is BUTNOT_1:
            return self.subtract(args[0])

        if atom is WITH_1:
            key = args[0]
            d = self.objectSet.copy()
            d[key] = None
            return ConstSet(d)

        if atom is WITHOUT_1:
            key = args[0]
            d = self.objectSet.copy()
            # Ignore the case where the key wasn't in the map.
            if key in d:
                del d[key]
            return ConstSet(d)

        if atom is INCLUDE_1:
            key = args[0]
            self.include(key)
            return NullObject

        if atom is REMOVE_1:
            key = args[0]
            self.remove(key)
            return NullObject

        if atom is POP_0:
            return self.pop()

        raise Refused(self, atom, args)
Ejemplo n.º 29
0
 def fromInts(self, data):
     return "".join([chr(unwrapInt(i)) for i in data])
Ejemplo n.º 30
0
 def testUnwrapIntPromise(self):
     with scopedVat(testingVat()):
         p = makeNear(IntObject(42))
         self.assertEqual(unwrapInt(p), 42)
Ejemplo n.º 31
0
def makeTCP4ServerEndpoint(port):
    """
    Make a TCPv4 server endpoint.
    """

    return TCP4ServerEndpoint(unwrapInt(port))
Ejemplo n.º 32
0
 def fromInts(self, data):
     return "".join([ensureByteInt(unwrapInt(i)) for i in data])