internal static PythonTuple ReduceProtocol0(CodeContext /*!*/ context, object self) { // CPython implements this in copyreg._reduce_ex PythonType myType = DynamicHelpers.GetPythonType(self); // PEP 307 calls this "D" ThrowIfNativelyPickable(myType); object?getState; bool hasGetState = PythonOps.TryGetBoundAttr(context, self, "__getstate__", out getState); if (PythonOps.TryGetBoundAttr(context, myType, "__slots__", out object?slots) && PythonOps.Length(slots) > 0 && !hasGetState) { // ??? does this work with superclass slots? throw PythonOps.TypeError("a class that defines __slots__ without defining __getstate__ cannot be pickled with protocols 0 or 1"); } PythonType closestNonPythonBase = FindClosestNonPythonBase(myType); // PEP 307 calls this "B" object func = context.LanguageContext.PythonReconstructor; object funcArgs = PythonTuple.MakeTuple( myType, closestNonPythonBase, TypeCache.Object == closestNonPythonBase ? null : PythonCalls.Call(context, closestNonPythonBase, self) ); object?state; if (hasGetState) { state = PythonOps.CallWithContext(context, getState); } else { if (self is IPythonObject ipo) { state = ipo.Dict; } else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out state)) { state = null; } } if (!PythonOps.IsTrue(state)) { state = null; } return(PythonTuple.MakeTuple(func, funcArgs, state)); }
internal static void AppendJoin(object value, int index, List <byte> byteList) { IList <byte> bytesValue; string strValue; if ((bytesValue = value as IList <byte>) != null) { byteList.AddRange(bytesValue); } else if ((strValue = value as string) != null) { byteList.AddRange(strValue.MakeByteArray()); } else { throw PythonOps.TypeError("sequence item {0}: expected bytes or byte array, {1} found", index.ToString(), PythonOps.GetPythonTypeName(value)); } }
internal static void AppendJoin(object value, int index, List <byte> byteList) { if (value is IList <byte> bytesValue) { byteList.AddRange(bytesValue); } else { throw PythonOps.TypeError("sequence item {0}: expected bytes or byte array, {1} found", index.ToString(), PythonOps.GetPythonTypeName(value)); } }
public static string __str__(CodeContext /*!*/ context, object o) { return(PythonOps.Repr(context, o)); }
private static PythonTuple ReduceProtocol2(CodeContext /*!*/ context, object self) { // builtin types which can't be pickled (due to tp_itemsize != 0) if (self is MemoryView) { throw PythonOps.TypeError("can't pickle memoryview objects"); } PythonType myType = DynamicHelpers.GetPythonType(self); object?state; object?[] funcArgs; var copyreg = context.LanguageContext.GetCopyRegModule(); var func = PythonOps.GetBoundAttr(context, copyreg, "__newobj__"); if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out object?getNewArgsCallable)) { // TypeError will bubble up if __getnewargs__ isn't callable if (!(PythonOps.CallWithContext(context, getNewArgsCallable, self) is PythonTuple newArgs)) { throw PythonOps.TypeError("__getnewargs__ should return a tuple"); } funcArgs = new object[1 + newArgs.Count]; funcArgs[0] = myType; for (int i = 0; i < newArgs.Count; i++) { funcArgs[i + 1] = newArgs[i]; } } else { funcArgs = new object[] { myType }; } if (!PythonTypeOps.TryInvokeUnaryOperator(context, self, "__getstate__", out state)) { object?dict; if (self is IPythonObject ipo) { dict = ipo.Dict; } else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out dict)) { dict = null; } PythonDictionary?initializedSlotValues = GetInitializedSlotValues(self); if (initializedSlotValues != null && initializedSlotValues.Count == 0) { initializedSlotValues = null; } if (dict == null && initializedSlotValues == null) { state = null; } else if (dict != null && initializedSlotValues == null) { state = dict; } else if (dict != null && initializedSlotValues != null) { state = PythonTuple.MakeTuple(dict, initializedSlotValues); } else /*dict == null && initializedSlotValues != null*/ state {
public static bool LessThan(Complex x, Complex y) { throw PythonOps.TypeError("complex is not an ordered type"); }
public static object __new__( CodeContext context, PythonType cls, [DefaultParameterValue(null)] object real, [DefaultParameterValue(null)] object imag ) { Complex real2, imag2; real2 = imag2 = new Complex(); if (real == null && imag == null && cls == TypeCache.Complex) { throw PythonOps.TypeError("argument must be a string or a number"); } if (imag != null) { if (real is string) { throw PythonOps.TypeError("complex() can't take second arg if first is a string"); } if (imag is string) { throw PythonOps.TypeError("complex() second arg can't be a string"); } imag2 = Converter.ConvertToComplex(imag); } if (real != null) { if (real is string) { real2 = LiteralParser.ParseComplex((string)real); } else if (real is Extensible <string> ) { real2 = LiteralParser.ParseComplex(((Extensible <string>)real).Value); } else if (real is Complex) { if (imag == null && cls == TypeCache.Complex) { return(real); } else { real2 = (Complex)real; } } else { real2 = Converter.ConvertToComplex(real); } } double real3 = real2.Real - imag2.Imaginary(); double imag3 = real2.Imaginary() + imag2.Real; if (cls == TypeCache.Complex) { return(new Complex(real3, imag3)); } else { return(cls.CreateInstance(context, real3, imag3)); } }
// 3.0-only public static object IterMethodForBytes(Bytes self) { return(PythonOps.BytesIntEnumerator(self)); }
public static string SimpleRepr(object self) { return(String.Format("<{0} object at {1}>", PythonTypeOps.GetName(self), PythonOps.HexId(self))); }
public static object __new__(CodeContext context, PythonType cls, object x) { Extensible <string> es; if (x is string) { return(ReturnObject(context, cls, ParseBigIntegerSign((string)x, 10))); } else if ((es = x as Extensible <string>) != null) { object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out value)) { return(ReturnObject(context, cls, (BigInteger)value)); } return(ReturnObject(context, cls, ParseBigIntegerSign(es.Value, 10))); } if (x is double) { return(ReturnObject(context, cls, DoubleOps.__long__((double)x))); } if (x is int) { return(ReturnObject(context, cls, (BigInteger)(int)x)); } if (x is BigInteger) { return(ReturnObject(context, cls, x)); } if (x is Complex) { throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))"); } if (x is decimal) { return(ReturnObject(context, cls, (BigInteger)(decimal)x)); } object result; int intRes; BigInteger bigintRes; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out result) && !Object.ReferenceEquals(result, NotImplementedType.Value)) { if (result is int || result is BigInteger || result is Extensible <int> || result is Extensible <BigInteger> ) { return(ReturnObject(context, cls, result)); } else { throw PythonOps.TypeError("__long__ returned non-long (type {0})", PythonTypeOps.GetName(result)); } } else if (PythonOps.TryGetBoundAttr(context, x, "__trunc__", out result)) { result = PythonOps.CallWithContext(context, result); if (Converter.TryConvertToInt32(result, out intRes)) { return(ReturnObject(context, cls, (BigInteger)intRes)); } else if (Converter.TryConvertToBigInteger(result, out bigintRes)) { return(ReturnObject(context, cls, bigintRes)); } else { throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonTypeOps.GetName(result)); } } throw PythonOps.TypeError("long() argument must be a string or a number, not '{0}'", DynamicHelpers.GetPythonType(x).Name); }
// 3.0-only public static object IterMethodForString(string self) { return(PythonOps.StringEnumerator(self)); }
private static BigInteger DivMod(BigInteger x, BigInteger y, out BigInteger r) { BigInteger rr; BigInteger qq; #if !FEATURE_NUMERICS if (Object.ReferenceEquals(x, null)) { throw PythonOps.TypeError("unsupported operands for div/mod: NoneType and long"); } if (Object.ReferenceEquals(y, null)) { throw PythonOps.TypeError("unsupported operands for div/mod: long and NoneType"); } #endif qq = BigInteger.DivRem(x, y, out rr); if (x >= BigInteger.Zero) { if (y > BigInteger.Zero) { r = rr; return(qq); } else { if (rr == BigInteger.Zero) { r = rr; return(qq); } else { r = rr + y; return(qq - BigInteger.One); } } } else { if (y > BigInteger.Zero) { if (rr == BigInteger.Zero) { r = rr; return(qq); } else { r = rr + y; return(qq - BigInteger.One); } } else { r = rr; return(qq); } } }
public void WriteObject(object o) { List <object> infinite = PythonOps.GetReprInfinite(); if (infinite.Contains(o)) { throw PythonOps.ValueError("Marshaled data contains infinite cycle"); } int index = infinite.Count; infinite.Add(o); try { if (o == null) { _bytes.Add((byte)'N'); } else if (o == ScriptingRuntimeHelpers.True || (o is bool && (bool)o)) { _bytes.Add((byte)'T'); } else if (o == ScriptingRuntimeHelpers.False || (o is bool && (!(bool)o))) { _bytes.Add((byte)'F'); } else if (o is IList <byte> ) { WriteBytes(o as IList <byte>); } else if (o is string) { WriteString(o as string); } else if (o is int) { WriteInt((int)o); } else if (o is float) { WriteFloat((float)o); } else if (o is double) { WriteFloat((double)o); } else if (o is long) { WriteLong((long)o); } else if (o.GetType() == typeof(PythonList)) { WriteList(o); } else if (o.GetType() == typeof(PythonDictionary)) { WriteDict(o); } else if (o.GetType() == typeof(PythonTuple)) { WriteTuple(o); } else if (o.GetType() == typeof(SetCollection)) { WriteSet(o); } else if (o.GetType() == typeof(FrozenSetCollection)) { WriteFrozenSet(o); } else if (o is BigInteger) { WriteInteger((BigInteger)o); } else if (o is Complex) { WriteComplex((Complex)o); } else if (o == PythonExceptions.StopIteration) { WriteStopIteration(); } else { throw PythonOps.ValueError("unmarshallable object " + o.GetType().ToString()); } } finally { infinite.RemoveAt(index); } }
public object ReadObject() { while (_myBytes.MoveNext()) { byte cur = _myBytes.Current; object res; switch ((char)cur) { case '(': PushStack(StackType.Tuple); break; case '[': PushStack(StackType.List); break; case '{': PushStack(StackType.Dict); break; case '<': PushStack(StackType.Set); break; case '>': PushStack(StackType.FrozenSet); break; case '0': // end of dictionary if (_stack == null || _stack.Count == 0) { throw PythonOps.ValueError("bad marshal data"); } _stack.Peek().StackCount = 0; break; // case 'c': break; default: res = YieldSimple(); if (_stack == null) { return(res); } do { res = UpdateStack(res); } while (res != null && _stack.Count > 0); if (_stack.Count == 0) { return(_result); } continue; } // handle empty lists/tuples... if (_stack != null && _stack.Count > 0 && _stack.Peek().StackCount == 0) { ProcStack ps = _stack.Pop(); res = ps.StackObj; if (ps.StackType == StackType.Tuple) { res = PythonTuple.Make(res); } else if (ps.StackType == StackType.FrozenSet) { res = FrozenSetCollection.Make(TypeCache.FrozenSet, res); } if (_stack.Count > 0) { // empty list/tuple do { res = UpdateStack(res); } while (res != null && _stack.Count > 0); if (_stack.Count == 0) { break; } } else { _result = res; break; } } } return(_result); }
public static int __int__(Complex self) { throw PythonOps.TypeError(" can't convert complex to int; use int(abs(z))"); }
public static string FancyRepr(object self) { PythonType pt = (PythonType)DynamicHelpers.GetPythonType(self); // we can't call ToString on a UserType because we'll stack overflow, so // only do FancyRepr for reflected types. if (pt.IsSystemType) { string toStr = self.ToString(); if (toStr == null) { toStr = String.Empty; } // get the type name to display (CLI name or Python name) Type type = pt.UnderlyingSystemType; string typeName = type.FullName; // Get the underlying .ToString() representation. Truncate multiple // lines, and don't display it if it's object's default representation (type name) // skip initial empty lines: int i = 0; while (i < toStr.Length && (toStr[i] == '\r' || toStr[i] == '\n')) { i++; } // read the first non-empty line: int j = i; while (j < toStr.Length && toStr[j] != '\r' && toStr[j] != '\n') { j++; } // skip following empty lines: int k = j; while (k < toStr.Length && (toStr[k] == '\r' || toStr[k] == '\n')) { k++; } if (j > i) { string first_non_empty_line = toStr.Substring(i, j - i); bool has_multiple_non_empty_lines = k < toStr.Length; return(String.Format("<{0} object at {1} [{2}{3}]>", typeName, PythonOps.HexId(self), first_non_empty_line, has_multiple_non_empty_lines ? "..." : String.Empty)); } else { return(String.Format("<{0} object at {1}>", typeName, PythonOps.HexId(self))); } } return(SimpleRepr(self)); }
public static BigInteger __long__(Complex self) { throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))"); }
public static BigInteger op_RightShift(BigInteger x, int y) { if (y < 0) { throw PythonOps.ValueError("negative shift count"); } return x >> y; }
public static bool GreaterThanOrEqual(Complex x, Complex y) { throw PythonOps.TypeError("complex is not an ordered type"); }
public static string/*!*/ __format__(CodeContext/*!*/ context, BigInteger/*!*/ self, [NotNull]string/*!*/ formatSpec) { StringFormatSpec spec = StringFormatSpec.FromString(formatSpec); if (spec.Precision != null) { throw PythonOps.ValueError("Precision not allowed in integer format specifier"); } BigInteger val = self; if (self < 0) { val = -self; } string digits; switch (spec.Type) { case 'n': CultureInfo culture = context.LanguageContext.NumericCulture; if (culture == CultureInfo.InvariantCulture) { // invariant culture maps to CPython's C culture, which doesn't // include any formatting info. goto case 'd'; } digits = FormattingHelper.ToCultureString(val, context.LanguageContext.NumericCulture.NumberFormat, spec); break; case null: case 'd': if (spec.ThousandsComma) { var width = spec.Width ?? 0; // If we're inserting commas, and we're padding with leading zeros. // AlignNumericText won't know where to place the commas, // so force .Net to help us out here. if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) { digits = val.ToString(FormattingHelper.ToCultureString(self, FormattingHelper.InvariantCommaNumberInfo, spec)); } else { digits = val.ToString("#,0", CultureInfo.InvariantCulture); } } else { digits = val.ToString("D", CultureInfo.InvariantCulture); } break; case '%': if (spec.ThousandsComma) { digits = val.ToString("#,0.000000%", CultureInfo.InvariantCulture); } else { digits = val.ToString("0.000000%", CultureInfo.InvariantCulture); } break; case 'e': if (spec.ThousandsComma) { digits = val.ToString("#,0.000000e+00", CultureInfo.InvariantCulture); } else { digits = val.ToString("0.000000e+00", CultureInfo.InvariantCulture); } break; case 'E': if (spec.ThousandsComma) { digits = val.ToString("#,0.000000E+00", CultureInfo.InvariantCulture); } else { digits = val.ToString("0.000000E+00", CultureInfo.InvariantCulture); } break; case 'f': case 'F': if (spec.ThousandsComma) { digits = val.ToString("#,########0.000000", CultureInfo.InvariantCulture); } else { digits = val.ToString("#########0.000000", CultureInfo.InvariantCulture); } break; case 'g': if (val >= 1000000) { digits = val.ToString("0.#####e+00", CultureInfo.InvariantCulture); } else if (spec.ThousandsComma) { goto case 'd'; } else { digits = val.ToString(CultureInfo.InvariantCulture); } break; case 'G': if (val >= 1000000) { digits = val.ToString("0.#####E+00", CultureInfo.InvariantCulture); } else if (spec.ThousandsComma) { goto case 'd'; } else { digits = val.ToString(CultureInfo.InvariantCulture); } break; case 'X': digits = AbsToHex(val, false); break; case 'x': digits = AbsToHex(val, true); break; case 'o': // octal digits = ToOctal(val, true); break; case 'b': // binary digits = ToBinary(val, false, true); break; case 'c': // single char int iVal; if (spec.Sign != null) { throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'"); } else if (!self.AsInt32(out iVal)) { throw PythonOps.OverflowError("long int too large to convert to int"); } else if(iVal < 0 || iVal > 0x10ffff) { throw PythonOps.OverflowError("%c arg not in range(0x110000)"); } digits = (iVal > char.MaxValue) ? char.ConvertFromUtf32(iVal) : ScriptingRuntimeHelpers.CharToString((char)iVal); break; default: throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'int'", spec.TypeRepr); } Debug.Assert(digits[0] != '-'); return spec.AlignNumericText(digits, self.IsZero(), self.IsPositive()); }
public static string __repr__(object self) { return($"<{PythonOps.GetPythonTypeName(self)} object at {PythonOps.HexId(self)}>"); }
public static Complex FloorDivide(CodeContext context, Complex x, Complex y) { throw PythonOps.TypeError("can't take floor of complex number"); }
public static string __format__(CodeContext /*!*/ context, object self, [NotNone] string /*!*/ formatSpec) { if (formatSpec != string.Empty) { throw PythonOps.TypeError("unsupported format string passed to {0}.__format__", PythonOps.GetPythonTypeName(self)); } return(PythonOps.ToString(context, self)); }
public static Complex Mod(CodeContext context, Complex x, Complex y) { throw PythonOps.TypeError("can't mod complex numbers"); }
public static object __getattribute__(CodeContext /*!*/ context, object self, string name) { return(PythonOps.ObjectGetAttribute(context, self, name)); }
public static PythonTuple DivMod(CodeContext context, Complex x, Complex y) { throw PythonOps.TypeError("can't take floor or mod of complex number"); }
internal static byte GetByte(object o) { Extensible <int> ei; Extensible <BigInteger> ebi; Extensible <double> ed; int i; if (o is int) { return(((int)o).ToByteChecked()); } else if (o is BigInteger) { return(((BigInteger)o).ToByteChecked()); } else if (o is double) { return(((double)o).ToByteChecked()); } else if ((ei = o as Extensible <int>) != null) { return(ei.Value.ToByteChecked()); } else if (!Object.ReferenceEquals(ebi = o as Extensible <BigInteger>, null)) { return(ebi.Value.ToByteChecked()); } else if (!Object.ReferenceEquals(ed = o as Extensible <double>, null)) { return(ed.Value.ToByteChecked()); } else if (o is byte) { return((byte)o); } else if (o is sbyte) { return(((int)(sbyte)o).ToByteChecked()); } else if (o is char) { return(((int)(char)o).ToByteChecked()); } else if (o is short) { return(((int)(short)o).ToByteChecked()); } else if (o is ushort) { return(((int)(ushort)o).ToByteChecked()); } else if (o is uint) { return(((BigInteger)(uint)o).ToByteChecked()); } else if (o is float) { return(((double)(float)o).ToByteChecked()); } else if (Converter.TryConvertToIndex(o, out i)) { return(i.ToByteChecked()); } else { throw PythonOps.TypeError("an integer or string of size 1 is required"); } }
// report the same errors as CPython for these invalid conversions public static double __float__(Complex self) { throw PythonOps.TypeError("can't convert complex to float; use abs(z)"); }
public static bool __new__(object cls, object o) { return(PythonOps.IsTrue(o)); }
public static string __repr__(object self) { return($"<{DynamicHelpers.GetPythonType(self).Name} object at {PythonOps.HexId(self)}>"); }