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