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