Evaluator: provides an API to evaluate C# statements and expressions dynamically.
This class exposes static methods to evaluate expressions in the current program. To initialize the evaluator with a number of compiler options call the Init(string[]args) method with a set of command line options that the compiler recognizes. To interrupt execution of a statement, you can invoke the Evaluator.Interrupt method.
Пример #1
0
		static int Main (string [] args)
		{
			var cmd = new CommandLineParser (Console.Out);
			cmd.UnknownOptionHandler += HandleExtraArguments;

			var settings = cmd.ParseArguments (args);
			if (settings == null)
				return 1;
			var startup_files = new string [settings.SourceFiles.Count];
			int i = 0;
			foreach (var source in settings.SourceFiles)
				startup_files [i++] = source.FullPathName;
			settings.SourceFiles.Clear ();

			var eval = new Evaluator (new CompilerContext (settings, new ConsoleReportPrinter ()));

			eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
			eval.DescribeTypeExpressions = true;

			CSharpShell shell;
#if !ON_DOTNET
			if (attach.HasValue) {
				shell = new ClientCSharpShell (eval, attach.Value);
			} else if (agent != null) {
				new CSharpAgent (eval, agent).Run (startup_files);
				return 0;
			} else
#endif
			{
				shell = new CSharpShell (eval);
			}
			return shell.Run (startup_files);
		}
