59e79d1f222f92763010ebe00c56c1d438c61ee1
[mono.git] / mcs / mcs / eval.cs
1 //
2 // eval.cs: Evaluation and Hosting API for the C# compiler
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@gnome.org)
6 //
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
11 //
12 using System;
13 using System.Threading;
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.IO;
18 using System.Globalization;
19 using System.Text;
20
21 namespace Mono.CSharp {
22
23         /// <summary>
24         ///   Evaluator: provides an API to evaluate C# statements and
25         ///   expressions dynamically.
26         /// </summary>
27         /// <remarks>
28         ///   This class exposes static methods to evaluate expressions in the
29         ///   current program.
30         ///
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.
34         ///
35         ///   To interrupt execution of a statement, you can invoke the
36         ///   Evaluator.Interrupt method.
37         /// </remarks>
38         public class Evaluator {
39                 static string current_debug_name;
40                 static int count;
41                 static Thread invoke_thread;
42                 
43                 static ArrayList using_alias_list = new ArrayList ();
44                 static ArrayList using_list = new ArrayList ();
45                 static Hashtable fields = new Hashtable ();
46
47                 static Type   interactive_base_class = typeof (InteractiveBase);
48                 static Driver driver;
49                 static bool inited;
50
51                 /// <summary>
52                 ///   Optional initialization for the Evaluator.
53                 /// </summary>
54                 /// <remarks>
55                 ///  Initializes the Evaluator with the command line options
56                 ///  that would be processed by the command line compiler.  Only
57                 ///  the first call to Init will work, any future invocations are
58                 ///  ignored.
59                 ///
60                 ///  You can safely avoid calling this method if your application
61                 ///  does not need any of the features exposed by the command line
62                 ///  interface.
63                 /// </remarks>
64                 public static void Init (string [] args)
65                 {
66                         if (inited)
67                                 return;
68
69                         RootContext.Version = LanguageVersion.Default;
70                         driver = Driver.Create (args, false);
71                         if (driver == null)
72                                 throw new Exception ("Failed to create compiler driver with the given arguments");
73
74                         driver.ProcessDefaultConfig ();
75                         CompilerCallableEntryPoint.Reset ();
76                         Driver.LoadReferences ();
77                         RootContext.EvalMode = true;
78                         inited = true;
79                 }
80
81                 static void Init ()
82                 {
83                         Init (new string [0]);
84                 }
85                 
86                 static void Reset ()
87                 {
88                         CompilerCallableEntryPoint.PartialReset ();
89
90                         //
91                         // PartialReset should not reset the core types, this is very redundant.
92                         //
93                         if (!TypeManager.InitCoreTypes ())
94                                 throw new Exception ("Failed to InitCoreTypes");
95                         TypeManager.InitOptionalCoreTypes ();
96                         
97                         Location.AddFile ("<interactive>");
98                         Location.Initialize ();
99
100                         current_debug_name = "interactive" + (count++) + ".dll";
101                         if (Environment.GetEnvironmentVariable ("SAVE") != null){
102                                 CodeGen.Init (current_debug_name, current_debug_name, false);
103                         } else
104                                 CodeGen.InitDynamic (current_debug_name);
105                 }
106
107                 /// <summary>
108                 ///   The base class for the classes that host the user generated code
109                 /// </summary>
110                 /// <remarks>
111                 ///
112                 ///   This is the base class that will host the code
113                 ///   executed by the Evaluator.  By default
114                 ///   this is the Mono.CSharp.InteractiveBase class
115                 ///   which is useful for interactive use.
116                 ///
117                 ///   By changing this property you can control the
118                 ///   base class and the static members that are
119                 ///   available to your evaluated code.
120                 /// </remarks>
121                 static public Type InteractiveBaseClass {
122                         get {
123                                 return interactive_base_class;
124                         }
125
126                         set {
127                                 if (value == null)
128                                         throw new ArgumentNullException ();
129                                 
130                                 interactive_base_class = value;
131                         }
132                 }
133
134                 /// <summary>
135                 ///   Interrupts the evaluation of an expression.
136                 /// </summary>
137                 /// <remarks>
138                 ///   Use this method to interrupt long-running invocations.
139                 /// </remarks>
140                 public static void Interrupt ()
141                 {
142                         if (!inited || !invoking)
143                                 return;
144                         
145                         if (invoke_thread != null)
146                                 invoke_thread.Abort ();
147                 }
148
149                 //
150                 // Todo: Should we handle errors, or expect the calling code to setup
151                 // the recording themselves?
152                 //
153
154                 /// <summary>
155                 ///   Evaluates and expression or statement and returns any result values.
156                 /// </summary>
157                 /// <remarks>
158                 ///   Evaluates the input string as a C# expression or
159                 ///   statement.  If the input string is an expression
160                 ///   the result will be stored in the result variable
161                 ///   and the result_set variable will be set to true.
162                 ///
163                 ///   It is necessary to use the result/result_set
164                 ///   pair to identify when a result was set (for
165                 ///   example, execution of user-provided input can be
166                 ///   an expression, a statement or others, and
167                 ///   result_set would only be set if the input was an
168                 ///   expression.
169                 ///
170                 ///   If the return value of this function is null,
171                 ///   this indicates that the parsing was complete.
172                 ///   If the return value is a string, it indicates
173                 ///   that the input is partial and that the user
174                 ///   should provide an updated string.
175                 /// </remarks>
176                 public static string Evaluate (string input, out object result, out bool result_set)
177                 {
178                         result_set = false;
179                         result = null;
180                         
181                         if (input == null || input.Length == 0)
182                                 return null;
183
184                         if (!inited)
185                                 Init ();
186                         
187                         bool partial_input;
188                         CSharpParser parser = ParseString (true, input, out partial_input);
189                         if (parser == null){
190                                 if (partial_input)
191                                         return input;
192                                 
193                                 ParseString (false, input, out partial_input);
194                                 return null;
195                         }
196
197                         object parser_result = parser.InteractiveResult;
198                         
199                         if (!(parser_result is Class))
200                                 parser.CurrentNamespace.Extract (using_alias_list, using_list);
201
202                         result = ExecuteBlock (parser_result as Class, parser.undo);
203                         //
204                         // We use a reference to a compiler type, in this case
205                         // Driver as a flag to indicate that this was a statement
206                         //
207                         if (result != typeof (NoValueSet))
208                                 result_set = true;
209
210                         return null;
211                 }
212
213                 /// <summary>
214                 ///   Executes the given expression or statement.
215                 /// </summary>
216                 /// <remarks>
217                 ///    Executes the provided statement, returns true
218                 ///    on success, false on parsing errors.  Exceptions
219                 ///    might be thrown by the called code.
220                 /// </remarks>
221                 public static bool Run (string statement)
222                 {
223                         if (!inited)
224                                 Init ();
225                         
226                         object result;
227                         bool result_set;
228                         
229                         bool ok = Evaluate (statement, out result, out result_set) == null;
230                         
231                         return ok;
232                 }
233
234                 /// <summary>
235                 ///   Evaluates and expression or statement and returns the result.
236                 /// </summary>
237                 /// <remarks>
238                 ///   Evaluates the input string as a C# expression or
239                 ///   statement and returns the value.   
240                 ///
241                 ///   This method will throw an exception if there is a syntax error,
242                 ///   of if the provided input is not an expression but a statement.
243                 /// </remarks>
244                 public static object Evaluate (string input)
245                 {
246                         object result;
247                         bool result_set;
248                         
249                         string r = Evaluate (input, out result, out result_set);
250
251                         if (r != null)
252                                 throw new ArgumentException ("Syntax error on input: partial input");
253                         
254                         if (result_set == false)
255                                 throw new ArgumentException ("The expression did not set a result");
256
257                         return result;
258                 }
259                 
260                 enum InputKind {
261                         EOF,
262                         StatementOrExpression,
263                         CompilationUnit,
264                         Error
265                 }
266
267                 //
268                 // Deambiguates the input string to determine if we
269                 // want to process a statement or if we want to
270                 // process a compilation unit.
271                 //
272                 // This is done using a top-down predictive parser,
273                 // since the yacc/jay parser can not deambiguage this
274                 // without more than one lookahead token.   There are very
275                 // few ambiguities.
276                 //
277                 static InputKind ToplevelOrStatement (SeekableStreamReader seekable)
278                 {
279                         Tokenizer tokenizer = new Tokenizer (seekable, Location.SourceFiles [0]);
280                         
281                         int t = tokenizer.token ();
282                         switch (t){
283                         case Token.EOF:
284                                 return InputKind.EOF;
285                                 
286                         // These are toplevels
287                         case Token.EXTERN:
288                         case Token.OPEN_BRACKET:
289                         case Token.ABSTRACT:
290                         case Token.CLASS:
291                         case Token.ENUM:
292                         case Token.INTERFACE:
293                         case Token.INTERNAL:
294                         case Token.NAMESPACE:
295                         case Token.PRIVATE:
296                         case Token.PROTECTED:
297                         case Token.PUBLIC:
298                         case Token.SEALED:
299                         case Token.STATIC:
300                         case Token.STRUCT:
301                                 return InputKind.CompilationUnit;
302                                 
303                         // Definitely expression
304                         case Token.FIXED:
305                         case Token.BOOL:
306                         case Token.BYTE:
307                         case Token.CHAR:
308                         case Token.DECIMAL:
309                         case Token.DOUBLE:
310                         case Token.FLOAT:
311                         case Token.INT:
312                         case Token.LONG:
313                         case Token.NEW:
314                         case Token.OBJECT:
315                         case Token.SBYTE:
316                         case Token.SHORT:
317                         case Token.STRING:
318                         case Token.UINT:
319                         case Token.ULONG:
320                                 return InputKind.StatementOrExpression;
321
322                         // These need deambiguation help
323                         case Token.USING:
324                                 t = tokenizer.token ();
325                                 if (t == Token.EOF)
326                                         return InputKind.EOF;
327
328                                 if (t == Token.IDENTIFIER)
329                                         return InputKind.CompilationUnit;
330                                 return InputKind.StatementOrExpression;
331
332
333                         // Distinguish between:
334                         //    delegate opt_anonymous_method_signature block
335                         //    delegate type 
336                         case Token.DELEGATE:
337                                 t = tokenizer.token ();
338                                 if (t == Token.EOF)
339                                         return InputKind.EOF;
340                                 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
341                                         return InputKind.StatementOrExpression;
342                                 return InputKind.CompilationUnit;
343
344                         // Distinguih between:
345                         //    unsafe block
346                         //    unsafe as modifier of a type declaration
347                         case Token.UNSAFE:
348                                 t = tokenizer.token ();
349                                 if (t == Token.EOF)
350                                         return InputKind.EOF;
351                                 if (t == Token.OPEN_PARENS)
352                                         return InputKind.StatementOrExpression;
353                                 return InputKind.CompilationUnit;
354                                 
355                         // These are errors: we list explicitly what we had
356                         // from the grammar, ERROR and then everything else
357
358                         case Token.READONLY:
359                         case Token.OVERRIDE:
360                         case Token.ERROR:
361                                 return InputKind.Error;
362
363                         // This catches everything else allowed by
364                         // expressions.  We could add one-by-one use cases
365                         // if needed.
366                         default:
367                                 return InputKind.StatementOrExpression;
368                         }
369                 }
370                 
371                 //
372                 // Parses the string @input and returns a CSharpParser if succeeful.
373                 //
374                 // if @silent is set to true then no errors are
375                 // reported to the user.  This is used to do various calls to the
376                 // parser and check if the expression is parsable.
377                 //
378                 // @partial_input: if @silent is true, then it returns whether the
379                 // parsed expression was partial, and more data is needed
380                 //
381                 static CSharpParser ParseString (bool silent, string input, out bool partial_input)
382                 {
383                         partial_input = false;
384                         Reset ();
385                         queued_fields.Clear ();
386
387                         Stream s = new MemoryStream (Encoding.Default.GetBytes (input));
388                         SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default);
389
390                         InputKind kind = ToplevelOrStatement (seekable);
391                         if (kind == InputKind.Error){
392                                 if (!silent)
393                                         Report.Error (-25, "Detection Parsing Error");
394                                 partial_input = false;
395                                 return null;
396                         }
397
398                         if (kind == InputKind.EOF){
399                                 if (silent == false)
400                                         Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
401                                 partial_input = true;
402                                 return null;
403                                 
404                         }
405                         seekable.Position = 0;
406
407                         CSharpParser parser = new CSharpParser (seekable, Location.SourceFiles [0]);
408                         parser.ErrorOutput = Report.Stderr;
409
410                         if (kind == InputKind.StatementOrExpression){
411                                 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
412                                 RootContext.StatementMode = true;
413                         } else {
414                                 //
415                                 // Do not activate EvalCompilationUnitParserCharacter until
416                                 // I have figured out all the limitations to invoke methods
417                                 // in the generated classes.  See repl.txt
418                                 //
419                                 parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
420                                 //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
421                                 RootContext.StatementMode = false;
422                         }
423
424                         if (silent)
425                                 Report.DisableReporting ();
426                         try {
427                                 parser.parse ();
428                         } finally {
429                                 if (Report.Errors != 0){
430                                         if (silent && parser.UnexpectedEOF)
431                                                 partial_input = true;
432
433                                         parser.undo.ExecuteUndo ();
434                                         parser = null;
435                                 }
436
437                                 if (silent)
438                                         Report.EnableReporting ();
439                         }
440                         return parser;
441                 }
442
443                 delegate void HostSignature (ref object retvalue);
444
445                 //
446                 // Queue all the fields that we use, as we need to then go from FieldBuilder to FieldInfo
447                 // or reflection gets confused (it basically gets confused, and variables override each
448                 // other).
449                 //
450                 static ArrayList queued_fields = new ArrayList ();
451                 
452                 //static ArrayList types = new ArrayList ();
453
454                 static volatile bool invoking;
455                 
456                 static object ExecuteBlock (Class host, Undo undo)
457                 {
458                         RootContext.ResolveTree ();
459                         if (Report.Errors != 0){
460                                 undo.ExecuteUndo ();
461                                 return typeof (NoValueSet);
462                         }
463                         
464                         RootContext.PopulateTypes ();
465                         RootContext.DefineTypes ();
466
467                         if (Report.Errors != 0){
468                                 undo.ExecuteUndo ();
469                                 return typeof (NoValueSet);
470                         }
471
472                         TypeBuilder tb = null;
473                         MethodBuilder mb = null;
474                                 
475                         if (host != null){
476                                 tb = host.TypeBuilder;
477                                 mb = null;
478                                 foreach (MemberCore member in host.Methods){
479                                         if (member.Name != "Host")
480                                                 continue;
481                                         
482                                         MethodOrOperator method = (MethodOrOperator) member;
483                                         mb = method.MethodBuilder;
484                                         break;
485                                 }
486
487                                 if (mb == null)
488                                         throw new Exception ("Internal error: did not find the method builder for the generated method");
489                         }
490                         
491                         RootContext.EmitCode ();
492                         if (Report.Errors != 0)
493                                 return typeof (NoValueSet);
494                         
495                         RootContext.CloseTypes ();
496
497                         if (Environment.GetEnvironmentVariable ("SAVE") != null)
498                                 CodeGen.Save (current_debug_name, false);
499
500                         if (host == null)
501                                 return typeof (NoValueSet);
502                         
503                         //
504                         // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
505                         // work from MethodBuilders.   Retarded, I know.
506                         //
507                         Type tt = CodeGen.Assembly.Builder.GetType (tb.Name);
508                         MethodInfo mi = tt.GetMethod (mb.Name);
509                         
510                         // Pull the FieldInfos from the type, and keep track of them
511                         foreach (Field field in queued_fields){
512                                 FieldInfo fi = tt.GetField (field.Name);
513                                 
514                                 FieldInfo old = (FieldInfo) fields [field.Name];
515                                 
516                                 // If a previous value was set, nullify it, so that we do
517                                 // not leak memory
518                                 if (old != null){
519                                         if (old.FieldType.IsValueType){
520                                                 //
521                                                 // TODO: Clear fields for structs
522                                                 //
523                                         } else {
524                                                 try {
525                                                         old.SetValue (null, null);
526                                                 } catch {
527                                                 }
528                                         }
529                                 }
530                                 
531                                 fields [field.Name] = fi;
532                         }
533                         //types.Add (tb);
534
535                         queued_fields.Clear ();
536                         
537                         HostSignature invoker = (HostSignature) System.Delegate.CreateDelegate (typeof (HostSignature), mi);
538                         object retval = typeof (NoValueSet);
539
540                         try {
541                                 invoke_thread = System.Threading.Thread.CurrentThread;
542                                 invoking = true;
543                                 invoker (ref retval);
544                         } catch (ThreadAbortException e){
545                                 Thread.ResetAbort ();
546                                 Console.WriteLine ("Interrupted!\n{0}", e);
547                         } finally {
548                                 invoking = false;
549                         }
550                         
551                         // d.DynamicInvoke  (new object [] { retval });
552
553                         return retval;
554                 }
555
556                 static internal void LoadAliases (NamespaceEntry ns)
557                 {
558                         ns.Populate (using_alias_list, using_list);
559                 }
560                 
561                 //
562                 // Just a placeholder class, used as a sentinel to determine that the
563                 // generated code did not set a value
564                 class NoValueSet {
565                 }
566
567                 static internal FieldInfo LookupField (string name)
568                 {
569                         FieldInfo fi =  (FieldInfo) fields [name];
570
571                         return fi;
572                 }
573
574                 //
575                 // Puts the FieldBuilder into a queue of names that will be
576                 // registered.   We can not register FieldBuilders directly
577                 // we need to fetch the FieldInfo after Reflection cooks the
578                 // types, or bad things happen (bad means: FieldBuilders behave
579                 // incorrectly across multiple assemblies, causing assignments to
580                 // invalid areas
581                 //
582                 // This also serves for the parser to register Field classes
583                 // that should be exposed as global variables
584                 //
585                 static internal void QueueField (Field f)
586                 {
587                         queued_fields.Add (f);
588                 }
589
590                 static string Quote (string s)
591                 {
592                         if (s.IndexOf ('"') != -1)
593                                 s = s.Replace ("\"", "\\\"");
594                         
595                         return "\"" + s + "\"";
596                 }
597
598                 static public string GetUsing ()
599                 {
600                         StringBuilder sb = new StringBuilder ();
601                         
602                         foreach (object x in using_alias_list)
603                                 sb.Append (String.Format ("using {0};\n", x));
604
605                         foreach (object x in using_list)
606                                 sb.Append (String.Format ("using {0};\n", x));
607
608                         return sb.ToString ();
609                 }
610
611                 static public string GetVars ()
612                 {
613                         StringBuilder sb = new StringBuilder ();
614                         
615                         foreach (DictionaryEntry de in fields){
616                                 FieldInfo fi = LookupField ((string) de.Key);
617                                 object value = null;
618                                 bool error = false;
619                                 
620                                 try {
621                                         if (value == null)
622                                                 value = "null";
623                                         value = fi.GetValue (null);
624                                         if (value is string)
625                                                 value = Quote ((string)value);
626                                 } catch {
627                                         error = true;
628                                 }
629
630                                 if (error)
631                                         sb.Append (String.Format ("{0} {1} <error reading value>", TypeManager.CSharpName(fi.FieldType), de.Key));
632                                 else
633                                         sb.Append (String.Format ("{0} {1} = {2}", TypeManager.CSharpName(fi.FieldType), de.Key, value));
634                         }
635
636                         return sb.ToString ();
637                 }
638
639                 /// <summary>
640                 ///    Loads the given assembly and exposes the API to the user.
641                 /// </summary>
642                 static public void LoadAssembly (string file)
643                 {
644                         Driver.LoadAssembly (file, true);
645                 }
646
647                 /// <summary>
648                 ///    Exposes the API of the given assembly to the Evaluator
649                 /// </summary>
650                 static public void ReferenceAssembly (Assembly a)
651                 {
652                         RootNamespace.Global.AddAssemblyReference (a);
653                 }
654                 
655         }
656
657         /// <summary>
658         ///   The default base class for every interaction line
659         /// </summary>
660         public class InteractiveBase {
661                 public static TextWriter Output = Console.Out;
662                 public static TextWriter Error = Console.Error;
663                 public static string Prompt             = "csharp> ";
664                 public static string ContinuationPrompt = "      > ";
665
666                 static public void ShowVars ()
667                 {
668                         Output.Write (Evaluator.GetVars ());
669                         Output.Flush ();
670                 }
671
672                 static public void ShowUsing ()
673                 {
674                         Output.Write (Evaluator.GetUsing ());
675                         Output.Flush ();
676                 }
677
678                 public delegate void Simple ();
679                 
680                 static public TimeSpan Time (Simple a)
681                 {
682                         DateTime start = DateTime.Now;
683                         a ();
684                         return DateTime.Now - start;
685                 }
686                 
687 #if !SMCS_SOURCE
688                 static public void LoadPackage (string pkg)
689                 {
690                         if (pkg == null){
691                                 Error.WriteLine ("Invalid package specified");
692                                 return;
693                         }
694
695                         string pkgout = Driver.GetPackageFlags (pkg, false);
696                         if (pkgout == null)
697                                 return;
698
699                         string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
700                                 Split (new Char [] { ' ', '\t'});
701
702                         foreach (string s in xargs){
703                                 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
704                                         string lib = s.Substring (s.IndexOf (':')+1);
705
706                                         Driver.LoadAssembly (lib, true);
707                                         continue;
708                                 }
709                         }
710                 }
711 #endif
712
713                 static public void LoadAssembly (string assembly)
714                 {
715                         Driver.LoadAssembly (assembly, true);
716                 }
717                 
718                 static public string help {
719                         get {
720                                 return  "Static methods:\n"+
721                                         "  LoadPackage (pkg); - Loads the given Package (like -pkg:FILE)\n" +
722                                         "  LoadAssembly (ass) - Loads the given assembly (like -r:ASS)\n" + 
723                                         "  ShowVars ();       - Shows defined local variables.\n" +
724                                         "  ShowUsing ();      - Show active using decltions.\n" +
725                                         "  Prompt             - The prompt used by the C# shell\n" +
726                                         "  ContinuationPrompt - The prompt for partial input\n" +
727                                         "  Time(() -> { })    - Times the specified code\n" +
728                                         "  quit;\n" +
729                                         "  help;\n";
730                         }
731                 }
732
733                 static public object quit {
734                         get {
735                                 Environment.Exit (0);
736                                 return null;
737                         }
738                 }
739         }
740
741         //
742         // A local variable reference that will create a Field in a
743         // Class with the resolved type.  This is necessary so we can
744         // support "var" as a field type in a class declaration.
745         //
746         // We allow LocalVariableReferece to do the heavy lifting, and
747         // then we insert the field with the resolved type
748         //
749         public class LocalVariableReferenceWithClassSideEffect : LocalVariableReference {
750                 TypeContainer container;
751                 string name;
752                 
753                 public LocalVariableReferenceWithClassSideEffect (TypeContainer container, string name, Block current_block, string local_variable_id, Location loc)
754                         : base (current_block, local_variable_id, loc)
755                 {
756                         this.container = container;
757                         this.name = name;
758                 }
759
760                 public override bool Equals (object obj)
761                 {
762                         LocalVariableReferenceWithClassSideEffect lvr = obj as LocalVariableReferenceWithClassSideEffect;
763                         if (lvr == null)
764                                 return false;
765
766                         if (lvr.name != name || lvr.container != container)
767                                 return false;
768
769                         return base.Equals (obj);
770                 }
771
772                 public override int GetHashCode ()
773                 {
774                         return name.GetHashCode ();
775                 }
776                 
777                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
778                 {
779                         Expression ret = base.DoResolveLValue (ec, right_side);
780                         if (ret == null)
781                                 return null;
782
783                         Field f = new Field (container, new TypeExpression (ret.Type, Location),
784                                              Modifiers.PUBLIC | Modifiers.STATIC,
785                                              name, null, Location);
786                         container.AddField (f);
787                         if (f.Define ())
788                                 Evaluator.QueueField (f);
789                         
790                         return ret;
791                 }
792         }
793
794         /// <summary>
795         ///    A class used to assign values if the source expression is not void
796         ///
797         ///    Used by the interactive shell to allow it to call this code to set
798         ///    the return value for an invocation.
799         /// </summary>
800         class OptionalAssign : SimpleAssign {
801                 public OptionalAssign (Expression t, Expression s, Location loc)
802                         : base (t, s, loc)
803                 {
804                 }
805
806                 public override Expression DoResolve (EmitContext ec)
807                 {
808                         CloneContext cc = new CloneContext ();
809                         Expression clone = source.Clone (cc);
810
811                         clone = clone.Resolve (ec);
812                         if (clone == null)
813                                 return null;
814
815                         // This means its really a statement.
816                         if (clone.Type == TypeManager.void_type){
817                                 source = source.Resolve (ec);
818                                 target = null;
819                                 type = TypeManager.void_type;
820                                 eclass = ExprClass.Value;
821                                 return this;
822                         }
823
824                         return base.DoResolve (ec);
825                 }
826
827                 public override void Emit (EmitContext ec)
828                 {
829                         if (target == null)
830                                 source.Emit (ec);
831                         else
832                                 base.Emit (ec);
833                 }
834
835                 public override void EmitStatement (EmitContext ec)
836                 {
837                         if (target == null)
838                                 source.Emit (ec);
839                         else
840                                 base.EmitStatement (ec);
841                 }
842         }
843
844         public class Undo {
845                 ArrayList undo_types;
846                 
847                 public Undo ()
848                 {
849                         undo_types = new ArrayList ();
850                 }
851
852                 public void AddTypeContainer (TypeContainer current_container, TypeContainer tc)
853                 {
854                         if (current_container == tc){
855                                 Console.Error.WriteLine ("Internal error: inserting container into itself");
856                                 return;
857                         }
858                         
859                         if (undo_types == null)
860                                 undo_types = new ArrayList ();
861                         undo_types.Add (new Pair (current_container, tc));
862                 }
863
864                 public void ExecuteUndo ()
865                 {
866                         if (undo_types == null)
867                                 return;
868
869                         foreach (Pair p in undo_types){
870                                 TypeContainer current_container = (TypeContainer) p.First;
871
872                                 current_container.RemoveTypeContainer ((TypeContainer) p.Second);
873                         }
874                         undo_types = null;
875                 }
876         }
877         
878 }
879