Exemple #1
0
        public static object __new__(CodeContext context, PythonType cls, string s, int radix) {
            int start = 0;
            if (radix == 16 || radix == 8 || radix == 2) {
                start = s.Length - Int32Ops.TrimRadix(s, radix).Length;
            }

            if (cls == TypeCache.BigInteger) {
                return ParseBigIntegerSign(s, radix, start);
            } else {
                BigInteger res = ParseBigIntegerSign(s, radix);
                return cls.CreateInstance(context, res);
            }
        }
        public static object __new__(CodeContext /*!*/ context, PythonType cls, object x)
        {
            object value = NewFloat(context, TypeCache.Double, x);

            if (cls == TypeCache.Double)
            {
                return(value);
            }
            else
            {
                return(cls.CreateInstance(context, value));
            }
        }
Exemple #3
0
        public static object __new__(CodeContext context, PythonType cls, string s, int radix)
        {
            var value = LiteralParser.ParseBigIntegerSign(s, radix, Int32Ops.FindStart(s, radix));

            if (cls == TypeCache.BigInteger)
            {
                return(value);
            }
            else
            {
                return(cls.CreateInstance(context, value));
            }
        }
Exemple #4
0
        public static object DefaultNew(CodeContext context, PythonType type\u00F8, params object[] args\u00F8)
        {
            if (type\u00F8 == null)
            {
                throw PythonOps.TypeError(
                          "__new__ expected type object, got {0}",
                          PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))
                          );
            }

            CheckNewArgs(context, null, args\u00F8, type\u00F8);

            return(type\u00F8.CreateInstance(context));
        }
Exemple #5
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, object x)
        {
            object value = null;

            if (x is string)
            {
                value = ParseFloat((string)x);
            }
            else if (x is Extensible <string> )
            {
                if (!PythonTypeOps.TryInvokeUnaryOperator(context, x, "__float__", out value))
                {
                    value = ParseFloat(((Extensible <string>)x).Value);
                }
            }
            else if (x is char)
            {
                value = ParseFloat(ScriptingRuntimeHelpers.CharToString((char)x));
            }
            else if (x is Complex)
            {
                throw PythonOps.TypeError("can't convert complex to float; use abs(z)");
            }
            else
            {
                object d = PythonOps.CallWithContext(context, PythonOps.GetBoundAttr(context, x, "__float__"));
                if (d is double)
                {
                    value = d;
                }
                else if (d is Extensible <double> )
                {
                    value = ((Extensible <double>)d).Value;
                }
                else
                {
                    throw PythonOps.TypeError("__float__ returned non-float (type {0})", PythonTypeOps.GetName(d));
                }
            }

            if (cls == TypeCache.Double)
            {
                return(value);
            }
            else
            {
                return(cls.CreateInstance(context, value));
            }
        }
Exemple #6
0
        public static object NonDefaultNewKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary <object, object> kwargs\u00F8, params object[] args\u00F8)
        {
            if (type\u00F8 == null)
            {
                throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8)));
            }
            if (args\u00F8 == null)
            {
                args\u00F8 = new object[1];
            }

            string [] names;
            GetKeywordArgs(kwargs\u00F8, args\u00F8, out args\u00F8, out names);
            return(type\u00F8.CreateInstance(context, args\u00F8, names));
        }
Exemple #7
0
 public static object __new__(CodeContext context, PythonType cls, object @object, object callback)
 {
     if (callback == null)
     {
         return(__new__(context, cls, @object));
     }
     if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(@ref)))
     {
         return(new @ref(context, @object, callback));
     }
     else
     {
         return(cls.CreateInstance(context, @object, callback));
     }
 }
Exemple #8
0
        public static object __new__(CodeContext context, PythonType cls, Extensible <double> o)
        {
            object value;

            // always succeeds as float defines __int__
            PythonTypeOps.TryInvokeUnaryOperator(context, o, "__int__", out value);
            if (cls == TypeCache.Int32)
            {
                return((int)value);
            }
            else
            {
                return(cls.CreateInstance(context, value));
            }
        }
Exemple #9
0
        public static object __new__(CodeContext/*!*/ context, PythonType cls, IList<byte> s, int @base=10) {
            object value;
            IPythonObject po = s as IPythonObject;
            if (po == null ||
                !PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__long__", out value)) {
                    value = ParseBigIntegerSign(s.MakeString(), @base);
            }

            if (cls == TypeCache.BigInteger) {
                return value;
            } else {
                // derived long creation...
                return cls.CreateInstance(context, value);
            }
        }
