Exemplo n.º 1
0
            public object Call(CodeContext /*!*/ context, object param)
            {
                object method = PythonOps.GetBoundAttr(context, param, _name);

                if (_dict == null)
                {
                    return(PythonOps.CallWithContext(context, method, _args));
                }
                else
                {
                    return(PythonCalls.CallWithKeywordArgs(context, method, _args, _dict));
                }
            }
Exemplo n.º 2
0
 bool IEnumerator.MoveNext()
 {
     if (_index > 0)
     {
         _index--;
         _current = PythonCalls.Call(_getItemMethod, _index);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 3
0
 public object __copy__(CodeContext /*!*/ context)
 {
     if (GetType() == typeof(deque))
     {
         deque res = new deque(_maxLen);
         res.extend(((IEnumerable)this).GetEnumerator());
         return(res);
     }
     else
     {
         return(PythonCalls.Call(context, DynamicHelpers.GetPythonType(this), ((IEnumerable)this).GetEnumerator()));
     }
 }
Exemplo n.º 4
0
        public object Call(CodeContext context, [ParamDictionary] IDictionary <object, object> dict, params object[] args)
        {
            object targetMethod;

            if (!DynamicHelpers.GetPythonType(target.Target).TryGetBoundMember(context, target.Target, name, out targetMethod))
            {
                throw PythonOps.AttributeError("type {0} has no attribute {1}",
                                               DynamicHelpers.GetPythonType(target.Target),
                                               name);
            }

            return(PythonCalls.CallWithKeywordArgs(context, targetMethod, args, dict));
        }
Exemplo n.º 5
0
 IC_PyInt_New(IntPtr typePtr, IntPtr argsPtr, IntPtr kwargsPtr)
 {
     try
     {
         PythonTuple args = (PythonTuple)this.Retrieve(argsPtr);
         return(this.Store(PythonCalls.Call(this.scratchContext, TypeCache.Int32, new object[] { args[0] })));
     }
     catch (Exception e)
     {
         this.LastException = e;
         return(IntPtr.Zero);
     }
 }
Exemplo n.º 6
0
 PyNumber_Long(IntPtr numberPtr)
 {
     try
     {
         object number = this.Retrieve(numberPtr);
         return(this.Store(PythonCalls.Call(TypeCache.BigInteger, new object[] { number })));
     }
     catch (Exception e)
     {
         this.LastException = e;
         return(IntPtr.Zero);
     }
 }
Exemplo n.º 7
0
        public new object __get__(CodeContext /*!*/ context, object instance, object owner)
        {
            PythonType selfType = PythonType;

            if (selfType == TypeCache.Super)
            {
                Super res = new Super();
                res.__init__(_thisClass, instance);
                return(res);
            }

            return(PythonCalls.Call(context, selfType, _thisClass, instance));
        }
Exemplo n.º 8
0
            public object cursor(CodeContext context, [Optional][DefaultParameterValue(null)] object factory)
            {
                checkThread(); checkConnection();

                object cursor = factory == null ? new Cursor(context, this) : PythonCalls.Call(context, factory, this);

                if (this.row_factory != null)
                {
                    context.LanguageContext.Operations.SetMember(cursor, "row_factory", this.row_factory);
                }

                return(cursor);
            }
Exemplo n.º 9
0
            public object Call(CodeContext context, [ParamDictionary] IDictionary <object, object> dict, params object[] args)
            {
                ValidateArgs(args);

                if (_inst != null)
                {
                    return(PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict));
                }
                else
                {
                    return(PythonCalls.CallWithKeywordArgs(context, _func, args, dict));
                }
            }
Exemplo n.º 10
0
        LogRefs()
        {
            int wtotal = 0;
            int stotal = 0;
            Dictionary <object, int> scounts = new Dictionary <object, int>();
            Dictionary <object, int> wcounts = new Dictionary <object, int>();

            wcounts["ZOMBIE"] = 0;
            foreach (long id in this.id2wref.Keys)
            {
                if (!this.id2sref.ContainsKey(id))
                {
                    wtotal += 1;
                    WeakReference wref = this.id2wref[id];
                    if (wref.IsAlive)
                    {
                        object type_ = PythonCalls.Call(Builtin.type, new object[] { wref.Target });
                        if (!wcounts.ContainsKey(type_))
                        {
                            wcounts[type_] = 0;
                        }
                        wcounts[type_] += 1;
                    }
                    else
                    {
                        wcounts["ZOMBIE"] += 1;
                    }
                }
                else
                {
                    stotal += 1;
                    object type_ = PythonCalls.Call(Builtin.type, new object[] { this.id2sref[id] });
                    if (!scounts.ContainsKey(type_))
                    {
                        scounts[type_] = 0;
                    }
                    scounts[type_] += 1;
                }
            }
            Console.WriteLine("weak refs: {0}", wtotal);
            foreach (object type_ in wcounts.Keys)
            {
                Console.WriteLine("{0}: {1}", PythonCalls.Call(Builtin.str, new object[] { type_ }), wcounts[type_]);
            }

            Console.WriteLine("strong refs: {0}", stotal);
            foreach (object type_ in scounts.Keys)
            {
                Console.WriteLine("{0}: {1}", PythonCalls.Call(Builtin.str, new object[] { type_ }), scounts[type_]);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Attempts to convert value into a index usable for slicing and return the integer
        /// value.  If the conversion fails false is returned.
        ///
        /// If throwOverflowError is true then BigInteger's outside the normal range of integers will
        /// result in an OverflowError.
        /// </summary>
        internal static bool TryConvertToIndex(object value, bool throwOverflowError, out object index)
        {
            index = ConvertToSliceIndexHelper(value, throwOverflowError);
            if (index == null)
            {
                object callable;
                if (PythonOps.TryGetBoundAttr(value, "__index__", out callable))
                {
                    index = ConvertToSliceIndexHelper(PythonCalls.Call(callable), throwOverflowError);
                }
            }

            return(index != null);
        }
Exemplo n.º 12
0
        Dispose(bool disposing)
        {
            if (!this.alive)
            {
                return;
            }

            this.alive = false;
            while (this.exitfuncs.Count > 0)
            {
                this.exitfuncs.Pop()();
            }

            PythonDictionary modules = (PythonDictionary)this.python.SystemState.Get__dict__()["modules"];

            if (!modules.Contains("numpy"))
            {
                // TODO: FIXME?
                // I don't know what it is about numpy, but using it heavily
                // makes this step extremely flaky: that's, like, BSOD flaky.
                // OTOH, even attempting this operation is very optimistic
                // indeed, and it's only really here so that I can repeatedly
                // construct/destroy mappers -- without leaking *too* much --
                // during test runs. In the wild, all this will be reclaimed
                // by the operating system at process shutdown time anyway.
                this.map.MapOverBridgePtrs(new PtrFunc(this.DumpPtr));
            }

            this.allocator.FreeAll();
            foreach (IntPtr FILE in this.FILEs.Values)
            {
                Unmanaged.fclose(FILE);
            }

            if (this.stub != null)
            {
                PythonCalls.Call(this.removeSysHacks);
                modules.Remove("mmap");
                modules.Remove("posix");
                modules.Remove("_csv");
                if (modules.Contains("csv"))
                {
                    modules.Remove("csv");
                }

                this.importer.Dispose();
                this.stub.Dispose();
            }
        }
Exemplo n.º 13
0
        public override void Init()
        {
            try
            {
                scriptSource = Engine.CreateScriptSourceFromFile(Path);
                compiledCode = scriptSource.Compile();
                compiledCode.Execute(Scope);

                PythonFunction InitAction = (PythonFunction)GetVariable("Init");
                PythonCalls.Call(codeContext, InitAction);
            }
            catch (ImportException e)
            {
            }
        }
Exemplo n.º 14
0
        public object __delslice__(CodeContext context, int i, int j)
        {
            object callable;

            if (TryRawGetAttr(context, "__delslice__", out callable))
            {
                return(PythonCalls.Call(context, callable, i, j));
            }
            else if (TryRawGetAttr(context, "__delitem__", out callable))
            {
                return(PythonCalls.Call(context, callable, new Slice(i, j)));
            }

            throw PythonOps.TypeError("instance {0} does not have __delslice__ or __delitem__", _class.Name);
        }
Exemplo n.º 15
0
        public object Call(CodeContext context, [ParamDictionary] IDictionary <object, object> dict\u00F8, [NotNull] params object[] args\u00F8)
        {
            OldInstance inst = new OldInstance(context, this);
            object      meth;

            if (PythonOps.TryGetBoundAttr(inst, "__init__", out meth))
            {
                PythonCalls.CallWithKeywordArgs(context, meth, args\u00F8, dict\u00F8);
            }
            else if (dict\u00F8.Count > 0 || args\u00F8.Length > 0)
            {
                MakeCallError();
            }
            return(inst);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Attempts to convert value into a index usable for slicing and return the integer
        /// value.  If the conversion fails false is returned.
        ///
        /// If throwOverflowError is true then BigInteger's outside the normal range of integers will
        /// result in an OverflowError.
        /// </summary>
        internal static bool TryConvertToIndex(object value, bool throwOverflowError, out int index)
        {
            int?res = ConvertToSliceIndexHelper(value, throwOverflowError);

            if (!res.HasValue)
            {
                object callable;
                if (PythonOps.TryGetBoundAttr(value, "__index__", out callable))
                {
                    res = ConvertToSliceIndexHelper(PythonCalls.Call(callable), throwOverflowError);
                }
            }

            index = res.HasValue ? res.Value : 0;
            return(res.HasValue);
        }
Exemplo n.º 17
0
 public bool MoveNext()
 {
     if (_index > 0)
     {
         _index--;
         Current = PythonCalls.Call(_getItemMethod, _index);
         return(true);
     }
     else
     {
         _obj           = null;
         _getItemMethod = null;
         Current        = null;
         return(false);
     }
 }
Exemplo n.º 18
0
        public void Init()
        {
            try
            {
                Reload();

                InitThreadId = Thread.CurrentThread.ManagedThreadId;
                Engine.SetTrace(OnTracebackReceived);

                PythonFunction InitAction = (PythonFunction)GetVariable("Init");
                PythonCalls.Call(codeContext, InitAction);
            }
            catch (ImportException e)
            {
            }
        }
Exemplo n.º 19
0
        public bool MoveNext()
        {
            while (_enumerator.MoveNext())
            {
                object?o = _enumerator.Current;
                object?t = (_function != null) ? PythonCalls.Call(_context, _function, o) : o;

                if (PythonOps.IsTrue(t))
                {
                    Current = o;
                    return(true);
                }
            }
            Current = default;
            return(false);
        }
Exemplo n.º 20
0
        public static void call_tracing(CodeContext /*!*/ context, object func, PythonTuple args)
        {
            PythonContext pyContext = (PythonContext)context.LanguageContext;

            pyContext.EnsureDebugContext();

            pyContext.UnregisterTracebackHandler();
            pyContext.PushTracebackHandler(new PythonTracebackListener((PythonContext)context.LanguageContext));
            pyContext.RegisterTracebackHandler();
            try {
                PythonCalls.Call(func, args.ToArray());
            } finally {
                pyContext.PopTracebackHandler();
                pyContext.UnregisterTracebackHandler();
            }
        }
Exemplo n.º 21
0
            /// <summary>
            /// Converts an object into a function call parameter.
            /// </summary>
            public object from_param(Pointer obj)
            {
                if (obj == null)
                {
                    return(ScriptingRuntimeHelpers.Int32ToObject(0));
                }

                if (obj.NativeType != this)
                {
                    throw PythonOps.TypeError("assign to pointer of type {0} from {1} is not valid", Name, ((PythonType)obj.NativeType).Name);
                }

                Pointer res = (Pointer)PythonCalls.Call(this);

                res._memHolder.WriteIntPtr(0, obj._memHolder.ReadMemoryHolder(0));
                return(res);
            }
Exemplo n.º 22
0
 PyNumber_Int(IntPtr numberPtr)
 {
     try
     {
         object result = PythonCalls.Call(TypeCache.Int32, new object[] { this.Retrieve(numberPtr) });
         if (!(result is Int32))
         {
             result = Converter.ConvertToBigInteger(result);
         }
         return(this.Store(result));
     }
     catch (Exception e)
     {
         this.LastException = e;
         return(IntPtr.Zero);
     }
 }
Exemplo n.º 23
0
        public void __setslice__(CodeContext context, int i, int j, object value)
        {
            object callable;

            if (TryRawGetAttr(context, "__setslice__", out callable))
            {
                PythonCalls.Call(context, callable, i, j, value);
                return;
            }
            else if (TryRawGetAttr(context, "__setitem__", out callable))
            {
                PythonCalls.Call(context, callable, new Slice(i, j), value);
                return;
            }

            throw PythonOps.TypeError("instance {0} does not have __setslice__ or __setitem__", _class.Name);
        }
Exemplo n.º 24
0
        private static SetCollection Make(PythonType /*!*/ cls, SetStorage items)
        {
            if (cls == TypeCache.Set)
            {
                return(new SetCollection(items));
            }

            SetCollection res = PythonCalls.Call(cls) as SetCollection;

            Debug.Assert(res != null);

            if (items.Count > 0)
            {
                res._items = items;
            }
            return(res);
        }
Exemplo n.º 25
0
            public object __next__(CodeContext context)
            {
                object next_row_tuple, next_row;

                connection.checkThread(); connection.checkConnection();

                if (this.next_row == null)
                {
                    if (this.statement != null)
                    {
                        this.statement.Reset();
                        this.statement = null;
                    }

                    throw new StopIterationException();
                }

                next_row_tuple = this.next_row;
                this.next_row  = null;

                if (this.row_factory != null)
                {
                    next_row = PythonCalls.Call(context, this.row_factory, this, next_row_tuple);
                }
                else
                {
                    next_row = next_row_tuple;
                }

                if (this.statement != null)
                {
                    int rc = this.statement.RawStep();
                    if (rc != Sqlite3.SQLITE_DONE && rc != Sqlite3.SQLITE_ROW)
                    {
                        this.statement.Reset();
                        throw GetSqliteError(this.connection.db, this.statement.st);
                    }

                    if (rc == Sqlite3.SQLITE_ROW)
                    {
                        this.next_row = fetchOneRow(context);
                    }
                }

                return(next_row);
            }
Exemplo n.º 26
0
        public bool MoveNext()
        {
            if (_nextMethod == null)
            {
                if (!PythonOps.TryGetBoundAttr(_baseObject, "next", out _nextMethod) || _nextMethod == null)
                {
                    throw PythonOps.TypeError("instance has no next() method");
                }
            }

            try {
                _current = PythonCalls.Call(_nextMethod);
                return(true);
            } catch (StopIterationException) {
                return(false);
            }
        }
Exemplo n.º 27
0
        public static bool TryCreate(object baseEnumerator, out IEnumerable enumerator) {
            Debug.Assert(!(baseEnumerator is IEnumerable) || baseEnumerator is IPythonObject);   // we shouldn't re-wrap things that don't need it
            object iter;

            if (PythonOps.TryGetBoundAttr(baseEnumerator, "__iter__", out iter)) {
                object iterator = PythonCalls.Call(iter);
                if (iterator is IEnumerable) {
                    enumerator = (IEnumerable)iterator;
                } else {
                    enumerator = new PythonEnumerable(iterator);
                }
                return true;
            } else {
                enumerator = null;
                return false;
            }
        }
Exemplo n.º 28
0
 PyObject_Str(IntPtr objPtr)
 {
     try
     {
         object obj = this.Retrieve(objPtr);
         if (obj is string)
         {
             return(this.Store(obj));
         }
         return(this.Store(PythonCalls.Call(Builtin.str, new object[] { obj })));
     }
     catch (Exception e)
     {
         this.LastException = e;
         return(IntPtr.Zero);
     }
 }
Exemplo n.º 29
0
        public static object encode(CodeContext /*!*/ context, object obj, string encoding = null, string errors = "strict")
        {
            if (encoding == null)
            {
                if (obj is string str)
                {
                    PythonContext lc = context.LanguageContext;
                    return(StringOps.DoEncode(context, str, errors, lc.GetDefaultEncodingName(), lc.DefaultEncoding, includePreamble: true));
                }
                else
                {
                    throw PythonOps.TypeError("expected str, got {0}", PythonTypeOps.GetName(obj));
                }
            }
            PythonTuple t = lookup(context, encoding);

            return(PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, errors), 0));
        }
Exemplo n.º 30
0
        public static object decode(CodeContext /*!*/ context, object obj, string encoding = null, string errors = "strict")
        {
            if (encoding == null)
            {
                if (obj is IList <byte> bytesLikeObj)
                {
                    PythonContext lc = context.LanguageContext;
                    return(StringOps.DoDecode(context, bytesLikeObj, errors, lc.GetDefaultEncodingName(), lc.DefaultEncoding, final: true, out _));
                }
                else
                {
                    throw PythonOps.TypeError("expected bytes-like object, got {0}", PythonTypeOps.GetName(obj));
                }
            }
            PythonTuple t = lookup(context, encoding);

            return(PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, errors), 0));
        }