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