Beispiel #1
0
 def printOn(self, out):
     out.call(u"print", [StrObject(self.repr().decode("utf-8"))])
Beispiel #2
0
 def testHashInequal(self):
     a = StrObject(u"acerbic")
     b = StrObject(u"bitter")
     self.assertNotEqual(a.hash(), b.hash())
Beispiel #3
0
 def testLastIndexOfFail(self):
     s = StrObject(u"needle")
     result = s.call(u"lastIndexOf", [StrObject(u"x")])
     self.assertEqual(result.getInt(), -1)
Beispiel #4
0
 def testToLowerCaseUnicode(self):
     s = StrObject(u"Α And Ω")
     result = s.call(u"toLowerCase", [])
     self.assertEqual(result._s, u"α and ω")
Beispiel #5
0
 def testToUpperCaseUnicode(self):
     s = StrObject(u"¡Holá!")
     result = s.call(u"toUpperCase", [])
     self.assertEqual(result._s, u"¡HOLÁ!")
Beispiel #6
0
 def testJoin(self):
     s = StrObject(u"|")
     result = s.call(
         u"join",
         [ConstList([StrObject(u"5"), StrObject(u"42")])])
     self.assertEqual(result._s, u"5|42")
Beispiel #7
0
 def testSliceStartStop(self):
     s = StrObject(u"the lime in the coconut")
     result = s.call(u"slice", [IntObject(4), IntObject(8)])
     self.assertEqual(result._s, u"lime")
Beispiel #8
0
 def printOn(self, out):
     out.call(u"print", [StrObject(u"Same")])
Beispiel #9
0
 def printOn(self, out):
     from typhon.objects.data import StrObject
     out.call(u"print", [StrObject(u"SubrangeGuard")])
Beispiel #10
0
 def printOn(self, out):
     out.call(u"print", [StrObject(u"FinalSlot[")])
     out.call(u"print", [self.valueGuard]),
     out.call(u"print", [StrObject(u"]")])
Beispiel #11
0
 def printOn(self, out):
     out.call(u"print", [StrObject(u"Same[")])
     out.call(u"print", [self.value])
     out.call(u"print", [StrObject(u"]")])
Beispiel #12
0
 def uncall(self):
     return wrapList([StrObject(self._s)])
Beispiel #13
0
 def printOn(self, out):
     out.call(u"print", [StrObject(u"<makeLiteral>")])
Beispiel #14
0
 def uncall(self):
     return wrapList([
         StrObject(self._d if self._d else u""), self._n,
         self._as if self._as is not None else NullObject,
         wrapList(self._implements), self._script
     ])
Beispiel #15
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)
Beispiel #16
0
 def printOn(self, out):
     from typhon.objects.data import StrObject
     out.call(u"print", [subrangeGuardMaker])
     out.call(u"print", [StrObject(u"[")])
     out.call(u"print", [self.superGuard])
     out.call(u"print", [StrObject(u"]")])
Beispiel #17
0
 def testGetOutOfBounds(self):
     s = StrObject(u"index")
     self.assertRaises(UserException, s.call, u"get", [IntObject(6)])