Пример #2
0
        private static void InitializeEvaluator()
        {
            _Interop.VarStorage["ReplVersion"] = typeof(Program).Assembly.GetName().Version;

            var settings = new CompilerSettings() {
                StdLib = true
            };

            var reportPrinter = new ConsoleReportPrinter();

            var ctx = new CompilerContext(settings, reportPrinter);

            evaluator = new Evaluator(ctx);

            evaluator.ReferenceAssembly(typeof(_Interop).Assembly);

            evaluator.Run(
            @"
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            ");

            evaluator.Run("var _v = _Interop.VarStorage;");
            evaluator.Run("var _h = _Interop.History;");
            evaluator.Run("_Interop.VoidMethod exit = _Interop.Exit;");
            evaluator.Run("_Interop.ReturnStringListMethod globals = _Interop.GetGlobals");
        }
Пример #3
0
        async Task <bool> Evaluate(string code, EvalResult result, string initCode, bool retryOnError)
        {
            try
            {
                printer.Reset();
                if (initCode != null)
                {
                    eval.Evaluate(initCode, out object retResult, out bool result_set);
                }
                result.Result = eval.Evaluate(code);
                return(true);
            }
            catch (Exception ex)
            {
                if (retryOnError)
                {
                    eval = null;
                    EnsureConfigured();
                    return(await Evaluate(code, result, initCode, false));
                }

                Log.Error($"Error evalutaing code");
                eval = null;
                if (printer.Messages.Count != 0)
                {
                    result.Messages = printer.Messages.ToArray();
                }
                else
                {
                    result.Messages = new[] { new EvalMessage("error", ex.ToString()) };
                }
                return(false);
            }
        }
Пример #4
0
        public ScriptingEngine()
        {
            tokenSource = new CancellationTokenSource();
            taskFactory = new TaskFactory(tokenSource.Token);

            context = new CompilerContext(new Mono.CSharp.CompilerSettings(), new ConsoleReportPrinter());
            evaluator = new Evaluator(context);
            evaluator.InteractiveBaseClass = typeof(ScriptingInteractiveBase);
            evaluator.DescribeTypeExpressions = true;

            ScriptingInteractiveBase.Evaluator = evaluator;
            var errorStream = new GuiStream(TextType.Error, OnConsoleOutput);
            var guiOutput = new StreamWriter(errorStream);
            guiOutput.AutoFlush = true;
            Console.SetError(guiOutput);
            ScriptingInteractiveBase.Output = guiOutput;

            var stdoutStream = new GuiStream(TextType.Output, OnConsoleOutput);
            guiOutput = new StreamWriter(stdoutStream);
            guiOutput.AutoFlush = true;
            Console.SetOut(guiOutput);
            ScriptingInteractiveBase.Error = guiOutput;

            codeCompletion = new CSharpCompletion(this);

            Evaluate("using System; using System.Linq; using System.Collections; using System.Collections.Generic;");

            //init the code completion so that the first character typed is not delayed
            //var readOnlyDocument = new ReadOnlyDocument(new StringTextSource(""), "init.csx");
            //codeCompletion.GetCompletions(readOnlyDocument, 0);
        }
Пример #5
0
        public CSharpCompiler()
        {
            CompilerSettings settings = new CompilerSettings ();
            Report report = new Report (new NullReportPrinter ());

            evaluator = new Evaluator (settings, report);
        }
Пример #6
0
		public Shell(MainWindow container) : base()
		{
			this.container = container;
			WrapMode = WrapMode.Word;
			CreateTags ();

			Pango.FontDescription font_description = new Pango.FontDescription();
			font_description.Family = "Monospace";
			ModifyFont(font_description);
			
			TextIter end = Buffer.EndIter;
			Buffer.InsertWithTagsByName (ref end, "Mono C# Shell, type 'help;' for help\n\nEnter statements or expressions below.\n", "Comment");
			ShowPrompt (false);
			
			report = new Report (new ConsoleReportPrinter ());
			evaluator = new Evaluator (new CompilerSettings (), report);
			evaluator.DescribeTypeExpressions = true;
			
			evaluator.InteractiveBaseClass = typeof (InteractiveGraphicsBase);
			evaluator.Run ("LoadAssembly (\"System.Drawing\");");
			evaluator.Run ("using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Drawing;");

			if (!MainClass.Debug){
				GuiStream error_stream = new GuiStream ("Error", (x, y) => Output (x, y));
				StreamWriter gui_output = new StreamWriter (error_stream);
				gui_output.AutoFlush = true;
				Console.SetError (gui_output);

				GuiStream stdout_stream = new GuiStream ("Stdout", (x, y) => Output (x, y));
				gui_output = new StreamWriter (stdout_stream);
				gui_output.AutoFlush = true;
				Console.SetOut (gui_output);
			}
		}
Пример #7
0
        public Task <bool> EvaluateCode(string code, EvalResult result)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Task.FromResult(false));
            }

            EnsureConfigured();

            try
            {
                printer.Reset();
                eval.Evaluate(code, out object retResult, out bool result_set);
                result.Result = retResult;
                return(Task.FromResult(true));
            }
            catch (Exception ex)
            {
                Log.Error($"Error evalutaing code");
                eval = null;
                if (printer.Messages.Count != 0)
                {
                    result.Messages = printer.Messages.ToArray();
                }
                else
                {
                    result.Messages = new[] { new EvalMessage("error", ex.ToString()) };
                }
                return(Task.FromResult(false));
            }
        }
Пример #8
0
        private void resetEvaluator()
        {
            m_errorStream = new StringBuilder();
            //StreamReader sr =
            TextWriter tw  = new StringWriter(m_errorStream);
            var        ctx = new Mono.CSharp.CompilerContext(
                new Mono.CSharp.CompilerSettings()
            {
                AssemblyReferences = new List <string>()
                {
                    typeof(ILMath).Assembly.FullName,
                    typeof(System.Drawing.PointF).Assembly.FullName,
                    typeof(System.Linq.Queryable).Assembly.FullName
                },
                //Unsafe = true
            }, new StreamReportPrinter(tw));

            var eval = new Mono.CSharp.Evaluator(ctx);

            // reset line colors (thread safe)
            ILNumerics.Drawing.Plotting.ILLinePlot.NextColors = new ILColorEnumerator();

            string m_head = @"
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq; 
using ILNumerics;
using ILNumerics.Drawing;
using ILNumerics.Drawing.Plotting;";

            eval.Run(m_head);
            m_evaluator = eval;
        }
