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;
28 /// Evaluator: provides an API to evaluate C# statements and
29 /// expressions dynamically.
32 /// This class exposes static methods to evaluate expressions in the
35 /// To initialize the evaluator with a number of compiler
36 /// options call the Init(string[]args) method with a set of
37 /// command line options that the compiler recognizes.
39 /// To interrupt execution of a statement, you can invoke the
40 /// Evaluator.Interrupt method.
42 public class Evaluator {
45 // Parse silently, do not output any error messages
48 // Report errors during parse
51 // Auto-complete, means that the tokenizer will start producing
52 // GETCOMPLETIONS tokens when it reaches a certain point.
56 static object evaluator_lock = new object ();
57 static volatile bool invoking;
62 static Thread invoke_thread;
64 readonly Dictionary<string, Tuple<FieldSpec, FieldInfo>> fields;
70 readonly CompilerContext ctx;
71 readonly ModuleContainer module;
72 readonly ReflectionImporter importer;
73 readonly CompilationSourceFile source_file;
75 public Evaluator (CompilerContext ctx)
79 module = new ModuleContainer (ctx);
80 module.Evaluator = this;
82 source_file = new CompilationSourceFile (module, null);
83 module.AddTypeContainer (source_file);
85 startup_files = ctx.SourceFiles.Count;
87 // FIXME: Importer needs this assembly for internalsvisibleto
88 module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
89 importer = new ReflectionImporter (module, ctx.BuiltinTypes);
91 InteractiveBaseClass = typeof (InteractiveBase);
92 fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
97 var loader = new DynamicLoader (importer, ctx);
99 CompilerCallableEntryPoint.Reset ();
100 RootContext.ToplevelTypes = module;
102 //var startup_files = new List<string> ();
103 //foreach (CompilationUnit file in Location.SourceFiles)
104 // startup_files.Add (file.Path);
106 loader.LoadReferences (module);
107 ctx.BuiltinTypes.CheckDefinitions (module);
108 module.InitializePredefinedTypes ();
113 void ParseStartupFiles ()
115 Driver d = new Driver (ctx);
117 Location.Initialize (ctx.SourceFiles);
119 var parser_session = new ParserSession ();
120 for (int i = 0; i < startup_files; ++i) {
121 var sf = ctx.SourceFiles [i];
122 d.Parse (sf, module, parser_session, ctx.Report);
128 CompilerCallableEntryPoint.PartialReset ();
131 Location.Initialize (ctx.SourceFiles);
135 /// When set evaluator will automatically wait on Task of async methods. When not
136 /// set it's called responsibility to handle Task execution
138 public bool WaitOnTask { get; set; }
141 /// If true, turns type expressions into valid expressions
142 /// and calls the describe method on it
144 public bool DescribeTypeExpressions;
147 /// Whether the evaluator will use terse syntax, and the semicolons at the end are optional
149 public bool Terse = true;
152 /// The base class for the classes that host the user generated code
156 /// This is the base class that will host the code
157 /// executed by the Evaluator. By default
158 /// this is the Mono.CSharp.InteractiveBase class
159 /// which is useful for interactive use.
161 /// By changing this property you can control the
162 /// base class and the static members that are
163 /// available to your evaluated code.
165 public Type InteractiveBaseClass {
172 if (value != null && typeof (InteractiveBase).IsAssignableFrom (value))
173 InteractiveBase.Evaluator = this;
178 /// Interrupts the evaluation of an expression executing in Evaluate.
181 /// Use this method to interrupt long-running invocations.
183 public void Interrupt ()
185 if (!inited || !invoking)
188 if (invoke_thread != null)
189 invoke_thread.Abort ();
193 /// Compiles the input string and returns a delegate that represents the compiled code.
197 /// Compiles the input string as a C# expression or
198 /// statement, unlike the Evaluate method, the
199 /// resulting delegate can be invoked multiple times
200 /// without incurring in the compilation overhead.
202 /// If the return value of this function is null,
203 /// this indicates that the parsing was complete.
204 /// If the return value is a string it indicates
205 /// that the input string was partial and that the
206 /// invoking code should provide more code before
207 /// the code can be successfully compiled.
209 /// If you know that you will always get full expressions or
210 /// statements and do not care about partial input, you can use
211 /// the other Compile overload.
213 /// On success, in addition to returning null, the
214 /// compiled parameter will be set to the delegate
215 /// that can be invoked to execute the code.
218 public string Compile (string input, out CompiledMethod compiled)
220 if (input == null || input.Length == 0){
225 lock (evaluator_lock){
228 ParseStartupFiles ();
230 ctx.Report.Printer.Reset ();
234 CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
236 // Terse mode, try to provide the trailing semicolon automatically.
237 if (parser == null && Terse && partial_input){
240 // check if the source would compile with a block, if so, we should not
241 // add the semicolon.
242 var needs_block = ParseString (ParseMode.Silent, input + "{}", out ignore) != null;
244 parser = ParseString (ParseMode.Silent, input + ";", out ignore);
251 ParseString (ParseMode.ReportErrors, input, out partial_input);
255 Class parser_result = parser.InteractiveResult;
256 compiled = CompileBlock (parser_result, parser.undo, ctx.Report);
262 /// Compiles the input string and returns a delegate that represents the compiled code.
266 /// Compiles the input string as a C# expression or
267 /// statement, unlike the Evaluate method, the
268 /// resulting delegate can be invoked multiple times
269 /// without incurring in the compilation overhead.
271 /// This method can only deal with fully formed input
272 /// strings and does not provide a completion mechanism.
273 /// If you must deal with partial input (for example for
274 /// interactive use) use the other overload.
276 /// On success, a delegate is returned that can be used
277 /// to invoke the method.
280 public CompiledMethod Compile (string input)
282 CompiledMethod compiled;
284 // Ignore partial inputs
285 if (Compile (input, out compiled) != null){
286 // Error, the input was partial.
290 // Either null (on error) or the compiled method.
295 /// Evaluates and expression or statement and returns any result values.
298 /// Evaluates the input string as a C# expression or
299 /// statement. If the input string is an expression
300 /// the result will be stored in the result variable
301 /// and the result_set variable will be set to true.
303 /// It is necessary to use the result/result_set
304 /// pair to identify when a result was set (for
305 /// example, execution of user-provided input can be
306 /// an expression, a statement or others, and
307 /// result_set would only be set if the input was an
310 /// If the return value of this function is null,
311 /// this indicates that the parsing was complete.
312 /// If the return value is a string, it indicates
313 /// that the input is partial and that the user
314 /// should provide an updated string.
316 public string Evaluate (string input, out object result, out bool result_set)
318 CompiledMethod compiled;
323 input = Compile (input, out compiled);
327 if (compiled == null)
331 // The code execution does not need to keep the compiler lock
333 object retval = typeof (QuitValue);
336 invoke_thread = System.Threading.Thread.CurrentThread;
338 compiled (ref retval);
339 } catch (ThreadAbortException e){
340 Thread.ResetAbort ();
341 Console.WriteLine ("Interrupted!\n{0}", e);
347 // We use a reference to a compiler type, in this case
348 // Driver as a flag to indicate that this was a statement
350 if (!ReferenceEquals (retval, typeof (QuitValue))) {
358 public string [] GetCompletions (string input, out string prefix)
361 if (input == null || input.Length == 0)
364 lock (evaluator_lock){
369 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
374 Class host = parser.InteractiveResult;
376 var base_class_imported = importer.ImportType (base_class);
377 var baseclass_list = new List<FullNamedExpression> (1) {
378 new TypeExpression (base_class_imported, host.Location)
380 host.SetBaseTypes (baseclass_list);
383 var access = AssemblyBuilderAccess.RunAndCollect;
385 var access = AssemblyBuilderAccess.Run;
387 var a = new AssemblyDefinitionDynamic (module, "completions");
388 a.Create (AppDomain.CurrentDomain, access);
389 module.SetDeclaringAssembly (a);
391 // Need to setup MemberCache
392 host.CreateContainer ();
393 // Need to setup base type
394 host.DefineContainer ();
396 var method = host.Members[0] as Method;
397 BlockContext bc = new BlockContext (method, method.Block, ctx.BuiltinTypes.Void);
400 method.Block.Resolve (bc, method);
401 } catch (CompletionResult cr) {
402 prefix = cr.BaseText;
410 /// Executes the given expression or statement.
413 /// Executes the provided statement, returns true
414 /// on success, false on parsing errors. Exceptions
415 /// might be thrown by the called code.
417 public bool Run (string statement)
422 return Evaluate (statement, out result, out result_set) == null;
426 /// Evaluates and expression or statement and returns the result.
429 /// Evaluates the input string as a C# expression or
430 /// statement and returns the value.
432 /// This method will throw an exception if there is a syntax error,
433 /// of if the provided input is not an expression but a statement.
435 public object Evaluate (string input)
440 string r = Evaluate (input, out result, out result_set);
443 throw new ArgumentException ("Syntax error on input: partial input");
445 if (result_set == false)
446 throw new ArgumentException ("The expression failed to resolve");
453 StatementOrExpression,
459 // Deambiguates the input string to determine if we
460 // want to process a statement or if we want to
461 // process a compilation unit.
463 // This is done using a top-down predictive parser,
464 // since the yacc/jay parser can not deambiguage this
465 // without more than one lookahead token. There are very
468 InputKind ToplevelOrStatement (SeekableStreamReader seekable)
470 Tokenizer tokenizer = new Tokenizer (seekable, source_file, new ParserSession (), ctx.Report);
472 // Prefer contextual block keywords over identifiers
473 tokenizer.parsing_block++;
475 int t = tokenizer.token ();
478 return InputKind.EOF;
480 // These are toplevels
482 case Token.OPEN_BRACKET:
486 case Token.INTERFACE:
488 case Token.NAMESPACE:
490 case Token.PROTECTED:
495 return InputKind.CompilationUnit;
497 // Definitely expression
514 return InputKind.StatementOrExpression;
516 // These need deambiguation help
518 t = tokenizer.token ();
520 return InputKind.EOF;
522 if (t == Token.IDENTIFIER)
523 return InputKind.CompilationUnit;
524 return InputKind.StatementOrExpression;
527 // Distinguish between:
528 // delegate opt_anonymous_method_signature block
531 t = tokenizer.token ();
533 return InputKind.EOF;
534 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
535 return InputKind.StatementOrExpression;
536 return InputKind.CompilationUnit;
538 // Distinguih between:
540 // unsafe as modifier of a type declaration
542 t = tokenizer.token ();
544 return InputKind.EOF;
545 if (t == Token.OPEN_PARENS)
546 return InputKind.StatementOrExpression;
547 return InputKind.CompilationUnit;
549 // These are errors: we list explicitly what we had
550 // from the grammar, ERROR and then everything else
555 return InputKind.Error;
557 // This catches everything else allowed by
558 // expressions. We could add one-by-one use cases
561 return InputKind.StatementOrExpression;
566 // Parses the string @input and returns a CSharpParser if succeeful.
568 // if @silent is set to true then no errors are
569 // reported to the user. This is used to do various calls to the
570 // parser and check if the expression is parsable.
572 // @partial_input: if @silent is true, then it returns whether the
573 // parsed expression was partial, and more data is needed
575 CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
577 partial_input = false;
580 var enc = ctx.Settings.Encoding;
581 var s = new MemoryStream (enc.GetBytes (input));
582 SeekableStreamReader seekable = new SeekableStreamReader (s, enc);
584 InputKind kind = ToplevelOrStatement (seekable);
585 if (kind == InputKind.Error){
586 if (mode == ParseMode.ReportErrors)
587 ctx.Report.Error (-25, "Detection Parsing Error");
588 partial_input = false;
592 if (kind == InputKind.EOF){
593 if (mode == ParseMode.ReportErrors)
594 Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
595 partial_input = true;
599 seekable.Position = 0;
601 source_file.DeclarationFound = false;
602 CSharpParser parser = new CSharpParser (seekable, source_file, new ParserSession ());
604 if (kind == InputKind.StatementOrExpression){
605 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
606 parser.Lexer.parsing_block++;
607 ctx.Settings.StatementMode = true;
609 parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
610 ctx.Settings.StatementMode = false;
613 if (mode == ParseMode.GetCompletions)
614 parser.Lexer.CompleteOnEOF = true;
616 ReportPrinter old_printer = null;
617 if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions))
618 old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null));
623 if (ctx.Report.Errors != 0){
624 if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
625 partial_input = true;
627 if (parser.undo != null)
628 parser.undo.ExecuteUndo ();
633 if (old_printer != null)
634 ctx.Report.SetPrinter (old_printer);
639 CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
642 throw new NotSupportedException ();
644 string current_debug_name = "eval-" + count + ".dll";
647 AssemblyDefinitionDynamic assembly;
648 AssemblyBuilderAccess access;
650 if (Environment.GetEnvironmentVariable ("SAVE") != null) {
651 access = AssemblyBuilderAccess.RunAndSave;
652 assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name);
653 assembly.Importer = importer;
656 access = AssemblyBuilderAccess.RunAndCollect;
658 access = AssemblyBuilderAccess.Run;
660 assembly = new AssemblyDefinitionDynamic (module, current_debug_name);
663 assembly.Create (AppDomain.CurrentDomain, access);
665 Method expression_method;
667 var base_class_imported = importer.ImportType (base_class);
668 var baseclass_list = new List<FullNamedExpression> (1) {
669 new TypeExpression (base_class_imported, host.Location)
672 host.SetBaseTypes (baseclass_list);
674 expression_method = (Method) host.Members[0];
676 if ((expression_method.ModFlags & Modifiers.ASYNC) != 0) {
678 // Host method is async. When WaitOnTask is set we wrap it with wait
680 // void AsyncWait (ref object $retval) {
682 // ((Task)$retval).Wait(); // When WaitOnTask is set
685 var p = new ParametersCompiled (
686 new Parameter (new TypeExpression (module.Compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null)
689 var method = new Method(host, new TypeExpression(module.Compiler.BuiltinTypes.Void, Location.Null),
690 Modifiers.PUBLIC | Modifiers.STATIC, new MemberName("AsyncWait"), p, null);
692 method.Block = new ToplevelBlock(method.Compiler, p, Location.Null);
693 method.Block.AddStatement(new StatementExpression (new SimpleAssign(
694 new SimpleName(p [0].Name, Location.Null),
695 new Invocation(new SimpleName(expression_method.MemberName.Name, Location.Null), new Arguments(0)),
696 Location.Null), Location.Null));
699 var task = new Cast (expression_method.TypeExpression, new SimpleName (p [0].Name, Location.Null), Location.Null);
701 method.Block.AddStatement (new StatementExpression (new Invocation (
702 new MemberAccess (task, "Wait", Location.Null),
703 new Arguments (0)), Location.Null));
706 host.AddMember(method);
708 expression_method = method;
711 host.CreateContainer();
712 host.DefineContainer();
716 expression_method = null;
719 module.CreateContainer ();
721 // Disable module and source file re-definition checks
722 module.EnableRedefinition ();
723 source_file.EnableRedefinition ();
727 if (Report.Errors != 0){
736 host.EmitContainer ();
739 module.EmitContainer ();
740 if (Report.Errors != 0){
746 module.CloseContainer ();
748 host.CloseContainer ();
750 if (access == AssemblyBuilderAccess.RunAndSave)
757 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
758 // work from MethodBuilders. Retarded, I know.
760 var tt = assembly.Builder.GetType (host.TypeBuilder.Name);
761 var mi = tt.GetMethod (expression_method.MemberName.Name);
764 // We need to then go from FieldBuilder to FieldInfo
765 // or reflection gets confused (it basically gets confused, and variables override each
768 foreach (var member in host.Members) {
769 var field = member as Field;
773 var fi = tt.GetField (field.Name);
775 Tuple<FieldSpec, FieldInfo> old;
777 // If a previous value was set, nullify it, so that we do
779 if (fields.TryGetValue (field.Name, out old)) {
780 if (old.Item1.MemberType.IsStruct) {
782 // TODO: Clear fields for structs
786 old.Item2.SetValue (null, null);
792 fields[field.Name] = Tuple.Create (field.Spec, fi);
795 return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
800 /// A sentinel value used to indicate that no value was
801 /// was set by the compiled function. This is used to
802 /// differentiate between a function not returning a
805 internal static class QuitValue { }
807 internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
809 Tuple<FieldSpec, FieldInfo> fi;
810 fields.TryGetValue (name, out fi);
814 static string Quote (string s)
816 if (s.IndexOf ('"') != -1)
817 s = s.Replace ("\"", "\\\"");
819 return "\"" + s + "\"";
822 public string GetUsing ()
824 StringBuilder sb = new StringBuilder ();
826 //foreach (object x in ns.using_alias_list)
827 // sb.AppendFormat ("using {0};\n", x);
829 foreach (var ue in source_file.Usings) {
830 sb.AppendFormat ("using {0};", ue.ToString ());
831 sb.Append (Environment.NewLine);
834 return sb.ToString ();
837 internal List<string> GetUsingList ()
839 var res = new List<string> ();
841 foreach (var ue in source_file.Usings) {
842 if (ue.Alias != null || ue.ResolvedExpression == null)
845 res.Add (ue.NamespaceExpression.Name);
851 internal string [] GetVarNames ()
853 lock (evaluator_lock){
854 return new List<string> (fields.Keys).ToArray ();
858 public string GetVars ()
860 lock (evaluator_lock){
861 StringBuilder sb = new StringBuilder ();
863 foreach (var de in fields){
864 var fi = LookupField (de.Key);
867 value = fi.Item2.GetValue (null);
869 value = Quote ((string)value);
871 value = "<error reading value>";
874 sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
878 return sb.ToString ();
883 /// Loads the given assembly and exposes the API to the user.
885 public void LoadAssembly (string file)
887 var loader = new DynamicLoader (importer, ctx);
888 var assembly = loader.LoadAssemblyFile (file, false);
889 if (assembly == null)
892 lock (evaluator_lock){
893 importer.ImportAssembly (assembly, module.GlobalRootNamespace);
898 /// Exposes the API of the given assembly to the Evaluator
900 public void ReferenceAssembly (Assembly a)
902 lock (evaluator_lock){
903 importer.ImportAssembly (a, module.GlobalRootNamespace);
910 /// A delegate that can be used to invoke the
911 /// compiled expression or statement.
914 /// Since the Compile methods will compile
915 /// statements and expressions into the same
916 /// delegate, you can tell if a value was returned
917 /// by checking whether the returned value is of type
921 public delegate void CompiledMethod (ref object retvalue);
924 /// The default base class for every interaction line
927 /// The expressions and statements behave as if they were
928 /// a static method of this class. The InteractiveBase class
929 /// contains a number of useful methods, but can be overwritten
930 /// by setting the InteractiveBaseType property in the Evaluator
932 public class InteractiveBase {
934 /// Determines where the standard output of methods in this class will go.
936 public static TextWriter Output = Console.Out;
939 /// Determines where the standard error of methods in this class will go.
941 public static TextWriter Error = Console.Error;
944 /// The primary prompt used for interactive use.
946 public static string Prompt = "csharp> ";
949 /// The secondary prompt used for interactive use (used when
950 /// an expression is incomplete).
952 public static string ContinuationPrompt = " > ";
955 /// Used to signal that the user has invoked the `quit' statement.
957 public static bool QuitRequested;
959 public static Evaluator Evaluator;
962 /// Shows all the variables defined so far.
964 static public void ShowVars ()
966 Output.Write (Evaluator.GetVars ());
971 /// Displays the using statements in effect at this point.
973 static public void ShowUsing ()
975 Output.Write (Evaluator.GetUsing ());
980 /// Times the execution of the given delegate
982 static public TimeSpan Time (Action a)
984 DateTime start = DateTime.Now;
986 return DateTime.Now - start;
990 /// Loads the assemblies from a package
993 /// Loads the assemblies from a package. This is equivalent
994 /// to passing the -pkg: command line flag to the C# compiler
995 /// on the command line.
997 static public void LoadPackage (string pkg)
1000 Error.WriteLine ("Invalid package specified");
1004 string pkgout = Driver.GetPackageFlags (pkg, null);
1006 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1007 Split (new Char [] { ' ', '\t'});
1009 foreach (string s in xargs){
1010 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
1011 string lib = s.Substring (s.IndexOf (':')+1);
1013 Evaluator.LoadAssembly (lib);
1020 /// Loads the assembly
1023 /// Loads the specified assembly and makes its types
1024 /// available to the evaluator. This is equivalent
1025 /// to passing the -pkg: command line flag to the C#
1026 /// compiler on the command line.
1028 static public void LoadAssembly (string assembly)
1030 Evaluator.LoadAssembly (assembly);
1033 static public void print (object obj)
1035 Output.WriteLine (obj);
1038 static public void print (string fmt, params object [] args)
1040 Output.WriteLine (fmt, args);
1044 /// Returns a list of available static methods.
1046 static public string help {
1048 return "Static methods:\n" +
1049 " Describe (object); - Describes the object's type\n" +
1050 " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" +
1051 " LoadAssembly (assembly); - Loads the given assembly (like -r:ASSEMBLY)\n" +
1052 " ShowVars (); - Shows defined local variables.\n" +
1053 " ShowUsing (); - Show active using declarations.\n" +
1054 " Prompt - The prompt used by the C# shell\n" +
1055 " ContinuationPrompt - The prompt for partial input\n" +
1056 " Time (() => { }); - Times the specified code\n" +
1057 " print (obj); - Shorthand for Console.WriteLine\n" +
1058 " quit; - You'll never believe it - this quits the repl!\n" +
1059 " help; - This help text\n";
1064 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1066 static public object quit {
1068 QuitRequested = true;
1070 // To avoid print null at the exit
1071 return typeof (Evaluator.QuitValue);
1076 /// Same as quit - useful in script scenerios
1078 static public void Quit () {
1079 QuitRequested = true;
1084 /// Describes an object or a type.
1087 /// This method will show a textual representation
1088 /// of the object's type. If the object is a
1089 /// System.Type it renders the type directly,
1090 /// otherwise it renders the type returned by
1091 /// invoking GetType on the object.
1093 static public string Describe (object x)
1098 var type = x as Type ?? x.GetType ();
1100 StringWriter sw = new StringWriter ();
1101 new Outline (type, sw, true, false, false).OutlineType ();
1102 return sw.ToString ();
1107 class InteractiveMethod : Method
1109 public InteractiveMethod(TypeDefinition parent, FullNamedExpression returnType, Modifiers mod, ParametersCompiled parameters)
1110 : base(parent, returnType, mod, new MemberName("Host"), parameters, null)
1114 public void ChangeToAsync ()
1116 ModFlags |= Modifiers.ASYNC;
1117 ModFlags &= ~Modifiers.UNSAFE;
1118 type_expr = new TypeExpression(Module.PredefinedTypes.Task.TypeSpec, Location);
1119 parameters = ParametersCompiled.EmptyReadOnlyParameters;
1122 public override string GetSignatureForError()
1124 return "InteractiveHost";
1128 class HoistedEvaluatorVariable : HoistedVariable
1130 public HoistedEvaluatorVariable (Field field)
1131 : base (null, field)
1135 protected override FieldExpr GetFieldExpression (EmitContext ec)
1137 return new FieldExpr (field, field.Location);
1142 /// A class used to assign values if the source expression is not void
1144 /// Used by the interactive shell to allow it to call this code to set
1145 /// the return value for an invocation.
1147 class OptionalAssign : SimpleAssign {
1148 public OptionalAssign (Expression s, Location loc)
1149 : base (null, s, loc)
1153 public override Location StartLocation {
1155 return Location.Null;
1159 protected override Expression DoResolve (ResolveContext ec)
1161 Expression clone = source.Clone (new CloneContext ());
1163 clone = clone.Resolve (ec);
1168 // A useful feature for the REPL: if we can resolve the expression
1169 // as a type, Describe the type;
1171 if (ec.Module.Evaluator.DescribeTypeExpressions && !(ec.CurrentAnonymousMethod is AsyncInitializer)) {
1172 var old_printer = ec.Report.SetPrinter (new SessionReportPrinter ());
1175 // Note: clone context cannot be shared otherwise block mapping would leak
1176 tclone = source.Clone (new CloneContext ());
1177 tclone = tclone.Resolve (ec, ResolveFlags.Type);
1178 if (ec.Report.Errors > 0)
1181 ec.Report.SetPrinter (old_printer);
1184 if (tclone is TypeExpr) {
1185 Arguments args = new Arguments (1);
1186 args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1187 return new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1191 // This means its really a statement.
1192 if (clone.Type.Kind == MemberKind.Void || clone is DynamicInvocation || clone is Assign) {
1198 var host = (Method) ec.MemberContext.CurrentMemberDefinition;
1200 if (host.ParameterInfo.IsEmpty) {
1201 eclass = ExprClass.Value;
1202 type = InternalType.FakeInternalType;
1206 target = new SimpleName (host.ParameterInfo[0].Name, Location);
1208 return base.DoResolve (ec);
1211 public override void EmitStatement(EmitContext ec)
1213 if (target == null) {
1218 base.EmitStatement(ec);
1224 List<Action> undo_actions;
1226 public void AddTypeContainer (TypeContainer current_container, TypeDefinition tc)
1228 if (current_container == tc){
1229 Console.Error.WriteLine ("Internal error: inserting container into itself");
1233 if (undo_actions == null)
1234 undo_actions = new List<Action> ();
1236 var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
1237 if (existing != null) {
1238 current_container.RemoveContainer (existing);
1239 undo_actions.Add (() => current_container.AddTypeContainer (existing));
1242 undo_actions.Add (() => current_container.RemoveContainer (tc));
1245 public void ExecuteUndo ()
1247 if (undo_actions == null)
1250 foreach (var p in undo_actions){
1254 undo_actions = null;