protected override void ExecuteInternal()
        {
            var pc = HostingHelpers.GetLanguageContext(Engine) as PythonContext;

            pc.SetModuleState(typeof(ScriptEngine), Engine);
            Type     t   = pc.GetType();
            Assembly ass = t.Assembly;

            try {
                base.ExecuteInternal();
            }
            catch (ImportException iex)
            {
                Console.WriteLine(iex.ToString(), Style.Warning);
            }
        }
        public IPyCompiler.Tokenizer CreateTokenizer(string text)
        {
            ScriptEngine  engine  = Python.CreateEngine();
            PythonContext context = HostingHelpers.GetLanguageContext(engine) as PythonContext;

            StringTextContentProvider textProvider = new StringTextContentProvider(text);
            SourceUnit source = context.CreateSourceUnit(textProvider, String.Empty, SourceCodeKind.SingleStatement);

            PythonCompilerSink sink = new PythonCompilerSink();

            IPyCompiler.PythonCompilerOptions options = new IPyCompiler.PythonCompilerOptions();

            tokenizer = new IPyCompiler.Tokenizer(sink, options);
            tokenizer.Initialize(source);
            return(tokenizer);
        }
示例#3
0
        void CreateDecompileEngine()
        {
            ScriptEngine python = Python.CreateEngine();

            // Disable Zip (This causes a weird error)
            var pc    = HostingHelpers.GetLanguageContext(python) as PythonContext;
            var hooks = pc.SystemState.Get__dict__()["path_hooks"] as List;

            hooks.Clear();

            python.SetSearchPaths(new List <string>()
            {
                @"Resources\DAKompiler", @"Lib"
            });
            _pythonDecompiler = python.CreateScriptSourceFromString(decompile_py).Compile();
        }
        public FromImportStatement ParseStatement(string text)
        {
            ScriptEngine  engine  = Python.CreateEngine();
            PythonContext context = HostingHelpers.GetLanguageContext(engine) as PythonContext;

            StringTextContentProvider textProvider = new StringTextContentProvider(text);
            SourceUnit source = context.CreateSourceUnit(textProvider, String.Empty, SourceCodeKind.SingleStatement);

            PythonCompilerSink sink            = new PythonCompilerSink();
            CompilerContext    compilerContext = new CompilerContext(source, new PythonCompilerOptions(), sink);

            PythonOptions options = new PythonOptions();

            using (Parser parser = Parser.CreateParser(compilerContext, options)) {
                return(parser.ParseSingleStatement().Body as FromImportStatement);
            }
        }
示例#5
0
            protected override void ExecuteInternal()
            {
                PythonContext ctx = HostingHelpers.GetLanguageContext(Engine) as PythonContext;

                Runtime.IO.SetOutput(new MemoryStream(), _control.Output);
                Runtime.IO.SetErrorOutput(new MemoryStream(), _control.Error);

                ctx.SetModuleState(typeof(ScriptEngine), Engine);
                Runtime.LoadAssembly(typeof(MainForm).Assembly);
                ICollection <string> searchPaths = Engine.GetSearchPaths();
                string item = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonLib");

                searchPaths.Add(item);
                Engine.SetSearchPaths(searchPaths);

                base.ExecuteInternal();
            }
示例#6
0
        private static string ExecutePython(string scriptContent, PythonModel model)
        {
            var engine = Python.CreateEngine();
            var pc     = HostingHelpers.GetLanguageContext(engine) as PythonContext;
            var hooks  = pc?.SystemState.Get__dict__()["path_hooks"] as List;

            hooks?.Clear();
            var searchPaths = engine.GetSearchPaths();

            searchPaths.Add(ConfigurationManager.AppSettings["PythonLibPath"]);
            engine.SetSearchPaths(searchPaths);

            using (var ms = new MemoryStream())
                using (var sw = new StreamWriter(ms))
                {
                    engine.Runtime.IO.SetOutput(ms, sw);
                    engine.Runtime.IO.SetErrorOutput(ms, sw);

                    try
                    {
                        var sc   = engine.CreateScriptSourceFromString(scriptContent);
                        var code = sc.Compile();

                        var scope = engine.CreateScope();
                        scope.SetVariable("model", model);
                        scope.SetVariable("Data", model.Data);

                        var qf = new QueryFunctions(model.db, model.dictionary);
                        scope.SetVariable("q", qf);
                        code.Execute(scope);

                        ms.Position = 0;

                        using (var sr = new StreamReader(ms))
                        {
                            var s = sr.ReadToEnd();
                            return(s);
                        }
                    }
                    catch (Exception ex)
                    {
                        var err = engine.GetService <ExceptionOperations>().FormatException(ex);
                        throw new Exception(err);
                    }
                }
        }
