Example #1
0
        /// <summary>
        /// Python ctor - maps to function.__new__
        /// 
        /// y = func(x.__code__, globals(), 'foo', None, (a, ))
        /// </summary>
        public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) {
            if (closure != null && closure.__len__() != 0) {
                throw new NotImplementedException("non empty closure argument is not supported");
            }

            if (globals == context.GlobalDict) {
                _module = context.Module.GetName();
                _context = context;
            } else {
                _module = null;
                _context = new CodeContext(new PythonDictionary(), new ModuleContext(globals, DefaultContext.DefaultPythonContext));
            }

            _defaults = defaults == null ? ArrayUtils.EmptyObjects : defaults.ToArray();
            _code = code;
            _name = name;
            _doc = code._initialDoc;
            Closure = null;

            var scopeStatement = _code.PythonCode;
            if (scopeStatement.IsClosure) {
                throw new NotImplementedException("code containing closures is not supported");
            }
            scopeStatement.RewriteBody(FunctionDefinition.ArbitraryGlobalsVisitorInstance);

            _compat = CalculatedCachedCompat();
        }
Example #2
0
        Py_InitModule4(string name, IntPtr methodsPtr, string doc, IntPtr selfPtr, int apiver)
        {
            name = this.FixImportName(name);
            
            PythonDictionary methodTable = new PythonDictionary();
            PythonModule module = new PythonModule();
            this.AddModule(name, module);
            this.CreateModulesContaining(name);

            PythonDictionary __dict__ = module.Get__dict__();
            __dict__["__doc__"] = doc;
            __dict__["__name__"] = name;
            string __file__ = this.importFiles.Peek();
            __dict__["__file__"] = __file__;
            List __path__ = new List();
            if (__file__ != null)
            {
                __path__.append(Path.GetDirectoryName(__file__));
            }
            __dict__["__path__"] = __path__;
            __dict__["_dispatcher"] = new Dispatcher(this, methodTable, selfPtr);

            StringBuilder moduleCode = new StringBuilder();
            moduleCode.Append(CodeSnippets.USEFUL_IMPORTS);
            CallableBuilder.GenerateFunctions(moduleCode, methodsPtr, methodTable);
            this.ExecInModule(moduleCode.ToString(), module);
            
            return this.Store(module);
        }
        /// <summary>APIの設定を用いてインスタンスを初期化します。 </summary>
        /// <param name="api">IronPython用APIの何らかの実装</param>
        /// <param name="setting">更新処理の設定</param>
        /// <param name="dictionary">キャラに対応するグローバル変数用にディクショナリ</param>
        public IronPythonUpdateProcessor(IScriptApi api, IScriptUpdateSetting setting, PythonDictionary dictionary)
        {
            _setting = setting;

            var engine = Python.CreateEngine();

            //名前参照にexeのディレクトリとキャラのディレクトリを追加
            var paths = engine.GetSearchPaths();
            paths.Add(Environment.CurrentDirectory);
            paths.Add(DirectoryNames.GetCharacterScriptDirectory(api.CharacterName));
            engine.SetSearchPaths(paths);

            //可視領域を限界まで広く取るためビルトインスコープにぶち込んでおく
            ScriptScope builtin = engine.GetBuiltinModule();
            builtin.SetVariable(IronPythonCommonVariableNames.ApiVariableName, api);
            builtin.SetVariable(IronPythonCommonVariableNames.ApiGlobalDictionaryName, dictionary);

            string path = Path.Combine(DirectoryNames.GetCharacterScriptDirectory(api.CharacterName), UpdateScriptName);

            //高スピードで読むので先にコンパイル
            try
            {
                _updateCode = engine.CreateScriptSourceFromFile(path).Compile();
                IsValid = true;
            }
            catch (Exception)
            {
                IsValid = false;
            }
        }
Example #4
0
            private static readonly Field[] _emptyFields = new Field[0]; // fields were never initialized before a type was created

            public StructType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members)
                : base(context, name, bases, members) {

                foreach (PythonType pt in ResolutionOrder) {
                    StructType st = pt as StructType;
                    if (st != this && st != null) {
                        st.EnsureFinal();
                    }

                    UnionType ut = pt as UnionType;
                    if (ut != null) {
                        ut.EnsureFinal();
                    }
                }

                object pack;
                if (members.TryGetValue("_pack_", out pack)) {
                    if (!(pack is int) || ((int)pack < 0)) {
                        throw PythonOps.ValueError("pack must be a non-negative integer");
                    }
                    _pack = (int)pack;
                }

                object fields;
                if (members.TryGetValue("_fields_", out fields)) {
                    SetFields(fields);
                }

                // TODO: _anonymous_
            }
