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