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