Example #5
0
 public PythonModule() {
     _dict = new PythonDictionary();
     if (GetType() != typeof(PythonModule) && this is IPythonObject) {
         // we should share the user dict w/ our dict.
         ((IPythonObject)this).ReplaceDict(_dict);
     }
 }
Example #6
0
        public Argument(PythonBoss pyBoss, long address, PythonDictionary spec, Process process, int depth, Arguments parent, string namePrefix)
        {
            Address = address;
            this.process = process;
            _pyBoss = pyBoss;
            _parent = parent;
            NamePrefix = namePrefix;

            // Parse the spec for this argument
            // stackspec: [{"name": "socket",
            //		      "size": 4,
            //		      "type": None,
            //		      "fuzz": NOFUZZ,
            //            "type_args": None},]

            Fuzz = (bool)spec.get("fuzz");
            Name = (string)spec.get("name");
            _argumentType = (object)spec.get("type");
            if ( spec.ContainsKey("type_args") )
            {
                _typeArgs = spec.get("type_args");
            }

            // Validate required fields
            if (Name == null)
                throw new Exception("ERROR: Argument specification must include 'name' attribute. Failed when parsing name prefix '" + namePrefix + "'.");
            else if (Fuzz == null)
                throw new Exception("ERROR: Argument specification must include 'fuzz' attribute. Failed when parsing type '" + namePrefix + Name + "'.");
            else if (spec.get("size") == null)
                throw new Exception("ERROR: Argument specification must include 'size' attribute. Failed when parsing type '" + namePrefix + Name + "'.");

            if (spec.get("size") is string)
            {
                object sizeArgument = null;
                if (parent.TryGetMemberSearchUp((string)spec.get("size"), out sizeArgument))
                    Size = ((Argument)sizeArgument).ToInt();
                else
                    throw new Exception("ERROR: Unable to load size for type '" + Name + "' from parent member named '" + (string)spec.get("size") + "'. Please make sure this field exists in the parent.");
            }
            else if (spec.get("size") is int)
            {
                Size = (int)spec.get("size");
            }
            else
            {
                throw new Exception("ERROR: Unable to load size for type '" + Name + "'. The size must be of type 'int' or type 'string'. Size is type: '" + spec.get("size").ToString() + "'" );
            }

            // Read the data
            try
            {
                Data = MemoryFunctions.ReadMemory(process.ProcessDotNet, address, (uint)Size);
            }
            catch (Exception e)
            {
                Data = null;
            }

            PointerTarget = null;
        }
Example #7
0
        public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {            
            var socket = context.GetBuiltinModule("socket");
            var socketError = PythonSocket.GetSocketError(context, socket.__dict__);
            
            context.EnsureModuleException("SSLError", socketError, dict, "SSLError", "ssl");

        }
Example #8
0
 /// <summary>
 /// Creates a new MemoryHolder at the specified address which will keep alive the 
 /// parent memory holder.
 /// </summary>
 public MemoryHolder(IntPtr data, int size, MemoryHolder parent) {
     GC.SuppressFinalize(this);
     _data = data;
     _parent = parent;
     _objects = parent._objects;
     _size = size;
 }
Example #9
0
        /// <summary>フィールド初期化を行います。</summary>
        private void Initialize()
        {
            var chatWindowPosition = new ChatWindowPositionModel(
                _mainWindow,
                _setting.ChatWindowLayout,
                _relocator
                );

            _chatWindow = new ChatWindowModel(chatWindowPosition);

            var voiceOperator = new VoiceOperator(_setting.Voice);
            voiceOperator.LipSynchRequested += (_, e) => _lipSyncher = e.LipSyncher;

            var scriptRequestor = new SimpleScriptRequestor();

            var api = new ScriptApi(
                _mainWindow, _character, voiceOperator, _chatWindow, scriptRequestor,
                _setting,
                _setting.ScriptApi,
                _characterName
                );

            var dict = new PythonDictionary();
            _updateProcessor = new IronPythonUpdateProcessor(api, _setting.ScriptUpdate, dict);

            var ironPythonReader = new IronPythonMainScriptReader(api, dict);
            _scriptStateManager = new ScriptStateManager(ironPythonReader, _setting.ScriptRoutine, _characterName);

            scriptRequestor.ScriptRequested += (_, e) => _scriptStateManager.Request(
                e.ScriptName,
                e.Priority
                );

        }