示例#7
0
        public static int Run(List <string> /*!*/ args)
        {
            if (Thread.CurrentThread.CurrentCulture.ToString() != "en-US")
            {
                Console.WriteLine("Current culture: {0}", Thread.CurrentThread.CurrentCulture);
            }

            if (!ParseArguments(args))
            {
                return(-3);
            }

            int status = 0;

            if (_runTokenizerDriver)
            {
                TokenizerTestDriver driver = new TokenizerTestDriver((RubyContext)HostingHelpers.GetLanguageContext(Ruby.CreateEngine()));
                if (!driver.ParseArgs(args))
                {
                    return(-3);
                }

                status = driver.RunTests();
            }
            else
            {
                InitializeDomain();
                Driver driver = new Driver();

                if (Manual.TestCode.Trim().Length == 0)
                {
                    status = driver.RunUnitTests(args);
                }
                else
                {
                    driver.RunManualTest();

                    // for case the test is forgotten, this would fail the test suite:
                    status = -2;
                }
            }

            // return failure on bad filter (any real failures throw)
            return(status);
        }
示例#8
0
        public void RestartEngine()
        {
            if (!m_runningScript)
            {
                if (ScriptEngineRestarting != null)
                {
                    ScriptEngineRestarting(this, new EventArgs());
                }

                var context = HostingHelpers.GetLanguageContext(m_engine);
                context.Shutdown();
                m_engine = CreateAndInitEngine();

                if (ScriptEngineRestarted != null)
                {
                    ScriptEngineRestarted(this, new EventArgs());
                }
            }
        }
示例#9
0
        public IronPythonInterpreter(ScriptEngine engine)
        {
            _engine = engine;
            var pythonContext = HostingHelpers.GetLanguageContext(_engine) as PythonContext;

            _codeContextCls = new ModuleContext(new PythonDictionary(), pythonContext).GlobalContext;
            _codeContextCls.ModuleContext.ShowCls = true;

            _codeContext = new ModuleContext(
                new PythonDictionary(),
                HostingHelpers.GetLanguageContext(_engine) as PythonContext
                ).GlobalContext;

            _namespaceTracker = new TopNamespaceTracker(_codeContext.LanguageContext.DomainManager);

            AddAssembly(LoadAssemblyInfo(typeof(string).Assembly));
            AddAssembly(LoadAssemblyInfo(typeof(Debug).Assembly));

            string installDir = GetPythonInstallDir();

            if (installDir != null)
            {
                var dllDir = Path.Combine(installDir, "DLLs");
                if (Directory.Exists(dllDir))
                {
                    foreach (var assm in Directory.GetFiles(dllDir))
                    {
                        try {
                            var asm = Assembly.LoadFile(Path.Combine(dllDir, assm));
                            _engine.Runtime.LoadAssembly(asm);

                            AddAssembly(LoadAssemblyInfo(asm));
                        } catch {
                        }
                    }
                }
            }

            LoadAssemblies();

            LoadModules();
        }
示例#10
0
        public TestRuntime(Driver /*!*/ driver, TestCase /*!*/ testCase)
        {
            _driver   = driver;
            _testName = testCase.Name;

            if (testCase.Options.NoRuntime)
            {
                return;
            }

#if !WIN8
            if (_driver.SaveToAssemblies)
            {
                Environment.SetEnvironmentVariable("DLR_AssembliesFileName", _testName);
            }
#endif
            _engine  = _driver.CreateRubyEngine(testCase.Options.PrivateBinding, testCase.Options);
            _runtime = _engine.Runtime;
            _context = (RubyContext)HostingHelpers.GetLanguageContext(_engine);
        }
