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