Exemple #10
0
        private static array ArrayReconstructor(CodeContext context, [NotNull] PythonType cls, [NotNull] string typecode, int mformat_code, [NotNull] Bytes items)
        {
            if (typecode.Length != 1)
            {
                throw PythonOps.TypeError("expected character, got {0}", PythonTypeOps.GetName(typecode));
            }
            if (!typecodes.Contains(typecode))
            {
                throw PythonOps.ValueError("bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
            }

            var actualTypeCode = MachineFormatToTypeCode(mformat_code, out bool isBigEndian, out string?encoding);

            var arrayType = DynamicHelpers.GetPythonTypeFromType(typeof(array));

            if (!cls.IsSubclassOf(arrayType))
            {
                throw PythonOps.TypeError($"{cls} is not a subtype of array.array");
            }

            array res;

            if (cls == arrayType)
            {
                res = new array(actualTypeCode);
            }
            else if (cls.CreateInstance(context, actualTypeCode) is array arr)
            {
                res = arr;
            }
            else
            {
                throw PythonOps.TypeError($"{cls} is not a subtype of array.array");
            }

            if (encoding == null)
            {
                res.frombytes(items);
                if (isBigEndian)
                {
                    res.byteswap();
                }
            }
            else
            {
                res.fromunicode(context, StringOps.RawDecode(context, items, encoding, null));
            }
            return(res);
Exemple #11
0
 public static struct_time __new__(CodeContext context, PythonType cls, int year, int month, int day, int hour, int minute, int second, int dayOfWeek, int dayOfYear, int isDst)
 {
     if (cls == _StructTimeType)
     {
         return(new struct_time(year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst));
     }
     else
     {
         struct_time st = cls.CreateInstance(context, year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst) as struct_time;
         if (st == null)
         {
             throw PythonOps.TypeError("{0} is not a subclass of time.struct_time", cls);
         }
         return(st);
     }
 }
Exemple #12
0
 public static FrozenSetCollection __new__(CodeContext /*!*/ context, [NotNull] PythonType cls, object?set)
 {
     if (cls == TypeCache.FrozenSet)
     {
         return(Make(set));
     }
     else
     {
         object res = cls.CreateInstance(context, set);
         if (res is FrozenSetCollection fs)
         {
             return(fs);
         }
         throw PythonOps.TypeError("{0} is not a subclass of frozenset", res);
     }
 }
Exemple #13
0
        public static object __new__(CodeContext context, PythonType cls, object x)
        {
            object value = FastNew(context, x);

            if (cls == TypeCache.Int32)
            {
                return(value);
            }
            else
            {
                ValidateType(cls);

                // derived int creation...
                return(cls.CreateInstance(context, value));
            }
        }
Exemple #14
0
 public static struct_time __new__(CodeContext context, PythonType cls, [NotNull] PythonTuple sequence)
 {
     if (sequence.__len__() != 9)
     {
         throw PythonOps.TypeError("time.struct_time() takes a 9-sequence ({0}-sequence given)", sequence.__len__());
     }
     if (cls == _StructTimeType)
     {
         return(new struct_time(sequence));
     }
     if (cls.CreateInstance(context, sequence) is struct_time st)
     {
         return(st);
     }
     throw PythonOps.TypeError("{0} is not a subclass of time.struct_time", cls);
 }
Exemple #15
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, IList <byte> s)
        {
            if (cls == TypeCache.BigInteger)
            {
                object        value;
                IPythonObject po = s as IPythonObject;
                if (po != null &&
                    PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__long__", out value))
                {
                    return(value);
                }

                return(ParseBigIntegerSign(s.MakeString(), 10));
            }

            return(cls.CreateInstance(context, ParseBigIntegerSign(s.MakeString(), 10)));
        }
Exemple #16
0
        /// <summary>
        /// Implementation of our cast function.  data is marshalled as a void*
        /// so it ends up as an address.  obj and type are marshalled as an object
        /// so we need to unmarshal them.
        /// </summary>
        private static IntPtr Cast(IntPtr data, IntPtr obj, IntPtr type)
        {
            GCHandle objHandle  = GCHandle.FromIntPtr(obj);
            GCHandle typeHandle = GCHandle.FromIntPtr(type);

            try {
                CData      cdata = objHandle.Target as CData;
                PythonType pt    = (PythonType)typeHandle.Target;

                CData res = (CData)pt.CreateInstance(pt.Context.SharedContext);
                if (IsPointer(pt))
                {
                    res.MemHolder = new MemoryHolder(IntPtr.Size);
                    if (IsPointer(DynamicHelpers.GetPythonType(cdata)))
                    {
                        res.MemHolder.WriteIntPtr(0, cdata.MemHolder.ReadIntPtr(0));
                    }
                    else
                    {
                        res.MemHolder.WriteIntPtr(0, data);
                    }

                    if (cdata != null)
                    {
                        res.MemHolder.Objects = cdata.MemHolder.Objects;
                        res.MemHolder.AddObject(IdDispenser.GetId(cdata), cdata);
                    }
                }
                else
                {
                    if (cdata != null)
                    {
                        res.MemHolder = new MemoryHolder(data, ((INativeType)pt).Size, cdata.MemHolder);
                    }
                    else
                    {
                        res.MemHolder = new MemoryHolder(data, ((INativeType)pt).Size);
                    }
                }

                return(GCHandle.ToIntPtr(GCHandle.Alloc(res)));
            } finally {
                typeHandle.Free();
                objHandle.Free();
            }
        }
Exemple #17
0
            public static chain from_iterable(CodeContext /*!*/ context, PythonType cls, object iterables)
            {
                chain res;

                if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(chain)))
                {
                    res = new chain();
                    res.InnerEnumerator = LazyYielder(iterables);
                }
                else
                {
                    res = (chain)cls.CreateInstance(context);
                    res.InnerEnumerator = LazyYielder(iterables);
                }

                return(res);
            }
