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