示例#11
0
        /// <summary>
        ///     This constructor creates an instance of the class named classname, and is called with pe.instance.Run().
        ///     It supports the old style of MorningBatch and RegisterEvent.
        /// </summary>
        public PythonModel(string dbname, string classname, string script)
            : this(dbname)
        {
            var engine = Python.CreateEngine();
            var pc     = HostingHelpers.GetLanguageContext(engine) as PythonContext;
            var hooks  = pc?.SystemState.Get__dict__()["path_hooks"] as List;
            hooks?.Clear();
            var searchPaths = engine.GetSearchPaths();
            searchPaths.Add(ConfigurationManager.AppSettings["PythonLibPath"]);
            engine.SetSearchPaths(searchPaths);
            var sc = engine.CreateScriptSourceFromString(script);

            var code  = sc.Compile();
            var scope = engine.CreateScope();
            scope.SetVariable("model", this);
            code.Execute(scope);

            dynamic Event = scope.GetVariable(classname);

            instance = Event();
        }
        private void ParsePythonCode(TextContentProvider content, out PythonAst ast, out CollectingErrorSink errorSink)
        {
            ast       = null;
            errorSink = new CollectingErrorSink();

            // parse the tree
            var source      = _engine.CreateScriptSource(content, "", SourceCodeKind.File);
            var compOptions = (PythonCompilerOptions)HostingHelpers.GetLanguageContext(_engine).GetCompilerOptions();
            var context     = new CompilerContext(HostingHelpers.GetSourceUnit(source), compOptions, errorSink);

            //compOptions.Verbatim = true;
            using (var parser = MakeParser(context)) {
                if (parser != null)
                {
                    try {
                        ast = parser.ParseFile(false);
                    } catch (Exception e) {
                        Debug.Assert(false, String.Format("Failure in IronPython parser: {0}", e.ToString()));
                    }
                }
            }
        }
示例#13
0
        private static void DoThePython()
        {
            var engine = Python.CreateEngine();

            PythonContext        context = HostingHelpers.GetLanguageContext(engine) as PythonContext;
            ICollection <string> paths   = context.GetSearchPaths();

            paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
            context.SetSearchPaths(paths);
            engine.ImportModule("xml");
            engine.Runtime.LoadAssembly(System.Reflection.Assembly.GetEntryAssembly());
            var scope = engine.CreateScope();

            engine.ExecuteFile(@"C:\Users\aheumann\Documents\vvd\CommonGraphDiffer.py", scope);
            var xmlToDS = scope.GetVariable <Func <string, dynamic> >("XMLToDS");
            var myDS    = xmlToDS(@"C:\Users\aheumann\Documents\vvd\foo.dsx");

            foreach (var change in myDS.Changes)
            {
                //Console.WriteLine(change.ToString());
            }
        }
示例#14
0
        //spawns the python compiler and analyzes a script
        // outputs: ParseInfo class containing:
        //          errors
        //          python ast
        public ParseInfo Parse(string source)
        {
            var parseErrorSink = new ScriptErrorSink();

            ScriptSource script_source = scriptEngine.CreateScriptSourceFromString(source, SourceCodeKind.File);
            var          source_unit   = HostingHelpers.GetSourceUnit(script_source);

            var    language_context = HostingHelpers.GetLanguageContext(scriptEngine);
            Parser parser           = Parser.CreateParser(
                new CompilerContext(source_unit, language_context.GetCompilerOptions(), parseErrorSink),
                (PythonOptions)language_context.Options);

            var python_ast = parser.ParseFile(false);

            var info = new ParseInfo(parseErrorSink.Errors, python_ast);

            //no need for that
            //var walker = new TurtleScriptAstWalker(info);
            //python_ast.Walk(walker);

            return(info);
        }
示例#15
0
文件: Program.cs 项目: wflk/canape
        protected override void ExecuteInternal()
        {
            PythonContext ctx = HostingHelpers.GetLanguageContext(Engine) as PythonContext;

            (HostingHelpers.GetLanguageContext(base.Engine) as PythonContext).SetModuleState(typeof(ScriptEngine), base.Engine);

            ctx.SetModuleState(typeof(ScriptEngine), Engine);
            Runtime.LoadAssembly(typeof(NetGraph).Assembly);
            Runtime.LoadAssembly(typeof(NetGraphDocument).Assembly);
            Runtime.LoadAssembly(typeof(ProxyNetworkService).Assembly);
            Runtime.LoadAssembly(typeof(ExpressionResolver).Assembly);
            Runtime.LoadAssembly(typeof(Program).Assembly);
            Runtime.LoadAssembly(typeof(BaseDataEndpoint).Assembly);
            Runtime.LoadAssembly(typeof(CertificateUtils).Assembly);
            Runtime.LoadAssembly(typeof(Org.BouncyCastle.Asn1.Asn1Encodable).Assembly);
            Runtime.LoadAssembly(typeof(NodeLibraryAttribute).Assembly);
            ICollection <string> searchPaths = Engine.GetSearchPaths();
            string item = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonLib");

            searchPaths.Add(item);
            Engine.SetSearchPaths(searchPaths);
            base.ExecuteInternal();
        }
