Esempio n. 1
0
    def inner(f):
        name = f.__name__.decode("utf-8")
        doc = f.__doc__.decode("utf-8") if f.__doc__ else None

        if singleAtom is None:
            arity = len(inspect.getargspec(f).args)
            theAtom = getAtom(name, arity)
        else:
            arity = singleAtom.arity
            theAtom = singleAtom
        unrolledArity = unrolling_iterable(range(arity))

        class runnableObject(Object):
            def toString(self):
                return u"<%s>" % name

            def auditorStamps(self):
                return _stamps

            def docString(self):
                return doc

            def respondingAtoms(self):
                return {theAtom: doc}

            def recv(self, atom, listArgs):
                if atom is theAtom:
                    args = ()
                    for i in unrolledArity:
                        args += (listArgs[i], )
                    return f(*args)
                else:
                    raise Refused(self, atom, listArgs)

        return runnableObject
Esempio n. 2
0
 def call(self, verb, arguments, namedArgs=None):
     """
     Pass a message immediately to this object.
     """
     from typhon.objects.collections.maps import EMPTY_MAP
     if namedArgs is None:
         namedArgs = EMPTY_MAP
     arity = len(arguments)
     atom = getAtom(verb, arity)
     return self.callAtom(atom, arguments, namedArgs)
Esempio n. 3
0
 def visitMethodExpr(self, doc, verb, patts, namedPatts, guard, body,
                     localSize, span):
     atom = getAtom(verb, len(patts))
     patts = [self.visitPatt(patt) for patt in patts]
     namedPatts = [self.visitNamedPatt(namedPatt) for namedPatt in
             namedPatts]
     guard = self.visitExpr(guard)
     body = self.visitExpr(body)
     return self.dest.MethodExpr(doc, atom, patts, namedPatts, guard, body,
                                 localSize, span)
Esempio n. 4
0
 def call(self, verb, arguments, namedArgs=None):
     """
     Pass a message immediately to this object.
     """
     from typhon.objects.collections.maps import EMPTY_MAP
     if namedArgs is None:
         namedArgs = EMPTY_MAP
     arity = len(arguments)
     atom = getAtom(verb, arity)
     return self.callAtom(atom, arguments, namedArgs)
Esempio n. 5
0
    def call(self, verb, arguments, namedArgs=None, span=None):
        """
        Pass a message immediately to this object.

        This is the correct method to call if you have a verb.
        """

        arity = len(arguments)
        atom = getAtom(verb, arity)
        return self.callAtom(atom, arguments, namedArgs, span)
Esempio n. 6
0
    def call(self, verb, arguments, namedArgs=None, span=None):
        """
        Pass a message immediately to this object.

        This is the correct method to call if you have a verb.
        """

        arity = len(arguments)
        atom = getAtom(verb, arity)
        return self.callAtom(atom, arguments, namedArgs, span)
Esempio n. 7
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
Esempio n. 8
0
File: safe.py Progetto: dckc/typhon
    def sendOnly(self, target, verb, args, namedArgs):
        """
        Send a message to an object.

        The message will be delivered on some subsequent turn.
        """

        namedArgs = resolution(namedArgs)
        if not isinstance(namedArgs, ConstMap):
            raise WrongType(u"namedArgs must be a ConstMap")
        # Signed, sealed, delivered, I'm yours.
        sendAtom = getAtom(verb, len(args))
        vat = currentVat.get()
        vat.sendOnly(target, sendAtom, args, namedArgs)
Esempio n. 9
0
    def sendOnly(self, target, verb, args, namedArgs):
        """
        Send a message to an object.

        The message will be delivered on some subsequent turn.
        """

        namedArgs = resolution(namedArgs)
        if not isinstance(namedArgs, ConstMap):
            raise WrongType(u"namedArgs must be a ConstMap")
        # Signed, sealed, delivered, I'm yours.
        sendAtom = getAtom(verb, len(args))
        vat = currentVat.get()
        vat.sendOnly(target, sendAtom, args, namedArgs)
Esempio n. 10
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
Esempio n. 11
0
File: safe.py Progetto: dckc/typhon
    def send(self, target, verb, args, namedArgs):
        """
        Send a message to an object, returning a promise for the message
        delivery.

        The promise will be fulfilled after successful delivery, or smashed
        upon error.

        The message will be delivered on some subsequent turn.
        """

        namedArgs = resolution(namedArgs)
        if not isinstance(namedArgs, ConstMap):
            raise WrongType(u"namedArgs must be a ConstMap")
        # Signed, sealed, delivered, I'm yours.
        sendAtom = getAtom(verb, len(args))
        vat = currentVat.get()
        return vat.send(target, sendAtom, args, namedArgs)
Esempio n. 12
0
    def send(self, target, verb, args, namedArgs):
        """
        Send a message to an object, returning a promise for the message
        delivery.

        The promise will be fulfilled after successful delivery, or smashed
        upon error.

        The message will be delivered on some subsequent turn.
        """

        namedArgs = resolution(namedArgs)
        if not isinstance(namedArgs, ConstMap):
            raise WrongType(u"namedArgs must be a ConstMap")
        # Signed, sealed, delivered, I'm yours.
        sendAtom = getAtom(verb, len(args))
        vat = currentVat.get()
        return vat.send(target, sendAtom, args, namedArgs)
Esempio n. 13
0
    def inner(f):
        name = f.__name__.decode("utf-8")
        doc = f.__doc__.decode("utf-8") if f.__doc__ else None

        if singleAtom is None:
            arity = len(inspect.getargspec(f).args)
            theAtom = getAtom(name, arity)
        else:
            arity = singleAtom.arity
            theAtom = singleAtom
        unrolledArity = unrolling_iterable(range(arity))

        class runnableObject(Object):

            def toString(self):
                return u"<%s>" % name

            def auditorStamps(self):
                from typhon.objects.collections.helpers import asSet
                return asSet(_stamps)

            def isSettled(self, sofar=None):
                return True

            def docString(self):
                return doc

            def respondingAtoms(self):
                return {theAtom: doc}

            def recv(self, atom, listArgs):
                if atom is theAtom:
                    args = ()
                    for i in unrolledArity:
                        args += (listArgs[i],)
                    return f(*args)
                else:
                    raise Refused(self, atom, listArgs)

        return runnableObject
Esempio n. 14
0
 def testIdempotency(self):
     first = getAtom(u"test", 5)
     second = getAtom(u"test", 5)
     self.assertTrue(first is second)
Esempio n. 15
0
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused
from typhon.objects.constants import NullObject
from typhon.objects.collections.sets import ConstSet, monteSet
from typhon.objects.data import IntObject, StrObject
from typhon.objects.root import Object


GETARITY_0 = getAtom(u"getArity", 0)
GETDOCSTRING_0 = getAtom(u"getDocstring", 0)
GETMETHODS_0 = getAtom(u"getMethods", 0)
GETVERB_0 = getAtom(u"getVerb", 0)


