Run() public method

Executes the given expression or statement.
Executes the provided statement, returns true on success, false on parsing errors. Exceptions might be thrown by the called code.
public Run ( string statement ) : bool
statement string
return bool
Ejemplo n.º 1
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);
			}
		}
Ejemplo n.º 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");
        }
Ejemplo n.º 3
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;");
        }
Ejemplo n.º 4
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;");
        }
Ejemplo n.º 5
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>;
        }
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
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;
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
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;");
 }
Ejemplo n.º 10
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);");
    }
Ejemplo n.º 11
0
 private static void Main(string[] args)
 {
     Console.WriteLine("Starting Simple C# REPL, enter q to quit");
       var evaluator = new Evaluator(new CompilerContext(
     new CompilerSettings(),
     new ConsoleReportPrinter()));
       evaluator.ReferenceAssembly(Assembly.GetExecutingAssembly());
       evaluator.Run("using System;");
       evaluator.Run("using SimpleREPL;");
       while (true)
       {
     Console.Write("> ");
     var input = Console.ReadLine();
     input = input.TrimStart('>', ' ');
     if (input.ToLower() == "q")
     {
       return;
     }
     try
     {
       if (input.EndsWith(";"))
       {
     evaluator.Run(input);
       }
       else
       {
     var output = evaluator.Evaluate(input);
     Console.WriteLine(output);
       }
     }
     catch
     {
       Console.WriteLine("Error in input");
     }
       }
 }
Ejemplo n.º 12
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;
        }
        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;
        }
Ejemplo n.º 14
0
 private static void LoadPlugins(Server server)
 {
     // TODO: Make this better
     // Dynamic plugins
     var eval = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter()));
     eval.ReferenceAssembly(typeof(Plugin).Assembly);
     eval.ReferenceAssembly(typeof(Command).Assembly);
     eval.ReferenceAssembly(typeof(MinecraftServer).Assembly);
     eval.InteractiveBaseClass = typeof(ScriptPluginBase);
     ScriptPluginBase.Server = server;
     foreach (var plugin in Directory.GetFiles(Path.Combine("plugins", "scripts"), "*.csx"))
         eval.Run(File.ReadAllText(plugin));
     foreach (var plugin in Directory.GetFiles(Path.Combine("plugins", "scripts"), "*.csc")) // TODO: Upgrade Mono.CSharp to Mono 3.0 to support Roslyn-style inline classes in csx files
         eval.Compile(File.ReadAllText(plugin));
     // Load plugins
     var types = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetTypes())
             .Aggregate((a, b) => a.Concat(b).ToArray()).Where(t => !t.IsAbstract && typeof(Plugin).IsAssignableFrom(t));
     foreach (var type in types)
     {
         var plugin = (Plugin)Activator.CreateInstance(type);
         plugin.OnInitialize(server);
     }
 }
Ejemplo n.º 15
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);
            eval.InteractiveBaseClass = typeof(ILShellBaseClass);

            // 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;
        }