示例#16
0
        public CodeFile Parse(string programText, string fileName)
        {
            ScriptEngine    py  = null;
            SourceUnit      src = null;
            LanguageContext pythonLanguageContext = null;
            CompilerContext cc = null;

            IronPython.PythonOptions   pyOptions;
            IronPython.Compiler.Parser pyParser = null;
            PythonAst ast = null;

            try
            {
                py  = IronPython.Hosting.Python.CreateEngine();
                src = HostingHelpers.GetSourceUnit(py.CreateScriptSourceFromString(programText));
                pythonLanguageContext = HostingHelpers.GetLanguageContext(py);
                cc        = new CompilerContext(src, pythonLanguageContext.GetCompilerOptions(), ErrorSink.Default);
                pyOptions = pythonLanguageContext.Options as IronPython.PythonOptions;
                pyParser  = Parser.CreateParser(cc, pyOptions);
                ast       = pyParser.ParseFile(true);
            }
            finally
            {
                pyParser?.Dispose();
            }

            PythonEntityCollector collector = new PythonEntityCollector();

            ast.Walk(collector);


            var cf = collector.getCodeFile();

            cf.Name = String.IsNullOrWhiteSpace(fileName) ? $"{rm.GetString("PythonString", CultureInfo.CurrentCulture)}" : fileName;

            return(cf);
        }
示例#17
0
        private static ScriptEngine CreateEngine(bool fromFile = false)
        {
            var engine = fromFile
                            ? Python.CreateEngine(new Dictionary <string, object> {
                ["Debug"] = true
            })
                            : Python.CreateEngine();
            var pc    = HostingHelpers.GetLanguageContext(engine) as PythonContext;
            var hooks = pc?.SystemState.Get__dict__()["path_hooks"] as List;

            hooks?.Clear();
            var searchPaths   = engine.GetSearchPaths();
            var pythonLibPath = ConfigurationManager.AppSettings["PythonLibPath"];

            if (pythonLibPath != null)
            {
                foreach (var path in pythonLibPath.Split(';'))
                {
                    searchPaths.Add(path);
                }
            }
            engine.SetSearchPaths(searchPaths);
            return(engine);
        }
示例#18
0
        public static void run(string path, Mml2vgmInfo info, int index)
        {
            ScriptEngine  engine  = null;
            ScriptRuntime runtime = null;

            try
            {
                engine = Python.CreateEngine();
                var pc    = HostingHelpers.GetLanguageContext(engine) as PythonContext;
                var hooks = pc.SystemState.Get__dict__()["path_hooks"] as List;
                hooks.Clear();
                ScriptSource source = engine.CreateScriptSourceFromFile(path);
                CompiledCode code   = source.Compile();
                ScriptScope  scope  = engine.CreateScope();
                runtime = engine.Runtime;
                Assembly assembly = typeof(Program).Assembly;
                runtime.LoadAssembly(Assembly.LoadFile(assembly.Location));
                source.Execute(scope);

                dynamic    pyClass       = scope.GetVariable("Mml2vgmScript");
                dynamic    mml2vgmScript = pyClass();
                ScriptInfo si            = mml2vgmScript.run(info, index);
                if (si != null && info.document != null)
                {
                    info.document.editor.azukiControl.Document.Replace(si.responseMessage);
                }
            }
            catch (Exception ex)
            {
                log.ForcedWrite(ex);
            }
            finally
            {
                runtime.Shutdown();
            }
        }
