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