@autohelp
class ComputedMethod(Object):
    """
    A method description.
    """

    _immutable_ = True

    def __init__(self, arity, docstring, verb):
        self.arity = arity
        self.docstring = docstring
        self.verb = verb

    def toString(self):
        return u"<computed message %s/%d>" % (self.verb, self.arity)
Esempio n. 16
0
from typhon.env import finalize
from typhon.errors import LoadFailed, Refused, userError
from typhon.importing import (codeFromAst, evaluateRaise, obtainModule,
                              obtainModuleFromSource)
from typhon.load.mast import loadMASTBytes
from typhon.nodes import kernelAstStamp
from typhon.objects.auditors import deepFrozenStamp, transparentStamp
from typhon.objects.collections.lists import ConstList
from typhon.objects.collections.maps import ConstMap, monteMap, unwrapMap
from typhon.objects.collections.sets import ConstSet
from typhon.objects.data import StrObject, unwrapBytes, wrapBool, unwrapStr
from typhon.objects.guards import (BoolGuard, BytesGuard, CharGuard,
                                   DoubleGuard, IntGuard, StrGuard, VoidGuard)
from typhon.objects.root import Object, audited, runnable

EVALTOPAIR_2 = getAtom(u"evalToPair", 2)
FROMAST_3 = getAtom(u"fromAST", 3)
RUN_1 = getAtom(u"run", 1)
RUN_2 = getAtom(u"run", 2)


@runnable(RUN_1, [deepFrozenStamp])
def isList(specimen):
    return wrapBool(isinstance(specimen, ConstList))


@runnable(RUN_1, [deepFrozenStamp])
def isMap(specimen):
    return wrapBool(isinstance(specimen, ConstMap))

Esempio n. 17
0
from rpython.rlib.rstring import ParseStringError
from rpython.rlib.rstruct.ieee import unpack_float

from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.collections.lists import listFromIterable
from typhon.objects.collections.maps import ConstMap
from typhon.objects.data import (bytesToString, unwrapInt,
        unwrapChar)
from typhon.objects.ejectors import throwStr
from typhon.objects.root import Object, audited, runnable
from typhon.profile import profileTyphon


FROMPAIRS_1 = getAtom(u"fromPairs", 1)


@autohelp
@audited.DF
class MakeBytes(Object):
    """
    The maker of `Bytes`.
    """

    def toString(self):
        return u"<makeBytes>"

    @method("Bytes", "Str")
    def fromStr(self, s):
        return "".join([chr(ord(c)) for c in s])
Esempio n. 18
0
from typhon.objects.data import StrObject, unwrapStr
from typhon.errors import Refused
from typhon.objects.exceptions import unsealException
from typhon.objects.files import makeFileResource
from typhon.objects.networking.dns import getAddrInfo
from typhon.objects.networking.endpoints import (makeTCP4ClientEndpoint,
                                                 makeTCP4ServerEndpoint)
from typhon.objects.networking.stdio import makeStdErr, makeStdIn, makeStdOut
from typhon.objects.processes import CurrentProcess, makeProcess
from typhon.objects.root import Object, audited
from typhon.objects.runtime import CurrentRuntime
from typhon.objects.timeit import bench
from typhon.objects.timers import Timer
from typhon.vats import CurrentVatProxy

RUN_1 = getAtom("run", 1)


@audited.DF
class FindTyphonFile(Object):
    def __init__(self, paths):
        self.paths = paths

    def recv(self, atom, args):
        if atom is RUN_1:
            pname = unwrapStr(args[0])
            for extension in [".ty", ".mast"]:
                path = pname.encode("utf-8") + extension
                for base in self.paths:
                    fullpath = os.path.join(base, path)
                    if os.path.exists(fullpath):
Esempio n. 19
0
from typhon.errors import Ejecting, Refused, UserException, userError
from typhon.log import log
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.constants import NullObject, unwrapBool, wrapBool
from typhon.objects.collections.lists import ConstList
from typhon.objects.data import StrObject, unwrapStr
from typhon.objects.ejectors import Ejector
from typhon.objects.guards import anyGuard
from typhon.objects.printers import Printer
from typhon.objects.root import Object
from typhon.objects.slots import finalBinding
from typhon.smallcaps.machine import SmallCaps

# XXX AuditionStamp, Audition guard

ASK_1 = getAtom(u"ask", 1)
GETGUARD_1 = getAtom(u"getGuard", 1)
GETOBJECTEXPR_0 = getAtom(u"getObjectExpr", 0)
GETFQN_0 = getAtom(u"getFQN", 0)


pemci = u".".join([
    u"lo lebna cu rivbi",
    u"lo nu fi ri facki",
    u"fa le vi larmuzga",
    u"fe le zi ca du'u",
    u"le lebna pu jbera",
    u"lo catlu pe ro da",
])

def boolStr(b):
Esempio n. 20
0
# Copyright (C) 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from typhon.atoms import getAtom
from typhon.objects.data import StrObject
from typhon.objects.root import runnable

GETFQNPREFIX_0 = getAtom(u"getFQNPrefix", 0)

@runnable(GETFQNPREFIX_0)
def MetaContext():
    """
    Obtain the fully qualified name prefix.
    """

    return StrObject(u"unknown$monte$source$")
Esempio n. 21
0
from rpython.rlib.objectmodel import compute_identity_hash

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, userError
from typhon.objects.auditors import selfless, transparentStamp
from typhon.objects.collections.lists import ConstList, unwrapList
from typhon.objects.collections.maps import ConstMap
from typhon.objects.constants import BoolObject, NullObject, wrapBool
from typhon.objects.data import BigInt, BytesObject, CharObject, DoubleObject, IntObject, StrObject
from typhon.objects.refs import resolution, isResolved
from typhon.objects.root import Object, audited


ISSETTLED_1 = getAtom(u"isSettled", 1)
MAKETRAVERSALKEY_1 = getAtom(u"makeTraversalKey", 1)
OPTSAME_2 = getAtom(u"optSame", 2)
SAMEEVER_2 = getAtom(u"sameEver", 2)
SAMEYET_2 = getAtom(u"sameYet", 2)


class Equality(object):
    def __init__(self, label):
        self._label = label

    def __repr__(self):
        return self._label


EQUAL = Equality("EQUAL")
Esempio n. 22
0
from rpython.rlib.rarithmetic import intmask

from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.objects.root import Object
from typhon.objects.collections.maps import EMPTY_MAP
from typhon.objects.data import IntObject

from typhon.ruv import (alloc_signal, free, SignalStart, SignalStop,
                        stashSignal, unstashSignal, unstashingSignal)

RUN_1 = getAtom(u"run", 1)


def _signalCB(signal, signum):
    with unstashingSignal(signal) as (vat, handle):
        vat.sendOnly(handle._target, RUN_1, [IntObject(intmask(signum))],
                     EMPTY_MAP)


