2 // eval.cs: Evaluation and Hosting API for the C# compiler
5 // Miguel de Icaza (miguel@gnome.org)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
14 using System.Threading;
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
25 /// Evaluator: provides an API to evaluate C# statements and
26 /// expressions dynamically.
29 /// This class exposes static methods to evaluate expressions in the
32 /// To initialize the evaluator with a number of compiler
33 /// options call the Init(string[]args) method with a set of
34 /// command line options that the compiler recognizes.
36 /// To interrupt execution of a statement, you can invoke the
37 /// Evaluator.Interrupt method.
39 public class Evaluator {
42 // Parse silently, do not output any error messages
45 // Report errors during parse
48 // Auto-complete, means that the tokenizer will start producing
49 // GETCOMPLETIONS tokens when it reaches a certain point.
53 static object evaluator_lock = new object ();
55 static string current_debug_name;
57 static Thread invoke_thread;
59 static List<NamespaceEntry.UsingAliasEntry> using_alias_list = new List<NamespaceEntry.UsingAliasEntry> ();
60 internal static List<NamespaceEntry.UsingEntry> using_list = new List<NamespaceEntry.UsingEntry> ();
61 static Dictionary<string, Tuple<FieldSpec, FieldInfo>> fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
63 static TypeSpec interactive_base_class;
67 static CompilerContext ctx;
68 static DynamicLoader loader;
70 public static TextWriter MessageOutput = Console.Out;
73 /// Optional initialization for the Evaluator.
76 /// Initializes the Evaluator with the command line options
77 /// that would be processed by the command line compiler. Only
78 /// the first call to Init will work, any future invocations are
81 /// You can safely avoid calling this method if your application
82 /// does not need any of the features exposed by the command line
85 public static void Init (string [] args)
87 InitAndGetStartupFiles (args);
90 internal static ReportPrinter SetPrinter (ReportPrinter report_printer)
92 return ctx.Report.SetPrinter (report_printer);
96 /// Optional initialization for the Evaluator.
99 /// Initializes the Evaluator with the command line
100 /// options that would be processed by the command
101 /// line compiler. Only the first call to
102 /// InitAndGetStartupFiles or Init will work, any future
103 /// invocations are ignored.
105 /// You can safely avoid calling this method if your application
106 /// does not need any of the features exposed by the command line
109 /// This method return an array of strings that contains any
110 /// files that were specified in `args'.
112 public static string [] InitAndGetStartupFiles (string [] args)
114 lock (evaluator_lock){
116 return new string [0];
118 driver = Driver.Create (args, false, new ConsoleReportPrinter ());
120 throw new Exception ("Failed to create compiler driver with the given arguments");
124 CompilerCallableEntryPoint.Reset ();
125 RootContext.ToplevelTypes = new ModuleContainer (ctx);
127 var startup_files = new List<string> ();
128 foreach (CompilationUnit file in Location.SourceFiles)
129 startup_files.Add (file.Path);
131 CompilerCallableEntryPoint.PartialReset ();
133 var importer = new ReflectionImporter (ctx.BuildinTypes);
134 loader = new DynamicLoader (importer, ctx);
136 RootContext.ToplevelTypes.SetDeclaringAssembly (new AssemblyDefinitionDynamic (RootContext.ToplevelTypes, "temp"));
138 loader.LoadReferences (RootContext.ToplevelTypes);
139 ctx.BuildinTypes.CheckDefinitions (RootContext.ToplevelTypes);
140 RootContext.ToplevelTypes.InitializePredefinedTypes ();
142 RootContext.EvalMode = true;
145 return startup_files.ToArray ();
151 Init (new string [0]);
156 CompilerCallableEntryPoint.PartialReset ();
158 Location.AddFile (null, "{interactive}");
159 Location.Initialize ();
161 current_debug_name = "interactive" + (count++) + ".dll";
165 /// The base class for the classes that host the user generated code
169 /// This is the base class that will host the code
170 /// executed by the Evaluator. By default
171 /// this is the Mono.CSharp.InteractiveBase class
172 /// which is useful for interactive use.
174 /// By changing this property you can control the
175 /// base class and the static members that are
176 /// available to your evaluated code.
178 static public TypeSpec InteractiveBaseClass {
180 if (interactive_base_class != null)
181 return interactive_base_class;
183 return loader.Importer.ImportType (typeof (InteractiveBase));
187 public static void SetInteractiveBaseClass (Type type)
190 throw new ArgumentNullException ();
192 lock (evaluator_lock)
193 interactive_base_class = loader.Importer.ImportType (type);
197 /// Interrupts the evaluation of an expression executing in Evaluate.
200 /// Use this method to interrupt long-running invocations.
202 public static void Interrupt ()
204 if (!inited || !invoking)
207 if (invoke_thread != null)
208 invoke_thread.Abort ();
212 /// Compiles the input string and returns a delegate that represents the compiled code.
216 /// Compiles the input string as a C# expression or
217 /// statement, unlike the Evaluate method, the
218 /// resulting delegate can be invoked multiple times
219 /// without incurring in the compilation overhead.
221 /// If the return value of this function is null,
222 /// this indicates that the parsing was complete.
223 /// If the return value is a string it indicates
224 /// that the input string was partial and that the
225 /// invoking code should provide more code before
226 /// the code can be successfully compiled.
228 /// If you know that you will always get full expressions or
229 /// statements and do not care about partial input, you can use
230 /// the other Compile overload.
232 /// On success, in addition to returning null, the
233 /// compiled parameter will be set to the delegate
234 /// that can be invoked to execute the code.
237 static public string Compile (string input, out CompiledMethod compiled)
239 if (input == null || input.Length == 0){
244 lock (evaluator_lock){
248 ctx.Report.Printer.Reset ();
250 // RootContext.ToplevelTypes = new ModuleContainer (ctx);
253 CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
259 ParseString (ParseMode.ReportErrors, input, out partial_input);
263 object parser_result = parser.InteractiveResult;
265 if (!(parser_result is Class)){
266 int errors = ctx.Report.Errors;
268 NamespaceEntry.VerifyAllUsing ();
269 if (errors == ctx.Report.Errors)
270 parser.CurrentNamespace.Extract (using_alias_list, using_list);
274 throw new NotSupportedException ();
276 compiled = CompileBlock (parser_result as Class, parser.undo, ctx.Report);
283 /// Compiles the input string and returns a delegate that represents the compiled code.
287 /// Compiles the input string as a C# expression or
288 /// statement, unlike the Evaluate method, the
289 /// resulting delegate can be invoked multiple times
290 /// without incurring in the compilation overhead.
292 /// This method can only deal with fully formed input
293 /// strings and does not provide a completion mechanism.
294 /// If you must deal with partial input (for example for
295 /// interactive use) use the other overload.
297 /// On success, a delegate is returned that can be used
298 /// to invoke the method.
301 static public CompiledMethod Compile (string input)
303 CompiledMethod compiled;
305 // Ignore partial inputs
306 if (Compile (input, out compiled) != null){
307 // Error, the input was partial.
311 // Either null (on error) or the compiled method.
316 // Todo: Should we handle errors, or expect the calling code to setup
317 // the recording themselves?
321 /// Evaluates and expression or statement and returns any result values.
324 /// Evaluates the input string as a C# expression or
325 /// statement. If the input string is an expression
326 /// the result will be stored in the result variable
327 /// and the result_set variable will be set to true.
329 /// It is necessary to use the result/result_set
330 /// pair to identify when a result was set (for
331 /// example, execution of user-provided input can be
332 /// an expression, a statement or others, and
333 /// result_set would only be set if the input was an
336 /// If the return value of this function is null,
337 /// this indicates that the parsing was complete.
338 /// If the return value is a string, it indicates
339 /// that the input is partial and that the user
340 /// should provide an updated string.
342 public static string Evaluate (string input, out object result, out bool result_set)
344 CompiledMethod compiled;
349 input = Compile (input, out compiled);
353 if (compiled == null)
357 // The code execution does not need to keep the compiler lock
359 object retval = typeof (NoValueSet);
362 invoke_thread = System.Threading.Thread.CurrentThread;
364 compiled (ref retval);
365 } catch (ThreadAbortException e){
366 Thread.ResetAbort ();
367 Console.WriteLine ("Interrupted!\n{0}", e);
373 // We use a reference to a compiler type, in this case
374 // Driver as a flag to indicate that this was a statement
376 if (retval != typeof (NoValueSet)){
384 public static string [] GetCompletions (string input, out string prefix)
387 if (input == null || input.Length == 0)
390 lock (evaluator_lock){
395 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
397 if (CSharpParser.yacc_verbose_flag != 0)
398 Console.WriteLine ("DEBUG: No completions available");
402 Class parser_result = parser.InteractiveResult as Class;
404 if (parser_result == null){
405 if (CSharpParser.yacc_verbose_flag != 0)
406 Console.WriteLine ("Do not know how to cope with !Class yet");
411 var a = new AssemblyDefinitionDynamic (RootContext.ToplevelTypes, "temp");
412 a.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Run);
413 RootContext.ToplevelTypes.SetDeclaringAssembly (a);
414 RootContext.ToplevelTypes.Define ();
415 if (ctx.Report.Errors != 0)
418 MethodOrOperator method = null;
419 foreach (MemberCore member in parser_result.Methods){
420 if (member.Name != "Host")
423 method = (MethodOrOperator) member;
427 throw new InternalErrorException ("did not find the the Host method");
429 BlockContext bc = new BlockContext (method, method.Block, method.ReturnType);
432 method.Block.Resolve (null, bc, method);
433 } catch (CompletionResult cr){
434 prefix = cr.BaseText;
438 parser.undo.ExecuteUndo ();
446 /// Executes the given expression or statement.
449 /// Executes the provided statement, returns true
450 /// on success, false on parsing errors. Exceptions
451 /// might be thrown by the called code.
453 public static bool Run (string statement)
461 bool ok = Evaluate (statement, out result, out result_set) == null;
467 /// Evaluates and expression or statement and returns the result.
470 /// Evaluates the input string as a C# expression or
471 /// statement and returns the value.
473 /// This method will throw an exception if there is a syntax error,
474 /// of if the provided input is not an expression but a statement.
476 public static object Evaluate (string input)
481 string r = Evaluate (input, out result, out result_set);
484 throw new ArgumentException ("Syntax error on input: partial input");
486 if (result_set == false)
487 throw new ArgumentException ("The expression did not set a result");
494 StatementOrExpression,
500 // Deambiguates the input string to determine if we
501 // want to process a statement or if we want to
502 // process a compilation unit.
504 // This is done using a top-down predictive parser,
505 // since the yacc/jay parser can not deambiguage this
506 // without more than one lookahead token. There are very
509 static InputKind ToplevelOrStatement (SeekableStreamReader seekable)
511 Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
513 int t = tokenizer.token ();
516 return InputKind.EOF;
518 // These are toplevels
520 case Token.OPEN_BRACKET:
524 case Token.INTERFACE:
526 case Token.NAMESPACE:
528 case Token.PROTECTED:
533 return InputKind.CompilationUnit;
535 // Definitely expression
552 return InputKind.StatementOrExpression;
554 // These need deambiguation help
556 t = tokenizer.token ();
558 return InputKind.EOF;
560 if (t == Token.IDENTIFIER)
561 return InputKind.CompilationUnit;
562 return InputKind.StatementOrExpression;
565 // Distinguish between:
566 // delegate opt_anonymous_method_signature block
569 t = tokenizer.token ();
571 return InputKind.EOF;
572 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
573 return InputKind.StatementOrExpression;
574 return InputKind.CompilationUnit;
576 // Distinguih between:
578 // unsafe as modifier of a type declaration
580 t = tokenizer.token ();
582 return InputKind.EOF;
583 if (t == Token.OPEN_PARENS)
584 return InputKind.StatementOrExpression;
585 return InputKind.CompilationUnit;
587 // These are errors: we list explicitly what we had
588 // from the grammar, ERROR and then everything else
593 return InputKind.Error;
595 // This catches everything else allowed by
596 // expressions. We could add one-by-one use cases
599 return InputKind.StatementOrExpression;
604 // Parses the string @input and returns a CSharpParser if succeeful.
606 // if @silent is set to true then no errors are
607 // reported to the user. This is used to do various calls to the
608 // parser and check if the expression is parsable.
610 // @partial_input: if @silent is true, then it returns whether the
611 // parsed expression was partial, and more data is needed
613 static CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
615 partial_input = false;
617 queued_fields.Clear ();
618 Tokenizer.LocatedToken.Initialize ();
620 Stream s = new MemoryStream (Encoding.Default.GetBytes (input));
621 SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default);
623 InputKind kind = ToplevelOrStatement (seekable);
624 if (kind == InputKind.Error){
625 if (mode == ParseMode.ReportErrors)
626 ctx.Report.Error (-25, "Detection Parsing Error");
627 partial_input = false;
631 if (kind == InputKind.EOF){
632 if (mode == ParseMode.ReportErrors)
633 Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
634 partial_input = true;
638 seekable.Position = 0;
640 CSharpParser parser = new CSharpParser (seekable, Location.SourceFiles [0], RootContext.ToplevelTypes);
642 if (kind == InputKind.StatementOrExpression){
643 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
644 RootContext.StatementMode = true;
647 // Do not activate EvalCompilationUnitParserCharacter until
648 // I have figured out all the limitations to invoke methods
649 // in the generated classes. See repl.txt
651 parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
652 //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
653 RootContext.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) && CSharpParser.yacc_verbose_flag == 0)
661 old_printer = SetPrinter (new StreamReportPrinter (TextWriter.Null));
666 if (ctx.Report.Errors != 0){
667 if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
668 partial_input = true;
670 parser.undo.ExecuteUndo ();
674 if (old_printer != null)
675 SetPrinter (old_printer);
681 // Queue all the fields that we use, as we need to then go from FieldBuilder to FieldInfo
682 // or reflection gets confused (it basically gets confused, and variables override each
685 static List<Field> queued_fields = new List<Field> ();
687 //static ArrayList types = new ArrayList ();
689 static volatile bool invoking;
691 static CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
693 AssemblyDefinitionDynamic assembly;
695 if (Environment.GetEnvironmentVariable ("SAVE") != null) {
696 assembly = new AssemblyDefinitionDynamic (RootContext.ToplevelTypes, current_debug_name, current_debug_name);
697 assembly.Importer = loader.Importer;
699 assembly = new AssemblyDefinitionDynamic (RootContext.ToplevelTypes, current_debug_name);
702 assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.RunAndSave);
703 RootContext.ToplevelTypes.SetDeclaringAssembly (assembly);
704 RootContext.ToplevelTypes.Define ();
706 if (Report.Errors != 0){
711 TypeBuilder tb = null;
712 MethodBuilder mb = null;
715 tb = host.TypeBuilder;
717 foreach (MemberCore member in host.Methods){
718 if (member.Name != "Host")
721 MethodOrOperator method = (MethodOrOperator) member;
722 mb = method.MethodBuilder;
727 throw new Exception ("Internal error: did not find the method builder for the generated method");
730 RootContext.ToplevelTypes.Emit ();
731 if (Report.Errors != 0){
736 RootContext.ToplevelTypes.CloseType ();
738 if (Environment.GetEnvironmentVariable ("SAVE") != null)
745 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
746 // work from MethodBuilders. Retarded, I know.
748 var tt = assembly.Builder.GetType (tb.Name);
749 MethodInfo mi = tt.GetMethod (mb.Name);
751 // Pull the FieldInfos from the type, and keep track of them
752 foreach (Field field in queued_fields){
753 FieldInfo fi = tt.GetField (field.Name);
755 Tuple<FieldSpec, FieldInfo> old;
757 // If a previous value was set, nullify it, so that we do
759 if (fields.TryGetValue (field.Name, out old)) {
760 if (old.Item1.MemberType.IsStruct) {
762 // TODO: Clear fields for structs
766 old.Item2.SetValue (null, null);
771 fields [field.Name] = Tuple.Create (old.Item1, fi);
773 fields.Add (field.Name, Tuple.Create (field.Spec, fi));
778 queued_fields.Clear ();
780 return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
783 static internal void LoadAliases (NamespaceEntry ns)
785 ns.Populate (using_alias_list, using_list);
789 /// A sentinel value used to indicate that no value was
790 /// was set by the compiled function. This is used to
791 /// differentiate between a function not returning a
794 public class NoValueSet {
797 static internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
799 Tuple<FieldSpec, FieldInfo> fi;
800 fields.TryGetValue (name, out fi);
805 // Puts the FieldBuilder into a queue of names that will be
806 // registered. We can not register FieldBuilders directly
807 // we need to fetch the FieldInfo after Reflection cooks the
808 // types, or bad things happen (bad means: FieldBuilders behave
809 // incorrectly across multiple assemblies, causing assignments to
812 // This also serves for the parser to register Field classes
813 // that should be exposed as global variables
815 static internal void QueueField (Field f)
817 queued_fields.Add (f);
820 static string Quote (string s)
822 if (s.IndexOf ('"') != -1)
823 s = s.Replace ("\"", "\\\"");
825 return "\"" + s + "\"";
828 static public string GetUsing ()
830 lock (evaluator_lock){
831 StringBuilder sb = new StringBuilder ();
833 foreach (object x in using_alias_list)
834 sb.Append (String.Format ("using {0};\n", x));
836 foreach (object x in using_list)
837 sb.Append (String.Format ("using {0};\n", x));
839 return sb.ToString ();
843 static internal ICollection<string> GetUsingList ()
845 var res = new List<string> (using_list.Count);
846 foreach (object ue in using_list)
847 res.Add (ue.ToString ());
851 static internal string [] GetVarNames ()
853 lock (evaluator_lock){
854 return new List<string> (fields.Keys).ToArray ();
858 static 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 static public void LoadAssembly (string file)
887 lock (evaluator_lock){
888 var a = loader.LoadAssemblyFile (file);
890 loader.Importer.ImportAssembly (a, RootContext.ToplevelTypes.GlobalRootNamespace);
895 /// Exposes the API of the given assembly to the Evaluator
897 static public void ReferenceAssembly (Assembly a)
899 lock (evaluator_lock){
900 loader.Importer.ImportAssembly (a, RootContext.ToplevelTypes.GlobalRootNamespace);
905 /// If true, turns type expressions into valid expressions
906 /// and calls the describe method on it
908 public static bool DescribeTypeExpressions;
913 /// A delegate that can be used to invoke the
914 /// compiled expression or statement.
917 /// Since the Compile methods will compile
918 /// statements and expressions into the same
919 /// delegate, you can tell if a value was returned
920 /// by checking whether the returned value is of type
924 public delegate void CompiledMethod (ref object retvalue);
927 /// The default base class for every interaction line
930 /// The expressions and statements behave as if they were
931 /// a static method of this class. The InteractiveBase class
932 /// contains a number of useful methods, but can be overwritten
933 /// by setting the InteractiveBaseType property in the Evaluator
935 public class InteractiveBase {
937 /// Determines where the standard output of methods in this class will go.
939 public static TextWriter Output = Console.Out;
942 /// Determines where the standard error of methods in this class will go.
944 public static TextWriter Error = Console.Error;
947 /// The primary prompt used for interactive use.
949 public static string Prompt = "csharp> ";
952 /// The secondary prompt used for interactive use (used when
953 /// an expression is incomplete).
955 public static string ContinuationPrompt = " > ";
958 /// Used to signal that the user has invoked the `quit' statement.
960 public static bool QuitRequested;
963 /// Shows all the variables defined so far.
965 static public void ShowVars ()
967 Output.Write (Evaluator.GetVars ());
972 /// Displays the using statements in effect at this point.
974 static public void ShowUsing ()
976 Output.Write (Evaluator.GetUsing ());
980 public delegate void Simple ();
983 /// Times the execution of the given delegate
985 static public TimeSpan Time (Simple a)
987 DateTime start = DateTime.Now;
989 return DateTime.Now - start;
992 #if !SMCS_SOURCE && !STATIC
994 /// Loads the assemblies from a package
997 /// Loads the assemblies from a package. This is equivalent
998 /// to passing the -pkg: command line flag to the C# compiler
999 /// on the command line.
1001 static public void LoadPackage (string pkg)
1004 Error.WriteLine ("Invalid package specified");
1008 string pkgout = Driver.GetPackageFlags (pkg, false, RootContext.ToplevelTypes.Compiler.Report);
1012 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1013 Split (new Char [] { ' ', '\t'});
1015 foreach (string s in xargs){
1016 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
1017 string lib = s.Substring (s.IndexOf (':')+1);
1019 Evaluator.LoadAssembly (lib);
1028 /// Loads the assembly
1031 /// Loads the specified assembly and makes its types
1032 /// available to the evaluator. This is equivalent
1033 /// to passing the -pkg: command line flag to the C#
1034 /// compiler on the command line.
1036 static public void LoadAssembly (string assembly)
1038 Evaluator.LoadAssembly (assembly);
1043 /// Returns a list of available static methods.
1045 static public string help {
1047 return "Static methods:\n" +
1048 " Describe (object) - Describes the object's type\n" +
1049 " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" +
1050 " LoadAssembly (assembly) - Loads the given assembly (like -r:ASSEMBLY)\n" +
1051 " ShowVars (); - Shows defined local variables.\n" +
1052 " ShowUsing (); - Show active using declarations.\n" +
1053 " Prompt - The prompt used by the C# shell\n" +
1054 " ContinuationPrompt - The prompt for partial input\n" +
1055 " Time(() -> { }) - Times the specified code\n" +
1056 " quit; - You'll never believe it - this quits the repl!\n" +
1057 " help; - This help text\n";
1062 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1064 static public object quit {
1066 QuitRequested = true;
1068 // To avoid print null at the exit
1069 return typeof (Evaluator.NoValueSet);
1075 /// Describes an object or a type.
1078 /// This method will show a textual representation
1079 /// of the object's type. If the object is a
1080 /// System.Type it renders the type directly,
1081 /// otherwise it renders the type returned by
1082 /// invoking GetType on the object.
1084 static public string Describe (object x)
1089 var type = x as Type ?? x.GetType ();
1091 StringWriter sw = new StringWriter ();
1092 new Outline (type, sw, true, false, false).OutlineType ();
1093 return sw.ToString ();
1098 class HoistedEvaluatorVariable : HoistedVariable
1100 public HoistedEvaluatorVariable (Field field)
1101 : base (null, field)
1105 public override void EmitSymbolInfo ()
1109 protected override FieldExpr GetFieldExpression (EmitContext ec)
1111 return new FieldExpr (field, field.Location);
1116 /// A class used to assign values if the source expression is not void
1118 /// Used by the interactive shell to allow it to call this code to set
1119 /// the return value for an invocation.
1121 class OptionalAssign : SimpleAssign {
1122 public OptionalAssign (Expression t, Expression s, Location loc)
1127 protected override Expression DoResolve (ResolveContext ec)
1129 CloneContext cc = new CloneContext ();
1130 Expression clone = source.Clone (cc);
1133 // A useful feature for the REPL: if we can resolve the expression
1134 // as a type, Describe the type;
1136 if (Evaluator.DescribeTypeExpressions){
1137 var old_printer = Evaluator.SetPrinter (new StreamReportPrinter (TextWriter.Null));
1138 clone = clone.Resolve (ec);
1140 clone = source.Clone (cc);
1141 clone = clone.Resolve (ec, ResolveFlags.Type);
1143 Evaluator.SetPrinter (old_printer);
1144 clone = source.Clone (cc);
1145 clone = clone.Resolve (ec);
1149 Arguments args = new Arguments (1);
1150 args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1151 source = new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1153 Evaluator.SetPrinter (old_printer);
1155 clone = clone.Resolve (ec);
1160 // This means its really a statement.
1161 if (clone.Type == TypeManager.void_type || clone is DynamicInvocation || clone is Assign) {
1165 return base.DoResolve (ec);
1170 List<KeyValuePair<TypeContainer, TypeContainer>> undo_types;
1174 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1177 public void AddTypeContainer (TypeContainer current_container, TypeContainer tc)
1179 if (current_container == tc){
1180 Console.Error.WriteLine ("Internal error: inserting container into itself");
1184 if (undo_types == null)
1185 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1187 undo_types.Add (new KeyValuePair<TypeContainer, TypeContainer> (current_container, tc));
1190 public void ExecuteUndo ()
1192 if (undo_types == null)
1195 foreach (var p in undo_types){
1196 TypeContainer current_container = p.Key;
1198 current_container.RemoveTypeContainer (p.Value);