Example #10
0
        public static void PerformModuleReload(PythonContext context, PythonDictionary dict) {
            if (!context.HasModuleState(_zip_directory_cache_key))
                context.SetModuleState(_zip_directory_cache_key, new PythonDictionary());

            dict["_zip_directory_cache"] = context.GetModuleState(_zip_directory_cache_key);
            InitModuleExceptions(context, dict);
        }
Example #11
0
            public UnionType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members)
                : base(context, name, bases, members) {

                object fields;
                if (members.TryGetValue("_fields_", out fields)) {
                    SetFields(fields);
                }
            }
Example #12
0
 public OldInstance(CodeContext/*!*/ context, OldClass @class) {
     _class = @class;
     _dict = MakeDictionary(@class);
     if (_class.HasFinalizer) {
         // class defines finalizer, we get it automatically.
         AddFinalizer(context);
     }
 }
Example #13
0
 public OldInstance(CodeContext/*!*/ context, OldClass @class, PythonDictionary dict) {
     _class = @class;
     _dict = dict ?? PythonDictionary.MakeSymbolDictionary();
     if (_class.HasFinalizer) {
         // class defines finalizer, we get it automatically.
         AddFinalizer(context);
     }
 }
Example #14
0
 public static void PerformModuleReload(PythonContext context, PythonDictionary dict) {
     PythonModule scope = Importer.ImportModule(context.SharedContext, context.SharedContext.GlobalDict, "itertools", false, -1) as PythonModule;
     if (scope != null) {
         dict["map"] = scope.__dict__["imap"];
         dict["filter"] = scope.__dict__["ifilter"];
         dict["zip"] = scope.__dict__["izip"];
     }
 }
        public static void MapRoute(string name, string url, PythonDictionary defaults) {
            var defaultValues = new RouteValueDictionary();
            foreach (var kvp in defaults) {
                defaultValues.Add(Convert.ToString(kvp.Key, CultureInfo.InvariantCulture), kvp.Value);
            }

            RouteTable.Routes.Add(name, new Route(url, defaultValues, new MvcRouteHandler())) ;
        }
Example #16
0
 public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
     context.EnsureModuleException("PickleError", dict, "PickleError", "cPickle");
     context.EnsureModuleException("PicklingError", dict, "PicklingError", "cPickle");
     context.EnsureModuleException("UnpicklingError", dict, "UnpicklingError", "cPickle");
     context.EnsureModuleException("UnpickleableError", dict, "UnpickleableError", "cPickle");
     context.EnsureModuleException("BadPickleGet", dict, "BadPickleGet", "cPickle");
     dict["__builtins__"] = context.BuiltinModuleInstance;
     dict["compatible_formats"] = PythonOps.MakeList("1.0", "1.1", "1.2", "1.3", "2.0");
 }
Example #17
0
        /// <summary>
        /// Creates a new ModuleContext for the specified module.
        /// </summary>
        public ModuleContext(PythonModule/*!*/ module, PythonContext/*!*/ creatingContext) {
            ContractUtils.RequiresNotNull(module, "module");
            ContractUtils.RequiresNotNull(creatingContext, "creatingContext");

            _globals = module.__dict__;
            _pyContext = creatingContext;
            _globalContext = new CodeContext(_globals, this);
            _module = module;
        }
Example #18
0
 private static void InitModuleExceptions(PythonContext context,
     PythonDictionary dict)
 {
     ZipImportError = context.EnsureModuleException(
         "zipimport.ZipImportError",
         PythonExceptions.ImportError,
         typeof(PythonExceptions.BaseException),
         dict, "ZipImportError", "zipimport",
         msg => new ImportException(msg));
 }
Example #19
0
        /// <summary>
        /// Creates a new ModuleContext which is backed by the specified dictionary.
        /// </summary>
        public ModuleContext(PythonDictionary/*!*/ globals, PythonContext/*!*/ creatingContext) {
            ContractUtils.RequiresNotNull(globals, "globals");
            ContractUtils.RequiresNotNull(creatingContext, "creatingContext");

            _globals = globals;
            _pyContext = creatingContext;
            _globalContext = new CodeContext(globals, this);
            _module = new PythonModule(globals);
            _module.Scope.SetExtension(_pyContext.ContextId, new PythonScopeExtension(_pyContext, _module, this));
        }
