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