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