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