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