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