示例#19
0
        public void TestAnalyzeStdLib()
        {
            //string dir = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles"), "IronPython 2.6 for .NET 4.0 RC\\Lib");
            string        dir   = Path.Combine("C:\\Python27\\Lib");
            List <string> files = new List <string>();

            CollectFiles(dir, files);

            List <SourceUnit> sourceUnits = new List <SourceUnit>();

            foreach (string file in files)
            {
                sourceUnits.Add(
                    new SourceUnit(
                        HostingHelpers.GetLanguageContext(_engine),
                        new FileTextContentProvider(new FileStreamContentProvider(file)),
                        Path.GetFileNameWithoutExtension(file),
                        SourceCodeKind.File
                        )
                    );
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();
            long start0                      = sw.ElapsedMilliseconds;
            var  projectState                = new ProjectState(_engine);
            List <ProjectEntry> modules      = new List <ProjectEntry>();
            PythonOptions       EmptyOptions = new PythonOptions();

            foreach (var sourceUnit in sourceUnits)
            {
                modules.Add(projectState.AddModule(Path.GetFileNameWithoutExtension(sourceUnit.Path), sourceUnit.Path, null));
            }
            long start1 = sw.ElapsedMilliseconds;

            Console.WriteLine("AddSourceUnit: {0} ms", start1 - start0);

            List <PythonAst> nodes = new List <PythonAst>();

            for (int i = 0; i < modules.Count; i++)
            {
                PythonAst ast = null;
                try {
                    var sourceUnit = sourceUnits[i];

                    var context = new CompilerContext(sourceUnit, HostingHelpers.GetLanguageContext(_engine).GetCompilerOptions(), ErrorSink.Null);
                    ast = Parser.CreateParser(context, EmptyOptions).ParseFile(false);
                } catch (Exception) {
                }
                nodes.Add(ast);
            }
            long start2 = sw.ElapsedMilliseconds;

            Console.WriteLine("Parse: {0} ms", start2 - start1);

            for (int i = 0; i < modules.Count; i++)
            {
                var ast = nodes[i];

                if (ast != null)
                {
                    modules[i].UpdateTree(ast, null);
                }
            }

            long start3 = sw.ElapsedMilliseconds;

            for (int i = 0; i < modules.Count; i++)
            {
                Console.WriteLine("Analyzing {1}: {0} ms", sw.ElapsedMilliseconds - start3, sourceUnits[i].Path);
                var ast = nodes[i];
                if (ast != null)
                {
                    modules[i].Analyze();
                }
            }
            long start4 = sw.ElapsedMilliseconds;

            Console.WriteLine("Analyze: {0} ms", start4 - start3);
            Console.ReadLine();
        }
示例#20
0
        public ProjectState(ScriptEngine pythonEngine)
        {
            _pythonEngine      = pythonEngine;
            _projectEntries    = new List <ProjectEntry>();
            _modules           = new Dictionary <string, ModuleReference>();
            _modulesByFilename = new Dictionary <string, ModuleInfo>(StringComparer.OrdinalIgnoreCase);
            _itemCache         = new Dictionary <object, object>();

            var pythonContext = HostingHelpers.GetLanguageContext(_pythonEngine) as PythonContext;

            _codeContextCls = new ModuleContext(new PythonDictionary(), pythonContext).GlobalContext;
            _codeContextCls.ModuleContext.ShowCls = true;

            _codeContext = new ModuleContext(
                new PythonDictionary(),
                HostingHelpers.GetLanguageContext(_pythonEngine) as PythonContext
                ).GlobalContext;

            InitializeBuiltinModules();

            // TODO: Use reflection-only!
            _references = new List <KeyValuePair <Assembly, TopNamespaceTracker> >();
            AddAssembly(LoadAssemblyInfo(typeof(string).Assembly));
            AddAssembly(LoadAssemblyInfo(typeof(Debug).Assembly));


            // cached for quick checks to see if we're a call to clr.AddReference
            SpecializeFunction("clr", "AddReference", (n, unit, args) => AddReference(n, null));
            SpecializeFunction("clr", "AddReferenceByPartialName", (n, unit, args) => AddReference(n, ClrModule.LoadAssemblyByPartialName));
            SpecializeFunction("clr", "AddReferenceByName", (n, unit, args) => AddReference(n, null));
            SpecializeFunction("clr", "AddReferenceToFile", (n, unit, args) => AddReference(n, (s) => ClrModule.LoadAssemblyFromFile(_codeContext, s)));
            SpecializeFunction("clr", "AddReferenceToFileAndPath", (n, unit, args) => AddReference(n, (s) => ClrModule.LoadAssemblyFromFileWithPath(_codeContext, s)));

            try {
                SpecializeFunction("wpf", "LoadComponent", LoadComponent);
            } catch (KeyNotFoundException) {
                // IronPython.Wpf.dll isn't available...
            }

            SpecializeFunction("__builtin__", "range", (n, unit, args) => unit.DeclaringModule.GetOrMakeNodeVariable(n, (nn) => new RangeInfo(ClrModule.GetPythonType(typeof(List)), unit.ProjectState).SelfSet));
            SpecializeFunction("__builtin__", "min", ReturnUnionOfInputs);
            SpecializeFunction("__builtin__", "max", ReturnUnionOfInputs);

            _builtinModule   = (BuiltinModule)Modules["__builtin__"].Module;
            _propertyObj     = GetBuiltin("property");
            _classmethodObj  = GetBuiltin("classmethod");
            _staticmethodObj = GetBuiltin("staticmethod");
            _typeObj         = GetBuiltin("type");
            _intType         = GetBuiltin("int");
            _stringType      = (BuiltinClassInfo)GetBuiltin("str");

            _objectSet = new HashSet <Namespace>(new[] { GetBuiltin("object") });

            _setType       = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Set);
            _rangeFunc     = GetBuiltin("range");
            _frozensetType = GetBuiltin("frozenset");
            _functionType  = GetNamespaceFromObjects(TypeCache.Function);
            _generatorType = (BuiltinClassInfo)GetNamespaceFromObjects(DynamicHelpers.GetPythonTypeFromType(typeof(PythonGenerator)));
            _dictType      = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Dict);
            _boolType      = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Boolean);
            _noneInst      = (ConstantInfo)GetNamespaceFromObjects(new object[] { null });
            _listType      = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.List);
            _tupleType     = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.PythonTuple);

            _queue = new Queue <AnalysisUnit>();

            _docProvider = CodeContext.LanguageContext.GetService <DocumentationProvider>();
        }
