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