@autohelp
class SignalHandle(Object):
    def __init__(self, signum, target, vat):
        self._signum = signum
        self._target = target
        self._vat = vat
        self._signal = alloc_signal(vat.uv_loop)
        SignalStart(self._signal, _signalCB, self._signum)
        stashSignal(self._signal, (vat, self))

    @method("Void")
Esempio n. 23
0
def alterMethods(cls):
    """
    Alter Monte methods on behalf of AutoHelp.

    Return the signatures of the altered methods.

    NOT_RPYTHON
    """

    atoms = []
    imports = set()
    execNames = {"Refused": Refused}

    def nextName(nameIndex=[0]):
        name = "_%d" % nameIndex[0]
        nameIndex[0] += 1
        return name

    def namedLiteral(lit):
        name = nextName()
        execNames[name] = lit
        return name

    dispatchClauses = []
    methods = harvestMethods(cls)
    for attr, (f, verb, args, kwargs, rv) in methods.iteritems():
        assignments = []
        if isStarArgs(args):
            atomTest = "atom.verb == %r" % verb
            call = "self.%s(args)" % attr
        else:
            atom = getAtom(verb, len(args))
            atomName = namedLiteral(atom)
            atoms.append(atom)
            atomTest = "atom is %s" % atomName
            argNames = []
            for i, arg in enumerate(args):
                argName = nextName()
                argNames.append(argName)
                assignments.append("%s = args[%d]" % (argName, i))
                if arg != "Any":
                    unwrapperModule = wrappers[arg]
                    pred = "is" + arg
                    imports.add("from %s import %s" % (unwrapperModule, pred))
                    atomTest += " and %s(args[%d])" % (pred, i)
                    unwrapper = "unwrap" + arg
                    imports.add("from %s import %s" % (unwrapperModule,
                        unwrapper))
                    assignments.append("%s = %s(%s)" % (argName, unwrapper,
                        argName))
                else:
                    imports.add("from typhon.objects.refs import resolution")
                    assignments.append("%s = resolution(%s)" % (argName,
                                                                argName))
            for k, v in kwargs.iteritems():
                # Look up the default value. We're going to pop this in and
                # use None as a sentinel value in .extractStringKey(). ~ C.
                default = getKwargDefault(f, k)
                defaultName = namedLiteral(default)
                kwargName = nextName()
                argNames.append("%s=%s" % (k, kwargName))
                assignments.append("%s = namedArgs.extractStringKey(%r, None)"
                        % (kwargName, k.decode("utf-8")))
                # If the kwarg is None, then it wasn't passed in; use the
                # default. Otherwise, invoke the unwrapper if one exists.
                assignments.append("if %s is None: %s = %s"
                        % (kwargName, kwargName, defaultName))
                if v != "Any":
                    unwrapperModule = wrappers[v]
                    unwrapper = "unwrap" + v
                    imports.add("from %s import %s"
                            % (unwrapperModule, unwrapper))
                    assignments.append("else: %s = %s(%s)"
                            % (kwargName, unwrapper, kwargName))
            call = "self.%s(%s)" % (attr, ",".join(argNames))
        retvals = []
        if rv == "Any":
            # No wrapping.
            retvals.append("return rv")
        elif rv == "Void":
            # Enforced correctness. Disobedience will not be tolerated.
            retvals.append("assert rv is None, 'habanero'")
            retvals.append("from typhon.objects.constants import NullObject")
            retvals.append("return NullObject")
        else:
            wrapperModule = wrappers[rv]
            wrapper = "wrap" + rv
            imports.add("from %s import %s" % (wrapperModule, wrapper))
            retvals.append("return %s(rv)" % wrapper)
        # We need to use newlines for the assignments since kwarg assignments
        # are conditional.
        dispatchClauses.append("""
 if %s:
  %s
  rv = %s
  %s
""" % (atomTest, "\n  ".join(assignments), call, ";".join(retvals)))
        setattr(cls, attr, f)
    # Temporary. Soon, all classes shall receive AutoHelp, and no class will
    # have a handwritten recv().
    if dispatchClauses:
        exec py.code.Source("""
def recvNamed(self, atom, args, namedArgs):
 %s
 %s
 rv = self.mirandaMethods(atom, args, namedArgs)
 if rv is None:
  raise Refused(self, atom, args)
 else:
  return rv
""" % (";".join(imports), "\n".join(dispatchClauses))).compile() in execNames
        recvNamed = execNames["recvNamed"]
        # This is the place for fixing the "too many constants" JIT
        # translation error. If there's too many dispatch clauses in
        # .recvNamed(), then the JIT transformation fails because too many
        # constant values are being mixed in. This number is determined
        # empirically; uncomment the next line to take measurements:
        # print "Made %d dispatch clauses for %r" % (len(dispatchClauses), cls)
        # Here's a worksheet. Please keep it up-to-date when altering this
        # section of code. ~ C.
        # * At last run, the longest working list of clauses had length 40
        # * And the shortest list which broke translation had length 46
        # * Assuming that each clause has a constant integral number of
        #   constants, the number of constants per clause is 6
        # * The maximum number of allowed constants is 255
        # * Therefore, the longest working list can have maximum length 42
        if len(dispatchClauses) >= 42:
            # Too many constants; forbid the JIT from recursing into us.
            recvNamed = dont_look_inside(recvNamed)
        cls.recvNamed = recvNamed

    return atoms
Esempio n. 24
0
from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.enum import makeEnum
from typhon.errors import Ejecting, UserException, userError
from typhon.log import log
from typhon.objects.auditors import deepFrozenStamp, selfless
from typhon.objects.constants import NullObject
from typhon.objects.ejectors import Ejector
from typhon.objects.root import Object, audited
from typhon.vats import currentVat


BROKEN, EVENTUAL, NEAR = makeEnum(u"RefState",
                                  u"broken eventual near".split())

RESOLVE_1 = getAtom(u"resolve", 1)
RESOLVE_2 = getAtom(u"resolve", 2)
RUN_1 = getAtom(u"run", 1)
_WHENBROKEN_1 = getAtom(u"_whenBroken", 1)
_WHENMORERESOLVED_1 = getAtom(u"_whenMoreResolved", 1)


def makePromise(guard=None):
    vat = currentVat.get()
    buf = MessageBuffer(vat)
    sref = SwitchableRef(BufferingRef(buf))
    return sref, LocalResolver(sref, buf, vat, guard)


def _toRef(o, vat):
    if isinstance(o, Promise):
Esempio n. 25
0
from rpython.rlib.rarithmetic import intmask
from rpython.rlib.objectmodel import we_are_translated
from rpython.rtyper.lltypesystem.rffi import charpsize2str

from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, userError
from typhon.objects.constants import NullObject
from typhon.objects.data import BytesObject, StrObject, unwrapBytes
from typhon.objects.root import Object
from typhon.vats import scopedVat


