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