Example #20
0
 GenerateFunctions(StringBuilder code, IntPtr methods, PythonDictionary methodTable)
 {
     GenerateCallablesFromMethodDefs(
         code, methods, methodTable, "",
         CodeSnippets.OLDARGS_FUNCTION_TEMPLATE,
         CodeSnippets.NOARGS_FUNCTION_TEMPLATE,
         CodeSnippets.OBJARG_FUNCTION_TEMPLATE,
         CodeSnippets.VARARGS_FUNCTION_TEMPLATE,
         CodeSnippets.VARARGS_KWARGS_FUNCTION_TEMPLATE);
 }
Example #21
0
 GenerateMethods(StringBuilder code, IntPtr methods, PythonDictionary methodTable, string tablePrefix)
 {
     GenerateCallablesFromMethodDefs(
         code, methods, methodTable, tablePrefix,
         CodeSnippets.OLDARGS_METHOD_TEMPLATE,
         CodeSnippets.NOARGS_METHOD_TEMPLATE,
         CodeSnippets.OBJARG_METHOD_TEMPLATE,
         CodeSnippets.VARARGS_METHOD_TEMPLATE,
         CodeSnippets.VARARGS_KWARGS_METHOD_TEMPLATE);
 }
        public Tree create_node(int left, int top, int width, int height, PythonDictionary tags)
        {
            BoundingBox bb = new BoundingBox(left, top, width, height);
            Dictionary<string, object> cTags = new Dictionary<string,object>();
            foreach(string key in tags.Keys)
                cTags[key] = tags[key];

            return Tree.FromBoundingBox(bb, cTags);
        
       }
Example #23
0
        private OldInstance(SerializationInfo info, StreamingContext context) {
            _class = (OldClass)info.GetValue("__class__", typeof(OldClass));
            _dict = MakeDictionary(_class);

            List<object> keys = (List<object>)info.GetValue("keys", typeof(List<object>));
            List<object> values = (List<object>)info.GetValue("values", typeof(List<object>));
            for (int i = 0; i < keys.Count; i++) {
                _dict[keys[i]] = values[i];
            }
        }
Example #24
0
        public static MutableTree from_bounding_box(IBoundingBox box, PythonDictionary dict)
        {
            var csharpDict = new Dictionary<string, object>();
            foreach (string key in dict.Keys)
            {
                csharpDict[key] = dict[key];
            }

            return MutableTree.FromBoundingBox(box, csharpDict);
        }
 public static PythonDictionary Get__dict__(CodeContext context, NamespaceTracker self) {
     PythonDictionary res = new PythonDictionary();
     foreach (var kvp in self) {
         if (kvp.Value is TypeGroup || kvp.Value is NamespaceTracker) {
             res[kvp.Key] = kvp.Value;
         } else {
             res[kvp.Key] = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)kvp.Value).Type);
         }
     }
     return res;
 }
Example #26
0
            public ArrayType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict)
                : base(context, name, bases, dict) {
                object len;
                int iLen;
                if (!dict.TryGetValue("_length_", out len) || !(len is int) || (iLen = (int)len) < 0) {
                    throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer");
                }

                object type;
                if (!dict.TryGetValue("_type_", out type)) {
                    throw PythonOps.AttributeError("class must define a '_type_' attribute");
                }

                _length = iLen;
                _type = (INativeType)type;

                if (_type is SimpleType) {
                    SimpleType st = (SimpleType)_type;
                    if (st._type == SimpleTypeKind.Char) {
                        // TODO: (c_int * 2).value isn't working
                        SetCustomMember(context,
                            "value",
                            new ReflectedExtensionProperty(
                                new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetCharArrayValue")),
                                NameType.Property | NameType.Python
                            )
                        );

                        SetCustomMember(context,
                            "raw",
                            new ReflectedExtensionProperty(
                                new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")),
                                NameType.Property | NameType.Python
                            )
                        );
                    } else if (st._type == SimpleTypeKind.WChar) {
                        SetCustomMember(context,
                            "value",
                            new ReflectedExtensionProperty(
                                new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayValue")),
                                NameType.Property | NameType.Python
                            )
                        );

                        SetCustomMember(context,
                            "raw",
                            new ReflectedExtensionProperty(
                                new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")),
                                NameType.Property | NameType.Python
                            )
                        );
                    }
                }
            }
