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