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