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