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