Example #27
0
        public static object CallWithKeywordArgs(CodeContext/*!*/ context, object func, object[] args, string[] names) {
            PythonDictionary dict = new PythonDictionary();
            for (int i = 0; i < names.Length; i++) {
                dict[names[i]] = args[args.Length - names.Length + i];
            }
            object[] newargs = new object[args.Length - names.Length];
            for (int i = 0; i < newargs.Length; i++) {
                newargs[i] = args[i];
            }

            return CallWithKeywordArgs(context, func, newargs, dict);
        }
Example #28
0
        public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
            if (!context.HasModuleState(_defaultTimeoutKey)) {
                context.SetModuleState(_defaultTimeoutKey, null);
            }

            context.SetModuleState(_defaultBufsizeKey, DefaultBufferSize);

            PythonType socketErr = GetSocketError(context, dict);
            context.EnsureModuleException("socketherror", socketErr, dict, "herror", "socket");
            context.EnsureModuleException("socketgaierror", socketErr, dict, "gaierror", "socket");
            context.EnsureModuleException("sockettimeout", socketErr, dict, "timeout", "socket");
        }
 UpdateMethodTableObj(PythonDictionary methodTable, object potentialMethodSource)
 {
     if (Builtin.hasattr(this.scratchContext, potentialMethodSource, "_dispatcher"))
     {
         PythonDictionary methodSource = (PythonDictionary)Builtin.getattr(
             this.scratchContext, Builtin.getattr(
                 this.scratchContext, potentialMethodSource, "_dispatcher"), "table");
         methodTable.update(this.scratchContext, methodSource);
     }
     this.Store(potentialMethodSource);
     return potentialMethodSource;
 }
Example #30
0
            public PointerType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members)
                : base(context, name, bases, members) {

                object type;
                if (members.TryGetValue("_type_", out type) && !(type is INativeType)) {
                    throw PythonOps.TypeError("_type_ must be a type");
                }
                _type = (INativeType)type;
                if (_type != null) {
                    _typeFormat = _type.TypeFormat;
                }
            }
Example #31
0
 private object DoImport(CodeContext context, string moduleName, PythonDictionary globals, PythonDictionary locals, PythonTuple tuple)
 {
     if (WhitelistNamespaces.Any(moduleName.StartsWith) || moduleName.Equals("System"))
     {
         return(IronPython.Modules.Builtin.__import__(context, moduleName));
     }
     return(null);
 }
Example #32
0
 bool IPythonObject.ReplaceDict(PythonDictionary dict)
 {
     return((GetObject() as IPythonObject).ReplaceDict(dict));
 }
Example #33
0
 public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict)
 {
     // we depend on locale, it needs to be initialized
     PythonLocale.EnsureLocaleInitialized(context);
 }
Example #34
0
 public DynamicData DynamicData(PythonDictionary dict)
 {
     return(new DynamicData(dict));
 }
Example #35
0
        internal OldClass(string name, PythonTuple bases, PythonDictionary /*!*/ dict, string instanceNames)
        {
            _bases = ValidateBases(bases);

            Init(name, dict, instanceNames);
        }
 /// <summary> APIの設定を用いてスクリプト読み込み器を初期化します。 </summary>
 /// <param name="api"></param>
 /// <param name="dictionary">スクリプトのグローバル変数を入れておくディクショナリ</param>
 public IronPythonMainScriptReader(IScriptApi api, PythonDictionary dictionary)
 {
     InitializeEngine(api, dictionary);
 }
Example #37
0
        public static object __new__(CodeContext /*!*/ context, [NotNull] PythonType cls, string name, PythonTuple bases, PythonDictionary /*!*/ dict)
        {
            if (dict == null)
            {
                throw PythonOps.TypeError("dict must be a dictionary");
            }
            else if (cls != TypeCache.OldClass)
            {
                throw PythonOps.TypeError("{0} is not a subtype of classobj", cls.Name);
            }

            if (!dict.ContainsKey("__module__"))
            {
                object moduleValue;
                if (context.TryGetGlobalVariable("__name__", out moduleValue))
                {
                    dict["__module__"] = moduleValue;
                }
            }

            foreach (object o in bases)
            {
                if (o is PythonType)
                {
                    return(PythonOps.MakeClass(context, name, bases._data, String.Empty, dict));
                }
            }

            return(new OldClass(name, bases, dict, String.Empty));
        }
