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