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