예제 #1
0
        internal CodeContext CreateContext() {            
            if (_optimizedContext == null) {
                CachedOptimizedCodeAttribute[] attrs = (CachedOptimizedCodeAttribute[])_code.Method.GetCustomAttributes(typeof(CachedOptimizedCodeAttribute), false);

                // create the CompilerContext for the ScriptCode
                CachedOptimizedCodeAttribute optimizedCode = attrs[0];

                // create the storage for the global scope
                Dictionary<string, PythonGlobal> globals = new Dictionary<string, PythonGlobal>(StringComparer.Ordinal);
                PythonGlobal[] globalArray = new PythonGlobal[optimizedCode.Names.Length];
                var dict = new PythonDictionary(new GlobalDictionaryStorage(globals, globalArray));

                ModuleContext mc = new ModuleContext(dict, (PythonContext)SourceUnit.LanguageContext);
                CodeContext res = mc.GlobalContext;

                for (int i = 0; i < optimizedCode.Names.Length; i++) {
                    string name = optimizedCode.Names[i];
                    globalArray[i] = globals[name] = new PythonGlobal(res, name);
                }

                _optimizedContext = CreateTopLevelCodeContext(dict, (PythonContext)SourceUnit.LanguageContext);
            }
            return _optimizedContext;
        }
예제 #2
0
 protected static CodeContext/*!*/ CreateTopLevelCodeContext(PythonDictionary/*!*/ dict, LanguageContext/*!*/ context) {
     ModuleContext modContext = new ModuleContext(dict, (PythonContext)context);
     return modContext.GlobalContext;
 }
예제 #3
0
        protected override Scope/*!*/ CreateScope() {
            ModuleOptions trueDiv = (PythonContext.PythonOptions.DivisionOptions == PythonDivisionOptions.New) ? ModuleOptions.TrueDivision : ModuleOptions.None;
            var modCtx = new ModuleContext(new PythonDictionary(), PythonContext);
            modCtx.Features = trueDiv;
            modCtx.InitializeBuiltins(true);

            PythonContext.PublishModule("__main__", modCtx.Module);
            modCtx.Globals["__doc__"] = null;
            modCtx.Globals["__name__"] = "__main__";

            return modCtx.GlobalScope;
        }
예제 #4
0
        /// <summary>
        /// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py)
        /// 
        /// level indiciates whether to perform absolute or relative imports.
        ///     -1 indicates both should be performed
        ///     0 indicates only absolute imports should be performed
        ///     Positive numbers indicate the # of parent directories to search relative to the calling module
        /// </summary>        
        public static object ImportModule(CodeContext/*!*/ context, object globals, string/*!*/ modName, bool bottom, int level) {
            if (modName.IndexOf(Path.DirectorySeparatorChar) != -1) {
                throw PythonOps.ImportError("Import by filename is not supported.", modName);
            }

            string package = null;
            object attribute;
            PythonDictionary pyGlobals = globals as PythonDictionary;
            if (pyGlobals != null) {
                if (pyGlobals._storage.TryGetPackage(out attribute)) {
                    package = attribute as string;
                    if (package == null && attribute != null) {
                        throw PythonOps.ValueError("__package__ set to non-string");
                    }
                } else {
                    package = null;
                    if (level > 0) {
                        // explicit relative import, calculate and store __package__
                        object pathAttr, nameAttr;
                        if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) {
                            if (pyGlobals._storage.TryGetPath(out pathAttr)) {
                                pyGlobals["__package__"] = nameAttr;
                            } else {
                                pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0];
                            }
                        }
                    }
                }
            }

            object newmod = null;
            string[] parts = modName.Split('.');
            string finalName = null;

            if (level != 0) {
                // try a relative import

                // if importing a.b.c, import "a" first and then import b.c from a
                string name;    // name of the module we are to import in relation to the current module
                PythonModule parentModule;
                List path;      // path to search
                if (TryGetNameAndPath(context, globals, parts[0], level, package, out name, out path, out parentModule)) {
                    finalName = name;
                    // import relative
                    if (!TryGetExistingOrMetaPathModule(context, name, path, out newmod)) {
                        newmod = ImportFromPath(context, parts[0], name, path);
                        if (newmod != null && parentModule != null) {
                            parentModule.__dict__[modName] = newmod;
                        }
                    } else if (parts.Length == 1) {
                        // if we imported before having the assembly
                        // loaded and then loaded the assembly we want
                        // to make the assembly available now.

                        if (newmod is NamespaceTracker) {
                            context.ShowCls = true;
                        }
                    }
                }
            }

            if (level <= 0) {
                // try an absolute import
                if (newmod == null) {
                    object parentPkg;
                    if (!String.IsNullOrEmpty(package) && !PythonContext.GetContext(context).SystemStateModules.TryGetValue(package, out parentPkg)) {
                        PythonModule warnModule = new PythonModule();
                        warnModule.__dict__["__file__"] = package;
                        warnModule.__dict__["__name__"] = package;
                        ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext);
                        PythonOps.Warn(
                            modContext.GlobalContext,
                            PythonExceptions.RuntimeWarning,
                            "Parent module '{0}' not found while handling absolute import",
                            package);
                    }

                    newmod = ImportTopAbsolute(context, parts[0]);
                    finalName = parts[0];
                    if (newmod == null) {
                        return null;
                    }
                }
            }

            // now import the a.b.c etc.  a needs to be included here
            // because the process of importing could have modified
            // sys.modules.
            object next = newmod;
            string curName = null;
            for (int i = 0; i < parts.Length; i++) {
                curName = i == 0 ? finalName : curName + "." + parts[i];
                object tmpNext;
                if (TryGetExistingModule(context, curName, out tmpNext)) {
                    next = tmpNext;
                    if (i == 0) {
                        // need to update newmod if we pulled it out of sys.modules
                        // just in case we're in bottom mode.
                        newmod = next;
                    }
                } else if (i != 0) {
                    // child module isn't loaded yet, import it.
                    next = ImportModuleFrom(context, next, parts[i]);
                } else {
                    // top-level module doesn't exist in sys.modules, probably
                    // came from some weird meta path hook.
                    newmod = next;
                }
            }

            return bottom ? next : newmod;
        }
