2010-04-29 Marek Safar <marek.safar@gmail.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.Generic;
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                 enum ParseMode {
41                         // Parse silently, do not output any error messages
42                         Silent,
43
44                         // Report errors during parse
45                         ReportErrors,
46
47                         // Auto-complete, means that the tokenizer will start producing
48                         // GETCOMPLETIONS tokens when it reaches a certain point.
49                         GetCompletions
50                 }
51
52                 static object evaluator_lock = new object ();
53                 
54                 static string current_debug_name;
55                 static int count;
56                 static Thread invoke_thread;
57
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, FieldInfo> fields = new Dictionary<string, FieldInfo> ();
61
62                 static TypeSpec interactive_base_class;
63                 static Driver driver;
64                 static bool inited;
65
66                 static CompilerContext ctx;
67                 
68                 public static TextWriter MessageOutput = Console.Out;
69
70                 /// <summary>
71                 ///   Optional initialization for the Evaluator.
72                 /// </summary>
73                 /// <remarks>
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
77                 ///  ignored.
78                 ///
79                 ///  You can safely avoid calling this method if your application
80                 ///  does not need any of the features exposed by the command line
81                 ///  interface.
82                 /// </remarks>
83                 public static void Init (string [] args)
84                 {
85                         InitAndGetStartupFiles (args);
86                 }
87
88                 internal static ReportPrinter SetPrinter (ReportPrinter report_printer)
89                 {
90                         return ctx.Report.SetPrinter (report_printer);
91                 }                               
92
93                 /// <summary>
94                 ///   Optional initialization for the Evaluator.
95                 /// </summary>
96                 /// <remarks>
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.
102                 ///
103                 ///  You can safely avoid calling this method if your application
104                 ///  does not need any of the features exposed by the command line
105                 ///  interface.
106                 ///
107                 ///  This method return an array of strings that contains any
108                 ///  files that were specified in `args'.
109                 /// </remarks>
110                 public static string [] InitAndGetStartupFiles (string [] args)
111                 {
112                         lock (evaluator_lock){
113                                 if (inited)
114                                         return new string [0];
115                                 
116                                 driver = Driver.Create (args, false, new ConsoleReportPrinter ());
117                                 if (driver == null)
118                                         throw new Exception ("Failed to create compiler driver with the given arguments");
119
120                                 RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
121                                 
122                                 driver.ProcessDefaultConfig ();
123
124                                 var startup_files = new List<string> ();
125                                 foreach (CompilationUnit file in Location.SourceFiles)
126                                         startup_files.Add (file.Path);
127                                 
128                                 CompilerCallableEntryPoint.Reset ();
129                                 RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
130                                 /*var ctypes = */TypeManager.InitCoreTypes ();
131                                 TypeManager.InitExpressionTypes ();
132
133                                 Import.Initialize ();
134                                 driver.LoadReferences ();
135                                 TypeManager.InitOptionalCoreTypes (ctx);
136
137                                 RootContext.EvalMode = true;
138                                 inited = true;
139
140                                 return startup_files.ToArray ();
141                         }
142                 }
143
144                 static void Init ()
145                 {
146                         Init (new string [0]);
147                 }
148                 
149                 static void Reset ()
150                 {
151                         CompilerCallableEntryPoint.PartialReset ();
152                         RootContext.PartialReset ();
153                         
154                         // Workaround for API limitation where full message printer cannot be passed
155                         ReportPrinter printer;
156                         if (MessageOutput == Console.Out || MessageOutput == Console.Error){
157                                 var console_reporter = new ConsoleReportPrinter (MessageOutput);
158                                 console_reporter.Fatal = driver.fatal_errors;
159                                 printer = console_reporter;
160                         } else
161                                 printer = new StreamReportPrinter (MessageOutput);
162
163                         ctx = new CompilerContext (new Report (printer));
164                         RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
165
166                         //
167                         // PartialReset should not reset the core types, this is very redundant.
168                         //
169 //                      if (!TypeManager.InitCoreTypes (ctx, null))
170 //                              throw new Exception ("Failed to InitCoreTypes");
171 //                      TypeManager.InitOptionalCoreTypes (ctx);
172                         
173                         Location.AddFile (null, "{interactive}");
174                         Location.Initialize ();
175
176                         current_debug_name = "interactive" + (count++) + ".dll";
177                         if (Environment.GetEnvironmentVariable ("SAVE") != null){
178                                 CodeGen.Init (current_debug_name, current_debug_name, false, ctx);
179                         } else
180                                 CodeGen.InitDynamic (ctx, current_debug_name);
181                 }
182
183                 /// <summary>
184                 ///   The base class for the classes that host the user generated code
185                 /// </summary>
186                 /// <remarks>
187                 ///
188                 ///   This is the base class that will host the code
189                 ///   executed by the Evaluator.  By default
190                 ///   this is the Mono.CSharp.InteractiveBase class
191                 ///   which is useful for interactive use.
192                 ///
193                 ///   By changing this property you can control the
194                 ///   base class and the static members that are
195                 ///   available to your evaluated code.
196                 /// </remarks>
197                 static public TypeSpec InteractiveBaseClass {
198                         get {
199                                 if (interactive_base_class != null)
200                                         return interactive_base_class;
201
202                                 return Import.ImportType (typeof (InteractiveBase));
203                         }
204                 }
205
206                 public static void SetInteractiveBaseClass (Type type)
207                 {
208                         if (type == null)
209                                 throw new ArgumentNullException ();
210
211                         lock (evaluator_lock)
212                                 interactive_base_class = Import.ImportType (type);
213                 }
214
215                 /// <summary>
216                 ///   Interrupts the evaluation of an expression executing in Evaluate.
217                 /// </summary>
218                 /// <remarks>
219                 ///   Use this method to interrupt long-running invocations.
220                 /// </remarks>
221                 public static void Interrupt ()
222                 {
223                         if (!inited || !invoking)
224                                 return;
225                         
226                         if (invoke_thread != null)
227                                 invoke_thread.Abort ();
228                 }
229
230                 /// <summary>
231                 ///   Compiles the input string and returns a delegate that represents the compiled code.
232                 /// </summary>
233                 /// <remarks>
234                 ///
235                 ///   Compiles the input string as a C# expression or
236                 ///   statement, unlike the Evaluate method, the
237                 ///   resulting delegate can be invoked multiple times
238                 ///   without incurring in the compilation overhead.
239                 ///
240                 ///   If the return value of this function is null,
241                 ///   this indicates that the parsing was complete.
242                 ///   If the return value is a string it indicates
243                 ///   that the input string was partial and that the
244                 ///   invoking code should provide more code before
245                 ///   the code can be successfully compiled.
246                 ///
247                 ///   If you know that you will always get full expressions or
248                 ///   statements and do not care about partial input, you can use
249                 ///   the other Compile overload. 
250                 ///
251                 ///   On success, in addition to returning null, the
252                 ///   compiled parameter will be set to the delegate
253                 ///   that can be invoked to execute the code.
254                 ///
255                 /// </remarks>
256                 static public string Compile (string input, out CompiledMethod compiled)
257                 {
258                         if (input == null || input.Length == 0){
259                                 compiled = null;
260                                 return null;
261                         }
262                         
263                         lock (evaluator_lock){
264                                 if (!inited)
265                                         Init ();
266                                 
267                                 bool partial_input;
268                                 CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
269                                 if (parser == null){
270                                         compiled = null;
271                                         if (partial_input)
272                                                 return input;
273                                         
274                                         ParseString (ParseMode.ReportErrors, input, out partial_input);
275                                         return null;
276                                 }
277                                 
278                                 object parser_result = parser.InteractiveResult;
279                                 
280                                 if (!(parser_result is Class)){
281                                         int errors = ctx.Report.Errors;
282                                         
283                                         NamespaceEntry.VerifyAllUsing ();
284                                         if (errors == ctx.Report.Errors)
285                                                 parser.CurrentNamespace.Extract (using_alias_list, using_list);
286                                 }
287
288                                 compiled = CompileBlock (parser_result as Class, parser.undo, ctx.Report);
289                         }
290                         
291                         return null;
292                 }
293
294                 /// <summary>
295                 ///   Compiles the input string and returns a delegate that represents the compiled code.
296                 /// </summary>
297                 /// <remarks>
298                 ///
299                 ///   Compiles the input string as a C# expression or
300                 ///   statement, unlike the Evaluate method, the
301                 ///   resulting delegate can be invoked multiple times
302                 ///   without incurring in the compilation overhead.
303                 ///
304                 ///   This method can only deal with fully formed input
305                 ///   strings and does not provide a completion mechanism.
306                 ///   If you must deal with partial input (for example for
307                 ///   interactive use) use the other overload. 
308                 ///
309                 ///   On success, a delegate is returned that can be used
310                 ///   to invoke the method.
311                 ///
312                 /// </remarks>
313                 static public CompiledMethod Compile (string input)
314                 {
315                         CompiledMethod compiled;
316
317                         // Ignore partial inputs
318                         if (Compile (input, out compiled) != null){
319                                 // Error, the input was partial.
320                                 return null;
321                         }
322
323                         // Either null (on error) or the compiled method.
324                         return compiled;
325                 }
326
327                 //
328                 // Todo: Should we handle errors, or expect the calling code to setup
329                 // the recording themselves?
330                 //
331
332                 /// <summary>
333                 ///   Evaluates and expression or statement and returns any result values.
334                 /// </summary>
335                 /// <remarks>
336                 ///   Evaluates the input string as a C# expression or
337                 ///   statement.  If the input string is an expression
338                 ///   the result will be stored in the result variable
339                 ///   and the result_set variable will be set to true.
340                 ///
341                 ///   It is necessary to use the result/result_set
342                 ///   pair to identify when a result was set (for
343                 ///   example, execution of user-provided input can be
344                 ///   an expression, a statement or others, and
345                 ///   result_set would only be set if the input was an
346                 ///   expression.
347                 ///
348                 ///   If the return value of this function is null,
349                 ///   this indicates that the parsing was complete.
350                 ///   If the return value is a string, it indicates
351                 ///   that the input is partial and that the user
352                 ///   should provide an updated string.
353                 /// </remarks>
354                 public static string Evaluate (string input, out object result, out bool result_set)
355                 {
356                         CompiledMethod compiled;
357
358                         result_set = false;
359                         result = null;
360
361                         input = Compile (input, out compiled);
362                         if (input != null)
363                                 return input;
364                         
365                         if (compiled == null)
366                                 return null;
367                                 
368                         //
369                         // The code execution does not need to keep the compiler lock
370                         //
371                         object retval = typeof (NoValueSet);
372
373                         try {
374                                 invoke_thread = System.Threading.Thread.CurrentThread;
375                                 invoking = true;
376                                 compiled (ref retval);
377                         } catch (ThreadAbortException e){
378                                 Thread.ResetAbort ();
379                                 Console.WriteLine ("Interrupted!\n{0}", e);
380                         } finally {
381                                 invoking = false;
382                         }
383
384                         //
385                         // We use a reference to a compiler type, in this case
386                         // Driver as a flag to indicate that this was a statement
387                         //
388                         if (retval != typeof (NoValueSet)){
389                                 result_set = true;
390                                 result = retval; 
391                         }
392
393                         return null;
394                 }
395
396                 public static string [] GetCompletions (string input, out string prefix)
397                 {
398                         prefix = "";
399                         if (input == null || input.Length == 0)
400                                 return null;
401                         
402                         lock (evaluator_lock){
403                                 if (!inited)
404                                         Init ();
405                                 
406                                 bool partial_input;
407                                 CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
408                                 if (parser == null){
409                                         if (CSharpParser.yacc_verbose_flag != 0)
410                                                 Console.WriteLine ("DEBUG: No completions available");
411                                         return null;
412                                 }
413                                 
414                                 Class parser_result = parser.InteractiveResult as Class;
415                                 
416                                 if (parser_result == null){
417                                         if (CSharpParser.yacc_verbose_flag != 0)
418                                                 Console.WriteLine ("Do not know how to cope with !Class yet");
419                                         return null;
420                                 }
421
422                                 try {
423                                         RootContext.ResolveTree ();
424                                         if (ctx.Report.Errors != 0)
425                                                 return null;
426                                         
427                                         RootContext.PopulateTypes ();
428                                         if (ctx.Report.Errors != 0)
429                                                 return null;
430
431                                         MethodOrOperator method = null;
432                                         foreach (MemberCore member in parser_result.Methods){
433                                                 if (member.Name != "Host")
434                                                         continue;
435                                                 
436                                                 method = (MethodOrOperator) member;
437                                                 break;
438                                         }
439                                         if (method == null)
440                                                 throw new InternalErrorException ("did not find the the Host method");
441
442                                         BlockContext bc = new BlockContext (method, method.Block, method.ReturnType);
443
444                                         try {
445                                                 method.Block.Resolve (null, bc, method.ParameterInfo, method);
446                                         } catch (CompletionResult cr){
447                                                 prefix = cr.BaseText;
448                                                 return cr.Result;
449                                         } 
450                                 } finally {
451                                         parser.undo.ExecuteUndo ();
452                                 }
453                                 
454                         }
455                         return null;
456                 }
457                 
458                 /// <summary>
459                 ///   Executes the given expression or statement.
460                 /// </summary>
461                 /// <remarks>
462                 ///    Executes the provided statement, returns true
463                 ///    on success, false on parsing errors.  Exceptions
464                 ///    might be thrown by the called code.
465                 /// </remarks>
466                 public static bool Run (string statement)
467                 {
468                         if (!inited)
469                                 Init ();
470
471                         object result;
472                         bool result_set;
473
474                         bool ok = Evaluate (statement, out result, out result_set) == null;
475                         
476                         return ok;
477                 }
478
479                 /// <summary>
480                 ///   Evaluates and expression or statement and returns the result.
481                 /// </summary>
482                 /// <remarks>
483                 ///   Evaluates the input string as a C# expression or
484                 ///   statement and returns the value.   
485                 ///
486                 ///   This method will throw an exception if there is a syntax error,
487                 ///   of if the provided input is not an expression but a statement.
488                 /// </remarks>
489                 public static object Evaluate (string input)
490                 {
491                         object result;
492                         bool result_set;
493                         
494                         string r = Evaluate (input, out result, out result_set);
495
496                         if (r != null)
497                                 throw new ArgumentException ("Syntax error on input: partial input");
498                         
499                         if (result_set == false)
500                                 throw new ArgumentException ("The expression did not set a result");
501
502                         return result;
503                 }
504         
505                 enum InputKind {
506                         EOF,
507                         StatementOrExpression,
508                         CompilationUnit,
509                         Error
510                 }
511
512                 //
513                 // Deambiguates the input string to determine if we
514                 // want to process a statement or if we want to
515                 // process a compilation unit.
516                 //
517                 // This is done using a top-down predictive parser,
518                 // since the yacc/jay parser can not deambiguage this
519                 // without more than one lookahead token.   There are very
520                 // few ambiguities.
521                 //
522                 static InputKind ToplevelOrStatement (SeekableStreamReader seekable)
523                 {
524                         Tokenizer tokenizer = new Tokenizer (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
525                         
526                         int t = tokenizer.token ();
527                         switch (t){
528                         case Token.EOF:
529                                 return InputKind.EOF;
530                                 
531                         // These are toplevels
532                         case Token.EXTERN:
533                         case Token.OPEN_BRACKET:
534                         case Token.ABSTRACT:
535                         case Token.CLASS:
536                         case Token.ENUM:
537                         case Token.INTERFACE:
538                         case Token.INTERNAL:
539                         case Token.NAMESPACE:
540                         case Token.PRIVATE:
541                         case Token.PROTECTED:
542                         case Token.PUBLIC:
543                         case Token.SEALED:
544                         case Token.STATIC:
545                         case Token.STRUCT:
546                                 return InputKind.CompilationUnit;
547                                 
548                         // Definitely expression
549                         case Token.FIXED:
550                         case Token.BOOL:
551                         case Token.BYTE:
552                         case Token.CHAR:
553                         case Token.DECIMAL:
554                         case Token.DOUBLE:
555                         case Token.FLOAT:
556                         case Token.INT:
557                         case Token.LONG:
558                         case Token.NEW:
559                         case Token.OBJECT:
560                         case Token.SBYTE:
561                         case Token.SHORT:
562                         case Token.STRING:
563                         case Token.UINT:
564                         case Token.ULONG:
565                                 return InputKind.StatementOrExpression;
566
567                         // These need deambiguation help
568                         case Token.USING:
569                                 t = tokenizer.token ();
570                                 if (t == Token.EOF)
571                                         return InputKind.EOF;
572
573                                 if (t == Token.IDENTIFIER)
574                                         return InputKind.CompilationUnit;
575                                 return InputKind.StatementOrExpression;
576
577
578                         // Distinguish between:
579                         //    delegate opt_anonymous_method_signature block
580                         //    delegate type 
581                         case Token.DELEGATE:
582                                 t = tokenizer.token ();
583                                 if (t == Token.EOF)
584                                         return InputKind.EOF;
585                                 if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
586                                         return InputKind.StatementOrExpression;
587                                 return InputKind.CompilationUnit;
588
589                         // Distinguih between:
590                         //    unsafe block
591                         //    unsafe as modifier of a type declaration
592                         case Token.UNSAFE:
593                                 t = tokenizer.token ();
594                                 if (t == Token.EOF)
595                                         return InputKind.EOF;
596                                 if (t == Token.OPEN_PARENS)
597                                         return InputKind.StatementOrExpression;
598                                 return InputKind.CompilationUnit;
599                                 
600                         // These are errors: we list explicitly what we had
601                         // from the grammar, ERROR and then everything else
602
603                         case Token.READONLY:
604                         case Token.OVERRIDE:
605                         case Token.ERROR:
606                                 return InputKind.Error;
607
608                         // This catches everything else allowed by
609                         // expressions.  We could add one-by-one use cases
610                         // if needed.
611                         default:
612                                 return InputKind.StatementOrExpression;
613                         }
614                 }
615                 
616                 //
617                 // Parses the string @input and returns a CSharpParser if succeeful.
618                 //
619                 // if @silent is set to true then no errors are
620                 // reported to the user.  This is used to do various calls to the
621                 // parser and check if the expression is parsable.
622                 //
623                 // @partial_input: if @silent is true, then it returns whether the
624                 // parsed expression was partial, and more data is needed
625                 //
626                 static CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
627                 {
628                         partial_input = false;
629                         Reset ();
630                         queued_fields.Clear ();
631                         Tokenizer.LocatedToken.Initialize ();
632
633                         Stream s = new MemoryStream (Encoding.Default.GetBytes (input));
634                         SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default);
635
636                         InputKind kind = ToplevelOrStatement (seekable);
637                         if (kind == InputKind.Error){
638                                 if (mode == ParseMode.ReportErrors)
639                                         ctx.Report.Error (-25, "Detection Parsing Error");
640                                 partial_input = false;
641                                 return null;
642                         }
643
644                         if (kind == InputKind.EOF){
645                                 if (mode == ParseMode.ReportErrors)
646                                         Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
647                                 partial_input = true;
648                                 return null;
649                                 
650                         }
651                         seekable.Position = 0;
652
653                         CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0], ctx);
654
655                         if (kind == InputKind.StatementOrExpression){
656                                 parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
657                                 RootContext.StatementMode = true;
658                         } else {
659                                 //
660                                 // Do not activate EvalCompilationUnitParserCharacter until
661                                 // I have figured out all the limitations to invoke methods
662                                 // in the generated classes.  See repl.txt
663                                 //
664                                 parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
665                                 //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
666                                 RootContext.StatementMode = false;
667                         }
668
669                         if (mode == ParseMode.GetCompletions)
670                                 parser.Lexer.CompleteOnEOF = true;
671
672                         ReportPrinter old_printer = null;
673                         if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0)
674                                 old_printer = SetPrinter (new StreamReportPrinter (TextWriter.Null));
675
676                         try {
677                                 parser.parse ();
678                         } finally {
679                                 if (ctx.Report.Errors != 0){
680                                         if (mode != ParseMode.ReportErrors  && parser.UnexpectedEOF)
681                                                 partial_input = true;
682
683                                         parser.undo.ExecuteUndo ();
684                                         parser = null;
685                                 }
686
687                                 if (old_printer != null)
688                                         SetPrinter (old_printer);
689                         }
690                         return parser;
691                 }
692
693                 //
694                 // Queue all the fields that we use, as we need to then go from FieldBuilder to FieldInfo
695                 // or reflection gets confused (it basically gets confused, and variables override each
696                 // other).
697                 //
698                 static List<Field> queued_fields = new List<Field> ();
699                 
700                 //static ArrayList types = new ArrayList ();
701
702                 static volatile bool invoking;
703                 
704                 static CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
705                 {
706                         RootContext.ResolveTree ();
707                         if (Report.Errors != 0){
708                                 undo.ExecuteUndo ();
709                                 return null;
710                         }
711                         
712                         RootContext.PopulateTypes ();
713
714                         if (Report.Errors != 0){
715                                 undo.ExecuteUndo ();
716                                 return null;
717                         }
718
719                         TypeBuilder tb = null;
720                         MethodBuilder mb = null;
721                                 
722                         if (host != null){
723                                 tb = host.TypeBuilder;
724                                 mb = null;
725                                 foreach (MemberCore member in host.Methods){
726                                         if (member.Name != "Host")
727                                                 continue;
728                                         
729                                         MethodOrOperator method = (MethodOrOperator) member;
730                                         mb = method.MethodBuilder;
731                                         break;
732                                 }
733
734                                 if (mb == null)
735                                         throw new Exception ("Internal error: did not find the method builder for the generated method");
736                         }
737                         
738                         RootContext.EmitCode ();
739                         if (Report.Errors != 0){
740                                 undo.ExecuteUndo ();
741                                 return null;
742                         }
743                         
744                         RootContext.CloseTypes ();
745
746                         if (Environment.GetEnvironmentVariable ("SAVE") != null)
747                                 CodeGen.Save (current_debug_name, false, Report);
748
749                         if (host == null)
750                                 return null;
751                         
752                         //
753                         // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
754                         // work from MethodBuilders.   Retarded, I know.
755                         //
756                         var tt = CodeGen.Assembly.Builder.GetType (tb.Name);
757                         MethodInfo mi = tt.GetMethod (mb.Name);
758                         
759                         // Pull the FieldInfos from the type, and keep track of them
760                         foreach (Field field in queued_fields){
761                                 FieldInfo fi = tt.GetField (field.Name);
762                                 
763                                 FieldInfo old;
764                                 
765                                 // If a previous value was set, nullify it, so that we do
766                                 // not leak memory
767                                 if (fields.TryGetValue (field.Name, out old)){
768                                         if (old.FieldType.IsValueType){
769                                                 //
770                                                 // TODO: Clear fields for structs
771                                                 //
772                                         } else {
773                                                 try {
774                                                         old.SetValue (null, null);
775                                                 } catch {
776                                                 }
777                                         }
778                                 }
779                                 
780                                 fields [field.Name] = fi;
781                         }
782                         //types.Add (tb);
783
784                         queued_fields.Clear ();
785                         
786                         return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
787                 }
788                 
789                 static internal void LoadAliases (NamespaceEntry ns)
790                 {
791                         ns.Populate (using_alias_list, using_list);
792                 }
793                 
794                 /// <summary>
795                 ///   A sentinel value used to indicate that no value was
796                 ///   was set by the compiled function.   This is used to
797                 ///   differentiate between a function not returning a
798                 ///   value and null.
799                 /// </summary>
800                 public class NoValueSet {
801                 }
802
803                 static internal FieldInfo LookupField (string name)
804                 {
805                         FieldInfo fi;
806                         if (!fields.TryGetValue (name, out fi))
807                                 return null;
808
809                         return fi;
810                 }
811
812                 //
813                 // Puts the FieldBuilder into a queue of names that will be
814                 // registered.   We can not register FieldBuilders directly
815                 // we need to fetch the FieldInfo after Reflection cooks the
816                 // types, or bad things happen (bad means: FieldBuilders behave
817                 // incorrectly across multiple assemblies, causing assignments to
818                 // invalid areas
819                 //
820                 // This also serves for the parser to register Field classes
821                 // that should be exposed as global variables
822                 //
823                 static internal void QueueField (Field f)
824                 {
825                         queued_fields.Add (f);
826                 }
827
828                 static string Quote (string s)
829                 {
830                         if (s.IndexOf ('"') != -1)
831                                 s = s.Replace ("\"", "\\\"");
832                         
833                         return "\"" + s + "\"";
834                 }
835
836                 static public string GetUsing ()
837                 {
838                         lock (evaluator_lock){
839                                 StringBuilder sb = new StringBuilder ();
840                                 
841                                 foreach (object x in using_alias_list)
842                                         sb.Append (String.Format ("using {0};\n", x));
843                                 
844                                 foreach (object x in using_list)
845                                         sb.Append (String.Format ("using {0};\n", x));
846                                 
847                                 return sb.ToString ();
848                         }
849                 }
850
851                 static internal ICollection<string> GetUsingList ()
852                 {
853                         var res = new List<string> (using_list.Count);
854                         foreach (object ue in using_list)
855                                 res.Add (ue.ToString ());
856                         return res;
857                 }
858                 
859                 static internal string [] GetVarNames ()
860                 {
861                         lock (evaluator_lock){
862                                 return new List<string> (fields.Keys).ToArray ();
863                         }
864                 }
865                 
866                 static public string GetVars ()
867                 {
868                         lock (evaluator_lock){
869                                 StringBuilder sb = new StringBuilder ();
870                                 
871                                 foreach (var de in fields){
872                                         FieldInfo fi = LookupField (de.Key);
873                                         object value = null;
874                                         //bool error = false;
875                                         
876                                         try {
877                                                 if (value == null)
878                                                         value = "null";
879                                                 value = fi.GetValue (null);
880                                                 if (value is string)
881                                                         value = Quote ((string)value);
882                                         } catch {
883                                                 //error = true;
884                                         }
885
886                                         throw new NotImplementedException ("net");
887                                         //if (error)
888                                         //    sb.Append (String.Format ("{0} {1} <error reading value>", TypeManager.CSharpName(fi.FieldType), de.Key));
889                                         //else
890                                         //    sb.Append (String.Format ("{0} {1} = {2}", TypeManager.CSharpName(fi.FieldType), de.Key, value));
891                                 }
892                                 
893                                 return sb.ToString ();
894                         }
895                 }
896
897                 /// <summary>
898                 ///    Loads the given assembly and exposes the API to the user.
899                 /// </summary>
900                 static public void LoadAssembly (string file)
901                 {
902                         lock (evaluator_lock){
903                                 driver.LoadAssembly (file, false);
904                                 GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
905                         }
906                 }
907
908                 /// <summary>
909                 ///    Exposes the API of the given assembly to the Evaluator
910                 /// </summary>
911                 static public void ReferenceAssembly (Assembly a)
912                 {
913                         lock (evaluator_lock){
914 //                              GlobalRootNamespace.Instance.AddAssemblyReference (a);
915 //                              GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
916                                 GlobalRootNamespace.Instance.ImportAssembly (a);
917                         }
918                 }
919
920                 /// <summary>
921                 ///   If true, turns type expressions into valid expressions
922                 ///   and calls the describe method on it
923                 /// </summary>
924                 public static bool DescribeTypeExpressions;
925         }
926
927         
928         /// <summary>
929         ///   A delegate that can be used to invoke the
930         ///   compiled expression or statement.
931         /// </summary>
932         /// <remarks>
933         ///   Since the Compile methods will compile
934         ///   statements and expressions into the same
935         ///   delegate, you can tell if a value was returned
936         ///   by checking whether the returned value is of type
937         ///   NoValueSet.   
938         /// </remarks>
939         
940         public delegate void CompiledMethod (ref object retvalue);
941
942         /// <summary>
943         ///   The default base class for every interaction line
944         /// </summary>
945         /// <remarks>
946         ///   The expressions and statements behave as if they were
947         ///   a static method of this class.   The InteractiveBase class
948         ///   contains a number of useful methods, but can be overwritten
949         ///   by setting the InteractiveBaseType property in the Evaluator
950         /// </remarks>
951         public class InteractiveBase {
952                 /// <summary>
953                 ///   Determines where the standard output of methods in this class will go. 
954                 /// </summary>
955                 public static TextWriter Output = Console.Out;
956
957                 /// <summary>
958                 ///   Determines where the standard error of methods in this class will go. 
959                 /// </summary>
960                 public static TextWriter Error = Console.Error;
961
962                 /// <summary>
963                 ///   The primary prompt used for interactive use.
964                 /// </summary>
965                 public static string Prompt             = "csharp> ";
966
967                 /// <summary>
968                 ///   The secondary prompt used for interactive use (used when
969                 ///   an expression is incomplete).
970                 /// </summary>
971                 public static string ContinuationPrompt = "      > ";
972
973                 /// <summary>
974                 ///   Used to signal that the user has invoked the  `quit' statement.
975                 /// </summary>
976                 public static bool QuitRequested;
977                 
978                 /// <summary>
979                 ///   Shows all the variables defined so far.
980                 /// </summary>
981                 static public void ShowVars ()
982                 {
983                         Output.Write (Evaluator.GetVars ());
984                         Output.Flush ();
985                 }
986
987                 /// <summary>
988                 ///   Displays the using statements in effect at this point. 
989                 /// </summary>
990                 static public void ShowUsing ()
991                 {
992                         Output.Write (Evaluator.GetUsing ());
993                         Output.Flush ();
994                 }
995
996                 public delegate void Simple ();
997                 
998                 /// <summary>
999                 ///   Times the execution of the given delegate
1000                 /// </summary>
1001                 static public TimeSpan Time (Simple a)
1002                 {
1003                         DateTime start = DateTime.Now;
1004                         a ();
1005                         return DateTime.Now - start;
1006                 }
1007                 
1008 #if !SMCS_SOURCE
1009                 /// <summary>
1010                 ///   Loads the assemblies from a package
1011                 /// </summary>
1012                 /// <remarks>
1013                 ///   Loads the assemblies from a package.   This is equivalent
1014                 ///   to passing the -pkg: command line flag to the C# compiler
1015                 ///   on the command line. 
1016                 /// </remarks>
1017                 static public void LoadPackage (string pkg)
1018                 {
1019                         if (pkg == null){
1020                                 Error.WriteLine ("Invalid package specified");
1021                                 return;
1022                         }
1023
1024                         string pkgout = Driver.GetPackageFlags (pkg, false, RootContext.ToplevelTypes.Compiler.Report);
1025                         if (pkgout == null)
1026                                 return;
1027
1028                         string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1029                                 Split (new Char [] { ' ', '\t'});
1030
1031                         foreach (string s in xargs){
1032                                 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
1033                                         string lib = s.Substring (s.IndexOf (':')+1);
1034
1035                                         Evaluator.LoadAssembly (lib);
1036                                         continue;
1037                                 }
1038                         }
1039                 }
1040 #endif
1041
1042                 /// <summary>
1043                 ///   Loads the assembly
1044                 /// </summary>
1045                 /// <remarks>
1046                 ///   Loads the specified assembly and makes its types
1047                 ///   available to the evaluator.  This is equivalent
1048                 ///   to passing the -pkg: command line flag to the C#
1049                 ///   compiler on the command line.
1050                 /// </remarks>
1051                 static public void LoadAssembly (string assembly)
1052                 {
1053                         Evaluator.LoadAssembly (assembly);
1054                 }
1055                 
1056                 /// <summary>
1057                 ///   Returns a list of available static methods. 
1058                 /// </summary>
1059                 static public string help {
1060                         get {
1061                                 return  "Static methods:\n"+
1062                                         "  Describe(obj)      - Describes the object's type\n" + 
1063                                         "  LoadPackage (pkg); - Loads the given Package (like -pkg:FILE)\n" +
1064                                         "  LoadAssembly (ass) - Loads the given assembly (like -r:ASS)\n" + 
1065                                         "  ShowVars ();       - Shows defined local variables.\n" +
1066                                         "  ShowUsing ();      - Show active using decltions.\n" +
1067                                         "  Prompt             - The prompt used by the C# shell\n" +
1068                                         "  ContinuationPrompt - The prompt for partial input\n" +
1069                                         "  Time(() -> { })    - Times the specified code\n" +
1070                                         "  quit;\n" +
1071                                         "  help;\n";
1072                         }
1073                 }
1074
1075                 /// <summary>
1076                 ///   Indicates to the read-eval-print-loop that the interaction should be finished. 
1077                 /// </summary>
1078                 static public object quit {
1079                         get {
1080                                 QuitRequested = true;
1081                                 return null;
1082                         }
1083                 }
1084
1085 #if !NET_2_1
1086                 /// <summary>
1087                 ///   Describes an object or a type.
1088                 /// </summary>
1089                 /// <remarks>
1090                 ///   This method will show a textual representation
1091                 ///   of the object's type.  If the object is a
1092                 ///   System.Type it renders the type directly,
1093                 ///   otherwise it renders the type returned by
1094                 ///   invoking GetType on the object.
1095                 /// </remarks>
1096                 static public string Describe (object x)
1097                 {
1098                         if (x == null)
1099                                 return "";
1100                         
1101                         TypeSpec t = x as TypeSpec;
1102 //                      if (t == null)
1103 //                              t = x.GetType ();
1104
1105                         StringWriter sw = new StringWriter ();
1106                         new Outline (t.GetMetaInfo (), sw, true, false, false).OutlineType ();
1107                         return sw.ToString ();
1108                 }
1109 #endif
1110         }
1111
1112         //
1113         // A local variable reference that will create a Field in a
1114         // Class with the resolved type.  This is necessary so we can
1115         // support "var" as a field type in a class declaration.
1116         //
1117         // We allow LocalVariableReferece to do the heavy lifting, and
1118         // then we insert the field with the resolved type
1119         //
1120         public class LocalVariableReferenceWithClassSideEffect : LocalVariableReference {
1121                 TypeContainer container;
1122                 string name;
1123                 
1124                 public LocalVariableReferenceWithClassSideEffect (TypeContainer container, string name, Block current_block, string local_variable_id, LocalInfo li, Location loc)
1125                         : base (current_block, local_variable_id, loc, li, false)
1126                 {
1127                         this.container = container;
1128                         this.name = name;
1129                 }
1130
1131                 public override bool Equals (object obj)
1132                 {
1133                         LocalVariableReferenceWithClassSideEffect lvr = obj as LocalVariableReferenceWithClassSideEffect;
1134                         if (lvr == null)
1135                                 return false;
1136
1137                         if (lvr.name != name || lvr.container != container)
1138                                 return false;
1139
1140                         return base.Equals (obj);
1141                 }
1142
1143                 public override int GetHashCode ()
1144                 {
1145                         return name.GetHashCode ();
1146                 }
1147                 
1148                 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
1149                 {
1150                         Expression ret = base.DoResolveLValue (ec, right_side);
1151                         if (ret == null)
1152                                 return null;
1153
1154                         Field f = new Field (container, new TypeExpression (ret.Type, Location),
1155                                              Modifiers.PUBLIC | Modifiers.STATIC,
1156                                              new MemberName (name, Location), null);
1157                         container.AddField (f);
1158                         if (f.Define ())
1159                                 Evaluator.QueueField (f);
1160                         
1161                         return ret;
1162                 }
1163         }
1164
1165         /// <summary>
1166         ///    A class used to assign values if the source expression is not void
1167         ///
1168         ///    Used by the interactive shell to allow it to call this code to set
1169         ///    the return value for an invocation.
1170         /// </summary>
1171         class OptionalAssign : SimpleAssign {
1172                 public OptionalAssign (Expression t, Expression s, Location loc)
1173                         : base (t, s, loc)
1174                 {
1175                 }
1176
1177                 protected override Expression DoResolve (ResolveContext ec)
1178                 {
1179                         CloneContext cc = new CloneContext ();
1180                         Expression clone = source.Clone (cc);
1181
1182                         //
1183                         // A useful feature for the REPL: if we can resolve the expression
1184                         // as a type, Describe the type;
1185                         //
1186                         if (Evaluator.DescribeTypeExpressions){
1187                                 var old_printer = Evaluator.SetPrinter (new StreamReportPrinter (TextWriter.Null));
1188                                 clone = clone.Resolve (ec);
1189                                 if (clone == null){
1190                                         clone = source.Clone (cc);
1191                                         clone = clone.Resolve (ec, ResolveFlags.Type);
1192                                         if (clone == null){
1193                                                 Evaluator.SetPrinter (old_printer);
1194                                                 clone = source.Clone (cc);
1195                                                 clone = clone.Resolve (ec);
1196                                                 return null;
1197                                         }
1198                                         
1199                                         Arguments args = new Arguments (1);
1200                                         args.Add (new Argument (new TypeOf (source, Location)));
1201                                         source = new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1202                                 }
1203                                 Evaluator.SetPrinter (old_printer);
1204                         } else {
1205                                 clone = clone.Resolve (ec);
1206                                 if (clone == null)
1207                                         return null;
1208                         }
1209         
1210                         // This means its really a statement.
1211                         if (clone.Type == TypeManager.void_type){
1212                                 source = source.Resolve (ec);
1213                                 target = null;
1214                                 type = TypeManager.void_type;
1215                                 eclass = ExprClass.Value;
1216                                 return this;
1217                         }
1218
1219                         return base.DoResolve (ec);
1220                 }
1221
1222                 public override void Emit (EmitContext ec)
1223                 {
1224                         if (target == null)
1225                                 source.Emit (ec);
1226                         else
1227                                 base.Emit (ec);
1228                 }
1229
1230                 public override void EmitStatement (EmitContext ec)
1231                 {
1232                         if (target == null)
1233                                 source.Emit (ec);
1234                         else
1235                                 base.EmitStatement (ec);
1236                 }
1237         }
1238
1239         public class Undo {
1240                 List<KeyValuePair<TypeContainer, TypeContainer>> undo_types;
1241                 
1242                 public Undo ()
1243                 {
1244                         undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1245                 }
1246
1247                 public void AddTypeContainer (TypeContainer current_container, TypeContainer tc)
1248                 {
1249                         if (current_container == tc){
1250                                 Console.Error.WriteLine ("Internal error: inserting container into itself");
1251                                 return;
1252                         }
1253
1254                         if (undo_types == null)
1255                                 undo_types = new List<KeyValuePair<TypeContainer, TypeContainer>> ();
1256
1257                         undo_types.Add (new KeyValuePair<TypeContainer, TypeContainer> (current_container, tc));
1258                 }
1259
1260                 public void ExecuteUndo ()
1261                 {
1262                         if (undo_types == null)
1263                                 return;
1264
1265                         foreach (var p in undo_types){
1266                                 TypeContainer current_container = p.Key;
1267
1268                                 current_container.RemoveTypeContainer (p.Value);
1269                         }
1270                         undo_types = null;
1271                 }
1272         }
1273         
1274 }
1275