Ejemplo n.º 16
0
    public R2Repl(string[] args)
    {
        this.e = new Evaluator(new CompilerContext(
                new CompilerSettings {
                WarningLevel = 0,
                ShowFullPaths = true
            }, new ConsoleReportPrinter()));

        e.Run("LoadAssembly(\"Mono.Posix\")");
        e.Run("LoadAssembly(\"r2pipe\")");
        e.Run("LoadAssembly(\"Newtonsoft.Json\")");
        e.Run("using System;");
        e.Run("using System.Collections;");
        e.Run("using System.Collections.Generic;");
        e.Run("using Mono.Unix;");
        e.Run("using Newtonsoft.Json;");

        e.Run(@"
        /* example */
        public class Opcode {
        public string opcode;
        public string family;
        public string type;
        public string esil;
        public int address;
        public int size;
        }

        public class r2w {
        public r2pipe.IR2Pipe Instance;
        public r2w() {
        Instance = new r2pipe.RlangPipe();
        }
        public r2w(string file) {
        Instance = new r2pipe.R2Pipe(file);
        }
        public string cmd(string cmd) {
        return Instance.RunCommand(cmd).Trim();
        }
        public dynamic cmdj(string cmd) {
        return JsonConvert.DeserializeObject(this.cmd(cmd));
        }
        public Opcode[] Opcodes(int n) {
        var ops = new List<Opcode>();
        foreach (var op in cmdj(""aoj 10"")) {
            ops.Add (op.ToObject<Opcode>());
        }
        return ops.ToArray();
        }
        public void Seek(string addr) {
        cmd(""s "" + addr);
        }
        }
            ");
        args = ParseArgs(args);
        if (args == null) {
            /* exit */
            return;
        }
        if (args.Length > 0) {
            e.Run("var r2 = new r2w(\""+args[0]+"\");");
        } else {
            try {
                e.Run("var r2 = new r2w();");
            } catch (Exception _) {
                Console.WriteLine(@"
        Cannot find R2PIPE environment. See: csharp-r2 -h
        Run this from r2 like this: '#!pipe mono main.exe'
        ");
                return;
            }
        }
        if (RunArgs()) {
            this.shell = new CSharpShell (e);
        }
    }
Ejemplo n.º 17
0
 void Init()
 {
     // workaround to load DLR types before Evaluator would want them
     var r = Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.BinaryOperationLogical, "gf", typeof(int));
     var settings = new CompilerSettings();
     var printer = new ConsoleReportPrinter();
     eval = new Evaluator(new CompilerContext(settings, printer));
     eval.ReferenceAssembly(typeof(REPL).Assembly);
     eval.Run("using System;");
     eval.Run("using FOnline;");
     eval.Run("using System.Collections.Generic;");
     eval.Run("using System.Linq;");
     statement = new StringBuilder();
 }
Ejemplo n.º 18
0
 private void CreateEvaluationObject(Evaluator eval, string theCode)
 {
     var code = CreateCode(theCode);
     eval.Run(code);
 }
Ejemplo n.º 19
0
        private void Run()
        {
            string input = this._template.Content;

                // Ask thread pool for a new thread to do the work.
                Thread thread = null;
                Task<StringBuilder> task = Task.Factory.StartNew<StringBuilder> (() =>
                {
                      //Capture the thread, so we can abort worker thread if it hangs.
                      thread = Thread.CurrentThread;

                      // Setup error reporting.
                      using (StringWriter reportwriter = new StringWriter ())
                      {
                            try
                            {
                                string evalcode = string.Empty;

                                Report report = new Report (new Mono.CSharp.StreamReportPrinter (reportwriter));

                                // Create new evaluator instance.
                                var evaluator = new Evaluator (new CompilerSettings (), report);

                                // Reference current assembly.
                                evaluator.ReferenceAssembly (Assembly.GetExecutingAssembly ());

                        evaluator.ReferenceAssembly (typeof (SNDK.Convert).Assembly);

                                // Using.
                                evaluator.Run ("using System; using System.Collections.Generic; using SorentoLib; using SNDK");

                                foreach (SorentoLib.Addins.IRuntime runtime in AddinManager.GetExtensionObjects (typeof(SorentoLib.Addins.IRuntime)))
                                {
                                      evaluator.ReferenceAssembly (runtime.Assembly);
                                      evaluator.Run ("using " + runtime.Assembly.GetName ().Name + ";");
                                }

                                // Anonymous methods.
                                evalcode += "SorentoLib.Parser.Hooks.Commands.Print.Delegate Print = delegate (object Value) { SorentoLib.Parser.Hooks.Commands.Print.Method (Value);};\n";

                                // Variables
                                int counter = 0;
                                Parser.Hooks.Variables = this._variables;

                                foreach (ParserVariable variable in this._variables)
                                {
                                      evalcode += variable.Value.GetType ().FullName + " " + variable.Name + " = (" + variable.Value.GetType ().FullName + ")SorentoLib.Parser.Hooks.Variables[" + counter + "].Value;\n";
                                      counter++;
                                }

                                evalcode += input;

                                // Output.
                                Parser.Hooks.Errors = null;
                                Parser.Hooks.Output = new StringBuilder ();

                                // Run evaluation.
                                evaluator.Run (evalcode);

                                // Cleanup.
                                evaluator = null;
                                report = null;
                                evalcode = null;

                                if (reportwriter.ToString () != string.Empty)
                                {
                                      Console.WriteLine ("!!!!" + reportwriter.ToString ());

                                      Parser.Hooks.Errors = new ParserError (reportwriter.ToString ());
                                }
                            } catch (Exception e)
                            {
                                Console.WriteLine (e);

                                string interactive = string.Empty;
                                interactive += "{interactive}(0,0): error SE0000: " + e.Message;
                                interactive += reportwriter.ToString ();

                                Parser.Hooks.Errors = new ParserError (interactive);
                            }

                            this._errors = Hooks.Errors;
            //					this._output = Parser.Hooks.Output;

                            return Parser.Hooks.Output;
                      }
                }
                );

            if (!task.IsCompleted)
            {
                if (!task.Wait (25000))
                {
                    thread.Abort ();
                    throw new Exceptions.Parser ("TEMPLATE PARSER TIMEOUT");
                }
            }

            if (this._errors != null)
            {
                string message = string.Empty;

                bool thr = false;
                message += "PARSER EXCEPTION:<br>\n";
                foreach (SorentoLib.ParserError.Error error in this._errors.Errors)
                {
                    if (error.Type == Enums.ParserErrorType.Error)
                    {
                        thr = true;
                    }

                    message += "Line: "+ error.Line + " - "+ error.Code +" - "+ error.Text +"<br>\n";
                }

                if (thr)
                {
                    throw new Exceptions.Parser (message);
                }
            }

            this._output = task.Result;

            //			task.Dispose ();
        }
Ejemplo n.º 20
0
 		public void SameSettings ()
 		{
			var ctx = new CompilerContext (settings, new AssertReportPrinter ());
			var evaluator2 = new Evaluator (ctx);
			evaluator2.Run ("int i = 0;");
		}
Ejemplo n.º 21
0
 /// <summary>
 /// Executes the code.
 /// </summary>
 /// <returns><c>null</c> if successful, otherwise, a <see cref="string"/></returns>
 /// <param name="code">Code to execute</param>
 /// <exception cref="InvalidProgramException">
 /// Is thrown when a program contains invalid CIL instructions or metadata.
 /// </exception>
 public string ExecuteCode(string source, Project project)
 {
     Trace.Log(TraceEventType.Information, "source=\"{0}\", project.Name=\"{0}\"",
         source.Length < 48 ? source : string.Format("string({0})", source.Length),
         project == null ? "(null)" : project.Name);
     Project.CodeUsings = CSEvaluator.GetUsing();
     Settings.AssemblyReferences = new System.Collections.Generic.List<string>(Project.ReferencePaths);
     CompilerOutput = new StringBuilder();
     Context = new CompilerContext(Settings, new StreamReportPrinter(new StringWriter(CompilerOutput)));
     CSEvaluator = new Evaluator(Context);
     CSEvaluator.Run(project.CodeUsings);
     string r = string.Empty;
     try
     {
         string prefix = "EntityContext RootContext = EntityContext.Root; EntityContext CurrentContext = EntityContext.Current; ICollection<Scene> _scenes = RootContext.OfType<Scene>(); Scene[] Scenes = new Scene[_scenes.Count]; _scenes.CopyTo(Scenes, 0);";
         string code = prefix + source;
         if (code.Contains(";") && !CSEvaluator.Run(code))
         {
             string error = string.Format("Evaluator.Run() == false (source = \"{0}\")", source.Length < 48 ? source : string.Format("string({0})", source.Length));
             Trace.Log(TraceEventType.Error, error);
             throw new InvalidProgramException(error);
         }
         else
         {
             object result;
             bool result_set;
             string input;
             source += ";";
             if (!CSEvaluator.Run(prefix))
             {
                 string error = string.Format("Evaluator.Run() == false (prefix = \"{0}\")", prefix.Replace("\n", " "));
                 Trace.Log(TraceEventType.Error, error);
                 throw new InvalidProgramException(error);
             }
             input = CSEvaluator.Evaluate(source, out result, out result_set);
             if (input != null)
             {
                 string error = string.Format("Evaluator.Evaluate() != null (code = \"{0}\") = \"{1}\"", source.Replace("\n", " "), input.Replace("\n", " "));
                 Trace.Log(TraceEventType.Error, error);
                 throw new InvalidProgramException(error);
             }
             if (result_set)
                 r += result != null ? result.ToString() : "(null)";
         }
     }
     catch (Exception ex)
     {
         string error = string.Format("Caught exception: " + ex.GetType().Name + ": " + ex.Message);
         Trace.Log(TraceEventType.Error, error);
         Console.Error.WriteLine((char)27 + "[31m" + ex.ToString());
     }
     return r.Length > 0 ? string.Concat(r, "\n") : string.Empty;
 }