Exemplo n.º 1
0
        internal bool DeleteCustomMember(CodeContext context, string name)
        {
            if (name == "__class__")
            {
                throw PythonOps.TypeError("__class__ must be set to class");
            }
            if (name == "__dict__")
            {
                throw PythonOps.TypeError("__dict__ must be set to a dictionary");
            }

            object delFunc;

            if (_class.HasDelAttr && _class.TryLookupSlot("__delattr__", out delFunc))
            {
                PythonCalls.Call(context, _class.GetOldStyleDescriptor(context, delFunc, this, _class), name.ToString());
                return(true);
            }


            if (name == "__del__")
            {
                // removing finalizer
                if (HasFinalizer() && !_class.HasFinalizer)
                {
                    ClearFinalizer();
                }
            }

            if (!_dict.Remove(name))
            {
                throw PythonOps.AttributeError("{0} is not a valid attribute", name);
            }
            return(true);
        }
Exemplo n.º 2
0
                public void stepCallback(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] param)
                {
                    if (instance == null)
                    {
                        try
                        {
                            instance = PythonCalls.Call(context, aggregate_class);
                        }
                        catch (Exception)
                        {
                            Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's '__init__' method raised error", -1);
                            return;
                        }
                    }

                    try
                    {
                        object   step = context.LanguageContext.Operations.GetMember(instance, "step");
                        object[] args = buildPyParams(context, ctx, argc, param);

                        PythonCalls.CallWithKeywordArgs(context, step, args, new Dictionary <object, object>());
                    }
                    catch (Exception e)
                    {
                        if (e is MissingMemberException)
                        {
                            throw;
                        }

                        Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's 'step' method raised error", -1);
                    }
                }
Exemplo n.º 3
0
        private object adaptValue(CodeContext context, object value)
        {
            object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol));
            object type  = DynamicHelpers.GetPythonType(value);

            object key = new PythonTuple(new[] { type, proto });

            object adapter;

            if (PythonSQLite.adapters.TryGetValue(key, out adapter))
            {
                object adapted = PythonCalls.Call(context, adapter, value);
                return(adapted);
            }

            // TODO: Use proto? Any value whatsoever?

            object conform;

            if (context.LanguageContext.Operations.TryGetMember(value, "__conform__", out conform))
            {
                object adapted = PythonCalls.Call(context, conform, proto);
                if (adapted != null)
                {
                    return(adapted);
                }
            }

            return(value);
        }
Exemplo n.º 4
0
        internal bool TryGetBoundCustomMember(CodeContext context, string name, out object value)
        {
            if (name == "__dict__")
            {
                //!!! user code can modify __del__ property of __dict__ behind our back
                value = _dict;
                return(true);
            }
            else if (name == "__class__")
            {
                value = _class;
                return(true);
            }

            if (TryRawGetAttr(context, name, out value))
            {
                return(true);
            }

            if (name != "__getattr__")
            {
                object getattr;
                if (TryRawGetAttr(context, "__getattr__", out getattr))
                {
                    try {
                        value = PythonCalls.Call(context, getattr, name);
                        return(true);
                    } catch (MissingMemberException) {
                        // __getattr__ raised AttributeError, return false.
                    }
                }
            }

            return(false);
        }
Exemplo n.º 5
0
        internal void SetCustomMember(CodeContext context, string name, object value)
        {
            object setFunc;

            if (name == "__class__")
            {
                SetClass(value);
            }
            else if (name == "__dict__")
            {
                SetDict(context, value);
            }
            else if (_class.HasSetAttr && _class.TryLookupSlot("__setattr__", out setFunc))
            {
                PythonCalls.Call(context, _class.GetOldStyleDescriptor(context, setFunc, this, _class), name.ToString(), value);
            }
            else if (name == "__del__")
            {
                SetFinalizer(context, name, value);
            }
            else
            {
                _dict[name] = value;
            }
        }
