2004-10-31 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / mcs / typemanager.cs
1 //
2 // typemanager.cs: C# type manager
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11 //
12
13 //
14 // We will eventually remove the SIMPLE_SPEEDUP, and should never change 
15 // the behavior of the compilation.  This can be removed if we rework
16 // the code to get a list of namespaces available.
17 //
18 #define SIMPLE_SPEEDUP
19
20 using System;
21 using System.IO;
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 using System.Text;
27 using System.Text.RegularExpressions;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
30
31 namespace Mono.CSharp {
32
33 public class TypeManager {
34         //
35         // A list of core types that the compiler requires or uses
36         //
37         static public Type object_type;
38         static public Type value_type;
39         static public Type string_type;
40         static public Type int32_type;
41         static public Type uint32_type;
42         static public Type int64_type;
43         static public Type uint64_type;
44         static public Type float_type;
45         static public Type double_type;
46         static public Type char_type;
47         static public Type char_ptr_type;
48         static public Type short_type;
49         static public Type decimal_type;
50         static public Type bool_type;
51         static public Type sbyte_type;
52         static public Type byte_type;
53         static public Type ushort_type;
54         static public Type enum_type;
55         static public Type delegate_type;
56         static public Type multicast_delegate_type;
57         static public Type void_type;
58         static public Type enumeration_type;
59         static public Type array_type;
60         static public Type runtime_handle_type;
61         static public Type icloneable_type;
62         static public Type type_type;
63         static public Type ienumerator_type;
64         static public Type ienumerable_type;
65         static public Type idisposable_type;
66         static public Type iconvertible_type;
67         static public Type default_member_type;
68         static public Type iasyncresult_type;
69         static public Type asynccallback_type;
70         static public Type intptr_type;
71         static public Type monitor_type;
72         static public Type runtime_field_handle_type;
73         static public Type runtime_argument_handle_type;
74         static public Type attribute_type;
75         static public Type attribute_usage_type;
76         static public Type dllimport_type;
77         static public Type unverifiable_code_type;
78         static public Type methodimpl_attr_type;
79         static public Type marshal_as_attr_type;
80         static public Type param_array_type;
81         static public Type guid_attr_type;
82         static public Type void_ptr_type;
83         static public Type indexer_name_type;
84         static public Type exception_type;
85         static public Type invalid_operation_exception_type;
86         static public Type not_supported_exception_type;
87         static public Type obsolete_attribute_type;
88         static public Type conditional_attribute_type;
89         static public Type in_attribute_type;
90         static public Type anonymous_method_type;
91         static public Type cls_compliant_attribute_type;
92         static public Type typed_reference_type;
93         static public Type arg_iterator_type;
94         static public Type mbr_type;
95         static public Type struct_layout_attribute_type;
96         static public Type field_offset_attribute_type;
97         static public Type security_attr_type;
98
99         //
100         // An empty array of types
101         //
102         static public Type [] NoTypes;
103         static public TypeExpr [] NoTypeExprs;
104
105
106         // 
107         // Expressions representing the internal types.  Used during declaration
108         // definition.
109         //
110         static public TypeExpr system_object_expr, system_string_expr; 
111         static public TypeExpr system_boolean_expr, system_decimal_expr;
112         static public TypeExpr system_single_expr, system_double_expr;
113         static public TypeExpr system_sbyte_expr, system_byte_expr;
114         static public TypeExpr system_int16_expr, system_uint16_expr;
115         static public TypeExpr system_int32_expr, system_uint32_expr;
116         static public TypeExpr system_int64_expr, system_uint64_expr;
117         static public TypeExpr system_char_expr, system_void_expr;
118         static public TypeExpr system_asynccallback_expr;
119         static public TypeExpr system_iasyncresult_expr;
120         static public TypeExpr system_valuetype_expr;
121         static public TypeExpr system_intptr_expr;
122
123         //
124         // This is only used when compiling corlib
125         //
126         static public Type system_int32_type;
127         static public Type system_array_type;
128         static public Type system_type_type;
129         static public Type system_assemblybuilder_type;
130         static public MethodInfo system_int_array_get_length;
131         static public MethodInfo system_int_array_get_rank;
132         static public MethodInfo system_object_array_clone;
133         static public MethodInfo system_int_array_get_length_int;
134         static public MethodInfo system_int_array_get_lower_bound_int;
135         static public MethodInfo system_int_array_get_upper_bound_int;
136         static public MethodInfo system_void_array_copyto_array_int;
137
138         
139         //
140         // Internal, not really used outside
141         //
142         static Type runtime_helpers_type;
143         
144         //
145         // These methods are called by code generated by the compiler
146         //
147         static public MethodInfo string_concat_string_string;
148         static public MethodInfo string_concat_string_string_string;
149         static public MethodInfo string_concat_string_string_string_string;
150         static public MethodInfo string_concat_string_dot_dot_dot;
151         static public MethodInfo string_concat_object_object;
152         static public MethodInfo string_concat_object_object_object;
153         static public MethodInfo string_concat_object_dot_dot_dot;
154         static public MethodInfo string_isinterneted_string;
155         static public MethodInfo system_type_get_type_from_handle;
156         static public MethodInfo object_getcurrent_void;
157         static public MethodInfo bool_movenext_void;
158         static public MethodInfo ienumerable_getenumerator_void;
159         static public MethodInfo void_reset_void;
160         static public MethodInfo void_dispose_void;
161         static public MethodInfo void_monitor_enter_object;
162         static public MethodInfo void_monitor_exit_object;
163         static public MethodInfo void_initializearray_array_fieldhandle;
164         static public MethodInfo int_getlength_int;
165         static public MethodInfo delegate_combine_delegate_delegate;
166         static public MethodInfo delegate_remove_delegate_delegate;
167         static public MethodInfo int_get_offset_to_string_data;
168         static public MethodInfo int_array_get_length;
169         static public MethodInfo int_array_get_rank;
170         static public MethodInfo object_array_clone;
171         static public MethodInfo int_array_get_length_int;
172         static public MethodInfo int_array_get_lower_bound_int;
173         static public MethodInfo int_array_get_upper_bound_int;
174         static public MethodInfo void_array_copyto_array_int;
175         
176         //
177         // The attribute constructors.
178         //
179         static public ConstructorInfo object_ctor;
180         static public ConstructorInfo cons_param_array_attribute;
181         static public ConstructorInfo void_decimal_ctor_five_args;
182         static public ConstructorInfo unverifiable_code_ctor;
183         static public ConstructorInfo invalid_operation_ctor;
184         static public ConstructorInfo default_member_ctor;
185         
186         // <remarks>
187         //   Holds the Array of Assemblies that have been loaded
188         //   (either because it is the default or the user used the
189         //   -r command line option)
190         // </remarks>
191         static Assembly [] assemblies;
192
193         // <remarks>
194         //  Keeps a list of modules. We used this to do lookups
195         //  on the module using GetType -- needed for arrays
196         // </remarks>
197         static Module [] modules;
198
199         // <remarks>
200         //   This is the type_cache from the assemblies to avoid
201         //   hitting System.Reflection on every lookup.
202         // </summary>
203         static Hashtable types;
204
205         // <remarks>
206         //  This is used to hotld the corresponding TypeContainer objects
207         //  since we need this in FindMembers
208         // </remarks>
209         static Hashtable typecontainers;
210
211         // <remarks>
212         //   Keeps track of those types that are defined by the
213         //   user's program
214         // </remarks>
215         static ArrayList user_types;
216
217         static PtrHashtable builder_to_declspace;
218
219         // <remarks>
220         //   Tracks the interfaces implemented by typebuilders.  We only
221         //   enter those who do implement or or more interfaces
222         // </remarks>
223         static PtrHashtable builder_to_ifaces;
224
225         // <remarks>
226         //   Maps MethodBase.RuntimeTypeHandle to a Type array that contains
227         //   the arguments to the method
228         // </remarks>
229         static Hashtable method_arguments;
230
231         // <remarks>
232         //   Maps PropertyBuilder to a Type array that contains
233         //   the arguments to the indexer
234         // </remarks>
235         static Hashtable indexer_arguments;
236
237         // <remarks>
238         //   Maybe `method_arguments' should be replaced and only
239         //   method_internal_params should be kept?
240         // <remarks>
241         static Hashtable method_internal_params;
242
243         // <remarks>
244         //  Keeps track of methods
245         // </remarks>
246
247         static Hashtable builder_to_method;
248
249         // <remarks>
250         //  Contains all public types from referenced assemblies.
251         //  This member is used only if CLS Compliance verification is required.
252         // </remarks>
253         public static Hashtable all_imported_types;
254
255         struct Signature {
256                 public string name;
257                 public Type [] args;
258         }
259         
260         public static void CleanUp ()
261         {
262                 // Lets get everything clean so that we can collect before generating code
263                 assemblies = null;
264                 modules = null;
265                 types = null;
266                 typecontainers = null;
267                 user_types = null;
268                 builder_to_declspace = null;
269                 builder_to_ifaces = null;
270                 method_arguments = null;
271                 indexer_arguments = null;
272                 method_internal_params = null;
273                 builder_to_method = null;
274                 
275                 fields = null;
276                 references = null;
277                 negative_hits = null;
278                 builder_to_constant = null;
279                 fieldbuilders_to_fields = null;
280                 events = null;
281                 priv_fields_events = null;
282                 properties = null;
283                 
284                 TypeHandle.CleanUp ();
285         }
286
287         /// <summary>
288         ///   A filter for Findmembers that uses the Signature object to
289         ///   extract objects
290         /// </summary>
291         static bool SignatureFilter (MemberInfo mi, object criteria)
292         {
293                 Signature sig = (Signature) criteria;
294
295                 if (!(mi is MethodBase))
296                         return false;
297                 
298                 if (mi.Name != sig.name)
299                         return false;
300
301                 int count = sig.args.Length;
302                 
303                 if (mi is MethodBuilder || mi is ConstructorBuilder){
304                         Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
305
306                         if (candidate_args.Length != count)
307                                 return false;
308                         
309                         for (int i = 0; i < count; i++)
310                                 if (candidate_args [i] != sig.args [i])
311                                         return false;
312                         
313                         return true;
314                 } else {
315                         ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
316
317                         if (pars.Length != count)
318                                 return false;
319
320                         for (int i = 0; i < count; i++)
321                                 if (pars [i].ParameterType != sig.args [i])
322                                         return false;
323                         return true;
324                 }
325         }
326
327         // A delegate that points to the filter above.
328         static MemberFilter signature_filter;
329
330         //
331         // These are expressions that represent some of the internal data types, used
332         // elsewhere
333         //
334         static void InitExpressionTypes ()
335         {
336                 system_object_expr  = new TypeLookupExpression ("System.Object");
337                 system_string_expr  = new TypeLookupExpression ("System.String");
338                 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
339                 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
340                 system_single_expr  = new TypeLookupExpression ("System.Single");
341                 system_double_expr  = new TypeLookupExpression ("System.Double");
342                 system_sbyte_expr   = new TypeLookupExpression ("System.SByte");
343                 system_byte_expr    = new TypeLookupExpression ("System.Byte");
344                 system_int16_expr   = new TypeLookupExpression ("System.Int16");
345                 system_uint16_expr  = new TypeLookupExpression ("System.UInt16");
346                 system_int32_expr   = new TypeLookupExpression ("System.Int32");
347                 system_uint32_expr  = new TypeLookupExpression ("System.UInt32");
348                 system_int64_expr   = new TypeLookupExpression ("System.Int64");
349                 system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
350                 system_char_expr    = new TypeLookupExpression ("System.Char");
351                 system_void_expr    = new TypeLookupExpression ("System.Void");
352                 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
353                 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
354                 system_valuetype_expr  = new TypeLookupExpression ("System.ValueType");
355                 system_intptr_expr  = new TypeLookupExpression ("System.IntPtr");
356         }
357
358         static TypeManager ()
359         {
360                 assemblies = new Assembly [0];
361                 modules = null;
362                 user_types = new ArrayList ();
363                 
364                 types = new Hashtable ();
365                 typecontainers = new Hashtable ();
366                 
367                 builder_to_declspace = new PtrHashtable ();
368                 builder_to_method = new PtrHashtable ();
369                 method_arguments = new PtrHashtable ();
370                 method_internal_params = new PtrHashtable ();
371                 indexer_arguments = new PtrHashtable ();
372                 builder_to_ifaces = new PtrHashtable ();
373                 
374                 NoTypes = new Type [0];
375                 NoTypeExprs = new TypeExpr [0];
376
377                 signature_filter = new MemberFilter (SignatureFilter);
378                 InitExpressionTypes ();
379         }
380
381         public static void HandleDuplicate (string name, Type t)
382         {
383                 Type prev = (Type) types [name];
384                 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
385                 
386                 if (tc != null){
387                         //
388                         // This probably never happens, as we catch this before
389                         //
390                         Report.Error (-17, "The type `" + name + "' has already been defined.");
391                         return;
392                 }
393                 
394                 tc = builder_to_declspace [t] as TypeContainer;
395                 if (tc != null){
396                         Report.Warning (
397                                         1595, "The type `" + name + "' is defined in an existing assembly;"+
398                                         " Using the new definition from: " + tc.Location);
399                 } else {
400                         Report.Warning (
401                                         1595, "The type `" + name + "' is defined in an existing assembly;");
402                 }
403                 
404                 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
405                 
406                 types.Remove (name);
407                 types.Add (name, t);
408         }
409         
410         public static void AddUserType (string name, TypeBuilder t, TypeExpr[] ifaces)
411         {
412                 try {
413                         types.Add (name, t);
414                 } catch {
415                         HandleDuplicate (name, t); 
416                 }
417                 user_types.Add (t);
418                         
419                 if (ifaces != null)
420                         builder_to_ifaces [t] = ifaces;
421         }
422
423         //
424         // This entry point is used by types that we define under the covers
425         // 
426         public static void RegisterBuilder (TypeBuilder tb, TypeExpr [] ifaces)
427         {
428                 if (ifaces != null)
429                         builder_to_ifaces [tb] = ifaces;
430         }
431         
432         public static void AddUserType (string name, TypeBuilder t, TypeContainer tc, TypeExpr [] ifaces)
433         {
434                 builder_to_declspace.Add (t, tc);
435                 typecontainers.Add (name, tc);
436                 AddUserType (name, t, ifaces);
437         }
438
439         public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
440         {
441                 try {
442                         types.Add (name, t);
443                 } catch {
444                         HandleDuplicate (name, t);
445                 }
446                 
447                 builder_to_declspace.Add (t, del);
448         }
449         
450         public static void AddEnumType (string name, TypeBuilder t, Enum en)
451         {
452                 try {
453                         types.Add (name, t);
454                 } catch {
455                         HandleDuplicate (name, t);
456                 }
457                 builder_to_declspace.Add (t, en);
458         }
459
460         public static void AddUserInterface (string name, TypeBuilder t, Interface i, TypeExpr [] ifaces)
461         {
462                 AddUserType (name, t, ifaces);
463                 builder_to_declspace.Add (t, i);
464         }
465
466
467         public static void AddMethod (MethodBase builder, IMethodData method)
468         {
469                 builder_to_method.Add (builder, method);
470         }
471
472         public static IMethodData GetMethod (MethodBase builder)
473         {
474                 return (IMethodData) builder_to_method [builder];
475         }
476
477         /// <summary>
478         ///   Returns the DeclSpace whose Type is `t' or null if there is no
479         ///   DeclSpace for `t' (ie, the Type comes from a library)
480         /// </summary>
481         public static DeclSpace LookupDeclSpace (Type t)
482         {
483                 return builder_to_declspace [t] as DeclSpace;
484         }
485
486         /// <summary>
487         ///   Returns the TypeContainer whose Type is `t' or null if there is no
488         ///   TypeContainer for `t' (ie, the Type comes from a library)
489         /// </summary>
490         public static TypeContainer LookupTypeContainer (Type t)
491         {
492                 return builder_to_declspace [t] as TypeContainer;
493         }
494         
495         /// <summary>
496         /// Fills member container from base interfaces
497         /// </summary>
498         public static IMemberContainer LookupInterfaceContainer (Type[] types)
499         {
500                 if (types == null)
501                         return null;
502
503                 IMemberContainer complete = null;
504                 foreach (Type t in types) {
505                         IMemberContainer one_type_cont = null;
506                         if (t is TypeBuilder) {
507                                 one_type_cont = builder_to_declspace [t] as IMemberContainer;
508                         } else
509                                 one_type_cont = TypeHandle.GetTypeHandle (t);
510
511                         if (complete == null) {
512                                 complete = one_type_cont;
513                                 continue;
514                         }
515
516                         // We need to avoid including same member more than once
517                         foreach (DictionaryEntry de in one_type_cont.MemberCache.Members) {
518                                 object o = complete.MemberCache.Members [de.Key];
519                                 if (o == null) {
520                                         complete.MemberCache.Members.Add (de.Key, de.Value);
521                                         continue;
522                                 }
523
524                                 ArrayList al_old = (ArrayList)o;
525                                 ArrayList al_new = (ArrayList)de.Value;
526
527                                 foreach (MemberCache.CacheEntry ce in al_new) {
528                                         bool exist = false;
529                                         foreach (MemberCache.CacheEntry ce_old in al_old) {
530                                                 if (ce.Member == ce_old.Member) {
531                                                         exist = true;
532                                                         break;
533                                                 }
534                                         }
535                                         if (!exist)
536                                                 al_old.Add (ce);
537                                 }
538                         }
539                 }
540                 return complete;
541         }
542
543         public static IMemberContainer LookupMemberContainer (Type t)
544         {
545                 if (t is TypeBuilder) {
546                         IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
547                         if (container != null)
548                                 return container;
549                 }
550
551                 return TypeHandle.GetTypeHandle (t);
552         }
553
554         public static TypeContainer LookupInterface (Type t)
555         {
556                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
557                 if ((tc == null) || (tc.Kind != Kind.Interface))
558                         return null;
559
560                 return tc;
561         }
562
563         public static Delegate LookupDelegate (Type t)
564         {
565                 return builder_to_declspace [t] as Delegate;
566         }
567
568         public static Enum LookupEnum (Type t)
569         {
570                 return builder_to_declspace [t] as Enum;
571         }
572
573         public static Class LookupClass (Type t)
574         {
575                 return (Class) builder_to_declspace [t];
576         }
577         
578         /// <summary>
579         ///   Registers an assembly to load types from.
580         /// </summary>
581         public static void AddAssembly (Assembly a)
582         {
583                 foreach (Assembly assembly in assemblies) {
584                         if (a == assembly)
585                                 return;
586                 }
587
588                 int top = assemblies.Length;
589                 Assembly [] n = new Assembly [top + 1];
590
591                 assemblies.CopyTo (n, 0);
592                 
593                 n [top] = a;
594                 assemblies = n;
595         }
596
597         public static Assembly [] GetAssemblies ()
598         {
599                 return assemblies;
600         }
601
602         /// <summary>
603         ///  Registers a module builder to lookup types from
604         /// </summary>
605         public static void AddModule (Module mb)
606         {
607                 int top = modules != null ? modules.Length : 0;
608                 Module [] n = new Module [top + 1];
609
610                 if (modules != null)
611                         modules.CopyTo (n, 0);
612                 n [top] = mb;
613                 modules = n;
614         }
615
616         public static Module[] Modules {
617                 get {
618                         return modules;
619                 }
620         }
621
622         static Hashtable references = new Hashtable ();
623         
624         //
625         // Gets the reference to T version of the Type (T&)
626         //
627         public static Type GetReferenceType (Type t)
628         {
629                 string tname = t.FullName + "&";
630                 
631                 Type ret = t.Assembly.GetType (tname);
632
633                 //
634                 // If the type comes from the assembly we are building
635                 // We need the Hashtable, because .NET 1.1 will return different instance types
636                 // every time we call ModuleBuilder.GetType.
637                 //
638                 if (ret == null){
639                         if (references [t] == null)
640                                 references [t] = CodeGen.Module.Builder.GetType (tname);
641                         ret = (Type) references [t];
642                 }
643
644                 return ret;
645         }
646
647         static Hashtable pointers = new Hashtable ();
648
649         //
650         // Gets the pointer to T version of the Type  (T*)
651         //
652         public static Type GetPointerType (Type t)
653         {
654                 string tname = t.FullName + "*";
655                 
656                 Type ret = t.Assembly.GetType (tname);
657                 
658                 //
659                 // If the type comes from the assembly we are building
660                 // We need the Hashtable, because .NET 1.1 will return different instance types
661                 // every time we call ModuleBuilder.GetType.
662                 //
663                 if (ret == null){
664                         if (pointers [t] == null)
665                                 pointers [t] = CodeGen.Module.Builder.GetType (tname);
666                         
667                         ret = (Type) pointers [t];
668                 }
669
670                 return ret;
671         }
672         
673         //
674         // Low-level lookup, cache-less
675         //
676         static Type LookupTypeReflection (string name)
677         {
678                 Type t;
679
680                 foreach (Assembly a in assemblies){
681                         t = a.GetType (name);
682                         if (t == null)
683                                 continue;
684
685                         do {
686                                 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
687                                 if (ta == TypeAttributes.NotPublic ||
688                                     ta == TypeAttributes.NestedPrivate ||
689                                     ta == TypeAttributes.NestedAssembly ||
690                                     ta == TypeAttributes.NestedFamANDAssem){
691                                         
692                                         //
693                                         // In .NET pointers turn out to be private, even if their
694                                         // element type is not
695                                         //
696                                         if (t.IsPointer){
697                                                 t = t.GetElementType ();
698                                                 continue;
699                                         } else
700                                                 t = null;
701                                 } else {
702                                         return t;
703                                 }
704                         } while (t != null);
705                 }
706
707                 foreach (Module mb in modules) {
708                         t = mb.GetType (name);
709                         if (t != null) 
710                                 return t;
711                 }
712                         
713                 return null;
714         }
715
716         static Hashtable negative_hits = new Hashtable ();
717         
718         //
719         // This function is used when you want to avoid the lookups, and want to go
720         // directly to the source.  This will use the cache.
721         //
722         // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
723         // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
724         // way to test things other than doing a fullname compare
725         //
726         public static Type LookupTypeDirect (string name)
727         {
728                 Type t = (Type) types [name];
729                 if (t != null)
730                         return t;
731                 
732                 if (negative_hits.Contains (name))
733                         return null;
734                 
735                 t = LookupTypeReflection (name);
736                 
737                 if (t == null)
738                         negative_hits [name] = null;
739                 else
740                         types [name] = t;
741                 
742                 return t;
743         }
744         
745         static readonly char [] dot_array = { '.' };
746
747         /// <summary>
748         ///   Returns the Type associated with @name, takes care of the fact that
749         ///   reflection expects nested types to be separated from the main type
750         ///   with a "+" instead of a "."
751         /// </summary>
752         public static Type LookupType (string name)
753         {
754                 Type t;
755
756                 //
757                 // First lookup in user defined and cached values
758                 //
759
760                 t = (Type) types [name];
761                 if (t != null)
762                         return t;
763
764                 // Two thirds of the failures are caught here.
765                 if (negative_hits.Contains (name))
766                         return null;
767
768                 // Sadly, split takes a param array, so this ends up allocating *EVERY TIME*
769                 string [] elements = name.Split (dot_array);
770                 int count = elements.Length;
771
772                 for (int n = 1; n <= count; n++){
773                         string top_level_type = String.Join (".", elements, 0, n);
774
775                         // One third of the failures are caught here.
776                         if (negative_hits.Contains (top_level_type))
777                                 continue;
778                         
779                         t = (Type) types [top_level_type];
780                         if (t == null){
781                                 t = LookupTypeReflection (top_level_type);
782                                 if (t == null){
783                                         negative_hits [top_level_type] = null;
784                                         continue;
785                                 }
786                         }
787                         
788                         if (count == n){
789                                 types [name] = t;
790                                 return t;
791                         } 
792
793                         //
794                         // We know that System.Object does not have children, and since its the parent of 
795                         // all the objects, it always gets probbed for inner classes. 
796                         //
797                         if (top_level_type == "System.Object")
798                                 return null;
799                         
800                         string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
801                         //Console.WriteLine ("Looking up: " + newt + " " + name);
802                         t = LookupTypeReflection (newt);
803                         if (t == null)
804                                 negative_hits [name] = null;
805                         else
806                                 types [name] = t;
807                         return t;
808                 }
809                 negative_hits [name] = null;
810                 return null;
811         }
812
813         /// <summary>
814         ///   Computes the namespaces that we import from the assemblies we reference.
815         /// </summary>
816         public static void ComputeNamespaces ()
817         {
818                 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
819
820                 //
821                 // First add the assembly namespaces
822                 //
823                 if (assembly_get_namespaces != null){
824                         int count = assemblies.Length;
825
826                         for (int i = 0; i < count; i++){
827                                 Assembly a = assemblies [i];
828                                 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
829                                 foreach (string ns in namespaces){
830                                         if (ns == "")
831                                                 continue;
832                                         Namespace.LookupNamespace (ns, true);
833                                 }
834                         }
835                 } else {
836                         Hashtable cache = new Hashtable ();
837                         cache.Add ("", null);
838                         foreach (Assembly a in assemblies) {
839                                 foreach (Type t in a.GetExportedTypes ()) {
840                                         string ns = t.Namespace;
841                                         if (ns == null || cache.Contains (ns))
842                                                 continue;
843
844                                         Namespace.LookupNamespace (ns, true);
845                                         cache.Add (ns, null);
846                                 }
847                         }
848                 }
849         }
850
851         /// <summary>
852         /// Fills static table with exported types from all referenced assemblies.
853         /// This information is required for CLS Compliance tests.
854         /// </summary>
855         public static void LoadAllImportedTypes ()
856         {
857                 all_imported_types = new Hashtable ();
858                 foreach (Assembly a in assemblies) {
859                         foreach (Type t in a.GetExportedTypes ()) {
860                                 all_imported_types [t.FullName] = t;
861                         }
862                 }
863         }
864
865         public static bool NamespaceClash (string name, Location loc)
866         {
867                 if (Namespace.LookupNamespace (name, false) == null)
868                         return false;
869
870                 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
871                 return true;
872         }
873
874         /// <summary>
875         ///   Returns the C# name of a type if possible, or the full type name otherwise
876         /// </summary>
877         static public string CSharpName (Type t)
878         {
879                 return Regex.Replace (t.FullName, 
880                         @"^System\." +
881                         @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
882                         @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
883                         @"Boolean|String|Void|Null)" +
884                         @"(\W+|\b)", 
885                         new MatchEvaluator (CSharpNameMatch));
886         }       
887         
888         static String CSharpNameMatch (Match match) 
889         {
890                 string s = match.Groups [1].Captures [0].Value;
891                 return s.ToLower ().
892                 Replace ("int32", "int").
893                 Replace ("uint32", "uint").
894                 Replace ("int16", "short").
895                 Replace ("uint16", "ushort").
896                 Replace ("int64", "long").
897                 Replace ("uint64", "ulong").
898                 Replace ("single", "float").
899                 Replace ("boolean", "bool")
900                 + match.Groups [2].Captures [0].Value;
901         }
902
903         /// <summary>
904         ///  Returns the signature of the method with full namespace classification
905         /// </summary>
906         static public string GetFullNameSignature (MemberInfo mi)
907         {
908                 return mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
909         }
910
911         static public string GetFullNameSignature (MethodBase mb)
912         {
913                 string name = mb.Name;
914                 if (name == ".ctor")
915                         name = mb.DeclaringType.Name;
916
917                 if (mb.IsSpecialName) {
918                         if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
919                                 name = name.Remove (0, 4);
920                         }
921
922                         if (name == "Item")
923                                 name = "this";
924                 }
925
926                 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
927         }
928
929         /// <summary>
930         ///   Returns the signature of the property and indexer
931         /// </summary>
932         static public string CSharpSignature (PropertyBuilder pb, bool is_indexer) 
933         {
934                 if (!is_indexer) {
935                         return GetFullNameSignature (pb);
936                 }
937
938                 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
939                 string signature = GetFullNameSignature (mb);
940                 string arg = TypeManager.LookupParametersByBuilder (mb).ParameterDesc (0);
941                 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
942         }
943
944         /// <summary>
945         ///   Returns the signature of the method
946         /// </summary>
947         static public string CSharpSignature (MethodBase mb)
948         {
949                 StringBuilder sig = new StringBuilder ("(");
950
951                 //
952                 // FIXME: We should really have a single function to do
953                 // everything instead of the following 5 line pattern
954                 //
955                 ParameterData iparams = LookupParametersByBuilder (mb);
956
957                 if (iparams == null)
958                         iparams = new ReflectionParameters (mb);
959
960                 // Is property
961                 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
962                         return GetFullNameSignature (mb);
963                 
964                 for (int i = 0; i < iparams.Count; i++) {
965                         if (i > 0) {
966                                 sig.Append (", ");
967                         }
968                         sig.Append (iparams.ParameterDesc (i));
969                 }
970                 sig.Append (")");
971
972                 // Is indexer
973                 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
974                         sig.Replace ('(', '[');
975                         sig.Replace (')', ']');
976                 }
977
978                 return GetFullNameSignature (mb) + sig.ToString ();
979         }
980
981         /// <summary>
982         ///   Looks up a type, and aborts if it is not found.  This is used
983         ///   by types required by the compiler
984         /// </summary>
985         static Type CoreLookupType (string name)
986         {
987                 Type t = LookupTypeDirect (name);
988
989                 if (t == null){
990                         Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
991                         Environment.Exit (1);
992                 }
993
994                 return t;
995         }
996
997         /// <summary>
998         ///   Returns the MethodInfo for a method named `name' defined
999         ///   in type `t' which takes arguments of types `args'
1000         /// </summary>
1001         static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
1002         {
1003                 MemberList list;
1004                 Signature sig;
1005                 BindingFlags flags = instance_and_static | BindingFlags.Public;
1006
1007                 sig.name = name;
1008                 sig.args = args;
1009
1010                 if (is_private)
1011                         flags |= BindingFlags.NonPublic;
1012
1013                 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
1014                 if (list.Count == 0) {
1015                         if (report_errors)
1016                                 Report.Error (-19, "Can not find the core function `" + name + "'");
1017                         return null;
1018                 }
1019
1020                 MethodInfo mi = list [0] as MethodInfo;
1021                 if (mi == null) {
1022                         if (report_errors)
1023                                 Report.Error (-19, "Can not find the core function `" + name + "'");
1024                         return null;
1025                 }
1026
1027                 return mi;
1028         }
1029
1030         static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
1031         {
1032                 return GetMethod (t, name, args, false, report_errors);
1033         }
1034
1035         static MethodInfo GetMethod (Type t, string name, Type [] args)
1036         {
1037                 return GetMethod (t, name, args, true);
1038         }
1039
1040
1041         /// <summary>
1042         ///    Returns the ConstructorInfo for "args"
1043         /// </summary>
1044         static ConstructorInfo GetConstructor (Type t, Type [] args)
1045         {
1046                 MemberList list;
1047                 Signature sig;
1048
1049                 sig.name = ".ctor";
1050                 sig.args = args;
1051                 
1052                 list = FindMembers (t, MemberTypes.Constructor,
1053                                     instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
1054                                     signature_filter, sig);
1055                 if (list.Count == 0){
1056                         Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1057                         return null;
1058                 }
1059
1060                 ConstructorInfo ci = list [0] as ConstructorInfo;
1061                 if (ci == null){
1062                         Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1063                         return null;
1064                 }
1065
1066                 return ci;
1067         }
1068
1069         public static void InitEnumUnderlyingTypes ()
1070         {
1071
1072                 int32_type    = CoreLookupType ("System.Int32");
1073                 int64_type    = CoreLookupType ("System.Int64");
1074                 uint32_type   = CoreLookupType ("System.UInt32"); 
1075                 uint64_type   = CoreLookupType ("System.UInt64"); 
1076                 byte_type     = CoreLookupType ("System.Byte");
1077                 sbyte_type    = CoreLookupType ("System.SByte");
1078                 short_type    = CoreLookupType ("System.Int16");
1079                 ushort_type   = CoreLookupType ("System.UInt16");
1080         }
1081         
1082         /// <remarks>
1083         ///   The types have to be initialized after the initial
1084         ///   population of the type has happened (for example, to
1085         ///   bootstrap the corlib.dll
1086         /// </remarks>
1087         public static void InitCoreTypes ()
1088         {
1089                 object_type   = CoreLookupType ("System.Object");
1090                 value_type    = CoreLookupType ("System.ValueType");
1091
1092                 InitEnumUnderlyingTypes ();
1093
1094                 char_type     = CoreLookupType ("System.Char");
1095                 string_type   = CoreLookupType ("System.String");
1096                 float_type    = CoreLookupType ("System.Single");
1097                 double_type   = CoreLookupType ("System.Double");
1098                 char_ptr_type = CoreLookupType ("System.Char*");
1099                 decimal_type  = CoreLookupType ("System.Decimal");
1100                 bool_type     = CoreLookupType ("System.Boolean");
1101                 enum_type     = CoreLookupType ("System.Enum");
1102
1103                 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1104                 delegate_type           = CoreLookupType ("System.Delegate");
1105
1106                 array_type    = CoreLookupType ("System.Array");
1107                 void_type     = CoreLookupType ("System.Void");
1108                 type_type     = CoreLookupType ("System.Type");
1109
1110                 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1111                 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1112                 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1113                 default_member_type  = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1114                 runtime_handle_type  = CoreLookupType ("System.RuntimeTypeHandle");
1115                 asynccallback_type   = CoreLookupType ("System.AsyncCallback");
1116                 iasyncresult_type    = CoreLookupType ("System.IAsyncResult");
1117                 ienumerator_type     = CoreLookupType ("System.Collections.IEnumerator");
1118                 ienumerable_type     = CoreLookupType ("System.Collections.IEnumerable");
1119                 idisposable_type     = CoreLookupType ("System.IDisposable");
1120                 icloneable_type      = CoreLookupType ("System.ICloneable");
1121                 iconvertible_type    = CoreLookupType ("System.IConvertible");
1122                 monitor_type         = CoreLookupType ("System.Threading.Monitor");
1123                 intptr_type          = CoreLookupType ("System.IntPtr");
1124
1125                 attribute_type       = CoreLookupType ("System.Attribute");
1126                 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1127                 dllimport_type       = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1128                 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1129                 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1130                 param_array_type     = CoreLookupType ("System.ParamArrayAttribute");
1131                 in_attribute_type    = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1132                 typed_reference_type = CoreLookupType ("System.TypedReference");
1133                 arg_iterator_type    = CoreLookupType ("System.ArgIterator");
1134                 mbr_type             = CoreLookupType ("System.MarshalByRefObject");
1135
1136                 //
1137                 // Sigh. Remove this before the release.  Wonder what versions of Mono
1138                 // people are running.
1139                 //
1140                 guid_attr_type        = LookupType ("System.Runtime.InteropServices.GuidAttribute");
1141
1142                 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1143
1144                 void_ptr_type         = CoreLookupType ("System.Void*");
1145
1146                 indexer_name_type     = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1147
1148                 exception_type        = CoreLookupType ("System.Exception");
1149                 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1150                 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1151
1152                 //
1153                 // Attribute types
1154                 //
1155                 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1156                 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1157                 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1158                 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1159                 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1160                 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1161
1162                 //
1163                 // When compiling corlib, store the "real" types here.
1164                 //
1165                 if (!RootContext.StdLib) {
1166                         system_int32_type = typeof (System.Int32);
1167                         system_array_type = typeof (System.Array);
1168                         system_type_type = typeof (System.Type);
1169                         system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1170
1171                         Type [] void_arg = {  };
1172                         system_int_array_get_length = GetMethod (
1173                                 system_array_type, "get_Length", void_arg);
1174                         system_int_array_get_rank = GetMethod (
1175                                 system_array_type, "get_Rank", void_arg);
1176                         system_object_array_clone = GetMethod (
1177                                 system_array_type, "Clone", void_arg);
1178
1179                         Type [] system_int_arg = { system_int32_type };
1180                         system_int_array_get_length_int = GetMethod (
1181                                 system_array_type, "GetLength", system_int_arg);
1182                         system_int_array_get_upper_bound_int = GetMethod (
1183                                 system_array_type, "GetUpperBound", system_int_arg);
1184                         system_int_array_get_lower_bound_int = GetMethod (
1185                                 system_array_type, "GetLowerBound", system_int_arg);
1186
1187                         Type [] system_array_int_arg = { system_array_type, system_int32_type };
1188                         system_void_array_copyto_array_int = GetMethod (
1189                                 system_array_type, "CopyTo", system_array_int_arg);
1190
1191                         Type [] system_3_type_arg = {
1192                                 system_type_type, system_type_type, system_type_type };
1193                         Type [] system_4_type_arg = {
1194                                 system_type_type, system_type_type, system_type_type, system_type_type };
1195
1196                         MethodInfo set_corlib_type_builders = GetMethod (
1197                                 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1198                                 system_4_type_arg, true, false);
1199
1200                         if (set_corlib_type_builders != null) {
1201                                 object[] args = new object [4];
1202                                 args [0] = object_type;
1203                                 args [1] = value_type;
1204                                 args [2] = enum_type;
1205                                 args [3] = void_type;
1206                                 
1207                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1208                         } else {
1209                                 // Compatibility for an older version of the class libs.
1210                                 set_corlib_type_builders = GetMethod (
1211                                         system_assemblybuilder_type, "SetCorlibTypeBuilders",
1212                                         system_3_type_arg, true, true);
1213
1214                                 if (set_corlib_type_builders == null) {
1215                                         Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1216                                         return;
1217                                 }
1218
1219                                 object[] args = new object [3];
1220                                 args [0] = object_type;
1221                                 args [1] = value_type;
1222                                 args [2] = enum_type;
1223                                 
1224                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1225                         }
1226                 }
1227
1228                 system_object_expr.Type = object_type;
1229                 system_string_expr.Type = string_type;
1230                 system_boolean_expr.Type = bool_type;
1231                 system_decimal_expr.Type = decimal_type;
1232                 system_single_expr.Type = float_type;
1233                 system_double_expr.Type = double_type;
1234                 system_sbyte_expr.Type = sbyte_type;
1235                 system_byte_expr.Type = byte_type;
1236                 system_int16_expr.Type = short_type;
1237                 system_uint16_expr.Type = ushort_type;
1238                 system_int32_expr.Type = int32_type;
1239                 system_uint32_expr.Type = uint32_type;
1240                 system_int64_expr.Type = int64_type;
1241                 system_uint64_expr.Type = uint64_type;
1242                 system_char_expr.Type = char_type;
1243                 system_void_expr.Type = void_type;
1244                 system_asynccallback_expr.Type = asynccallback_type;
1245                 system_iasyncresult_expr.Type = iasyncresult_type;
1246                 system_valuetype_expr.Type = value_type;
1247
1248                 //
1249                 // These are only used for compare purposes
1250                 //
1251                 anonymous_method_type = typeof (AnonymousMethod);
1252         }
1253
1254         //
1255         // The helper methods that are used by the compiler
1256         //
1257         public static void InitCodeHelpers ()
1258         {
1259                 //
1260                 // Now load the default methods that we use.
1261                 //
1262                 Type [] string_string = { string_type, string_type };
1263                 string_concat_string_string = GetMethod (
1264                         string_type, "Concat", string_string);
1265                 Type [] string_string_string = { string_type, string_type, string_type };
1266                 string_concat_string_string_string = GetMethod (
1267                         string_type, "Concat", string_string_string);
1268                 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1269                 string_concat_string_string_string_string = GetMethod (
1270                         string_type, "Concat", string_string_string_string);
1271                 Type[] params_string = { TypeManager.LookupType ("System.String[]") };
1272                 string_concat_string_dot_dot_dot = GetMethod (
1273                         string_type, "Concat", params_string);
1274
1275                 Type [] object_object = { object_type, object_type };
1276                 string_concat_object_object = GetMethod (
1277                         string_type, "Concat", object_object);
1278                 Type [] object_object_object = { object_type, object_type, object_type };
1279                 string_concat_object_object_object = GetMethod (
1280                         string_type, "Concat", object_object_object);
1281                 Type[] params_object = { TypeManager.LookupType ("System.Object[]") };
1282                 string_concat_object_dot_dot_dot = GetMethod (
1283                         string_type, "Concat", params_object);
1284
1285                 Type [] string_ = { string_type };
1286                 string_isinterneted_string = GetMethod (
1287                         string_type, "IsInterned", string_);
1288                 
1289                 Type [] runtime_type_handle = { runtime_handle_type };
1290                 system_type_get_type_from_handle = GetMethod (
1291                         type_type, "GetTypeFromHandle", runtime_type_handle);
1292
1293                 Type [] delegate_delegate = { delegate_type, delegate_type };
1294                 delegate_combine_delegate_delegate = GetMethod (
1295                                 delegate_type, "Combine", delegate_delegate);
1296
1297                 delegate_remove_delegate_delegate = GetMethod (
1298                                 delegate_type, "Remove", delegate_delegate);
1299
1300                 //
1301                 // Void arguments
1302                 //
1303                 Type [] void_arg = {  };
1304                 object_getcurrent_void = GetMethod (
1305                         ienumerator_type, "get_Current", void_arg);
1306                 bool_movenext_void = GetMethod (
1307                         ienumerator_type, "MoveNext", void_arg);
1308                 void_reset_void = GetMethod (
1309                         ienumerator_type, "Reset", void_arg);
1310                 void_dispose_void = GetMethod (
1311                         idisposable_type, "Dispose", void_arg);
1312                 int_get_offset_to_string_data = GetMethod (
1313                         runtime_helpers_type, "get_OffsetToStringData", void_arg);
1314                 int_array_get_length = GetMethod (
1315                         array_type, "get_Length", void_arg);
1316                 int_array_get_rank = GetMethod (
1317                         array_type, "get_Rank", void_arg);
1318                 ienumerable_getenumerator_void = GetMethod (
1319                         ienumerable_type, "GetEnumerator", void_arg);
1320                 
1321                 //
1322                 // Int32 arguments
1323                 //
1324                 Type [] int_arg = { int32_type };
1325                 int_array_get_length_int = GetMethod (
1326                         array_type, "GetLength", int_arg);
1327                 int_array_get_upper_bound_int = GetMethod (
1328                         array_type, "GetUpperBound", int_arg);
1329                 int_array_get_lower_bound_int = GetMethod (
1330                         array_type, "GetLowerBound", int_arg);
1331
1332                 //
1333                 // System.Array methods
1334                 //
1335                 object_array_clone = GetMethod (
1336                         array_type, "Clone", void_arg);
1337                 Type [] array_int_arg = { array_type, int32_type };
1338                 void_array_copyto_array_int = GetMethod (
1339                         array_type, "CopyTo", array_int_arg);
1340                 
1341                 //
1342                 // object arguments
1343                 //
1344                 Type [] object_arg = { object_type };
1345                 void_monitor_enter_object = GetMethod (
1346                         monitor_type, "Enter", object_arg);
1347                 void_monitor_exit_object = GetMethod (
1348                         monitor_type, "Exit", object_arg);
1349
1350                 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1351                 
1352                 void_initializearray_array_fieldhandle = GetMethod (
1353                         runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1354
1355                 //
1356                 // Array functions
1357                 //
1358                 int_getlength_int = GetMethod (
1359                         array_type, "GetLength", int_arg);
1360
1361                 //
1362                 // Decimal constructors
1363                 //
1364                 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1365                 void_decimal_ctor_five_args = GetConstructor (
1366                         decimal_type, dec_arg);
1367                 
1368                 //
1369                 // Attributes
1370                 //
1371                 cons_param_array_attribute = GetConstructor (
1372                         param_array_type, void_arg);
1373
1374                 unverifiable_code_ctor = GetConstructor (
1375                         unverifiable_code_type, void_arg);
1376
1377                 default_member_ctor = GetConstructor (default_member_type, string_);
1378
1379                 //
1380                 // InvalidOperationException
1381                 //
1382                 invalid_operation_ctor = GetConstructor (
1383                         invalid_operation_exception_type, void_arg);
1384
1385
1386                 // Object
1387                 object_ctor = GetConstructor (object_type, void_arg);
1388
1389         }
1390
1391         const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1392
1393         /// <remarks>
1394         ///   This is the "old", non-cache based FindMembers() function.  We cannot use
1395         ///   the cache here because there is no member name argument.
1396         /// </remarks>
1397         public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1398                                               MemberFilter filter, object criteria)
1399         {
1400                 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1401
1402                 //
1403                 // `builder_to_declspace' contains all dynamic types.
1404                 //
1405                 if (decl != null) {
1406                         MemberList list;
1407                         Timer.StartTimer (TimerType.FindMembers);
1408                         list = decl.FindMembers (mt, bf, filter, criteria);
1409                         Timer.StopTimer (TimerType.FindMembers);
1410                         return list;
1411                 }
1412
1413                 //
1414                 // We have to take care of arrays specially, because GetType on
1415                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1416                 // and we can not call FindMembers on this type.
1417                 //
1418                 if (t.IsSubclassOf (TypeManager.array_type))
1419                         return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1420
1421                 //
1422                 // Since FindMembers will not lookup both static and instance
1423                 // members, we emulate this behaviour here.
1424                 //
1425                 if ((bf & instance_and_static) == instance_and_static){
1426                         MemberInfo [] i_members = t.FindMembers (
1427                                 mt, bf & ~BindingFlags.Static, filter, criteria);
1428
1429                         int i_len = i_members.Length;
1430                         if (i_len == 1){
1431                                 MemberInfo one = i_members [0];
1432
1433                                 //
1434                                 // If any of these are present, we are done!
1435                                 //
1436                                 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1437                                         return new MemberList (i_members);
1438                         }
1439                                 
1440                         MemberInfo [] s_members = t.FindMembers (
1441                                 mt, bf & ~BindingFlags.Instance, filter, criteria);
1442
1443                         int s_len = s_members.Length;
1444                         if (i_len > 0 || s_len > 0)
1445                                 return new MemberList (i_members, s_members);
1446                         else {
1447                                 if (i_len > 0)
1448                                         return new MemberList (i_members);
1449                                 else
1450                                         return new MemberList (s_members);
1451                         }
1452                 }
1453
1454                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1455         }
1456
1457
1458         /// <summary>
1459         ///   This method is only called from within MemberLookup.  It tries to use the member
1460         ///   cache if possible and falls back to the normal FindMembers if not.  The `used_cache'
1461         ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
1462         ///   our return value will already contain all inherited members and the caller don't need
1463         ///   to check base classes and interfaces anymore.
1464         /// </summary>
1465         private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1466                                                             string name, out bool used_cache)
1467         {
1468                 //
1469                 // We have to take care of arrays specially, because GetType on
1470                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1471                 // and we can not call FindMembers on this type.
1472                 //
1473                 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1474                         used_cache = true;
1475                         return TypeHandle.ArrayType.MemberCache.FindMembers (
1476                                 mt, bf, name, FilterWithClosure_delegate, null);
1477                 }
1478
1479                 //
1480                 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1481                 // and we can ask the DeclSpace for the MemberCache.
1482                 //
1483                 if (t is TypeBuilder) {
1484                         DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1485                         MemberCache cache = decl.MemberCache;
1486
1487                         //
1488                         // If this DeclSpace has a MemberCache, use it.
1489                         //
1490
1491                         if (cache != null) {
1492                                 used_cache = true;
1493                                 return cache.FindMembers (
1494                                         mt, bf, name, FilterWithClosure_delegate, null);
1495                         }
1496
1497                         // If there is no MemberCache, we need to use the "normal" FindMembers.
1498                         // Note, this is a VERY uncommon route!
1499                         
1500                         MemberList list;
1501                         Timer.StartTimer (TimerType.FindMembers);
1502                         list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1503                                                  FilterWithClosure_delegate, name);
1504                         Timer.StopTimer (TimerType.FindMembers);
1505                         used_cache = false;
1506                         
1507                         return (MemberInfo []) list;
1508                 }
1509
1510                 //
1511                 // This call will always succeed.  There is exactly one TypeHandle instance per
1512                 // type, TypeHandle.GetTypeHandle() will either return it or create a new one
1513                 // if it didn't already exist.
1514                 //
1515                 TypeHandle handle = TypeHandle.GetTypeHandle (t);
1516
1517                 used_cache = true;
1518                 return handle.MemberCache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1519         }
1520
1521         public static bool IsBuiltinType (Type t)
1522         {
1523                 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1524                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1525                     t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1526                     t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1527                         return true;
1528                 else
1529                         return false;
1530         }
1531
1532         public static bool IsBuiltinType (TypeContainer tc)
1533         {
1534                 return IsBuiltinType (tc.TypeBuilder);
1535         }
1536
1537         //
1538         // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1539         // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1540         // 
1541         public static bool IsCLRType (Type t)
1542         {
1543                 if (t == object_type || t == int32_type || t == uint32_type ||
1544                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1545                     t == char_type || t == short_type || t == bool_type ||
1546                     t == sbyte_type || t == byte_type || t == ushort_type)
1547                         return true;
1548                 else
1549                         return false;
1550         }
1551
1552         public static bool IsDelegateType (Type t)
1553         {
1554                 if (t.IsSubclassOf (TypeManager.delegate_type))
1555                         return true;
1556                 else
1557                         return false;
1558         }
1559         
1560         public static bool IsEnumType (Type t)
1561         {
1562                 if (t.IsSubclassOf (TypeManager.enum_type))
1563                         return true;
1564                 else
1565                         return false;
1566         }
1567         public static bool IsBuiltinOrEnum (Type t)
1568         {
1569                 if (IsBuiltinType (t))
1570                         return true;
1571                 
1572                 if (IsEnumType (t))
1573                         return true;
1574
1575                 return false;
1576         }
1577
1578         //
1579         // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
1580         //
1581         public static bool IsUnmanagedType (Type t)
1582         {
1583                 if (IsBuiltinType (t) && t != TypeManager.string_type)
1584                         return true;
1585
1586                 if (IsEnumType (t))
1587                         return true;
1588
1589                 if (t.IsPointer)
1590                         return true;
1591
1592                 if (IsValueType (t)){
1593                         if (t is TypeBuilder){
1594                                 TypeContainer tc = LookupTypeContainer (t);
1595
1596                                 if (tc.Fields != null){
1597                                         foreach (Field f in tc.Fields){
1598                                                 if (f.FieldBuilder.IsStatic)
1599                                                         continue;
1600                                                 if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1601                                                         return false;
1602                                         }
1603                                 } else
1604                                         return true;
1605                         } else {
1606                                 FieldInfo [] fields = t.GetFields ();
1607
1608                                 foreach (FieldInfo f in fields){
1609                                         if (f.IsStatic)
1610                                                 continue;
1611                                         if (!IsUnmanagedType (f.FieldType))
1612                                                 return false;
1613                                 }
1614                         }
1615                         return true;
1616                 }
1617
1618                 return false;
1619         }
1620                 
1621         public static bool IsValueType (Type t)
1622         {
1623                 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1624                         return true;
1625                 else
1626                         return false;
1627         }
1628         
1629         public static bool IsInterfaceType (Type t)
1630         {
1631                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1632                 if (tc == null)
1633                         return false;
1634
1635                 return tc.Kind == Kind.Interface;
1636         }
1637
1638         //
1639         // Checks whether `type' is a subclass or nested child of `parent'.
1640         //
1641         public static bool IsSubclassOrNestedChildOf (Type type, Type parent)
1642         {
1643                 do {
1644                         if ((type == parent) || type.IsSubclassOf (parent))
1645                                 return true;
1646
1647                         // Handle nested types.
1648                         type = type.DeclaringType;
1649                 } while (type != null);
1650
1651                 return false;
1652         }
1653
1654         //
1655         // Checks whether `type' is a nested child of `parent'.
1656         //
1657         public static bool IsNestedChildOf (Type type, Type parent)
1658         {
1659                 if (type == parent)
1660                         return false;
1661
1662                 type = type.DeclaringType;
1663                 while (type != null) {
1664                         if (type == parent)
1665                                 return true;
1666
1667                         type = type.DeclaringType;
1668                 }
1669
1670                 return false;
1671         }
1672
1673         //
1674         // Do the right thing when returning the element type of an
1675         // array type based on whether we are compiling corlib or not
1676         //
1677         public static Type GetElementType (Type t)
1678         {
1679                 if (RootContext.StdLib)
1680                         return t.GetElementType ();
1681                 else
1682                         return TypeToCoreType (t.GetElementType ());
1683         }
1684
1685         /// <summary>
1686         ///   Returns the User Defined Types
1687         /// </summary>
1688         public static ArrayList UserTypes {
1689                 get {
1690                         return user_types;
1691                 }
1692         }
1693
1694         public static Hashtable TypeContainers {
1695                 get {
1696                         return typecontainers;
1697                 }
1698         }
1699
1700         static Hashtable builder_to_constant;
1701
1702         public static void RegisterConstant (FieldBuilder fb, Const c)
1703         {
1704                 if (builder_to_constant == null)
1705                         builder_to_constant = new PtrHashtable ();
1706
1707                 if (builder_to_constant.Contains (fb))
1708                         return;
1709
1710                 builder_to_constant.Add (fb, c);
1711         }
1712
1713         public static Const LookupConstant (FieldBuilder fb)
1714         {
1715                 if (builder_to_constant == null)
1716                         return null;
1717                 
1718                 return (Const) builder_to_constant [fb];
1719         }
1720         
1721         /// <summary>
1722         ///   Gigantic work around for missing features in System.Reflection.Emit follows.
1723         /// </summary>
1724         ///
1725         /// <remarks>
1726         ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
1727         ///   for anything which is dynamic, and we need this in a number of places,
1728         ///   we register this information here, and use it afterwards.
1729         /// </remarks>
1730         static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1731         {
1732                 if (args == null)
1733                         args = NoTypes;
1734                                 
1735                 method_arguments.Add (mb, args);
1736                 method_internal_params.Add (mb, ip);
1737         }
1738         
1739         static public InternalParameters LookupParametersByBuilder (MethodBase mb)
1740         {
1741                 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
1742                         return null;
1743                 
1744                 if (method_internal_params.Contains (mb))
1745                         return (InternalParameters) method_internal_params [mb];
1746                 else
1747                         throw new Exception ("Argument for Method not registered" + mb);
1748         }
1749
1750         /// <summary>
1751         ///    Returns the argument types for a method based on its methodbase
1752         ///
1753         ///    For dynamic methods, we use the compiler provided types, for
1754         ///    methods from existing assemblies we load them from GetParameters,
1755         ///    and insert them into the cache
1756         /// </summary>
1757         static public Type [] GetArgumentTypes (MethodBase mb)
1758         {
1759                 object t = method_arguments [mb];
1760                 if (t != null)
1761                         return (Type []) t;
1762
1763                 ParameterInfo [] pi = mb.GetParameters ();
1764                 int c = pi.Length;
1765                 Type [] types;
1766
1767                 if (c == 0) {
1768                         types = NoTypes;
1769                 } else {
1770                         types = new Type [c];
1771                         for (int i = 0; i < c; i++)
1772                                 types [i] = pi [i].ParameterType;
1773                 }
1774                 method_arguments.Add (mb, types);
1775                 return types;
1776         }
1777
1778         /// <summary>
1779         ///    Returns the argument types for an indexer based on its PropertyInfo
1780         ///
1781         ///    For dynamic indexers, we use the compiler provided types, for
1782         ///    indexers from existing assemblies we load them from GetParameters,
1783         ///    and insert them into the cache
1784         /// </summary>
1785         static public Type [] GetArgumentTypes (PropertyInfo indexer)
1786         {
1787                 if (indexer_arguments.Contains (indexer))
1788                         return (Type []) indexer_arguments [indexer];
1789                 else if (indexer is PropertyBuilder)
1790                         // If we're a PropertyBuilder and not in the
1791                         // `indexer_arguments' hash, then we're a property and
1792                         // not an indexer.
1793                         return NoTypes;
1794                 else {
1795                         ParameterInfo [] pi = indexer.GetIndexParameters ();
1796                         // Property, not an indexer.
1797                         if (pi == null)
1798                                 return NoTypes;
1799                         int c = pi.Length;
1800                         Type [] types = new Type [c];
1801                         
1802                         for (int i = 0; i < c; i++)
1803                                 types [i] = pi [i].ParameterType;
1804
1805                         indexer_arguments.Add (indexer, types);
1806                         return types;
1807                 }
1808         }
1809         
1810         // <remarks>
1811         //  This is a workaround the fact that GetValue is not
1812         //  supported for dynamic types
1813         // </remarks>
1814         static Hashtable fields = new Hashtable ();
1815         static public bool RegisterFieldValue (FieldBuilder fb, object value)
1816         {
1817                 if (fields.Contains (fb))
1818                         return false;
1819
1820                 fields.Add (fb, value);
1821
1822                 return true;
1823         }
1824
1825         static public object GetValue (FieldBuilder fb)
1826         {
1827                 return fields [fb];
1828         }
1829
1830         static Hashtable fieldbuilders_to_fields = new Hashtable ();
1831         static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1832         {
1833                 if (fieldbuilders_to_fields.Contains (fb))
1834                         return false;
1835
1836                 fieldbuilders_to_fields.Add (fb, f);
1837                 return true;
1838         }
1839
1840         //
1841         // The return value can be null;  This will be the case for
1842         // auxiliary FieldBuilders created by the compiler that have no
1843         // real field being declared on the source code
1844         //
1845         static public FieldBase GetField (FieldInfo fb)
1846         {
1847                 return (FieldBase) fieldbuilders_to_fields [fb];
1848         }
1849         
1850         static Hashtable events;
1851
1852         static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1853         {
1854                 if (events == null)
1855                         events = new Hashtable ();
1856
1857                 if (!events.Contains (eb)) {
1858                         events.Add (eb, new Pair (add, remove));
1859                 }
1860         }
1861
1862         static public MethodInfo GetAddMethod (EventInfo ei)
1863         {
1864                 if (ei is MyEventBuilder) {
1865                         Pair pair = (Pair) events [ei];
1866
1867                         return (MethodInfo) pair.First;
1868                 }
1869                 return ei.GetAddMethod (true);
1870         }
1871
1872         static public MethodInfo GetRemoveMethod (EventInfo ei)
1873         {
1874                 if (ei is MyEventBuilder) {
1875                         Pair pair = (Pair) events [ei];
1876
1877                         return (MethodInfo) pair.Second;
1878                 }
1879                 return ei.GetRemoveMethod (true);
1880         }
1881
1882         static Hashtable priv_fields_events;
1883
1884         static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1885         {
1886                 if (priv_fields_events == null)
1887                         priv_fields_events = new Hashtable ();
1888
1889                 if (priv_fields_events.Contains (einfo))
1890                         return false;
1891
1892                 priv_fields_events.Add (einfo, builder);
1893
1894                 return true;
1895         }
1896
1897         static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1898         {
1899                 if (priv_fields_events == null)
1900                         return null;
1901                 else
1902                         return (MemberInfo) priv_fields_events [ei];
1903         }
1904                 
1905         static Hashtable properties;
1906         
1907         static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1908         {
1909                 if (properties == null)
1910                         properties = new Hashtable ();
1911
1912                 if (properties.Contains (pb))
1913                         return false;
1914
1915                 properties.Add (pb, new Pair (get, set));
1916
1917                 return true;
1918         }
1919
1920         static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1921                                             MethodBase set, Type[] args)
1922         {
1923                 if (!RegisterProperty (pb, get,set))
1924                         return false;
1925
1926                 indexer_arguments.Add (pb, args);
1927
1928                 return true;
1929         }
1930
1931         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1932         {
1933                 Hashtable hash = new Hashtable ();
1934                 return CheckStructCycles (tc, seen, hash);
1935         }
1936
1937         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1938                                               Hashtable hash)
1939         {
1940                 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1941                         return true;
1942
1943                 //
1944                 // `seen' contains all types we've already visited.
1945                 //
1946                 if (seen.Contains (tc))
1947                         return true;
1948                 seen.Add (tc, null);
1949
1950                 if (tc.Fields == null)
1951                         return true;
1952
1953                 foreach (Field field in tc.Fields) {
1954                         if (field.FieldBuilder.IsStatic)
1955                                 continue;
1956
1957                         Type ftype = field.FieldBuilder.FieldType;
1958                         TypeContainer ftc = LookupTypeContainer (ftype);
1959                         if (ftc == null)
1960                                 continue;
1961
1962                         if (hash.Contains (ftc)) {
1963                                 Report.Error (523, tc.Location,
1964                                               "Struct member `{0}.{1}' of type `{2}' " +
1965                                               "causes a cycle in the struct layout",
1966                                               tc.Name, field.Name, ftc.Name);
1967                                 return false;
1968                         }
1969
1970                         //
1971                         // `hash' contains all types in the current path.
1972                         //
1973                         hash.Add (tc, null);
1974
1975                         bool ok = CheckStructCycles (ftc, seen, hash);
1976
1977                         hash.Remove (tc);
1978
1979                         if (!ok)
1980                                 return false;
1981
1982                         if (!seen.Contains (ftc))
1983                                 seen.Add (ftc, null);
1984                 }
1985
1986                 return true;
1987         }
1988
1989         /// <summary>
1990         ///   Given an array of interface types, expand and eliminate repeated ocurrences
1991         ///   of an interface.  
1992         /// </summary>
1993         ///
1994         /// <remarks>
1995         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1996         ///   be IA, IB, IC.
1997         /// </remarks>
1998         public static TypeExpr[] ExpandInterfaces (TypeExpr [] base_interfaces)
1999         {
2000                 ArrayList new_ifaces = new ArrayList ();
2001                 
2002                 foreach (TypeExpr iface in base_interfaces){
2003                         if (!new_ifaces.Contains (iface))
2004                                 new_ifaces.Add (iface);
2005                         
2006                         TypeExpr [] implementing = iface.GetInterfaces ();
2007                         
2008                         foreach (TypeExpr imp in implementing){
2009                                 if (!new_ifaces.Contains (imp))
2010                                         new_ifaces.Add (imp);
2011                         }
2012                 }
2013                 TypeExpr [] ret = new TypeExpr [new_ifaces.Count];
2014                 new_ifaces.CopyTo (ret, 0);
2015                 return ret;
2016         }
2017         
2018         static PtrHashtable iface_cache = new PtrHashtable ();
2019                 
2020         /// <summary>
2021         ///   This function returns the interfaces in the type `t'.  Works with
2022         ///   both types and TypeBuilders.
2023         /// </summary>
2024         public static TypeExpr [] GetInterfaces (Type t)
2025         {
2026                 
2027                 TypeExpr [] cached = iface_cache [t] as TypeExpr [];
2028                 if (cached != null)
2029                         return cached;
2030                 
2031                 //
2032                 // The reason for catching the Array case is that Reflection.Emit
2033                 // will not return a TypeBuilder for Array types of TypeBuilder types,
2034                 // but will still throw an exception if we try to call GetInterfaces
2035                 // on the type.
2036                 //
2037                 // Since the array interfaces are always constant, we return those for
2038                 // the System.Array
2039                 //
2040                 
2041                 if (t.IsArray)
2042                         t = TypeManager.array_type;
2043                 
2044                 if (t is TypeBuilder){
2045                         TypeExpr [] parent_ifaces;
2046                         
2047                         if (t.BaseType == null)
2048                                 parent_ifaces = NoTypeExprs;
2049                         else
2050                                 parent_ifaces = GetInterfaces (t.BaseType);
2051                         TypeExpr [] type_ifaces = (TypeExpr []) builder_to_ifaces [t];
2052                         if (type_ifaces == null)
2053                                 type_ifaces = NoTypeExprs;
2054
2055                         int parent_count = parent_ifaces.Length;
2056                         TypeExpr [] result = new TypeExpr [parent_count + type_ifaces.Length];
2057                         parent_ifaces.CopyTo (result, 0);
2058                         type_ifaces.CopyTo (result, parent_count);
2059
2060                         iface_cache [t] = result;
2061                         return result;
2062                 } else {
2063                         Type [] ifaces = t.GetInterfaces ();
2064                         if (ifaces.Length == 0)
2065                                 return NoTypeExprs;
2066
2067                         TypeExpr [] result = new TypeExpr [ifaces.Length];
2068                         for (int i = 0; i < ifaces.Length; i++)
2069                                 result [i] = new TypeExpression (ifaces [i], Location.Null);
2070                         
2071                         iface_cache [t] = result;
2072                         return result;
2073                 }
2074         }
2075         
2076         //
2077         // gets the interfaces that are declared explicitly on t
2078         //
2079         public static TypeExpr [] GetExplicitInterfaces (TypeBuilder t)
2080         {
2081                 return (TypeExpr []) builder_to_ifaces [t];
2082         }
2083         
2084         /// <remarks>
2085         ///  The following is used to check if a given type implements an interface.
2086         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2087         /// </remarks>
2088         public static bool ImplementsInterface (Type t, Type iface)
2089         {
2090                 TypeExpr [] interfaces;
2091
2092                 //
2093                 // FIXME OPTIMIZATION:
2094                 // as soon as we hit a non-TypeBuiler in the interface
2095                 // chain, we could return, as the `Type.GetInterfaces'
2096                 // will return all the interfaces implement by the type
2097                 // or its parents.
2098                 //
2099                 do {
2100                         interfaces = GetInterfaces (t);
2101
2102                         if (interfaces != null){
2103                                 foreach (TypeExpr i in interfaces){
2104                                         if (i.Type == iface)
2105                                                 return true;
2106                                 }
2107                         }
2108                         
2109                         t = t.BaseType;
2110                 } while (t != null);
2111                 
2112                 return false;
2113         }
2114
2115         static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2116
2117         // This is a custom version of Convert.ChangeType() which works
2118         // with the TypeBuilder defined types when compiling corlib.
2119         public static object ChangeType (object value, Type conversionType, out bool error)
2120         {
2121                 IConvertible convert_value = value as IConvertible;
2122                 
2123                 if (convert_value == null){
2124                         error = true;
2125                         return null;
2126                 }
2127                 
2128                 //
2129                 // We must use Type.Equals() here since `conversionType' is
2130                 // the TypeBuilder created version of a system type and not
2131                 // the system type itself.  You cannot use Type.GetTypeCode()
2132                 // on such a type - it'd always return TypeCode.Object.
2133                 //
2134                 error = false;
2135                 try {
2136                         if (conversionType.Equals (typeof (Boolean)))
2137                                 return (object)(convert_value.ToBoolean (nf_provider));
2138                         else if (conversionType.Equals (typeof (Byte)))
2139                                 return (object)(convert_value.ToByte (nf_provider));
2140                         else if (conversionType.Equals (typeof (Char)))
2141                                 return (object)(convert_value.ToChar (nf_provider));
2142                         else if (conversionType.Equals (typeof (DateTime)))
2143                                 return (object)(convert_value.ToDateTime (nf_provider));
2144                         else if (conversionType.Equals (typeof (Decimal)))
2145                                 return (object)(convert_value.ToDecimal (nf_provider));
2146                         else if (conversionType.Equals (typeof (Double)))
2147                                 return (object)(convert_value.ToDouble (nf_provider));
2148                         else if (conversionType.Equals (typeof (Int16)))
2149                                 return (object)(convert_value.ToInt16 (nf_provider));
2150                         else if (conversionType.Equals (typeof (Int32)))
2151                                 return (object)(convert_value.ToInt32 (nf_provider));
2152                         else if (conversionType.Equals (typeof (Int64)))
2153                                 return (object)(convert_value.ToInt64 (nf_provider));
2154                         else if (conversionType.Equals (typeof (SByte)))
2155                                 return (object)(convert_value.ToSByte (nf_provider));
2156                         else if (conversionType.Equals (typeof (Single)))
2157                                 return (object)(convert_value.ToSingle (nf_provider));
2158                         else if (conversionType.Equals (typeof (String)))
2159                                 return (object)(convert_value.ToString (nf_provider));
2160                         else if (conversionType.Equals (typeof (UInt16)))
2161                                 return (object)(convert_value.ToUInt16 (nf_provider));
2162                         else if (conversionType.Equals (typeof (UInt32)))
2163                                 return (object)(convert_value.ToUInt32 (nf_provider));
2164                         else if (conversionType.Equals (typeof (UInt64)))
2165                                 return (object)(convert_value.ToUInt64 (nf_provider));
2166                         else if (conversionType.Equals (typeof (Object)))
2167                                 return (object)(value);
2168                         else 
2169                                 error = true;
2170                 } catch {
2171                         error = true;
2172                 }
2173                 return null;
2174         }
2175
2176         //
2177         // This is needed, because enumerations from assemblies
2178         // do not report their underlyingtype, but they report
2179         // themselves
2180         //
2181         public static Type EnumToUnderlying (Type t)
2182         {
2183                 if (t == TypeManager.enum_type)
2184                         return t;
2185
2186                 t = t.UnderlyingSystemType;
2187                 if (!TypeManager.IsEnumType (t))
2188                         return t;
2189         
2190                 if (t is TypeBuilder) {
2191                         // slow path needed to compile corlib
2192                         if (t == TypeManager.bool_type ||
2193                             t == TypeManager.byte_type ||
2194                             t == TypeManager.sbyte_type ||
2195                             t == TypeManager.char_type ||
2196                             t == TypeManager.short_type ||
2197                             t == TypeManager.ushort_type ||
2198                             t == TypeManager.int32_type ||
2199                             t == TypeManager.uint32_type ||
2200                             t == TypeManager.int64_type ||
2201                             t == TypeManager.uint64_type)
2202                                 return t;
2203                         throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2204                 }
2205                 TypeCode tc = Type.GetTypeCode (t);
2206
2207                 switch (tc){
2208                 case TypeCode.Boolean:
2209                         return TypeManager.bool_type;
2210                 case TypeCode.Byte:
2211                         return TypeManager.byte_type;
2212                 case TypeCode.SByte:
2213                         return TypeManager.sbyte_type;
2214                 case TypeCode.Char:
2215                         return TypeManager.char_type;
2216                 case TypeCode.Int16:
2217                         return TypeManager.short_type;
2218                 case TypeCode.UInt16:
2219                         return TypeManager.ushort_type;
2220                 case TypeCode.Int32:
2221                         return TypeManager.int32_type;
2222                 case TypeCode.UInt32:
2223                         return TypeManager.uint32_type;
2224                 case TypeCode.Int64:
2225                         return TypeManager.int64_type;
2226                 case TypeCode.UInt64:
2227                         return TypeManager.uint64_type;
2228                 }
2229                 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2230         }
2231
2232         //
2233         // When compiling corlib and called with one of the core types, return
2234         // the corresponding typebuilder for that type.
2235         //
2236         public static Type TypeToCoreType (Type t)
2237         {
2238                 if (RootContext.StdLib || (t is TypeBuilder))
2239                         return t;
2240
2241                 TypeCode tc = Type.GetTypeCode (t);
2242
2243                 switch (tc){
2244                 case TypeCode.Boolean:
2245                         return TypeManager.bool_type;
2246                 case TypeCode.Byte:
2247                         return TypeManager.byte_type;
2248                 case TypeCode.SByte:
2249                         return TypeManager.sbyte_type;
2250                 case TypeCode.Char:
2251                         return TypeManager.char_type;
2252                 case TypeCode.Int16:
2253                         return TypeManager.short_type;
2254                 case TypeCode.UInt16:
2255                         return TypeManager.ushort_type;
2256                 case TypeCode.Int32:
2257                         return TypeManager.int32_type;
2258                 case TypeCode.UInt32:
2259                         return TypeManager.uint32_type;
2260                 case TypeCode.Int64:
2261                         return TypeManager.int64_type;
2262                 case TypeCode.UInt64:
2263                         return TypeManager.uint64_type;
2264                 case TypeCode.Single:
2265                         return TypeManager.float_type;
2266                 case TypeCode.Double:
2267                         return TypeManager.double_type;
2268                 case TypeCode.String:
2269                         return TypeManager.string_type;
2270                 default:
2271                         if (t == typeof (void))
2272                                 return TypeManager.void_type;
2273                         if (t == typeof (object))
2274                                 return TypeManager.object_type;
2275                         if (t == typeof (System.Type))
2276                                 return TypeManager.type_type;
2277                         if (t == typeof (System.IntPtr))
2278                                 return TypeManager.intptr_type;
2279                         return t;
2280                 }
2281         }
2282
2283         /// <summary>
2284         ///   Utility function that can be used to probe whether a type
2285         ///   is managed or not.  
2286         /// </summary>
2287         public static bool VerifyUnManaged (Type t, Location loc)
2288         {
2289                 if (t.IsValueType || t.IsPointer){
2290                         //
2291                         // FIXME: this is more complex, we actually need to
2292                         // make sure that the type does not contain any
2293                         // classes itself
2294                         //
2295                         return true;
2296                 }
2297
2298                 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
2299                         // We need this explicit check here to make it work when
2300                         // compiling corlib.
2301                         return true;
2302
2303                 Report.Error (
2304                         208, loc,
2305                         "Cannot take the address or size of a variable of a managed type ('" +
2306                         CSharpName (t) + "')");
2307                 return false;   
2308         }
2309         
2310         /// <summary>
2311         ///   Returns the name of the indexer in a given type.
2312         /// </summary>
2313         /// <remarks>
2314         ///   The default is not always `Item'.  The user can change this behaviour by
2315         ///   using the IndexerNameAttribute in the container.
2316         ///   For example, the String class indexer is named `Chars' not `Item' 
2317         /// </remarks>
2318         public static string IndexerPropertyName (Type t)
2319         {
2320                 if (t is TypeBuilder) {
2321                         TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2322                         return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2323                 }
2324                 
2325                 System.Attribute attr = System.Attribute.GetCustomAttribute (
2326                         t, TypeManager.default_member_type);
2327                 if (attr != null){
2328                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2329                         return dma.MemberName;
2330                 }
2331
2332                 return TypeContainer.DefaultIndexerName;
2333         }
2334
2335         static MethodInfo declare_local_method = null;
2336         
2337         public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2338         {
2339                 if (declare_local_method == null){
2340                         declare_local_method = typeof (ILGenerator).GetMethod (
2341                                 "DeclareLocal",
2342                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2343                                 null, 
2344                                 new Type [] { typeof (Type), typeof (bool)},
2345                                 null);
2346                         if (declare_local_method == null){
2347                                 Report.Warning (-24, new Location (-1),
2348                                                 "This version of the runtime does not support making pinned local variables.  " +
2349                                                 "This code may cause errors on a runtime with a moving GC");
2350                                 return ig.DeclareLocal (t);
2351                         }
2352                 }
2353                 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2354         }
2355         
2356         //
2357         // Returns whether the array of memberinfos contains the given method
2358         //
2359         public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2360         {
2361                 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2362                 
2363                 foreach (MethodBase method in array) {
2364                         if (method.Name != new_method.Name)
2365                                 continue;
2366
2367                         if (method is MethodInfo && new_method is MethodInfo)
2368                                 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2369                                         continue;
2370
2371                         
2372                         Type [] old_args = TypeManager.GetArgumentTypes (method);
2373                         int old_count = old_args.Length;
2374                         int i;
2375                         
2376                         if (new_args.Length != old_count)
2377                                 continue;
2378                         
2379                         for (i = 0; i < old_count; i++){
2380                                 if (old_args [i] != new_args [i])
2381                                         break;
2382                         }
2383                         if (i != old_count)
2384                                 continue;
2385
2386                         return true;
2387                 }
2388                 
2389                 return false;
2390         }
2391         
2392         //
2393         // We copy methods from `new_members' into `target_list' if the signature
2394         // for the method from in the new list does not exist in the target_list
2395         //
2396         // The name is assumed to be the same.
2397         //
2398         public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2399         {
2400                 if (target_list == null){
2401                         target_list = new ArrayList ();
2402
2403                         foreach (MemberInfo mi in new_members){
2404                                 if (mi is MethodBase)
2405                                         target_list.Add (mi);
2406                         }
2407                         return target_list;
2408                 }
2409                 
2410                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2411                 target_list.CopyTo (target_array, 0);
2412                 
2413                 foreach (MemberInfo mi in new_members){
2414                         MethodBase new_method = (MethodBase) mi;
2415                         
2416                         if (!ArrayContainsMethod (target_array, new_method))
2417                                 target_list.Add (new_method);
2418                 }
2419                 return target_list;
2420         }
2421
2422
2423 #region MemberLookup implementation
2424         
2425         //
2426         // Whether we allow private members in the result (since FindMembers
2427         // uses NonPublic for both protected and private), we need to distinguish.
2428         //
2429
2430         static internal bool FilterNone (MemberInfo m, object filter_criteria)
2431         {
2432                 return true;
2433         }
2434
2435         internal class Closure {
2436                 internal bool     private_ok;
2437
2438                 // Who is invoking us and which type is being queried currently.
2439                 internal Type     invocation_type;
2440                 internal Type     qualifier_type;
2441
2442                 // The assembly that defines the type is that is calling us
2443                 internal Assembly invocation_assembly;
2444                 internal IList almost_match;
2445
2446                 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2447                 {
2448                         if (invocation_type == null)
2449                                 return false;
2450
2451                         Debug.Assert (IsSubclassOrNestedChildOf (invocation_type, m.DeclaringType));
2452
2453                         if (is_static)
2454                                 return true;
2455                         
2456                         // A nested class has access to all the protected members visible to its parent.
2457                         if (qualifier_type != null
2458                             && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2459                                 return true;
2460
2461                         if (invocation_type == m.DeclaringType
2462                             || invocation_type.IsSubclassOf (m.DeclaringType)) {
2463                                 // Although a derived class can access protected members of its base class
2464                                 // it cannot do so through an instance of the base class (CS1540).
2465                                 // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
2466                                 if (qualifier_type == null
2467                                     || qualifier_type == invocation_type
2468                                     || qualifier_type.IsSubclassOf (invocation_type))
2469                                         return true;
2470                         }
2471
2472                         if (almost_match != null)
2473                                 almost_match.Add (m);
2474                         return false;
2475                 }
2476                 
2477                 //
2478                 // This filter filters by name + whether it is ok to include private
2479                 // members in the search
2480                 //
2481                 internal bool Filter (MemberInfo m, object filter_criteria)
2482                 {
2483                         //
2484                         // Hack: we know that the filter criteria will always be in the `closure'
2485                         // fields. 
2486                         //
2487
2488                         if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2489                                 return false;
2490                         
2491                         if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2492                             (m.DeclaringType == invocation_type))
2493                                 return true;
2494                         
2495                         //
2496                         // Ugly: we need to find out the type of `m', and depending
2497                         // on this, tell whether we accept or not
2498                         //
2499                         if (m is MethodBase){
2500                                 MethodBase mb = (MethodBase) m;
2501                                 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2502
2503                                 if (ma == MethodAttributes.Private)
2504                                         return private_ok || (invocation_type == m.DeclaringType) ||
2505                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2506                                 
2507                                 // Assembly succeeds if we're in the same assembly.
2508                                 if (ma == MethodAttributes.Assembly)
2509                                         return (invocation_assembly == mb.DeclaringType.Assembly);
2510                                 
2511                                 // FamAndAssem requires that we not only derive, but we are on the same assembly.  
2512                                 if (ma == MethodAttributes.FamANDAssem){
2513                                         if (invocation_assembly != mb.DeclaringType.Assembly)
2514                                                 return false;
2515                                 }
2516                                 
2517                                 // Family and FamANDAssem require that we derive.
2518                                 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem))
2519                                         return CheckValidFamilyAccess (mb.IsStatic, m);
2520                                 
2521                                 // Public.
2522                                 return true;
2523                         }
2524                         
2525                         if (m is FieldInfo){
2526                                 FieldInfo fi = (FieldInfo) m;
2527                                 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2528                                 
2529                                 if (fa == FieldAttributes.Private)
2530                                         return private_ok || (invocation_type == m.DeclaringType) ||
2531                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2532                                 
2533                                 // Assembly succeeds if we're in the same assembly.
2534                                 if (fa == FieldAttributes.Assembly)
2535                                         return (invocation_assembly == fi.DeclaringType.Assembly);
2536                                                 
2537                                 // FamAndAssem requires that we not only derive, but we are on the same assembly.  
2538                                 if (fa == FieldAttributes.FamANDAssem){
2539                                         if (invocation_assembly != fi.DeclaringType.Assembly)
2540                                                 return false;
2541                                 }
2542                                 
2543                                 // Family and FamANDAssem require that we derive.
2544                                 if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem))
2545                                         return CheckValidFamilyAccess (fi.IsStatic, m);
2546                                 
2547                                 // Public.
2548                                 return true;
2549                         }
2550                         
2551                         //
2552                         // EventInfos and PropertyInfos, return true because they lack permission
2553                         // information, so we need to check later on the methods.
2554                         //
2555                         return true;
2556                 }
2557         }
2558
2559         static Closure closure = new Closure ();
2560         static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2561
2562         //
2563         // Looks up a member called `name' in the `queried_type'.  This lookup
2564         // is done by code that is contained in the definition for `invocation_type'
2565         // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2566         //
2567         // `invocation_type' is used to check whether we're allowed to access the requested
2568         // member wrt its protection level.
2569         //
2570         // When called from MemberAccess, `qualifier_type' is the type which is used to access
2571         // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2572         // is B and qualifier_type is A).  This is used to do the CS1540 check.
2573         //
2574         // When resolving a SimpleName, `qualifier_type' is null.
2575         //
2576         // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2577         // the same than `queried_type' - except when we're being called from BaseAccess;
2578         // in this case, `invocation_type' is the current type and `queried_type' the base
2579         // type, so this'd normally trigger a CS1540.
2580         //
2581         // The binding flags are `bf' and the kind of members being looked up are `mt'
2582         //
2583         // The return value always includes private members which code in `invocation_type'
2584         // is allowed to access (using the specified `qualifier_type' if given); only use
2585         // BindingFlags.NonPublic to bypass the permission check.
2586         //
2587         // The 'almost_match' argument is used for reporting error CS1540.
2588         //
2589         // Returns an array of a single element for everything but Methods/Constructors
2590         // that might return multiple matches.
2591         //
2592         public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2593                                                   Type queried_type,  MemberTypes mt,
2594                                                   BindingFlags original_bf, string name, IList almost_match)
2595         {
2596                 Timer.StartTimer (TimerType.MemberLookup);
2597
2598                 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2599                                                         queried_type, mt, original_bf, name, almost_match);
2600
2601                 Timer.StopTimer (TimerType.MemberLookup);
2602
2603                 return retval;
2604         }
2605
2606         static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2607                                                Type queried_type, MemberTypes mt,
2608                                                BindingFlags original_bf, string name, IList almost_match)
2609         {
2610                 BindingFlags bf = original_bf;
2611                 
2612                 ArrayList method_list = null;
2613                 Type current_type = queried_type;
2614                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2615                 bool skip_iface_check = true, used_cache = false;
2616                 bool always_ok_flag = false;
2617
2618                 closure.invocation_type = invocation_type;
2619                 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2620                 closure.qualifier_type = qualifier_type;
2621                 closure.almost_match = almost_match;
2622
2623                 //
2624                 // If we are a nested class, we always have access to our container
2625                 // type names
2626                 //
2627                 if (invocation_type != null){
2628                         string invocation_name = invocation_type.FullName;
2629                         if (invocation_name.IndexOf ('+') != -1){
2630                                 string container = queried_type.FullName + "+";
2631                                 int container_length = container.Length;
2632
2633                                 if (invocation_name.Length > container_length){
2634                                         string shared = invocation_name.Substring (0, container_length);
2635                                 
2636                                         if (shared == container)
2637                                                 always_ok_flag = true;
2638                                 }
2639                         }
2640                 }
2641                 
2642                 // This is from the first time we find a method
2643                 // in most cases, we do not actually find a method in the base class
2644                 // so we can just ignore it, and save the arraylist allocation
2645                 MemberInfo [] first_members_list = null;
2646                 bool use_first_members_list = false;
2647                 
2648                 do {
2649                         MemberInfo [] list;
2650
2651                         //
2652                         // `NonPublic' is lame, because it includes both protected and
2653                         // private methods, so we need to control this behavior by
2654                         // explicitly tracking if a private method is ok or not.
2655                         //
2656                         // The possible cases are:
2657                         //    public, private and protected (internal does not come into the
2658                         //    equation)
2659                         //
2660                         if ((invocation_type != null) &&
2661                             ((invocation_type == current_type) ||
2662                              IsNestedChildOf (invocation_type, current_type)) ||
2663                             always_ok_flag)
2664                                 bf = original_bf | BindingFlags.NonPublic;
2665                         else
2666                                 bf = original_bf;
2667
2668                         closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2669
2670                         Timer.StopTimer (TimerType.MemberLookup);
2671
2672                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2673
2674                         Timer.StartTimer (TimerType.MemberLookup);
2675
2676                         //
2677                         // When queried for an interface type, the cache will automatically check all
2678                         // inherited members, so we don't need to do this here.  However, this only
2679                         // works if we already used the cache in the first iteration of this loop.
2680                         //
2681                         // If we used the cache in any further iteration, we can still terminate the
2682                         // loop since the cache always looks in all parent classes.
2683                         //
2684
2685                         if (used_cache)
2686                                 searching = false;
2687                         else
2688                                 skip_iface_check = false;
2689
2690                         if (current_type == TypeManager.object_type)
2691                                 searching = false;
2692                         else {
2693                                 current_type = current_type.BaseType;
2694                                 
2695                                 //
2696                                 // This happens with interfaces, they have a null
2697                                 // basetype.  Look members up in the Object class.
2698                                 //
2699                                 if (current_type == null) {
2700                                         current_type = TypeManager.object_type;
2701                                         searching = true;
2702                                 }
2703                         }
2704                         
2705                         if (list.Length == 0)
2706                                 continue;
2707
2708                         //
2709                         // Events and types are returned by both `static' and `instance'
2710                         // searches, which means that our above FindMembers will
2711                         // return two copies of the same.
2712                         //
2713                         if (list.Length == 1 && !(list [0] is MethodBase)){
2714                                 return list;
2715                         }
2716
2717                         //
2718                         // Multiple properties: we query those just to find out the indexer
2719                         // name
2720                         //
2721                         if (list [0] is PropertyInfo)
2722                                 return list;
2723
2724                         //
2725                         // We found an event: the cache lookup returns both the event and
2726                         // its private field.
2727                         //
2728                         if (list [0] is EventInfo) {
2729                                 if ((list.Length == 2) && (list [1] is FieldInfo))
2730                                         return new MemberInfo [] { list [0] };
2731
2732                                 // Oooops
2733                                 return null;
2734                         }
2735
2736                         //
2737                         // We found methods, turn the search into "method scan"
2738                         // mode.
2739                         //
2740
2741                         if (first_members_list != null) {
2742                                 if (use_first_members_list) {
2743                                         method_list = CopyNewMethods (method_list, first_members_list);
2744                                         use_first_members_list = false;
2745                                 }
2746                                 
2747                                 method_list = CopyNewMethods (method_list, list);
2748                         } else {
2749                                 first_members_list = list;
2750                                 use_first_members_list = true;
2751                                 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2752                         }
2753                 } while (searching);
2754                 
2755                 if (use_first_members_list) {
2756                         foreach (MemberInfo mi in first_members_list) {
2757                                 if (! (mi is MethodBase)) {
2758                                         method_list = CopyNewMethods (method_list, first_members_list);
2759                                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2760                                 }
2761                         }
2762                         return (MemberInfo []) first_members_list;
2763                 }
2764
2765                 if (method_list != null && method_list.Count > 0)
2766                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2767                 
2768                 //
2769                 // This happens if we already used the cache in the first iteration, in this case
2770                 // the cache already looked in all interfaces.
2771                 //
2772                 if (skip_iface_check)
2773                         return null;
2774
2775                 //
2776                 // Interfaces do not list members they inherit, so we have to
2777                 // scan those.
2778                 // 
2779                 if (!queried_type.IsInterface)
2780                         return null;
2781
2782                 if (queried_type.IsArray)
2783                         queried_type = TypeManager.array_type;
2784                 
2785                 TypeExpr [] ifaces = GetInterfaces (queried_type);
2786                 if (ifaces == null)
2787                         return null;
2788                 
2789                 foreach (TypeExpr itype in ifaces){
2790                         MemberInfo [] x;
2791
2792                         x = MemberLookup (null, null, itype.Type, mt, bf, name, null);
2793                         if (x != null)
2794                                 return x;
2795                 }
2796                                         
2797                 return null;
2798         }
2799
2800         // Tests whether external method is really special
2801         public static bool IsSpecialMethod (MethodBase mb)
2802         {
2803                 string name = mb.Name;
2804                 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2805                         return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2806
2807                 if (name.StartsWith ("add_"))
2808                         return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2809
2810                 if (name.StartsWith ("remove_"))
2811                         return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2812
2813                 if (name.StartsWith ("op_")){
2814                         foreach (string oname in Unary.oper_names) {
2815                                 if (oname == name)
2816                                         return true;
2817                         }
2818                 
2819                         foreach (string oname in Binary.oper_names) {
2820                                 if (oname == name)
2821                                         return true;
2822                         }
2823                 }
2824                 return false;
2825         }
2826                 
2827 #endregion
2828         
2829 }
2830
2831 /// <summary>
2832 ///   There is exactly one instance of this class per type.
2833 /// </summary>
2834 public sealed class TypeHandle : IMemberContainer {
2835         public readonly TypeHandle BaseType;
2836
2837         readonly int id = ++next_id;
2838         static int next_id = 0;
2839
2840         /// <summary>
2841         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
2842         ///   a TypeHandle yet, a new instance of it is created.  This static method
2843         ///   ensures that we'll only have one TypeHandle instance per type.
2844         /// </summary>
2845         public static TypeHandle GetTypeHandle (Type t)
2846         {
2847                 TypeHandle handle = (TypeHandle) type_hash [t];
2848                 if (handle != null)
2849                         return handle;
2850
2851                 handle = new TypeHandle (t);
2852                 type_hash.Add (t, handle);
2853                 return handle;
2854         }
2855         
2856         public static void CleanUp ()
2857         {
2858                 type_hash = null;
2859         }
2860
2861         /// <summary>
2862         ///   Returns the TypeHandle for TypeManager.object_type.
2863         /// </summary>
2864         public static IMemberContainer ObjectType {
2865                 get {
2866                         if (object_type != null)
2867                                 return object_type;
2868
2869                         object_type = GetTypeHandle (TypeManager.object_type);
2870
2871                         return object_type;
2872                 }
2873         }
2874
2875         /// <summary>
2876         ///   Returns the TypeHandle for TypeManager.array_type.
2877         /// </summary>
2878         public static IMemberContainer ArrayType {
2879                 get {
2880                         if (array_type != null)
2881                                 return array_type;
2882
2883                         array_type = GetTypeHandle (TypeManager.array_type);
2884
2885                         return array_type;
2886                 }
2887         }
2888
2889         private static PtrHashtable type_hash = new PtrHashtable ();
2890
2891         private static TypeHandle object_type = null;
2892         private static TypeHandle array_type = null;
2893
2894         private Type type;
2895         private bool is_interface;
2896         private MemberCache member_cache;
2897
2898         private TypeHandle (Type type)
2899         {
2900                 this.type = type;
2901                 if (type.BaseType != null)
2902                         BaseType = GetTypeHandle (type.BaseType);
2903                 this.is_interface = type.IsInterface;
2904                 this.member_cache = new MemberCache (this, true);
2905         }
2906
2907         // IMemberContainer methods
2908
2909         public string Name {
2910                 get {
2911                         return type.FullName;
2912                 }
2913         }
2914
2915         public Type Type {
2916                 get {
2917                         return type;
2918                 }
2919         }
2920
2921         public IMemberContainer ParentContainer {
2922                 get {
2923                         return BaseType;
2924                 }
2925         }
2926
2927         public bool IsInterface {
2928                 get {
2929                         return is_interface;
2930                 }
2931         }
2932
2933         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2934         {
2935                 MemberInfo [] members;
2936                 if (mt == MemberTypes.Event)
2937                         members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2938                 else
2939                         members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2940                                                     null, null);
2941                 Array.Reverse (members);
2942
2943                 return new MemberList (members);
2944         }
2945
2946         // IMemberFinder methods
2947
2948         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2949                                        MemberFilter filter, object criteria)
2950         {
2951                 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2952         }
2953
2954         public MemberCache MemberCache {
2955                 get {
2956                         return member_cache;
2957                 }
2958         }
2959
2960         public override string ToString ()
2961         {
2962                 if (BaseType != null)
2963                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2964                 else
2965                         return "TypeHandle (" + id + "," + Name + ")";
2966         }
2967 }
2968
2969 }