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