Beispiel #18
0
    def recv(self, atom, args):
        from typhon.nodes import Noun, Method, Obj
        from typhon.objects.equality import optSame, EQUAL
        from typhon.objects.user import Audition
        if atom is _UNCALL_0:
            from typhon.objects.collections.maps import EMPTY_MAP
            return ConstList([
                subrangeGuardMaker,
                StrObject(u"get"),
                ConstList([self.superGuard]), EMPTY_MAP
            ])

        if atom is AUDIT_1:
            audition = args[0]
            if not isinstance(audition, Audition):
                raise userError(u"not invoked with an Audition")
            ast = audition.ast
            if not isinstance(ast, Obj):
                raise userError(u"audition not created with an object expr")
            methods = ast._script._methods
            for m in methods:
                if isinstance(m, Method) and m._verb == u"coerce":
                    mguard = m._g
                    if isinstance(mguard, Noun):
                        rGSG = audition.getGuard(mguard.name)
                        if isinstance(rGSG, FinalSlotGuard):
                            rGSG0 = rGSG.valueGuard
                            if isinstance(rGSG0, SameGuard):
                                resultGuard = rGSG0.value

                                if (optSame(resultGuard,
                                            self.superGuard) is EQUAL or
                                    (SUPERSETOF_1
                                     in self.superGuard.respondingAtoms()
                                     and self.superGuard.call(
                                         u"supersetOf",
                                         [resultGuard]) is wrapBool(True))):
                                    return wrapBool(True)
                                raise userError(
                                    u"%s does not have a result guard implying "
                                    u"%s, but %s" %
                                    (audition.fqn, self.superGuard.toQuote(),
                                     resultGuard.toQuote()))
                            raise userError(
                                u"%s does not have a determinable "
                                u"result guard, but <& %s> :%s" %
                                (audition.fqn, mguard.name, rGSG.toQuote()))
                    break
            return self
        if atom is PASSES_1:
            return wrapBool(args[0].auditedBy(self))
        if atom is COERCE_2:
            specimen, ej = args[0], args[1]
            if specimen.auditedBy(self):
                return specimen
            c = specimen.call(u"_conformTo", [self])
            if c.auditedBy(self):
                return c
            throw(
                ej,
                StrObject(u"%s does not conform to %s" %
                          (specimen.toQuote(), self.toQuote())))

        raise Refused(self, atom, args)
Beispiel #19
0
 def testSliceStart(self):
     s = StrObject(u"slice of lemon")
     result = s.call(u"slice", [IntObject(9)])
     self.assertEqual(result._s, u"lemon")
Beispiel #20
0
 def _uncall(self):
     from typhon.objects.collections.lists import wrapList
     from typhon.objects.collections.maps import EMPTY_MAP
     # [1,2,3].asSet() -> [[1,2,3], "asSet"]
     rv = wrapList(self.objectSet.keys())
     return [rv, StrObject(u"asSet"), wrapList([]), EMPTY_MAP]
Beispiel #21
0
 def testSliceStartNegative(self):
     s = StrObject(u"nope")
     self.assertRaises(UserException, s.call, u"slice", [IntObject(-2)])
Beispiel #22
0
def unboxUnconnectedRef(value):
    assert isinstance(value, UnconnectedRef), "Implementation detail"
    return value._problem


unboxedStrategies = [
    makeUnboxedListStrategy(cls, box, unbox, exemplar)
    for (cls, box, unbox, exemplar) in [
        # Bools.
        (BoolObject, wrapBool, unwrapBool, FalseObject),
        # Chars.
        (CharObject, CharObject, unwrapChar, CharObject(u'▲')),
        # Small ints.
        (IntObject, IntObject, unwrapInt, IntObject(42)),
        # Unicode strings.
        (StrObject, StrObject, unwrapStr, StrObject(u"▲")),
        # Bytestrings.
        (BytesObject, BytesObject, unwrapBytes, BytesObject("M")),
        # _booleanFlow-generated lists of unconnected refs.
        (UnconnectedRef, UnconnectedRef, unboxUnconnectedRef,
         UnconnectedRef(StrObject(u"Implementation detail leaked"))),
    ]
]


@rstrategies.strategy(generalize=[NullListStrategy] + unboxedStrategies +
                      [GenericListStrategy])
class EmptyListStrategy(Strategy):
    """
    A list with no elements.
    """
Beispiel #23
0
 def testToUpperCase(self):
     s = StrObject(u"lower")
     result = s.call(u"toUpperCase", [])
     self.assertEqual(result._s, u"LOWER")
Beispiel #24
0
 def fireString(self, message):
     return self.fire(StrObject(message))
Beispiel #25
0
 def testHashEqual(self):
     a = StrObject(u"acidic")
     b = StrObject(u"acidic")
     self.assertEqual(a.hash(), b.hash())
Beispiel #26
0
 def visitStrExpr(self, s, span):
     return self.dest.LiveExpr(StrObject(s), span)
