* statement.cs (ToplevelBlock.ResolveMeta): Move CS0136 checks ...
[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 (args [i].Name);
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         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         public static MethodInfo enumerable_select;
1360
1361         static void InitSystemCore ()
1362         {
1363                 if (RootContext.Version != LanguageVersion.LINQ)
1364                         return;
1365
1366                 if (extension_attribute_type != null)
1367                         extension_attribute_attr = new CustomAttributeBuilder (
1368                                 GetConstructor (extension_attribute_type, Type.EmptyTypes), new object[0]);
1369
1370                 Type t = CoreLookupType ("System.Linq", "Enumerable");
1371                 MemberList select = TypeManager.FindMembers (t, MemberTypes.Method, BindingFlags.Static | BindingFlags.Public,
1372                         Type.FilterName, "Select");
1373
1374                 // TODO: implement correct selection
1375                 enumerable_select = ((MethodInfo)select[0]);
1376         }
1377 #endif
1378
1379         const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1380
1381         /// <remarks>
1382         ///   This is the "old", non-cache based FindMembers() function.  We cannot use
1383         ///   the cache here because there is no member name argument.
1384         /// </remarks>
1385         public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1386                                               MemberFilter filter, object criteria)
1387         {
1388 #if MS_COMPATIBLE && GMCS_SOURCE
1389                 if (t.IsGenericType)
1390                         t = t.GetGenericTypeDefinition ();
1391 #endif
1392
1393                 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1394
1395                 //
1396                 // `builder_to_declspace' contains all dynamic types.
1397                 //
1398                 if (decl != null) {
1399                         MemberList list;
1400                         Timer.StartTimer (TimerType.FindMembers);
1401                         list = decl.FindMembers (mt, bf, filter, criteria);
1402                         Timer.StopTimer (TimerType.FindMembers);
1403                         return list;
1404                 }
1405
1406                 //
1407                 // We have to take care of arrays specially, because GetType on
1408                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1409                 // and we can not call FindMembers on this type.
1410                 //
1411                 if (
1412 #if MS_COMPATIBLE && GMCS_SOURCE
1413                         !t.IsGenericType &&
1414 #endif
1415                         t.IsSubclassOf (TypeManager.array_type))
1416                         return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1417
1418 #if GMCS_SOURCE
1419                 if (t is GenericTypeParameterBuilder) {
1420                         TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1421
1422                         Timer.StartTimer (TimerType.FindMembers);
1423                         MemberList list = tparam.FindMembers (
1424                                 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1425                         Timer.StopTimer (TimerType.FindMembers);
1426                         return list;
1427                 }
1428 #endif
1429
1430                 //
1431                 // Since FindMembers will not lookup both static and instance
1432                 // members, we emulate this behaviour here.
1433                 //
1434                 if ((bf & instance_and_static) == instance_and_static){
1435                         MemberInfo [] i_members = t.FindMembers (
1436                                 mt, bf & ~BindingFlags.Static, filter, criteria);
1437
1438                         int i_len = i_members.Length;
1439                         if (i_len == 1){
1440                                 MemberInfo one = i_members [0];
1441
1442                                 //
1443                                 // If any of these are present, we are done!
1444                                 //
1445                                 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1446                                         return new MemberList (i_members);
1447                         }
1448                                 
1449                         MemberInfo [] s_members = t.FindMembers (
1450                                 mt, bf & ~BindingFlags.Instance, filter, criteria);
1451
1452                         int s_len = s_members.Length;
1453                         if (i_len > 0 || s_len > 0)
1454                                 return new MemberList (i_members, s_members);
1455                         else {
1456                                 if (i_len > 0)
1457                                         return new MemberList (i_members);
1458                                 else
1459                                         return new MemberList (s_members);
1460                         }
1461                 }
1462
1463                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1464         }
1465
1466
1467         /// <summary>
1468         ///   This method is only called from within MemberLookup.  It tries to use the member
1469         ///   cache if possible and falls back to the normal FindMembers if not.  The `used_cache'
1470         ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
1471         ///   our return value will already contain all inherited members and the caller don't need
1472         ///   to check base classes and interfaces anymore.
1473         /// </summary>
1474         private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1475                                                                string name, out bool used_cache)
1476         {
1477                 MemberCache cache;
1478
1479 #if GMCS_SOURCE && MS_COMPATIBLE
1480                 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1481                         t = t.GetGenericTypeDefinition();
1482 #endif
1483
1484                 //
1485                 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1486                 // and we can ask the DeclSpace for the MemberCache.
1487                 //
1488                 if (t is TypeBuilder) {
1489                         DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1490                         cache = decl.MemberCache;
1491
1492                         //
1493                         // If this DeclSpace has a MemberCache, use it.
1494                         //
1495
1496                         if (cache != null) {
1497                                 used_cache = true;
1498                                 return cache.FindMembers (
1499                                         mt, bf, name, FilterWithClosure_delegate, null);
1500                         }
1501
1502                         // If there is no MemberCache, we need to use the "normal" FindMembers.
1503                         // Note, this is a VERY uncommon route!
1504
1505                         MemberList list;
1506                         Timer.StartTimer (TimerType.FindMembers);
1507                         list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1508                                                  FilterWithClosure_delegate, name);
1509                         Timer.StopTimer (TimerType.FindMembers);
1510                         used_cache = false;
1511                         return (MemberInfo []) list;
1512                 }
1513
1514                 //
1515                 // We have to take care of arrays specially, because GetType on
1516                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1517                 // and we can not call FindMembers on this type.
1518                 //
1519                 if (t.IsArray) { //  == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1520                         used_cache = true;
1521                         return TypeHandle.ArrayType.MemberCache.FindMembers (
1522                                 mt, bf, name, FilterWithClosure_delegate, null);
1523                 }
1524
1525 #if GMCS_SOURCE
1526                 if (t is GenericTypeParameterBuilder) {
1527                         TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1528
1529                         used_cache = true;
1530                         if (tparam.MemberCache == null)
1531                                 return new MemberInfo [0];
1532
1533                         return tparam.MemberCache.FindMembers (
1534                                 mt, bf, name, FilterWithClosure_delegate, null);
1535                 }
1536 #endif
1537
1538                 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1539                         //
1540                         // This happens if we're resolving a class'es base class and interfaces
1541                         // in TypeContainer.DefineType().  At this time, the types aren't
1542                         // populated yet, so we can't use the cache.
1543                         //
1544                         MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1545                                                            FilterWithClosure_delegate, name);
1546                         used_cache = false;
1547                         return info;
1548                 }
1549
1550                 //
1551                 // This call will always succeed.  There is exactly one TypeHandle instance per
1552                 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1553                 // the corresponding MemberCache.
1554                 //
1555                 cache = TypeHandle.GetMemberCache (t);
1556
1557                 used_cache = true;
1558                 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1559         }
1560
1561         public static bool IsBuiltinType (Type t)
1562         {
1563                 t = TypeToCoreType (t);
1564                 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1565                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1566                     t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1567                     t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1568                         return true;
1569                 else
1570                         return false;
1571         }
1572
1573         public static bool IsBuiltinType (TypeContainer tc)
1574         {
1575                 return IsBuiltinType (tc.TypeBuilder);
1576         }
1577
1578         //
1579         // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1580         // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1581         // 
1582         public static bool IsPrimitiveType (Type t)
1583         {
1584                 return (t == int32_type || t == uint32_type ||
1585                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1586                     t == char_type || t == short_type || t == bool_type ||
1587                     t == sbyte_type || t == byte_type || t == ushort_type);
1588         }
1589
1590         public static bool IsDelegateType (Type t)
1591         {
1592                 t = DropGenericTypeArguments (t);
1593                 if (t.IsSubclassOf (TypeManager.delegate_type))
1594                         return true;
1595                 else
1596                         return false;
1597         }
1598         
1599         public static bool IsEnumType (Type t)
1600         {
1601                 t = DropGenericTypeArguments (t);
1602                 if (builder_to_declspace [t] is Enum)
1603                         return true;
1604
1605 #if MS_COMPATIBLE && GMCS_SOURCE
1606                 if (t.IsGenericParameter || t.IsGenericType)
1607                         return false;
1608 #endif
1609                 return t.IsEnum;
1610         }
1611
1612         public static bool IsBuiltinOrEnum (Type t)
1613         {
1614                 if (IsBuiltinType (t))
1615                         return true;
1616                 
1617                 if (IsEnumType (t))
1618                         return true;
1619
1620                 return false;
1621         }
1622
1623         public static bool IsNullType (Type t)
1624         {
1625                 return t == null_type;
1626         }
1627
1628         public static bool IsAttributeType (Type t)
1629         {
1630                 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1631         }
1632         
1633         static Stack unmanaged_enclosing_types = new Stack (4);
1634
1635         //
1636         // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
1637         //
1638         public static bool IsUnmanagedType (Type t)
1639         {
1640                 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1641                 if (unmanaged_enclosing_types.Contains (t))
1642                         return true;
1643
1644                 // builtins that are not unmanaged types
1645                 if (t == TypeManager.object_type || t == TypeManager.string_type)
1646                         return false;
1647
1648                 if (IsGenericType (t) || IsGenericParameter (t))
1649                         return false;
1650
1651                 if (IsBuiltinOrEnum (t))
1652                         return true;
1653
1654                 // Someone did the work of checking if the ElementType of t is unmanaged.  Let's not repeat it.
1655                 if (t.IsPointer)
1656                         return true;
1657
1658                 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1659                 if (t.IsArray)
1660                         return false;
1661
1662                 if (!IsValueType (t))
1663                         return false;
1664
1665 #if GMCS_SOURCE
1666                 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1667                         if (p.IsGenericTypeDefinition)
1668                                 return false;
1669                 }
1670 #endif
1671
1672                 unmanaged_enclosing_types.Push (t);
1673
1674                 bool retval = true;
1675
1676                 if (t is TypeBuilder) {
1677                         TypeContainer tc = LookupTypeContainer (t);
1678                         if (tc.Fields != null){
1679                                 foreach (FieldBase f in tc.Fields){
1680                                         // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1681                                         if ((f.ModFlags & Modifiers.STATIC) != 0)
1682                                                 continue;
1683                                         if (f.MemberType == null)
1684                                                 continue;
1685                                         if (!IsUnmanagedType (f.MemberType)){
1686                                                 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1687                                                 retval = false;
1688                                         }
1689                                 }
1690                         }
1691                 } else {
1692                         FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1693                         
1694                         foreach (FieldInfo f in fields){
1695                                 if (!IsUnmanagedType (f.FieldType)){
1696                                         Report.SymbolRelatedToPreviousError (f);
1697                                         retval = false;
1698                                 }
1699                         }
1700                 }
1701
1702                 unmanaged_enclosing_types.Pop ();
1703
1704                 return retval;
1705         }
1706                 
1707         public static bool IsValueType (Type t)
1708         {
1709                 return t.IsValueType || IsGenericParameter (t);
1710         }
1711         
1712         public static bool IsInterfaceType (Type t)
1713         {
1714                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1715                 if (tc == null)
1716                         return false;
1717
1718                 return tc.Kind == Kind.Interface;
1719         }
1720
1721         public static bool IsSubclassOf (Type type, Type base_type)
1722         {
1723                 TypeParameter tparam = LookupTypeParameter (type);
1724                 TypeParameter pparam = LookupTypeParameter (base_type);
1725
1726                 if ((tparam != null) && (pparam != null)) {
1727                         if (tparam == pparam)
1728                                 return true;
1729
1730                         return tparam.IsSubclassOf (base_type);
1731                 }
1732
1733 #if MS_COMPATIBLE && GMCS_SOURCE
1734                 if (type.IsGenericType)
1735                         type = type.GetGenericTypeDefinition ();
1736 #endif
1737
1738                 if (type.IsSubclassOf (base_type))
1739                         return true;
1740
1741                 do {
1742                         if (IsEqual (type, base_type))
1743                                 return true;
1744
1745                         type = type.BaseType;
1746                 } while (type != null);
1747
1748                 return false;
1749         }
1750
1751         public static bool IsPrivateAccessible (Type type, Type parent)
1752         {
1753                 if (type == null)
1754                         return false;
1755
1756                 if (type.Equals (parent))
1757                         return true;
1758
1759                 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1760         }
1761
1762         public static bool IsFamilyAccessible (Type type, Type parent)
1763         {
1764                 TypeParameter tparam = LookupTypeParameter (type);
1765                 TypeParameter pparam = LookupTypeParameter (parent);
1766
1767                 if ((tparam != null) && (pparam != null)) {
1768                         if (tparam == pparam)
1769                                 return true;
1770
1771                         return tparam.IsSubclassOf (parent);
1772                 }
1773
1774                 do {
1775                         if (IsInstantiationOfSameGenericType (type, parent))
1776                                 return true;
1777
1778                         type = type.BaseType;
1779                 } while (type != null);
1780
1781                 return false;
1782         }
1783
1784         //
1785         // Checks whether `type' is a subclass or nested child of `base_type'.
1786         //
1787         public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1788         {
1789                 do {
1790                         if (IsFamilyAccessible (type, base_type))
1791                                 return true;
1792
1793                         // Handle nested types.
1794                         type = type.DeclaringType;
1795                 } while (type != null);
1796
1797                 return false;
1798         }
1799
1800         //
1801         // Checks whether `type' is a nested child of `parent'.
1802         //
1803         public static bool IsNestedChildOf (Type type, Type parent)
1804         {
1805                 if (type == null)
1806                         return false;
1807
1808                 type = DropGenericTypeArguments (type);
1809                 parent = DropGenericTypeArguments (parent);
1810
1811                 if (IsEqual (type, parent))
1812                         return false;
1813
1814                 type = type.DeclaringType;
1815                 while (type != null) {
1816                         if (IsEqual (type, parent))
1817                                 return true;
1818
1819                         type = type.DeclaringType;
1820                 }
1821
1822                 return false;
1823         }
1824
1825 #if GMCS_SOURCE
1826         //
1827         // Checks whether `extern_type' is friend of the output assembly
1828         //
1829         public static bool IsFriendAssembly (Assembly assembly)
1830         {
1831                 // FIXME: This should not be reached
1832                 if (assembly == CodeGen.Assembly.Builder)
1833                         return false;
1834
1835                 if (assembly_internals_vis_attrs.Contains (assembly))
1836                         return (bool)(assembly_internals_vis_attrs [assembly]);
1837                 
1838                 object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
1839                 if (attrs.Length == 0) {
1840                         assembly_internals_vis_attrs.Add (assembly, false);
1841                         return false;
1842                 }
1843
1844                 AssemblyName this_name = CodeGen.Assembly.Name;
1845                 byte [] this_token = this_name.GetPublicKeyToken ();
1846                 bool is_friend = false;
1847                 foreach (InternalsVisibleToAttribute attr in attrs) {
1848                         if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1849                                 continue;
1850                         
1851                         AssemblyName aname = null;
1852                         try {
1853                                 aname = new AssemblyName (attr.AssemblyName);
1854                         } catch (FileLoadException) {
1855                         } catch (ArgumentException) {
1856                         }
1857
1858                         if (aname == null || aname.Name != this_name.Name)
1859                                 continue;
1860                         
1861                         byte [] key_token = aname.GetPublicKeyToken ();
1862                         if (key_token != null) {
1863                                 if (this_token == null) {
1864                                         // Same name, but key token is null
1865                                         Error_FriendAccessNameNotMatching (aname.FullName);
1866                                         break;
1867                                 }
1868                                 
1869                                 if (!CompareKeyTokens (this_token, key_token))
1870                                         continue;
1871                         }
1872
1873                         is_friend = true;
1874                         break;
1875                 }
1876
1877                 assembly_internals_vis_attrs.Add (assembly, is_friend);
1878                 return is_friend;
1879         }
1880
1881         static bool CompareKeyTokens (byte [] token1, byte [] token2)
1882         {
1883                 for (int i = 0; i < token1.Length; i++)
1884                         if (token1 [i] != token2 [i])
1885                                 return false;
1886
1887                 return true;
1888         }
1889
1890         static void Error_FriendAccessNameNotMatching (string other_name)
1891         {
1892                 Report.Error (281, "Friend access was granted to `" + other_name + 
1893                                 "', but the output assembly is named `" + CodeGen.Assembly.Name.FullName +
1894                                 "'. Try adding a reference to `" + other_name + 
1895                                 "' or change the output assembly name to match it");
1896         }
1897 #else
1898         public static bool IsFriendAssembly (Assembly assembly)
1899         {
1900                 return false;
1901         }
1902 #endif
1903         
1904         //
1905         // Do the right thing when returning the element type of an
1906         // array type based on whether we are compiling corlib or not
1907         //
1908         public static Type GetElementType (Type t)
1909         {
1910                 if (RootContext.StdLib)
1911                         return t.GetElementType ();
1912                 else
1913                         return TypeToCoreType (t.GetElementType ());
1914         }
1915
1916         /// <summary>
1917         /// This method is not implemented by MS runtime for dynamic types
1918         /// </summary>
1919         public static bool HasElementType (Type t)
1920         {
1921                 return t.IsArray || t.IsPointer || t.IsByRef;
1922         }
1923         
1924         /// <summary>
1925         ///   Gigantic work around for missing features in System.Reflection.Emit follows.
1926         /// </summary>
1927         ///
1928         /// <remarks>
1929         ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
1930         ///   for anything which is dynamic, and we need this in a number of places,
1931         ///   we register this information here, and use it afterwards.
1932         /// </remarks>
1933         static public void RegisterMethod (MethodBase mb, Parameters ip)
1934         {
1935                 method_params.Add (mb, ip);
1936         }
1937         
1938         static public ParameterData GetParameterData (MethodBase mb)
1939         {
1940                 ParameterData pd = (ParameterData)method_params [mb];
1941                 if (pd == null) {
1942                         if (mb is MethodBuilder || mb is ConstructorBuilder)
1943                                 throw new InternalErrorException ("Argument for Method not registered" + mb);
1944
1945 #if MS_COMPATIBLE
1946                         if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition)
1947                                 return GetParameterData (((MethodInfo)mb).GetGenericMethodDefinition ());
1948 #endif
1949                         pd = new ReflectionParameters (mb);
1950                         method_params.Add (mb, pd);
1951                 }
1952                 return pd;
1953         }
1954
1955         static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1956         {
1957                 if (!method_overrides.Contains (override_method))
1958                         method_overrides [override_method] = base_method;
1959                 if (method_overrides [override_method] != base_method)
1960                         throw new InternalErrorException ("Override mismatch: " + override_method);
1961         }
1962
1963         static public bool IsOverride (MethodBase m)
1964         {
1965                 m = DropGenericMethodArguments (m);
1966
1967                 return m.IsVirtual &&
1968                         (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1969                         (m is MethodBuilder || method_overrides.Contains (m));
1970         }
1971
1972         static public MethodBase TryGetBaseDefinition (MethodBase m)
1973         {
1974                 m = DropGenericMethodArguments (m);
1975
1976                 return (MethodBase) method_overrides [m];
1977         }
1978
1979         /// <summary>
1980         ///    Returns the argument types for an indexer based on its PropertyInfo
1981         ///
1982         ///    For dynamic indexers, we use the compiler provided types, for
1983         ///    indexers from existing assemblies we load them from GetParameters,
1984         ///    and insert them into the cache
1985         /// </summary>
1986         static public Type [] GetArgumentTypes (PropertyInfo indexer)
1987         {
1988                 if (indexer_arguments.Contains (indexer))
1989                         return (Type []) indexer_arguments [indexer];
1990                 else if (indexer is PropertyBuilder)
1991                         // If we're a PropertyBuilder and not in the
1992                         // `indexer_arguments' hash, then we're a property and
1993                         // not an indexer.
1994                         return Type.EmptyTypes;
1995                 else {
1996                         ParameterInfo [] pi = indexer.GetIndexParameters ();
1997                         // Property, not an indexer.
1998                         if (pi == null)
1999                                 return Type.EmptyTypes;
2000                         int c = pi.Length;
2001                         Type [] types = new Type [c];
2002                         
2003                         for (int i = 0; i < c; i++)
2004                                 types [i] = pi [i].ParameterType;
2005
2006                         indexer_arguments.Add (indexer, types);
2007                         return types;
2008                 }
2009         }
2010         
2011         public static void RegisterConstant (FieldInfo fb, IConstant ic)
2012         {
2013                 fields.Add (fb, ic);
2014         }
2015
2016         public static IConstant GetConstant (FieldInfo fb)
2017         {
2018                 if (fb == null)
2019                         return null;
2020
2021                 return (IConstant)fields [fb];
2022         }
2023
2024         public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
2025         {
2026                 propertybuilder_to_property.Add (pi, pb);
2027         }
2028
2029         public static PropertyBase GetProperty (PropertyInfo pi)
2030         {
2031                 return (PropertyBase)propertybuilder_to_property [pi];
2032         }
2033
2034         static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
2035         {
2036                 fieldbuilders_to_fields.Add (fb, f);
2037         }
2038
2039         //
2040         // The return value can be null;  This will be the case for
2041         // auxiliary FieldBuilders created by the compiler that have no
2042         // real field being declared on the source code
2043         //
2044         static public FieldBase GetField (FieldInfo fb)
2045         {
2046 #if GMCS_SOURCE
2047                 fb = GetGenericFieldDefinition (fb);
2048 #endif
2049                 return (FieldBase) fieldbuilders_to_fields [fb];
2050         }
2051
2052         static public MethodInfo GetAddMethod (EventInfo ei)
2053         {
2054                 if (ei is MyEventBuilder) {
2055                         return ((MyEventBuilder)ei).GetAddMethod (true);
2056                 }
2057                 return ei.GetAddMethod (true);
2058         }
2059
2060         static public MethodInfo GetRemoveMethod (EventInfo ei)
2061         {
2062                 if (ei is MyEventBuilder) {
2063                         return ((MyEventBuilder)ei).GetRemoveMethod (true);
2064                 }
2065                 return ei.GetRemoveMethod (true);
2066         }
2067
2068         static public void RegisterEventField (EventInfo einfo, EventField e)
2069         {
2070                 if (events == null)
2071                         events = new Hashtable ();
2072
2073                 events.Add (einfo, e);
2074         }
2075
2076         static public EventField GetEventField (EventInfo ei)
2077         {
2078                 if (events == null)
2079                         return null;
2080
2081                 return (EventField) events [ei];
2082         }
2083
2084         static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
2085                                             MethodBase set, Type[] args)
2086         {
2087                 indexer_arguments.Add (pb, args);
2088
2089                 return true;
2090         }
2091
2092         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
2093         {
2094                 Hashtable hash = new Hashtable ();
2095                 return CheckStructCycles (tc, seen, hash);
2096         }
2097
2098         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
2099                                               Hashtable hash)
2100         {
2101                 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
2102                         return true;
2103
2104                 //
2105                 // `seen' contains all types we've already visited.
2106                 //
2107                 if (seen.Contains (tc))
2108                         return true;
2109                 seen.Add (tc, null);
2110
2111                 if (tc.Fields == null)
2112                         return true;
2113
2114                 foreach (FieldBase field in tc.Fields) {
2115                         if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
2116                                 continue;
2117
2118                         Type ftype = field.FieldBuilder.FieldType;
2119                         TypeContainer ftc = LookupTypeContainer (ftype);
2120                         if (ftc == null)
2121                                 continue;
2122
2123                         if (hash.Contains (ftc)) {
2124                                 Report.Error (523, tc.Location,
2125                                               "Struct member `{0}.{1}' of type `{2}' " +
2126                                               "causes a cycle in the struct layout",
2127                                               tc.Name, field.Name, ftc.Name);
2128                                 return false;
2129                         }
2130
2131                         //
2132                         // `hash' contains all types in the current path.
2133                         //
2134                         hash.Add (tc, null);
2135
2136                         bool ok = CheckStructCycles (ftc, seen, hash);
2137
2138                         hash.Remove (tc);
2139
2140                         if (!ok)
2141                                 return false;
2142
2143                         if (!seen.Contains (ftc))
2144                                 seen.Add (ftc, null);
2145                 }
2146
2147                 return true;
2148         }
2149
2150         /// <summary>
2151         ///   Given an array of interface types, expand and eliminate repeated ocurrences
2152         ///   of an interface.  
2153         /// </summary>
2154         ///
2155         /// <remarks>
2156         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2157         ///   be IA, IB, IC.
2158         /// </remarks>
2159         public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
2160         {
2161                 ArrayList new_ifaces = new ArrayList ();
2162
2163                 foreach (TypeExpr iface in base_interfaces){
2164                         Type itype = iface.Type;
2165
2166                         if (new_ifaces.Contains (itype))
2167                                 continue;
2168
2169                         new_ifaces.Add (itype);
2170                         
2171                         Type [] implementing = GetInterfaces (itype);
2172
2173                         foreach (Type imp in implementing){
2174                                 if (!new_ifaces.Contains (imp))
2175                                         new_ifaces.Add (imp);
2176                         }
2177                 }
2178                 Type [] ret = new Type [new_ifaces.Count];
2179                 new_ifaces.CopyTo (ret, 0);
2180                 return ret;
2181         }
2182
2183         public static Type[] ExpandInterfaces (Type [] base_interfaces)
2184         {
2185                 ArrayList new_ifaces = new ArrayList ();
2186
2187                 foreach (Type itype in base_interfaces){
2188                         if (new_ifaces.Contains (itype))
2189                                 continue;
2190
2191                         new_ifaces.Add (itype);
2192                         
2193                         Type [] implementing = GetInterfaces (itype);
2194
2195                         foreach (Type imp in implementing){
2196                                 if (!new_ifaces.Contains (imp))
2197                                         new_ifaces.Add (imp);
2198                         }
2199                 }
2200                 Type [] ret = new Type [new_ifaces.Count];
2201                 new_ifaces.CopyTo (ret, 0);
2202                 return ret;
2203         }
2204                 
2205         static PtrHashtable iface_cache = new PtrHashtable ();
2206                 
2207         /// <summary>
2208         ///   This function returns the interfaces in the type `t'.  Works with
2209         ///   both types and TypeBuilders.
2210         /// </summary>
2211         public static Type [] GetInterfaces (Type t)
2212         {
2213                 Type [] cached = iface_cache [t] as Type [];
2214                 if (cached != null)
2215                         return cached;
2216                 
2217                 //
2218                 // The reason for catching the Array case is that Reflection.Emit
2219                 // will not return a TypeBuilder for Array types of TypeBuilder types,
2220                 // but will still throw an exception if we try to call GetInterfaces
2221                 // on the type.
2222                 //
2223                 // Since the array interfaces are always constant, we return those for
2224                 // the System.Array
2225                 //
2226                 
2227                 if (t.IsArray)
2228                         t = TypeManager.array_type;
2229                 
2230                 if ((t is TypeBuilder) || IsGenericType (t)) {
2231                         Type [] base_ifaces;
2232                         
2233                         if (t.BaseType == null)
2234                                 base_ifaces = Type.EmptyTypes;
2235                         else
2236                                 base_ifaces = GetInterfaces (t.BaseType);
2237                         Type[] type_ifaces;
2238                         if (IsGenericType (t))
2239 #if MS_COMPATIBLE && GMCS_SOURCE
2240                                 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
2241 #else
2242                                 type_ifaces = t.GetInterfaces ();
2243 #endif
2244                         else
2245                                 type_ifaces = (Type []) builder_to_ifaces [t];
2246                         if (type_ifaces == null || type_ifaces.Length == 0)
2247                                 type_ifaces = Type.EmptyTypes;
2248
2249                         int base_count = base_ifaces.Length;
2250                         Type [] result = new Type [base_count + type_ifaces.Length];
2251                         base_ifaces.CopyTo (result, 0);
2252                         type_ifaces.CopyTo (result, base_count);
2253
2254                         iface_cache [t] = result;
2255                         return result;
2256 #if GMCS_SOURCE
2257                 } else if (t is GenericTypeParameterBuilder){
2258                         Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2259                         if (type_ifaces == null || type_ifaces.Length == 0)
2260                                 type_ifaces = Type.EmptyTypes;
2261
2262                         iface_cache [t] = type_ifaces;
2263                         return type_ifaces;
2264 #endif
2265                 } else {
2266                         Type[] ifaces = t.GetInterfaces ();
2267                         iface_cache [t] = ifaces;
2268                         return ifaces;
2269                 }
2270         }
2271         
2272         //
2273         // gets the interfaces that are declared explicitly on t
2274         //
2275         public static Type [] GetExplicitInterfaces (TypeBuilder t)
2276         {
2277                 return (Type []) builder_to_ifaces [t];
2278         }
2279         
2280         /// <remarks>
2281         ///  The following is used to check if a given type implements an interface.
2282         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2283         /// </remarks>
2284         public static bool ImplementsInterface (Type t, Type iface)
2285         {
2286                 Type [] interfaces;
2287
2288                 //
2289                 // FIXME OPTIMIZATION:
2290                 // as soon as we hit a non-TypeBuiler in the interface
2291                 // chain, we could return, as the `Type.GetInterfaces'
2292                 // will return all the interfaces implement by the type
2293                 // or its bases.
2294                 //
2295                 do {
2296                         interfaces = GetInterfaces (t);
2297
2298                         if (interfaces != null){
2299                                 foreach (Type i in interfaces){
2300                                         if (i == iface)
2301                                                 return true;
2302                                 }
2303                         }
2304                         
2305                         t = t.BaseType;
2306                 } while (t != null);
2307                 
2308                 return false;
2309         }
2310
2311         static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2312
2313         // This is a custom version of Convert.ChangeType() which works
2314         // with the TypeBuilder defined types when compiling corlib.
2315         public static object ChangeType (object value, Type conversionType, out bool error)
2316         {
2317                 IConvertible convert_value = value as IConvertible;
2318                 
2319                 if (convert_value == null){
2320                         error = true;
2321                         return null;
2322                 }
2323                 
2324                 //
2325                 // We must use Type.Equals() here since `conversionType' is
2326                 // the TypeBuilder created version of a system type and not
2327                 // the system type itself.  You cannot use Type.GetTypeCode()
2328                 // on such a type - it'd always return TypeCode.Object.
2329                 //
2330                 error = false;
2331                 try {
2332                         if (conversionType.Equals (typeof (Boolean)))
2333                                 return (object)(convert_value.ToBoolean (nf_provider));
2334                         else if (conversionType.Equals (typeof (Byte)))
2335                                 return (object)(convert_value.ToByte (nf_provider));
2336                         else if (conversionType.Equals (typeof (Char)))
2337                                 return (object)(convert_value.ToChar (nf_provider));
2338                         else if (conversionType.Equals (typeof (DateTime)))
2339                                 return (object)(convert_value.ToDateTime (nf_provider));
2340                         else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2341                                 return (object)(convert_value.ToDecimal (nf_provider));
2342                         else if (conversionType.Equals (typeof (Double)))
2343                                 return (object)(convert_value.ToDouble (nf_provider));
2344                         else if (conversionType.Equals (typeof (Int16)))
2345                                 return (object)(convert_value.ToInt16 (nf_provider));
2346                         else if (conversionType.Equals (typeof (Int32)))
2347                                 return (object)(convert_value.ToInt32 (nf_provider));
2348                         else if (conversionType.Equals (typeof (Int64)))
2349                                 return (object)(convert_value.ToInt64 (nf_provider));
2350                         else if (conversionType.Equals (typeof (SByte)))
2351                                 return (object)(convert_value.ToSByte (nf_provider));
2352                         else if (conversionType.Equals (typeof (Single)))
2353                                 return (object)(convert_value.ToSingle (nf_provider));
2354                         else if (conversionType.Equals (typeof (String)))
2355                                 return (object)(convert_value.ToString (nf_provider));
2356                         else if (conversionType.Equals (typeof (UInt16)))
2357                                 return (object)(convert_value.ToUInt16 (nf_provider));
2358                         else if (conversionType.Equals (typeof (UInt32)))
2359                                 return (object)(convert_value.ToUInt32 (nf_provider));
2360                         else if (conversionType.Equals (typeof (UInt64)))
2361                                 return (object)(convert_value.ToUInt64 (nf_provider));
2362                         else if (conversionType.Equals (typeof (Object)))
2363                                 return (object)(value);
2364                         else 
2365                                 error = true;
2366                 } catch {
2367                         error = true;
2368                 }
2369                 return null;
2370         }
2371
2372         //
2373         // This is needed, because enumerations from assemblies
2374         // do not report their underlyingtype, but they report
2375         // themselves
2376         //
2377         public static Type EnumToUnderlying (Type t)
2378         {
2379                 t = DropGenericTypeArguments (t);
2380                 if (t == TypeManager.enum_type)
2381                         return t;
2382
2383                 t = t.UnderlyingSystemType;
2384                 if (!TypeManager.IsEnumType (t))
2385                         return t;
2386         
2387                 if (t is TypeBuilder) {
2388                         // slow path needed to compile corlib
2389                         if (t == TypeManager.bool_type ||
2390                             t == TypeManager.byte_type ||
2391                             t == TypeManager.sbyte_type ||
2392                             t == TypeManager.char_type ||
2393                             t == TypeManager.short_type ||
2394                             t == TypeManager.ushort_type ||
2395                             t == TypeManager.int32_type ||
2396                             t == TypeManager.uint32_type ||
2397                             t == TypeManager.int64_type ||
2398                             t == TypeManager.uint64_type)
2399                                 return t;
2400                 }
2401                 TypeCode tc = Type.GetTypeCode (t);
2402
2403                 switch (tc){
2404                 case TypeCode.Boolean:
2405                         return TypeManager.bool_type;
2406                 case TypeCode.Byte:
2407                         return TypeManager.byte_type;
2408                 case TypeCode.SByte:
2409                         return TypeManager.sbyte_type;
2410                 case TypeCode.Char:
2411                         return TypeManager.char_type;
2412                 case TypeCode.Int16:
2413                         return TypeManager.short_type;
2414                 case TypeCode.UInt16:
2415                         return TypeManager.ushort_type;
2416                 case TypeCode.Int32:
2417                         return TypeManager.int32_type;
2418                 case TypeCode.UInt32:
2419                         return TypeManager.uint32_type;
2420                 case TypeCode.Int64:
2421                         return TypeManager.int64_type;
2422                 case TypeCode.UInt64:
2423                         return TypeManager.uint64_type;
2424                 }
2425                 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2426         }
2427
2428         //
2429         // When compiling corlib and called with one of the core types, return
2430         // the corresponding typebuilder for that type.
2431         //
2432         public static Type TypeToCoreType (Type t)
2433         {
2434                 if (RootContext.StdLib || (t is TypeBuilder))
2435                         return t;
2436
2437                 TypeCode tc = Type.GetTypeCode (t);
2438
2439                 switch (tc){
2440                 case TypeCode.Boolean:
2441                         return TypeManager.bool_type;
2442                 case TypeCode.Byte:
2443                         return TypeManager.byte_type;
2444                 case TypeCode.SByte:
2445                         return TypeManager.sbyte_type;
2446                 case TypeCode.Char:
2447                         return TypeManager.char_type;
2448                 case TypeCode.Int16:
2449                         return TypeManager.short_type;
2450                 case TypeCode.UInt16:
2451                         return TypeManager.ushort_type;
2452                 case TypeCode.Int32:
2453                         return TypeManager.int32_type;
2454                 case TypeCode.UInt32:
2455                         return TypeManager.uint32_type;
2456                 case TypeCode.Int64:
2457                         return TypeManager.int64_type;
2458                 case TypeCode.UInt64:
2459                         return TypeManager.uint64_type;
2460                 case TypeCode.Single:
2461                         return TypeManager.float_type;
2462                 case TypeCode.Double:
2463                         return TypeManager.double_type;
2464                 case TypeCode.String:
2465                         return TypeManager.string_type;
2466                 case TypeCode.Decimal:
2467                         return TypeManager.decimal_type;
2468                 default:
2469                         if (t == typeof (void))
2470                                 return TypeManager.void_type;
2471                         if (t == typeof (object))
2472                                 return TypeManager.object_type;
2473                         if (t == typeof (System.Type))
2474                                 return TypeManager.type_type;
2475                         if (t == typeof (System.IntPtr))
2476                                 return TypeManager.intptr_type;
2477                         return t;
2478                 }
2479         }
2480
2481         /// <summary>
2482         ///   Utility function that can be used to probe whether a type
2483         ///   is managed or not.  
2484         /// </summary>
2485         public static bool VerifyUnManaged (Type t, Location loc)
2486         {
2487                 if (IsUnmanagedType (t))
2488                         return true;
2489
2490                 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2491                         CSharpName (t));
2492
2493                 return false;   
2494         }
2495         
2496         /// <summary>
2497         ///   Returns the name of the indexer in a given type.
2498         /// </summary>
2499         /// <remarks>
2500         ///   The default is not always `Item'.  The user can change this behaviour by
2501         ///   using the IndexerNameAttribute in the container.
2502         ///   For example, the String class indexer is named `Chars' not `Item' 
2503         /// </remarks>
2504         public static string IndexerPropertyName (Type t)
2505         {
2506                 t = DropGenericTypeArguments (t);
2507                 if (t is TypeBuilder) {
2508                         TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2509                         return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2510                 }
2511                 
2512                 System.Attribute attr = System.Attribute.GetCustomAttribute (
2513                         t, TypeManager.default_member_type);
2514                 if (attr != null){
2515                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2516                         return dma.MemberName;
2517                 }
2518
2519                 return TypeContainer.DefaultIndexerName;
2520         }
2521
2522         static MethodInfo declare_local_method = null;
2523         
2524         public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2525         {
2526                 if (declare_local_method == null){
2527                         declare_local_method = typeof (ILGenerator).GetMethod (
2528                                 "DeclareLocal",
2529                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2530                                 null, 
2531                                 new Type [] { typeof (Type), typeof (bool)},
2532                                 null);
2533                         if (declare_local_method == null){
2534                                 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2535                                 return ig.DeclareLocal (t);
2536                         }
2537                 }
2538                 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2539         }
2540
2541         private static bool IsSignatureEqual (Type a, Type b)
2542         {
2543                 ///
2544                 /// Consider the following example (bug #77674):
2545                 ///
2546                 ///     public abstract class A
2547                 ///     {
2548                 ///        public abstract T Foo<T> ();
2549                 ///     }
2550                 ///
2551                 ///     public abstract class B : A
2552                 ///     {
2553                 ///        public override U Foo<T> ()
2554                 ///        { return default (U); }
2555                 ///     }
2556                 ///
2557                 /// Here, `T' and `U' are method type parameters from different methods
2558                 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2559                 ///
2560                 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2561                 /// we need to do a signature based comparision and consider them equal.
2562
2563                 if (a == b)
2564                         return true;
2565
2566 #if GMCS_SOURCE
2567                 if (a.IsGenericParameter && b.IsGenericParameter &&
2568                     (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2569                         return a.GenericParameterPosition == b.GenericParameterPosition;
2570                 }
2571 #endif
2572
2573                 if (a.IsArray && b.IsArray) {
2574                         if (a.GetArrayRank () != b.GetArrayRank ())
2575                                 return false;
2576
2577                         return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2578                 }
2579
2580                 if (a.IsByRef && b.IsByRef)
2581                         return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2582
2583 #if GMCS_SOURCE
2584                 if (a.IsGenericType && b.IsGenericType) {
2585                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2586                                 return false;
2587
2588                         Type[] aargs = a.GetGenericArguments ();
2589                         Type[] bargs = b.GetGenericArguments ();
2590
2591                         if (aargs.Length != bargs.Length)
2592                                 return false;
2593
2594                         for (int i = 0; i < aargs.Length; i++) {
2595                                 if (!IsSignatureEqual (aargs [i], bargs [i]))
2596                                         return false;
2597                         }
2598
2599                         return true;
2600                 }
2601 #endif
2602
2603                 return false;
2604         }
2605
2606         //
2607         // Returns whether the array of memberinfos contains the given method
2608         //
2609         public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2610         {
2611                 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2612                 
2613                 foreach (MethodBase method in array) {
2614                         if (method.Name != new_method.Name)
2615                                 continue;
2616
2617                         if (method is MethodInfo && new_method is MethodInfo)
2618                                 if (!IsSignatureEqual (((MethodInfo) method).ReturnType,
2619                                                        ((MethodInfo) new_method).ReturnType))
2620                                         continue;
2621
2622                         
2623                         Type [] old_args = TypeManager.GetParameterData (method).Types;
2624                         int old_count = old_args.Length;
2625                         int i;
2626                         
2627                         if (new_args.Length != old_count)
2628                                 continue;
2629                         
2630                         for (i = 0; i < old_count; i++){
2631                                 if (!IsSignatureEqual (old_args [i], new_args [i]))
2632                                         break;
2633                         }
2634                         if (i != old_count)
2635                                 continue;
2636
2637                         return true;
2638                 }
2639                 
2640                 return false;
2641         }
2642         
2643         //
2644         // We copy methods from `new_members' into `target_list' if the signature
2645         // for the method from in the new list does not exist in the target_list
2646         //
2647         // The name is assumed to be the same.
2648         //
2649         public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2650         {
2651                 if (target_list == null){
2652                         target_list = new ArrayList ();
2653
2654                         foreach (MemberInfo mi in new_members){
2655                                 if (mi is MethodBase)
2656                                         target_list.Add (mi);
2657                         }
2658                         return target_list;
2659                 }
2660                 
2661                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2662                 target_list.CopyTo (target_array, 0);
2663                 
2664                 foreach (MemberInfo mi in new_members){
2665                         MethodBase new_method = (MethodBase) mi;
2666                         
2667                         if (!ArrayContainsMethod (target_array, new_method))
2668                                 target_list.Add (new_method);
2669                 }
2670                 return target_list;
2671         }
2672
2673 #region Generics
2674         // <remarks>
2675         //   Tracks the generic parameters.
2676         // </remarks>
2677         static PtrHashtable builder_to_type_param;
2678
2679         public static void AddTypeParameter (Type t, TypeParameter tparam)
2680         {
2681                 if (!builder_to_type_param.Contains (t))
2682                         builder_to_type_param.Add (t, tparam);
2683         }
2684
2685         public static TypeParameter LookupTypeParameter (Type t)
2686         {
2687                 return (TypeParameter) builder_to_type_param [t];
2688         }
2689
2690         // This method always return false for non-generic compiler,
2691         // while Type.IsGenericParameter is returned if it is supported.
2692         public static bool IsGenericParameter (Type type)
2693         {
2694 #if GMCS_SOURCE
2695                 return type.IsGenericParameter;
2696 #else
2697                 return false;
2698 #endif
2699         }
2700
2701         public static int GenericParameterPosition (Type type)
2702         {
2703 #if GMCS_SOURCE
2704                 return type.GenericParameterPosition;
2705 #else
2706                 throw new InternalErrorException ("should not be called");
2707 #endif
2708         }
2709
2710         public static bool IsGenericType (Type type)
2711         {
2712 #if GMCS_SOURCE
2713                 return type.IsGenericType;
2714 #else
2715                 return false;
2716 #endif
2717         }
2718
2719         public static bool IsGenericTypeDefinition (Type type)
2720         {
2721 #if GMCS_SOURCE
2722                 return type.IsGenericTypeDefinition;
2723 #else
2724                 return false;
2725 #endif
2726         }
2727
2728         public static bool ContainsGenericParameters (Type type)
2729         {
2730 #if GMCS_SOURCE
2731                 return type.ContainsGenericParameters;
2732 #else
2733                 return false;
2734 #endif
2735         }
2736
2737         public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2738         {
2739 #if GMCS_SOURCE
2740                 if (fi.DeclaringType.IsGenericTypeDefinition ||
2741                     !fi.DeclaringType.IsGenericType)
2742                         return fi;
2743
2744                 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2745                 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2746                         BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2747
2748                 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2749                 foreach (FieldInfo f in t.GetFields (bf))
2750                         if (f.MetadataToken == fi.MetadataToken)
2751                                 return f;
2752 #endif
2753
2754                 return fi;
2755         }
2756
2757         public static bool IsEqual (Type a, Type b)
2758         {
2759                 if (a.Equals (b)) {
2760                         // MS BCL returns true even if enum types are different
2761                         if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2762                                 return a.FullName == b.FullName;
2763
2764                         return true;
2765                 }
2766
2767 #if GMCS_SOURCE
2768                 if (a.IsGenericParameter && b.IsGenericParameter) {
2769                         if (a.DeclaringMethod != b.DeclaringMethod &&
2770                             (a.DeclaringMethod == null || b.DeclaringMethod == null))
2771                                 return false;
2772                         return a.GenericParameterPosition == b.GenericParameterPosition;
2773                 }
2774
2775                 if (a.IsArray && b.IsArray) {
2776                         if (a.GetArrayRank () != b.GetArrayRank ())
2777                                 return false;
2778                         return IsEqual (a.GetElementType (), b.GetElementType ());
2779                 }
2780
2781                 if (a.IsByRef && b.IsByRef)
2782                         return IsEqual (a.GetElementType (), b.GetElementType ());
2783
2784                 if (a.IsGenericType && b.IsGenericType) {
2785                         Type adef = a.GetGenericTypeDefinition ();
2786                         Type bdef = b.GetGenericTypeDefinition ();
2787
2788                         if (adef != bdef)
2789                                 return false;
2790
2791                         if (adef.IsEnum && bdef.IsEnum)
2792                                 return true;
2793
2794                         Type[] aargs = a.GetGenericArguments ();
2795                         Type[] bargs = b.GetGenericArguments ();
2796
2797                         if (aargs.Length != bargs.Length)
2798                                 return false;
2799
2800                         for (int i = 0; i < aargs.Length; i++) {
2801                                 if (!IsEqual (aargs [i], bargs [i]))
2802                                         return false;
2803                         }
2804
2805                         return true;
2806                 }
2807 #endif
2808
2809                 return false;
2810         }
2811
2812         public static Type DropGenericTypeArguments (Type t)
2813         {
2814 #if GMCS_SOURCE
2815                 if (!t.IsGenericType)
2816                         return t;
2817                 // Micro-optimization: a generic typebuilder is always a generic type definition
2818                 if (t is TypeBuilder)
2819                         return t;
2820                 return t.GetGenericTypeDefinition ();
2821 #else
2822                 return t;
2823 #endif
2824         }
2825
2826         public static MethodBase DropGenericMethodArguments (MethodBase m)
2827         {
2828 #if GMCS_SOURCE
2829                 if (m.IsGenericMethodDefinition)
2830                         return m;
2831                 if (m.IsGenericMethod)
2832                         return ((MethodInfo) m).GetGenericMethodDefinition ();
2833                 if (!m.DeclaringType.IsGenericType)
2834                         return m;
2835
2836                 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2837                 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2838                         BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2839
2840 #if MS_COMPATIBLE
2841                 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2842                 return m;
2843 #endif
2844
2845                 if (m is ConstructorInfo) {
2846                         foreach (ConstructorInfo c in t.GetConstructors (bf))
2847                                 if (c.MetadataToken == m.MetadataToken)
2848                                         return c;
2849                 } else {
2850                         foreach (MethodBase mb in t.GetMethods (bf))
2851                                 if (mb.MetadataToken == m.MetadataToken)
2852                                         return mb;
2853                 }
2854 #endif
2855
2856                 return m;
2857         }
2858
2859         public static Type[] GetGenericArguments (MethodInfo mi)
2860         {
2861 #if GMCS_SOURCE
2862                 return mi.GetGenericArguments ();
2863 #else
2864                 return Type.EmptyTypes;
2865 #endif
2866         }
2867
2868         public static Type[] GetTypeArguments (Type t)
2869         {
2870 #if GMCS_SOURCE
2871                 DeclSpace tc = LookupDeclSpace (t);
2872                 if (tc != null) {
2873                         if (!tc.IsGeneric)
2874                                 return Type.EmptyTypes;
2875
2876                         TypeParameter[] tparam = tc.TypeParameters;
2877                         Type[] ret = new Type [tparam.Length];
2878                         for (int i = 0; i < tparam.Length; i++) {
2879                                 ret [i] = tparam [i].Type;
2880                                 if (ret [i] == null)
2881                                         throw new InternalErrorException ();
2882                         }
2883
2884                         return ret;
2885                 } else
2886                         return t.GetGenericArguments ();
2887 #else
2888                 throw new InternalErrorException ();
2889 #endif
2890         }
2891
2892         public static bool HasGenericArguments (Type t)
2893         {
2894                 return GetNumberOfTypeArguments (t) > 0;
2895         }
2896
2897         public static int GetNumberOfTypeArguments (Type t)
2898         {
2899 #if GMCS_SOURCE
2900                 if (t.IsGenericParameter)
2901                         return 0;
2902                 DeclSpace tc = LookupDeclSpace (t);
2903                 if (tc != null)
2904                         return tc.IsGeneric ? tc.CountTypeParameters : 0;
2905                 else
2906                         return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2907 #else
2908                 return 0;
2909 #endif
2910         }
2911
2912         /// <summary>
2913         ///   Check whether `type' and `parent' are both instantiations of the same
2914         ///   generic type.  Note that we do not check the type parameters here.
2915         /// </summary>
2916         public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2917         {
2918                 int tcount = GetNumberOfTypeArguments (type);
2919                 int pcount = GetNumberOfTypeArguments (parent);
2920
2921                 if (tcount != pcount)
2922                         return false;
2923
2924                 type = DropGenericTypeArguments (type);
2925                 parent = DropGenericTypeArguments (parent);
2926
2927                 return type.Equals (parent);
2928         }
2929
2930         /// <summary>
2931         ///   Whether `mb' is a generic method definition.
2932         /// </summary>
2933         public static bool IsGenericMethodDefinition (MethodBase mb)
2934         {
2935 #if GMCS_SOURCE
2936                 if (mb.DeclaringType is TypeBuilder) {
2937                         IMethodData method = (IMethodData) builder_to_method [mb];
2938                         if (method == null)
2939                                 return false;
2940
2941                         return method.GenericMethod != null;
2942                 }
2943
2944                 return mb.IsGenericMethodDefinition;
2945 #else
2946                 return false;
2947 #endif
2948         }
2949
2950         /// <summary>
2951         ///   Whether `mb' is a generic method.
2952         /// </summary>
2953         public static bool IsGenericMethod (MethodBase mb)
2954         {
2955 #if GMCS_SOURCE
2956                 return mb.IsGenericMethod;
2957 #else
2958                 return false;
2959 #endif
2960         }
2961
2962         public static bool IsNullableType (Type t)
2963         {
2964 #if GMCS_SOURCE
2965                 return generic_nullable_type == DropGenericTypeArguments (t);
2966 #else
2967                 return false;
2968 #endif
2969         }
2970
2971         public static bool IsNullableTypeOf (Type t, Type nullable)
2972         {
2973 #if GMCS_SOURCE
2974                 if (!IsNullableType (t))
2975                         return false;
2976
2977                 return GetTypeArguments (t) [0] == nullable;
2978 #else
2979                 return false;
2980 #endif
2981         }
2982
2983         public static bool IsNullableValueType (Type t)
2984         {
2985 #if GMCS_SOURCE
2986                 if (!IsNullableType (t))
2987                         return false;
2988
2989                 return GetTypeArguments (t) [0].IsValueType;
2990 #else
2991                 return false;
2992 #endif
2993         }
2994 #endregion
2995
2996 #region MemberLookup implementation
2997         
2998         //
2999         // Whether we allow private members in the result (since FindMembers
3000         // uses NonPublic for both protected and private), we need to distinguish.
3001         //
3002
3003         internal class Closure {
3004                 internal bool     private_ok;
3005
3006                 // Who is invoking us and which type is being queried currently.
3007                 internal Type     invocation_type;
3008                 internal Type     qualifier_type;
3009
3010                 // The assembly that defines the type is that is calling us
3011                 internal Assembly invocation_assembly;
3012                 internal IList almost_match;
3013
3014                 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
3015                 {
3016                         if (invocation_type == null)
3017                                 return false;
3018
3019                         if (is_static && qualifier_type == null)
3020                                 // It resolved from a simple name, so it should be visible.
3021                                 return true;
3022
3023                         if (IsNestedChildOf (invocation_type, m.DeclaringType))
3024                                 return true;
3025
3026                         for (Type t = invocation_type; t != null; t = t.DeclaringType) {
3027                                 if (!IsFamilyAccessible (t, m.DeclaringType))
3028                                         continue;
3029
3030                                 // Although a derived class can access protected members of its base class
3031                                 // it cannot do so through an instance of the base class (CS1540).
3032                                 // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
3033                                 if (is_static || qualifier_type == null ||
3034                                     IsInstantiationOfSameGenericType (t, qualifier_type) ||
3035                                     IsFamilyAccessible (qualifier_type, t))
3036                                         return true;
3037                         }
3038
3039                         if (almost_match != null)
3040                                 almost_match.Add (m);
3041
3042                         return false;
3043                 }
3044                 
3045                 //
3046                 // This filter filters by name + whether it is ok to include private
3047                 // members in the search
3048                 //
3049                 internal bool Filter (MemberInfo m, object filter_criteria)
3050                 {
3051                         //
3052                         // Hack: we know that the filter criteria will always be in the
3053                         // `closure' // fields. 
3054                         //
3055
3056                         if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
3057                                 return false;
3058
3059                         if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
3060                             (invocation_type != null) &&
3061                             IsPrivateAccessible (m.DeclaringType, invocation_type))
3062                                 return true;
3063
3064                         //
3065                         // Ugly: we need to find out the type of `m', and depending
3066                         // on this, tell whether we accept or not
3067                         //
3068                         if (m is MethodBase){
3069                                 MethodBase mb = (MethodBase) m;
3070                                 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
3071
3072                                 if (ma == MethodAttributes.Public)
3073                                         return true;
3074
3075                                 if (ma == MethodAttributes.PrivateScope)
3076                                         return false;
3077
3078                                 if (ma == MethodAttributes.Private)
3079                                         return private_ok ||
3080                                                 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
3081                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
3082
3083                                 if (invocation_assembly == mb.DeclaringType.Assembly ||
3084                                     TypeManager.IsFriendAssembly (mb.DeclaringType.Assembly)) {
3085                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
3086                                                 return true;
3087                                 } else {
3088                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
3089                                                 return false;
3090                                 }
3091
3092                                 // Family, FamORAssem or FamANDAssem
3093                                 return CheckValidFamilyAccess (mb.IsStatic, m);
3094                         }
3095                         
3096                         if (m is FieldInfo){
3097                                 FieldInfo fi = (FieldInfo) m;
3098                                 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
3099
3100                                 if (fa == FieldAttributes.Public)
3101                                         return true;
3102
3103                                 if (fa == FieldAttributes.PrivateScope)
3104                                         return false;
3105
3106                                 if (fa == FieldAttributes.Private)
3107                                         return private_ok ||
3108                                                 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
3109                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
3110
3111                                 if ((invocation_assembly == fi.DeclaringType.Assembly) ||
3112                                     (invocation_assembly == null) ||
3113                                     TypeManager.IsFriendAssembly (fi.DeclaringType.Assembly)) {
3114                                         if ((fa == FieldAttributes.Assembly) ||
3115                                             (fa == FieldAttributes.FamORAssem))
3116                                                 return true;
3117                                 } else {
3118                                         if ((fa == FieldAttributes.Assembly) ||
3119                                             (fa == FieldAttributes.FamANDAssem))
3120                                                 return false;
3121                                 }
3122
3123                                 // Family, FamORAssem or FamANDAssem
3124                                 return CheckValidFamilyAccess (fi.IsStatic, m);
3125                         }
3126
3127                         //
3128                         // EventInfos and PropertyInfos, return true because they lack
3129                         // permission information, so we need to check later on the methods.
3130                         //
3131                         return true;
3132                 }
3133         }
3134
3135         static Closure closure = new Closure ();
3136         static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
3137
3138         //
3139         // Looks up a member called `name' in the `queried_type'.  This lookup
3140         // is done by code that is contained in the definition for `invocation_type'
3141         // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
3142         //
3143         // `invocation_type' is used to check whether we're allowed to access the requested
3144         // member wrt its protection level.
3145         //
3146         // When called from MemberAccess, `qualifier_type' is the type which is used to access
3147         // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
3148         // is B and qualifier_type is A).  This is used to do the CS1540 check.
3149         //
3150         // When resolving a SimpleName, `qualifier_type' is null.
3151         //
3152         // The `qualifier_type' is used for the CS1540 check; it's normally either null or
3153         // the same than `queried_type' - except when we're being called from BaseAccess;
3154         // in this case, `invocation_type' is the current type and `queried_type' the base
3155         // type, so this'd normally trigger a CS1540.
3156         //
3157         // The binding flags are `bf' and the kind of members being looked up are `mt'
3158         //
3159         // The return value always includes private members which code in `invocation_type'
3160         // is allowed to access (using the specified `qualifier_type' if given); only use
3161         // BindingFlags.NonPublic to bypass the permission check.
3162         //
3163         // The 'almost_match' argument is used for reporting error CS1540.
3164         //
3165         // Returns an array of a single element for everything but Methods/Constructors
3166         // that might return multiple matches.
3167         //
3168         public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
3169                                                   Type queried_type, MemberTypes mt,
3170                                                   BindingFlags original_bf, string name, IList almost_match)
3171         {
3172                 Timer.StartTimer (TimerType.MemberLookup);
3173
3174                 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
3175                                                         queried_type, mt, original_bf, name, almost_match);
3176
3177                 Timer.StopTimer (TimerType.MemberLookup);
3178
3179                 return retval;
3180         }
3181
3182         static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
3183                                                Type queried_type, MemberTypes mt,
3184                                                BindingFlags original_bf, string name, IList almost_match)
3185         {
3186                 BindingFlags bf = original_bf;
3187                 
3188                 ArrayList method_list = null;
3189                 Type current_type = queried_type;
3190                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
3191                 bool skip_iface_check = true, used_cache = false;
3192                 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
3193
3194                 closure.invocation_type = invocation_type;
3195                 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
3196                 closure.qualifier_type = qualifier_type;
3197                 closure.almost_match = almost_match;
3198
3199                 // This is from the first time we find a method
3200                 // in most cases, we do not actually find a method in the base class
3201                 // so we can just ignore it, and save the arraylist allocation
3202                 MemberInfo [] first_members_list = null;
3203                 bool use_first_members_list = false;
3204                 
3205                 do {
3206                         MemberInfo [] list;
3207
3208                         //
3209                         // `NonPublic' is lame, because it includes both protected and
3210                         // private methods, so we need to control this behavior by
3211                         // explicitly tracking if a private method is ok or not.
3212                         //
3213                         // The possible cases are:
3214                         //    public, private and protected (internal does not come into the
3215                         //    equation)
3216                         //
3217                         if ((invocation_type != null) &&
3218                             ((invocation_type == current_type) ||
3219                              IsNestedChildOf (invocation_type, current_type)) ||
3220                             always_ok_flag)
3221                                 bf = original_bf | BindingFlags.NonPublic;
3222                         else
3223                                 bf = original_bf;
3224
3225                         closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
3226
3227                         Timer.StopTimer (TimerType.MemberLookup);
3228
3229                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
3230
3231                         Timer.StartTimer (TimerType.MemberLookup);
3232
3233                         //
3234                         // When queried for an interface type, the cache will automatically check all
3235                         // inherited members, so we don't need to do this here.  However, this only
3236                         // works if we already used the cache in the first iteration of this loop.
3237                         //
3238                         // If we used the cache in any further iteration, we can still terminate the
3239                         // loop since the cache always looks in all base classes.
3240                         //
3241
3242                         if (used_cache)
3243                                 searching = false;
3244                         else
3245                                 skip_iface_check = false;
3246
3247                         if (current_type == TypeManager.object_type)
3248                                 searching = false;
3249                         else {
3250                                 current_type = current_type.BaseType;
3251                                 
3252                                 //
3253                                 // This happens with interfaces, they have a null
3254                                 // basetype.  Look members up in the Object class.
3255                                 //
3256                                 if (current_type == null) {
3257                                         current_type = TypeManager.object_type;
3258                                         searching = true;
3259                                 }
3260                         }
3261                         
3262                         if (list.Length == 0)
3263                                 continue;
3264
3265                         //
3266                         // Events and types are returned by both `static' and `instance'
3267                         // searches, which means that our above FindMembers will
3268                         // return two copies of the same.
3269                         //
3270                         if (list.Length == 1 && !(list [0] is MethodBase)){
3271                                 return list;
3272                         }
3273
3274                         //
3275                         // Multiple properties: we query those just to find out the indexer
3276                         // name
3277                         //
3278                         if (list [0] is PropertyInfo)
3279                                 return list;
3280
3281                         //
3282                         // We found an event: the cache lookup returns both the event and
3283                         // its private field.
3284                         //
3285                         if (list [0] is EventInfo) {
3286                                 if ((list.Length == 2) && (list [1] is FieldInfo))
3287                                         return new MemberInfo [] { list [0] };
3288
3289                                 return list;
3290                         }
3291
3292                         //
3293                         // We found methods, turn the search into "method scan"
3294                         // mode.
3295                         //
3296
3297                         if (first_members_list != null) {
3298                                 if (use_first_members_list) {
3299                                         method_list = CopyNewMethods (method_list, first_members_list);
3300                                         use_first_members_list = false;
3301                                 }
3302                                 
3303                                 method_list = CopyNewMethods (method_list, list);
3304                         } else {
3305                                 first_members_list = list;
3306                                 use_first_members_list = true;
3307                                 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3308                         }
3309                 } while (searching);
3310
3311                 if (use_first_members_list)
3312                         return first_members_list;
3313
3314                 if (method_list != null && method_list.Count > 0) {
3315                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3316                 }
3317                 //
3318                 // This happens if we already used the cache in the first iteration, in this case
3319                 // the cache already looked in all interfaces.
3320                 //
3321                 if (skip_iface_check)
3322                         return null;
3323
3324                 //
3325                 // Interfaces do not list members they inherit, so we have to
3326                 // scan those.
3327                 // 
3328                 if (!queried_type.IsInterface)
3329                         return null;
3330
3331                 if (queried_type.IsArray)
3332                         queried_type = TypeManager.array_type;
3333                 
3334                 Type [] ifaces = GetInterfaces (queried_type);
3335                 if (ifaces == null)
3336                         return null;
3337                 
3338                 foreach (Type itype in ifaces){
3339                         MemberInfo [] x;
3340
3341                         x = MemberLookup (null, null, itype, mt, bf, name, null);
3342                         if (x != null)
3343                                 return x;
3344                 }
3345                                         
3346                 return null;
3347         }
3348
3349         const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3350                                                                         BindingFlags.Static | BindingFlags.Instance | 
3351                                                                         BindingFlags.DeclaredOnly;
3352
3353         // Currently is designed to work with external types only
3354         public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3355         {
3356                 if (!mb.IsSpecialName)
3357                         return null;
3358
3359                 string name = mb.Name;
3360                 if (name.Length < 5)
3361                         return null;
3362
3363                 if (name [3] != '_')
3364                         return null;
3365
3366                 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3367                         MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3368                                 Type.FilterName, name.Substring (4));
3369
3370                         if (pi == null)
3371                                 return null;
3372
3373                         // This can happen when property is indexer (it can have same name but different parameters)
3374                         foreach (PropertyInfo p in pi) {
3375                                 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3376                                         if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3377                                                 return p;
3378                                 }
3379                         }
3380                 }
3381
3382                 return null;
3383         }
3384
3385         // Currently is designed to work with external types only
3386         public static MemberInfo GetEventFromAccessor (MethodBase mb)
3387         {
3388                 if (!mb.IsSpecialName)
3389                         return null;
3390
3391                 string name = mb.Name;
3392                 if (name.Length < 5)
3393                         return null;
3394
3395                 if (name.StartsWith ("add_"))
3396                         return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3397
3398                 if (name.StartsWith ("remove_"))
3399                         return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3400
3401                 return null;
3402         }
3403
3404         // Tests whether external method is really special
3405         public static bool IsSpecialMethod (MethodBase mb)
3406         {
3407                 if (!mb.IsSpecialName)
3408                         return false;
3409
3410                 IMethodData md = TypeManager.GetMethod (mb);
3411                 if (md != null) 
3412                         return (md is AbstractPropertyEventMethod || md is Operator);
3413
3414                 PropertyInfo pi = GetPropertyFromAccessor (mb);
3415                 if (pi != null)
3416                         return IsValidProperty (pi);
3417                                 
3418                 if (GetEventFromAccessor (mb) != null)
3419                         return true;
3420
3421                 string name = mb.Name;
3422                 if (name.StartsWith ("op_")){
3423                         foreach (string oname in Unary.oper_names) {
3424                                 if (oname == name)
3425                                         return true;
3426                         }
3427
3428                         foreach (string oname in Binary.oper_names) {
3429                                 if (oname == name)
3430                                         return true;
3431                         }
3432                 }
3433                 return false;
3434         }
3435
3436         // Tests whether imported property is valid C# property.
3437         // TODO: It seems to me that we should do a lot of sanity tests before
3438         // we accept property as C# property
3439         static bool IsValidProperty (PropertyInfo pi)
3440         {
3441                 MethodInfo get_method = pi.GetGetMethod (true);
3442                 MethodInfo set_method = pi.GetSetMethod (true);
3443                 if (get_method != null && set_method != null) {
3444                         int g_count = get_method.GetParameters ().Length;
3445                         int s_count = set_method.GetParameters ().Length;
3446                         if (g_count + 1 != s_count)
3447                                 return false;
3448                 }
3449                 return true;
3450         }
3451
3452 #endregion
3453         
3454 }
3455
3456 /// <summary>
3457 ///   There is exactly one instance of this class per type.
3458 /// </summary>
3459 public sealed class TypeHandle : IMemberContainer {
3460         public readonly IMemberContainer BaseType;
3461
3462         readonly int id = ++next_id;
3463         static int next_id = 0;
3464
3465         static TypeHandle ()
3466         {
3467                 Reset ();
3468         }
3469
3470         /// <summary>
3471         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
3472         ///   a TypeHandle yet, a new instance of it is created.  This static method
3473         ///   ensures that we'll only have one TypeHandle instance per type.
3474         /// </summary>
3475         private static TypeHandle GetTypeHandle (Type t)
3476         {
3477                 TypeHandle handle = (TypeHandle) type_hash [t];
3478                 if (handle != null)
3479                         return handle;
3480
3481                 handle = new TypeHandle (t);
3482                 type_hash.Add (t, handle);
3483                 return handle;
3484         }
3485
3486         public static MemberCache GetMemberCache (Type t)
3487         {
3488                 return GetTypeHandle (t).MemberCache;
3489         }
3490         
3491         public static void CleanUp ()
3492         {
3493                 type_hash = null;
3494         }
3495
3496         public static void Reset ()
3497         {
3498                 type_hash = new PtrHashtable ();
3499         }
3500
3501         /// <summary>
3502         ///   Returns the TypeHandle for TypeManager.object_type.
3503         /// </summary>
3504         public static IMemberContainer ObjectType {
3505                 get {
3506                         if (object_type != null)
3507                                 return object_type;
3508
3509                         object_type = GetTypeHandle (TypeManager.object_type);
3510
3511                         return object_type;
3512                 }
3513         }
3514
3515         /// <summary>
3516         ///   Returns the TypeHandle for TypeManager.array_type.
3517         /// </summary>
3518         public static IMemberContainer ArrayType {
3519                 get {
3520                         if (array_type != null)
3521                                 return array_type;
3522
3523                         array_type = GetTypeHandle (TypeManager.array_type);
3524
3525                         return array_type;
3526                 }
3527         }
3528
3529         private static PtrHashtable type_hash;
3530
3531         private static TypeHandle object_type = null;
3532         private static TypeHandle array_type = null;
3533
3534         private Type type;
3535         private string full_name;
3536         private bool is_interface;
3537         private MemberCache member_cache;
3538         private MemberCache base_cache;
3539
3540         private TypeHandle (Type type)
3541         {
3542                 this.type = type;
3543 #if MS_COMPATIBLE && GMCS_SOURCE
3544                 if (type.IsGenericType)
3545                         this.type = this.type.GetGenericTypeDefinition ();
3546 #endif
3547                 full_name = type.FullName != null ? type.FullName : type.Name;
3548                 if (type.BaseType != null) {
3549                         base_cache = TypeManager.LookupMemberCache (type.BaseType);
3550                         BaseType = base_cache.Container;
3551                 } else if (type.IsInterface)
3552                         base_cache = TypeManager.LookupBaseInterfacesCache (type);
3553                 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3554                 this.member_cache = new MemberCache (this);
3555         }
3556
3557         // IMemberContainer methods
3558
3559         public string Name {
3560                 get {
3561                         return full_name;
3562                 }
3563         }
3564
3565         public Type Type {
3566                 get {
3567                         return type;
3568                 }
3569         }
3570
3571         public MemberCache BaseCache {
3572                 get {
3573                         return base_cache;
3574                 }
3575         }
3576
3577         public bool IsInterface {
3578                 get {
3579                         return is_interface;
3580                 }
3581         }
3582
3583         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3584         {
3585                 MemberInfo [] members;
3586
3587 #if GMCS_SOURCE
3588                 if (type is GenericTypeParameterBuilder)
3589                         return MemberList.Empty;
3590 #endif
3591
3592                 if (mt == MemberTypes.Event)
3593                         members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3594                 else
3595                         members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3596                                                     null, null);
3597                 Array.Reverse (members);
3598
3599                 return new MemberList (members);
3600         }
3601
3602         // IMemberFinder methods
3603
3604         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3605                                        MemberFilter filter, object criteria)
3606         {
3607                 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3608         }
3609
3610         public MemberCache MemberCache {
3611                 get {
3612                         return member_cache;
3613                 }
3614         }
3615
3616         public override string ToString ()
3617         {
3618                 if (BaseType != null)
3619                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3620                 else
3621                         return "TypeHandle (" + id + "," + Name + ")";
3622         }
3623 }
3624
3625 }