Example #38
0
            private object UpdateStack(object res)
            {
                ProcStack curStack = _stack.Peek();

                switch (curStack.StackType)
                {
                case StackType.Dict:
                    PythonDictionary od = curStack.StackObj as PythonDictionary;
                    if (curStack.HaveKey)
                    {
                        od[curStack.Key] = res;
                        curStack.HaveKey = false;
                    }
                    else
                    {
                        curStack.HaveKey = true;
                        curStack.Key     = res;
                    }
                    break;

                case StackType.Tuple:
                    List <object> objs = curStack.StackObj as List <object>;
                    objs.Add(res);
                    curStack.StackCount--;
                    if (curStack.StackCount == 0)
                    {
                        _stack.Pop();
                        object tuple = PythonTuple.Make(objs);
                        if (_stack.Count == 0)
                        {
                            _result = tuple;
                        }
                        return(tuple);
                    }
                    break;

                case StackType.List:
                    PythonList ol = curStack.StackObj as PythonList;
                    ol.AddNoLock(res);
                    curStack.StackCount--;
                    if (curStack.StackCount == 0)
                    {
                        _stack.Pop();
                        if (_stack.Count == 0)
                        {
                            _result = ol;
                        }
                        return(ol);
                    }
                    break;

                case StackType.Set:
                    SetCollection os = curStack.StackObj as SetCollection;
                    os.add(res);
                    curStack.StackCount--;
                    if (curStack.StackCount == 0)
                    {
                        _stack.Pop();
                        if (_stack.Count == 0)
                        {
                            _result = os;
                        }
                        return(os);
                    }
                    break;

                case StackType.FrozenSet:
                    List <object> ofs = curStack.StackObj as List <object>;
                    ofs.Add(res);
                    curStack.StackCount--;
                    if (curStack.StackCount == 0)
                    {
                        _stack.Pop();
                        object frozenSet = FrozenSetCollection.Make(ofs);
                        if (_stack.Count == 0)
                        {
                            _result = frozenSet;
                        }
                        return(frozenSet);
                    }
                    break;
                }
                return(null);
            }
Example #39
0
        public static void warn(CodeContext context, object message, [DefaultParameterValue(null)] PythonType category, [DefaultParameterValue(1)] int stacklevel)
        {
            PythonContext    pContext = PythonContext.GetContext(context);
            List             argv     = pContext.GetSystemStateValue("argv") as List;
            PythonDictionary dict     = pContext.GetSystemStateValue("__dict__") as PythonDictionary;

            if (PythonOps.IsInstance(message, PythonExceptions.Warning))
            {
                category = DynamicHelpers.GetPythonType(message);
            }
            if (category == null)
            {
                category = PythonExceptions.UserWarning;
            }
            if (!category.IsSubclassOf(PythonExceptions.Warning))
            {
                throw PythonOps.ValueError("category is not a subclass of Warning");
            }

            TraceBackFrame   caller = null;
            PythonDictionary globals;
            int lineno;

            if (PythonContext.GetContext(context).PythonOptions.Frames)
            {
                try {
                    caller = SysModule._getframeImpl(context, stacklevel);
                } catch (ValueErrorException) { }
            }
            if (caller == null)
            {
                globals = Builtin.globals(context) as PythonDictionary;
                lineno  = 1;
            }
            else
            {
                globals = caller.f_globals;
                lineno  = (int)caller.f_lineno;
            }

            string module;
            string filename;

            if (globals != null && globals.ContainsKey("__name__"))
            {
                module = (string)globals.get("__name__");
            }
            else
            {
                module = "<string>";
            }

            filename = globals.get("__file__") as string;
            if (filename == null || filename == "")
            {
                if (module == "__main__")
                {
                    if (argv != null && argv.Count > 0)
                    {
                        filename = argv[0] as string;
                    }
                    else
                    {
                        // interpreter lacks sys.argv
                        filename = "__main__";
                    }
                }
                if (filename == null || filename == "")
                {
                    filename = module;
                }
            }

            PythonDictionary registry = (PythonDictionary)globals.setdefault("__warningregistry__", new PythonDictionary());

            warn_explicit(context, message, category, filename, lineno, module, registry, globals);
        }