Beispiel #27
0
 def testIndexOf(self):
     s = StrObject(u"needle")
     result = s.call(u"indexOf", [StrObject(u"e")])
     self.assertEqual(result.getInt(), 1)
Beispiel #28
0
def runTyphon(argv):
    recorder = Recorder()
    recorder.start()

    # Initialize libsodium.
    if rsodium.init() < 0:
        print "Couldn't initialize libsodium!"
        return 1

    config = Configuration(argv)

    if config.verbose:
        enableDebugPrint()

    config.enableLogging()

    if len(config.argv) < 2:
        print "No file provided?"
        return 1

    # Pass user configuration to the JIT.
    set_user_param(None, config.jit)

    # Intialize our loop.
    uv_loop = ruv.alloc_loop()

    # Usurp SIGPIPE, as libuv does not handle it.
    rsignal.pypysig_ignore(rsignal.SIGPIPE)

    # Initialize our first vat. It shall be immortal.
    vatManager = VatManager()
    vat = Vat(vatManager, uv_loop, checkpoints=-1)
    vatManager.vats.append(vat)

    # Update loop timing information. Until the loop really gets going, we
    # have to do this ourselves in order to get the timing correct for early
    # timers.
    ruv.update_time(uv_loop)
    try:
        with scopedVat(vat) as vat:
            prelude = loadPrelude(config, recorder, vat)
    except LoadFailed as lf:
        print lf
        return 1

    registerGlobals(prelude)

    scope = safeScope()
    scope.update(prelude)
    ss = scope.copy()
    reflectedSS = monteMap()
    for k, b in ss.iteritems():
        reflectedSS[StrObject(u"&&" + k)] = b
    ss[u"safeScope"] = finalBinding(ConstMap(reflectedSS), deepFrozenGuard)
    reflectedSS[StrObject(u"&&safeScope")] = ss[u"safeScope"]
    scope[u"safeScope"] = ss[u"safeScope"]
    scope.update(unsafeScope(config))
    reflectedUnsafeScope = monteMap()
    unsafeScopeDict = {}
    for k, b in scope.iteritems():
        reflectedUnsafeScope[StrObject(u"&&" + k)] = b
        unsafeScopeDict[k] = b
    rus = finalBinding(ConstMap(reflectedUnsafeScope), anyGuard)
    reflectedUnsafeScope[StrObject(u"&&unsafeScope")] = rus
    unsafeScopeDict[u"unsafeScope"] = rus
    try:
        code = obtainModule([""], config.argv[1], recorder)
    except LoadFailed as lf:
        print lf
        return 1

    if config.loadOnly:
        # We are finished.
        return 0

    if not config.benchmark:
        benchmarkSettings.disable()

    with profiling("vmprof.log", config.profile):
        # Update loop timing information.
        ruv.update_time(uv_loop)
        debug_print("Taking initial turn in script...")
        result = NullObject
        with recorder.context("Time spent in vats"):
            with scopedVat(vat):
                result = evaluateTerms([code], unsafeScopeDict)
        if result is None:
            return 1

        # Exit status code.
        exitStatus = 0
        # Update loop timing information.
        ruv.update_time(uv_loop)
        try:
            runUntilDone(vatManager, uv_loop, recorder)
            rv = resolution(result) if result is not None else NullObject
            if isinstance(rv, IntObject):
                exitStatus = rv.getInt()
        except SystemExit:
            pass
            # Huh, apparently this doesn't work. Wonder why/why not.
            # exitStatus = se.code
        finally:
            recorder.stop()
            recorder.printResults()

    # Clean up and exit.
    cleanUpEverything()
    return exitStatus
Beispiel #29
0
 def testTrimEmpty(self):
     s = StrObject(u"")
     result = s.call(u"trim", [])
     self.assertEqual(result._s, u"")
Beispiel #30
0
 def printOn(self, printer):
     # Note that the printer is a Monte-level object. Also note that, at
     # this point, we have had a bad day; we did not respond to _printOn/1.
     from typhon.objects.data import StrObject
     printer.call(u"print",
                  [StrObject(u"<%s>" % self.codeScript.displayName)])