Пример #9
0
        public int Run()
        {
            // Enable unsafe code by default
            var settings = new CompilerSettings () {
                Unsafe = true
            };

            var startup_files = new string [0];
            settings.SourceFiles.Clear ();
            ReportPrinter printer= new ConsoleReportPrinter ();
            var eval = new Evaluator (new CompilerContext (settings, printer));
            eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
            eval.DescribeTypeExpressions = true;
            eval.WaitOnTask = true;

            CSharpShell shell;
            #if !ON_DOTNET
            if (attach.HasValue) {
                shell = new ClientCSharpShell (eval, attach.Value);
            } else if (agent != null) {
                new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
                return 0;
            } else
                #endif
            {
                shell = new CSharpShell (eval, console);
            }
            return shell.Run (startup_files);
        }
Пример #10
0
        static void Main(string[] args)
        {
            var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());
            var evaluator = new Evaluator(compilerContext);

            // Make it reference our own assembly so it can use IFoo
            evaluator.ReferenceAssembly(typeof(IFoo).Assembly);

            // Feed it some code
            evaluator.Compile(
                @"
            public class Foo : MonoCompilerDemo.IFoo
            {
            public string Bar(string s) { return s.ToUpper(); }
            }");

            for (; ; )
            {
                string line = Console.ReadLine();
                if (line == null) break;

                object result;
                bool result_set;
                evaluator.Evaluate(line, out result, out result_set);
                if (result_set) Console.WriteLine(result);
            }
        }
Пример #11
0
        public Task <bool> EvaluateExpression(string expression, string code, EvalResult result)
        {
            EnsureConfigured();
            try
            {
                object retResult;
                bool   hasResult;

                printer.Reset();
                if (!String.IsNullOrEmpty(code))
                {
                    var ret = eval.Evaluate(code, out retResult, out hasResult);
                }
                result.Result = eval.Evaluate(expression);
                return(Task.FromResult(true));
            }
            catch (Exception ex)
            {
                Log.Error($"Error creating a new instance of {expression}");
                if (printer.Messages.Count != 0)
                {
                    result.Messages = printer.Messages.ToArray();
                }
                else
                {
                    result.Messages = new EvalMessage[] { new EvalMessage("error", ex.ToString()) };
                }
                if (!result.HasResult && result.Messages.Length == 0)
                {
                    result.Messages = new EvalMessage[] { new EvalMessage("error", "Internal Error") };
                }
                eval = null;
            }
            return(Task.FromResult(false));
        }
Пример #12
0
        /// <summary>
        /// Discards current instance of Evaluator, and CompilingResult, and replaces
        /// them with new ones. Also nullifies the AllREferencedAssemblies array
        /// </summary>
        public void Reset()
        {
            CompilationResult = new CompilingResult();

            CompilationOutput = new CompilerOutput();

            service = new MCS.Evaluator(new CompilerContext(new CompilerSettings(), CompilationResult));

            AllReferencedAssemblies = new List <Assembly>();
        }
Пример #13
0
 private void AddDefaultNamespaces(Evaluator eval)
 {
     eval.Run("using System;");
     eval.Run("using System.Collections.Generic;");
     eval.Run("using System.Linq;");
     eval.Run("using Db4objects.Db4o;");
     eval.Run("using Db4objects.Db4o.Linq;");
     eval.Run("using Db4oTutorial.ExampleRunner.Demos;");
     eval.Run("using Console = Db4oTutorial.ExampleRunner.ConsoleOutReplacement;");
 }
Пример #14
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            EvaluatorSession = this.ControllerContext.HttpContext.Session[EVALUATOR_KEY] as Evaluator;

            if (EvaluatorSession == null)
            {
                this.ControllerContext.HttpContext.Session[EVALUATOR_KEY] = new Evaluator(context);
                EvaluatorSession = this.ControllerContext.HttpContext.Session[EVALUATOR_KEY] as Evaluator;
            }
        }
Пример #15
0
        /// <summary>
        /// Initializes the evaluator and includes a few basic System libraries
        /// </summary>
        public Runner()
        {
            _report   = new Report(new Printer(this));
            _settings = new CommandLineParser(_report).ParseArguments(new string[] {});
            _eval     = new Evaluator(_settings, _report);

            _eval.Run("using System;");
            _eval.Run("using System.Linq;");
            _eval.Run("using System.Collections.Generic;");
        }
