Merge pull request #347 from JamesB7/master
[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);
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);
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                         source_file.EnableUsingClausesRedefinition ();
660                         module.Define ();
661
662                         if (Report.Errors != 0){
663                                 if (undo != null)
664                                         undo.ExecuteUndo ();
665
666                                 return null;
667                         }
668
669                         if (host != null){
670                                 host.EmitContainer ();
671                         }
672                         
673                         module.EmitContainer ();
674                         if (Report.Errors != 0){
675                                 if (undo != null)
676                                         undo.ExecuteUndo ();
677                                 return null;
678                         }
679
680                         module.CloseContainer ();
681                         if (host != null)
682                                 host.CloseContainer ();
683
684                         if (access == AssemblyBuilderAccess.RunAndSave)
685                                 assembly.Save ();
686
687                         if (host == null)
688                                 return null;
689                         
690                         //
691                         // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
692                         // work from MethodBuilders.   Retarded, I know.
693                         //
694                         var tt = assembly.Builder.GetType (host.TypeBuilder.Name);
695                         var mi = tt.GetMethod (expression_method.MemberName.Name);
696
697                         //
698                         // We need to then go from FieldBuilder to FieldInfo
699                         // or reflection gets confused (it basically gets confused, and variables override each
700                         // other).
701                         //
702                         foreach (var member in host.Members) {
703                                 var field = member as Field;
704                                 if (field == null)
705                                         continue;
706
707                                 var fi = tt.GetField (field.Name);
708
709                                 Tuple<FieldSpec, FieldInfo> old;
710
711                                 // If a previous value was set, nullify it, so that we do
712                                 // not leak memory
713                                 if (fields.TryGetValue (field.Name, out old)) {
714                                         if (old.Item1.MemberType.IsStruct) {
715                                                 //
716                                                 // TODO: Clear fields for structs
717                                                 //
718                                         } else {
719                                                 try {
720                                                         old.Item2.SetValue (null, null);
721                                                 } catch {
722                                                 }
723                                         }
724                                 }
725
726                                 fields[field.Name] = Tuple.Create (field.Spec, fi);
727                         }
728                         
729                         return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
730 #endif
731                 }
732
733                 /// <summary>
734                 ///   A sentinel value used to indicate that no value was
735                 ///   was set by the compiled function.   This is used to
736                 ///   differentiate between a function not returning a
737                 ///   value and null.
738                 /// </summary>
739                 internal static class QuitValue { }
740
741                 internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
742                 {
743                         Tuple<FieldSpec, FieldInfo> fi;
744                         fields.TryGetValue (name, out fi);
745                         return fi;
746                 }
747
748                 static string Quote (string s)
749                 {
750                         if (s.IndexOf ('"') != -1)
751                                 s = s.Replace ("\"", "\\\"");
752                         
753                         return "\"" + s + "\"";
754                 }
755
756                 public string GetUsing ()
757                 {
758                         StringBuilder sb = new StringBuilder ();
759                         // TODO:
760                         //foreach (object x in ns.using_alias_list)
761                         //    sb.AppendFormat ("using {0};\n", x);
762
763                         foreach (var ue in source_file.Usings) {
764                                 sb.AppendFormat ("using {0};", ue.ToString ());
765                                 sb.Append (Environment.NewLine);
766                         }
767
768                         return sb.ToString ();
769                 }
770
771                 internal List<string> GetUsingList ()
772                 {
773                         var res = new List<string> ();
774
775                         foreach (var ue in source_file.Usings) {
776                                 if (ue.Alias != null || ue.ResolvedExpression == null)
777                                         continue;
778
779                                 res.Add (ue.NamespaceExpression.Name);
780                         }
781
782                         return res;
783                 }
784                 
785                 internal string [] GetVarNames ()
786                 {
787                         lock (evaluator_lock){
788                                 return new List<string> (fields.Keys).ToArray ();
789                         }
790                 }
791                 
792                 public string GetVars ()
793                 {
794                         lock (evaluator_lock){
795                                 StringBuilder sb = new StringBuilder ();
796                                 
797                                 foreach (var de in fields){
798                                         var fi = LookupField (de.Key);
799                                         object value;
800                                         try {
801                                                 value = fi.Item2.GetValue (null);
802                                                 if (value is string)
803                                                         value = Quote ((string)value);
804                                         } catch {
805                                                 value = "<error reading value>";
806                                         }
807
808                                         sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
809                                         sb.AppendLine ();
810                                 }
811                                 
812                                 return sb.ToString ();
813                         }
814                 }
815
816                 /// <summary>
817                 ///    Loads the given assembly and exposes the API to the user.
818                 /// </summary>
819                 public void LoadAssembly (string file)
820                 {
821                         var loader = new DynamicLoader (importer, ctx);
822                         var assembly = loader.LoadAssemblyFile (file, false);
823                         if (assembly == null)
824                                 return;
825
826                         lock (evaluator_lock){
827                                 importer.ImportAssembly (assembly, module.GlobalRootNamespace);
828                         }
829                 }
830
831                 /// <summary>
832                 ///    Exposes the API of the given assembly to the Evaluator
833                 /// </summary>
834                 public void ReferenceAssembly (Assembly a)
835                 {
836                         lock (evaluator_lock){
837                                 importer.ImportAssembly (a, module.GlobalRootNamespace);
838                         }
839                 }
840         }
841
842         
843         /// <summary>
844         ///   A delegate that can be used to invoke the
845         ///   compiled expression or statement.
846         /// </summary>
847         /// <remarks>
848         ///   Since the Compile methods will compile
849         ///   statements and expressions into the same
850         ///   delegate, you can tell if a value was returned
851         ///   by checking whether the returned value is of type
852         ///   NoValueSet.   
853         /// </remarks>
854         
855         public delegate void CompiledMethod (ref object retvalue);
856
857         /// <summary>
858         ///   The default base class for every interaction line
859         /// </summary>
860         /// <remarks>
861         ///   The expressions and statements behave as if they were
862         ///   a static method of this class.   The InteractiveBase class
863         ///   contains a number of useful methods, but can be overwritten
864         ///   by setting the InteractiveBaseType property in the Evaluator
865         /// </remarks>
866         public class InteractiveBase {
867                 /// <summary>
868                 ///   Determines where the standard output of methods in this class will go. 
869                 /// </summary>
870                 public static TextWriter Output = Console.Out;
871
872                 /// <summary>
873                 ///   Determines where the standard error of methods in this class will go. 
874                 /// </summary>
875                 public static TextWriter Error = Console.Error;
876
877                 /// <summary>
878                 ///   The primary prompt used for interactive use.
879                 /// </summary>
880                 public static string Prompt             = "csharp> ";
881
882                 /// <summary>
883                 ///   The secondary prompt used for interactive use (used when
884                 ///   an expression is incomplete).
885                 /// </summary>
886                 public static string ContinuationPrompt = "      > ";
887
888                 /// <summary>
889                 ///   Used to signal that the user has invoked the  `quit' statement.
890                 /// </summary>
891                 public static bool QuitRequested;
892
893                 public static Evaluator Evaluator;
894                 
895                 /// <summary>
896                 ///   Shows all the variables defined so far.
897                 /// </summary>
898                 static public void ShowVars ()
899                 {
900                         Output.Write (Evaluator.GetVars ());
901                         Output.Flush ();
902                 }
903
904                 /// <summary>
905                 ///   Displays the using statements in effect at this point. 
906                 /// </summary>
907                 static public void ShowUsing ()
908                 {
909                         Output.Write (Evaluator.GetUsing ());
910                         Output.Flush ();
911                 }
912         
913                 /// <summary>
914                 ///   Times the execution of the given delegate
915                 /// </summary>
916                 static public TimeSpan Time (Action a)
917                 {
918                         DateTime start = DateTime.Now;
919                         a ();
920                         return DateTime.Now - start;
921                 }
922                 
923                 /// <summary>
924                 ///   Loads the assemblies from a package
925                 /// </summary>
926                 /// <remarks>
927                 ///   Loads the assemblies from a package.   This is equivalent
928                 ///   to passing the -pkg: command line flag to the C# compiler
929                 ///   on the command line. 
930                 /// </remarks>
931                 static public void LoadPackage (string pkg)
932                 {
933                         if (pkg == null){
934                                 Error.WriteLine ("Invalid package specified");
935                                 return;
936                         }
937
938                         string pkgout = Driver.GetPackageFlags (pkg, null);
939
940                         string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
941                                 Split (new Char [] { ' ', '\t'});
942
943                         foreach (string s in xargs){
944                                 if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
945                                         string lib = s.Substring (s.IndexOf (':')+1);
946
947                                         Evaluator.LoadAssembly (lib);
948                                         continue;
949                                 }
950                         }
951                 }
952
953                 /// <summary>
954                 ///   Loads the assembly
955                 /// </summary>
956                 /// <remarks>
957                 ///   Loads the specified assembly and makes its types
958                 ///   available to the evaluator.  This is equivalent
959                 ///   to passing the -pkg: command line flag to the C#
960                 ///   compiler on the command line.
961                 /// </remarks>
962                 static public void LoadAssembly (string assembly)
963                 {
964                         Evaluator.LoadAssembly (assembly);
965                 }
966
967                 static public void print (object obj)
968                 {
969                         Output.WriteLine (obj);
970                 }
971
972                 static public void print (string fmt, params object [] args)
973                 {
974                         Output.WriteLine (fmt, args);
975                 }
976                 
977                 /// <summary>
978                 ///   Returns a list of available static methods. 
979                 /// </summary>
980                 static public string help {
981                         get {
982                                 return "Static methods:\n" +
983 #if !NET_2_1
984                                         "  Describe (object);       - Describes the object's type\n" +
985 #endif
986                                         "  LoadPackage (package);   - Loads the given Package (like -pkg:FILE)\n" +
987                                         "  LoadAssembly (assembly); - Loads the given assembly (like -r:ASSEMBLY)\n" +
988                                         "  ShowVars ();             - Shows defined local variables.\n" +
989                                         "  ShowUsing ();            - Show active using declarations.\n" +
990                                         "  Prompt                   - The prompt used by the C# shell\n" +
991                                         "  ContinuationPrompt       - The prompt for partial input\n" +
992                                         "  Time (() => { });        - Times the specified code\n" +
993                                         "  print (obj);             - Shorthand for Console.WriteLine\n" +
994                                         "  quit;                    - You'll never believe it - this quits the repl!\n" +
995                                         "  help;                    - This help text\n";
996                         }
997                 }
998
999                 /// <summary>
1000                 ///   Indicates to the read-eval-print-loop that the interaction should be finished. 
1001                 /// </summary>
1002                 static public object quit {
1003                         get {
1004                                 QuitRequested = true;
1005
1006                                 // To avoid print null at the exit
1007                                 return typeof (Evaluator.QuitValue);
1008                         }
1009                 }
1010
1011                 /// <summary>
1012                 ///   Same as quit - useful in script scenerios
1013                 /// </summary>
1014                 static public void Quit () {
1015                         QuitRequested = true;
1016                 }
1017
1018 #if !NET_2_1
1019                 /// <summary>
1020                 ///   Describes an object or a type.
1021                 /// </summary>
1022                 /// <remarks>
1023                 ///   This method will show a textual representation
1024                 ///   of the object's type.  If the object is a
1025                 ///   System.Type it renders the type directly,
1026                 ///   otherwise it renders the type returned by
1027                 ///   invoking GetType on the object.
1028                 /// </remarks>
1029                 static public string Describe (object x)
1030                 {
1031                         if (x == null)
1032                                 return "<null>";
1033
1034                         var type = x as Type ?? x.GetType ();
1035
1036                         StringWriter sw = new StringWriter ();
1037                         new Outline (type, sw, true, false, false).OutlineType ();
1038                         return sw.ToString ();
1039                 }
1040 #endif
1041         }
1042
1043         class HoistedEvaluatorVariable : HoistedVariable
1044         {
1045                 public HoistedEvaluatorVariable (Field field)
1046                         : base (null, field)
1047                 {
1048                 }
1049
1050                 protected override FieldExpr GetFieldExpression (EmitContext ec)
1051                 {
1052                         return new FieldExpr (field, field.Location);
1053                 }
1054         }
1055
1056         /// <summary>
1057         ///    A class used to assign values if the source expression is not void
1058         ///
1059         ///    Used by the interactive shell to allow it to call this code to set
1060         ///    the return value for an invocation.
1061         /// </summary>
1062         class OptionalAssign : SimpleAssign {
1063                 public OptionalAssign (Expression t, Expression s, Location loc)
1064                         : base (t, s, loc)
1065                 {
1066                 }
1067
1068                 protected override Expression DoResolve (ResolveContext ec)
1069                 {
1070                         Expression clone = source.Clone (new CloneContext ());
1071
1072                         clone = clone.Resolve (ec);
1073                         if (clone == null)
1074                                 return null;
1075
1076                         //
1077                         // A useful feature for the REPL: if we can resolve the expression
1078                         // as a type, Describe the type;
1079                         //
1080                         if (ec.Module.Evaluator.DescribeTypeExpressions){
1081                                 var old_printer = ec.Report.SetPrinter (new SessionReportPrinter ());
1082                                 Expression tclone;
1083                                 try {
1084                                         // Note: clone context cannot be shared otherwise block mapping would leak
1085                                         tclone = source.Clone (new CloneContext ());
1086                                         tclone = tclone.Resolve (ec, ResolveFlags.Type);
1087                                         if (ec.Report.Errors > 0)
1088                                                 tclone = null;
1089                                 } finally {
1090                                         ec.Report.SetPrinter (old_printer);
1091                                 }
1092
1093                                 if (tclone is TypeExpr) {
1094                                         Arguments args = new Arguments (1);
1095                                         args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
1096                                         return new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
1097                                 }
1098                         }
1099
1100                         // This means its really a statement.
1101                         if (clone.Type.Kind == MemberKind.Void || clone is DynamicInvocation || clone is Assign) {
1102                                 return clone;
1103                         }
1104
1105                         source = clone;
1106                         return base.DoResolve (ec);
1107                 }
1108         }
1109
1110         public class Undo
1111         {
1112                 List<Action> undo_actions;
1113                 
1114                 public Undo ()
1115                 {
1116                 }
1117
1118                 public void AddTypeContainer (TypeContainer current_container, TypeDefinition tc)
1119                 {
1120                         if (current_container == tc){
1121                                 Console.Error.WriteLine ("Internal error: inserting container into itself");
1122                                 return;
1123                         }
1124
1125                         if (undo_actions == null)
1126                                 undo_actions = new List<Action> ();
1127
1128                         var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
1129                         if (existing != null) {
1130                                 current_container.RemoveContainer (existing);
1131                                 undo_actions.Add (() => current_container.AddTypeContainer (existing));
1132                         }
1133
1134                         undo_actions.Add (() => current_container.RemoveContainer (tc));
1135                 }
1136
1137                 public void ExecuteUndo ()
1138                 {
1139                         if (undo_actions == null)
1140                                 return;
1141
1142                         foreach (var p in undo_actions){
1143                                 p ();
1144                         }
1145
1146                         undo_actions = null;
1147                 }
1148         }
1149         
1150 }