예제 #5
0
 /// <summary>
 /// Creates a new CodeContext which is backed by the specified Python dictionary.
 /// </summary>
 public CodeContext(PythonDictionary/*!*/ dict, ModuleContext/*!*/ moduleContext) {
     ContractUtils.RequiresNotNull(dict, "dict");
     ContractUtils.RequiresNotNull(moduleContext, "moduleContext");
     _dict = dict;
     _modContext = moduleContext;
 }
예제 #6
0
        /// <summary>
        /// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py)
        ///
        /// level indiciates whether to perform absolute or relative imports.
        ///     -1 indicates both should be performed
        ///     0 indicates only absolute imports should be performed
        ///     Positive numbers indicate the # of parent directories to search relative to the calling module
        /// </summary>
        public static object ImportModule(CodeContext /*!*/ context, object globals, string /*!*/ modName, bool bottom, int level)
        {
            if (modName.IndexOf(Path.DirectorySeparatorChar) != -1)
            {
                throw PythonOps.ImportError("Import by filename is not supported.", modName);
            }

            string package = null;
            object attribute;

            if (globals is PythonDictionary pyGlobals)
            {
                if (pyGlobals._storage.TryGetPackage(out attribute))
                {
                    package = attribute as string;
                    if (package == null && attribute != null)
                    {
                        throw PythonOps.ValueError("__package__ set to non-string");
                    }
                }
                else
                {
                    package = null;
                    if (level > 0)
                    {
                        // explicit relative import, calculate and store __package__
                        object pathAttr, nameAttr;
                        if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string)
                        {
                            if (pyGlobals._storage.TryGetPath(out pathAttr))
                            {
                                pyGlobals["__package__"] = nameAttr;
                            }
                            else
                            {
                                pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0];
                            }
                        }
                    }
                }
            }

            object newmod = null;
            string firstName;
            int    firstDot = modName.IndexOf('.');

            if (firstDot == -1)
            {
                firstName = modName;
            }
            else
            {
                firstName = modName.Substring(0, firstDot);
            }
            string finalName = null;

            if (level != 0)
            {
                // try a relative import

                // if importing a.b.c, import "a" first and then import b.c from a
                string       name; // name of the module we are to import in relation to the current module
                PythonModule parentModule;
                List         path; // path to search
                if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule))
                {
                    finalName = name;
                    // import relative
                    if (!TryGetExistingOrMetaPathModule(context, name, path, out newmod))
                    {
                        newmod = ImportFromPath(context, firstName, name, path);
                        if (newmod == null)
                        {
                            // add an indirection entry saying this module does not exist
                            // see http://www.python.org/doc/essays/packages.html "Dummy Entries"
                            context.LanguageContext.SystemStateModules[name] = null;
                        }
                        else if (parentModule != null)
                        {
                            parentModule.__dict__[firstName] = newmod;
                        }
                    }
                    else if (firstDot == -1)
                    {
                        // if we imported before having the assembly
                        // loaded and then loaded the assembly we want
                        // to make the assembly available now.

                        if (newmod is NamespaceTracker)
                        {
                            context.ShowCls = true;
                        }
                    }
                }
            }

            if (level <= 0)
            {
                // try an absolute import
                if (newmod == null)
                {
                    object parentPkg;
                    if (!String.IsNullOrEmpty(package) && !context.LanguageContext.SystemStateModules.TryGetValue(package, out parentPkg))
                    {
                        PythonModule warnModule = new PythonModule();
                        warnModule.__dict__["__file__"] = package;
                        warnModule.__dict__["__name__"] = package;
                        ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext);
                        PythonOps.Warn(
                            modContext.GlobalContext,
                            PythonExceptions.RuntimeWarning,
                            "Parent module '{0}' not found while handling absolute import",
                            package);
                    }
                    newmod    = ImportTopAbsolute(context, firstName);
                    finalName = firstName;
                    if (newmod == null)
                    {
                        return(null);
                    }
                }
            }

            // now import the a.b.c etc.  a needs to be included here
            // because the process of importing could have modified
            // sys.modules.
            string[] parts   = modName.Split('.');
            object   next    = newmod;
            string   curName = null;

            for (int i = 0; i < parts.Length; i++)
            {
                curName = i == 0 ? finalName : curName + "." + parts[i];
                object tmpNext;
                if (TryGetExistingModule(context, curName, out tmpNext))
                {
                    next = tmpNext;
                    if (i == 0)
                    {
                        // need to update newmod if we pulled it out of sys.modules
                        // just in case we're in bottom mode.
                        newmod = next;
                    }
                }
                else if (i != 0)
                {
                    // child module isn't loaded yet, import it.
                    next = ImportModuleFrom(context, next, parts, i);
                }
                else
                {
                    // top-level module doesn't exist in sys.modules, probably
                    // came from some weird meta path hook.
                    newmod = next;
                }
            }

            return(bottom ? next : newmod);
        }