Пример #16
0
        public static void Main(String[] myArgs)
        {
            _Compiler = new Runner();

            //var a = _Compiler.Execute("Math.Abs(-42);");
            //Assert.AreEqual(42, a);

            //var b = _Compiler.Execute("class Fact { public int Run(int n) { return n <= 0 ? 1 : n*Run(n-1); } }");
            //var c = _Compiler.Execute("new Fact().Run(5);");
            //Assert.AreEqual(120, c);

            //var d = _Compiler.Execute("\"abcdefgh\".Substring(1, 2);");
            //Assert.AreEqual("bc", d);

            //var e = _Compiler.Execute("var test = 123;");
            //Assert.AreEqual("bc", e);

            #region Feel free to step through...

            _Compiler = new Runner();
            var a = _Compiler.Execute("Math.Abs(-42);");
            var b = _Compiler.Execute("Math.Sin(Math.PI / 6);");
            var c = _Compiler.Execute("class Fact { public int Run(int n) { return n <= 0 ? 1 : n*Run(n-1); } }");
            var d = _Compiler.Execute("new Fact().Run(5);");
            var e = _Compiler.Execute("\"abcdefgh\".Substring(1, 2);");
            var f = _Compiler.Execute("class Echo { public Object Print(Object o) { return o; } }");
            var g = _Compiler.Execute("var test = 123;");
            var h = _Compiler.Execute("new Echo().Print(test);");

            #endregion

            #region Start the interactive (read-eval-print loop) shell...

            var _Report = new Report(new ConsoleReportPrinter());
            var _CLP    = new CommandLineParser(_Report);
                _CLP.UnknownOptionHandler += Mono.Driver.HandleExtraArguments;

            var _Settings = _CLP.ParseArguments(myArgs);
            if (_Settings == null || _Report.Errors > 0)
                Environment.Exit(1);

            var _Evaluator = new Evaluator(_Settings, _Report)
            {
                InteractiveBaseClass    = typeof(InteractiveBaseShell),
                DescribeTypeExpressions = true
            };

            //// Adding a assembly twice will lead to delayed errors...
            //_Evaluator.ReferenceAssembly(typeof(YourAssembly).Assembly);

            var _CSharpShell = new CSharpShell(_Evaluator).Run();

            #endregion
        }
Пример #17
0
        public void Setup()
        {
            var builder = new StringBuilder();
            var writer = new StringWriter(builder);
            var printer = new StreamReportPrinter(writer);
            var settings = new CompilerSettings();
            settings.AssemblyReferences.Add("DbTool.Testing");

            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context);
        }
Пример #18
0
		public CompileRequest (string code, Action<CompileResult> continuation)
		{
			Code = code;
			eval = new Evaluator (new CompilerContext (new CompilerSettings (), new ConsoleReportPrinter (errors)));
			this.continuation = continuation;
			Compile ().ContinueWith (t => {
				if (t.IsFaulted) {
					Console.WriteLine (t.Exception);
				}
			});
		}
Пример #19
0
        /// <summary>
        /// Initializes the evaluator and includes a few basic System libraries
        /// </summary>
        public Runner()
        {
            _report = new Report(new Printer(this));
            _settings = new CommandLineParser(_report).ParseArguments (new string[] {});
            _eval = new Evaluator(_settings, _report);

            _eval.ReferenceAssembly(typeof(System.Linq.Enumerable).Assembly);

            _eval.Run("using System;");
            _eval.Run("using System.Collections.Generic;");
            _eval.Run("using System.Linq;");
        }
Пример #20
0
 public Cs(Bot bot)
 {
     this.bot = bot;
     evaluator = new Evaluator(new CompilerContext(new CompilerSettings { Unsafe = true }, reportPrinter))
     {
         DescribeTypeExpressions = true,
         WaitOnTask = true
     };
     bool resultSet;
     object result;
     evaluator.Evaluate("using System; using System.Linq; using System.Collections.Generic; using System.Text;", out result, out resultSet);
 }
        public static void Start()
        {
            MainEvaluator = new Evaluator(CompilerContext.Create());
            MainThreadCancellationToken = new CancellationTokenSource();

            Task.Factory.StartNew(MainThread);

            while (!MainThreadCancellationToken.Token.IsCancellationRequested)
                Thread.Sleep(250);

            OnMainThreadFinished();
        }
