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