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 ModuleCompiled (ctx, true);
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 RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
132 var ctypes = TypeManager.InitCoreTypes ();
134 ctx.MetaImporter.Initialize ();
135 driver.LoadReferences ();
136 TypeManager.InitCoreTypes (ctx, ctypes);
137 TypeManager.InitOptionalCoreTypes (ctx);
139 RootContext.EvalMode = true;
142 return startup_files.ToArray ();
148 Init (new string [0]);
153 CompilerCallableEntryPoint.PartialReset ();
154 RootContext.PartialReset ();
156 RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
158 Location.AddFile (null, "{interactive}");
159 Location.Initialize ();
161 current_debug_name = "interactive" + (count++) + ".dll";
162 if (Environment.GetEnvironmentVariable ("SAVE") != null){
163 CodeGen.Init (current_debug_name, current_debug_name, false, ctx);
165 CodeGen.InitDynamic (ctx, current_debug_name);
169 /// The base class for the classes that host the user generated code
173 /// This is the base class that will host the code
174 /// executed by the Evaluator. By default
175 /// this is the Mono.CSharp.InteractiveBase class
176 /// which is useful for interactive use.
178 /// By changing this property you can control the
179 /// base class and the static members that are
180 /// available to your evaluated code.
182 static public TypeSpec InteractiveBaseClass {
184 if (interactive_base_class != null)
185 return interactive_base_class;
187 return ctx.MetaImporter.ImportType (typeof (InteractiveBase));
191 public static void SetInteractiveBaseClass (Type type)
194 throw new ArgumentNullException ();
196 lock (evaluator_lock)
197 interactive_base_class = ctx.MetaImporter.ImportType (type);
201 /// Interrupts the evaluation of an expression executing in Evaluate.
204 /// Use this method to interrupt long-running invocations.
206 public static void Interrupt ()
208 if (!inited || !invoking)
211 if (invoke_thread != null)
212 invoke_thread.Abort ();
216 /// Compiles the input string and returns a delegate that represents the compiled code.
220 /// Compiles the input string as a C# expression or
221 /// statement, unlike the Evaluate method, the
222 /// resulting delegate can be invoked multiple times
223 /// without incurring in the compilation overhead.
225 /// If the return value of this function is null,
226 /// this indicates that the parsing was complete.
227 /// If the return value is a string it indicates
228 /// that the input string was partial and that the
229 /// invoking code should provide more code before
230 /// the code can be successfully compiled.
232 /// If you know that you will always get full expressions or
233 /// statements and do not care about partial input, you can use
234 /// the other Compile overload.
236 /// On success, in addition to returning null, the
237 /// compiled parameter will be set to the delegate
238 /// that can be invoked to execute the code.
241 static public string Compile (string input, out CompiledMethod compiled)
243 if (input == null || input.Length == 0){
248 lock (evaluator_lock){
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);
273 compiled = CompileBlock (parser_result as Class, parser.undo, ctx.Report);
280 /// Compiles the input string and returns a delegate that represents the compiled code.
284 /// Compiles the input string as a C# expression or
285 /// statement, unlike the Evaluate method, the
286 /// resulting delegate can be invoked multiple times
287 /// without incurring in the compilation overhead.
289 /// This method can only deal with fully formed input
290 /// strings and does not provide a completion mechanism.
291 /// If you must deal with partial input (for example for
292 /// interactive use) use the other overload.
294 /// On success, a delegate is returned that can be used
295 /// to invoke the method.
298 static public CompiledMethod Compile (string input)
300 CompiledMethod compiled;
302 // Ignore partial inputs
303 if (Compile (input, out compiled) != null){
304 // Error, the input was partial.
308 // Either null (on error) or the compiled method.
313 // Todo: Should we handle errors, or expect the calling code to setup
314 // the recording themselves?
318 /// Evaluates and expression or statement and returns any result values.
321 /// Evaluates the input string as a C# expression or
322 /// statement. If the input string is an expression
323 /// the result will be stored in the result variable
324 /// and the result_set variable will be set to true.
326 /// It is necessary to use the result/result_set
327 /// pair to identify when a result was set (for
328 /// example, execution of user-provided input can be
329 /// an expression, a statement or others, and
330 /// result_set would only be set if the input was an
333 /// If the return value of this function is null,
334 /// this indicates that the parsing was complete.
335 /// If the return value is a string, it indicates
336 /// that the input is partial and that the user
337 /// should provide an updated string.
339 public static string Evaluate (string input, out object result, out bool result_set)
341 CompiledMethod compiled;
346 input = Compile (input, out compiled);
350 if (compiled == null)
354 // The code execution does not need to keep the compiler lock
356 object retval = typeof (NoValueSet);
359 invoke_thread = System.Threading.Thread.CurrentThread;
361 compiled (ref retval);
362 } catch (ThreadAbortException e){
363 Thread.ResetAbort ();
364 Console.WriteLine ("Interrupted!\n{0}", e);
370 // We use a reference to a compiler type, in this case
371 // Driver as a flag to indicate that this was a statement
373 if (retval != typeof (NoValueSet)){
381 public static string [] GetCompletions (string input, out string prefix)
384 if (input == null || input.Length == 0)
387 lock (evaluator_lock){
392 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
394 if (CSharpParser.yacc_verbose_flag != 0)
395 Console.WriteLine ("DEBUG: No completions available");
399 Class parser_result = parser.InteractiveResult as Class;
401 if (parser_result == null){
402 if (CSharpParser.yacc_verbose_flag != 0)
403 Console.WriteLine ("Do not know how to cope with !Class yet");
408 RootContext.ResolveTree ();
409 if (ctx.Report.Errors != 0)
412 RootContext.PopulateTypes ();
413 if (ctx.Report.Errors != 0)
416 MethodOrOperator method = null;
417 foreach (MemberCore member in parser_result.Methods){
418 if (member.Name != "Host")
421 method = (MethodOrOperator) member;
425 throw new InternalErrorException ("did not find the the Host method");
427 BlockContext bc = new BlockContext (method, method.Block, method.ReturnType);
430 method.Block.Resolve (null, bc, method);
431 } catch (CompletionResult cr){
432 prefix = cr.BaseText;
436 parser.undo.ExecuteUndo ();
444 /// Executes the given expression or statement.
447 /// Executes the provided statement, returns true
448 /// on success, false on parsing errors. Exceptions
449 /// might be thrown by the called code.
451 public static bool Run (string statement)
459 bool ok = Evaluate (statement, out result, out result_set) == null;
465 /// Evaluates and expression or statement and returns the result.
468 /// Evaluates the input string as a C# expression or
469 /// statement and returns the value.
471 /// This method will throw an exception if there is a syntax error,
472 /// of if the provided input is not an expression but a statement.
474 public static object Evaluate (string input)
479 string r = Evaluate (input, out result, out result_set);
482 throw new ArgumentException ("Syntax error on input: partial input");
484 if (result_set == false)
485 throw new ArgumentException ("The expression did not set a result");
492 StatementOrExpression,
498 // Deambiguates the input string to determine if we
499 // want to process a statement or if we want to
500 // process a compilation unit.
502 // This is done using a top-down predictive parser,
503 // since the yacc/jay parser can not deambiguage this
504 // without more than one lookahead token. There are very
507 static InputKind ToplevelOrStatement (SeekableStreamReader seekable)
509 Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
511 int t = tokenizer.token ();
514 return InputKind.EOF;
516 // These are toplevels
518 case Token.OPEN_BRACKET:
522 case Token.INTERFACE:
524 case Token.NAMESPACE:
526 case Token.PROTECTED:
531 return InputKind.CompilationUnit;
533 // Definitely expression
550 return InputKind.StatementOrExpression;
552 // These need deambiguation help
554 t = tokenizer.token ();
556 return InputKind.EOF;
558 if (t == Token.IDENTIFIER)
559 return InputKind.CompilationUnit;
560 return InputKind.StatementOrExpression;
563 // Distinguish between:
564 // delegate opt_anonymous_method_signature block
567 t = tokenizer.token ();
569 return InputKind.EOF;
570 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
571 return InputKind.StatementOrExpression;
572 return InputKind.CompilationUnit;
574 // Distinguih between:
576 // unsafe as modifier of a type declaration
578 t = tokenizer.token ();
580 return InputKind.EOF;
581 if (t == Token.OPEN_PARENS)
582 return InputKind.StatementOrExpression;
583 return InputKind.CompilationUnit;
585 // These are errors: we list explicitly what we had
586 // from the grammar, ERROR and then everything else
591 return InputKind.Error;
593 // This catches everything else allowed by
594 // expressions. We could add one-by-one use cases
597 return InputKind.StatementOrExpression;
602 // Parses the string @input and returns a CSharpParser if succeeful.
604 // if @silent is set to true then no errors are
605 // reported to the user. This is used to do various calls to the
606 // parser and check if the expression is parsable.
608 // @partial_input: if @silent is true, then it returns whether the
609 // parsed expression was partial, and more data is needed
611 static CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
613 partial_input = false;
615 queued_fields.Clear ();
616 Tokenizer.LocatedToken.Initialize ();
618 Stream s = new MemoryStream (Encoding.Default.GetBytes (input));
619 SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default);
621 InputKind kind = ToplevelOrStatement (seekable);
622 if (kind == InputKind.Error){
623 if (mode == ParseMode.ReportErrors)
624 ctx.Report.Error (-25, "Detection Parsing Error");
625 partial_input = false;
629 if (kind == InputKind.EOF){
630 if (mode == ParseMode.ReportErrors)
631 Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
632 partial_input = true;
636 seekable.Position = 0;
638 CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
640 if (kind == InputKind.StatementOrExpression){
641 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
642 RootContext.StatementMode = true;
645 // Do not activate EvalCompilationUnitParserCharacter until
646 // I have figured out all the limitations to invoke methods
647 // in the generated classes. See repl.txt
649 parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
650 //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
651 RootContext.StatementMode = false;
654 if (mode == ParseMode.GetCompletions)
655 parser.Lexer.CompleteOnEOF = true;
657 ReportPrinter old_printer = null;
658 if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0)
659 old_printer = SetPrinter (new StreamReportPrinter (TextWriter.Null));
664 if (ctx.Report.Errors != 0){
665 if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF)
666 partial_input = true;
668 parser.undo.ExecuteUndo ();
672 if (old_printer != null)
673 SetPrinter (old_printer);
679 // Queue all the fields that we use, as we need to then go from FieldBuilder to FieldInfo
680 // or reflection gets confused (it basically gets confused, and variables override each
683 static List<Field> queued_fields = new List<Field> ();
685 //static ArrayList types = new ArrayList ();
687 static volatile bool invoking;
689 static CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
691 RootContext.ResolveTree ();
692 if (Report.Errors != 0){
697 RootContext.PopulateTypes ();
699 if (Report.Errors != 0){
704 TypeBuilder tb = null;
705 MethodBuilder mb = null;
708 tb = host.TypeBuilder;
710 foreach (MemberCore member in host.Methods){
711 if (member.Name != "Host")
714 MethodOrOperator method = (MethodOrOperator) member;
715 mb = method.MethodBuilder;
720 throw new Exception ("Internal error: did not find the method builder for the generated method");
723 RootContext.EmitCode ();
724 if (Report.Errors != 0){
729 RootContext.CloseTypes (ctx);
731 if (Environment.GetEnvironmentVariable ("SAVE") != null)
732 CodeGen.Save (current_debug_name, false, Report);
738 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
739 // work from MethodBuilders. Retarded, I know.
741 var tt = CodeGen.Assembly.Builder.GetType (tb.Name);
742 MethodInfo mi = tt.GetMethod (mb.Name);
744 // Pull the FieldInfos from the type, and keep track of them
745 foreach (Field field in queued_fields){
746 FieldInfo fi = tt.GetField (field.Name);
748 Tuple<FieldSpec, FieldInfo> old;
750 // If a previous value was set, nullify it, so that we do
752 if (fields.TryGetValue (field.Name, out old)) {
753 if (old.Item1.MemberType.IsStruct) {
755 // TODO: Clear fields for structs
759 old.Item2.SetValue (null, null);
764 fields [field.Name] = Tuple.Create (old.Item1, fi);
766 fields.Add (field.Name, Tuple.Create (field.Spec, fi));
771 queued_fields.Clear ();
773 return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
776 static internal void LoadAliases (NamespaceEntry ns)
778 ns.Populate (using_alias_list, using_list);
782 /// A sentinel value used to indicate that no value was
783 /// was set by the compiled function. This is used to
784 /// differentiate between a function not returning a
787 public class NoValueSet {
790 static internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
792 Tuple<FieldSpec, FieldInfo> fi;
793 fields.TryGetValue (name, out fi);
798 // Puts the FieldBuilder into a queue of names that will be
799 // registered. We can not register FieldBuilders directly
800 // we need to fetch the FieldInfo after Reflection cooks the
801 // types, or bad things happen (bad means: FieldBuilders behave
802 // incorrectly across multiple assemblies, causing assignments to
805 // This also serves for the parser to register Field classes
806 // that should be exposed as global variables
808 static internal void QueueField (Field f)
810 queued_fields.Add (f);
813 static string Quote (string s)
815 if (s.IndexOf ('"') != -1)
816 s = s.Replace ("\"", "\\\"");
818 return "\"" + s + "\"";
821 static public string GetUsing ()
823 lock (evaluator_lock){
824 StringBuilder sb = new StringBuilder ();
826 foreach (object x in using_alias_list)
827 sb.Append (String.Format ("using {0};\n", x));
829 foreach (object x in using_list)
830 sb.Append (String.Format ("using {0};\n", x));
832 return sb.ToString ();
836 static internal ICollection<string> GetUsingList ()
838 var res = new List<string> (using_list.Count);
839 foreach (object ue in using_list)
840 res.Add (ue.ToString ());
844 static internal string [] GetVarNames ()
846 lock (evaluator_lock){
847 return new List<string> (fields.Keys).ToArray ();
851 static public string GetVars ()
853 lock (evaluator_lock){
854 StringBuilder sb = new StringBuilder ();
856 foreach (var de in fields){
857 var fi = LookupField (de.Key);
860 value = fi.Item2.GetValue (null);
862 value = Quote ((string)value);
864 value = "<error reading value>";
867 sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
871 return sb.ToString ();
876 /// Loads the given assembly and exposes the API to the user.
878 static public void LoadAssembly (string file)
880 lock (evaluator_lock){
881 driver.LoadAssembly (file, false);
882 ctx.GlobalRootNamespace.ComputeNamespaces (ctx);
887 /// Exposes the API of the given assembly to the Evaluator
889 static public void ReferenceAssembly (Assembly a)
891 lock (evaluator_lock){
892 // GlobalRootNamespace.Instance.AddAssemblyReference (a);
893 // GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
894 ctx.MetaImporter.ImportAssembly (a, ctx.GlobalRootNamespace);
899 /// If true, turns type expressions into valid expressions
900 /// and calls the describe method on it
902 public static bool DescribeTypeExpressions;
907 /// A delegate that can be used to invoke the
908 /// compiled expression or statement.
911 /// Since the Compile methods will compile
912 /// statements and expressions into the same
913 /// delegate, you can tell if a value was returned
914 /// by checking whether the returned value is of type
918 public delegate void CompiledMethod (ref object retvalue);
921 /// The default base class for every interaction line
924 /// The expressions and statements behave as if they were
925 /// a static method of this class. The InteractiveBase class
926 /// contains a number of useful methods, but can be overwritten
927 /// by setting the InteractiveBaseType property in the Evaluator
929 public class InteractiveBase {
931 /// Determines where the standard output of methods in this class will go.
933 public static TextWriter Output = Console.Out;
936 /// Determines where the standard error of methods in this class will go.
938 public static TextWriter Error = Console.Error;
941 /// The primary prompt used for interactive use.
943 public static string Prompt = "csharp> ";
946 /// The secondary prompt used for interactive use (used when
947 /// an expression is incomplete).
949 public static string ContinuationPrompt = " > ";
952 /// Used to signal that the user has invoked the `quit' statement.
954 public static bool QuitRequested;
957 /// Shows all the variables defined so far.
959 static public void ShowVars ()
961 Output.Write (Evaluator.GetVars ());
966 /// Displays the using statements in effect at this point.
968 static public void ShowUsing ()
970 Output.Write (Evaluator.GetUsing ());
974 public delegate void Simple ();
977 /// Times the execution of the given delegate
979 static public TimeSpan Time (Simple a)
981 DateTime start = DateTime.Now;
983 return DateTime.Now - start;
988 /// Loads the assemblies from a package
991 /// Loads the assemblies from a package. This is equivalent
992 /// to passing the -pkg: command line flag to the C# compiler
993 /// on the command line.
995 static public void LoadPackage (string pkg)
998 Error.WriteLine ("Invalid package specified");
1002 string pkgout = Driver.GetPackageFlags (pkg, false, RootContext.ToplevelTypes.Compiler.Report);
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);
1021 /// Loads the assembly
1024 /// Loads the specified assembly and makes its types
1025 /// available to the evaluator. This is equivalent
1026 /// to passing the -pkg: command line flag to the C#
1027 /// compiler on the command line.
1029 static public void LoadAssembly (string assembly)
1031 Evaluator.LoadAssembly (assembly);
1035 /// Returns a list of available static methods.
1037 static public string help {
1039 return "Static methods:\n" +
1040 " Describe (object) - Describes the object's type\n" +
1041 " LoadPackage (package); - Loads the given Package (like -pkg:FILE)\n" +
1042 " LoadAssembly (assembly) - Loads the given assembly (like -r:ASSEMBLY)\n" +
1043 " ShowVars (); - Shows defined local variables.\n" +
1044 " ShowUsing (); - Show active using declarations.\n" +
1045 " Prompt - The prompt used by the C# shell\n" +
1046 " ContinuationPrompt - The prompt for partial input\n" +
1047 " Time(() -> { }) - Times the specified code\n" +
1048 " quit; - You'll never believe it - this quits the repl!\n" +
1049 " help; - This help text\n";
1054 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1056 static public object quit {
1058 QuitRequested = true;
1060 // To avoid print null at the exit
1061 return typeof (Evaluator.NoValueSet);
1067 /// Describes an object or a type.
1070 /// This method will show a textual representation
1071 /// of the object's type. If the object is a
1072 /// System.Type it renders the type directly,
1073 /// otherwise it renders the type returned by
1074 /// invoking GetType on the object.
1076 static public string Describe (object x)
1081 var type = x as Type ?? x.GetType ();
1083 StringWriter sw = new StringWriter ();
1084 new Outline (type, sw, true, false, false).OutlineType ();
1085 return sw.ToString ();
1090 class HoistedEvaluatorVariable : HoistedVariable
1092 public HoistedEvaluatorVariable (Field field)
1093 : base (null, field)
1097 public override void EmitSymbolInfo ()
1101 protected override FieldExpr GetFieldExpression (EmitContext ec)
1103 return new FieldExpr (field, field.Location);
1108 /// A class used to assign values if the source expression is not void
1110 /// Used by the interactive shell to allow it to call this code to set
1111 /// the return value for an invocation.
1113 class OptionalAssign : SimpleAssign {
1114 public OptionalAssign (Expression t, Expression s, Location loc)
1119 protected override Expression DoResolve (ResolveContext ec)
1121 CloneContext cc = new CloneContext ();
1122 Expression clone = source.Clone (cc);
1125 // A useful feature for the REPL: if we can resolve the expression
1126 // as a type, Describe the type;
1128 if (Evaluator.DescribeTypeExpressions){
1129 var old_printer = Evaluator.SetPrinter (new StreamReportPrinter (TextWriter.Null));
1130 clone = clone.Resolve (ec);
1132 clone = source.Clone (cc);
1133 clone = clone.Resolve (ec, ResolveFlags.Type);
1135 Evaluator.SetPrinter (old_printer);
1136 clone = source.Clone (cc);
1137 clone = clone.Resolve (ec);
1141 Arguments args = new Arguments (1);
1142 args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1143 source = new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1145 Evaluator.SetPrinter (old_printer);
1147 clone = clone.Resolve (ec);
1152 // This means its really a statement.
1153 if (clone.Type == TypeManager.void_type || clone is DynamicInvocation || clone is Assign) {
1157 return base.DoResolve (ec);
1162 List<KeyValuePair<TypeContainer, TypeContainer>> undo_types;
1166 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1169 public void AddTypeContainer (TypeContainer current_container, TypeContainer tc)
1171 if (current_container == tc){
1172 Console.Error.WriteLine ("Internal error: inserting container into itself");
1176 if (undo_types == null)
1177 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1179 undo_types.Add (new KeyValuePair<TypeContainer, TypeContainer> (current_container, tc));
1182 public void ExecuteUndo ()
1184 if (undo_types == null)
1187 foreach (var p in undo_types){
1188 TypeContainer current_container = p.Key;
1190 current_container.RemoveTypeContainer (p.Value);