Пример #22
0
        private void DemandCompiler() {
            if (Engine != null) {
                return;
            }

            Engine = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter()));

            Engine.Run("using System;");
            Engine.Run("using System.Collections.Generic;");
            Engine.Run("var dictionary = new Dictionary<string, dynamic>();");
            Dictionary = Engine.Evaluate("dictionary") as IDictionary<string, dynamic>;
        }
Пример #23
0
    void Eval_Void_With_Pure_Mono()
    {
        Mono.CSharp.Evaluator evaluator = CSScript.MonoEvaluator.GetService();
        //Note: Calling evaluator.ReferenceAssembly will trigger the error as the ExecutingAssembly
        //(as one of all AddDomain static assemblies) is already referenced during
        //CSScript.Evaluator initialization.
        //However the call CSScript.Evaluator.ReferenceAssembly is safe as CSScript.Evaluator
        //keeps track of the assemblies and does not reference one again if it is already there.
        //evaluator.ReferenceAssembly (Assembly.GetExecutingAssembly());

        this.Name = "ScriptTester";
        evaluator.Run("System.Console.WriteLine(\"Host Name = \" + HostApp.Instance.Name);");
    }
Пример #24
0
        static Evaluator()
        {
            var eval = new Mono.CSharp.Evaluator(new CompilerContext(new CompilerSettings(), new Printer()));

            try
            {
                eval.Evaluate("2+2");
                isEvaluationSupported = true;
            }
            catch (Exception ex)
            {
                isEvaluationSupported = false;
            }
        }
Пример #25
0
        static Evaluator()
        {
            var eval = new Mono.CSharp.Evaluator(new CompilerContext(new CompilerSettings(), new Printer()));

            try
            {
                eval.Evaluate("2+2");
                isEvaluationSupported = true;
            }
            catch (Exception ex)
            {
                Log.Error("Runtime evaluation not supported, did you set the mtouch option --enable-repl?");
                isEvaluationSupported = false;
            }
        }
Пример #26
0
Файл: repl.cs Проект: GirlD/mono
		static int Main (string [] args)
		{
			var cmd = new CommandLineParser (Console.Out);
			cmd.UnknownOptionHandler += HandleExtraArguments;

			// Enable unsafe code by default
			var settings = new CompilerSettings () {
				Unsafe = true
			};

			if (!cmd.ParseArguments (settings, args))
				return 1;

			var startup_files = new string [settings.SourceFiles.Count];
			int i = 0;
			foreach (var source in settings.SourceFiles)
				startup_files [i++] = source.FullPathName;
			settings.SourceFiles.Clear ();

			TextWriter agent_stderr = null;
			ReportPrinter printer;
			if (agent != null) {
				agent_stderr = new StringWriter ();
				printer = new StreamReportPrinter (agent_stderr);
			} else {
				printer = new ConsoleReportPrinter ();
			}

			var eval = new Evaluator (new CompilerContext (settings, printer));

			eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
			eval.DescribeTypeExpressions = true;
			eval.WaitOnTask = true;

			CSharpShell shell;
#if !ON_DOTNET
			if (attach.HasValue) {
				shell = new ClientCSharpShell (eval, attach.Value);
			} else if (agent != null) {
				new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
				return 0;
			} else
#endif
			{
				shell = new CSharpShell (eval);
			}
			return shell.Run (startup_files);
		}
