Evaluate() public method

Evaluates and expression or statement and returns the result.
Evaluates the input string as a C# expression or statement and returns the value. This method will throw an exception if there is a syntax error, of if the provided input is not an expression but a statement.
public Evaluate ( string input ) : object
input string
return object
Example #1
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));
        }
Example #2
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);
            }
        }
Example #3
0
    static void MonoCSharp_Test()
    {
        string className = GetClass();
        string code      = GetCode(className);

        evaluator.Compile(code);

        dynamic script = evaluator.Evaluate("new " + className + "();");

        int result = script.Sum(1, 2);
    }
Example #4
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));
            }
        }
Example #5
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);
            }
        }
Example #6
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);
 }
Example #7
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>;
        }
Example #8
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;
            }
        }
Example #9
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;
            }
        }
Example #10
0
 public Task <bool> EvaluateExpression(string expression, string code, EvalResult result)
 {
     EnsureConfigured();
     try
     {
         object retResult;
         bool   hasResult;
         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.Exception(ex);
         Log.Error($"Unhandled error creating new instance of {expression}");
         result.Messages = new EvalMessage[] { new EvalMessage {
                                                   MessageType = "error", Text = ex.ToString()
                                               } };
     }
     return(Task.FromResult(false));
 }
Example #11
0
 public Task <bool> CreateTypeInstance(string typeName, EvalResult result)
 {
     EnsureConfigured();
     try
     {
         result.Result = eval.Evaluate($"new {typeName} ()");
         return(Task.FromResult(true));
     }
     catch (Exception ex)
     {
         Log.Exception(ex);
         Log.Error($"Unhandled error creating new instance of {typeName}");
         result.Messages = new EvalMessage[] { new EvalMessage {
                                                   MessageType = "error", Text = ex.ToString()
                                               } };
     }
     return(Task.FromResult(false));
 }
        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;
        }
Example #13
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");
     }
       }
 }
Example #14
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;
 }
Example #15
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 ();
			}
		}
Example #16
0
        private Tuple<string, bool, object> EvaluateHelper(Evaluator ev, string input, CancellationToken canceller)
        {
            using (canceller.Register(Thread.CurrentThread.Abort)) {
                bool result_set;
                object result;

                input = ev.Evaluate(input, out result, out result_set);
                return Tuple.Create(input, result_set, result);
            }
        }