Example #40
0
 PythonDictionary IPythonObject.SetDict(PythonDictionary dict)
 {
     return((GetObject() as IPythonObject).SetDict(dict));
 }
Example #41
0
        /// <summary>
        /// Translates our CallSignature into a DLR Argument list and gives the simple MetaObject's which are extracted
        /// from the tuple or dictionary parameters being splatted.
        /// </summary>
        private void TranslateArguments(DynamicMetaObject target, DynamicMetaObject /*!*/[] /*!*/ args, out CallInfo /*!*/ callInfo, out List <Expression /*!*/> /*!*/ metaArgs, out Expression test, out BindingRestrictions restrictions)
        {
            Argument[] argInfo = _signature.GetArgumentInfos();

            List <string> namedArgNames = new List <string>();

            metaArgs = new List <Expression>();
            metaArgs.Add(target.Expression);
            Expression splatArgTest   = null;
            Expression splatKwArgTest = null;

            restrictions = BindingRestrictions.Empty;

            for (int i = 0; i < argInfo.Length; i++)
            {
                Argument ai = argInfo[i];

                switch (ai.Kind)
                {
                case ArgumentType.Dictionary:
                    PythonDictionary iac      = (PythonDictionary)args[i].Value;
                    List <string>    argNames = new List <string>();

                    foreach (KeyValuePair <object, object> kvp in iac)
                    {
                        string key = (string)kvp.Key;
                        namedArgNames.Add(key);
                        argNames.Add(key);

                        metaArgs.Add(
                            Expression.Call(
                                AstUtils.Convert(args[i].Expression, typeof(PythonDictionary)),
                                typeof(PythonDictionary).GetMethod("get_Item", new[] { typeof(object) }),
                                AstUtils.Constant(key)
                                )
                            );
                    }

                    restrictions   = restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(args[i].Expression, args[i].GetLimitType()));
                    splatKwArgTest = Expression.Call(
                        typeof(PythonOps).GetMethod(nameof(PythonOps.CheckDictionaryMembers)),
                        AstUtils.Convert(args[i].Expression, typeof(PythonDictionary)),
                        AstUtils.Constant(argNames.ToArray())
                        );
                    break;

                case ArgumentType.List:
                    IList <object> splattedArgs = (IList <object>)args[i].Value;
                    splatArgTest = Expression.Equal(
                        Expression.Property(AstUtils.Convert(args[i].Expression, args[i].GetLimitType()), typeof(ICollection <object>).GetProperty("Count")),
                        AstUtils.Constant(splattedArgs.Count)
                        );

                    for (int splattedArg = 0; splattedArg < splattedArgs.Count; splattedArg++)
                    {
                        metaArgs.Add(
                            Expression.Call(
                                AstUtils.Convert(args[i].Expression, typeof(IList <object>)),
                                typeof(IList <object>).GetMethod("get_Item"),
                                AstUtils.Constant(splattedArg)
                                )
                            );
                    }

                    restrictions = restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(args[i].Expression, args[i].GetLimitType()));
                    break;

                case ArgumentType.Named:
                    namedArgNames.Add(ai.Name);
                    metaArgs.Add(args[i].Expression);
                    break;

                case ArgumentType.Simple:
                    metaArgs.Add(args[i].Expression);
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }

            callInfo = new CallInfo(metaArgs.Count - 1, namedArgNames.ToArray());

            test = splatArgTest;
            if (splatKwArgTest != null)
            {
                if (test != null)
                {
                    test = Expression.AndAlso(test, splatKwArgTest);
                }
                else
                {
                    test = splatKwArgTest;
                }
            }
        }
