ReferenceAssembly() public method

Exposes the API of the given assembly to the Evaluator
public ReferenceAssembly ( Assembly a ) : void
a System.Reflection.Assembly
return void
Example #1
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");
        }
Example #2
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 #3
0
        void LoadAssembly(Assembly assembly)
        {
            var name = assembly.GetName().Name;

            if (name == "mscorlib" || name == "System" || name == "System.Core")
            {
                return;
            }
            eval?.ReferenceAssembly(assembly);
        }
Example #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;");
        }
        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;");
        }
Example #6
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;
        }
Example #8
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 #9
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 ();
        }
Example #10
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);
     }
 }
        public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces,
            ScriptPackSession scriptPackSession)
        {
            references.PathReferences.UnionWith(scriptPackSession.References);

            SessionState<Evaluator> sessionState;
            if (!scriptPackSession.State.ContainsKey(SessionKey))
            {
                Logger.Debug("Creating session");
                var context = new CompilerContext(new CompilerSettings
                {
                    AssemblyReferences = references.PathReferences.ToList()
                }, new ConsoleReportPrinter());

                var evaluator = new Evaluator(context);
                var builder = new StringBuilder();

                foreach (var ns in namespaces.Union(scriptPackSession.Namespaces).Distinct())
                {
                    builder.AppendLine(string.Format("using {0};", ns));
                }

                evaluator.Compile(builder.ToString());

                var parser = new SyntaxParser();
                var parseResult = parser.Parse(code);

                var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs);
                MonoHost.SetHost((ScriptHost)host);

                evaluator.ReferenceAssembly(typeof(MonoHost).Assembly);
                evaluator.InteractiveBaseClass = typeof(MonoHost);

                if (parseResult.Declarations != null)
                {
                    evaluator.Compile(parseResult.Declarations);
                    code = null;
                }

                if (parseResult.Evaluations != null)
                {
                    code = parseResult.Evaluations;
                }

                sessionState = new SessionState<Evaluator>
                {
                    References = references,
                    Session = evaluator
                };
                scriptPackSession.State[SessionKey] = sessionState;
            }
            else
            {
                Logger.Debug("Reusing existing session");
                sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey];

                var newReferences = sessionState.References == null ? references : references.Except(sessionState.References);
                foreach (var reference in newReferences.PathReferences)
                {
                    Logger.DebugFormat("Adding reference to {0}", reference);
                    sessionState.Session.LoadAssembly(reference);
                }

                sessionState.References = newReferences;

                var parser = new SyntaxParser();
                var parseResult = parser.Parse(code);

                if (parseResult.Declarations != null)
                {
                    var compiledMethod = sessionState.Session.Compile(parseResult.Declarations);
                    return new ScriptResult();
                    //code = parseResult.Declarations;
                }
                //var newUsings = sessionState.References == null || !sessionState.References.Any() ? distinctReferences : distinctReferences.Except(sessionState.References);
            }

            Logger.Debug("Starting execution");

            try
            {
                if (code != null)
                {
                    object scriptResult;
                    bool resultSet;
                    var result = sessionState.Session.Evaluate(code, out scriptResult, out resultSet);

                    Logger.Debug("Finished execution");
                    return new ScriptResult { ReturnValue = scriptResult };
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
            }

            return new ScriptResult();
        }
Example #12
0
 private void AddReferencedAssemblies(Evaluator eval)
 {
     eval.ReferenceAssembly(typeof (CodeCompiler).Assembly);
     eval.ReferenceAssembly(typeof (IObjectContainer).Assembly);
     eval.ReferenceAssembly(typeof (ObjectContainerExtensions).Assembly);
     eval.ReferenceAssembly(typeof(Enumerable).Assembly);
 }
Example #13
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();
 }