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