Exemplo n.º 6
0
        public static int ConvertToIndex(object value)
        {
            int?res = ConvertToSliceIndexHelper(value, false);

            if (res.HasValue)
            {
                return(res.Value);
            }

            object callable;

            if (PythonOps.TryGetBoundAttr(value, "__index__", out callable))
            {
                object index = PythonCalls.Call(callable);
                res = ConvertToSliceIndexHelper(index, false);
                if (res.HasValue)
                {
                    return(res.Value);
                }

                throw PythonOps.TypeError("__index__ returned bad value: {0}", DynamicHelpers.GetPythonType(index).Name);
            }

            throw PythonOps.TypeError("expected index value, got {0}", DynamicHelpers.GetPythonType(value).Name);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Finds a user defined importer for the given path or returns null if no importer
        /// handles this path.
        /// </summary>
        private static object FindImporterForPath(CodeContext /*!*/ context, string dirname)
        {
            PythonList pathHooks = context.LanguageContext.GetSystemStateValue("path_hooks") as PythonList;

            foreach (object hook in (IEnumerable)pathHooks)
            {
                try {
                    object handler = PythonCalls.Call(context, hook, dirname);

                    if (handler != null)
                    {
                        return(handler);
                    }
                } catch (ImportException) {
                    // we can't handle the path
                }
            }

            if (!context.LanguageContext.DomainManager.Platform.DirectoryExists(dirname))
            {
                return(new PythonImport.NullImporter(dirname));
            }

            return(null);
        }
Exemplo n.º 8
0
        public static bool TryCreate(object baseObject, out IEnumerator enumerator)
        {
            if (TryCastIEnumer(baseObject, out enumerator))
            {
                return(true);
            }

            object iter;

            if (PythonOps.TryGetBoundAttr(baseObject, "__iter__", out iter))
            {
                object iterator = PythonCalls.Call(iter);
                // don't re-wrap if we don't need to (common case is PythonGenerator).
                if (TryCastIEnumer(iterator, out enumerator))
                {
                    return(true);
                }
                enumerator = new PythonEnumerator(iterator);
                return(true);
            }
            else
            {
                enumerator = null;
                return(false);
            }
        }
Exemplo n.º 9
0
        public static object __new__(CodeContext context, PythonType type, object o)
        {
            object reversed;

            if (PythonOps.TryGetBoundAttr(context, o, "__reversed__", out reversed))
            {
                return(PythonCalls.Call(context, reversed));
            }

            object boundFunc;

            PythonTypeSlot getitem;
            PythonType     pt = DynamicHelpers.GetPythonType(o);

            if (!pt.TryResolveSlot(context, "__getitem__", out getitem) ||
                !getitem.TryGetValue(context, o, pt, out boundFunc) ||
                o is PythonDictionary)
            {
                throw PythonOps.TypeError("argument to reversed() must be a sequence");
            }

            int length;

            if (!DynamicHelpers.GetPythonType(o).TryGetLength(context, o, out length))
            {
                throw PythonOps.TypeError("object of type '{0}' has no len()", DynamicHelpers.GetPythonType(o).Name);
            }

            if (type.UnderlyingSystemType == typeof(ReversedEnumerator))
            {
                return(new ReversedEnumerator((int)length, boundFunc));
            }

            return(type.CreateInstance(context, length, getitem));
        }
Exemplo n.º 10
0
            object INativeType.GetValue(MemoryHolder /*!*/ owner, object readingFrom, int offset, bool raw)
            {
                object res;

                switch (_type)
                {
                case SimpleTypeKind.Boolean: res = owner.ReadByte(offset) != 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; break;

                case SimpleTypeKind.Char: res = new string((char)owner.ReadByte(offset), 1); break;

                case SimpleTypeKind.SignedByte: res = GetIntReturn((int)(sbyte)owner.ReadByte(offset)); break;

                case SimpleTypeKind.UnsignedByte: res = GetIntReturn((int)owner.ReadByte(offset)); break;

                case SimpleTypeKind.SignedShort: res = GetIntReturn(owner.ReadInt16(offset, _swap)); break;

                case SimpleTypeKind.WChar: res = new string((char)owner.ReadInt16(offset), 1); break;

                case SimpleTypeKind.UnsignedShort: res = GetIntReturn((ushort)owner.ReadInt16(offset, _swap)); break;

                case SimpleTypeKind.VariantBool: res = owner.ReadInt16(offset, _swap) != 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; break;

                case SimpleTypeKind.SignedInt: res = GetIntReturn(owner.ReadInt32(offset, _swap)); break;

                case SimpleTypeKind.UnsignedInt: res = GetIntReturn((uint)owner.ReadInt32(offset, _swap)); break;

                case SimpleTypeKind.UnsignedLong: res = GetIntReturn((uint)owner.ReadInt32(offset, _swap)); break;

                case SimpleTypeKind.SignedLong: res = GetIntReturn(owner.ReadInt32(offset, _swap)); break;

                case SimpleTypeKind.Single: res = GetSingleReturn(owner.ReadInt32(offset, _swap)); break;

                case SimpleTypeKind.Double: res = GetDoubleReturn(owner.ReadInt64(offset, _swap)); break;

                case SimpleTypeKind.UnsignedLongLong: res = GetIntReturn((ulong)owner.ReadInt64(offset, _swap)); break;

                case SimpleTypeKind.SignedLongLong: res = GetIntReturn(owner.ReadInt64(offset, _swap)); break;

                case SimpleTypeKind.Object: res = GetObjectReturn(owner.ReadIntPtr(offset)); break;

                case SimpleTypeKind.Pointer: res = owner.ReadIntPtr(offset).ToPython(); break;

                case SimpleTypeKind.CharPointer: res = owner.ReadMemoryHolder(offset).ReadAnsiString(0); break;

                case SimpleTypeKind.WCharPointer: res = owner.ReadMemoryHolder(offset).ReadUnicodeString(0); break;

                case SimpleTypeKind.BStr: res = Marshal.PtrToStringBSTR(owner.ReadIntPtr(offset)); break;

                default:
                    throw new InvalidOperationException();
                }

                if (!raw && IsSubClass)
                {
                    res = PythonCalls.Call(this, res);
                }

                return(res);
            }
Exemplo n.º 11
0
 internal static object MakeDict(CodeContext /*!*/ context, PythonType cls)
 {
     if (cls == TypeCache.Dict)
     {
         return(new PythonDictionary());
     }
     return(PythonCalls.Call(context, cls));
 }
Exemplo n.º 12
0
        PyObject_Call(IntPtr objPtr, IntPtr argsPtr, IntPtr kwargsPtr)
        {
            try
            {
                object obj = this.Retrieve(objPtr);

                PythonDictionary builtins = this.GetModule("__builtin__").Get__dict__();
                if (obj == TypeCache.PythonFile || obj == builtins["open"])
                {
                    obj = this.cFileClass;
                }

                object[] argsArray = null;

                if (argsPtr == IntPtr.Zero)
                {
                    argsArray = new object[0];
                }
                else
                {
                    ICollection args = (ICollection)this.Retrieve(argsPtr);
                    argsArray = new object[args.Count];
                    args.CopyTo(argsArray, 0);
                }

                if (obj == builtins["__import__"])
                {
                    // I really, really wish that Pyrex used the C API for importing things,
                    // instead of PyObject_Call __import__. However, it doesn't, so I have to
                    // do this.
                    // This is only tested in functionalitytest -- if h5's pyd submodules each
                    // have their own copy of _sync, this bit is broken.
                    if (kwargsPtr != IntPtr.Zero)
                    {
                        throw new NotImplementedException("Someone tried to PyObject_Call __import__ with non-null kwargs.");
                    }
                    return(this.DoFoulImportHack(argsArray));
                }

                object result = null;
                if (kwargsPtr == IntPtr.Zero)
                {
                    result = PythonCalls.Call(obj, argsArray);
                }
                else
                {
                    PythonDictionary kwargs = (PythonDictionary)this.Retrieve(kwargsPtr);
                    result = PythonCalls.CallWithKeywordArgs(this.scratchContext, obj, argsArray, kwargs);
                }

                return(this.Store(result));
            }
            catch (Exception e)
            {
                this.LastException = e;
                return(IntPtr.Zero);
            }
        }
Exemplo n.º 13
0
        public static void InvokeAction(ISynchronizeInvoke synchronizer,
                                        PythonFunction method)
        {
            Action action = () => {
                PythonCalls.Call(method);
            };

            UnifiedSynchronizerAccess.Invoke(synchronizer, action, null);
        }
Exemplo n.º 14
0
        public static UnifiedInvokeResult InvokeFunc <T> (ISynchronizeInvoke synchronizer,
                                                          PythonFunction method)
        {
            Func <T> func = () => {
                return((T)PythonCalls.Call(method));
            };

            return(UnifiedSynchronizerAccess.Invoke(synchronizer, func, null));
        }
Exemplo n.º 15
0
        public static object encode(CodeContext /*!*/ context, object obj, string encoding = null, string errors = "strict")
        {
            if (encoding == null)
            {
                encoding = context.LanguageContext.DefaultEncoding.EncodingName;
            }
            PythonTuple t = lookup(context, encoding);

            return(PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, errors), 0));
        }