示例#21
0
 private static PythonContext /*!*/ GetPythonContext(ScriptEngine /*!*/ engine)
 {
     return(HostingHelpers.GetLanguageContext(engine) as PythonContext);
 }
示例#22
0
        public static int Run(List <string> /*!*/ args, string baseDirectory)
        {
#if !WIN8
            if (Thread.CurrentThread.CurrentCulture.ToString() != "en-US")
            {
                WriteOutput("Current culture: {0}", Thread.CurrentThread.CurrentCulture);
            }
#endif
            if (!ParseArguments(args))
            {
                return(-3);
            }

#if !WIN8
            if (_runTokenizerDriver)
            {
                TokenizerTestDriver tokenizerDriver = new TokenizerTestDriver((RubyContext)HostingHelpers.GetLanguageContext(Ruby.CreateEngine()));
                if (!tokenizerDriver.ParseArgs(args))
                {
                    return(-3);
                }

                return(tokenizerDriver.RunTests());
            }
#endif
            InitializeDomain();
            Driver driver = new Driver(baseDirectory);

            if (Manual.TestCode.Trim().Length == 0)
            {
                return(driver.RunUnitTests(args));
            }

#if !WIN8
            driver.RunManualTest();
#endif
            // for case the test is forgotten, this would fail the test suite:
            return(-2);
        }
示例#23
0
 // TODO:
 public static RubyContext /*!*/ GetExecutionContext(ScriptEngine /*!*/ engine)
 {
     ContractUtils.RequiresNotNull(engine, "engine");
     return((RubyContext)HostingHelpers.GetLanguageContext(engine));
 }
        protected override bool ShouldEvaluateForCompletion(string source)
        {
            var scriptSrc = _localEngine.CreateScriptSource(new StringTextContentProvider(source), "", SourceCodeKind.Expression);
            var context   = new CompilerContext(HostingHelpers.GetSourceUnit(scriptSrc), HostingHelpers.GetLanguageContext(_localEngine).GetCompilerOptions(), ErrorSink.Null);
            var parser    = Parser.CreateParser(context, new PythonOptions());

            var stmt       = parser.ParseSingleStatement();
            var exprWalker = new ExprWalker();

            stmt.Walk(exprWalker);
            return(exprWalker.ShouldExecute);
        }
示例#25
0
 public static EssenceSharpContext essenceSharpContext(this ScriptEngine engine)
 {
     return((EssenceSharpContext)HostingHelpers.GetLanguageContext(engine));
 }
示例#26
0
        protected SourceUnit CreateSourceUnit(string code)
        {
            var context = HostingHelpers.GetLanguageContext(_engine);

            return(context.CreateSnippet(code, SourceCodeKind.InteractiveCode));
        }
