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