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 invoke_thread.Abort ();
200 /// Compiles the input string and returns a delegate that represents the compiled code.
204 /// Compiles the input string as a C# expression or
205 /// statement, unlike the Evaluate method, the
206 /// resulting delegate can be invoked multiple times
207 /// without incurring in the compilation overhead.
209 /// If the return value of this function is null,
210 /// this indicates that the parsing was complete.
211 /// If the return value is a string it indicates
212 /// that the input string was partial and that the
213 /// invoking code should provide more code before
214 /// the code can be successfully compiled.
216 /// If you know that you will always get full expressions or
217 /// statements and do not care about partial input, you can use
218 /// the other Compile overload.
220 /// On success, in addition to returning null, the
221 /// compiled parameter will be set to the delegate
222 /// that can be invoked to execute the code.
225 public string Compile (string input, out CompiledMethod compiled)
227 if (input == null || input.Length == 0){
232 lock (evaluator_lock){
235 ParseStartupFiles ();
237 ctx.Report.Printer.Reset ();
241 CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
243 // Terse mode, try to provide the trailing semicolon automatically.
244 if (parser == null && Terse && partial_input){
247 // check if the source would compile with a block, if so, we should not
248 // add the semicolon.
249 var needs_block = ParseString (ParseMode.Silent, input + "{}", out ignore) != null;
251 parser = ParseString (ParseMode.Silent, input + ";", out ignore);
258 ParseString (ParseMode.ReportErrors, input, out partial_input);
262 Class parser_result = parser.InteractiveResult;
263 compiled = CompileBlock (parser_result, parser.undo, ctx.Report);
269 /// Compiles the input string and returns a delegate that represents the compiled code.
273 /// Compiles the input string as a C# expression or
274 /// statement, unlike the Evaluate method, the
275 /// resulting delegate can be invoked multiple times
276 /// without incurring in the compilation overhead.
278 /// This method can only deal with fully formed input
279 /// strings and does not provide a completion mechanism.
280 /// If you must deal with partial input (for example for
281 /// interactive use) use the other overload.
283 /// On success, a delegate is returned that can be used
284 /// to invoke the method.
287 public CompiledMethod Compile (string input)
289 CompiledMethod compiled;
291 // Ignore partial inputs
292 if (Compile (input, out compiled) != null){
293 // Error, the input was partial.
297 // Either null (on error) or the compiled method.
301 static MethodInfo listener_proxy_value;
302 internal void EmitValueChangedCallback (EmitContext ec, string name, TypeSpec type, Location loc)
304 if (listener_id == null)
305 listener_id = ListenerProxy.Register (ModificationListener);
307 if (listener_proxy_value == null)
308 listener_proxy_value = typeof (ListenerProxy).GetMethod ("ValueChanged");
311 throw new NotSupportedException ();
313 // object value, int row, int col, string name, int listenerId
314 if (type.IsStructOrEnum)
315 ec.Emit (OpCodes.Box, type);
317 Console.WriteLine ("EMIT: {0} => {1},{2}", name, loc.Row, loc.Column);
319 ec.EmitInt (loc.Row);
320 ec.EmitInt (loc.Column);
321 ec.Emit (OpCodes.Ldstr, name);
322 ec.EmitInt (listener_id.Value);
323 ec.Emit (OpCodes.Call, listener_proxy_value);
328 /// Evaluates and expression or statement and returns any result values.
331 /// Evaluates the input string as a C# expression or
332 /// statement. If the input string is an expression
333 /// the result will be stored in the result variable
334 /// and the result_set variable will be set to true.
336 /// It is necessary to use the result/result_set
337 /// pair to identify when a result was set (for
338 /// example, execution of user-provided input can be
339 /// an expression, a statement or others, and
340 /// result_set would only be set if the input was an
343 /// If the return value of this function is null,
344 /// this indicates that the parsing was complete.
345 /// If the return value is a string, it indicates
346 /// that the input is partial and that the user
347 /// should provide an updated string.
349 public string Evaluate (string input, out object result, out bool result_set)
351 CompiledMethod compiled;
356 input = Compile (input, out compiled);
360 if (compiled == null)
364 // The code execution does not need to keep the compiler lock
366 object retval = typeof (QuitValue);
369 invoke_thread = System.Threading.Thread.CurrentThread;
371 compiled (ref retval);
372 } catch (ThreadAbortException e){
373 Thread.ResetAbort ();
374 Console.WriteLine ("Interrupted!\n{0}", e);
378 if (listener_id != null) {
379 ListenerProxy.Unregister (listener_id.Value);
385 // We use a reference to a compiler type, in this case
386 // Driver as a flag to indicate that this was a statement
388 if (!ReferenceEquals (retval, typeof (QuitValue))) {
396 public string [] GetCompletions (string input, out string prefix)
399 if (input == null || input.Length == 0)
402 lock (evaluator_lock){
407 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
412 Class host = parser.InteractiveResult;
414 var base_class_imported = importer.ImportType (base_class);
415 var baseclass_list = new List<FullNamedExpression> (1) {
416 new TypeExpression (base_class_imported, host.Location)
418 host.SetBaseTypes (baseclass_list);
421 var access = AssemblyBuilderAccess.RunAndCollect;
423 var access = AssemblyBuilderAccess.Run;
425 var a = new AssemblyDefinitionDynamic (module, "completions");
426 a.Create (AppDomain.CurrentDomain, access);
427 module.SetDeclaringAssembly (a);
429 // Need to setup MemberCache
430 host.CreateContainer ();
431 // Need to setup base type
432 host.DefineContainer ();
434 var method = host.Members[0] as Method;
435 BlockContext bc = new BlockContext (method, method.Block, ctx.BuiltinTypes.Void);
438 method.Block.Resolve (bc, method);
439 } catch (CompletionResult cr) {
440 prefix = cr.BaseText;
448 /// Executes the given expression or statement.
451 /// Executes the provided statement, returns true
452 /// on success, false on parsing errors. Exceptions
453 /// might be thrown by the called code.
455 public bool Run (string statement)
460 return Evaluate (statement, out result, out result_set) == null;
464 /// Evaluates and expression or statement and returns the result.
467 /// Evaluates the input string as a C# expression or
468 /// statement and returns the value.
470 /// This method will throw an exception if there is a syntax error,
471 /// of if the provided input is not an expression but a statement.
473 public object Evaluate (string input)
478 string r = Evaluate (input, out result, out result_set);
481 throw new ArgumentException ("Syntax error on input: partial input");
483 if (result_set == false)
484 throw new ArgumentException ("The expression failed to resolve");
492 public ValueModificationHandler ModificationListener { get; set; }
496 StatementOrExpression,
502 // Deambiguates the input string to determine if we
503 // want to process a statement or if we want to
504 // process a compilation unit.
506 // This is done using a top-down predictive parser,
507 // since the yacc/jay parser can not deambiguage this
508 // without more than one lookahead token. There are very
511 InputKind ToplevelOrStatement (SeekableStreamReader seekable)
513 Tokenizer tokenizer = new Tokenizer (seekable, source_file, new ParserSession (), ctx.Report);
515 // Prefer contextual block keywords over identifiers
516 tokenizer.parsing_block++;
518 int t = tokenizer.token ();
521 return InputKind.EOF;
523 // These are toplevels
525 case Token.OPEN_BRACKET:
529 case Token.INTERFACE:
531 case Token.NAMESPACE:
533 case Token.PROTECTED:
538 return InputKind.CompilationUnit;
540 // Definitely expression
557 return InputKind.StatementOrExpression;
559 // These need deambiguation help
561 t = tokenizer.token ();
563 return InputKind.EOF;
565 if (t == Token.IDENTIFIER)
566 return InputKind.CompilationUnit;
567 return InputKind.StatementOrExpression;
570 // Distinguish between:
571 // delegate opt_anonymous_method_signature block
574 t = tokenizer.token ();
576 return InputKind.EOF;
577 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
578 return InputKind.StatementOrExpression;
579 return InputKind.CompilationUnit;
581 // Distinguih between:
583 // unsafe as modifier of a type declaration
585 t = tokenizer.token ();
587 return InputKind.EOF;
588 if (t == Token.OPEN_PARENS)
589 return InputKind.StatementOrExpression;
590 return InputKind.CompilationUnit;
592 // These are errors: we list explicitly what we had
593 // from the grammar, ERROR and then everything else
598 return InputKind.Error;
600 // This catches everything else allowed by
601 // expressions. We could add one-by-one use cases
604 return InputKind.StatementOrExpression;
609 // Parses the string @input and returns a CSharpParser if succeeful.
611 // if @silent is set to true then no errors are
612 // reported to the user. This is used to do various calls to the
613 // parser and check if the expression is parsable.
615 // @partial_input: if @silent is true, then it returns whether the
616 // parsed expression was partial, and more data is needed
618 CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
620 partial_input = false;
623 var enc = ctx.Settings.Encoding;
624 var s = new MemoryStream (enc.GetBytes (input));
625 SeekableStreamReader seekable = new SeekableStreamReader (s, enc);
627 InputKind kind = ToplevelOrStatement (seekable);
628 if (kind == InputKind.Error){
629 if (mode == ParseMode.ReportErrors)
630 ctx.Report.Error (-25, "Detection Parsing Error");
631 partial_input = false;
635 if (kind == InputKind.EOF){
636 if (mode == ParseMode.ReportErrors)
637 Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
638 partial_input = true;
642 seekable.Position = 0;
644 source_file.DeclarationFound = false;
645 CSharpParser parser = new CSharpParser (seekable, source_file, new ParserSession ());
647 if (kind == InputKind.StatementOrExpression){
648 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
649 parser.Lexer.parsing_block++;
650 ctx.Settings.StatementMode = true;
652 parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
653 ctx.Settings.StatementMode = false;
656 if (mode == ParseMode.GetCompletions)
657 parser.Lexer.CompleteOnEOF = true;
659 ReportPrinter old_printer = null;
660 if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions))
661 old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null));
666 if (ctx.Report.Errors != 0){
667 if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
668 partial_input = true;
670 if (parser.undo != null)
671 parser.undo.ExecuteUndo ();
676 if (old_printer != null)
677 ctx.Report.SetPrinter (old_printer);
682 CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
685 throw new NotSupportedException ();
687 string current_debug_name = "eval-" + count + ".dll";
690 AssemblyDefinitionDynamic assembly;
691 AssemblyBuilderAccess access;
693 if (Environment.GetEnvironmentVariable ("SAVE") != null) {
694 access = AssemblyBuilderAccess.RunAndSave;
695 assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name);
696 assembly.Importer = importer;
699 access = AssemblyBuilderAccess.RunAndCollect;
701 access = AssemblyBuilderAccess.Run;
703 assembly = new AssemblyDefinitionDynamic (module, current_debug_name);
706 assembly.Create (AppDomain.CurrentDomain, access);
708 Method expression_method;
710 var base_class_imported = importer.ImportType (base_class);
711 var baseclass_list = new List<FullNamedExpression> (1) {
712 new TypeExpression (base_class_imported, host.Location)
715 host.SetBaseTypes (baseclass_list);
717 expression_method = (Method) host.Members[0];
719 if ((expression_method.ModFlags & Modifiers.ASYNC) != 0) {
721 // Host method is async. When WaitOnTask is set we wrap it with wait
723 // void AsyncWait (ref object $retval) {
725 // ((Task)$retval).Wait(); // When WaitOnTask is set
728 var p = new ParametersCompiled (
729 new Parameter (new TypeExpression (module.Compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null)
732 var method = new Method(host, new TypeExpression(module.Compiler.BuiltinTypes.Void, Location.Null),
733 Modifiers.PUBLIC | Modifiers.STATIC, new MemberName("AsyncWait"), p, null);
735 method.Block = new ToplevelBlock(method.Compiler, p, Location.Null);
736 method.Block.AddStatement(new StatementExpression (new SimpleAssign(
737 new SimpleName(p [0].Name, Location.Null),
738 new Invocation(new SimpleName(expression_method.MemberName.Name, Location.Null), new Arguments(0)),
739 Location.Null), Location.Null));
742 var task = new Cast (expression_method.TypeExpression, new SimpleName (p [0].Name, Location.Null), Location.Null);
744 method.Block.AddStatement (new StatementExpression (new Invocation (
745 new MemberAccess (task, "Wait", Location.Null),
746 new Arguments (0)), Location.Null));
749 host.AddMember(method);
751 expression_method = method;
754 host.CreateContainer();
755 host.DefineContainer();
759 expression_method = null;
762 module.CreateContainer ();
764 // Disable module and source file re-definition checks
765 module.EnableRedefinition ();
766 source_file.EnableRedefinition ();
770 if (Report.Errors != 0){
779 host.EmitContainer ();
782 module.EmitContainer ();
784 if (Report.Errors != 0){
790 module.CloseContainer ();
792 host.CloseContainer ();
794 if (access == AssemblyBuilderAccess.RunAndSave)
801 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
802 // work from MethodBuilders. Retarded, I know.
804 var tt = assembly.Builder.GetType (host.TypeBuilder.Name);
805 var mi = tt.GetMethod (expression_method.MemberName.Name);
808 // We need to then go from FieldBuilder to FieldInfo
809 // or reflection gets confused (it basically gets confused, and variables override each
812 foreach (var member in host.Members) {
813 var field = member as Field;
817 var fi = tt.GetField (field.Name);
819 Tuple<FieldSpec, FieldInfo> old;
821 // If a previous value was set, nullify it, so that we do
823 if (fields.TryGetValue (field.Name, out old)) {
824 if (old.Item1.MemberType.IsStruct) {
826 // TODO: Clear fields for structs
830 old.Item2.SetValue (null, null);
836 fields[field.Name] = Tuple.Create (field.Spec, fi);
839 return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
844 /// A sentinel value used to indicate that no value was
845 /// was set by the compiled function. This is used to
846 /// differentiate between a function not returning a
849 internal static class QuitValue { }
851 internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
853 Tuple<FieldSpec, FieldInfo> fi;
854 fields.TryGetValue (name, out fi);
858 static string Quote (string s)
860 if (s.IndexOf ('"') != -1)
861 s = s.Replace ("\"", "\\\"");
863 return "\"" + s + "\"";
866 public string GetUsing ()
868 StringBuilder sb = new StringBuilder ();
870 //foreach (object x in ns.using_alias_list)
871 // sb.AppendFormat ("using {0};\n", x);
873 foreach (var ue in source_file.Usings) {
874 sb.AppendFormat ("using {0};", ue.ToString ());
875 sb.Append (Environment.NewLine);
878 return sb.ToString ();
881 internal List<string> GetUsingList ()
883 var res = new List<string> ();
885 foreach (var ue in source_file.Usings) {
886 if (ue.Alias != null || ue.ResolvedExpression == null)
889 res.Add (ue.NamespaceExpression.Name);
895 internal string [] GetVarNames ()
897 lock (evaluator_lock){
898 return new List<string> (fields.Keys).ToArray ();
902 public string GetVars ()
904 lock (evaluator_lock){
905 StringBuilder sb = new StringBuilder ();
907 foreach (var de in fields){
908 var fi = LookupField (de.Key);
911 value = fi.Item2.GetValue (null);
913 value = Quote ((string)value);
915 value = "<error reading value>";
918 sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
922 return sb.ToString ();
927 /// Loads the given assembly and exposes the API to the user.
929 public void LoadAssembly (string file)
931 var loader = new DynamicLoader (importer, ctx);
932 var assembly = loader.LoadAssemblyFile (file, false);
933 if (assembly == null)
936 lock (evaluator_lock){
937 importer.ImportAssembly (assembly, module.GlobalRootNamespace);
942 /// Exposes the API of the given assembly to the Evaluator
944 public void ReferenceAssembly (Assembly a)
946 lock (evaluator_lock){
947 importer.ImportAssembly (a, module.GlobalRootNamespace);
954 /// A delegate that can be used to invoke the
955 /// compiled expression or statement.
958 /// Since the Compile methods will compile
959 /// statements and expressions into the same
960 /// delegate, you can tell if a value was returned
961 /// by checking whether the returned value is of type
965 public delegate void CompiledMethod (ref object retvalue);
968 /// The default base class for every interaction line
971 /// The expressions and statements behave as if they were
972 /// a static method of this class. The InteractiveBase class
973 /// contains a number of useful methods, but can be overwritten
974 /// by setting the InteractiveBaseType property in the Evaluator
976 public class InteractiveBase {
978 /// Determines where the standard output of methods in this class will go.
980 public static TextWriter Output = Console.Out;
983 /// Determines where the standard error of methods in this class will go.
985 public static TextWriter Error = Console.Error;
988 /// The primary prompt used for interactive use.
990 public static string Prompt = "csharp> ";
993 /// The secondary prompt used for interactive use (used when
994 /// an expression is incomplete).
996 public static string ContinuationPrompt = " > ";
999 /// Used to signal that the user has invoked the `quit' statement.
1001 public static bool QuitRequested;
1003 public static Evaluator Evaluator;
1006 /// Shows all the variables defined so far.
1008 static public void ShowVars ()
1010 Output.Write (Evaluator.GetVars ());
1015 /// Displays the using statements in effect at this point.
1017 static public void ShowUsing ()
1019 Output.Write (Evaluator.GetUsing ());
1024 /// Times the execution of the given delegate
1026 static public TimeSpan Time (Action a)
1028 DateTime start = DateTime.Now;
1030 return DateTime.Now - start;
1034 /// Loads the assemblies from a package
1037 /// Loads the assemblies from a package. This is equivalent
1038 /// to passing the -pkg: command line flag to the C# compiler
1039 /// on the command line.
1041 static public void LoadPackage (string pkg)
1044 Error.WriteLine ("Invalid package specified");
1048 string pkgout = Driver.GetPackageFlags (pkg, null);
1050 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1051 Split (new Char [] { ' ', '\t'});
1053 foreach (string s in xargs){
1054 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
1055 string lib = s.Substring (s.IndexOf (':')+1);
1057 Evaluator.LoadAssembly (lib);
1064 /// Loads the assembly
1067 /// Loads the specified assembly and makes its types
1068 /// available to the evaluator. This is equivalent
1069 /// to passing the -pkg: command line flag to the C#
1070 /// compiler on the command line.
1072 static public void LoadAssembly (string assembly)
1074 Evaluator.LoadAssembly (assembly);
1077 static public void print (object obj)
1079 Output.WriteLine (obj);
1082 static public void print (string fmt, params object [] args)
1084 Output.WriteLine (fmt, args);
1088 /// Returns a list of available static methods.
1090 static public string help {
1092 return "Static methods:\n" +
1093 " Describe (object); - Describes the object's type\n" +
1094 " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" +
1095 " LoadAssembly (assembly); - Loads the given assembly (like -r:ASSEMBLY)\n" +
1096 " ShowVars (); - Shows defined local variables.\n" +
1097 " ShowUsing (); - Show active using declarations.\n" +
1098 " Prompt - The prompt used by the C# shell\n" +
1099 " ContinuationPrompt - The prompt for partial input\n" +
1100 " Time (() => { }); - Times the specified code\n" +
1101 " print (obj); - Shorthand for Console.WriteLine\n" +
1102 " quit; - You'll never believe it - this quits the repl!\n" +
1103 " help; - This help text\n";
1108 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1110 static public object quit {
1112 QuitRequested = true;
1114 // To avoid print null at the exit
1115 return typeof (Evaluator.QuitValue);
1120 /// Same as quit - useful in script scenerios
1122 static public void Quit () {
1123 QuitRequested = true;
1128 /// Describes an object or a type.
1131 /// This method will show a textual representation
1132 /// of the object's type. If the object is a
1133 /// System.Type it renders the type directly,
1134 /// otherwise it renders the type returned by
1135 /// invoking GetType on the object.
1137 static public string Describe (object x)
1142 var type = x as Type ?? x.GetType ();
1144 StringWriter sw = new StringWriter ();
1145 new Outline (type, sw, true, false, false).OutlineType ();
1146 return sw.ToString ();
1151 class InteractiveMethod : Method
1153 public InteractiveMethod(TypeDefinition parent, FullNamedExpression returnType, Modifiers mod, ParametersCompiled parameters)
1154 : base(parent, returnType, mod, new MemberName("Host"), parameters, null)
1158 public void ChangeToAsync ()
1160 ModFlags |= Modifiers.ASYNC;
1161 ModFlags &= ~Modifiers.UNSAFE;
1162 type_expr = new TypeExpression(Module.PredefinedTypes.Task.TypeSpec, Location);
1163 parameters = ParametersCompiled.EmptyReadOnlyParameters;
1166 public override string GetSignatureForError()
1168 return "InteractiveHost";
1172 class HoistedEvaluatorVariable : HoistedVariable
1174 public HoistedEvaluatorVariable (Field field)
1175 : base (null, field)
1179 protected override FieldExpr GetFieldExpression (EmitContext ec)
1181 return new FieldExpr (field, field.Location);
1186 /// A class used to assign values if the source expression is not void
1188 /// Used by the interactive shell to allow it to call this code to set
1189 /// the return value for an invocation.
1191 class OptionalAssign : SimpleAssign {
1192 public OptionalAssign (Expression s, Location loc)
1193 : base (null, s, loc)
1197 public override Location StartLocation {
1199 return Location.Null;
1203 protected override Expression DoResolve (ResolveContext ec)
1205 Expression clone = source.Clone (new CloneContext ());
1207 clone = clone.Resolve (ec);
1212 // A useful feature for the REPL: if we can resolve the expression
1213 // as a type, Describe the type;
1215 if (ec.Module.Evaluator.DescribeTypeExpressions && !(ec.CurrentAnonymousMethod is AsyncInitializer)) {
1216 var old_printer = ec.Report.SetPrinter (new SessionReportPrinter ());
1219 // Note: clone context cannot be shared otherwise block mapping would leak
1220 tclone = source.Clone (new CloneContext ());
1221 tclone = tclone.Resolve (ec, ResolveFlags.Type);
1222 if (ec.Report.Errors > 0)
1225 ec.Report.SetPrinter (old_printer);
1228 if (tclone is TypeExpr) {
1229 Arguments args = new Arguments (1);
1230 args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1231 return new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1235 // This means its really a statement.
1236 if (clone.Type.Kind == MemberKind.Void || clone is DynamicInvocation || clone is Assign) {
1242 var host = (Method) ec.MemberContext.CurrentMemberDefinition;
1244 if (host.ParameterInfo.IsEmpty) {
1245 eclass = ExprClass.Value;
1246 type = InternalType.FakeInternalType;
1250 target = new SimpleName (host.ParameterInfo[0].Name, Location);
1252 return base.DoResolve (ec);
1255 public override void EmitStatement(EmitContext ec)
1257 if (target == null) {
1262 base.EmitStatement(ec);
1268 List<Action> undo_actions;
1270 public void AddTypeContainer (TypeContainer current_container, TypeDefinition tc)
1272 if (current_container == tc){
1273 Console.Error.WriteLine ("Internal error: inserting container into itself");
1277 if (undo_actions == null)
1278 undo_actions = new List<Action> ();
1280 if (current_container.Containers != null)
1282 var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
1283 if (existing != null) {
1284 current_container.RemoveContainer (existing);
1285 undo_actions.Add (() => current_container.AddTypeContainer (existing));
1289 undo_actions.Add (() => current_container.RemoveContainer (tc));
1292 public void ExecuteUndo ()
1294 if (undo_actions == null)
1297 foreach (var p in undo_actions){
1301 undo_actions = null;
1305 static class ListenerProxy
1307 static readonly Dictionary<int, ValueModificationHandler> listeners = new Dictionary<int, ValueModificationHandler> ();
1311 public static int Register (ValueModificationHandler listener)
1315 listeners.Add (id, listener);
1320 public static void Unregister (int listenerId)
1323 listeners.Remove (listenerId);
1327 public static void ValueChanged (object value, int row, int col, string name, int listenerId)
1329 ValueModificationHandler action;
1331 if (!listeners.TryGetValue (listenerId, out action))
1335 action (name, row, col, value);