Пример #27
0
        EvalResult EvalOnMainThread(EvalRequest code, CancellationToken token)
        {
            var sw = new System.Diagnostics.Stopwatch ();

            object result = null;
            bool hasResult = false;

            lock (mutex) {
                InitIfNeeded ();

                Log ("EVAL ON THREAD {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);

                printer.Messages.Clear ();

                sw.Start ();

                try {
                    if (!string.IsNullOrEmpty (code.Declarations))
                    {
                        eval.Evaluate (code.Declarations, out result, out hasResult);
                    }
                    if (!string.IsNullOrEmpty (code.ValueExpression))
                    {
                        eval.Evaluate (code.ValueExpression, out result, out hasResult);
                    }
                } catch (InternalErrorException) {
                    eval = null; // Force re-init
                } catch (Exception ex) {
                    // Sometimes Mono.CSharp fails when constructing failure messages
                    if (ex.StackTrace.Contains ("Mono.CSharp.InternalErrorException")) {
                        eval = null; // Force re-init
                    }
                    printer.AddError (ex);
                }

                sw.Stop ();

                Log ("END EVAL ON THREAD {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            }

            return new EvalResult {
                Messages = printer.Messages.ToArray (),
                Duration = sw.Elapsed,
                Result = result,
                HasResult = hasResult,
            };
        }
Пример #28
0
        public void Init()
        {
            var printer = new StreamReportPrinter(_stringWriter);
            var settings = new CompilerSettings();
            settings.AssemblyReferences.AddRange(InitialAssemblies);
            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context)
                {
                    InteractiveBaseClass = typeof (DbToolInteractive),
                    DescribeTypeExpressions = true,
                };
            ReferenceAssemblies(typeof(Database).Assembly, typeof(DynamicSqlQuery).Assembly);

            Using(InitialUsings);
            DbToolInteractive.Evaluator = _evaluator;
            DbToolInteractive.Output = _stringWriter;
        }
Пример #29
0
        // This method evaluates the given code and returns a CompilerOutput object
        public static CompilerOutput evaluateCode(string code)
        {
            CompilerOutput compilerOutput = new CompilerOutput ();
            /*
            var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());

            var evaluator = new Evaluator(compilerContext);
            */
            var reportWriter = new StringWriter();
            var settings = new CompilerSettings();
            var printer = new ConsoleReportPrinter(reportWriter);

            var compilerContext = new CompilerContext (settings, printer);
            var reports = new Report(compilerContext, printer);
            var evaluator = new Evaluator(compilerContext);

            var myString = "";
            originalConsoleOut_global = Console.Out; // preserve the original stream
            using(var writer = new StringWriter())
            {
                Console.SetOut(writer);

                evaluator.Run (code);
                evaluator.Run ("MainClass m1 = new MainClass(); m1.Main();");

                //bConsole.WriteLine ("after executing code");

                if (reports.Errors > 0) {
                    Console.WriteLine ("reportWriter.ToString: \n" + reportWriter.ToString ());
                    compilerOutput.errors = reportWriter.ToString ();
                }

                writer.Flush(); // make sure everything is written out of consule

                myString = writer.GetStringBuilder().ToString();

                compilerOutput.consoleOut = myString;

            }

            Console.SetOut(originalConsoleOut_global); // restore Console.Out

            return compilerOutput;
        }
Пример #30
0
        ///////////////////////////////////////////////////////////////////////
        private void Initialize()
        {
            CompilerSettings sett = new CompilerSettings();
            ReportPrinter prnt = new ConsoleReportPrinter();

            // TODO programatically add references for all flynn assemblies

            sett.AssemblyReferences.Add("Flynn.Core.dll");
            sett.AssemblyReferences.Add("Flynn.X10.dll");
            sett.AssemblyReferences.Add("Flynn.Cron.dll");
            sett.AssemblyReferences.Add("Flynn.Utilities.dll");

            CompilerContext ctx = new CompilerContext(sett, prnt);

            _eval = new Evaluator(ctx);

            _eval.Run(Resources.CSharpEngine_InitUsings);
            _eval.Run(Resources.CSharpEngine_InitScript);
        }
Пример #31
0
		public EvalResult Eval (string code)
		{
			var sw = new System.Diagnostics.Stopwatch ();

			object result = null;
			bool hasResult = false;

			lock (mutex) {
				InitIfNeeded ();

				Log ("EVAL ON THREAD {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);

				printer.Messages.Clear ();

				sw.Start ();

				try {
//					Log (code);
					eval.Evaluate (code, out result, out hasResult);					
				} catch (InternalErrorException ex) {
					eval = null; // Force re-init
				} catch (Exception ex) {
					// Sometimes Mono.CSharp fails when constructing failure messages
					if (ex.StackTrace.Contains ("Mono.CSharp.InternalErrorException")) {
						eval = null; // Force re-init
					}
					printer.AddError (ex);
				}

				sw.Stop ();

				Log ("END EVAL ON THREAD {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
			}

			return new EvalResult {
				Code = code,
				Messages = printer.Messages.ToArray (),
				Duration = sw.Elapsed,
				Result = result,
				HasResult = hasResult,
			};
		}
Пример #32
0
        void EnsureConfigured()
        {
            if (eval != null)
            {
                return;
            }

            var settings = new CompilerSettings();
            var context  = new CompilerContext(settings, new ConsoleReportPrinter());

            eval = new Mono.CSharp.Evaluator(context);
            AppDomain.CurrentDomain.AssemblyLoad += (_, e) =>
            {
                LoadAssembly(e.LoadedAssembly);
            };
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                LoadAssembly(a);
            }
        }
Пример #33
0
        public void ClearSession(Action callback = null)
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                _errors = new List<string>();
                _warnings = new List<string>();

                var report = new Report(new Printer(msg => _errors.Add(msg.Text), msg => _warnings.Add(msg.Text)));
                var settings = new CommandLineParser(report).ParseArguments(new string[] { });
                _eval = new Evaluator(settings, report);

                foreach (string @namespace in Options.DefaultNamespaces)
                {
                    addUsing(@namespace);
                }

                if (callback != null)
                    callback();
            });
        }