예제 #7
0
 public PythonScopeExtension(PythonContext context, PythonModule module, ModuleContext modContext)
     : base(module.Scope) {
     _module = module;
     _modContext = modContext;
 }
예제 #8
0
 public PythonScopeExtension(PythonContext context, Scope scope) : base(scope) {
     _module = new PythonModule(context, scope);
     _modContext = new ModuleContext(_module, context);
 }
예제 #9
0
파일: PythonAst.cs 프로젝트: Xiaoqing/main
        internal override void FinishBind(PythonNameBinder binder) {
            _contextInfo = CompilationMode.GetContext();

            // create global variables for compiler context.
            PythonGlobal[] globalArray = new PythonGlobal[Variables == null ? 0 : Variables.Count];
            Dictionary<string, PythonGlobal> globals = new Dictionary<string, PythonGlobal>();
            GlobalDictionaryStorage storage = new GlobalDictionaryStorage(globals, globalArray);
            var modContext = _modContext = new ModuleContext(new PythonDictionary(storage), PyContext);

            if (_mode == CompilationMode.ToDisk) {
                _arrayExpression = _globalArray;
            } else {
                var newArray = new ConstantExpression(globalArray);
                newArray.Parent = this;
                _arrayExpression = newArray;
            }

            if (Variables != null) {
                int globalIndex = 0;
                foreach (PythonVariable variable in Variables.Values) {
                    PythonGlobal global = new PythonGlobal(modContext.GlobalContext, variable.Name);
                    _globalVariables[variable] = CompilationMode.GetGlobal(GetGlobalContext(), globals.Count, variable, global);
                    globalArray[globalIndex++] = globals[variable.Name] = global;
                }
            }

            CompilationMode.PublishContext(modContext.GlobalContext, _contextInfo);
        }
예제 #10
0
 public PythonScopeExtension(PythonContext context, PythonModule module, ModuleContext modContext)
     : base(module.Scope)
 {
     _module     = module;
     _modContext = modContext;
 }
예제 #11
0
 public PythonScopeExtension(PythonContext context, Scope scope) : base(scope)
 {
     _module     = new PythonModule(context, scope);
     _modContext = new ModuleContext(_module, context);
 }
예제 #12
0
 internal static CodeContext/*!*/ CreateDefaultCLSContext(PythonContext/*!*/ context) {
     ModuleContext mc = new ModuleContext(new PythonDictionary(), context);
     mc.ShowCls = true;
     return mc.GlobalContext;
 }
예제 #13
0
 public ArrayGlobalAllocator(PythonContext/*!*/ context) {
     _globalArray = Ast.Parameter(typeof(PythonGlobal[]), "$globalArray");
     _modContext = new ModuleContext(new PythonDictionary(new GlobalDictionaryStorage(_globalVals)), context);
     _context = _modContext.GlobalContext;
     _array = new GlobalArrayConstant();
 }