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
13 using System.Threading;
14 using System.Collections.Generic;
15 using System.Reflection;
16 using System.Reflection.Emit;
18 using System.Globalization;
21 namespace Mono.CSharp {
24 /// Evaluator: provides an API to evaluate C# statements and
25 /// expressions dynamically.
28 /// This class exposes static methods to evaluate expressions in the
31 /// To initialize the evaluator with a number of compiler
32 /// options call the Init(string[]args) method with a set of
33 /// command line options that the compiler recognizes.
35 /// To interrupt execution of a statement, you can invoke the
36 /// Evaluator.Interrupt method.
38 public class Evaluator {
41 // Parse silently, do not output any error messages
44 // Report errors during parse
47 // Auto-complete, means that the tokenizer will start producing
48 // GETCOMPLETIONS tokens when it reaches a certain point.
52 static object evaluator_lock = new object ();
54 static string current_debug_name;
56 static Thread invoke_thread;
58 static List<NamespaceEntry.UsingAliasEntry> using_alias_list = new List<NamespaceEntry.UsingAliasEntry> ();
59 internal static List<NamespaceEntry.UsingEntry> using_list = new List<NamespaceEntry.UsingEntry> ();
60 static Dictionary<string, Tuple<FieldSpec, FieldInfo>> fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
62 static TypeSpec interactive_base_class;
66 static CompilerContext ctx;
68 public static TextWriter MessageOutput = Console.Out;
71 /// Optional initialization for the Evaluator.
74 /// Initializes the Evaluator with the command line options
75 /// that would be processed by the command line compiler. Only
76 /// the first call to Init will work, any future invocations are
79 /// You can safely avoid calling this method if your application
80 /// does not need any of the features exposed by the command line
83 public static void Init (string [] args)
85 InitAndGetStartupFiles (args);
88 internal static ReportPrinter SetPrinter (ReportPrinter report_printer)
90 return ctx.Report.SetPrinter (report_printer);
94 /// Optional initialization for the Evaluator.
97 /// Initializes the Evaluator with the command line
98 /// options that would be processed by the command
99 /// line compiler. Only the first call to
100 /// InitAndGetStartupFiles or Init will work, any future
101 /// invocations are ignored.
103 /// You can safely avoid calling this method if your application
104 /// does not need any of the features exposed by the command line
107 /// This method return an array of strings that contains any
108 /// files that were specified in `args'.
110 public static string [] InitAndGetStartupFiles (string [] args)
112 lock (evaluator_lock){
114 return new string [0];
116 driver = Driver.Create (args, false, new ConsoleReportPrinter ());
118 throw new Exception ("Failed to create compiler driver with the given arguments");
122 RootContext.ToplevelTypes = new ModuleContainer (ctx);
124 driver.ProcessDefaultConfig ();
126 var startup_files = new List<string> ();
127 foreach (CompilationUnit file in Location.SourceFiles)
128 startup_files.Add (file.Path);
130 CompilerCallableEntryPoint.Reset ();
131 var ctypes = TypeManager.InitCoreTypes ();
133 ctx.MetaImporter.Initialize ();
135 RootContext.ToplevelTypes.MakeExecutable ("temp");
136 driver.LoadReferences (RootContext.ToplevelTypes);
137 TypeManager.InitCoreTypes (RootContext.ToplevelTypes, ctypes);
138 TypeManager.InitOptionalCoreTypes (ctx);
140 RootContext.EvalMode = true;
143 return startup_files.ToArray ();
149 Init (new string [0]);
154 CompilerCallableEntryPoint.PartialReset ();
156 Location.AddFile (null, "{interactive}");
157 Location.Initialize ();
159 current_debug_name = "interactive" + (count++) + ".dll";
163 /// The base class for the classes that host the user generated code
167 /// This is the base class that will host the code
168 /// executed by the Evaluator. By default
169 /// this is the Mono.CSharp.InteractiveBase class
170 /// which is useful for interactive use.
172 /// By changing this property you can control the
173 /// base class and the static members that are
174 /// available to your evaluated code.
176 static public TypeSpec InteractiveBaseClass {
178 if (interactive_base_class != null)
179 return interactive_base_class;
181 return ctx.MetaImporter.ImportType (typeof (InteractiveBase));
185 public static void SetInteractiveBaseClass (Type type)
188 throw new ArgumentNullException ();
190 lock (evaluator_lock)
191 interactive_base_class = ctx.MetaImporter.ImportType (type);
195 /// Interrupts the evaluation of an expression executing in Evaluate.
198 /// Use this method to interrupt long-running invocations.
200 public static void Interrupt ()
202 if (!inited || !invoking)
205 if (invoke_thread != null)
206 invoke_thread.Abort ();
210 /// Compiles the input string and returns a delegate that represents the compiled code.
214 /// Compiles the input string as a C# expression or
215 /// statement, unlike the Evaluate method, the
216 /// resulting delegate can be invoked multiple times
217 /// without incurring in the compilation overhead.
219 /// If the return value of this function is null,
220 /// this indicates that the parsing was complete.
221 /// If the return value is a string it indicates
222 /// that the input string was partial and that the
223 /// invoking code should provide more code before
224 /// the code can be successfully compiled.
226 /// If you know that you will always get full expressions or
227 /// statements and do not care about partial input, you can use
228 /// the other Compile overload.
230 /// On success, in addition to returning null, the
231 /// compiled parameter will be set to the delegate
232 /// that can be invoked to execute the code.
235 static public string Compile (string input, out CompiledMethod compiled)
237 if (input == null || input.Length == 0){
242 lock (evaluator_lock){
246 // RootContext.ToplevelTypes = new ModuleContainer (ctx);
249 CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
255 ParseString (ParseMode.ReportErrors, input, out partial_input);
259 object parser_result = parser.InteractiveResult;
261 if (!(parser_result is Class)){
262 int errors = ctx.Report.Errors;
264 NamespaceEntry.VerifyAllUsing ();
265 if (errors == ctx.Report.Errors)
266 parser.CurrentNamespace.Extract (using_alias_list, using_list);
269 compiled = CompileBlock (parser_result as Class, parser.undo, ctx.Report);
276 /// Compiles the input string and returns a delegate that represents the compiled code.
280 /// Compiles the input string as a C# expression or
281 /// statement, unlike the Evaluate method, the
282 /// resulting delegate can be invoked multiple times
283 /// without incurring in the compilation overhead.
285 /// This method can only deal with fully formed input
286 /// strings and does not provide a completion mechanism.
287 /// If you must deal with partial input (for example for
288 /// interactive use) use the other overload.
290 /// On success, a delegate is returned that can be used
291 /// to invoke the method.
294 static public CompiledMethod Compile (string input)
296 CompiledMethod compiled;
298 // Ignore partial inputs
299 if (Compile (input, out compiled) != null){
300 // Error, the input was partial.
304 // Either null (on error) or the compiled method.
309 // Todo: Should we handle errors, or expect the calling code to setup
310 // the recording themselves?
314 /// Evaluates and expression or statement and returns any result values.
317 /// Evaluates the input string as a C# expression or
318 /// statement. If the input string is an expression
319 /// the result will be stored in the result variable
320 /// and the result_set variable will be set to true.
322 /// It is necessary to use the result/result_set
323 /// pair to identify when a result was set (for
324 /// example, execution of user-provided input can be
325 /// an expression, a statement or others, and
326 /// result_set would only be set if the input was an
329 /// If the return value of this function is null,
330 /// this indicates that the parsing was complete.
331 /// If the return value is a string, it indicates
332 /// that the input is partial and that the user
333 /// should provide an updated string.
335 public static string Evaluate (string input, out object result, out bool result_set)
337 CompiledMethod compiled;
342 input = Compile (input, out compiled);
346 if (compiled == null)
350 // The code execution does not need to keep the compiler lock
352 object retval = typeof (NoValueSet);
355 invoke_thread = System.Threading.Thread.CurrentThread;
357 compiled (ref retval);
358 } catch (ThreadAbortException e){
359 Thread.ResetAbort ();
360 Console.WriteLine ("Interrupted!\n{0}", e);
366 // We use a reference to a compiler type, in this case
367 // Driver as a flag to indicate that this was a statement
369 if (retval != typeof (NoValueSet)){
377 public static string [] GetCompletions (string input, out string prefix)
380 if (input == null || input.Length == 0)
383 lock (evaluator_lock){
388 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
390 if (CSharpParser.yacc_verbose_flag != 0)
391 Console.WriteLine ("DEBUG: No completions available");
395 Class parser_result = parser.InteractiveResult as Class;
397 if (parser_result == null){
398 if (CSharpParser.yacc_verbose_flag != 0)
399 Console.WriteLine ("Do not know how to cope with !Class yet");
404 var a = RootContext.ToplevelTypes.MakeExecutable ("temp");
405 a.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Run);
406 RootContext.ToplevelTypes.Define ();
407 if (ctx.Report.Errors != 0)
410 MethodOrOperator method = null;
411 foreach (MemberCore member in parser_result.Methods){
412 if (member.Name != "Host")
415 method = (MethodOrOperator) member;
419 throw new InternalErrorException ("did not find the the Host method");
421 BlockContext bc = new BlockContext (method, method.Block, method.ReturnType);
424 method.Block.Resolve (null, bc, method);
425 } catch (CompletionResult cr){
426 prefix = cr.BaseText;
430 parser.undo.ExecuteUndo ();
438 /// Executes the given expression or statement.
441 /// Executes the provided statement, returns true
442 /// on success, false on parsing errors. Exceptions
443 /// might be thrown by the called code.
445 public static bool Run (string statement)
453 bool ok = Evaluate (statement, out result, out result_set) == null;
459 /// Evaluates and expression or statement and returns the result.
462 /// Evaluates the input string as a C# expression or
463 /// statement and returns the value.
465 /// This method will throw an exception if there is a syntax error,
466 /// of if the provided input is not an expression but a statement.
468 public static object Evaluate (string input)
473 string r = Evaluate (input, out result, out result_set);
476 throw new ArgumentException ("Syntax error on input: partial input");
478 if (result_set == false)
479 throw new ArgumentException ("The expression did not set a result");
486 StatementOrExpression,
492 // Deambiguates the input string to determine if we
493 // want to process a statement or if we want to
494 // process a compilation unit.
496 // This is done using a top-down predictive parser,
497 // since the yacc/jay parser can not deambiguage this
498 // without more than one lookahead token. There are very
501 static InputKind ToplevelOrStatement (SeekableStreamReader seekable)
503 Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
505 int t = tokenizer.token ();
508 return InputKind.EOF;
510 // These are toplevels
512 case Token.OPEN_BRACKET:
516 case Token.INTERFACE:
518 case Token.NAMESPACE:
520 case Token.PROTECTED:
525 return InputKind.CompilationUnit;
527 // Definitely expression
544 return InputKind.StatementOrExpression;
546 // These need deambiguation help
548 t = tokenizer.token ();
550 return InputKind.EOF;
552 if (t == Token.IDENTIFIER)
553 return InputKind.CompilationUnit;
554 return InputKind.StatementOrExpression;
557 // Distinguish between:
558 // delegate opt_anonymous_method_signature block
561 t = tokenizer.token ();
563 return InputKind.EOF;
564 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
565 return InputKind.StatementOrExpression;
566 return InputKind.CompilationUnit;
568 // Distinguih between:
570 // unsafe as modifier of a type declaration
572 t = tokenizer.token ();
574 return InputKind.EOF;
575 if (t == Token.OPEN_PARENS)
576 return InputKind.StatementOrExpression;
577 return InputKind.CompilationUnit;
579 // These are errors: we list explicitly what we had
580 // from the grammar, ERROR and then everything else
585 return InputKind.Error;
587 // This catches everything else allowed by
588 // expressions. We could add one-by-one use cases
591 return InputKind.StatementOrExpression;
596 // Parses the string @input and returns a CSharpParser if succeeful.
598 // if @silent is set to true then no errors are
599 // reported to the user. This is used to do various calls to the
600 // parser and check if the expression is parsable.
602 // @partial_input: if @silent is true, then it returns whether the
603 // parsed expression was partial, and more data is needed
605 static CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
607 partial_input = false;
609 queued_fields.Clear ();
610 Tokenizer.LocatedToken.Initialize ();
612 Stream s = new MemoryStream (Encoding.Default.GetBytes (input));
613 SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default);
615 InputKind kind = ToplevelOrStatement (seekable);
616 if (kind == InputKind.Error){
617 if (mode == ParseMode.ReportErrors)
618 ctx.Report.Error (-25, "Detection Parsing Error");
619 partial_input = false;
623 if (kind == InputKind.EOF){
624 if (mode == ParseMode.ReportErrors)
625 Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
626 partial_input = true;
630 seekable.Position = 0;
632 CSharpParser parser = new CSharpParser (seekable, Location.SourceFiles [0], RootContext.ToplevelTypes);
634 if (kind == InputKind.StatementOrExpression){
635 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
636 RootContext.StatementMode = true;
639 // Do not activate EvalCompilationUnitParserCharacter until
640 // I have figured out all the limitations to invoke methods
641 // in the generated classes. See repl.txt
643 parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
644 //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
645 RootContext.StatementMode = false;
648 if (mode == ParseMode.GetCompletions)
649 parser.Lexer.CompleteOnEOF = true;
651 ReportPrinter old_printer = null;
652 if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0)
653 old_printer = SetPrinter (new StreamReportPrinter (TextWriter.Null));
658 if (ctx.Report.Errors != 0){
659 if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
660 partial_input = true;
662 parser.undo.ExecuteUndo ();
666 if (old_printer != null)
667 SetPrinter (old_printer);
673 // Queue all the fields that we use, as we need to then go from FieldBuilder to FieldInfo
674 // or reflection gets confused (it basically gets confused, and variables override each
677 static List<Field> queued_fields = new List<Field> ();
679 //static ArrayList types = new ArrayList ();
681 static volatile bool invoking;
683 static CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
685 AssemblyDefinition assembly;
687 if (Environment.GetEnvironmentVariable ("SAVE") != null) {
688 assembly = RootContext.ToplevelTypes.MakeExecutable (current_debug_name, current_debug_name);
690 assembly = RootContext.ToplevelTypes.MakeExecutable (current_debug_name);
693 assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.RunAndSave);
694 RootContext.ToplevelTypes.Define ();
696 if (Report.Errors != 0){
701 TypeBuilder tb = null;
702 MethodBuilder mb = null;
705 tb = host.TypeBuilder;
707 foreach (MemberCore member in host.Methods){
708 if (member.Name != "Host")
711 MethodOrOperator method = (MethodOrOperator) member;
712 mb = method.MethodBuilder;
717 throw new Exception ("Internal error: did not find the method builder for the generated method");
720 RootContext.ToplevelTypes.Emit ();
721 if (Report.Errors != 0){
726 RootContext.ToplevelTypes.CloseType ();
728 if (Environment.GetEnvironmentVariable ("SAVE") != null)
735 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
736 // work from MethodBuilders. Retarded, I know.
738 var tt = assembly.Builder.GetType (tb.Name);
739 MethodInfo mi = tt.GetMethod (mb.Name);
741 // Pull the FieldInfos from the type, and keep track of them
742 foreach (Field field in queued_fields){
743 FieldInfo fi = tt.GetField (field.Name);
745 Tuple<FieldSpec, FieldInfo> old;
747 // If a previous value was set, nullify it, so that we do
749 if (fields.TryGetValue (field.Name, out old)) {
750 if (old.Item1.MemberType.IsStruct) {
752 // TODO: Clear fields for structs
756 old.Item2.SetValue (null, null);
761 fields [field.Name] = Tuple.Create (old.Item1, fi);
763 fields.Add (field.Name, Tuple.Create (field.Spec, fi));
768 queued_fields.Clear ();
770 return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
773 static internal void LoadAliases (NamespaceEntry ns)
775 ns.Populate (using_alias_list, using_list);
779 /// A sentinel value used to indicate that no value was
780 /// was set by the compiled function. This is used to
781 /// differentiate between a function not returning a
784 public class NoValueSet {
787 static internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
789 Tuple<FieldSpec, FieldInfo> fi;
790 fields.TryGetValue (name, out fi);
795 // Puts the FieldBuilder into a queue of names that will be
796 // registered. We can not register FieldBuilders directly
797 // we need to fetch the FieldInfo after Reflection cooks the
798 // types, or bad things happen (bad means: FieldBuilders behave
799 // incorrectly across multiple assemblies, causing assignments to
802 // This also serves for the parser to register Field classes
803 // that should be exposed as global variables
805 static internal void QueueField (Field f)
807 queued_fields.Add (f);
810 static string Quote (string s)
812 if (s.IndexOf ('"') != -1)
813 s = s.Replace ("\"", "\\\"");
815 return "\"" + s + "\"";
818 static public string GetUsing ()
820 lock (evaluator_lock){
821 StringBuilder sb = new StringBuilder ();
823 foreach (object x in using_alias_list)
824 sb.Append (String.Format ("using {0};\n", x));
826 foreach (object x in using_list)
827 sb.Append (String.Format ("using {0};\n", x));
829 return sb.ToString ();
833 static internal ICollection<string> GetUsingList ()
835 var res = new List<string> (using_list.Count);
836 foreach (object ue in using_list)
837 res.Add (ue.ToString ());
841 static internal string [] GetVarNames ()
843 lock (evaluator_lock){
844 return new List<string> (fields.Keys).ToArray ();
848 static public string GetVars ()
850 lock (evaluator_lock){
851 StringBuilder sb = new StringBuilder ();
853 foreach (var de in fields){
854 var fi = LookupField (de.Key);
857 value = fi.Item2.GetValue (null);
859 value = Quote ((string)value);
861 value = "<error reading value>";
864 sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
868 return sb.ToString ();
873 /// Loads the given assembly and exposes the API to the user.
875 static public void LoadAssembly (string file)
877 lock (evaluator_lock){
878 var a = driver.LoadAssemblyFile (file, false);
880 ctx.MetaImporter.ImportAssembly (a, RootContext.ToplevelTypes.GlobalRootNamespace);
885 /// Exposes the API of the given assembly to the Evaluator
887 static public void ReferenceAssembly (Assembly a)
889 lock (evaluator_lock){
890 ctx.MetaImporter.ImportAssembly (a, RootContext.ToplevelTypes.GlobalRootNamespace);
895 /// If true, turns type expressions into valid expressions
896 /// and calls the describe method on it
898 public static bool DescribeTypeExpressions;
903 /// A delegate that can be used to invoke the
904 /// compiled expression or statement.
907 /// Since the Compile methods will compile
908 /// statements and expressions into the same
909 /// delegate, you can tell if a value was returned
910 /// by checking whether the returned value is of type
914 public delegate void CompiledMethod (ref object retvalue);
917 /// The default base class for every interaction line
920 /// The expressions and statements behave as if they were
921 /// a static method of this class. The InteractiveBase class
922 /// contains a number of useful methods, but can be overwritten
923 /// by setting the InteractiveBaseType property in the Evaluator
925 public class InteractiveBase {
927 /// Determines where the standard output of methods in this class will go.
929 public static TextWriter Output = Console.Out;
932 /// Determines where the standard error of methods in this class will go.
934 public static TextWriter Error = Console.Error;
937 /// The primary prompt used for interactive use.
939 public static string Prompt = "csharp> ";
942 /// The secondary prompt used for interactive use (used when
943 /// an expression is incomplete).
945 public static string ContinuationPrompt = " > ";
948 /// Used to signal that the user has invoked the `quit' statement.
950 public static bool QuitRequested;
953 /// Shows all the variables defined so far.
955 static public void ShowVars ()
957 Output.Write (Evaluator.GetVars ());
962 /// Displays the using statements in effect at this point.
964 static public void ShowUsing ()
966 Output.Write (Evaluator.GetUsing ());
970 public delegate void Simple ();
973 /// Times the execution of the given delegate
975 static public TimeSpan Time (Simple a)
977 DateTime start = DateTime.Now;
979 return DateTime.Now - start;
984 /// Loads the assemblies from a package
987 /// Loads the assemblies from a package. This is equivalent
988 /// to passing the -pkg: command line flag to the C# compiler
989 /// on the command line.
991 static public void LoadPackage (string pkg)
994 Error.WriteLine ("Invalid package specified");
998 string pkgout = Driver.GetPackageFlags (pkg, false, RootContext.ToplevelTypes.Compiler.Report);
1002 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1003 Split (new Char [] { ' ', '\t'});
1005 foreach (string s in xargs){
1006 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
1007 string lib = s.Substring (s.IndexOf (':')+1);
1009 Evaluator.LoadAssembly (lib);
1017 /// Loads the assembly
1020 /// Loads the specified assembly and makes its types
1021 /// available to the evaluator. This is equivalent
1022 /// to passing the -pkg: command line flag to the C#
1023 /// compiler on the command line.
1025 static public void LoadAssembly (string assembly)
1027 Evaluator.LoadAssembly (assembly);
1031 /// Returns a list of available static methods.
1033 static public string help {
1035 return "Static methods:\n" +
1036 " Describe (object) - Describes the object's type\n" +
1037 " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" +
1038 " LoadAssembly (assembly) - Loads the given assembly (like -r:ASSEMBLY)\n" +
1039 " ShowVars (); - Shows defined local variables.\n" +
1040 " ShowUsing (); - Show active using declarations.\n" +
1041 " Prompt - The prompt used by the C# shell\n" +
1042 " ContinuationPrompt - The prompt for partial input\n" +
1043 " Time(() -> { }) - Times the specified code\n" +
1044 " quit; - You'll never believe it - this quits the repl!\n" +
1045 " help; - This help text\n";
1050 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1052 static public object quit {
1054 QuitRequested = true;
1056 // To avoid print null at the exit
1057 return typeof (Evaluator.NoValueSet);
1063 /// Describes an object or a type.
1066 /// This method will show a textual representation
1067 /// of the object's type. If the object is a
1068 /// System.Type it renders the type directly,
1069 /// otherwise it renders the type returned by
1070 /// invoking GetType on the object.
1072 static public string Describe (object x)
1077 var type = x as Type ?? x.GetType ();
1079 StringWriter sw = new StringWriter ();
1080 new Outline (type, sw, true, false, false).OutlineType ();
1081 return sw.ToString ();
1086 class HoistedEvaluatorVariable : HoistedVariable
1088 public HoistedEvaluatorVariable (Field field)
1089 : base (null, field)
1093 public override void EmitSymbolInfo ()
1097 protected override FieldExpr GetFieldExpression (EmitContext ec)
1099 return new FieldExpr (field, field.Location);
1104 /// A class used to assign values if the source expression is not void
1106 /// Used by the interactive shell to allow it to call this code to set
1107 /// the return value for an invocation.
1109 class OptionalAssign : SimpleAssign {
1110 public OptionalAssign (Expression t, Expression s, Location loc)
1115 protected override Expression DoResolve (ResolveContext ec)
1117 CloneContext cc = new CloneContext ();
1118 Expression clone = source.Clone (cc);
1121 // A useful feature for the REPL: if we can resolve the expression
1122 // as a type, Describe the type;
1124 if (Evaluator.DescribeTypeExpressions){
1125 var old_printer = Evaluator.SetPrinter (new StreamReportPrinter (TextWriter.Null));
1126 clone = clone.Resolve (ec);
1128 clone = source.Clone (cc);
1129 clone = clone.Resolve (ec, ResolveFlags.Type);
1131 Evaluator.SetPrinter (old_printer);
1132 clone = source.Clone (cc);
1133 clone = clone.Resolve (ec);
1137 Arguments args = new Arguments (1);
1138 args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1139 source = new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1141 Evaluator.SetPrinter (old_printer);
1143 clone = clone.Resolve (ec);
1148 // This means its really a statement.
1149 if (clone.Type == TypeManager.void_type || clone is DynamicInvocation || clone is Assign) {
1153 return base.DoResolve (ec);
1158 List<KeyValuePair<TypeContainer, TypeContainer>> undo_types;
1162 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1165 public void AddTypeContainer (TypeContainer current_container, TypeContainer tc)
1167 if (current_container == tc){
1168 Console.Error.WriteLine ("Internal error: inserting container into itself");
1172 if (undo_types == null)
1173 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1175 undo_types.Add (new KeyValuePair<TypeContainer, TypeContainer> (current_container, tc));
1178 public void ExecuteUndo ()
1180 if (undo_types == null)
1183 foreach (var p in undo_types){
1184 TypeContainer current_container = p.Key;
1186 current_container.RemoveTypeContainer (p.Value);