Пример #34
0
Файл: repl.cs Проект: saga/mono
		static int Main (string [] args)
		{
			var r = new Report (new ConsoleReportPrinter ());
			var cmd = new CommandLineParser (r);
			cmd.UnknownOptionHandler += HandleExtraArguments;

			var settings = cmd.ParseArguments (args);
			if (settings == null || r.Errors > 0)
				return 1;

			var eval = new Evaluator (settings, r);

			eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
			eval.DescribeTypeExpressions = true;

			string[] startup_files = { };
			/*
			try {
				startup_files = Evaluator.InitAndGetStartupFiles (args, HandleExtraArguments);
				Evaluator.DescribeTypeExpressions = true;
				Evaluator.SetInteractiveBaseClass (typeof (InteractiveBaseShell));
			} catch {
				return 1;
			}
			*/

			CSharpShell shell;
#if !ON_DOTNET
			if (attach.HasValue) {
				shell = new ClientCSharpShell (eval, attach.Value);
			} else if (agent != null) {
				new CSharpAgent (eval, agent).Run (startup_files);
				return 0;
			} else
#endif
			{
				shell = new CSharpShell (eval);
			}

			return shell.Run (startup_files);
		}
Пример #35
0
        public MonoCSharpExecutor()
        {
            _reportBuilder = new StringBuilder();
            var writer = new StringWriter(_reportBuilder);
            var printer = new StreamReportPrinter(writer);
            var settings = new CompilerSettings();

            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context);
            _evaluator.InteractiveBaseClass = typeof (InteractiveStuff);
            _evaluator.ReferenceAssembly(typeof(HttpContext).Assembly);
            _evaluator.ReferenceAssembly(typeof(VisualFarmRepo).Assembly);
            _evaluator.ReferenceAssembly(typeof(BondegardFacade).Assembly);
            _evaluator.ReferenceAssembly(typeof(IVFSConfig).Assembly);
            Execute("using System;");
            Execute("using System.Linq;");
            Execute("using System.Web;");
            Execute("using VisualFarmStudio.Core.Domain;");
            Execute("using VisualFarmStudio.Core.Repository;");
            Execute("using VisualFarmStudio.Lib.Model;");
            Execute("using VisualFarmStudio.Lib.Containers;");
        }