ABORTFLOW_0 = getAtom(u"abortFlow", 0)
FLOWABORTED_1 = getAtom(u"flowAborted", 1)
FLOWINGFROM_1 = getAtom(u"flowingFrom", 1)
FLOWSTOPPED_1 = getAtom(u"flowStopped", 1)
FLOWTO_1 = getAtom(u"flowTo", 1)
FLUSH_0 = getAtom(u"flush", 0)
PAUSEFLOW_0 = getAtom(u"pauseFlow", 0)
RECEIVE_1 = getAtom(u"receive", 1)
RUN_2 = getAtom(u"run", 2)
STOPFLOW_0 = getAtom(u"stopFlow", 0)
UNPAUSE_0 = getAtom(u"unpause", 0)


@autohelp
class StreamUnpauser(Object):
    """
Esempio n. 26
0
 def visitCallExpr(self, obj, verb, args, namedArgs, span):
     obj = self.visitExpr(obj)
     atom = getAtom(verb, len(args))
     args = [self.visitExpr(arg) for arg in args]
     namedArgs = [self.visitNamedArg(namedArg) for namedArg in namedArgs]
     return self.dest.CallExpr(obj, atom, args, namedArgs, span)
Esempio n. 27
0
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.rarithmetic import intmask

from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, userError
from typhon.objects.collections.lists import ConstList, unwrapList
from typhon.objects.constants import NullObject
from typhon.objects.data import StrObject, unwrapBytes, unwrapInt
from typhon.objects.networking.streams import StreamDrain, StreamFount
from typhon.objects.refs import LocalResolver, makePromise
from typhon.objects.root import Object, runnable
from typhon.vats import currentVat, scopedVat

CONNECT_0 = getAtom(u"connect", 0)
LISTEN_1 = getAtom(u"listen", 1)
RUN_1 = getAtom(u"run", 1)
RUN_2 = getAtom(u"run", 2)
SHUTDOWN_0 = getAtom(u"shutdown", 0)


def connectCB(connect, status):
    status = intmask(status)
    stream = connect.c_handle

    try:
        vat, resolvers = ruv.unstashStream(stream)
        fountResolver, drainResolver = unwrapList(resolvers)
        assert isinstance(fountResolver, LocalResolver)
        assert isinstance(drainResolver, LocalResolver)
Esempio n. 28
0
from rpython.rlib.jit import JitDriver, promote

from typhon.atoms import getAtom
from typhon.errors import Ejecting
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.collections.lists import unwrapList
from typhon.objects.collections.maps import EMPTY_MAP
from typhon.objects.constants import NullObject
from typhon.objects.ejectors import Ejector
from typhon.objects.root import runnable
from typhon.objects.user import BusyObject, ScriptObject
from typhon.smallcaps.machine import SmallCaps


RUN_2 = getAtom(u"run", 2)
RUN_3 = getAtom(u"run", 3)


def getLocation(code):
    return code.profileName


loopDriver = JitDriver(greens=["code"],
                       reds=["consumer", "ejector", "iterator"],
                       get_printable_location=getLocation)


def slowLoop(iterable, consumer):
    iterator = iterable.call(u"_makeIterator", [])
Esempio n. 29
0
from typhon.atoms import getAtom
from typhon.errors import userError
from typhon.vats import currentVat
from typhon.objects.collections.lists import ConstList
from typhon.objects.collections.maps import EMPTY_MAP
from typhon.objects.data import NullObject, StrObject, unwrapBool
from typhon.objects.equality import (EQUAL, TraversalKey, optSame, isSameEver,
                                     isSettled)
from typhon.objects.guards import anyGuard
from typhon.objects.refs import (EVENTUAL, NEAR, Promise, UnconnectedRef,
                                 isResolved, resolution)
from typhon.objects.root import audited
from typhon.objects.slots import FinalSlot

HANDLESEND_3 = getAtom(u"handleSend", 3)
HANDLESENDONLY_3 = getAtom(u"handleSendOnly", 3)
RUN_3 = getAtom(u"run", 3)


def send(ref, atom, args, namedArgs):
    if isinstance(ref, Promise):
        return ref.sendAll(atom, args, namedArgs)
    else:
        vat = currentVat.get()
        return vat.send(ref, atom, args, namedArgs)


def sendOnly(ref, atom, args, namedArgs):
    if isinstance(ref, Promise):
        ref.sendAllOnly(atom, args, namedArgs)
    else:
Esempio n. 30
0
# under the License.

from rpython.rlib.jit import JitDriver

from typhon.atoms import getAtom
from typhon.errors import Ejecting
from typhon.nano.interp import InterpObject
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.collections.lists import unwrapList
from typhon.objects.collections.maps import EMPTY_MAP
from typhon.objects.constants import NullObject
from typhon.objects.ejectors import Ejector
from typhon.objects.root import runnable


RUN_2 = getAtom(u"run", 2)


def getLocation(method, displayName):
    return displayName


loopDriver = JitDriver(greens=["method", "displayName"],
                       reds=["consumer", "ejector", "iterator"],
                       get_printable_location=getLocation)


def slowLoop(iterable, consumer):
    iterator = iterable.call(u"_makeIterator", [])

    with Ejector() as ej:
Esempio n. 31
0
def alterMethods(cls):
    """
    Alter Monte methods on behalf of AutoHelp.

    Return the signatures of the altered methods.

    NOT_RPYTHON
    """

    atoms = {}
    imports = set()
    execNames = {"Refused": Refused}

    def nextName(nameIndex=[0]):
        name = "_%d" % nameIndex[0]
        nameIndex[0] += 1
        return name

    def namedLiteral(lit):
        name = nextName()
        execNames[name] = lit
        return name

    dispatchClauses = []
    methods = harvestMethods(cls)
    for attr, (f, verb, args, kwargs, rv) in methods.iteritems():
        assignments = []
        if isStarArgs(args):
            atomTest = "atom.verb == %r" % verb
            call = "self.%s(args)" % attr
        else:
            atom = getAtom(verb, len(args))
            atomName = namedLiteral(atom)
            ds = f.__doc__
            if ds is not None:
                ds = ds.decode("utf-8")
            atoms[atom] = ds
            atomTest = "atom is %s" % atomName
            argNames = []
            for i, arg in enumerate(args):
                argName = nextName()
                argNames.append(argName)
                assignments.append("%s = args[%d]" % (argName, i))
                if arg != "Any":
                    unwrapperModule = wrappers[arg]
                    pred = "is" + arg
                    imports.add("from %s import %s" % (unwrapperModule, pred))
                    atomTest += " and %s(args[%d])" % (pred, i)
                    unwrapper = "unwrap" + arg
                    imports.add("from %s import %s" % (unwrapperModule,
                        unwrapper))
                    assignments.append("%s = %s(%s)" % (argName, unwrapper,
                        argName))
                else:
                    imports.add("from typhon.objects.refs import resolution")
                    assignments.append("%s = resolution(%s)" % (argName,
                                                                argName))
            for k, v in kwargs.iteritems():
                # Look up the default value. We're going to pop this in and
                # use None as a sentinel value in .extractStringKey(). ~ C.
                default = getKwargDefault(f, k)
                defaultName = namedLiteral(default)
                kwargName = nextName()
                argNames.append("%s=%s" % (k, kwargName))
                assignments.append("%s = namedArgs.extractStringKey(%r, None)"
                        % (kwargName, k.decode("utf-8")))
                # If the kwarg is None, then it wasn't passed in; use the
                # default. Otherwise, invoke the unwrapper if one exists.
                assignments.append("if %s is None: %s = %s"
                        % (kwargName, kwargName, defaultName))
                if v != "Any":
                    unwrapperModule = wrappers[v]
                    unwrapper = "unwrap" + v
                    imports.add("from %s import %s"
                            % (unwrapperModule, unwrapper))
                    assignments.append("else: %s = %s(%s)"
                            % (kwargName, unwrapper, kwargName))
            call = "self.%s(%s)" % (attr, ",".join(argNames))
        retvals = []
        if rv == "Any":
            # No wrapping.
            retvals.append("return rv")
        elif rv == "Void":
            # Enforced correctness. Disobedience will not be tolerated.
            retvals.append("assert rv is None, 'habanero'")
            retvals.append("from typhon.objects.constants import NullObject")
            retvals.append("return NullObject")
        else:
            wrapperModule = wrappers[rv]
            wrapper = "wrap" + rv
            imports.add("from %s import %s" % (wrapperModule, wrapper))
            retvals.append("return %s(rv)" % wrapper)
        # We need to use newlines for the assignments since kwarg assignments
        # are conditional.
        dispatchClauses.append("""
 if %s:
  %s
  rv = %s
  %s