Exemplo n.º 16
0
 public object CallFunction(object function, params object[] args)
 {
     try
     {
         return(PythonCalls.Call(function, args));
     } catch (Exception ex) {
         Log.Write(ex, "Call function failed: '{0}'", ex.Message);
         throw new Exception(_pi.FormatException(ex), ex);
     }
 }
Exemplo n.º 17
0
        Register_PyEllipsis_Type(IntPtr address)
        {
            // not quite trivial to autogenerate
            // (but surely there's a better way to get the Ellipsis object...)
            CPyMarshal.Zero(address, Marshal.SizeOf(typeof(PyTypeObject)));
            CPyMarshal.WriteIntField(address, typeof(PyTypeObject), "ob_refcnt", 1);
            CPyMarshal.WriteCStringField(address, typeof(PyTypeObject), "tp_name", "ellipsis");
            object ellipsisType = PythonCalls.Call(Builtin.type, new object[] { PythonOps.Ellipsis });

            this.map.Associate(address, ellipsisType);
        }
Exemplo n.º 18
0
        public static object __rdivmod__(CodeContext context, object divmod, [NotNull] OldInstance self)
        {
            object value;

            if (self.TryGetBoundCustomMember(context, "__rdivmod__", out value))
            {
                return(PythonCalls.Call(context, value, divmod));
            }

            return(NotImplementedType.Value);
        }
