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