""" % (atomTest, "\n  ".join(assignments), call, ";".join(retvals)))
        setattr(cls, attr, f)
    # Temporary. Soon, all classes shall receive AutoHelp, and no class will
    # have a handwritten recv().
    if dispatchClauses:
        exec py.code.Source("""
def recvNamed(self, atom, args, namedArgs):
 %s
 %s
 rv = self.mirandaMethods(atom, args, namedArgs)
 if rv is None:
  raise Refused(self, atom, args)
 else:
  return rv
""" % (";".join(imports), "\n".join(dispatchClauses))).compile() in execNames
        recvNamed = execNames["recvNamed"]
        # This is the place for fixing the "too many constants" JIT
        # translation error. If there's too many dispatch clauses in
        # .recvNamed(), then the JIT transformation fails because too many
        # constant values are being mixed in. This number is determined
        # empirically; uncomment the next line to take measurements:
        # print "Made %d dispatch clauses for %r" % (len(dispatchClauses), cls)
        # Here's a worksheet. Please keep it up-to-date when altering this
        # section of code. ~ C.
        # * At last run, the longest working list of clauses had length 40
        # * And the shortest list which broke translation had length 46
        # * Assuming that each clause has a constant integral number of
        #   constants, the number of constants per clause is 6
        # * The maximum number of allowed constants is 255
        # * Therefore, the longest working list can have maximum length 42
        if len(dispatchClauses) >= 42:
            # Too many constants; forbid the JIT from recursing into us.
            recvNamed = dont_look_inside(recvNamed)
        cls.recvNamed = recvNamed

    return atoms
Esempio n. 32
0
from rpython.rtyper.lltypesystem.lltype import nullptr
from rpython.rtyper.lltypesystem.rffi import getintfield

from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused
from typhon.objects.collections.lists import ConstList
from typhon.objects.data import (bytesToString, unwrapBytes, BytesObject,
                                 StrObject)
from typhon.objects.refs import LocalResolver, makePromise
from typhon.objects.root import Object, runnable
from typhon.vats import currentVat, scopedVat


GETADDRESS_0 = getAtom(u"getAddress", 0)
GETFAMILY_0 = getAtom(u"getFamily", 0)
GETSOCKETTYPE_0 = getAtom(u"getSocketType", 0)
RUN_2 = getAtom(u"run", 2)


socktypes = {
    s.SOCK_DGRAM: u"datagram",
    s.SOCK_RAW: u"raw",
    s.SOCK_RDM: u"reliable datagram",
    s.SOCK_SEQPACKET: u"packet",
    s.SOCK_STREAM: u"stream",
}


class AddrInfo(Object):
Esempio n. 33
0
File: stdio.py Progetto: dckc/typhon
from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.objects.files import FileFount, FileDrain
from typhon.objects.networking.streams import StreamDrain, StreamFount
from typhon.objects.networking.streamcaps import (FileSink, FileSource,
                                                  StreamSink, StreamSource)
from typhon.objects.root import Object, runnable
from typhon.vats import currentVat


RUN_0 = getAtom(u"run", 0)


@runnable(RUN_0)
def makeStdIn():
    vat = currentVat.get()
    uv_loop = vat.uv_loop
    stdinKind = ruv.guess_handle(0)
    if stdinKind == ruv.HANDLE_TTY:
        stdin = ruv.alloc_tty(uv_loop, 0, True)
        return StreamFount(ruv.rffi.cast(ruv.stream_tp, stdin), vat)
    else:
        return FileFount(ruv.alloc_fs(), 0, vat)


@runnable(RUN_0)
def makeStdOut():
    vat = currentVat.get()
    uv_loop = vat.uv_loop
    stdoutKind = ruv.guess_handle(1)
Esempio n. 34
0
from rpython.rlib.rarithmetic import intmask
from rpython.rtyper.lltypesystem.lltype import scoped_alloc
from rpython.rtyper.lltypesystem.rffi import charpsize2str, INTP

from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.errors import userError
from typhon.objects.constants import NullObject
from typhon.objects.data import BytesObject, StrObject
from typhon.objects.refs import makePromise
from typhon.objects.signals import SignalHandle
from typhon.objects.root import Object
from typhon.vats import scopedVat

ABORT_1 = getAtom(u"abort", 1)
COMPLETE_0 = getAtom(u"complete", 0)
RUN_1 = getAtom(u"run", 1)


@autohelp
class _NullSink(Object):
    """
    A sink which does nothing.
    """
    @method("Void", "Any")
    def run(self, _):
        pass

    @method("Void")
    def complete(self):
Esempio n. 35
0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, userError
from typhon.objects.collections.lists import ConstList
from typhon.objects.constants import NullObject
from typhon.objects.data import StrObject
from typhon.objects.root import Object, audited

_UNCALL_0 = getAtom(u"_uncall", 0)
GET_0 = getAtom(u"get", 0)
GETGUARD_0 = getAtom(u"getGuard", 0)
PUT_1 = getAtom(u"put", 1)


@autohelp
@audited.Transparent
class Binding(Object):
    """
    A slot and a guard describing the nature of the slot.
    """

    _immutable_ = True

    def __init__(self, slot, guard):
Esempio n. 36
0
from rpython.rlib.objectmodel import specialize

from typhon.atoms import getAtom
from typhon.env import Environment
from typhon.errors import Ejecting, UserException, userError
from typhon.objects.collections.lists import unwrapList
from typhon.objects.collections.maps import ConstMap, monteMap, unwrapMap
from typhon.objects.constants import NullObject, unwrapBool
from typhon.objects.data import StrObject
from typhon.objects.ejectors import Ejector, theThrower, throw
from typhon.objects.exceptions import sealException
from typhon.objects.guards import anyGuard
from typhon.objects.slots import finalBinding, varBinding
from typhon.smallcaps import ops

GET_0 = getAtom(u"get", 0)
PUT_1 = getAtom(u"put", 1)


def mkMirandaArgs():
    # XXX monteMap()
    _d = monteMap()
    _d[StrObject(u"FAIL")] = theThrower
    return ConstMap(_d)


MIRANDA_ARGS = mkMirandaArgs()


class SmallCaps(object):
    """
