2 // eval.cs: Evaluation and Hosting API for the C# compiler
5 // Miguel de Icaza (miguel@gnome.org)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
13 using System
.Threading
;
14 using System
.Collections
;
15 using System
.Reflection
;
16 using System
.Reflection
.Emit
;
18 using System
.Globalization
;
21 namespace Mono
.CSharp
{
24 /// Evaluator: provides an API to evaluate C# statements and
25 /// expressions dynamically.
28 /// This class exposes static methods to evaluate expressions in the
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.
35 /// To interrupt execution of a statement, you can invoke the
36 /// Evaluator.Interrupt method.
38 public class Evaluator
{
41 // Parse silently, do not output any error messages
44 // Report errors during parse
47 // Auto-complete, means that the tokenizer will start producing
48 // GETCOMPLETIONS tokens when it reaches a certain point.
52 static object evaluator_lock
= new object ();
54 static string current_debug_name
;
56 static Thread invoke_thread
;
58 static ArrayList using_alias_list
= new ArrayList ();
59 internal static ArrayList using_list
= new ArrayList ();
60 static Hashtable fields
= new Hashtable ();
62 static Type interactive_base_class
= typeof (InteractiveBase
);
66 static CompilerContext ctx
;
68 public static TextWriter MessageOutput
= Console
.Out
;
71 /// Optional initialization for the Evaluator.
74 /// Initializes the Evaluator with the command line options
75 /// that would be processed by the command line compiler. Only
76 /// the first call to Init will work, any future invocations are
79 /// You can safely avoid calling this method if your application
80 /// does not need any of the features exposed by the command line
83 public static void Init (string [] args
)
85 InitAndGetStartupFiles (args
);
90 /// Optional initialization for the Evaluator.
93 /// Initializes the Evaluator with the command line
94 /// options that would be processed by the command
95 /// line compiler. Only the first call to
96 /// InitAndGetStartupFiles or Init will work, any future
97 /// invocations are ignored.
99 /// You can safely avoid calling this method if your application
100 /// does not need any of the features exposed by the command line
103 /// This method return an array of strings that contains any
104 /// files that were specified in `args'.
106 public static string [] InitAndGetStartupFiles (string [] args
)
108 lock (evaluator_lock
){
110 return new string [0];
112 driver
= Driver
.Create (args
, false, new ConsoleReportPrinter ());
114 throw new Exception ("Failed to create compiler driver with the given arguments");
116 RootContext
.ToplevelTypes
= new ModuleCompiled (ctx
, true);
118 driver
.ProcessDefaultConfig ();
120 ArrayList startup_files
= new ArrayList ();
121 foreach (CompilationUnit file
in Location
.SourceFiles
)
122 startup_files
.Add (file
.Path
);
124 CompilerCallableEntryPoint
.Reset ();
125 RootContext
.ToplevelTypes
= new ModuleCompiled (ctx
, true);
127 driver
.LoadReferences ();
128 RootContext
.EvalMode
= true;
131 return (string []) startup_files
.ToArray (typeof (string));
137 Init (new string [0]);
142 CompilerCallableEntryPoint
.PartialReset ();
144 // Workaround for API limitation where full message printer cannot be passed
145 ReportPrinter printer
= MessageOutput
== Console
.Out
|| MessageOutput
== Console
.Error
?
146 new ConsoleReportPrinter (MessageOutput
) :
147 new StreamReportPrinter (MessageOutput
);
149 ctx
= new CompilerContext (new Report (printer
));
150 RootContext
.ToplevelTypes
= new ModuleCompiled (ctx
, true);
153 // PartialReset should not reset the core types, this is very redundant.
155 if (!TypeManager
.InitCoreTypes (ctx
))
156 throw new Exception ("Failed to InitCoreTypes");
157 TypeManager
.InitOptionalCoreTypes (ctx
);
159 Location
.AddFile (null, "{interactive}");
160 Location
.Initialize ();
162 current_debug_name
= "interactive" + (count
++) + ".dll";
163 if (Environment
.GetEnvironmentVariable ("SAVE") != null){
164 CodeGen
.Init (current_debug_name
, current_debug_name
, false, ctx
);
166 CodeGen
.InitDynamic (ctx
, current_debug_name
);
170 /// The base class for the classes that host the user generated code
174 /// This is the base class that will host the code
175 /// executed by the Evaluator. By default
176 /// this is the Mono.CSharp.InteractiveBase class
177 /// which is useful for interactive use.
179 /// By changing this property you can control the
180 /// base class and the static members that are
181 /// available to your evaluated code.
183 static public Type InteractiveBaseClass
{
185 return interactive_base_class
;
190 throw new ArgumentNullException ();
192 lock (evaluator_lock
)
193 interactive_base_class
= value;
198 /// Interrupts the evaluation of an expression executing in Evaluate.
201 /// Use this method to interrupt long-running invocations.
203 public static void Interrupt ()
205 if (!inited
|| !invoking
)
208 if (invoke_thread
!= null)
209 invoke_thread
.Abort ();
213 /// Compiles the input string and returns a delegate that represents the compiled code.
217 /// Compiles the input string as a C# expression or
218 /// statement, unlike the Evaluate method, the
219 /// resulting delegate can be invoked multiple times
220 /// without incurring in the compilation overhead.
222 /// If the return value of this function is null,
223 /// this indicates that the parsing was complete.
224 /// If the return value is a string it indicates
225 /// that the input string was partial and that the
226 /// invoking code should provide more code before
227 /// the code can be successfully compiled.
229 /// If you know that you will always get full expressions or
230 /// statements and do not care about partial input, you can use
231 /// the other Compile overload.
233 /// On success, in addition to returning null, the
234 /// compiled parameter will be set to the delegate
235 /// that can be invoked to execute the code.
238 static public string Compile (string input
, out CompiledMethod compiled
)
240 if (input
== null || input
.Length
== 0){
245 lock (evaluator_lock
){
250 CSharpParser parser
= ParseString (ParseMode
.Silent
, input
, out partial_input
);
256 ParseString (ParseMode
.ReportErrors
, input
, out partial_input
);
260 object parser_result
= parser
.InteractiveResult
;
262 if (!(parser_result
is Class
)){
263 int errors
= ctx
.Report
.Errors
;
265 NamespaceEntry
.VerifyAllUsing ();
266 if (errors
== ctx
.Report
.Errors
)
267 parser
.CurrentNamespace
.Extract (using_alias_list
, using_list
);
270 compiled
= CompileBlock (parser_result
as Class
, parser
.undo
, ctx
.Report
);
277 /// Compiles the input string and returns a delegate that represents the compiled code.
281 /// Compiles the input string as a C# expression or
282 /// statement, unlike the Evaluate method, the
283 /// resulting delegate can be invoked multiple times
284 /// without incurring in the compilation overhead.
286 /// This method can only deal with fully formed input
287 /// strings and does not provide a completion mechanism.
288 /// If you must deal with partial input (for example for
289 /// interactive use) use the other overload.
291 /// On success, a delegate is returned that can be used
292 /// to invoke the method.
295 static public CompiledMethod
Compile (string input
)
297 CompiledMethod compiled
;
299 // Ignore partial inputs
300 if (Compile (input
, out compiled
) != null){
301 // Error, the input was partial.
305 // Either null (on error) or the compiled method.
310 // Todo: Should we handle errors, or expect the calling code to setup
311 // the recording themselves?
315 /// Evaluates and expression or statement and returns any result values.
318 /// Evaluates the input string as a C# expression or
319 /// statement. If the input string is an expression
320 /// the result will be stored in the result variable
321 /// and the result_set variable will be set to true.
323 /// It is necessary to use the result/result_set
324 /// pair to identify when a result was set (for
325 /// example, execution of user-provided input can be
326 /// an expression, a statement or others, and
327 /// result_set would only be set if the input was an
330 /// If the return value of this function is null,
331 /// this indicates that the parsing was complete.
332 /// If the return value is a string, it indicates
333 /// that the input is partial and that the user
334 /// should provide an updated string.
336 public static string Evaluate (string input
, out object result
, out bool result_set
)
338 CompiledMethod compiled
;
343 input
= Compile (input
, out compiled
);
347 if (compiled
== null)
351 // The code execution does not need to keep the compiler lock
353 object retval
= typeof (NoValueSet
);
356 invoke_thread
= System
.Threading
.Thread
.CurrentThread
;
358 compiled (ref retval
);
359 } catch (ThreadAbortException e
){
360 Thread
.ResetAbort ();
361 Console
.WriteLine ("Interrupted!\n{0}", e
);
367 // We use a reference to a compiler type, in this case
368 // Driver as a flag to indicate that this was a statement
370 if (retval
!= typeof (NoValueSet
)){
378 public static string [] GetCompletions (string input
, out string prefix
)
381 if (input
== null || input
.Length
== 0)
384 lock (evaluator_lock
){
389 CSharpParser parser
= ParseString (ParseMode
.GetCompletions
, input
, out partial_input
);
391 if (CSharpParser
.yacc_verbose_flag
!= 0)
392 Console
.WriteLine ("DEBUG: No completions available");
396 Class parser_result
= parser
.InteractiveResult
as Class
;
398 if (parser_result
== null){
399 if (CSharpParser
.yacc_verbose_flag
!= 0)
400 Console
.WriteLine ("Do not know how to cope with !Class yet");
405 RootContext
.ResolveTree ();
406 if (ctx
.Report
.Errors
!= 0)
409 RootContext
.PopulateTypes ();
410 if (ctx
.Report
.Errors
!= 0)
413 MethodOrOperator method
= null;
414 foreach (MemberCore member
in parser_result
.Methods
){
415 if (member
.Name
!= "Host")
418 method
= (MethodOrOperator
) member
;
422 throw new InternalErrorException ("did not find the the Host method");
424 BlockContext bc
= new BlockContext (method
, method
.Block
, method
.ReturnType
);
427 method
.Block
.Resolve (null, bc
, method
.ParameterInfo
, method
);
428 } catch (CompletionResult cr
){
429 prefix
= cr
.BaseText
;
433 parser
.undo
.ExecuteUndo ();
441 /// Executes the given expression or statement.
444 /// Executes the provided statement, returns true
445 /// on success, false on parsing errors. Exceptions
446 /// might be thrown by the called code.
448 public static bool Run (string statement
)
456 bool ok
= Evaluate (statement
, out result
, out result_set
) == null;
462 /// Evaluates and expression or statement and returns the result.
465 /// Evaluates the input string as a C# expression or
466 /// statement and returns the value.
468 /// This method will throw an exception if there is a syntax error,
469 /// of if the provided input is not an expression but a statement.
471 public static object Evaluate (string input
)
476 string r
= Evaluate (input
, out result
, out result_set
);
479 throw new ArgumentException ("Syntax error on input: partial input");
481 if (result_set
== false)
482 throw new ArgumentException ("The expression did not set a result");
489 StatementOrExpression
,
495 // Deambiguates the input string to determine if we
496 // want to process a statement or if we want to
497 // process a compilation unit.
499 // This is done using a top-down predictive parser,
500 // since the yacc/jay parser can not deambiguage this
501 // without more than one lookahead token. There are very
504 static InputKind
ToplevelOrStatement (SeekableStreamReader seekable
)
506 Tokenizer tokenizer
= new Tokenizer (seekable
, (CompilationUnit
) Location
.SourceFiles
[0], ctx
);
508 int t
= tokenizer
.token ();
511 return InputKind
.EOF
;
513 // These are toplevels
515 case Token
.OPEN_BRACKET
:
519 case Token
.INTERFACE
:
521 case Token
.NAMESPACE
:
523 case Token
.PROTECTED
:
528 return InputKind
.CompilationUnit
;
530 // Definitely expression
547 return InputKind
.StatementOrExpression
;
549 // These need deambiguation help
551 t
= tokenizer
.token ();
553 return InputKind
.EOF
;
555 if (t
== Token
.IDENTIFIER
)
556 return InputKind
.CompilationUnit
;
557 return InputKind
.StatementOrExpression
;
560 // Distinguish between:
561 // delegate opt_anonymous_method_signature block
564 t
= tokenizer
.token ();
566 return InputKind
.EOF
;
567 if (t
== Token
.OPEN_PARENS
|| t
== Token
.OPEN_BRACE
)
568 return InputKind
.StatementOrExpression
;
569 return InputKind
.CompilationUnit
;
571 // Distinguih between:
573 // unsafe as modifier of a type declaration
575 t
= tokenizer
.token ();
577 return InputKind
.EOF
;
578 if (t
== Token
.OPEN_PARENS
)
579 return InputKind
.StatementOrExpression
;
580 return InputKind
.CompilationUnit
;
582 // These are errors: we list explicitly what we had
583 // from the grammar, ERROR and then everything else
588 return InputKind
.Error
;
590 // This catches everything else allowed by
591 // expressions. We could add one-by-one use cases
594 return InputKind
.StatementOrExpression
;
599 // Parses the string @input and returns a CSharpParser if succeeful.
601 // if @silent is set to true then no errors are
602 // reported to the user. This is used to do various calls to the
603 // parser and check if the expression is parsable.
605 // @partial_input: if @silent is true, then it returns whether the
606 // parsed expression was partial, and more data is needed
608 static CSharpParser
ParseString (ParseMode mode
, string input
, out bool partial_input
)
610 partial_input
= false;
612 queued_fields
.Clear ();
614 Stream s
= new MemoryStream (Encoding
.Default
.GetBytes (input
));
615 SeekableStreamReader seekable
= new SeekableStreamReader (s
, Encoding
.Default
);
617 InputKind kind
= ToplevelOrStatement (seekable
);
618 if (kind
== InputKind
.Error
){
619 if (mode
== ParseMode
.ReportErrors
)
620 ctx
.Report
.Error (-25, "Detection Parsing Error");
621 partial_input
= false;
625 if (kind
== InputKind
.EOF
){
626 if (mode
== ParseMode
.ReportErrors
)
627 Console
.Error
.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
628 partial_input
= true;
632 seekable
.Position
= 0;
634 CSharpParser parser
= new CSharpParser (seekable
, (CompilationUnit
) Location
.SourceFiles
[0], ctx
);
636 if (kind
== InputKind
.StatementOrExpression
){
637 parser
.Lexer
.putback_char
= Tokenizer
.EvalStatementParserCharacter
;
638 RootContext
.StatementMode
= true;
641 // Do not activate EvalCompilationUnitParserCharacter until
642 // I have figured out all the limitations to invoke methods
643 // in the generated classes. See repl.txt
645 parser
.Lexer
.putback_char
= Tokenizer
.EvalUsingDeclarationsParserCharacter
;
646 //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
647 RootContext
.StatementMode
= false;
650 if (mode
== ParseMode
.GetCompletions
)
651 parser
.Lexer
.CompleteOnEOF
= true;
653 bool disable_error_reporting
;
654 if ((mode
== ParseMode
.Silent
|| mode
== ParseMode
.GetCompletions
) && CSharpParser
.yacc_verbose_flag
== 0)
655 disable_error_reporting
= true;
657 disable_error_reporting
= false;
659 if (disable_error_reporting
)
660 ctx
.Report
.DisableReporting ();
664 if (ctx
.Report
.Errors
!= 0){
665 if (mode
!= ParseMode
.ReportErrors
&& parser
.UnexpectedEOF
)
666 partial_input
= true;
668 parser
.undo
.ExecuteUndo ();
672 if (disable_error_reporting
)
673 ctx
.Report
.EnableReporting ();
679 // Queue all the fields that we use, as we need to then go from FieldBuilder to FieldInfo
680 // or reflection gets confused (it basically gets confused, and variables override each
683 static ArrayList queued_fields
= new ArrayList ();
685 //static ArrayList types = new ArrayList ();
687 static volatile bool invoking
;
689 static CompiledMethod
CompileBlock (Class host
, Undo undo
, Report Report
)
691 RootContext
.ResolveTree ();
692 if (Report
.Errors
!= 0){
697 RootContext
.PopulateTypes ();
699 if (Report
.Errors
!= 0){
704 TypeBuilder tb
= null;
705 MethodBuilder mb
= null;
708 tb
= host
.TypeBuilder
;
710 foreach (MemberCore member
in host
.Methods
){
711 if (member
.Name
!= "Host")
714 MethodOrOperator method
= (MethodOrOperator
) member
;
715 mb
= method
.MethodBuilder
;
720 throw new Exception ("Internal error: did not find the method builder for the generated method");
723 RootContext
.EmitCode ();
724 if (Report
.Errors
!= 0)
727 RootContext
.CloseTypes ();
729 if (Environment
.GetEnvironmentVariable ("SAVE") != null)
730 CodeGen
.Save (current_debug_name
, false, Report
);
736 // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
737 // work from MethodBuilders. Retarded, I know.
739 Type tt
= CodeGen
.Assembly
.Builder
.GetType (tb
.Name
);
740 MethodInfo mi
= tt
.GetMethod (mb
.Name
);
742 // Pull the FieldInfos from the type, and keep track of them
743 foreach (Field field
in queued_fields
){
744 FieldInfo fi
= tt
.GetField (field
.Name
);
746 FieldInfo old
= (FieldInfo
) fields
[field
.Name
];
748 // If a previous value was set, nullify it, so that we do
751 if (TypeManager
.IsStruct (old
.FieldType
)){
753 // TODO: Clear fields for structs
757 old
.SetValue (null, null);
763 fields
[field
.Name
] = fi
;
767 queued_fields
.Clear ();
769 return (CompiledMethod
) System
.Delegate
.CreateDelegate (typeof (CompiledMethod
), mi
);
772 static internal void LoadAliases (NamespaceEntry ns
)
774 ns
.Populate (using_alias_list
, using_list
);
778 /// A sentinel value used to indicate that no value was
779 /// was set by the compiled function. This is used to
780 /// differentiate between a function not returning a
783 public class NoValueSet
{
786 static internal FieldInfo
LookupField (string name
)
788 FieldInfo fi
= (FieldInfo
) fields
[name
];
794 // Puts the FieldBuilder into a queue of names that will be
795 // registered. We can not register FieldBuilders directly
796 // we need to fetch the FieldInfo after Reflection cooks the
797 // types, or bad things happen (bad means: FieldBuilders behave
798 // incorrectly across multiple assemblies, causing assignments to
801 // This also serves for the parser to register Field classes
802 // that should be exposed as global variables
804 static internal void QueueField (Field f
)
806 queued_fields
.Add (f
);
809 static string Quote (string s
)
811 if (s
.IndexOf ('"') != -1)
812 s
= s
.Replace ("\"", "\\\"");
814 return "\"" + s
+ "\"";
817 static public string GetUsing ()
819 lock (evaluator_lock
){
820 StringBuilder sb
= new StringBuilder ();
822 foreach (object x
in using_alias_list
)
823 sb
.Append (String
.Format ("using {0};\n", x
));
825 foreach (object x
in using_list
)
826 sb
.Append (String
.Format ("using {0};\n", x
));
828 return sb
.ToString ();
832 static internal ICollection
GetUsingList ()
834 ArrayList res
= new ArrayList (using_list
.Count
);
835 foreach (object ue
in using_list
)
836 res
.Add (ue
.ToString ());
840 static internal string [] GetVarNames ()
842 lock (evaluator_lock
){
843 return (string []) new ArrayList (fields
.Keys
).ToArray (typeof (string));
847 static public string GetVars ()
849 lock (evaluator_lock
){
850 StringBuilder sb
= new StringBuilder ();
852 foreach (DictionaryEntry de
in fields
){
853 FieldInfo fi
= LookupField ((string) de
.Key
);
860 value = fi
.GetValue (null);
862 value = Quote ((string)value);
868 sb
.Append (String
.Format ("{0} {1} <error reading value>", TypeManager
.CSharpName(fi
.FieldType
), de
.Key
));
870 sb
.Append (String
.Format ("{0} {1} = {2}", TypeManager
.CSharpName(fi
.FieldType
), de
.Key
, value));
873 return sb
.ToString ();
878 /// Loads the given assembly and exposes the API to the user.
880 static public void LoadAssembly (string file
)
882 lock (evaluator_lock
){
883 driver
.LoadAssembly (file
, false);
884 GlobalRootNamespace
.Instance
.ComputeNamespaces (ctx
);
889 /// Exposes the API of the given assembly to the Evaluator
891 static public void ReferenceAssembly (Assembly a
)
893 lock (evaluator_lock
){
894 GlobalRootNamespace
.Instance
.AddAssemblyReference (a
);
895 GlobalRootNamespace
.Instance
.ComputeNamespaces (ctx
);
903 /// A delegate that can be used to invoke the
904 /// compiled expression or statement.
907 /// Since the Compile methods will compile
908 /// statements and expressions into the same
909 /// delegate, you can tell if a value was returned
910 /// by checking whether the returned value is of type
914 public delegate void CompiledMethod (ref object retvalue
);
917 /// The default base class for every interaction line
920 /// The expressions and statements behave as if they were
921 /// a static method of this class. The InteractiveBase class
922 /// contains a number of useful methods, but can be overwritten
923 /// by setting the InteractiveBaseType property in the Evaluator
925 public class InteractiveBase
{
927 /// Determines where the standard output of methods in this class will go.
929 public static TextWriter Output
= Console
.Out
;
932 /// Determines where the standard error of methods in this class will go.
934 public static TextWriter Error
= Console
.Error
;
937 /// The primary prompt used for interactive use.
939 public static string Prompt
= "csharp> ";
942 /// The secondary prompt used for interactive use (used when
943 /// an expression is incomplete).
945 public static string ContinuationPrompt
= " > ";
948 /// Used to signal that the user has invoked the `quit' statement.
950 public static bool QuitRequested
;
953 /// Shows all the variables defined so far.
955 static public void ShowVars ()
957 Output
.Write (Evaluator
.GetVars ());
962 /// Displays the using statements in effect at this point.
964 static public void ShowUsing ()
966 Output
.Write (Evaluator
.GetUsing ());
970 public delegate void Simple ();
973 /// Times the execution of the given delegate
975 static public TimeSpan
Time (Simple a
)
977 DateTime start
= DateTime
.Now
;
979 return DateTime
.Now
- start
;
984 /// Loads the assemblies from a package
987 /// Loads the assemblies from a package. This is equivalent
988 /// to passing the -pkg: command line flag to the C# compiler
989 /// on the command line.
991 static public void LoadPackage (string pkg
)
994 Error
.WriteLine ("Invalid package specified");
998 string pkgout
= Driver
.GetPackageFlags (pkg
, false, RootContext
.ToplevelTypes
.Compiler
.Report
);
1002 string [] xargs
= pkgout
.Trim (new Char
[] {' ', '\n', '\r', '\t'}
).
1003 Split (new Char
[] { ' ', '\t'}
);
1005 foreach (string s
in xargs
){
1006 if (s
.StartsWith ("-r:") || s
.StartsWith ("/r:") || s
.StartsWith ("/reference:")){
1007 string lib
= s
.Substring (s
.IndexOf (':')+1);
1009 Evaluator
.LoadAssembly (lib
);
1017 /// Loads the assembly
1020 /// Loads the specified assembly and makes its types
1021 /// available to the evaluator. This is equivalent
1022 /// to passing the -pkg: command line flag to the C#
1023 /// compiler on the command line.
1025 static public void LoadAssembly (string assembly
)
1027 Evaluator
.LoadAssembly (assembly
);
1031 /// Returns a list of available static methods.
1033 static public string help
{
1035 return "Static methods:\n"+
1036 " Describe(obj) - Describes the object's type\n" +
1037 " LoadPackage (pkg); - Loads the given Package (like -pkg:FILE)\n" +
1038 " LoadAssembly (ass) - Loads the given assembly (like -r:ASS)\n" +
1039 " ShowVars (); - Shows defined local variables.\n" +
1040 " ShowUsing (); - Show active using decltions.\n" +
1041 " Prompt - The prompt used by the C# shell\n" +
1042 " ContinuationPrompt - The prompt for partial input\n" +
1043 " Time(() -> { }) - Times the specified code\n" +
1050 /// Indicates to the read-eval-print-loop that the interaction should be finished.
1052 static public object quit
{
1054 QuitRequested
= true;
1061 /// Describes an object or a type.
1064 /// This method will show a textual representation
1065 /// of the object's type. If the object is a
1066 /// System.Type it renders the type directly,
1067 /// otherwise it renders the type returned by
1068 /// invoking GetType on the object.
1070 static public string Describe (object x
)
1079 StringWriter sw
= new StringWriter ();
1080 new Outline (t
, sw
, true, false, false).OutlineType ();
1081 return sw
.ToString ();
1087 // A local variable reference that will create a Field in a
1088 // Class with the resolved type. This is necessary so we can
1089 // support "var" as a field type in a class declaration.
1091 // We allow LocalVariableReferece to do the heavy lifting, and
1092 // then we insert the field with the resolved type
1094 public class LocalVariableReferenceWithClassSideEffect
: LocalVariableReference
{
1095 TypeContainer container
;
1098 public LocalVariableReferenceWithClassSideEffect (TypeContainer container
, string name
, Block current_block
, string local_variable_id
, LocalInfo li
, Location loc
)
1099 : base (current_block
, local_variable_id
, loc
, li
, false)
1101 this.container
= container
;
1105 public override bool Equals (object obj
)
1107 LocalVariableReferenceWithClassSideEffect lvr
= obj
as LocalVariableReferenceWithClassSideEffect
;
1111 if (lvr
.name
!= name
|| lvr
.container
!= container
)
1114 return base.Equals (obj
);
1117 public override int GetHashCode ()
1119 return name
.GetHashCode ();
1122 override public Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
1124 Expression ret
= base.DoResolveLValue (ec
, right_side
);
1128 Field f
= new Field (container
, new TypeExpression (ret
.Type
, Location
),
1129 Modifiers
.PUBLIC
| Modifiers
.STATIC
,
1130 new MemberName (name
, Location
), null);
1131 container
.AddField (f
);
1133 Evaluator
.QueueField (f
);
1140 /// A class used to assign values if the source expression is not void
1142 /// Used by the interactive shell to allow it to call this code to set
1143 /// the return value for an invocation.
1145 class OptionalAssign
: SimpleAssign
{
1146 public OptionalAssign (Expression t
, Expression s
, Location loc
)
1151 protected override Expression
DoResolve (ResolveContext ec
)
1153 CloneContext cc
= new CloneContext ();
1154 Expression clone
= source
.Clone (cc
);
1156 clone
= clone
.Resolve (ec
);
1160 // This means its really a statement.
1161 if (clone
.Type
== TypeManager
.void_type
){
1162 source
= source
.Resolve (ec
);
1164 type
= TypeManager
.void_type
;
1165 eclass
= ExprClass
.Value
;
1169 return base.DoResolve (ec
);
1172 public override void Emit (EmitContext ec
)
1180 public override void EmitStatement (EmitContext ec
)
1185 base.EmitStatement (ec
);
1190 ArrayList undo_types
;
1194 undo_types
= new ArrayList ();
1197 public void AddTypeContainer (TypeContainer current_container
, TypeContainer tc
)
1199 if (current_container
== tc
){
1200 Console
.Error
.WriteLine ("Internal error: inserting container into itself");
1204 if (undo_types
== null)
1205 undo_types
= new ArrayList ();
1206 undo_types
.Add (new Pair (current_container
, tc
));
1209 public void ExecuteUndo ()
1211 if (undo_types
== null)
1214 foreach (Pair p
in undo_types
){
1215 TypeContainer current_container
= (TypeContainer
) p
.First
;
1217 current_container
.RemoveTypeContainer ((TypeContainer
) p
.Second
);