示例#27
0
        public PythonEnvironmentModule(IEventAggregator aggregator, IEntityManagerViewModel entityManager,
                                       IThermodynamicSystemImporter importer,
                                       IChartViewModelFactory chartFactory,
                                       IFlowsheetEntityEditorFactory flowsheetFactory,
                                       IPureComponentPropertyDatabase pureDB,
                                       IThermodynamicSystemViewModelFactory thermoEditorFactory
                                       )
        {
            _aggregator          = aggregator;
            _entityManager       = entityManager;
            _importer            = importer;
            _chartFactory        = chartFactory;
            _flowsheetFactory    = flowsheetFactory;
            _pyEngine            = Python.CreateEngine();
            _pyScope             = _pyEngine.CreateScope();
            _pureComponentDB     = pureDB;
            _thermoEditorFactory = thermoEditorFactory;

            _pyScope.SetVariable("_host", this);
            _pyScope.SetVariable("Items", _entityManager);
            _pyEngine.SetSearchPaths(new List <string> {
                Environment.CurrentDirectory
            });
            var pc    = HostingHelpers.GetLanguageContext(_pyEngine) as PythonContext;
            var hooks = pc.SystemState.Get__dict__()["path_hooks"] as List;

            hooks.Clear();
            Run("import sys");
            Run("import clr");
            Run("clr.AddReferenceToFile(\"OpenFMSL.Core.dll\")");
            Run("clr.AddReferenceToFile(\"OpenFMSL.Contracts.dll\")");

            Run("from OpenFMSL.Core.Expressions import *");
            Run("from OpenFMSL.Core.Flowsheeting import *");
            Run("from OpenFMSL.Core.Flowsheeting.Documentation import *");
            Run("from OpenFMSL.Core.Numerics import *");
            Run("from OpenFMSL.Core.Numerics.Solvers import *");
            Run("from OpenFMSL.Core.UnitsOfMeasure import *");
            Run("from OpenFMSL.Core.ModelLibrary import *");
            Run("from OpenFMSL.Core.Thermodynamics import *");

            Run("from OpenFMSL.Contracts.Entities import *");
            Run("from OpenFMSL.Contracts.Infrastructure.Reporting import *");

            Run("from System import Math");
            Run("sys.stdout=_host");
            Run("runFile= _host.RunFile");
            Run("run= _host.RunEntity");
            Run("pause= _host.WaitThread");
            Run("CreateThermo= _host.LoadThermodynamicSystem");

            _pureComponentDB.SetLogCallback(Write);

            ipopt       = new IpoptSolver();
            ipopt.OnLog = (x) => Write("    " + x + Environment.NewLine);
            _pyScope.SetVariable("_ipopt", ipopt);
            _pyScope.SetVariable("Database", _pureComponentDB);

            newton              = new Newton();
            newton.OnLog        = (x) => Write("    " + x + Environment.NewLine);
            newton.OnLogDebug   = (x) => Write(x + Environment.NewLine);
            newton.OnLogError   = (x) => Write("!!! " + x + Environment.NewLine);
            newton.OnLogSuccess = (x) => Write("+++ " + x + Environment.NewLine);
            newton.OnLogWarning = (x) => Write("*** " + x + Environment.NewLine);
            newton.OnLogInfo    = (x) => Write("--- " + x + Environment.NewLine);
            _pyScope.SetVariable("_newton", newton);

            var flash = new FlashRoutines(newton);

            _pyScope.SetVariable("_flash", flash);

            decomp              = new Decomposer();
            decomp.OnLog        = (x) => Write("    " + x + Environment.NewLine);
            decomp.OnLogDebug   = (x) => Write(x + Environment.NewLine);
            decomp.OnLogError   = (x) => Write("!!! " + x + Environment.NewLine);
            decomp.OnLogSuccess = (x) => Write("+++ " + x + Environment.NewLine);
            decomp.OnLogWarning = (x) => Write("*** " + x + Environment.NewLine);
            decomp.OnLogInfo    = (x) => Write("--- " + x + Environment.NewLine);

            _pyScope.SetVariable("_decomp", decomp);

            Run("solve= _host.Solve");
            Run("decomp= _host.Decompose");
            Run("report= _host.Report");

            Run("show= _host.Show");
            Run("check= _host.Check");

            Run("info= _host.SendLogMessage");
            Run("warn= _host.SendWarningMessage");
            Run("error= _host.SendErrorMessage");

            Run("FlashPT= _flash.CalculateTP");
            Run("FlashPZ= _flash.CalculateZP");



            Run("status= _host.SendStatusTextChangeMessage");

            Run("print 'Python console running...");
        }