Exemple #18
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, IList <byte> s)
        {
            if (cls == TypeCache.Int32)
            {
                object        value;
                IPythonObject po = s as IPythonObject;
                if (po != null &&
                    PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__int__", out value))
                {
                    return(value);
                }

                return(FastNew(context, s.MakeString()));
            }

            ValidateType(cls);

            // derived int creation...
            return(cls.CreateInstance(context, FastNew(context, s.MakeString())));
        }
Exemple #19
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, object x)
        {
            if (cls != TypeCache.Single)
            {
                return(cls.CreateInstance(context, x));
            }

            if (x is string)
            {
                return(ParseFloat((string)x));
            }
            else if (x is Extensible <string> )
            {
                return(ParseFloat(((Extensible <string>)x).Value));
            }
            else if (x is char)
            {
                return(ParseFloat(ScriptingRuntimeHelpers.CharToString((char)x)));
            }

            double doubleVal;

            if (Converter.TryConvertToDouble(x, out doubleVal))
            {
                return((float)doubleVal);
            }

            if (x is Complex)
            {
                throw PythonOps.TypeError("can't convert complex to Single; use abs(z)");
            }

            object d = PythonOps.CallWithContext(context, PythonOps.GetBoundAttr(context, x, "__float__"));

            if (d is double)
            {
                return((float)(double)d);
            }
            throw PythonOps.TypeError("__float__ returned non-float (type %s)", DynamicHelpers.GetPythonType(d));
        }
