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