Esempio n. 37
0
from typhon.atoms import getAtom
from typhon.errors import userError
from typhon.vats import currentVat
from typhon.objects.collections.lists import wrapList
from typhon.objects.collections.maps import EMPTY_MAP
from typhon.objects.data import NullObject, StrObject
from typhon.objects.equality import EQUAL, TraversalKey, optSame, isSameEver
from typhon.objects.guards import anyGuard
from typhon.objects.refs import (EVENTUAL, NEAR, Promise, UnconnectedRef,
                                 isResolved, resolution)
from typhon.objects.root import audited
from typhon.objects.slots import FinalSlot

HANDLESEND_3 = getAtom(u"handleSend", 3)
HANDLESENDONLY_3 = getAtom(u"handleSendOnly", 3)
RUN_3 = getAtom(u"run", 3)


def send(ref, atom, args, namedArgs):
    if isinstance(ref, Promise):
        return ref.sendAll(atom, args, namedArgs)
    else:
        vat = currentVat.get()
        return vat.send(ref, atom, args, namedArgs)


def sendOnly(ref, atom, args, namedArgs):
    if isinstance(ref, Promise):
        ref.sendAllOnly(atom, args, namedArgs)
    else:
        vat = currentVat.get()
Esempio n. 38
0
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from rpython.rlib.jit import promote, unroll_safe
from rpython.rlib.objectmodel import always_inline

from typhon.atoms import getAtom
from typhon.objects.auditors import deepFrozenGuard, deepFrozenStamp
from typhon.objects.data import StrObject
from typhon.objects.guards import anyGuard
from typhon.objects.slots import Binding, finalBinding, VarSlot


GET_0 = getAtom(u"get", 0)
PUT_1 = getAtom(u"put", 1)


@always_inline
def bindingToSlot(binding):
    if isinstance(binding, Binding):
        return binding.get()
    from typhon.objects.collections.maps import EMPTY_MAP
    return binding.callAtom(GET_0, [], EMPTY_MAP)


@always_inline
def bindingToValue(binding):
    from typhon.objects.collections.maps import EMPTY_MAP
    if isinstance(binding, Binding):
Esempio n. 39
0
 def testRepr(self):
     atom = getAtom(u"test", 5)
     self.assertEqual(repr(atom), u"Atom(test/5)")
Esempio n. 40
0
File: files.py Progetto: dckc/typhon
from rpython.rtyper.lltypesystem.lltype import scoped_alloc
from rpython.rtyper.lltypesystem.rffi import charpsize2str

from typhon import log, rsodium, ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.enum import makeEnum
from typhon.errors import userError
from typhon.objects.constants import NullObject
from typhon.objects.data import BytesObject, StrObject, unwrapStr
from typhon.objects.refs import LocalResolver, makePromise
from typhon.objects.root import Object, runnable
from typhon.vats import currentVat, scopedVat


ABORTFLOW_0 = getAtom(u"abortFlow", 0)
FLOWABORTED_1 = getAtom(u"flowAborted", 1)
FLOWSTOPPED_1 = getAtom(u"flowStopped", 1)
RECEIVE_1 = getAtom(u"receive", 1)
RUN_1 = getAtom(u"run", 1)


@autohelp
class FileUnpauser(Object):
    """
    A pause on a file fount.
    """

    def __init__(self, fount):
        self.fount = fount
Esempio n. 41
0
# License for the specific language governing permissions and limitations
# under the License.

import inspect

from rpython.rlib import rgc
from rpython.rlib.unroll import unrolling_iterable
from rpython.rlib.jit import jit_debug, promote, unroll_safe
from rpython.rlib.objectmodel import compute_identity_hash, specialize
from rpython.rlib.rstackovf import StackOverflow, check_stack_overflow

from typhon.atoms import getAtom
from typhon.errors import Refused, UserException, userError
from typhon.profile import profileTyphon

RUN_1 = getAtom(u"run", 1)
_CONFORMTO_1 = getAtom(u"_conformTo", 1)
_GETALLEGEDINTERFACE_0 = getAtom(u"_getAllegedInterface", 0)
_PRINTON_1 = getAtom(u"_printOn", 1)
_RESPONDSTO_2 = getAtom(u"_respondsTo", 2)
_SEALEDDISPATCH_1 = getAtom(u"_sealedDispatch", 1)
_UNCALL_0 = getAtom(u"_uncall", 0)
_WHENMORERESOLVED_1 = getAtom(u"_whenMoreResolved", 1)