Exemple #20
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, IList <byte> s)
        {
            // First, check for subclasses of bytearray/bytes
            object        value;
            IPythonObject po = s as IPythonObject;

            if (po == null ||
                !PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__float__", out value))
            {
                // If __float__oes not exist, just parse the string normally
                value = ParseFloat(s.MakeString());
            }

            if (cls == TypeCache.Double)
            {
                return(value);
            }
            else
            {
                return(cls.CreateInstance(context, value));
            }
        }
Exemple #21
0
        public static object __new__(CodeContext /*!*/ context, PythonType cls, IList <byte> s)
        {
            if (cls != TypeCache.Single)
            {
                return(cls.CreateInstance(context, s));
            }

            object        value;
            IPythonObject po = s as IPythonObject;

            if (po != null &&
                PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__float__", out value))
            {
                if (value is double)
                {
                    return((float)(double)value);
                }
                return(value);
            }

            return(ParseFloat(s.MakeString()));
        }
        public static object __new__(CodeContext context, PythonType cls, object?real, [Optional] object?imag)
        {
            // Fast-track for a single argument when type(arg) is complex and no subclasses are involved.
            if (real is Complex && imag is Missing && cls == TypeCache.Complex)
            {
                return(real);
            }

            if (real is string s)
            {
                return(ParseComplex(s, imag));
            }
            if (real is Extensible <string> es)
            {
                return(ParseComplex(es.Value, imag));
            }

            if (imag is string || imag is Extensible <string> )
            {
                throw PythonOps.TypeError("complex() second arg can't be a string");
            }

            Complex real2;
            bool    real_is_entirely_real = false;

            if (real is Complex z)
            {
                real2 = z;
            }
            else if (!TryInvokeComplex(context, real, out real2))
            {
                if (real is Extensible <Complex> ez)
                {
                    real2 = ez.Value;
                }
                else if (DoubleOps.TryToFloat(context, real, out double res))
                {
                    real2 = res;
                    real_is_entirely_real = true;  // to preserve zero-sign of imag
                }
                else
                {
                    throw PythonOps.TypeErrorForBadInstance("complex() first argument must be a string or a number, not '{0}'", real);
                }
            }

            double real3, imag3;

            if (imag is Missing)
            {
                real3 = real2.Real;
                imag3 = real2.Imaginary;
            }
            else
            {
                Complex imag2;
                if (imag is Complex z2)
                {
                    imag2 = z2;
                    // surprisingly, no TryInvokeComplex here
                }
                else if (imag is Extensible <Complex> ez2)
                {
                    imag2 = ez2.Value;
                }
                else if (DoubleOps.TryToFloat(context, imag, out double res))
                {
                    imag2 = res;
                }
                else
                {
                    throw PythonOps.TypeErrorForBadInstance("complex() second argument must be a number, not '{0}'", imag);
                }

                real3 = real2.Real - imag2.Imaginary;
                imag3 = real_is_entirely_real ? imag2.Real : real2.Imaginary + imag2.Real;
            }

            if (cls == TypeCache.Complex)
            {
                return(new Complex(real3, imag3));
            }
            else
            {
                return(cls.CreateInstance(context, real3, imag3));
            }
Exemple #23
0
        public static object __new__(CodeContext context, PythonType cls, [Optional] object?real, [Optional] object?imag)
        {
            if (real == null)
            {
                throw PythonOps.TypeError($"complex() first argument must be a string or a number, not '{PythonTypeOps.GetName(real)}'");
            }
            if (imag == null)
            {
                throw PythonOps.TypeError($"complex() second argument must be a number, not '{PythonTypeOps.GetName(real)}'");
            }

            Complex imag2;

            if (imag is Missing)
            {
                imag2 = Complex.Zero;
            }
            else
            {
                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");
                }
                if (!Converter.TryConvertToComplex(imag, out imag2))
                {
                    throw PythonOps.TypeError($"complex() second argument must be a number, not '{PythonTypeOps.GetName(real)}'");
                }
            }

            Complex real2;

            if (real is Missing)
            {
                real2 = Complex.Zero;
            }
            else 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 is Missing && cls == TypeCache.Complex)
                {
                    return(real);
                }
                else
                {
                    real2 = (Complex)real;
                }
            }
            else if (!Converter.TryConvertToComplex(real, out real2))
            {
                throw PythonOps.TypeError($"complex() first argument must be a string or a number, not '{PythonTypeOps.GetName(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));
            }
        }
Exemple #24
0
        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));
            }
        }
Exemple #25
0
 public static timedelta __new__(CodeContext context, PythonType cls,
     [DefaultParameterValue(0D)] double days,
     [DefaultParameterValue(0D)] double seconds,
     [DefaultParameterValue(0D)] double microseconds,
     [DefaultParameterValue(0D)] double milliseconds,
     [DefaultParameterValue(0D)] double minutes,
     [DefaultParameterValue(0D)] double hours,
     [DefaultParameterValue(0D)] double weeks)
 {
     if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(timedelta))) {
         return new timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks);
     } else {
         timedelta delta = cls.CreateInstance(context, days, seconds, microseconds, milliseconds, minutes, hours, weeks) as timedelta;
         if (delta == null) throw PythonOps.TypeError("{0} is not a subclass of datetime.timedelta", cls);
         return delta;
     }
 }
Exemple #26
0
        /// <summary>
        /// Returns a pointer instance for the given CData
        /// </summary>
        public static Pointer pointer(CodeContext /*!*/ context, CData data)
        {
            PythonType ptrType = POINTER(context, DynamicHelpers.GetPythonType(data));

            return((Pointer)ptrType.CreateInstance(context, data));
        }
Exemple #27
0
 public static object CreateCFunction(IntPtr address, PythonType type)
 {
     return(type.CreateInstance(type.Context.SharedContext, address));
 }