2 // eval.cs: Evaluation and Hosting API for the C# compiler
5 // Miguel de Icaza (miguel@gnome.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2011 Novell, Inc
12 // Copyright 2011 Xamarin Inc
16 using System.Threading;
17 using System.Collections.Generic;
18 using System.Reflection;
19 using System.Reflection.Emit;
30 public delegate void ValueModificationHandler (string variableName, int row, int column, object value);
33 /// Evaluator: provides an API to evaluate C# statements and
34 /// expressions dynamically.
37 /// This class exposes static methods to evaluate expressions in the
40 /// To initialize the evaluator with a number of compiler
41 /// options call the Init(string[]args) method with a set of
42 /// command line options that the compiler recognizes.
44 /// To interrupt execution of a statement, you can invoke the
45 /// Evaluator.Interrupt method.
47 public class Evaluator {
50 // Parse silently, do not output any error messages
53 // Report errors during parse
56 // Auto-complete, means that the tokenizer will start producing
57 // GETCOMPLETIONS tokens when it reaches a certain point.
61 static object evaluator_lock = new object ();
62 static volatile bool invoking;
67 static Thread invoke_thread;
69 readonly Dictionary<string, Tuple<FieldSpec, FieldInfo>> fields;
75 readonly CompilerContext ctx;
76 readonly ModuleContainer module;
77 readonly ReflectionImporter importer;
78 readonly CompilationSourceFile source_file;
82 public Evaluator (CompilerContext ctx)
86 module = new ModuleContainer (ctx);
87 module.Evaluator = this;
89 source_file = new CompilationSourceFile (module, null);
90 module.AddTypeContainer (source_file);
92 startup_files = ctx.SourceFiles.Count;
94 // FIXME: Importer needs this assembly for internalsvisibleto
95 module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
96 importer = new ReflectionImporter (module, ctx.BuiltinTypes);
98 InteractiveBaseClass = typeof (InteractiveBase);
99 fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
104 var loader = new DynamicLoader (importer, ctx);
106 CompilerCallableEntryPoint.Reset ();
107 RootContext.ToplevelTypes = module;
109 //var startup_files = new List<string> ();
110 //foreach (CompilationUnit file in Location.SourceFiles)
111 // startup_files.Add (file.Path);
113 loader.LoadReferences (module);
114 ctx.BuiltinTypes.CheckDefinitions (module);
115 module.InitializePredefinedTypes ();
120 void ParseStartupFiles ()
122 Driver d = new Driver (ctx);
124 Location.Initialize (ctx.SourceFiles);
126 var parser_session = new ParserSession ();
127 for (int i = 0; i < startup_files; ++i) {
128 var sf = ctx.SourceFiles [i];
129 d.Parse (sf, module, parser_session, ctx.Report);
135 CompilerCallableEntryPoint.PartialReset ();
138 Location.Initialize (ctx.SourceFiles);
142 /// When set evaluator will automatically wait on Task of async methods. When not
143 /// set it's called responsibility to handle Task execution
145 public bool WaitOnTask { get; set; }
148 /// If true, turns type expressions into valid expressions
149 /// and calls the describe method on it
151 public bool DescribeTypeExpressions;
154 /// Whether the evaluator will use terse syntax, and the semicolons at the end are optional
156 public bool Terse = true;
159 /// The base class for the classes that host the user generated code
163 /// This is the base class that will host the code
164 /// executed by the Evaluator. By default
165 /// this is the Mono.CSharp.InteractiveBase class
166 /// which is useful for interactive use.
168 /// By changing this property you can control the
169 /// base class and the static members that are
170 /// available to your evaluated code.
172 public Type InteractiveBaseClass {
179 if (value != null && typeof (InteractiveBase).IsAssignableFrom (value))
180 InteractiveBase.Evaluator = this;
185 /// Interrupts the evaluation of an expression executing in Evaluate.
188 /// Use this method to interrupt long-running invocations.
190 public void Interrupt ()
192 if (!inited || !invoking)
195 if (invoke_thread != null) {
196 #if MONO_FEATURE_THREAD_ABORT
197 invoke_thread.Abort ();
199 invoke_thread.Interrupt ();
205 /// Compiles the input string and returns a delegate that represents the compiled code.
209 /// Compiles the input string as a C# expression or
210 /// statement, unlike the Evaluate method, the
211 /// resulting delegate can be invoked multiple times
212 /// without incurring in the compilation overhead.
214 /// If the return value of this function is null,
215 /// this indicates that the parsing was complete.
216 /// If the return value is a string it indicates
217 /// that the input string was partial and that the
218 /// invoking code should provide more code before
219 /// the code can be successfully compiled.
221 /// If you know that you will always get full expressions or
222 /// statements and do not care about partial input, you can use
223 /// the other Compile overload.
225 /// On success, in addition to returning null, the
226 /// compiled parameter will be set to the delegate
227 /// that can be invoked to execute the code.
230 public string Compile (string input, out CompiledMethod compiled)
232 if (input == null || input.Length == 0){
237 lock (evaluator_lock){
240 ParseStartupFiles ();
242 ctx.Report.Printer.Reset ();
246 CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
248 // Terse mode, try to provide the trailing semicolon automatically.
249 if (parser == null && Terse && partial_input){
252 // check if the source would compile with a block, if so, we should not
253 // add the semicolon.
254 var needs_block = ParseString (ParseMode.Silent, input + "{}", out ignore) != null;
256 parser = ParseString (ParseMode.Silent, input + ";", out ignore);
263 ParseString (ParseMode.ReportErrors, input, out partial_input);
267 Class parser_result = parser.InteractiveResult;
268 compiled = CompileBlock (parser_result, parser.undo, ctx.Report);
274 /// Compiles the input string and returns a delegate that represents the compiled code.
278 /// Compiles the input string as a C# expression or
279 /// statement, unlike the Evaluate method, the
280 /// resulting delegate can be invoked multiple times
281 /// without incurring in the compilation overhead.
283 /// This method can only deal with fully formed input
284 /// strings and does not provide a completion mechanism.
285 /// If you must deal with partial input (for example for
286 /// interactive use) use the other overload.
288 /// On success, a delegate is returned that can be used
289 /// to invoke the method.
292 public CompiledMethod Compile (string input)
294 CompiledMethod compiled;
296 // Ignore partial inputs
297 if (Compile (input, out compiled) != null){
298 // Error, the input was partial.
302 // Either null (on error) or the compiled method.
306 static MethodInfo listener_proxy_value;
307 internal void EmitValueChangedCallback (EmitContext ec, string name, TypeSpec type, Location loc)
309 if (listener_id == null)
310 listener_id = ListenerProxy.Register (ModificationListener);
312 if (listener_proxy_value == null)
313 listener_proxy_value = typeof (ListenerProxy).GetMethod ("ValueChanged");
316 throw new NotSupportedException ();
318 // object value, int row, int col, string name, int listenerId
319 if (type.IsStructOrEnum)
320 ec.Emit (OpCodes.Box, type);
322 ec.EmitInt (loc.Row);
323 ec.EmitInt (loc.Column);
324 ec.Emit (OpCodes.Ldstr, name);
325 ec.EmitInt (listener_id.Value);
326 ec.Emit (OpCodes.Call, listener_proxy_value);
331 /// Evaluates and expression or statement and returns any result values.
334 /// Evaluates the input string as a C# expression or
335 /// statement. If the input string is an expression
336 /// the result will be stored in the result variable
337 /// and the result_set variable will be set to true.
339 /// It is necessary to use the result/result_set
340 /// pair to identify when a result was set (for
341 /// example, execution of user-provided input can be
342 /// an expression, a statement or others, and
343 /// result_set would only be set if the input was an
346 /// If the return value of this function is null,
347 /// this indicates that the parsing was complete.
348 /// If the return value is a string, it indicates
349 /// that the input is partial and that the user
350 /// should provide an updated string.
352 public string Evaluate (string input, out object result, out bool result_set)
354 CompiledMethod compiled;
359 input = Compile (input, out compiled);
363 if (compiled == null)
367 // The code execution does not need to keep the compiler lock
369 object retval = typeof (QuitValue);
372 invoke_thread = System.Threading.Thread.CurrentThread;
374 compiled (ref retval);
375 #if MONO_FEATURE_THREAD_ABORT
376 } catch (ThreadAbortException e){
377 Thread.ResetAbort ();
378 Console.WriteLine ("Interrupted!\n{0}", e);
380 } catch (ThreadInterruptedException e) {
381 Console.WriteLine ("Interrupted!\n{0}", e);
386 if (listener_id != null) {
387 ListenerProxy.Unregister (listener_id.Value);
393 // We use a reference to a compiler type, in this case
394 // Driver as a flag to indicate that this was a statement
396 if (!ReferenceEquals (retval, typeof (QuitValue))) {
404 public string [] GetCompletions (string input, out string prefix)
407 if (input == null || input.Length == 0)
410 lock (evaluator_lock){
415 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
420 Class host = parser.InteractiveResult;
422 var base_class_imported = importer.ImportType (base_class);
423 var baseclass_list = new List<FullNamedExpression> (1) {
424 new TypeExpression (base_class_imported, host.Location)
426 host.SetBaseTypes (baseclass_list);
428 var access = AssemblyBuilderAccess.RunAndCollect;
429 var a = new AssemblyDefinitionDynamic (module, "completions");
430 a.Create (AppDomain.CurrentDomain, access);
431 module.SetDeclaringAssembly (a);
433 // Need to setup MemberCache
434 host.CreateContainer ();
435 // Need to setup base type
436 host.DefineContainer ();
438 var method = host.Members[0] as Method;
439 BlockContext bc = new BlockContext (method, method.Block, ctx.BuiltinTypes.Void);
442 method.Block.Resolve (bc, method);
443 } catch (CompletionResult cr) {
444 prefix = cr.BaseText;
452 /// Executes the given expression or statement.
455 /// Executes the provided statement, returns true
456 /// on success, false on parsing errors. Exceptions
457 /// might be thrown by the called code.
459 public bool Run (string statement)
464 return Evaluate (statement, out result, out result_set) == null;
468 /// Evaluates and expression or statement and returns the result.
471 /// Evaluates the input string as a C# expression or
472 /// statement and returns the value.
474 /// This method will throw an exception if there is a syntax error,
475 /// of if the provided input is not an expression but a statement.
477 public object Evaluate (string input)
482 string r = Evaluate (input, out result, out result_set);
485 throw new ArgumentException ("Syntax error on input: partial input");
487 if (result_set == false)
488 throw new ArgumentException ("The expression failed to resolve");
496 public ValueModificationHandler ModificationListener { get; set; }
500 StatementOrExpression,
506 // Deambiguates the input string to determine if we
507 // want to process a statement or if we want to
508 // process a compilation unit.
510 // This is done using a top-down predictive parser,
511 // since the yacc/jay parser can not deambiguage this
512 // without more than one lookahead token. There are very
515 InputKind ToplevelOrStatement (SeekableStreamReader seekable)
517 Tokenizer tokenizer = new Tokenizer (seekable, source_file, new ParserSession (), ctx.Report);
519 // Prefer contextual block keywords over identifiers
520 tokenizer.parsing_block++;
522 int t = tokenizer.token ();
525 return InputKind.EOF;
527 // These are toplevels
529 case Token.OPEN_BRACKET:
530 case Token.OPEN_BRACKET_EXPR:
534 case Token.INTERFACE:
536 case Token.NAMESPACE:
538 case Token.PROTECTED:
543 return InputKind.CompilationUnit;
545 // Definitely expression
562 return InputKind.StatementOrExpression;
564 // These need deambiguation help
566 t = tokenizer.token ();
568 return InputKind.EOF;
570 if (t == Token.IDENTIFIER || t == Token.STATIC)
571 return InputKind.CompilationUnit;
572 return InputKind.StatementOrExpression;
575 // Distinguish between:
576 // delegate opt_anonymous_method_signature block
579 t = tokenizer.token ();
581 return InputKind.EOF;
582 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
583 return InputKind.StatementOrExpression;
584 return InputKind.CompilationUnit;
586 // Distinguih between:
588 // unsafe as modifier of a type declaration
590 t = tokenizer.token ();
592 return InputKind.EOF;
593 if (t == Token.OPEN_PARENS)
594 return InputKind.StatementOrExpression;
595 return InputKind.CompilationUnit;
597 // These are errors: we list explicitly what we had
598 // from the grammar, ERROR and then everything else
603 return InputKind.Error;
605 // This catches everything else allowed by
606 // expressions. We could add one-by-one use cases
609 return InputKind.StatementOrExpression;
614 // Parses the string @input and returns a CSharpParser if succeeful.
616 // if @silent is set to true then no errors are
617 // reported to the user. This is used to do various calls to the
618 // parser and check if the expression is parsable.
620 // @partial_input: if @silent is true, then it returns whether the
621 // parsed expression was partial, and more data is needed
623 CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
625 partial_input = false;
628 var enc = ctx.Settings.Encoding;
629 var s = new MemoryStream (enc.GetBytes (input));
630 SeekableStreamReader seekable = new SeekableStreamReader (s, enc);
632 InputKind kind = ToplevelOrStatement (seekable);
633 if (kind == InputKind.Error){
634 if (mode == ParseMode.ReportErrors)
635 ctx.Report.Error (-25, "Detection Parsing Error");
636 partial_input = false;
640 if (kind == InputKind.EOF){
641 if (mode == ParseMode.ReportErrors)
642 Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
643 partial_input = true;
647 seekable.Position = 0;
649 source_file.DeclarationFound = false;
650 CSharpParser parser = new CSharpParser (seekable, source_file, new ParserSession ());
652 if (kind == InputKind.StatementOrExpression){
653 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
654 parser.Lexer.parsing_block++;
655 ctx.Settings.StatementMode = true;
657 parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
658 ctx.Settings.StatementMode = false;
661 if (mode == ParseMode.GetCompletions)
662 parser.Lexer.CompleteOnEOF = true;
664 ReportPrinter old_printer = null;
665 if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions))
666 old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null));
671 if (ctx.Report.Errors != 0){
672 if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
673 partial_input = true;
675 if (parser.undo != null)
676 parser.undo.ExecuteUndo ();
681 if (old_printer != null)
682 ctx.Report.SetPrinter (old_printer);
687 CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
690 throw new NotSupportedException ();
692 string current_debug_name = "eval-" + count + ".dll";
695 AssemblyDefinitionDynamic assembly;
696 AssemblyBuilderAccess access;
698 if (Environment.GetEnvironmentVariable ("SAVE") != null) {
699 access = AssemblyBuilderAccess.RunAndSave;
700 assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name);
701 assembly.Importer = importer;
703 access = AssemblyBuilderAccess.RunAndCollect;
704 assembly = new AssemblyDefinitionDynamic (module, current_debug_name);
707 assembly.Create (AppDomain.CurrentDomain, access);
709 Method expression_method;
711 var base_class_imported = importer.ImportType (base_class);
712 var baseclass_list = new List<FullNamedExpression> (1) {
713 new TypeExpression (base_class_imported, host.Location)
716 host.SetBaseTypes (baseclass_list);
718 expression_method = (Method) host.Members[0];
720 if ((expression_method.ModFlags & Modifiers.ASYNC) != 0) {
722 // Host method is async. When WaitOnTask is set we wrap it with wait
724 // void AsyncWait (ref object $retval) {
726 // ((Task)$retval).Wait(); // When WaitOnTask is set
729 var p = new ParametersCompiled (
730 new Parameter (new TypeExpression (module.Compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null)
733 var method = new Method(host, new TypeExpression(module.Compiler.BuiltinTypes.Void, Location.Null),
734 Modifiers.PUBLIC | Modifiers.STATIC, new MemberName("AsyncWait"), p, null);
736 method.Block = new ToplevelBlock(method.Compiler, p, Location.Null);
737 method.Block.AddStatement(new StatementExpression (new SimpleAssign(
738 new SimpleName(p [0].Name, Location.Null),
739 new Invocation(new SimpleName(expression_method.MemberName.Name, Location.Null), new Arguments(0)),
740 Location.Null), Location.Null));
743 var task = new Cast (expression_method.TypeExpression, new SimpleName (p [0].Name, Location.Null), Location.Null);
745 method.Block.AddStatement (new StatementExpression (new Invocation (
746 new MemberAccess (task, "Wait", Location.Null),
747 new Arguments (0)), Location.Null));
750 host.AddMember(method);
752 expression_method = method;
755 host.CreateContainer();
756 host.DefineContainer();
760 expression_method = null;
763 module.CreateContainer ();
765 // Disable module and source file re-definition checks
766 module.EnableRedefinition ();
767 source_file.EnableRedefinition ();
771 if (Report.Errors != 0){
780 host.EmitContainer ();
783 module.EmitContainer ();
785 if (Report.Errors != 0){
791 module.CloseContainer ();
793 host.CloseContainer ();
795 if (access == AssemblyBuilderAccess.RunAndSave)
802 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
803 // work from MethodBuilders. Retarded, I know.
805 var tt = assembly.Builder.GetType (host.TypeBuilder.Name);
806 var mi = tt.GetMethod (expression_method.MemberName.Name);
809 // We need to then go from FieldBuilder to FieldInfo
810 // or reflection gets confused (it basically gets confused, and variables override each
813 foreach (var member in host.Members) {
814 var field = member as Field;
818 var fi = tt.GetField (field.Name);
820 Tuple<FieldSpec, FieldInfo> old;
822 // If a previous value was set, nullify it, so that we do
824 if (fields.TryGetValue (field.Name, out old)) {
825 if (old.Item1.MemberType.IsStruct) {
827 // TODO: Clear fields for structs
831 old.Item2.SetValue (null, null);
837 fields[field.Name] = Tuple.Create (field.Spec, fi);
840 return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
845 /// A sentinel value used to indicate that no value was
846 /// was set by the compiled function. This is used to
847 /// differentiate between a function not returning a
850 internal static class QuitValue { }
852 internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
854 Tuple<FieldSpec, FieldInfo> fi;
855 fields.TryGetValue (name, out fi);
859 static string Quote (string s)
861 if (s.IndexOf ('"') != -1)
862 s = s.Replace ("\"", "\\\"");
864 return "\"" + s + "\"";
867 public string GetUsing ()
869 if (source_file == null || source_file.Usings == null)
872 StringBuilder sb = new StringBuilder ();
874 //foreach (object x in ns.using_alias_list)
875 // sb.AppendFormat ("using {0};\n", x);
877 foreach (var ue in source_file.Usings) {
878 if (ue.Alias != null || ue.ResolvedExpression == null)
881 sb.AppendFormat("using {0};", ue.ToString ());
882 sb.Append (Environment.NewLine);
885 return sb.ToString ();
888 internal List<string> GetUsingList ()
890 var res = new List<string> ();
892 if (source_file == null || source_file.Usings == null)
895 foreach (var ue in source_file.Usings)
897 if (ue.Alias != null || ue.ResolvedExpression == null)
900 res.Add (ue.NamespaceExpression.Name);
906 internal string [] GetVarNames ()
908 lock (evaluator_lock){
909 return new List<string> (fields.Keys).ToArray ();
913 public string GetVars ()
915 lock (evaluator_lock){
916 StringBuilder sb = new StringBuilder ();
918 foreach (var de in fields){
919 var fi = LookupField (de.Key);
922 value = fi.Item2.GetValue (null);
924 value = Quote ((string)value);
926 value = "<error reading value>";
929 sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
933 return sb.ToString ();
938 /// Loads the given assembly and exposes the API to the user.
940 public void LoadAssembly (string file)
942 var loader = new DynamicLoader (importer, ctx);
943 var assembly = loader.LoadAssemblyFile (file, false);
944 if (assembly == null)
947 lock (evaluator_lock){
948 importer.ImportAssembly (assembly, module.GlobalRootNamespace);
953 /// Exposes the API of the given assembly to the Evaluator
955 public void ReferenceAssembly (Assembly a)
957 lock (evaluator_lock){
958 importer.ImportAssembly (a, module.GlobalRootNamespace);
962 public void ImportTypes (bool importExtensionTypes, params Type[] types) {
964 importer.ImportTypes (types, module.GlobalRootNamespace, importExtensionTypes);
971 /// A delegate that can be used to invoke the
972 /// compiled expression or statement.
975 /// Since the Compile methods will compile
976 /// statements and expressions into the same
977 /// delegate, you can tell if a value was returned
978 /// by checking whether the returned value is of type
982 public delegate void CompiledMethod (ref object retvalue);
985 /// The default base class for every interaction line
988 /// The expressions and statements behave as if they were
989 /// a static method of this class. The InteractiveBase class
990 /// contains a number of useful methods, but can be overwritten
991 /// by setting the InteractiveBaseType property in the Evaluator
993 public class InteractiveBase {
995 /// Determines where the standard output of methods in this class will go.
997 public static TextWriter Output = Console.Out;
1000 /// Determines where the standard error of methods in this class will go.
1002 public static TextWriter Error = Console.Error;
1005 /// The primary prompt used for interactive use.
1007 public static string Prompt = "csharp> ";
1010 /// The secondary prompt used for interactive use (used when
1011 /// an expression is incomplete).
1013 public static string ContinuationPrompt = " > ";
1016 /// Used to signal that the user has invoked the `quit' statement.
1018 public static bool QuitRequested;
1020 public static Evaluator Evaluator;
1023 /// Shows all the variables defined so far.
1025 static public void ShowVars ()
1027 Output.Write (Evaluator.GetVars ());
1032 /// Displays the using statements in effect at this point.
1034 static public void ShowUsing ()
1036 Output.Write (Evaluator.GetUsing ());
1041 /// Times the execution of the given delegate
1043 static public TimeSpan Time (Action a)
1045 DateTime start = DateTime.Now;
1047 return DateTime.Now - start;
1051 /// Loads the assemblies from a package
1054 /// Loads the assemblies from a package. This is equivalent
1055 /// to passing the -pkg: command line flag to the C# compiler
1056 /// on the command line.
1058 static public void LoadPackage (string pkg)
1061 Error.WriteLine ("Invalid package specified");
1065 string pkgout = Driver.GetPackageFlags (pkg, null);
1067 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1068 Split (new Char [] { ' ', '\t'});
1070 foreach (string s in xargs){
1071 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
1072 string lib = s.Substring (s.IndexOf (':')+1);
1074 Evaluator.LoadAssembly (lib);
1081 /// Loads the assembly
1084 /// Loads the specified assembly and makes its types
1085 /// available to the evaluator. This is equivalent
1086 /// to passing the -pkg: command line flag to the C#
1087 /// compiler on the command line.
1089 static public void LoadAssembly (string assembly)
1091 Evaluator.LoadAssembly (assembly);
1094 static public void print (object obj)
1096 Output.WriteLine (obj);
1099 static public void print (string fmt, params object [] args)
1101 Output.WriteLine (fmt, args);
1105 /// Returns a list of available static methods.
1107 static public string help {
1109 return "Static methods:\n" +
1110 " Describe (object); - Describes the object's type\n" +
1111 " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" +
1112 " LoadAssembly (assembly); - Loads the given assembly (like -r:ASSEMBLY)\n" +
1113 " ShowVars (); - Shows defined local variables.\n" +
1114 " ShowUsing (); - Show active using declarations.\n" +
1115 " Prompt - The prompt used by the C# shell\n" +
1116 " ContinuationPrompt - The prompt for partial input\n" +
1117 " Time (() => { }); - Times the specified code\n" +
1118 " print (obj); - Shorthand for Console.WriteLine\n" +
1119 " quit; - You'll never believe it - this quits the repl!\n" +
1120 " help; - This help text\n";
1125 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1127 static public object quit {
1129 QuitRequested = true;
1131 // To avoid print null at the exit
1132 return typeof (Evaluator.QuitValue);
1137 /// Same as quit - useful in script scenerios
1139 static public void Quit () {
1140 QuitRequested = true;
1145 /// Describes an object or a type.
1148 /// This method will show a textual representation
1149 /// of the object's type. If the object is a
1150 /// System.Type it renders the type directly,
1151 /// otherwise it renders the type returned by
1152 /// invoking GetType on the object.
1154 static public string Describe (object x)
1159 var type = x as Type ?? x.GetType ();
1161 StringWriter sw = new StringWriter ();
1162 new Outline (type, sw, true, false, false).OutlineType ();
1163 return sw.ToString ();
1168 class InteractiveMethod : Method
1170 public InteractiveMethod(TypeDefinition parent, FullNamedExpression returnType, Modifiers mod, ParametersCompiled parameters)
1171 : base(parent, returnType, mod, new MemberName("Host"), parameters, null)
1175 public void ChangeToAsync ()
1177 ModFlags |= Modifiers.ASYNC;
1178 ModFlags &= ~Modifiers.UNSAFE;
1179 type_expr = new TypeExpression(Module.PredefinedTypes.Task.TypeSpec, Location);
1180 parameters = ParametersCompiled.EmptyReadOnlyParameters;
1183 public override string GetSignatureForError()
1185 return "InteractiveHost";
1189 class HoistedEvaluatorVariable : HoistedVariable
1191 public HoistedEvaluatorVariable (Field field)
1192 : base (null, field)
1196 protected override FieldExpr GetFieldExpression (EmitContext ec)
1198 return new FieldExpr (field, field.Location);
1203 /// A class used to assign values if the source expression is not void
1205 /// Used by the interactive shell to allow it to call this code to set
1206 /// the return value for an invocation.
1208 class OptionalAssign : SimpleAssign {
1209 public OptionalAssign (Expression s, Location loc)
1210 : base (null, s, loc)
1214 public override Location StartLocation {
1216 return Location.Null;
1220 protected override Expression DoResolve (ResolveContext ec)
1222 Expression clone = source.Clone (new CloneContext ());
1224 clone = clone.Resolve (ec);
1229 // A useful feature for the REPL: if we can resolve the expression
1230 // as a type, Describe the type;
1232 if (ec.Module.Evaluator.DescribeTypeExpressions && !(ec.CurrentAnonymousMethod is AsyncInitializer)) {
1233 var old_printer = ec.Report.SetPrinter (new SessionReportPrinter ());
1236 // Note: clone context cannot be shared otherwise block mapping would leak
1237 tclone = source.Clone (new CloneContext ());
1238 tclone = tclone.Resolve (ec, ResolveFlags.Type);
1239 if (ec.Report.Errors > 0)
1242 ec.Report.SetPrinter (old_printer);
1245 if (tclone is TypeExpr) {
1246 Arguments args = new Arguments (1);
1247 args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1248 return new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1252 // This means its really a statement.
1253 if (clone.Type.Kind == MemberKind.Void || clone is DynamicInvocation || clone is Assign) {
1259 var host = (Method) ec.MemberContext.CurrentMemberDefinition;
1261 if (host.ParameterInfo.IsEmpty) {
1262 eclass = ExprClass.Value;
1263 type = InternalType.FakeInternalType;
1267 target = new SimpleName (host.ParameterInfo[0].Name, Location);
1269 return base.DoResolve (ec);
1272 public override void EmitStatement(EmitContext ec)
1274 if (target == null) {
1279 base.EmitStatement(ec);
1285 List<Action> undo_actions;
1287 public void AddTypeContainer (TypeContainer current_container, TypeDefinition tc)
1289 if (current_container == tc){
1290 Console.Error.WriteLine ("Internal error: inserting container into itself");
1294 if (undo_actions == null)
1295 undo_actions = new List<Action> ();
1297 if (current_container.Containers != null)
1299 var existing = current_container.Containers.FirstOrDefault (l => l.MemberName.Basename == tc.MemberName.Basename);
1300 if (existing != null) {
1301 current_container.RemoveContainer (existing);
1302 undo_actions.Add (() => current_container.AddTypeContainer (existing));
1306 undo_actions.Add (() => current_container.RemoveContainer (tc));
1309 public void ExecuteUndo ()
1311 if (undo_actions == null)
1314 foreach (var p in undo_actions){
1318 undo_actions = null;
1322 static class ListenerProxy
1324 static readonly Dictionary<int, ValueModificationHandler> listeners = new Dictionary<int, ValueModificationHandler> ();
1328 public static int Register (ValueModificationHandler listener)
1332 listeners.Add (id, listener);
1337 public static void Unregister (int listenerId)
1340 listeners.Remove (listenerId);
1344 public static void ValueChanged (object value, int row, int col, string name, int listenerId)
1346 ValueModificationHandler action;
1348 if (!listeners.TryGetValue (listenerId, out action))
1352 action (name, row, col, value);