Example #42
0
        public static void warn_explicit(CodeContext context, object message, PythonType category, string filename, int lineno, [DefaultParameterValue(null)] string module, [DefaultParameterValue(null)] PythonDictionary registry, [DefaultParameterValue(null)] object module_globals)
        {
            PythonContext    pContext = PythonContext.GetContext(context);
            PythonDictionary fields   = (PythonDictionary)pContext.GetModuleState(_keyFields);

            PythonExceptions.BaseException msg;
            string text; // message text

            if (string.IsNullOrEmpty(module))
            {
                module = (filename == null || filename == "") ? "<unknown>" : filename;
                if (module.EndsWith(".py"))
                {
                    module = module.Substring(0, module.Length - 3);
                }
            }
            if (registry == null)
            {
                registry = new PythonDictionary();
            }
            if (PythonOps.IsInstance(message, PythonExceptions.Warning))
            {
                msg      = (PythonExceptions.BaseException)message;
                text     = msg.ToString();
                category = DynamicHelpers.GetPythonType(msg);
            }
            else
            {
                text = message.ToString();
                msg  = PythonExceptions.CreatePythonThrowable(category, message.ToString());
            }

            PythonTuple key = PythonTuple.MakeTuple(text, category, lineno);

            if (registry.ContainsKey(key))
            {
                return;
            }

            string      action      = Converter.ConvertToString(fields[_keyDefaultAction]);
            PythonTuple last_filter = null;
            bool        loop_break  = false;

            foreach (PythonTuple filter in (List)fields[_keyFilters])
            {
                last_filter = filter;
                action      = (string)filter._data[0];
                PythonRegex.RE_Pattern fMsg = (PythonRegex.RE_Pattern)filter._data[1];
                PythonType             fCat = (PythonType)filter._data[2];
                PythonRegex.RE_Pattern fMod = (PythonRegex.RE_Pattern)filter._data[3];
                int fLno;
                if (filter._data[4] is int)
                {
                    fLno = (int)filter._data[4];
                }
                else
                {
                    fLno = (Extensible <int>)filter._data[4];
                }

                if ((fMsg == null || fMsg.match(text) != null) &&
                    category.IsSubclassOf(fCat) &&
                    (fMod == null || fMod.match(module) != null) &&
                    (fLno == 0 || fLno == lineno))
                {
                    loop_break = true;
                    break;
                }
            }
            if (!loop_break)
            {
                action = Converter.ConvertToString(fields[_keyDefaultAction]);
            }

            switch (action)
            {
            case "ignore":
                registry.Add(key, 1);
                return;

            case "error":
                throw msg.GetClrException();

            case "once":
                registry.Add(key, 1);
                PythonTuple      onceKey  = PythonTuple.MakeTuple(text, category);
                PythonDictionary once_reg = (PythonDictionary)fields[_keyOnceRegistry];
                if (once_reg.ContainsKey(onceKey))
                {
                    return;
                }
                once_reg.Add(key, 1);
                break;

            case "always":
                break;

            case "module":
                registry.Add(key, 1);
                PythonTuple altKey = PythonTuple.MakeTuple(text, category, 0);
                if (registry.ContainsKey(altKey))
                {
                    return;
                }
                registry.Add(altKey, 1);
                break;

            case "default":
                registry.Add(key, 1);
                break;

            default:
                throw PythonOps.RuntimeError("Unrecognized action ({0}) in warnings.filters:\n {1}", action, last_filter);
            }

            object warnings = pContext.GetWarningsModule();

            if (warnings != null)
            {
                PythonCalls.Call(
                    context,
                    PythonOps.GetBoundAttr(context, warnings, "showwarning"),
                    msg, category, filename, lineno, null, null);
            }
            else
            {
                showwarning(context, msg, category, filename, lineno, null, null);
            }
        }
Example #43
0
 public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict)
 {
     context.EnsureModuleException(_ErrorKey, PythonExceptions.ValueError, dict, "Error", "binascii");
     context.EnsureModuleException(_IncompleteKey, dict, "Incomplete", "binascii");
 }
Example #44
0
 public static void PerformModuleReload(PythonContext /*!*/ context, PythonDictionary /*!*/ dict)
 {
     EnsureLocaleInitialized(context);
     context.EnsureModuleException("_localeerror", dict, "Error", "_locale");
 }
Example #45
0
        /// <summary>
        /// Implements the default __reduce_ex__ method as specified by PEP 307 case 3 (new-style instance, protocol 2)
        /// </summary>
        private static PythonTuple ReduceProtocol2(CodeContext /*!*/ context, object self)
        {
            PythonType myType = DynamicHelpers.GetPythonType(self);

            object func, state, listIterator, dictIterator;

            object[] funcArgs;

            func = PythonContext.GetContext(context).NewObject;

            object getNewArgsCallable;

            if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out getNewArgsCallable))
            {
                // TypeError will bubble up if __getnewargs__ isn't callable
                PythonTuple newArgs = PythonOps.CallWithContext(context, getNewArgsCallable, self) as PythonTuple;
                if (newArgs == null)
                {
                    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;
                IPythonObject ipo = self as IPythonObject;
                if (ipo != null)
                {
                    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 {