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