Exemplo n.º 19
0
        StoreTyped(PythonExceptions.BaseException exc)
        {
            IntPtr ptr = this.allocator.Alloc((uint)Marshal.SizeOf(typeof(PyObject)));

            CPyMarshal.WriteIntField(ptr, typeof(PyObject), "ob_refcnt", 1);
            object type_ = PythonCalls.Call(Builtin.type, new object[] { exc });

            CPyMarshal.WritePtrField(ptr, typeof(PyObject), "ob_type", this.Store(type_));
            this.map.Associate(ptr, exc);
            return(ptr);
        }
Exemplo n.º 20
0
 private void AddTask(PythonFunction task, Func <int, int> interval, int executeTimes, int waitTime, bool withArg = false)
 {
     if (withArg)
     {
         AddTask(new ScheduledTask(t => PythonCalls.Call(task, t), interval, executeTimes, waitTime));
     }
     else
     {
         AddTask(new ScheduledTask(t => PythonCalls.Call(task), interval, executeTimes, waitTime));
     }
 }
Exemplo n.º 21
0
        public object __coerce__(CodeContext context, object other)
        {
            object value;

            if (TryGetBoundCustomMember(context, "__coerce__", out value))
            {
                return(PythonCalls.Call(context, value, other));
            }

            return(NotImplementedType.Value);
        }
Exemplo n.º 22
0
 public void AddTask(PythonFunction func, int interval, int executeTimes, int waitTime, bool withArg = false)
 {
     if (withArg)
     {
         AddTask(task => PythonCalls.Call(func, task), interval, executeTimes, waitTime);
     }
     else
     {
         AddTask(task => PythonCalls.Call(func), interval, executeTimes, waitTime);
     }
 }
Exemplo n.º 23
0
        public object DeleteItem(CodeContext context, object item)
        {
            object value;

            if (TryGetBoundCustomMember(context, "__delitem__", out value))
            {
                return(PythonCalls.Call(context, value, item));
            }

            throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__delitem__");
        }
Exemplo n.º 24
0
 object INativeType.GetValue(MemoryHolder owner, object readingFrom, int offset, bool raw)
 {
     if (!raw)
     {
         Pointer res = (Pointer)PythonCalls.Call(Context.SharedContext, this);
         res._memHolder.WriteIntPtr(0, owner.ReadIntPtr(offset));
         res._memHolder.AddObject(offset, readingFrom);
         return(res);
     }
     return(owner.ReadIntPtr(offset).ToPython());
 }
Exemplo n.º 25
0
        public object __divmod__(CodeContext context, object divmod)
        {
            object value;

            if (TryGetBoundCustomMember(context, "__divmod__", out value))
            {
                return(PythonCalls.Call(context, value, divmod));
            }


            return(NotImplementedType.Value);
        }
Exemplo n.º 26
0
 PyNumber_Float(IntPtr numberPtr)
 {
     try
     {
         return(this.Store(PythonCalls.Call(TypeCache.Double, new object[] { this.Retrieve(numberPtr) })));
     }
     catch (Exception e)
     {
         this.LastException = e;
         return(IntPtr.Zero);
     }
 }
Exemplo n.º 27
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.º 28
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.º 29
0
 bool IEnumerator.MoveNext()
 {
     if (_index > 0)
     {
         _index--;
         _current = PythonCalls.Call(_getItemMethod, _index);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 30
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()));
     }
 }