Пример #36
0
        public DebuggerWindow(PluginContext context, String hackPath)
        {
            this.InitializeComponent();

            Trace.Listeners.Add(this.listener);

            var compilerSettings = new CompilerSettings
            {
                Unsafe = true,
            };
            compilerSettings.AssemblyReferences.Add("System.dll");
            compilerSettings.AssemblyReferences.Add("System.Core.dll");
            compilerSettings.AssemblyReferences.Add(typeof(MessageBox).Assembly.CodeBase); // PresentationFramework.dll
            compilerSettings.AssemblyReferences.Add(Path.Combine(hackPath, "SharpCraft.dll"));

            var compilerContext = new CompilerContext(compilerSettings, new DebuggerReportPrinter());

            evaluator = new Evaluator(compilerContext);
            evaluator.Compile("using System;");
            evaluator.Compile("using TinkerWorX.SharpCraft;");
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
Пример #37
0
        public static Evaluator Create()
        {
            var evaluator = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter()));

            evaluator.ReferenceAssembly(typeof(CodeEvaluator).Assembly);
            // Rx Core
            evaluator.ReferenceAssembly(typeof(ObservableExtensions).Assembly);
            // Rx Interfaces
            evaluator.ReferenceAssembly(typeof(IEventSource<>).Assembly);
            // Rx Linq
            evaluator.ReferenceAssembly(typeof(Observable).Assembly);

            evaluator.Run(@"
                using System;
                using System.Linq;
                using System.Linq.Expressions;
                using System.Reactive;
                using System.Reactive.Linq;
                using Sensorium;
            ");

            return evaluator;
        }
Пример #38
0
		void InitIfNeeded()
		{
			if (eval == null) {

				Log ("INIT EVAL");

				var settings = new CompilerSettings ();
				settings.AddConditionalSymbol ("__Continuous__");
				settings.AddConditionalSymbol ("DEBUG");
				PlatformSettings (settings);
				var context = new CompilerContext (settings, printer);
				eval = new Evaluator (context);

				//
				// Add References to get UIKit, etc. Also add a hook to catch dynamically loaded assemblies.
				//
				AppDomain.CurrentDomain.AssemblyLoad += (_, e) => {
					Log ("DYNAMIC REF {0}", e.LoadedAssembly);
					AddReference (e.LoadedAssembly);
				};
				foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
					Log ("STATIC REF {0}", a);
					AddReference (a);
				}

				//
				// Add default namespaces
				//
				object res;
				bool hasRes;
				eval.Evaluate ("using System;", out res, out hasRes);
				eval.Evaluate ("using System.Collections.Generic;", out res, out hasRes);
				eval.Evaluate ("using System.Linq;", out res, out hasRes);
				PlatformInit ();
			}
		}
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            CompilerSettings settings = new CompilerSettings();
            Report report = new Report(new ConsoleReportPrinter());
            Evaluator eval = new Evaluator(settings, report);

            object instance = null;
            bool instanceCreated = false;
            eval.ReferenceAssembly(typeof(Controller).Assembly);

            foreach (Assembly assembly in assemblies)
            {
                eval.ReferenceAssembly(assembly);
            }

            string controllerName = GetControllerName(requestContext, controllerType);
            string path = pathProvider.GetPath(requestContext, controllerName);
            CSharpControllerFile controllerFile = CSharpControllerFile.Parse(File.ReadAllText(path));

            eval.Run(controllerFile.ClassSource);
            eval.Evaluate("new " + controllerName + "();", out instance, out instanceCreated);

            return (IController)instance;
        }
Пример #40
0
        /// <summary>
        /// Discards current instance of Evaluator, and CompilingResult, and replaces
        /// them with new ones. Previously referenced assemblies get referenced again.
        /// </summary>
        public void SoftReset()
        {
            service = new MCS.Evaluator(new CompilerContext(new CompilerSettings(), CompilationResult));

            ReferencePreviouslyReferencedAssemblies();
        }
Пример #41
0
        public override void GetCompletionStartingWith(string prefix, List <string> results)
        {
            var names = Evaluator.GetVarNames();

            results.AddRange(names.Where(l => l.StartsWith(prefix)));
        }