mirandaAtoms = [
    _CONFORMTO_1,
    _GETALLEGEDINTERFACE_0,
    _PRINTON_1,
    _RESPONDSTO_2,
    _SEALEDDISPATCH_1,
    _UNCALL_0,
Esempio n. 42
0
# under the License.

import inspect

from rpython.rlib import rgc
from rpython.rlib.unroll import unrolling_iterable
from rpython.rlib.jit import jit_debug, promote, unroll_safe
from rpython.rlib.objectmodel import compute_identity_hash, specialize
from rpython.rlib.rstackovf import StackOverflow, check_stack_overflow

from typhon.atoms import getAtom
from typhon.errors import Refused, UserException, userError
from typhon.profile import profileTyphon


RUN_1 = getAtom(u"run", 1)
_CONFORMTO_1 = getAtom(u"_conformTo", 1)
_GETALLEGEDINTERFACE_0 = getAtom(u"_getAllegedInterface", 0)
_PRINTON_1 = getAtom(u"_printOn", 1)
_RESPONDSTO_2 = getAtom(u"_respondsTo", 2)
_SEALEDDISPATCH_1 = getAtom(u"_sealedDispatch", 1)
_UNCALL_0 = getAtom(u"_uncall", 0)
_WHENMORERESOLVED_1 = getAtom(u"_whenMoreResolved", 1)


def makeMirandaArgs():
    from typhon.objects.collections.maps import monteMap
    from typhon.objects.data import StrObject
    from typhon.objects.ejectors import theThrower

    # XXX monteMap()
Esempio n. 43
0
"""
Some cryptographic services.
"""

from rpython.rlib.rarithmetic import intmask

from typhon import log, rsodium
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, WrongType, userError
from typhon.objects.collections.lists import ConstList
from typhon.objects.data import (BytesObject, IntObject, StrObject,
                                 unwrapBytes)
from typhon.objects.root import Object

ASBYTES_0 = getAtom(u"asBytes", 0)
FROMBYTES_1 = getAtom(u"fromBytes", 1)
FROMPUBLICBYTES_1 = getAtom(u"fromPublicBytes", 1)
FROMSECRETBYTES_1 = getAtom(u"fromSecretBytes", 1)
GETALGORITHM_0 = getAtom(u"getAlgorithm", 0)
GETENTROPY_0 = getAtom(u"getEntropy", 0)
KEYMAKER_0 = getAtom(u"keyMaker", 0)
MAKESECUREENTROPY_0 = getAtom(u"makeSecureEntropy", 0)
PAIRWITH_1 = getAtom(u"pairWith", 1)
PUBLICKEY_0 = getAtom(u"publicKey", 0)
RUN_0 = getAtom(u"run", 0)
SEAL_1 = getAtom(u"seal", 1)
UNSEAL_2 = getAtom(u"unseal", 2)


@autohelp
Esempio n. 44
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
Esempio n. 45
0
from rpython.rlib.rstring import StringBuilder, UnicodeBuilder, replace, split
from rpython.rlib.rstruct.ieee import pack_float
from rpython.rlib.unicodedata import unicodedb_6_2_0 as unicodedb

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, WrongType, userError
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.comparison import Incomparable
from typhon.objects.constants import NullObject, unwrapBool, wrapBool
from typhon.objects.root import Object, audited, runnable
from typhon.prelude import getGlobalValue
from typhon.quoting import quoteChar, quoteStr


ABOVEZERO_0 = getAtom(u"aboveZero", 0)
ABS_0 = getAtom(u"abs", 0)
ADD_1 = getAtom(u"add", 1)
AND_1 = getAtom(u"and", 1)
APPROXDIVIDE_1 = getAtom(u"approxDivide", 1)
ASINTEGER_0 = getAtom(u"asInteger", 0)
ASLIST_0 = getAtom(u"asList", 0)
ASSET_0 = getAtom(u"asSet", 0)
ASSTRING_0 = getAtom(u"asString", 0)
ATLEASTZERO_0 = getAtom(u"atLeastZero", 0)
ATMOSTZERO_0 = getAtom(u"atMostZero", 0)
BELOWZERO_0 = getAtom(u"belowZero", 0)
BITLENGTH_0 = getAtom(u"bitLength", 0)
COMBINE_1 = getAtom(u"combine", 1)
COMPLEMENT_0 = getAtom(u"complement", 0)
CONTAINS_1 = getAtom(u"contains", 1)
Esempio n. 46
0
import py

from rpython.rlib.rbigint import BASE10, rbigint

from typhon import nodes
from typhon.atoms import getAtom
from typhon.autohelp import autoguard, autohelp, method
from typhon.errors import userError
from typhon.nanopass import makeIR
from typhon.objects.constants import NullObject
from typhon.objects.data import SourceSpan
from typhon.objects.root import Object, audited
from typhon.quoting import quoteChar, quoteStr
from typhon.objects.collections.lists import ConstList

GETSTARTLINE_0 = getAtom(u"getStartLine", 0)

def saveScripts(ast):
    ast = SanityCheck().visitExpr(ast)
    ast = SaveScripts().visitExpr(ast)
    return ast

MastIR = makeIR("Mast",
    ["Noun"],
    {
        "Expr": {
            "NullExpr": [],
            "CharExpr": [("c", None)],
            "DoubleExpr": [("d", None)],
            "IntExpr": [("i", None)],
            "StrExpr": [("s", None)],
Esempio n. 47
0
from typhon.errors import Ejecting, Refused, UserException, userError
from typhon.log import log
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.constants import NullObject, unwrapBool, wrapBool
from typhon.objects.collections.lists import ConstList
from typhon.objects.data import StrObject, unwrapStr
from typhon.objects.ejectors import Ejector
from typhon.objects.guards import anyGuard
from typhon.objects.printers import Printer
from typhon.objects.root import Object
from typhon.objects.slots import finalBinding
from typhon.smallcaps.machine import SmallCaps

# XXX AuditionStamp, Audition guard

ASK_1 = getAtom(u"ask", 1)
GETGUARD_1 = getAtom(u"getGuard", 1)
GETOBJECTEXPR_0 = getAtom(u"getObjectExpr", 0)
GETFQN_0 = getAtom(u"getFQN", 0)

pemci = u".".join([
    u"lo lebna cu rivbi",
    u"lo nu fi ri facki",
    u"fa le vi larmuzga",
    u"fe le zi ca du'u",
    u"le lebna pu jbera",
    u"lo catlu pe ro da",
])


def boolStr(b):
Esempio n. 48
0
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.collections.lists import wrapList
from typhon.objects.data import StrObject
from typhon.objects.ejectors import throwStr
from typhon.objects.root import Object, runnable


RUN_2 = getAtom(u"run", 2)


def sealException(ue):
    val = ue.getPayload()
    trail = ue.trail
    if isinstance(val, SealedException):
        return val
    return SealedException(val, trail)


@autohelp
class SealedException(Object):
    """
    An exception.

    Sealed within this object are the details of an exceptional occurrence.
    """

    def __init__(self, value, trail):
        self.value = value
        self.trail = trail
Esempio n. 49
0
from rpython.rlib.rstring import StringBuilder, UnicodeBuilder, replace, split
from rpython.rlib.rstruct.ieee import float_pack
from rpython.rlib.unicodedata import unicodedb_6_2_0 as unicodedb

from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.errors import WrongType, userError
from typhon.objects.auditors import deepFrozenStamp
from typhon.objects.comparison import Incomparable
from typhon.objects.constants import NullObject, unwrapBool, wrapBool
from typhon.objects.root import Object, audited, runnable
from typhon.spans import Span
from typhon.prelude import getGlobalValue
from typhon.quoting import quoteChar, quoteStr

RUN_6 = getAtom(u"run", 6)


@specialize.argtype(0, 1)
def cmp(l, r):
    if l < r:
        return -1
    elif l > r:
        return 1
    else:
        return 0


@specialize.argtype(0, 1)
def polyCmp(l, r):
    if l < r:
Esempio n. 50
0
from rpython.rlib.objectmodel import import_from_mixin
from rpython.rlib.rarithmetic import intmask

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Ejecting, Refused, UserException, userError
from typhon.objects.collections.helpers import MonteSorter
from typhon.objects.constants import NullObject, wrapBool
from typhon.objects.data import IntObject, StrObject, unwrapInt
from typhon.objects.ejectors import Ejector, throw
from typhon.objects.printers import toString
from typhon.objects.root import Object, audited
from typhon.rstrategies import rstrategies
from typhon.strategies import strategyFactory

ADD_1 = getAtom(u"add", 1)
ASMAP_0 = getAtom(u"asMap", 0)
ASSET_0 = getAtom(u"asSet", 0)
CONTAINS_1 = getAtom(u"contains", 1)
DIVERGE_0 = getAtom(u"diverge", 0)
EXTEND_1 = getAtom(u"extend", 1)
GET_1 = getAtom(u"get", 1)
INDEXOF_1 = getAtom(u"indexOf", 1)
INDEXOF_2 = getAtom(u"indexOf", 2)
INSERT_2 = getAtom(u"insert", 2)
JOIN_1 = getAtom(u"join", 1)
LAST_0 = getAtom(u"last", 0)
MULTIPLY_1 = getAtom(u"multiply", 1)
NEXT_1 = getAtom(u"next", 1)
OP__CMP_1 = getAtom(u"op__cmp", 1)
POP_0 = getAtom(u"pop", 0)
Esempio n. 51
0
from rpython.rlib import rgc
from rpython.rlib.rerased import new_erasing_pair

# from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused
from typhon.objects.collections.lists import ConstList
from typhon.objects.collections.maps import ConstMap, monteMap
from typhon.objects.data import IntObject, StrObject
from typhon.objects.root import Object, runnable
from typhon.objects.user import ScriptObject

GETBUCKETS_0 = getAtom(u"getBuckets", 0)
GETCRYPT_0 = getAtom(u"getCrypt", 0)
GETDISASSEMBLER_0 = getAtom(u"getDisassembler", 0)
GETHANDLES_0 = getAtom(u"getHandles", 0)
GETHEAPSTATISTICS_0 = getAtom(u"getHeapStatistics", 0)
GETMEMORYUSAGE_0 = getAtom(u"getMemoryUsage", 0)
GETOBJECTCOUNT_0 = getAtom(u"getObjectCount", 0)
GETREACTORSTATISTICS_0 = getAtom(u"getReactorStatistics", 0)

# The fun of GC management. This is all very subject to change and only works
# with rpython 0.1.4 from PyPI. Sorry. ~ C.


def clear_gcflag_extra(fromlist):
    pending = fromlist[:]
    while pending:
        gcref = pending.pop()
        if rgc.get_gcflag_extra(gcref):
Esempio n. 52
0
import weakref

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.enum import makeEnum
from typhon.errors import Refused, UserException, userError
from typhon.log import log
from typhon.objects.auditors import deepFrozenStamp, selfless
from typhon.objects.constants import NullObject, unwrapBool, wrapBool
from typhon.objects.data import StrObject
from typhon.objects.root import Object, audited
from typhon.vats import currentVat

BROKEN, EVENTUAL, NEAR = makeEnum(u"RefState", u"broken eventual near".split())

BROKEN_1 = getAtom(u"broken", 1)
FULFILLMENT_1 = getAtom(u"fulfillment", 1)
ISBROKEN_1 = getAtom(u"isBroken", 1)
ISDEEPFROZEN_1 = getAtom(u"isDeepFrozen", 1)
ISEVENTUAL_1 = getAtom(u"isEventual", 1)
ISFAR_1 = getAtom(u"isFar", 1)
ISNEAR_1 = getAtom(u"isNear", 1)
ISRESOLVED_1 = getAtom(u"isResolved", 1)
ISSELFISH_1 = getAtom(u"isSelfish", 1)
ISSELFLESS_1 = getAtom(u"isSelfless", 1)
ISSETTLED_1 = getAtom(u"isSettled", 1)
MAKEPROXY_3 = getAtom(u"makeProxy", 3)
OPTPROBLEM_1 = getAtom(u"optProblem", 1)
PROMISE_0 = getAtom(u"promise", 0)
RESOLVE_1 = getAtom(u"resolve", 1)
RESOLVE_2 = getAtom(u"resolve", 2)
Esempio n. 53
0
File: nodes.py Progetto: dckc/typhon
 def getAtom(self):
     return getAtom(self._verb, len(self._ps))
Esempio n. 54
0
from rpython.rlib.rarithmetic import intmask
from rpython.rtyper.lltypesystem.lltype import nullptr

from typhon import ruv
from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.errors import userError
from typhon.objects.collections.maps import monteMap
from typhon.objects.data import BytesObject, StrObject, unwrapBytes
from typhon.objects.networking.streamcaps import (StreamSink, StreamSource,
                                                  emptySource, nullSink)
from typhon.objects.root import Object, audited
from typhon.objects.refs import makePromise
from typhon.vats import currentVat, scopedVat

FLOWTO_1 = getAtom(u"flowTo", 1)
RUN_3 = getAtom(u"run", 3)


@autohelp
class CurrentProcess(Object):
    """
    The current process on the local node.
    """
    def __init__(self, config):
        self.config = config

    def toString(self):
        return u"<current process (PID %d)>" % os.getpid()

    @method("List")
Esempio n. 55
0
from typhon.atoms import getAtom
from typhon.autohelp import autohelp, method
from typhon.errors import UserException
from typhon.objects.auditors import (SealedPortrayal, deepFrozenStamp,
                                     selfless, semitransparentStamp)
from typhon.objects.collections.helpers import asSet
from typhon.objects.collections.lists import wrapList
from typhon.objects.collections.maps import EMPTY_MAP
from typhon.objects.data import StrObject
from typhon.objects.ejectors import throwStr
from typhon.objects.root import Object, runnable

RUN_1 = getAtom(u"run", 1)
RUN_2 = getAtom(u"run", 2)


def sealException(ue):
    val = ue.getPayload()
    if isinstance(val, SealedException):
        return val
    else:
        return SealedException(ue)


@autohelp
class SealedException(Object):
    """
    An exception.

    Sealed within this object are the details of an exceptional occurrence.
    """
Esempio n. 56
0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, userError
from typhon.objects.root import Object, audited
from typhon.prelude import getGlobalValue


AND_1 = getAtom(u"and", 1)
BUTNOT_1 = getAtom(u"butNot", 1)
NOT_0 = getAtom(u"not", 0)
OP__CMP_1 = getAtom(u"op__cmp", 1)
OR_1 = getAtom(u"or", 1)
PICK_2 = getAtom(u"pick", 2)
XOR_1 = getAtom(u"xor", 1)


@autohelp
@audited.DF
class _NullObject(Object):
    """
    The null object.
    """