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