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