def recv(self, atom, args): if atom is ISSETTLED_1: return wrapBool(isSettled(args[0])) if atom is OPTSAME_2: first, second = args result = optSame(first, second) if result is NOTYET: return NullObject return wrapBool(result is EQUAL) if atom is SAMEEVER_2: first, second = args result = optSame(first, second) if result is NOTYET: raise userError(u"Not yet settled!") return wrapBool(result is EQUAL) if atom is SAMEYET_2: first, second = args result = optSame(first, second) return wrapBool(result is EQUAL) if atom is MAKETRAVERSALKEY_1: return TraversalKey(args[0]) raise Refused(self, atom, args)
def safeScope(): return finalize({ u"null": NullObject, u"Infinity": Infinity, u"NaN": NaN, u"false": wrapBool(False), u"true": wrapBool(True), u"Any": anyGuard, u"Binding": BindingGuard(), u"DeepFrozen": deepFrozenGuard, u"FinalSlot": theFinalSlotGuardMaker, u"Near": NearGuard(), u"Same": sameGuardMaker, u"Selfless": selfless, u"SubrangeGuard": subrangeGuardMaker, u"VarSlot": theVarSlotGuardMaker, u"M": MObject(), u"Ref": RefOps(), u"_auditedBy": auditedBy(), u"_equalizer": Equalizer(), u"_loop": loop(), u"_makeBytes": theMakeBytes, u"_makeDouble": theMakeDouble, u"_makeFinalSlot": theFinalSlotMaker, u"_makeInt": theMakeInt, u"_makeList": theMakeList, u"_makeMap": theMakeMap, u"_makeSourceSpan": makeSourceSpan, u"_makeStr": theMakeStr, u"_makeVarSlot": theVarSlotMaker, u"_slotToBinding": theSlotBinder, u"throw": theThrower, u"trace": TraceLn(), u"traceln": TraceLn(), })
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)
def recv(self, atom, args): if atom is RESOLVE_1: return wrapBool(self.resolve(args[0])) if atom is RESOLVE_2: return wrapBool(self.resolve(args[0], unwrapBool(args[1]))) if atom is SMASH_1: return wrapBool(self.smash(args[0])) raise Refused(self, atom, args)
def auditedBy(auditor, specimen): """ Whether an auditor has audited a specimen. """ from typhon.objects.refs import resolution from typhon.objects.constants import wrapBool return wrapBool(resolution(specimen).auditedBy(auditor))
def recv(self, atom, args): from typhon.objects.constants import wrapBool from typhon.objects.constants import NullObject if atom is AUDIT_1: return wrapBool(True) if atom is PASSES_1: return wrapBool(args[0].auditedBy(selfless)) if atom is COERCE_2: if args[0].auditedBy(selfless): return args[0] from typhon.objects.ejectors import throw throw(args[1], NullObject) return NullObject raise Refused(self, atom, args)
def _uncall(self): from typhon.objects.collections.lists import wrapList from typhon.objects.collections.maps import EMPTY_MAP return [ makeSourceSpan, StrObject(u"run"), wrapList([wrapBool(self._isOneToOne), IntObject(self.startLine), IntObject(self.startCol), IntObject(self.endLine), IntObject(self.endCol)]), EMPTY_MAP]
def recv(self, atom, args): from typhon.objects.data import StrObject if atom is AUDIT_1: from typhon.objects.constants import wrapBool return wrapBool(True) if atom is COERCE_2: if args[0].auditedBy(self): return args[0] args[1].call(u"run", [StrObject(u"Not DeepFrozen")]) raise Refused(self, atom, args)
def optSame(self, first, second): """ Whether `first` and `second` are the same. Returns `null` if `first` or `second` are too unsettled to compare. """ result = optSame(first, second) if result is NOTYET: return NullObject return wrapBool(result is EQUAL)
def recv(self, atom, args): if atom is COERCE_2: for g in self.subguards: with Ejector() as ej: try: return g.call(u"coerce", [args[0], ej]) except Ejecting as e: if e.ejector is ej: continue throw(args[1], StrObject(u"No subguards matched")) if atom is SUPERSETOF_1: for g in self.subguards: if not unwrapBool(g.call(u"supersetOf", [args[0]])): return wrapBool(False) return wrapBool(True) if atom is _UNCALL_0: from typhon.objects.collections.maps import EMPTY_MAP return ConstList([anyGuard, StrObject(u"get"), ConstList(self.subguards), EMPTY_MAP]) raise Refused(self, atom, args)
def recv(self, atom, args): from typhon.objects.constants import wrapBool, NullObject if atom is PASSES_1: return wrapBool(args[0].auditedBy(transparentStamp)) if atom is COERCE_2: if args[0].auditedBy(transparentStamp): return args[0] from typhon.objects.ejectors import throw throw(args[1], NullObject) return NullObject raise Refused(self, atom, args)
def recv(self, atom, args): from typhon.objects.constants import wrapBool from typhon.objects.collections.helpers import monteMap from typhon.objects.user import Audition if atom is AUDIT_1: audition = args[0] if not isinstance(audition, Audition): raise userError(u"not an Audition") return wrapBool(self.audit(audition)) if atom is COERCE_2: from typhon.objects.constants import NullObject from typhon.objects.ejectors import theThrower ej = args[1] if ej is NullObject: ej = theThrower checkDeepFrozen(args[0], monteMap(), ej, args[0]) return args[0] if atom is SUPERSETOF_1: return wrapBool(deepFrozenSupersetOf(args[0])) raise Refused(self, atom, args)
def safeScope(): return finalize({ u"null": NullObject, u"Infinity": Infinity, u"NaN": NaN, u"false": wrapBool(False), u"true": wrapBool(True), u"Any": anyGuard, u"Binding": BindingGuard(), u"DeepFrozen": deepFrozenGuard, u"FinalSlot": theFinalSlotGuardMaker, u"Near": NearGuard(), u"Same": sameGuardMaker, u"Selfless": selfless, u"SubrangeGuard": subrangeGuardMaker, u"VarSlot": theVarSlotGuardMaker, u"M": MObject(), u"Ref": RefOps(), u"_auditedBy": auditedBy(), u"_equalizer": Equalizer(), u"_loop": loop(), u"_makeBytes": theMakeBytes, u"_makeDouble": theMakeDouble, u"_makeFinalSlot": theFinalSlotMaker, u"_makeInt": theMakeInt, u"_makeList": theMakeList, u"_makeMap": theMakeMap, u"_makeSourceSpan": makeSourceSpan, u"_makeStr": theMakeStr, u"_makeString": theMakeStr, u"_makeVarSlot": theVarSlotMaker, u"_slotToBinding": theSlotBinder, u"throw": theThrower, u"trace": TraceLn(), u"traceln": TraceLn(), })
def _uncall(self): from typhon.objects.collections.lists import wrapList from typhon.objects.collections.maps import EMPTY_MAP return [ makeSourceSpan, StrObject(u"run"), wrapList([ wrapBool(self._isOneToOne), IntObject(self.startLine), IntObject(self.startCol), IntObject(self.endLine), IntObject(self.endCol) ]), EMPTY_MAP ]
def recv(self, atom, args): if atom is ASK_1: return wrapBool(self.ask(args[0])) if atom is GETGUARD_1: return self.getGuard(unwrapStr(args[0])) if atom is GETOBJECTEXPR_0: return self.ast if atom is GETFQN_0: return StrObject(self.fqn) raise Refused(self, atom, args)
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
def recv(self, atom, args): if atom is COERCE_2: for g in self.subguards: with Ejector() as ej: try: return g.call(u"coerce", [args[0], ej]) except Ejecting as e: if e.ejector is ej: continue throw(args[1], StrObject(u"No subguards matched")) if atom is SUPERSETOF_1: for g in self.subguards: if not unwrapBool(g.call(u"supersetOf", [args[0]])): return wrapBool(False) return wrapBool(True) if atom is _UNCALL_0: from typhon.objects.collections.maps import EMPTY_MAP return ConstList([ anyGuard, StrObject(u"get"), ConstList(self.subguards), EMPTY_MAP ]) raise Refused(self, atom, args)
def recv(self, atom, args): if atom is _UNCALL_0: from typhon.objects.collections.maps import EMPTY_MAP from typhon.scopes.safe import theFinalSlotGuardMaker return ConstList([theFinalSlotGuardMaker, StrObject(u"get"), ConstList([self.valueGuard]), EMPTY_MAP]) if atom is GETGUARD_0: return self.valueGuard if atom is COERCE_2: return self.coerce(args[0], args[1]) if atom is SUPERSETOF_1: s = args[0] if isinstance(s, FinalSlot): return self.valueGuard.call(u"supersetOf", [s._guard]) return wrapBool(False) raise Refused(self, atom, args)
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)
def recv(self, atom, args): if atom is EXTRACTGUARD_2: specimen, ej = args[0], args[1] if specimen is self: return anyGuard elif isinstance(specimen, VarSlotGuard): return specimen.valueGuard else: ej.call(u"run", [StrObject(u"Not a VarSlot guard")]) if atom is GETGUARD_0: return NullObject if atom is COERCE_2: return self.coerce(args[0], args[1]) if atom is GET_1: # XXX Coerce arg to Guard? return VarSlotGuard(args[0]) if atom is SUPERSETOF_1: return wrapBool(isinstance(args[0], VarSlotGuard) or isinstance(args[0], VarSlotGuardMaker)) raise Refused(self, atom, args)
def recv(self, atom, args): if atom is _UNCALL_0: from typhon.objects.collections.maps import EMPTY_MAP from typhon.scopes.safe import theFinalSlotGuardMaker return ConstList([ theFinalSlotGuardMaker, StrObject(u"get"), ConstList([self.valueGuard]), EMPTY_MAP ]) if atom is GETGUARD_0: return self.valueGuard if atom is COERCE_2: return self.coerce(args[0], args[1]) if atom is SUPERSETOF_1: s = args[0] if isinstance(s, FinalSlot): return self.valueGuard.call(u"supersetOf", [s._guard]) return wrapBool(False) raise Refused(self, atom, args)
def recv(self, atom, args): if atom is EXTRACTGUARD_2: specimen, ej = args[0], args[1] if specimen is self: return anyGuard elif isinstance(specimen, VarSlotGuard): return specimen.valueGuard else: ej.call(u"run", [StrObject(u"Not a VarSlot guard")]) if atom is GETGUARD_0: return NullObject if atom is COERCE_2: return self.coerce(args[0], args[1]) if atom is GET_1: # XXX Coerce arg to Guard? return VarSlotGuard(args[0]) if atom is SUPERSETOF_1: return wrapBool( isinstance(args[0], VarSlotGuard) or isinstance(args[0], VarSlotGuardMaker)) raise Refused(self, atom, args)
def recv(self, atom, args): if atom is COERCE_2: return args[0] if atom is SUPERSETOF_1: return wrapBool(True) if atom is EXTRACTGUARDS_2: g = args[0] ej = args[1] if isinstance(g, AnyOfGuard): return ConstList(g.subguards) else: ej.call(u"run", [StrObject(u"Not an AnyOf guard")]) if atom is GETMETHODS_0: return ConstSet(monteSet()) if atom.verb == u"get": return AnyOfGuard(args) raise Refused(self, atom, args)
def audit(self, audition): from typhon.nodes import Noun, Method, Obj from typhon.objects.equality import optSame, EQUAL from typhon.objects.user import Audition 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 (self.superGuard.call(u"supersetOf", [resultGuard]) is wrapBool(True))): return 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 False
def recv(self, atom, args): if atom is COMBINE_1: return self.combine(args[0]) if atom is GETSTARTCOL_0: return self.getStartCol() if atom is GETSTARTLINE_0: return self.getStartLine() if atom is GETENDCOL_0: return self.getEndCol() if atom is GETENDLINE_0: return self.getEndLine() if atom is ISONETOONE_0: return self.isOneToOne() if atom is NOTONETOONE_0: return self.notOneToOne() if atom is _UNCALL_0: from typhon.objects.collections.lists import ConstList from typhon.objects.collections.maps import EMPTY_MAP return ConstList([ makeSourceSpan, StrObject(u"run"), ConstList([wrapBool(self._isOneToOne), IntObject(self.startLine), IntObject(self.startCol), IntObject(self.endLine), IntObject(self.endCol)]), EMPTY_MAP]) raise Refused(self, atom, args)
def recv(self, atom, args): # Ints can be compared to ints and also to doubles. if atom is OP__CMP_1: try: other = unwrapInt(args[0]) return polyCmp(self._i, other) except WrongType: try: other = unwrapBigInt(args[0]) # This has to be switched around. if other.int_lt(self._i): return IntObject(1) elif other.int_gt(self._i): return IntObject(-1) else: # Using a property of integers here. return IntObject(0) except WrongType: other = unwrapDouble(args[0]) if math.isnan(other): # Whoa there! Gotta watch out for those pesky NaNs. return Incomparable return polyCmp(self._i, other) # Ints are usually used to store the results of comparisons. if atom is ABOVEZERO_0: return wrapBool(self._i > 0) if atom is ATLEASTZERO_0: return wrapBool(self._i >= 0) if atom is ATMOSTZERO_0: return wrapBool(self._i <= 0) if atom is BELOWZERO_0: return wrapBool(self._i < 0) if atom is ISZERO_0: return wrapBool(self._i == 0) if atom is ADD_1: other = args[0] try: i = unwrapInt(other) return IntObject(ovfcheck(self._i + i)) except OverflowError: i = unwrapInt(other) return BigInt(rbigint.fromint(self._i).int_add(i)) except WrongType: try: # Addition commutes. return BigInt(unwrapBigInt(other).int_add(self._i)) except WrongType: return DoubleObject(self._i + unwrapDouble(other)) if atom is AND_1: try: other = unwrapInt(args[0]) return IntObject(self._i & other) except WrongType: other = unwrapBigInt(args[0]) return BigInt(other.int_and_(self._i)) if atom is APPROXDIVIDE_1: # approxDivide/1: Promote both this int and its argument to # double, then perform division. d = float(self._i) other = promoteToDouble(args[0]) try: return DoubleObject(d / other) except ZeroDivisionError: # We tried to divide by zero. return NaN if atom is BITLENGTH_0: # bitLength/0: The number of bits required to store this integer. # Cribbed from PyPy. return IntObject(self.bitLength()) if atom is COMPLEMENT_0: return IntObject(~self._i) if atom is FLOORDIVIDE_1: try: other = unwrapInt(args[0]) return IntObject(self._i // other) except WrongType: other = unwrapBigInt(args[0]) bi = rbigint.fromint(self._i) return BigInt(bi.floordiv(other)) except ZeroDivisionError: raise userError(u"Integer division by zero") if atom is MAX_1: other = unwrapInt(args[0]) return self if self._i > other else args[0] if atom is MIN_1: other = unwrapInt(args[0]) return self if self._i < other else args[0] if atom is MODPOW_2: exponent = unwrapInt(args[0]) modulus = unwrapInt(args[1]) try: return self.intModPow(exponent, modulus) except OverflowError: return BigInt(rbigint.fromint(self._i).pow(rbigint.fromint(exponent), rbigint.fromint(modulus))) if atom is MOD_1: other = unwrapInt(args[0]) return IntObject(self._i % other) if atom is MULTIPLY_1: other = args[0] try: i = unwrapInt(other) return IntObject(ovfcheck(self._i * i)) except OverflowError: i = unwrapInt(other) return BigInt(rbigint.fromint(self._i).int_mul(i)) except WrongType: try: # Multiplication commutes. return BigInt(unwrapBigInt(other).int_mul(self._i)) except WrongType: return DoubleObject(self._i * unwrapDouble(other)) if atom is NEGATE_0: return IntObject(-self._i) if atom is NEXT_0: return IntObject(self._i + 1) if atom is OR_1: try: other = unwrapInt(args[0]) return IntObject(self._i | other) except WrongType: other = unwrapBigInt(args[0]) return BigInt(other.int_or_(self._i)) if atom is POW_1: other = unwrapInt(args[0]) try: return self.intPow(other) except OverflowError: return BigInt(rbigint.fromint(self._i).pow(rbigint.fromint(other))) if atom is PREVIOUS_0: return IntObject(self._i - 1) if atom is SHIFTLEFT_1: other = unwrapInt(args[0]) try: if other >= LONG_BIT: # Definite overflow won't always be detected by # ovfcheck(). Raise manually in this case. raise OverflowError return IntObject(ovfcheck(self._i << other)) except OverflowError: return BigInt(rbigint.fromint(self._i).lshift(other)) if atom is SHIFTRIGHT_1: other = unwrapInt(args[0]) if other >= LONG_BIT: # This'll underflow, returning who-knows-what when translated. # To keep things reasonable, we define an int that has been # right-shifted past word width to be 0, since every bit has # been shifted off. return IntObject(0) return IntObject(self._i >> other) if atom is SUBTRACT_1: other = args[0] try: i = unwrapInt(other) return IntObject(ovfcheck(self._i - i)) except OverflowError: i = unwrapInt(other) return BigInt(rbigint.fromint(self._i).int_sub(i)) except WrongType: try: # Subtraction doesn't commute, so we have to work a little # harder. bi = unwrapBigInt(other) return BigInt(rbigint.fromint(self._i).sub(bi)) except WrongType: return DoubleObject(self._i - unwrapDouble(other)) if atom is XOR_1: try: other = unwrapInt(args[0]) return IntObject(self._i ^ other) except WrongType: other = unwrapBigInt(args[0]) return BigInt(other.int_xor(self._i)) raise Refused(self, atom, args)
def isOneToOne(self): return wrapBool(self._isOneToOne)
def recv(self, atom, args): if atom is ADD_1: other = args[0] if isinstance(other, BytesObject): return BytesObject(self._bs + other._bs) if isinstance(other, IntObject): return BytesObject(self._bs + str(chr(other._i))) if atom is ASLIST_0: from typhon.objects.collections.lists import ConstList return ConstList(self.asList()) if atom is ASSET_0: from typhon.objects.collections.sets import ConstSet return ConstSet(self.asSet()) if atom is CONTAINS_1: needle = args[0] if isinstance(needle, IntObject): return wrapBool(chr(needle._i) in self._bs) if isinstance(needle, BytesObject): return wrapBool(needle._bs in self._bs) if atom is GET_1: index = unwrapInt(args[0]) if not 0 <= index < len(self._bs): raise userError(u"string.get/1: Index out of bounds: %d" % index) return IntObject(ord(self._bs[index])) if atom is INDEXOF_1: needle = unwrapBytes(args[0]) return IntObject(self._bs.find(needle)) if atom is INDEXOF_2: needle = unwrapBytes(args[0]) offset = unwrapInt(args[1]) if offset < 0: raise userError(u"indexOf/2: Negative offset %d not supported" % offset) return IntObject(self._bs.find(needle, offset)) if atom is JOIN_1: from typhon.objects.collections.lists import unwrapList return BytesObject(self.join(unwrapList(args[0]))) if atom is LASTINDEXOF_1: needle = unwrapBytes(args[0]) return IntObject(self._bs.rfind(needle)) if atom is MULTIPLY_1: amount = args[0] if isinstance(amount, IntObject): return BytesObject(self._bs * amount._i) if atom is OP__CMP_1: return polyCmp(self._bs, unwrapBytes(args[0])) if atom is REPLACE_2: return BytesObject(replace(self._bs, unwrapBytes(args[0]), unwrapBytes(args[1]))) if atom is SIZE_0: return IntObject(len(self._bs)) if atom is SLICE_1: start = unwrapInt(args[0]) if start < 0: raise userError(u"Slice start cannot be negative") return BytesObject(self._bs[start:]) if atom is SLICE_2: start = unwrapInt(args[0]) stop = unwrapInt(args[1]) if start < 0: raise userError(u"Slice start cannot be negative") if stop < 0: raise userError(u"Slice stop cannot be negative") return BytesObject(self._bs[start:stop]) if atom is SPLIT_1: from typhon.objects.collections.lists import ConstList return ConstList(self.split(unwrapBytes(args[0]))) if atom is SPLIT_2: from typhon.objects.collections.lists import ConstList return ConstList(self.split(unwrapBytes(args[0]), unwrapInt(args[1]))) if atom is TOLOWERCASE_0: return BytesObject(self.toLowerCase()) if atom is TOUPPERCASE_0: return BytesObject(self.toUpperCase()) if atom is TRIM_0: return BytesObject(self.trim()) if atom is WITH_1: return BytesObject(self._bs + chr(unwrapInt(args[0]))) if atom is _MAKEITERATOR_0: return bytesIterator(self._bs) raise Refused(self, atom, args)
def recv(self, atom, args): # Doubles can be compared. if atom is OP__CMP_1: other = promoteToDouble(args[0]) # NaN cannot compare equal to any float. if math.isnan(self._d) or math.isnan(other): return Incomparable return polyCmp(self._d, other) # Doubles are related to zero. if atom is ABOVEZERO_0: return wrapBool(self._d > 0.0) if atom is ATLEASTZERO_0: return wrapBool(self._d >= 0.0) if atom is ATMOSTZERO_0: return wrapBool(self._d <= 0.0) if atom is BELOWZERO_0: return wrapBool(self._d < 0.0) if atom is ISZERO_0: return wrapBool(self._d == 0.0) if atom is ABS_0: return DoubleObject(abs(self._d)) if atom is ADD_1: return self.add(args[0]) if atom is FLOOR_0: return IntObject(int(self._d)) if atom is MULTIPLY_1: return self.mul(args[0]) if atom is NEGATE_0: return DoubleObject(-self._d) if atom is SQRT_0: return DoubleObject(math.sqrt(self._d)) if atom is SUBTRACT_1: return self.subtract(args[0]) if atom is APPROXDIVIDE_1: divisor = promoteToDouble(args[0]) return DoubleObject(self._d / divisor) # Logarithms. if atom is LOG_0: return DoubleObject(math.log(self._d)) if atom is LOG_1: base = promoteToDouble(args[0]) return DoubleObject(math.log(self._d) / math.log(base)) # Trigonometry. if atom is SIN_0: return DoubleObject(math.sin(self._d)) if atom is COS_0: return DoubleObject(math.cos(self._d)) if atom is TAN_0: return DoubleObject(math.tan(self._d)) if atom is TOBYTES_0: result = [] pack_float(result, self._d, 8, True) return BytesObject(result[0]) raise Refused(self, atom, args)
def testUnwrapBoolPromise(self): with scopedVat(testingVat()): p = makeNear(wrapBool(False)) self.assertFalse(unwrapBool(p))
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)
def recv(self, atom, args): if atom is RUN_1: return wrapBool(self.resolver.smash(args[0])) raise Refused(self, atom, args)
def recv(self, atom, args): if atom is BROKEN_1: return self.broken(args[0]) if atom is FULFILLMENT_1: return self.fulfillment(args[0]) if atom is ISBROKEN_1: return wrapBool(self.isBroken(args[0])) if atom is ISDEEPFROZEN_1: return wrapBool(self.isDeepFrozen(args[0])) if atom is ISEVENTUAL_1: return wrapBool(self.isEventual(args[0])) if atom is ISNEAR_1: return wrapBool(self.isNear(args[0])) if atom is ISFAR_1: return wrapBool(self.isFar(args[0])) if atom is ISRESOLVED_1: return wrapBool(isResolved(args[0])) if atom is ISSELFISH_1: return wrapBool(self.isSelfish(args[0])) if atom is ISSELFLESS_1: return wrapBool(self.isSelfless(args[0])) if atom is ISSETTLED_1: from typhon.objects.equality import isSettled return wrapBool(isSettled(args[0])) if atom is MAKEPROXY_3: from typhon.objects.proxy import makeProxy return makeProxy(args[0], args[1], args[2]) if atom is OPTPROBLEM_1: ref = args[0] if isinstance(ref, Promise): return ref.optProblem() return NullObject if atom is PROMISE_0: return self.promise() # Inlined for name clash reasons. if atom is STATE_1: o = args[0] if isinstance(o, Promise): s = o.state() else: s = NEAR return StrObject(s.repr) if atom is WHENBROKEN_2: return self.whenBroken(args[0], args[1]) if atom is WHENRESOLVED_2: return self.whenResolved(args[0], args[1]) if atom is WHENRESOLVEDONLY_2: return self.whenResolvedOnly(args[0], args[1]) raise Refused(self, atom, args)
def deepFrozenSupersetOf(guard): from typhon.objects.collections.helpers import monteMap from typhon.objects.collections.lists import unwrapList from typhon.objects.constants import wrapBool from typhon.objects.ejectors import Ejector from typhon.objects.refs import Promise from typhon.objects.guards import (AnyOfGuard, BoolGuard, BytesGuard, CharGuard, DoubleGuard, FinalSlotGuard, IntGuard, SameGuard, StrGuard, SubrangeGuard, VoidGuard) from typhon.prelude import getGlobalValue if guard is deepFrozenGuard: return True if guard is deepFrozenStamp: return True if isinstance(guard, Promise): guard = guard.resolution() if isinstance(guard, BoolGuard): return True if isinstance(guard, BytesGuard): return True if isinstance(guard, CharGuard): return True if isinstance(guard, DoubleGuard): return True if isinstance(guard, IntGuard): return True if isinstance(guard, StrGuard): return True if isinstance(guard, VoidGuard): return True if isinstance(guard, SameGuard): with Ejector() as ej: try: v = guard.value checkDeepFrozen(v, monteMap(), ej, v) return True except Ejecting: return False if isinstance(guard, FinalSlotGuard): return deepFrozenSupersetOf(guard.valueGuard) for superGuardName in [u"List", u"NullOk", u"Set"]: superGuard = getGlobalValue(superGuardName) if superGuard is None: continue with Ejector() as ej: try: subGuard = superGuard.call(u"extractGuard", [guard, ej]) return deepFrozenSupersetOf(subGuard) except Ejecting as e: # Just keep going. if e.ejector is not ej: raise for pairGuardName in [u"Map", u"Pair"]: pairGuard = getGlobalValue(pairGuardName) if pairGuard is None: continue with Ejector() as ej: try: guardPair = pairGuard.call(u"extractGuards", [guard, ej]) l = unwrapList(guardPair, ej) if len(l) == 2: return deepFrozenSupersetOf(l[0]) and deepFrozenSupersetOf( l[1]) except Ejecting as e: if e.ejector is not ej: raise if (SubrangeGuard(deepFrozenGuard).call(u"passes", [guard]) is wrapBool(True)): return True if isinstance(guard, AnyOfGuard): for g in guard.subguards: if not deepFrozenSupersetOf(g): return False return True return False
def isDone(self): return wrapBool(self._ref is None)
def optSame(self, first, second): result = optSame(first, second) if result is NOTYET: return NullObject return wrapBool(result is EQUAL)
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
def recv(self, atom, args): from typhon.objects.constants import wrapBool if atom is AUDIT_1: return wrapBool(True) raise Refused(self, atom, args)
def deepFrozenSupersetOf(guard): from typhon.objects.collections.helpers import monteMap from typhon.objects.collections.lists import ConstList from typhon.objects.constants import wrapBool from typhon.objects.ejectors import Ejector from typhon.objects.refs import Promise from typhon.objects.guards import ( AnyOfGuard, BoolGuard, BytesGuard, CharGuard, DoubleGuard, FinalSlotGuard, IntGuard, SameGuard, StrGuard, SubrangeGuard, VoidGuard) from typhon.prelude import getGlobalValue if guard is deepFrozenGuard: return True if guard is deepFrozenStamp: return True if isinstance(guard, Promise): guard = guard.resolution() if isinstance(guard, BoolGuard): return True if isinstance(guard, BytesGuard): return True if isinstance(guard, CharGuard): return True if isinstance(guard, DoubleGuard): return True if isinstance(guard, IntGuard): return True if isinstance(guard, StrGuard): return True if isinstance(guard, VoidGuard): return True if isinstance(guard, SameGuard): ej = Ejector() try: v = guard.value checkDeepFrozen(v, monteMap(), ej, v) return True except Ejecting: return False if isinstance(guard, FinalSlotGuard): return deepFrozenSupersetOf(guard.valueGuard) for superGuardName in [u"List", u"NullOk", u"Set"]: superGuard = getGlobalValue(superGuardName) if superGuard is None: continue ej = Ejector() try: subGuard = superGuard.call(u"extractGuard", [guard, ej]) return deepFrozenSupersetOf(subGuard) except Ejecting: # XXX lets other ejectors get through pass for pairGuardName in [u"Map", u"Pair"]: pairGuard = getGlobalValue(pairGuardName) if pairGuard is None: continue ej = Ejector() try: guardPair = pairGuard.call(u"extractGuards", [guard, ej]) if isinstance(guardPair, ConstList) and guardPair.size() == 2: return ( (deepFrozenSupersetOf(guardPair.strategy.fetch( guardPair, 0))) and (deepFrozenSupersetOf(guardPair.strategy.fetch( guardPair, 1)))) except Ejecting: # XXX lets other ejectors get through pass if (SubrangeGuard(deepFrozenGuard).call(u"passes", [guard]) is wrapBool(True)): return True if isinstance(guard, AnyOfGuard): for g in guard.subguards: if not deepFrozenSupersetOf(g): return False return True return False
def testResolveNear(self): with scopedVat(testingVat()): p = makeNear(wrapBool(False)) self.assertFalse(resolution(p).isTrue())