2004-02-04 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / mbas / 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 using System;
13 using System.Globalization;
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Text.RegularExpressions;
18 using System.Runtime.CompilerServices;
19 using System.Diagnostics;
20
21 namespace Mono.MonoBASIC {
22
23 public class TypeManager {
24         //
25         // A list of core types that the compiler requires or uses
26         //
27         static public Type object_type;
28         static public Type value_type;
29         static public Type string_type;
30         static public Type int32_type;
31         static public Type uint32_type;
32         static public Type int64_type;
33         static public Type uint64_type;
34         static public Type float_type;
35         static public Type double_type;
36         static public Type char_type;
37         static public Type char_ptr_type;
38         static public Type short_type;
39         static public Type decimal_type;
40         static public Type date_type;
41         static public Type bool_type;
42         static public Type sbyte_type;
43         static public Type byte_type;
44         static public Type ushort_type;
45         static public Type enum_type;
46         static public Type delegate_type;
47         static public Type multicast_delegate_type;
48         static public Type void_type;
49         static public Type enumeration_type;
50         static public Type array_type;
51         static public Type runtime_handle_type;
52         static public Type icloneable_type;
53         static public Type type_type;
54         static public Type ienumerator_type;
55         static public Type idisposable_type;
56         static public Type default_member_type;
57         static public Type iasyncresult_type;
58         static public Type asynccallback_type;
59         static public Type intptr_type;
60         static public Type monitor_type;
61         static public Type runtime_field_handle_type;
62         static public Type attribute_type;
63         static public Type attribute_usage_type;
64         static public Type dllimport_type;
65         static public Type unverifiable_code_type;
66         static public Type methodimpl_attr_type;
67         static public Type marshal_as_attr_type;
68         static public Type param_array_type;
69         static public Type void_ptr_type;
70         static public Type indexer_name_type;
71         static public Type exception_type;
72         static public object obsolete_attribute_type;
73         static public object conditional_attribute_type;
74
75         //
76         // An empty array of types
77         //
78         static public Type [] NoTypes;
79
80
81         // 
82         // Expressions representing the internal types.  Used during declaration
83         // definition.
84         //
85         static public Expression system_object_expr, system_string_expr; 
86         static public Expression system_boolean_expr, system_decimal_expr;
87         static public Expression system_single_expr, system_double_expr;
88         static public Expression system_sbyte_expr, system_byte_expr;
89         static public Expression system_int16_expr, system_uint16_expr;
90         static public Expression system_int32_expr, system_uint32_expr;
91         static public Expression system_int64_expr, system_uint64_expr;
92         static public Expression system_char_expr, system_void_expr;
93         static public Expression system_date_expr;
94         static public Expression system_asynccallback_expr;
95         static public Expression system_iasyncresult_expr;
96
97         //
98         // This is only used when compiling corlib
99         //
100         static public Type system_int32_type;
101         static public Type system_array_type;
102         static public Type system_type_type;
103         static public Type system_assemblybuilder_type;
104         static public MethodInfo system_int_array_get_length;
105         static public MethodInfo system_int_array_get_rank;
106         static public MethodInfo system_object_array_clone;
107         static public MethodInfo system_int_array_get_length_int;
108         static public MethodInfo system_int_array_get_lower_bound_int;
109         static public MethodInfo system_int_array_get_upper_bound_int;
110         static public MethodInfo system_void_array_copyto_array_int;
111         static public MethodInfo system_void_set_corlib_type_builders;
112
113         
114         //
115         // Internal, not really used outside
116         //
117         static Type runtime_helpers_type;
118         
119         //
120         // These methods are called by code generated by the compiler
121         //
122         static public MethodInfo string_concat_string_string;
123         static public MethodInfo string_concat_object_object;
124         static public MethodInfo string_isinterneted_string;
125         static public MethodInfo system_type_get_type_from_handle;
126         static public MethodInfo object_getcurrent_void;
127         static public MethodInfo bool_movenext_void;
128         static public MethodInfo void_dispose_void;
129         static public MethodInfo void_monitor_enter_object;
130         static public MethodInfo void_monitor_exit_object;
131         static public MethodInfo void_initializearray_array_fieldhandle;
132         static public MethodInfo int_getlength_int;
133         static public MethodInfo delegate_combine_delegate_delegate;
134         static public MethodInfo delegate_remove_delegate_delegate;
135         static public MethodInfo int_get_offset_to_string_data;
136         static public MethodInfo int_array_get_length;
137         static public MethodInfo int_array_get_rank;
138         static public MethodInfo object_array_clone;
139         static public MethodInfo int_array_get_length_int;
140         static public MethodInfo int_array_get_lower_bound_int;
141         static public MethodInfo int_array_get_upper_bound_int;
142         static public MethodInfo void_array_copyto_array_int;
143         
144         //
145         // The attribute constructors.
146         //
147         static public ConstructorInfo cons_param_array_attribute;
148         static public ConstructorInfo void_decimal_ctor_five_args;
149         static public ConstructorInfo void_datetime_ctor_ticks_arg;
150         static public ConstructorInfo unverifiable_code_ctor;
151         
152         // <remarks>
153         //   Holds the Array of Assemblies that have been loaded
154         //   (either because it is the default or the user used the
155         //   -r command line option)
156         // </remarks>
157         static Assembly [] assemblies;
158
159         // <remarks>
160         //  Keeps a list of module builders. We used this to do lookups
161         //  on the modulebuilder using GetType -- needed for arrays
162         // </remarks>
163         static ModuleBuilder [] modules;
164
165         // <remarks>
166         //   This is the type_cache from the assemblies to avoid
167         //   hitting System.Reflection on every lookup.
168         // </summary>
169         static CaseInsensitiveHashtable types;
170
171         // <remarks>
172         //  This is used to hotld the corresponding TypeContainer objects
173         //  since we need this in FindMembers
174         // </remarks>
175         static CaseInsensitiveHashtable typecontainers;
176
177         // <remarks>
178         //   Keeps track of those types that are defined by the
179         //   user's program
180         // </remarks>
181         static ArrayList user_types;
182
183         static PtrHashtable builder_to_declspace;
184
185         // <remarks>
186         //   Tracks the interfaces implemented by typebuilders.  We only
187         //   enter those who do implement or or more interfaces
188         // </remarks>
189         static PtrHashtable builder_to_ifaces;
190
191         // <remarks>
192         //   Maps MethodBase.RuntimeTypeHandle to a Type array that contains
193         //   the arguments to the method
194         // </remarks>
195         static Hashtable method_arguments;
196
197         // <remarks>
198         //   Maps PropertyBuilder to a Type array that contains
199         //   the arguments to the indexer
200         // </remarks>
201         static Hashtable indexer_arguments;
202
203         // <remarks>
204         //   Maybe 'method_arguments' should be replaced and only
205         //   method_internal_params should be kept?
206         // <remarks>
207         static Hashtable method_internal_params;
208
209         // <remarks>
210         //  Keeps track of attribute types
211         // </remarks>
212
213         static Hashtable builder_to_attr;
214
215         // <remarks>
216         //  Keeps track of methods
217         // </remarks>
218
219         static Hashtable builder_to_method;
220
221         struct Signature {
222                 public string name;
223                 public Type [] args;
224         }
225
226         /// <summary>
227         ///   A filter for Findmembers that uses the Signature object to
228         ///   extract objects
229         /// </summary>
230         static bool SignatureFilter (MemberInfo mi, object criteria)
231         {
232                 Signature sig = (Signature) criteria;
233
234                 if (!(mi is MethodBase))
235                         return false;
236                 
237                 if (mi.Name != sig.name)
238                         return false;
239
240                 int count = sig.args.Length;
241                 
242                 if (mi is MethodBuilder || mi is ConstructorBuilder){
243                         Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
244
245                         if (candidate_args.Length != count)
246                                 return false;
247                         
248                         for (int i = 0; i < count; i++)
249                                 if (candidate_args [i] != sig.args [i])
250                                         return false;
251                         
252                         return true;
253                 } else {
254                         ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
255
256                         if (pars.Length != count)
257                                 return false;
258
259                         for (int i = 0; i < count; i++)
260                                 if (pars [i].ParameterType != sig.args [i])
261                                         return false;
262                         return true;
263                 }
264         }
265
266         // A delegate that points to the filter above.
267         static MemberFilter signature_filter;
268
269         //
270         // These are expressions that represent some of the internal data types, used
271         // elsewhere
272         //
273         static void InitExpressionTypes ()
274         {
275                 system_object_expr  = new TypeLookupExpression ("System.Object");
276                 system_string_expr  = new TypeLookupExpression ("System.String");
277                 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
278                 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
279                 system_single_expr  = new TypeLookupExpression ("System.Single");
280                 system_double_expr  = new TypeLookupExpression ("System.Double");
281                 system_sbyte_expr   = new TypeLookupExpression ("System.SByte");
282                 system_byte_expr    = new TypeLookupExpression ("System.Byte");
283                 system_int16_expr   = new TypeLookupExpression ("System.Int16");
284                 system_uint16_expr  = new TypeLookupExpression ("System.UInt16");
285                 system_int32_expr   = new TypeLookupExpression ("System.Int32");
286                 system_uint32_expr  = new TypeLookupExpression ("System.UInt32");
287                 system_int64_expr   = new TypeLookupExpression ("System.Int64");
288                 system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
289                 system_char_expr    = new TypeLookupExpression ("System.Char");
290                 system_void_expr    = new TypeLookupExpression ("System.Void");
291                 system_date_expr    = new TypeLookupExpression ("System.DateTime");
292                 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
293                 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
294         }
295         
296         static TypeManager ()
297         {
298                 assemblies = new Assembly [0];
299                 modules = null;
300                 user_types = new ArrayList ();
301                 
302                 types = new CaseInsensitiveHashtable ();
303                 typecontainers = new CaseInsensitiveHashtable ();
304                 
305                 builder_to_declspace = new PtrHashtable ();
306                 builder_to_attr = new PtrHashtable ();
307                 builder_to_method = new PtrHashtable ();
308                 method_arguments = new PtrHashtable ();
309                 method_internal_params = new PtrHashtable ();
310                 indexer_arguments = new PtrHashtable ();
311                 builder_to_ifaces = new PtrHashtable ();
312                 
313                 NoTypes = new Type [0];
314
315                 signature_filter = new MemberFilter (SignatureFilter);
316                 InitExpressionTypes ();
317         }
318
319         public static void AddUserType (string name, TypeBuilder t, Type [] ifaces)
320         {
321                 try {
322                         types.Add (name, t);
323                 } catch {
324                         Type prev = (Type) types [name];
325                         TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
326
327                         if (tc != null){
328                                 //
329                                 // This probably never happens, as we catch this before
330                                 //
331                                 Report.Error (-17, "The type '" + name + "' has already been defined.");
332                                 return;
333                         }
334
335                         tc = builder_to_declspace [t] as TypeContainer;
336                         
337                         Report.Warning (
338                                 1595, "The type '" + name + "' is defined in an existing assembly;"+
339                                 " Using the new definition from: " + tc.Location);
340                         Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
341                         
342                         types.Remove (name);
343                         types.Add (name, t);
344                 }
345                 user_types.Add (t);
346                         
347                 if (ifaces != null)
348                         builder_to_ifaces [t] = ifaces;
349         }
350
351         //
352         // This entry point is used by types that we define under the covers
353         // 
354         public static void RegisterBuilder (TypeBuilder tb, Type [] ifaces)
355         {
356                 if (ifaces != null)
357                         builder_to_ifaces [tb] = ifaces;
358         }
359         
360         public static void AddUserType (string name, TypeBuilder t, TypeContainer tc, Type [] ifaces)
361         {
362                 builder_to_declspace.Add (t, tc);
363                 typecontainers.Add (name, tc);
364                 AddUserType (name, t, ifaces);
365         }
366
367         public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
368         {
369                 types.Add (name, t);
370                 builder_to_declspace.Add (t, del);
371         }
372         
373         public static void AddEnumType (string name, TypeBuilder t, Enum en)
374         {
375                 types.Add (name, t);
376                 builder_to_declspace.Add (t, en);
377         }
378
379         public static void AddUserInterface (string name, TypeBuilder t, Interface i, Type [] ifaces)
380         {
381                 AddUserType (name, t, ifaces);
382                 builder_to_declspace.Add (t, i);
383         }
384
385         public static void AddMethod (MethodBuilder builder, MethodData method)
386         {
387                 builder_to_method.Add (builder, method);
388         }
389
390         public static void RegisterAttrType (Type t, TypeContainer tc)
391         {
392                 builder_to_attr.Add (t, tc);
393         }
394
395         /// <summary>
396         ///   Returns the TypeContainer whose Type is 't' or null if there is no
397         ///   TypeContainer for 't' (ie, the Type comes from a library)
398         /// </summary>
399         public static TypeContainer LookupTypeContainer (Type t)
400         {
401                 return builder_to_declspace [t] as TypeContainer;
402         }
403
404         public static IMemberContainer LookupMemberContainer (Type t)
405         {
406                 if (t is TypeBuilder) {
407                         IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
408                         if (container != null)
409                                 return container;
410                 }
411
412                 return TypeHandle.GetTypeHandle (t);
413         }
414
415         public static Interface LookupInterface (Type t)
416         {
417                 return builder_to_declspace [t] as Interface;
418         }
419
420         public static Delegate LookupDelegate (Type t)
421         {
422                 return builder_to_declspace [t] as Delegate;
423         }
424
425         public static Enum LookupEnum (Type t)
426         {
427                 return builder_to_declspace [t] as Enum;
428         }
429         
430         public static TypeContainer LookupAttr (Type t)
431         {
432                 return (TypeContainer) builder_to_attr [t];
433         }
434         
435         /// <summary>
436         ///   Registers an assembly to load types from.
437         /// </summary>
438         public static void AddAssembly (Assembly a)
439         {
440                 int top = assemblies.Length;
441                 Assembly [] n = new Assembly [top + 1];
442
443                 assemblies.CopyTo (n, 0);
444                 
445                 n [top] = a;
446                 assemblies = n;
447         }
448
449         /// <summary>
450         ///  Registers a module builder to lookup types from
451         /// </summary>
452         public static void AddModule (ModuleBuilder mb)
453         {
454                 int top = modules != null ? modules.Length : 0;
455                 ModuleBuilder [] n = new ModuleBuilder [top + 1];
456
457                 if (modules != null)
458                         modules.CopyTo (n, 0);
459                 n [top] = mb;
460                 modules = n;
461         }
462
463         //
464         // Low-level lookup, cache-less
465         //
466         static Type LookupTypeReflection (string name)
467         {
468                 Type t;
469
470                 try {
471                         foreach (Assembly a in assemblies){
472                                 t = a.GetType (name, false, true);
473                                 if (t != null)
474                                         return t;
475                         }
476
477                         foreach (ModuleBuilder mb in modules) {
478                                 t = mb.GetType (name, false, true);
479                                 if (t != null){
480                                         return t;
481                                 }
482                         }
483                 } catch (Exception e) {
484                         System.Console.WriteLine("\nERROR: " + e.ToString() + "WHILE EXECUTING LookupTypeReflection(\"" + name + "\")\n");
485                 }
486                 return null;
487         }
488
489         //
490         // This function is used when you want to avoid the lookups, and want to go
491         // directly to the source.  This will use the cache.
492         //
493         // Notice that bypassing the cache is bad, because on Microsoft.NET runtime
494         // GetType ("DynamicType[]") != GetType ("DynamicType[]"), and there is no
495         // way to test things other than doing a fullname compare
496         //
497         public static Type LookupTypeDirect (string name)
498         {
499                 Type t = (Type) types [name];
500                 if (t != null)
501                         return t;
502
503                 t = LookupTypeReflection (name);
504                 if (t == null)
505                         return null;
506
507                 types [name] = t;
508                 return t;
509         }
510         
511         /// <summary>
512         ///   Returns the Type associated with @name, takes care of the fact that
513         ///   reflection expects nested types to be separated from the main type
514         ///   with a "+" instead of a "."
515         /// </summary>
516         public static Type LookupType (string name)
517         {
518                 Type t;
519
520                 //
521                 // First lookup in user defined and cached values
522                 //
523
524                 t = (Type) types [name];
525                 if (t != null)
526                         return t;
527
528                 //
529                 // Optimization: ComposedCast will work with an existing type, and might already have the
530                 // full name of the type, so the full system lookup can probably be avoided.
531                 //
532                 
533                 string [] elements = name.Split ('.');
534                 int count = elements.Length;
535
536                 for (int n = 1; n <= count; n++){
537                         string top_level_type = String.Join (".", elements, 0, n);
538
539                         t = (Type) types [top_level_type];
540                         if (t == null){
541                                 t = LookupTypeReflection (top_level_type);
542                                 if (t == null)
543                                         continue;
544                         }
545                         
546                         if (count == n){
547                                 types [name] = t;
548                                 return t;
549                         } 
550                         
551                         string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
552                         t = LookupTypeDirect (newt);
553                         if (t != null)
554                                 types [newt] = t;
555                         return t;
556                 }
557                 return null;
558         }
559
560         //
561         // Returns a list of all namespaces in the assemblies and types loaded.
562         //
563         public static CaseInsensitiveHashtable GetNamespaces ()
564         {
565                 CaseInsensitiveHashtable namespaces = new CaseInsensitiveHashtable ();
566
567                 foreach (Assembly a in assemblies){
568                         foreach (Type t in a.GetTypes ()){
569                                 string ns = t.Namespace;
570
571                                 if (namespaces.Contains (ns))
572                                         continue;
573                                 namespaces [ns] = ns;
574                         }
575                 }
576
577                 foreach (ModuleBuilder mb in modules){
578                         foreach (Type t in mb.GetTypes ()){
579                                 string ns = t.Namespace;
580
581                                 if (namespaces.Contains (ns))
582                                         continue;
583                                 namespaces [ns] = ns;
584                         }
585                 }
586                 return namespaces;
587         }
588         
589         /// <summary>
590         ///   Returns the C# name of a type if possible, or the full type name otherwise
591         /// </summary>
592         static public string MonoBASIC_Name (Type t)
593         {
594                 return Regex.Replace (t.FullName, 
595                         @"^System\." +
596                         @"(Int32|Int16|Int64|Single|Double|Char|Decimal|Byte|Object|Boolean|String|DateTime)" +
597                         @"(\W+|\b)", 
598                         new MatchEvaluator (MonoBASIC_NameMatch));
599         }       
600         
601         static String MonoBASIC_NameMatch (Match match) 
602         {
603                 string s = match.Groups [1].Captures [0].Value;
604                 return s.ToLower ().
605                 Replace ("int32", "integer").
606                 Replace ("int16", "short").
607                 Replace ("int64", "long").
608                 Replace ("datetime", "date")
609                 + match.Groups [2].Captures [0].Value;
610         }
611
612         /// <summary>
613         ///   Returns the signature of the method
614         /// </summary>
615         static public string MonoBASIC_Signature (MethodBase mb)
616         {
617                 string sig = "(";
618
619                 //
620                 // FIXME: We should really have a single function to do
621                 // everything instead of the following 5 line pattern
622                 //
623                 ParameterData iparams = LookupParametersByBuilder (mb);
624
625                 if (iparams == null){
626                         ParameterInfo [] pi = mb.GetParameters ();
627                         iparams = new ReflectionParameters (pi);
628                 }
629                 
630                 for (int i = 0; i < iparams.Count; i++) {
631                         if (i > 0) {
632                                 sig += ", ";
633                         }
634                         sig += iparams.ParameterDesc(i);
635                 }
636                 sig += ")";
637
638                 return mb.DeclaringType.Name + "." + mb.Name + sig;
639         }
640
641         /// <summary>
642         ///   Looks up a type, and aborts if it is not found.  This is used
643         ///   by types required by the compiler
644         /// </summary>
645         static Type CoreLookupType (string name)
646         {
647                 Type t = LookupType (name);
648
649                 if (t == null){
650                         Report.Error (518, "The predefined type '" + name + "' is not defined or imported");
651                         Environment.Exit (0);
652                 }
653
654                 return t;
655         }
656
657         /// <summary>
658         ///   Returns the MethodInfo for a method named 'name' defined
659         ///   in type 't' which takes arguments of types 'args'
660         /// </summary>
661         static MethodInfo GetMethod (Type t, string name, Type [] args)
662         {
663                 MemberList list;
664                 Signature sig;
665
666                 sig.name = name;
667                 sig.args = args;
668                 
669                 list = FindMembers (t, MemberTypes.Method, instance_and_static | BindingFlags.Public| BindingFlags.IgnoreCase,
670                                     signature_filter, sig);
671                 if (list.Count == 0) {
672                         Report.Error (-19, "Can not find the core function '" + name + "'");
673                         return null;
674                 }
675
676                 MethodInfo mi = list [0] as MethodInfo;
677                 if (mi == null) {
678                         Report.Error (-19, "Can not find the core function '" + name + "'");
679                         return null;
680                 }
681
682                 return mi;
683         }
684
685         /// <summary>
686         ///    Returns the ConstructorInfo for "args"
687         /// </summary>
688         public static ConstructorInfo GetConstructor (Type t, Type [] args)
689         {
690                 MemberList list;
691                 Signature sig;
692
693                 sig.name = ".ctor";
694                 sig.args = args;
695                 
696                 list = FindMembers (t, MemberTypes.Constructor,
697                                     instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
698                                     signature_filter, sig);
699                 if (list.Count == 0){
700                         Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
701                         return null;
702                 }
703
704                 ConstructorInfo ci = list [0] as ConstructorInfo;
705                 if (ci == null){
706                         Report.Error (-19, "Can not find the core constructor for type '" + t.Name + "'");
707                         return null;
708                 }
709
710                 return ci;
711         }
712
713         public static void InitEnumUnderlyingTypes ()
714         {
715
716                 int32_type    = CoreLookupType ("System.Int32");
717                 int64_type    = CoreLookupType ("System.Int64");
718                 uint32_type   = CoreLookupType ("System.UInt32"); 
719                 uint64_type   = CoreLookupType ("System.UInt64"); 
720                 byte_type     = CoreLookupType ("System.Byte");
721                 sbyte_type    = CoreLookupType ("System.SByte");
722                 short_type    = CoreLookupType ("System.Int16");
723                 ushort_type   = CoreLookupType ("System.UInt16");
724         }
725         
726         /// <remarks>
727         ///   The types have to be initialized after the initial
728         ///   population of the type has happened (for example, to
729         ///   bootstrap the corlib.dll
730         /// </remarks>
731         public static void InitCoreTypes ()
732         {
733                 object_type   = CoreLookupType ("System.Object");
734                 value_type    = CoreLookupType ("System.ValueType");
735
736                 InitEnumUnderlyingTypes ();
737
738                 char_type     = CoreLookupType ("System.Char");
739                 string_type   = CoreLookupType ("System.String");
740                 float_type    = CoreLookupType ("System.Single");
741                 double_type   = CoreLookupType ("System.Double");
742                 char_ptr_type = CoreLookupType ("System.Char*");
743                 decimal_type  = CoreLookupType ("System.Decimal");
744                 bool_type     = CoreLookupType ("System.Boolean");
745                 enum_type     = CoreLookupType ("System.Enum");
746
747                 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
748                 delegate_type           = CoreLookupType ("System.Delegate");
749
750                 array_type    = CoreLookupType ("System.Array");
751                 void_type     = CoreLookupType ("System.Void");
752                 date_type         = CoreLookupType ("System.DateTime");
753                 type_type     = CoreLookupType ("System.Type");
754
755                 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
756                 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
757                 default_member_type  = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
758                 runtime_handle_type  = CoreLookupType ("System.RuntimeTypeHandle");
759                 asynccallback_type   = CoreLookupType ("System.AsyncCallback");
760                 iasyncresult_type    = CoreLookupType ("System.IAsyncResult");
761                 ienumerator_type     = CoreLookupType ("System.Collections.IEnumerator");
762                 idisposable_type     = CoreLookupType ("System.IDisposable");
763                 icloneable_type      = CoreLookupType ("System.ICloneable");
764                 monitor_type         = CoreLookupType ("System.Threading.Monitor");
765                 intptr_type          = CoreLookupType ("System.IntPtr");
766
767                 attribute_type       = CoreLookupType ("System.Attribute");
768                 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
769                 dllimport_type       = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
770                 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
771                 marshal_as_attr_type  = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
772                 param_array_type      = CoreLookupType ("System.ParamArrayAttribute");
773
774                 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
775
776                 void_ptr_type         = CoreLookupType ("System.Void*");
777
778                 indexer_name_type     = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
779
780                 exception_type        = CoreLookupType ("System.Exception");
781
782                 //
783                 // Attribute types
784                 //
785                 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
786                 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
787
788                 //
789                 // When compiling corlib, store the "real" types here.
790                 //
791                 if (!RootContext.StdLib) {
792                         system_int32_type = typeof (System.Int32);
793                         system_array_type = typeof (System.Array);
794                         system_type_type = typeof (System.Type);
795                         system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
796
797                         Type [] void_arg = {  };
798                         system_int_array_get_length = GetMethod (
799                                 system_array_type, "get_Length", void_arg);
800                         system_int_array_get_rank = GetMethod (
801                                 system_array_type, "get_Rank", void_arg);
802                         system_object_array_clone = GetMethod (
803                                 system_array_type, "Clone", void_arg);
804
805                         Type [] system_int_arg = { system_int32_type };
806                         system_int_array_get_length_int = GetMethod (
807                                 system_array_type, "GetLength", system_int_arg);
808                         system_int_array_get_upper_bound_int = GetMethod (
809                                 system_array_type, "GetUpperBound", system_int_arg);
810                         system_int_array_get_lower_bound_int = GetMethod (
811                                 system_array_type, "GetLowerBound", system_int_arg);
812
813                         Type [] system_array_int_arg = { system_array_type, system_int32_type };
814                         system_void_array_copyto_array_int = GetMethod (
815                                 system_array_type, "CopyTo", system_array_int_arg);
816
817                         Type [] system_type_type_arg = { system_type_type, system_type_type, system_type_type };
818
819                         try {
820                         system_void_set_corlib_type_builders = GetMethod (
821                                 system_assemblybuilder_type, "SetCorlibTypeBuilders",
822                                 system_type_type_arg);
823
824                         object[] args = new object [3];
825                         args [0] = object_type;
826                         args [1] = value_type;
827                         args [2] = enum_type;
828
829                         system_void_set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
830                         } catch {
831                                 Console.WriteLine ("Corlib compilation is not supported in Microsoft.NET due to bugs in it");
832                         }
833                 }
834         }
835
836         //
837         // The helper methods that are used by the compiler
838         //
839         public static void InitCodeHelpers ()
840         {
841                 //
842                 // Now load the default methods that we use.
843                 //
844                 Type [] string_string = { string_type, string_type };
845                 string_concat_string_string = GetMethod (
846                         string_type, "Concat", string_string);
847
848                 Type [] object_object = { object_type, object_type };
849                 string_concat_object_object = GetMethod (
850                         string_type, "Concat", object_object);
851
852                 Type [] string_ = { string_type };
853                 string_isinterneted_string = GetMethod (
854                         string_type, "IsInterned", string_);
855                 
856                 Type [] runtime_type_handle = { runtime_handle_type };
857                 system_type_get_type_from_handle = GetMethod (
858                         type_type, "GetTypeFromHandle", runtime_type_handle);
859
860                 Type [] delegate_delegate = { delegate_type, delegate_type };
861                 delegate_combine_delegate_delegate = GetMethod (
862                                 delegate_type, "Combine", delegate_delegate);
863
864                 delegate_remove_delegate_delegate = GetMethod (
865                                 delegate_type, "Remove", delegate_delegate);
866
867                 //
868                 // Void arguments
869                 //
870                 Type [] void_arg = {  };
871                 object_getcurrent_void = GetMethod (
872                         ienumerator_type, "get_Current", void_arg);
873                 bool_movenext_void = GetMethod (
874                         ienumerator_type, "MoveNext", void_arg);
875                 void_dispose_void = GetMethod (
876                         idisposable_type, "Dispose", void_arg);
877                 int_get_offset_to_string_data = GetMethod (
878                         runtime_helpers_type, "get_OffsetToStringData", void_arg);
879                 int_array_get_length = GetMethod (
880                         array_type, "get_Length", void_arg);
881                 int_array_get_rank = GetMethod (
882                         array_type, "get_Rank", void_arg);
883
884                 //
885                 // Int32 arguments
886                 //
887                 Type [] int_arg = { int32_type };
888                 int_array_get_length_int = GetMethod (
889                         array_type, "GetLength", int_arg);
890                 int_array_get_upper_bound_int = GetMethod (
891                         array_type, "GetUpperBound", int_arg);
892                 int_array_get_lower_bound_int = GetMethod (
893                         array_type, "GetLowerBound", int_arg);
894
895                 //
896                 // System.Array methods
897                 //
898                 object_array_clone = GetMethod (
899                         array_type, "Clone", void_arg);
900                 Type [] array_int_arg = { array_type, int32_type };
901                 void_array_copyto_array_int = GetMethod (
902                         array_type, "CopyTo", array_int_arg);
903                 
904                 //
905                 // object arguments
906                 //
907                 Type [] object_arg = { object_type };
908                 void_monitor_enter_object = GetMethod (
909                         monitor_type, "Enter", object_arg);
910                 void_monitor_exit_object = GetMethod (
911                         monitor_type, "Exit", object_arg);
912
913                 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
914                 
915                 void_initializearray_array_fieldhandle = GetMethod (
916                         runtime_helpers_type, "InitializeArray", array_field_handle_arg);
917
918                 //
919                 // Array functions
920                 //
921                 int_getlength_int = GetMethod (
922                         array_type, "GetLength", int_arg);
923
924                 //
925                 // Decimal constructors
926                 //
927                 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
928                 void_decimal_ctor_five_args = GetConstructor (
929                         decimal_type, dec_arg);
930                 
931                 // DateTime constructor
932                 Type [] ticks_arg = { int64_type };
933                 void_datetime_ctor_ticks_arg = GetConstructor ( date_type, ticks_arg);
934                 
935                 //
936                 // Attributes
937                 //
938                 cons_param_array_attribute = GetConstructor (
939                         param_array_type, void_arg);
940
941                 unverifiable_code_ctor = GetConstructor (
942                         unverifiable_code_type, void_arg);
943                 
944         }
945
946         const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
947
948         static CaseInsensitiveHashtable type_hash = new CaseInsensitiveHashtable ();
949
950         /// <remarks>
951         ///   This is the "old", non-cache based FindMembers() function.  We cannot use
952         ///   the cache here because there is no member name argument.
953         /// </remarks>
954         public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
955                                               MemberFilter filter, object criteria)
956         {
957                 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
958                 bf |= BindingFlags.IgnoreCase;
959                 //
960                 // 'builder_to_declspace' contains all dynamic types.
961                 //
962                 if (decl != null) {
963                         MemberList list;
964                         Timer.StartTimer (TimerType.FindMembers);
965                         list = decl.FindMembers (mt, bf, filter, criteria);
966                         Timer.StopTimer (TimerType.FindMembers);
967                         return list;
968                 }
969
970                 //
971                 // We have to take care of arrays specially, because GetType on
972                 // a TypeBuilder array will return a Type, not a TypeBuilder,
973                 // and we can not call FindMembers on this type.
974                 //
975                 if (t.IsSubclassOf (TypeManager.array_type))
976                         return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
977
978                 //
979                 // Since FindMembers will not lookup both static and instance
980                 // members, we emulate this behaviour here.
981                 //
982                 if ((bf & instance_and_static) == instance_and_static){
983                         MemberInfo [] i_members = t.FindMembers (
984                                 mt, (bf & ~BindingFlags.Static) | BindingFlags.IgnoreCase, filter, criteria);
985
986                         int i_len = i_members.Length;
987                         if (i_len == 1){
988                                 MemberInfo one = i_members [0];
989
990                                 //
991                                 // If any of these are present, we are done!
992                                 //
993                                 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
994                                         return new MemberList (i_members);
995                         }
996                                 
997                         MemberInfo [] s_members = t.FindMembers (
998                                 mt, (bf & ~BindingFlags.Instance) | BindingFlags.IgnoreCase, filter, criteria);
999
1000                         int s_len = s_members.Length;
1001                         if (i_len > 0 || s_len > 0)
1002                                 return new MemberList (i_members, s_members);
1003                         else {
1004                                 if (i_len > 0)
1005                                         return new MemberList (i_members);
1006                                 else
1007                                         return new MemberList (s_members);
1008                         }
1009                 }
1010
1011                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1012         }
1013
1014
1015         /// <summary>
1016         ///   This method is only called from within MemberLookup.  It tries to use the member
1017         ///   cache if possible and falls back to the normal FindMembers if not.  The 'used_cache'
1018         ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
1019         ///   our return value will already contain all inherited members and the caller don't need
1020         ///   to check base classes and interfaces anymore.
1021         /// </summary>
1022         private static MemberList MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1023                                                             string name, out bool used_cache)
1024         {
1025                 //
1026                 // We have to take care of arrays specially, because GetType on
1027                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1028                 // and we can not call FindMembers on this type.
1029                 //
1030                 if (t.IsSubclassOf (TypeManager.array_type)) {
1031                         used_cache = true;
1032                         return TypeHandle.ArrayType.MemberCache.FindMembers (
1033                                 mt, bf, name, FilterWithClosure_delegate, null);
1034                 }
1035
1036                 //
1037                 // If this is a dynamic type, it's always in the 'builder_to_declspace' hash table
1038                 // and we can ask the DeclSpace for the MemberCache.
1039                 //
1040                 if (t is TypeBuilder) {
1041                         DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1042                         MemberCache cache = decl.MemberCache;
1043
1044                         //
1045                         // If this DeclSpace has a MemberCache, use it.
1046                         //
1047
1048                         if (cache != null) {
1049                                 used_cache = true;
1050                                 return cache.FindMembers (
1051                                         mt, bf, name, FilterWithClosure_delegate, null);
1052                         }
1053
1054                         // If there is no MemberCache, we need to use the "normal" FindMembers.
1055
1056                         MemberList list;
1057                         Timer.StartTimer (TimerType.FindMembers);
1058                         list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
1059                                                  FilterWithClosure_delegate, name);
1060                         Timer.StopTimer (TimerType.FindMembers);
1061                         used_cache = false;
1062                         return list;
1063                 }
1064
1065                 //
1066                 // This call will always succeed.  There is exactly one TypeHandle instance per
1067                 // type, TypeHandle.GetTypeHandle() will either return it or create a new one
1068                 // if it didn't already exist.
1069                 //
1070                 TypeHandle handle = TypeHandle.GetTypeHandle (t);
1071
1072                 used_cache = true;
1073                 return handle.MemberCache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1074         }
1075
1076         public static bool IsBuiltinType (Type t)
1077         {
1078                 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1079                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1080                     t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1081                     t == sbyte_type || t == byte_type || t == ushort_type || t == void_type ||
1082                         t == date_type)
1083                         return true;
1084                 else
1085                         return false;
1086         }
1087
1088         public static bool IsDelegateType (Type t)
1089         {
1090                 if (t.IsSubclassOf (TypeManager.delegate_type))
1091                         return true;
1092                 else
1093                         return false;
1094         }
1095         
1096         public static bool IsEnumType (Type t)
1097         {
1098                 if (t.IsSubclassOf (TypeManager.enum_type))
1099                         return true;
1100                 else
1101                         return false;
1102         }
1103
1104         //
1105         // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
1106         //
1107         public static bool IsUnmanagedType (Type t)
1108         {
1109                 if (IsBuiltinType (t) && t != TypeManager.string_type)
1110                         return true;
1111
1112                 if (IsEnumType (t))
1113                         return true;
1114
1115                 if (t.IsPointer)
1116                         return true;
1117
1118                 if (IsValueType (t)){
1119                         if (t is TypeBuilder){
1120                                 TypeContainer tc = LookupTypeContainer (t);
1121
1122                                 foreach (Field f in tc.Fields){
1123                                         if (f.FieldBuilder.IsStatic)
1124                                                 continue;
1125                                         if (!IsUnmanagedType (f.FieldBuilder.FieldType))
1126                                                 return false;
1127                                 }
1128                         } else {
1129                                 FieldInfo [] fields = t.GetFields ();
1130
1131                                 foreach (FieldInfo f in fields){
1132                                         if (f.IsStatic)
1133                                                 continue;
1134                                         if (!IsUnmanagedType (f.FieldType))
1135                                                 return false;
1136                                 }
1137                         }
1138                         return true;
1139                 }
1140
1141                 return false;
1142         }
1143                 
1144         public static bool IsValueType (Type t)
1145         {
1146                 if (t.IsSubclassOf (TypeManager.value_type))
1147                         return true;
1148                 else
1149                         return false;
1150         }
1151         
1152         public static bool IsInterfaceType (Type t)
1153         {
1154                 Interface iface = builder_to_declspace [t] as Interface;
1155
1156                 if (iface != null)
1157                         return true;
1158                 else
1159                         return false;
1160         }
1161
1162         //
1163         // Checks whether 'type' is a subclass or nested child of 'parent'.
1164         //
1165         public static bool IsSubclassOrNestedChildOf (Type type, Type parent)
1166         {
1167                 do {
1168                         if ((type == parent) || type.IsSubclassOf (parent))
1169                                 return true;
1170
1171                         // Handle nested types.
1172                         type = type.DeclaringType;
1173                 } while (type != null);
1174
1175                 return false;
1176         }
1177
1178         //
1179         // Checks whether 'type' is a nested child of 'parent'.
1180         //
1181         public static bool IsNestedChildOf (Type type, Type parent)
1182         {
1183                 if ((type == parent) || type.IsSubclassOf (parent))
1184                         return false;
1185                 else
1186                         return IsSubclassOrNestedChildOf (type, parent);
1187         }
1188
1189         /// <summary>
1190         ///   Returns the User Defined Types
1191         /// </summary>
1192         public static ArrayList UserTypes {
1193                 get {
1194                         return user_types;
1195                 }
1196         }
1197
1198         public static CaseInsensitiveHashtable TypeContainers {
1199                 get {
1200                         return typecontainers;
1201                 }
1202         }
1203
1204         static Hashtable builder_to_constant;
1205
1206         public static void RegisterConstant (FieldBuilder fb, Const c)
1207         {
1208                 if (builder_to_constant == null)
1209                         builder_to_constant = new PtrHashtable ();
1210
1211                 if (builder_to_constant.Contains (fb))
1212                         return;
1213
1214                 builder_to_constant.Add (fb, c);
1215         }
1216
1217         public static Const LookupConstant (FieldBuilder fb)
1218         {
1219                 if (builder_to_constant == null)
1220                         return null;
1221                 
1222                 return (Const) builder_to_constant [fb];
1223         }
1224         
1225         /// <summary>
1226         ///   Gigantic work around for missing features in System.Reflection.Emit follows.
1227         /// </summary>
1228         ///
1229         /// <remarks>
1230         ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
1231         ///   for anything which is dynamic, and we need this in a number of places,
1232         ///   we register this information here, and use it afterwards.
1233         /// </remarks>
1234         static public bool RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1235         {
1236                 if (args == null)
1237                         args = NoTypes;
1238                                 
1239                 method_arguments.Add (mb, args);
1240                 method_internal_params.Add (mb, ip);
1241                 
1242                 return true;
1243         }
1244         
1245         static public InternalParameters LookupParametersByBuilder (MethodBase mb)
1246         {
1247                 if (! (mb is ConstructorBuilder || mb is MethodBuilder))
1248                         return null;
1249                 
1250                 if (method_internal_params.Contains (mb))
1251                         return (InternalParameters) method_internal_params [mb];
1252                 else
1253                         throw new Exception ("Argument for Method not registered" + mb);
1254         }
1255
1256         /// <summary>
1257         ///    Returns the argument types for a method based on its methodbase
1258         ///
1259         ///    For dynamic methods, we use the compiler provided types, for
1260         ///    methods from existing assemblies we load them from GetParameters,
1261         ///    and insert them into the cache
1262         /// </summary>
1263         static public Type [] GetArgumentTypes (MethodBase mb)
1264         {
1265                 if (method_arguments.Contains (mb))
1266                         return (Type []) method_arguments [mb];
1267                 else {
1268                         ParameterInfo [] pi = mb.GetParameters ();
1269                         int c = pi.Length;
1270                         Type [] types = new Type [c];
1271                         
1272                         for (int i = 0; i < c; i++)
1273                                 types [i] = pi [i].ParameterType;
1274
1275                         method_arguments.Add (mb, types);
1276                         return types;
1277                 }
1278         }
1279
1280         /// <summary>
1281         ///    Returns the argument types for an indexer based on its PropertyInfo
1282         ///
1283         ///    For dynamic indexers, we use the compiler provided types, for
1284         ///    indexers from existing assemblies we load them from GetParameters,
1285         ///    and insert them into the cache
1286         /// </summary>
1287         static public Type [] GetArgumentTypes (PropertyInfo indexer)
1288         {
1289                 if (indexer_arguments.Contains (indexer))
1290                         return (Type []) indexer_arguments [indexer];
1291                 else if (indexer is PropertyBuilder)
1292                         // If we're a PropertyBuilder and not in the
1293                         // 'indexer_arguments' hash, then we're a property and
1294                         // not an indexer.
1295                         return NoTypes;
1296                 else {
1297                         ParameterInfo [] pi = indexer.GetIndexParameters ();
1298                         // Property, not an indexer.
1299                         if (pi == null)
1300                                 return NoTypes;
1301                         int c = pi.Length;
1302                         Type [] types = new Type [c];
1303                         
1304                         for (int i = 0; i < c; i++)
1305                                 types [i] = pi [i].ParameterType;
1306
1307                         indexer_arguments.Add (indexer, types);
1308                         return types;
1309                 }
1310         }
1311         
1312         // <remarks>
1313         //  This is a workaround the fact that GetValue is not
1314         //  supported for dynamic types
1315         // </remarks>
1316         static CaseInsensitiveHashtable fields = new CaseInsensitiveHashtable ();
1317         static public bool RegisterFieldValue (FieldBuilder fb, object value)
1318         {
1319                 if (fields.Contains (fb))
1320                         return false;
1321
1322                 fields.Add (fb, value);
1323
1324                 return true;
1325         }
1326
1327         static public object GetValue (FieldBuilder fb)
1328         {
1329                 return fields [fb];
1330         }
1331
1332         static CaseInsensitiveHashtable fieldbuilders_to_fields = new CaseInsensitiveHashtable ();
1333         static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1334         {
1335                 if (fieldbuilders_to_fields.Contains (fb))
1336                         return false;
1337
1338                 fieldbuilders_to_fields.Add (fb, f);
1339                 return true;
1340         }
1341
1342         static public FieldBase GetField (FieldInfo fb)
1343         {
1344                 return (FieldBase) fieldbuilders_to_fields [fb];
1345         }
1346         
1347         static CaseInsensitiveHashtable events;
1348
1349         static public bool RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1350         {
1351                 if (events == null)
1352                         events = new CaseInsensitiveHashtable ();
1353
1354                 if (events.Contains (eb))
1355                         return false;
1356
1357                 events.Add (eb, new Pair (add, remove));
1358
1359                 return true;
1360         }
1361
1362         static public MethodInfo GetAddMethod (EventInfo ei)
1363         {
1364                 if (ei is MyEventBuilder) {
1365                         Pair pair = (Pair) events [ei];
1366
1367                         return (MethodInfo) pair.First;
1368                 } else
1369                         return ei.GetAddMethod ();
1370         }
1371
1372         static public MethodInfo GetRemoveMethod (EventInfo ei)
1373         {
1374                 if (ei is MyEventBuilder) {
1375                         Pair pair = (Pair) events [ei];
1376
1377                         return (MethodInfo) pair.Second;
1378                 } else
1379                         return ei.GetAddMethod ();
1380         }
1381
1382         static CaseInsensitiveHashtable priv_fields_events;
1383
1384         static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1385         {
1386                 if (priv_fields_events == null)
1387                         priv_fields_events = new CaseInsensitiveHashtable ();
1388
1389                 if (priv_fields_events.Contains (einfo))
1390                         return false;
1391
1392                 priv_fields_events.Add (einfo, builder);
1393
1394                 return true;
1395         }
1396
1397         static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1398         {
1399                 return (MemberInfo) priv_fields_events [ei];
1400         }
1401                 
1402         static CaseInsensitiveHashtable properties;
1403         
1404         static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1405         {
1406                 if (properties == null)
1407                         properties = new CaseInsensitiveHashtable ();
1408
1409                 if (properties.Contains (pb))
1410                         return false;
1411
1412                 properties.Add (pb, new Pair (get, set));
1413
1414                 return true;
1415         }
1416
1417         static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get, MethodBase set, Type[] args)
1418         {
1419                 if (!RegisterProperty (pb, get,set))
1420                         return false;
1421
1422                 indexer_arguments.Add (pb, args);
1423
1424                 return true;
1425         }
1426
1427         static public MethodInfo GetPropertyGetter (PropertyInfo pi)
1428         {
1429                 if (pi is PropertyBuilder){
1430                         Pair de = (Pair) properties [pi];
1431
1432                         return (MethodInfo) de.Second;
1433                 } else
1434                         return pi.GetSetMethod ();
1435         }
1436
1437         static public MethodInfo GetPropertySetter (PropertyInfo pi)
1438         {
1439                 if (pi is PropertyBuilder){
1440                         Pair de = (Pair) properties [pi];
1441
1442                         return (MethodInfo) de.First;
1443                 } else
1444                         return pi.GetGetMethod ();
1445         }
1446
1447         /// <summary>
1448         ///   Given an array of interface types, expand and eliminate repeated ocurrences
1449         ///   of an interface.  
1450         /// </summary>
1451         ///
1452         /// <remarks>
1453         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1454         ///   be IA, IB, IC.
1455         /// </remarks>
1456         public static Type [] ExpandInterfaces (Type [] base_interfaces)
1457         {
1458                 ArrayList new_ifaces = new ArrayList ();
1459                 
1460                 foreach (Type iface in base_interfaces){
1461                         if (!new_ifaces.Contains (iface))
1462                                 new_ifaces.Add (iface);
1463                         
1464                         Type [] implementing = TypeManager.GetInterfaces (iface);
1465                         
1466                         foreach (Type imp in implementing){
1467                                 if (!new_ifaces.Contains (imp))
1468                                         new_ifaces.Add (imp);
1469                         }
1470                 }
1471                 Type [] ret = new Type [new_ifaces.Count];
1472                 new_ifaces.CopyTo (ret, 0);
1473                 return ret;
1474         }
1475                 
1476         /// <summary>
1477         ///   This function returns the interfaces in the type 't'.  Works with
1478         ///   both types and TypeBuilders.
1479         /// </summary>
1480         public static Type [] GetInterfaces (Type t)
1481         {
1482                 //
1483                 // The reason for catching the Array case is that Reflection.Emit
1484                 // will not return a TypeBuilder for Array types of TypeBuilder types,
1485                 // but will still throw an exception if we try to call GetInterfaces
1486                 // on the type.
1487                 //
1488                 // Since the array interfaces are always constant, we return those for
1489                 // the System.Array
1490                 //
1491                 
1492                 if (t.IsArray)
1493                         t = TypeManager.array_type;
1494                 
1495                 if (t is TypeBuilder){
1496                         Type [] parent_ifaces;
1497                         
1498                         if (t.BaseType == null)
1499                                 parent_ifaces = NoTypes;
1500                         else
1501                                 parent_ifaces = GetInterfaces (t.BaseType);
1502                         Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1503                         if (type_ifaces == null)
1504                                 type_ifaces = NoTypes;
1505
1506                         int parent_count = parent_ifaces.Length;
1507                         Type [] result = new Type [parent_count + type_ifaces.Length];
1508                         parent_ifaces.CopyTo (result, 0);
1509                         type_ifaces.CopyTo (result, parent_count);
1510
1511                         return result;
1512                 } else
1513                         return t.GetInterfaces ();
1514         }
1515         
1516         /// <remarks>
1517         ///  The following is used to check if a given type implements an interface.
1518         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1519         /// </remarks>
1520         public static bool ImplementsInterface (Type t, Type iface)
1521         {
1522                 Type [] interfaces;
1523
1524                 //
1525                 // FIXME OPTIMIZATION:
1526                 // as soon as we hit a non-TypeBuiler in the interface
1527                 // chain, we could return, as the 'Type.GetInterfaces'
1528                 // will return all the interfaces implement by the type
1529                 // or its parents.
1530                 //
1531                 do {
1532                         interfaces = GetInterfaces (t);
1533
1534                         if (interfaces != null){
1535                                 foreach (Type i in interfaces){
1536                                         if (i == iface)
1537                                                 return true;
1538                                 }
1539                         }
1540                         
1541                         t = t.BaseType;
1542                 } while (t != null);
1543                 
1544                 return false;
1545         }
1546
1547         // This is a custom version of Convert.ChangeType() which works
1548         // with the TypeBuilder defined types when compiling corlib.
1549         public static object ChangeType (object value, Type conversionType)
1550         {
1551                 if (!(value is IConvertible))
1552                         throw new ArgumentException ();
1553
1554                 IConvertible convertValue = (IConvertible) value;
1555                 CultureInfo ci = CultureInfo.CurrentCulture;
1556                 NumberFormatInfo provider = ci.NumberFormat;
1557
1558                 //
1559                 // We must use Type.Equals() here since 'conversionType' is
1560                 // the TypeBuilder created version of a system type and not
1561                 // the system type itself.  You cannot use Type.GetTypeCode()
1562                 // on such a type - it'd always return TypeCode.Object.
1563                 //
1564                 if (conversionType.Equals (typeof (Boolean)))
1565                         return (object)(convertValue.ToBoolean (provider));
1566                 else if (conversionType.Equals (typeof (Byte)))
1567                         return (object)(convertValue.ToByte (provider));
1568                 else if (conversionType.Equals (typeof (Char)))
1569                         return (object)(convertValue.ToChar (provider));
1570                 else if (conversionType.Equals (typeof (DateTime)))
1571                         return (object)(convertValue.ToDateTime (provider));
1572                 else if (conversionType.Equals (typeof (Decimal)))
1573                         return (object)(convertValue.ToDecimal (provider));
1574                 else if (conversionType.Equals (typeof (Double)))
1575                         return (object)(convertValue.ToDouble (provider));
1576                 else if (conversionType.Equals (typeof (Int16)))
1577                         return (object)(convertValue.ToInt16 (provider));
1578                 else if (conversionType.Equals (typeof (Int32)))
1579                         return (object)(convertValue.ToInt32 (provider));
1580                 else if (conversionType.Equals (typeof (Int64)))
1581                         return (object)(convertValue.ToInt64 (provider));
1582                 else if (conversionType.Equals (typeof (SByte)))
1583                         return (object)(convertValue.ToSByte (provider));
1584                 else if (conversionType.Equals (typeof (Single)))
1585                         return (object)(convertValue.ToSingle (provider));
1586                 else if (conversionType.Equals (typeof (String)))
1587                         return (object)(convertValue.ToString (provider));
1588                 else if (conversionType.Equals (typeof (UInt16)))
1589                         return (object)(convertValue.ToUInt16 (provider));
1590                 else if (conversionType.Equals (typeof (UInt32)))
1591                         return (object)(convertValue.ToUInt32 (provider));
1592                 else if (conversionType.Equals (typeof (UInt64)))
1593                         return (object)(convertValue.ToUInt64 (provider));
1594                 else if (conversionType.Equals (typeof (Object)))
1595                         return (object)(value);
1596                 else 
1597                         throw new InvalidCastException ();
1598         }
1599
1600         //
1601         // This is needed, because enumerations from assemblies
1602         // do not report their underlyingtype, but they report
1603         // themselves
1604         //
1605         public static Type EnumToUnderlying (Type t)
1606         {
1607                 if (t == TypeManager.enum_type)
1608                         return t;
1609
1610                 t = t.UnderlyingSystemType;
1611                 if (!TypeManager.IsEnumType (t))
1612                         return t;
1613         
1614                 if (t is TypeBuilder) {
1615                         // slow path needed to compile corlib
1616                         if (t == TypeManager.bool_type ||
1617                                         t == TypeManager.byte_type ||
1618                                         t == TypeManager.sbyte_type ||
1619                                         t == TypeManager.char_type ||
1620                                         t == TypeManager.short_type ||
1621                                         t == TypeManager.ushort_type ||
1622                                         t == TypeManager.int32_type ||
1623                                         t == TypeManager.uint32_type ||
1624                                         t == TypeManager.int64_type ||
1625                                         t == TypeManager.uint64_type)
1626                                 return t;
1627                         throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
1628                 }
1629                 TypeCode tc = Type.GetTypeCode (t);
1630
1631                 switch (tc){
1632                 case TypeCode.Boolean:
1633                         return TypeManager.bool_type;
1634                 case TypeCode.Byte:
1635                         return TypeManager.byte_type;
1636                 case TypeCode.SByte:
1637                         return TypeManager.sbyte_type;
1638                 case TypeCode.Char:
1639                         return TypeManager.char_type;
1640                 case TypeCode.Int16:
1641                         return TypeManager.short_type;
1642                 case TypeCode.UInt16:
1643                         return TypeManager.ushort_type;
1644                 case TypeCode.Int32:
1645                         return TypeManager.int32_type;
1646                 case TypeCode.UInt32:
1647                         return TypeManager.uint32_type;
1648                 case TypeCode.Int64:
1649                         return TypeManager.int64_type;
1650                 case TypeCode.UInt64:
1651                         return TypeManager.uint64_type;
1652                 }
1653                 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1654         }
1655
1656         //
1657         // When compiling corlib and called with one of the core types, return
1658         // the corresponding typebuilder for that type.
1659         //
1660         public static Type TypeToCoreType (Type t)
1661         {
1662                 if (RootContext.StdLib || (t is TypeBuilder))
1663                         return t;
1664
1665                 TypeCode tc = Type.GetTypeCode (t);
1666
1667                 switch (tc){
1668                 case TypeCode.Boolean:
1669                         return TypeManager.bool_type;
1670                 case TypeCode.Byte:
1671                         return TypeManager.byte_type;
1672                 case TypeCode.SByte:
1673                         return TypeManager.sbyte_type;
1674                 case TypeCode.Char:
1675                         return TypeManager.char_type;
1676                 case TypeCode.Int16:
1677                         return TypeManager.short_type;
1678                 case TypeCode.UInt16:
1679                         return TypeManager.ushort_type;
1680                 case TypeCode.Int32:
1681                         return TypeManager.int32_type;
1682                 case TypeCode.UInt32:
1683                         return TypeManager.uint32_type;
1684                 case TypeCode.Int64:
1685                         return TypeManager.int64_type;
1686                 case TypeCode.UInt64:
1687                         return TypeManager.uint64_type;
1688                 case TypeCode.String:
1689                         return TypeManager.string_type;
1690                 case TypeCode.DateTime:
1691                         return TypeManager.date_type;
1692                 default:
1693                         if (t == typeof (void))
1694                                 return TypeManager.void_type;
1695                         if (t == typeof (object))
1696                                 return TypeManager.object_type;
1697                         if (t == typeof (System.Type))
1698                                 return TypeManager.type_type;
1699                         return t;
1700                 }
1701         }
1702
1703         /// <summary>
1704         ///   Utility function that can be used to probe whether a type
1705         ///   is managed or not.  
1706         /// </summary>
1707         public static bool VerifyUnManaged (Type t, Location loc)
1708         {
1709                 if (t.IsValueType || t.IsPointer){
1710                         //
1711                         // FIXME: this is more complex, we actually need to
1712                         // make sure that the type does not contain any
1713                         // classes itself
1714                         //
1715                         return true;
1716                 }
1717
1718                 if (!RootContext.StdLib && (t == TypeManager.decimal_type))
1719                         // We need this explicit check here to make it work when
1720                         // compiling corlib.
1721                         return true;
1722
1723                 Report.Error (
1724                         208, loc,
1725                         "Cannot take the address or size of a variable of a managed type ('" +
1726                         MonoBASIC_Name (t) + "')");
1727                 return false;   
1728         }
1729         
1730         /// <summary>
1731         ///   Returns the name of the indexer in a given type.
1732         /// </summary>
1733         /// <remarks>
1734         ///   The default is not always 'Item'.  The user can change this behaviour by
1735         ///   using the DefaultMemberAttribute in the class.
1736         ///
1737         ///   For example, the String class indexer is named 'Chars' not 'Item' 
1738         /// </remarks>
1739         public static string IndexerPropertyName (Type t)
1740         {
1741                 if (t is TypeBuilder) {
1742                         if (t.IsInterface) {
1743                                 Interface i = LookupInterface (t);
1744
1745                                 if ((i == null) || (i.IndexerName == null))
1746                                         return "Item";
1747
1748                                 return i.IndexerName;
1749                         } else {
1750                                 TypeContainer tc = LookupTypeContainer (t);
1751
1752                                 if ((tc == null) || (tc.IndexerName == null))
1753                                         return "Item";
1754
1755                                 return tc.IndexerName;
1756                         }
1757                 }
1758                 
1759                 System.Attribute attr = System.Attribute.GetCustomAttribute (
1760                         t, TypeManager.default_member_type);
1761                 if (attr != null){
1762                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
1763                         return dma.MemberName;
1764                 }
1765
1766                 return "Item";
1767         }
1768
1769         public static void MakePinned (LocalBuilder builder)
1770         {
1771                 //
1772                 // FIXME: Flag the "LocalBuilder" type as being
1773                 // pinned.  Figure out API.
1774                 //
1775         }
1776
1777
1778         //
1779         // Returns whether the array of memberinfos contains the given method
1780         //
1781         static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
1782         {
1783                 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
1784                 
1785                 foreach (MethodBase method in array){
1786                         if (method.Name != new_method.Name)
1787                                 continue;
1788                         
1789                         Type [] old_args = TypeManager.GetArgumentTypes (method);
1790                         int old_count = old_args.Length;
1791                         int i;
1792                         
1793                         if (new_args.Length != old_count)
1794                                 continue;
1795                         
1796                         for (i = 0; i < old_count; i++){
1797                                 if (old_args [i] != new_args [i])
1798                                         break;
1799                         }
1800                         if (i != old_count)
1801                                 continue;
1802
1803                         return true;
1804                 }
1805                 return false;
1806         }
1807         
1808         //
1809         // We copy methods from 'new_members' into 'target_list' if the signature
1810         // for the method from in the new list does not exist in the target_list
1811         //
1812         // The name is assumed to be the same.
1813         //
1814         public static ArrayList CopyNewMethods (ArrayList target_list, MemberList new_members)
1815         {
1816                 if (target_list == null){
1817                         target_list = new ArrayList ();
1818
1819                         foreach (MemberInfo mi in new_members){
1820                                 if (mi is MethodBase)
1821                                         target_list.Add (mi);
1822                         }
1823                         return target_list;
1824                 }
1825                 
1826                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
1827                 target_list.CopyTo (target_array, 0);
1828                 
1829                 foreach (MemberInfo mi in new_members){
1830                         MethodBase new_method = (MethodBase) mi;
1831                         
1832                         if (!ArrayContainsMethod (target_array, new_method))
1833                                 target_list.Add (new_method);
1834                 }
1835                 return target_list;
1836         }
1837
1838         [Flags]
1839         public enum MethodFlags {
1840                 IsObsolete = 1,
1841                 IsObsoleteError = 2,
1842                 ShouldIgnore = 3
1843         }
1844         
1845         //
1846         // Returns the TypeManager.MethodFlags for this method.
1847         // This emits an error 619 / warning 618 if the method is obsolete.
1848         // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
1849         //
1850         static public MethodFlags GetMethodFlags (MethodBase mb, Location loc)
1851         {
1852                 MethodFlags flags = 0;
1853                 
1854                 if (mb.DeclaringType is TypeBuilder){
1855                         MethodData method = (MethodData) builder_to_method [mb];
1856                         if (method == null) {
1857                                 // FIXME: implement Obsolete attribute on Property,
1858                                 //        Indexer and Event.
1859                                 return 0;
1860                         }
1861
1862                         return method.GetMethodFlags (loc);
1863                 }
1864
1865                 object [] attrs = mb.GetCustomAttributes (true);
1866                 foreach (object ta in attrs){
1867                         if (!(ta is System.Attribute)){
1868                                 Console.WriteLine ("Unknown type in GetMethodFlags: " + ta);
1869                                 continue;
1870                         }
1871                         System.Attribute a = (System.Attribute) ta;
1872                         if (a.TypeId == TypeManager.obsolete_attribute_type){
1873                                 ObsoleteAttribute oa = (ObsoleteAttribute) a;
1874
1875                                 string method_desc = TypeManager.MonoBASIC_Signature (mb);
1876
1877                                 if (oa.IsError) {
1878                                         Report.Error (619, loc, "Method '" + method_desc +
1879                                                       "' is obsolete: '" + oa.Message + "'");
1880                                         return MethodFlags.IsObsoleteError;
1881                                 } else
1882                                         Report.Warning (618, loc, "Method '" + method_desc +
1883                                                         "' is obsolete: '" + oa.Message + "'");
1884
1885                                 flags |= MethodFlags.IsObsolete;
1886
1887                                 continue;
1888                         }
1889                         
1890                         //
1891                         // Skip over conditional code.
1892                         //
1893                         if (a.TypeId == TypeManager.conditional_attribute_type){
1894                                 ConditionalAttribute ca = (ConditionalAttribute) a;
1895
1896                                 if (RootContext.AllDefines [ca.ConditionString] == null)
1897                                         flags |= MethodFlags.ShouldIgnore;
1898                         }
1899                 }
1900
1901                 return flags;
1902         }
1903         
1904 #region MemberLookup implementation
1905         
1906         //
1907         // Name of the member
1908         //
1909         static string   closure_name;
1910
1911         //
1912         // Whether we allow private members in the result (since FindMembers
1913         // uses NonPublic for both protected and private), we need to distinguish.
1914         //
1915         static bool     closure_private_ok;
1916
1917         //
1918         // Who is invoking us and which type is being queried currently.
1919         //
1920         static Type     closure_invocation_type;
1921         static Type     closure_queried_type;
1922         static Type     closure_start_type;
1923
1924         //
1925         // The assembly that defines the type is that is calling us
1926         //
1927         static Assembly closure_invocation_assembly;
1928
1929         //
1930         // This filter filters by name + whether it is ok to include private
1931         // members in the search
1932         //
1933         static internal bool FilterWithClosure (MemberInfo m, object filter_criteria)
1934         {
1935                 //
1936                 // Hack: we know that the filter criteria will always be in the 'closure'
1937                 // fields. 
1938                 //
1939
1940                 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
1941                                 return false;
1942
1943                 if ((closure_start_type == closure_invocation_type) &&
1944                     (m.DeclaringType == closure_invocation_type))
1945                         return true;
1946
1947                 //
1948                 // Ugly: we need to find out the type of 'm', and depending
1949                 // on this, tell whether we accept or not
1950                 //
1951                 if (m is MethodBase){
1952                         MethodBase mb = (MethodBase) m;
1953                         MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
1954
1955                         if (ma == MethodAttributes.Private)
1956                                 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
1957
1958                         //
1959                         // FamAndAssem requires that we not only derivate, but we are on the
1960                         // same assembly.  
1961                         //
1962                         if (ma == MethodAttributes.FamANDAssem){
1963                                 if (closure_invocation_assembly != mb.DeclaringType.Assembly)
1964                                         return false;
1965                         }
1966
1967                         // Assembly and FamORAssem succeed if we're in the same assembly.
1968                         if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
1969                                 if (closure_invocation_assembly == mb.DeclaringType.Assembly)
1970                                         return true;
1971                         }
1972
1973                         // We already know that we aren't in the same assembly.
1974                         if (ma == MethodAttributes.Assembly)
1975                                 return false;
1976
1977                         // Family and FamANDAssem require that we derive.
1978                         if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
1979                                 if (closure_invocation_type == null)
1980                                         return false;
1981
1982                                 if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
1983                                         return false;
1984
1985                                 return true;
1986                         }
1987
1988                         // Public.
1989                         return true;
1990                 }
1991
1992                 if (m is FieldInfo){
1993                         FieldInfo fi = (FieldInfo) m;
1994                         FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
1995
1996                         if (fa == FieldAttributes.Private)
1997                                 return closure_private_ok || (closure_invocation_type == m.DeclaringType);
1998
1999                         //
2000                         // FamAndAssem requires that we not only derivate, but we are on the
2001                         // same assembly.  
2002                         //
2003                         if (fa == FieldAttributes.FamANDAssem){
2004                                 if (closure_invocation_assembly != fi.DeclaringType.Assembly)
2005                                         return false;
2006                         }
2007
2008                         // Assembly and FamORAssem succeed if we're in the same assembly.
2009                         if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
2010                                 if (closure_invocation_assembly == fi.DeclaringType.Assembly)
2011                                         return true;
2012                         }
2013
2014                         // We already know that we aren't in the same assembly.
2015                         if (fa == FieldAttributes.Assembly)
2016                                 return false;
2017
2018                         // Family and FamANDAssem require that we derive.
2019                         if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
2020                                 if (closure_invocation_type == null)
2021                                         return false;
2022
2023                                 if (!IsSubclassOrNestedChildOf (closure_invocation_type, fi.DeclaringType))
2024                                         return false;
2025
2026                                 // Although a derived class can access protected members of its base class
2027                                 // it cannot do so through an instance of the base class (CS1540).
2028                                 if ((closure_invocation_type != closure_start_type) &&
2029                                     closure_invocation_type.IsSubclassOf (closure_start_type))
2030                                         return false;
2031
2032                                 return true;
2033                         }
2034
2035                         // Public.
2036                         return true;
2037                 }
2038
2039                 //
2040                 // EventInfos and PropertyInfos, return true
2041                 //
2042                 return true;
2043         }
2044
2045         static MemberFilter FilterWithClosure_delegate = new MemberFilter (FilterWithClosure);
2046
2047         //
2048         // Looks up a member called 'name' in the 'queried_type'.  This lookup
2049         // is done by code that is contained in the definition for 'invocation_type'.
2050         //
2051         // The binding flags are 'bf' and the kind of members being looked up are 'mt'
2052         //
2053         // Returns an array of a single element for everything but Methods/Constructors
2054         // that might return multiple matches.
2055         //
2056         public static MemberInfo [] MemberLookup (Type invocation_type, Type queried_type, 
2057                                                   MemberTypes mt, BindingFlags original_bf, string name)
2058         {
2059                 Timer.StartTimer (TimerType.MemberLookup);
2060
2061                 MemberInfo[] retval = RealMemberLookup (invocation_type, queried_type,
2062                                                         mt, original_bf, name);
2063
2064                 Timer.StopTimer (TimerType.MemberLookup);
2065
2066                 return retval;
2067         }
2068
2069         static MemberInfo [] RealMemberLookup (Type invocation_type, Type queried_type, 
2070                                                MemberTypes mt, BindingFlags original_bf, string name)
2071         {
2072                 BindingFlags bf = original_bf;
2073                 
2074                 ArrayList method_list = null;
2075                 Type current_type = queried_type;
2076                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2077                 bool private_ok;
2078                 bool always_ok_flag = false;
2079                 bool skip_iface_check = true, used_cache = false;
2080
2081                 closure_name = name;
2082                 closure_invocation_type = invocation_type;
2083                 closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2084                 closure_start_type = queried_type;
2085
2086                 //
2087                 // If we are a nested class, we always have access to our container
2088                 // type names
2089                 //
2090                 if (invocation_type != null){
2091                         string invocation_name = invocation_type.FullName;
2092                         if (invocation_name.IndexOf ('+') != -1){
2093                                 string container = queried_type.FullName + "+";
2094                                 int container_length = container.Length;
2095                                 
2096                                 if (invocation_name.Length > container_length){
2097                                         string shared = invocation_name.Substring (0, container_length);
2098                                 
2099                                         if (shared == container)
2100                                                 always_ok_flag = true;
2101                                 }
2102                         }
2103                 }
2104                 
2105                 do {
2106                         MemberList list;
2107
2108                         //
2109                         // 'NonPublic' is lame, because it includes both protected and
2110                         // private methods, so we need to control this behavior by
2111                         // explicitly tracking if a private method is ok or not.
2112                         //
2113                         // The possible cases are:
2114                         //    public, private and protected (internal does not come into the
2115                         //    equation)
2116                         //
2117                         if (invocation_type != null){
2118                                 if (invocation_type == current_type){
2119                                         private_ok = (bf & BindingFlags.NonPublic) != 0;
2120                                 } else
2121                                         private_ok = always_ok_flag;
2122
2123                                 if (invocation_type.IsSubclassOf (current_type))
2124                                         private_ok = true;
2125                                 
2126                                 if (private_ok)
2127                                         bf = original_bf | BindingFlags.NonPublic;
2128                         } else {
2129                                 private_ok = false;
2130                                 bf = original_bf & ~BindingFlags.NonPublic;
2131                         }
2132
2133                         closure_private_ok = private_ok;
2134                         closure_queried_type = current_type;
2135
2136                         Timer.StopTimer (TimerType.MemberLookup);
2137 bf |= BindingFlags.IgnoreCase;
2138                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2139
2140                         Timer.StartTimer (TimerType.MemberLookup);
2141
2142                         //
2143                         // When queried for an interface type, the cache will automatically check all
2144                         // inherited members, so we don't need to do this here.  However, this only
2145                         // works if we already used the cache in the first iteration of this loop.
2146                         //
2147                         // If we used the cache in any further iteration, we can still terminate the
2148                         // loop since the cache always looks in all parent classes.
2149                         //
2150
2151                         if (used_cache)
2152                                 searching = false;
2153                         else
2154                                 skip_iface_check = false;
2155
2156                         if (current_type == TypeManager.object_type)
2157                                 searching = false;
2158                         else {
2159                                 current_type = current_type.BaseType;
2160                                 
2161                                 //
2162                                 // This happens with interfaces, they have a null
2163                                 // basetype.  Look members up in the Object class.
2164                                 //
2165                                 if (current_type == null)
2166                                         current_type = TypeManager.object_type;
2167                         }
2168                         
2169                         if (list.Count == 0)
2170                                 continue;
2171                                 
2172                         //
2173                         // Events and types are returned by both 'static' and 'instance'
2174                         // searches, which means that our above FindMembers will
2175                         // return two copies of the same.
2176                         //
2177                         if (list.Count == 1 && !(list [0] is MethodBase)){
2178                                 return (MemberInfo []) list;
2179                         }
2180
2181                         //
2182                         // Multiple properties: we query those just to find out the indexer
2183                         // name
2184                         //
2185                         if (list [0] is PropertyInfo)
2186                                 return (MemberInfo []) list;
2187
2188                         //
2189                         // We found methods, turn the search into "method scan"
2190                         // mode.
2191                         //
2192                         
2193                         method_list = CopyNewMethods (method_list, list);
2194                         mt &= (MemberTypes.Method | MemberTypes.Constructor);
2195                 } while (searching);
2196
2197                 if (method_list != null && method_list.Count > 0)
2198                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2199
2200                 //
2201                 // This happens if we already used the cache in the first iteration, in this case
2202                 // the cache already looked in all interfaces.
2203                 //
2204                 if (skip_iface_check)
2205                         return null;
2206
2207                 //
2208                 // Interfaces do not list members they inherit, so we have to
2209                 // scan those.
2210                 // 
2211                 if (!queried_type.IsInterface)
2212                         return null;
2213
2214                 if (queried_type.IsArray)
2215                         queried_type = TypeManager.array_type;
2216                 
2217                 Type [] ifaces = GetInterfaces (queried_type);
2218                 if (ifaces == null)
2219                         return null;
2220                 
2221                 foreach (Type itype in ifaces){
2222                         MemberInfo [] x;
2223
2224                         x = MemberLookup (null, itype, mt, bf, name);
2225                         if (x != null)
2226                                 return x;
2227                 }
2228                                         
2229                 return null;
2230         }
2231 #endregion
2232         
2233 }
2234
2235 /// <summary>
2236 ///   There is exactly one instance of this class per type.
2237 /// </summary>
2238 public sealed class TypeHandle : IMemberContainer {
2239         public readonly TypeHandle BaseType;
2240
2241         readonly int id = ++next_id;
2242         static int next_id = 0;
2243
2244         /// <summary>
2245         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
2246         ///   a TypeHandle yet, a new instance of it is created.  This static method
2247         ///   ensures that we'll only have one TypeHandle instance per type.
2248         /// </summary>
2249         public static TypeHandle GetTypeHandle (Type t)
2250         {
2251                 TypeHandle handle = (TypeHandle) type_hash [t];
2252                 if (handle != null)
2253                         return handle;
2254
2255                 handle = new TypeHandle (t);
2256                 type_hash.Add (t, handle);
2257                 return handle;
2258         }
2259
2260         /// <summary>
2261         ///   Returns the TypeHandle for TypeManager.object_type.
2262         /// </summary>
2263         public static IMemberContainer ObjectType {
2264                 get {
2265                         if (object_type != null)
2266                                 return object_type;
2267
2268                         object_type = GetTypeHandle (TypeManager.object_type);
2269
2270                         return object_type;
2271                 }
2272         }
2273
2274         /// <summary>
2275         ///   Returns the TypeHandle for TypeManager.array_type.
2276         /// </summary>
2277         public static IMemberContainer ArrayType {
2278                 get {
2279                         if (array_type != null)
2280                                 return array_type;
2281
2282                         array_type = GetTypeHandle (TypeManager.array_type);
2283
2284                         return array_type;
2285                 }
2286         }
2287
2288         private static PtrHashtable type_hash = new PtrHashtable ();
2289
2290         private static TypeHandle object_type = null;
2291         private static TypeHandle array_type = null;
2292
2293         private Type type;
2294         private bool is_interface;
2295         private MemberCache member_cache;
2296
2297         private TypeHandle (Type type)
2298         {
2299                 this.type = type;
2300                 if (type.BaseType != null)
2301                         BaseType = GetTypeHandle (type.BaseType);
2302                 else if ((type != TypeManager.object_type) && (type != typeof (object)))
2303                         is_interface = true;
2304                 this.member_cache = new MemberCache (this);
2305         }
2306
2307         // IMemberContainer methods
2308
2309         public string Name {
2310                 get {
2311                         return type.FullName;
2312                 }
2313         }
2314
2315         public Type Type {
2316                 get {
2317                         return type;
2318                 }
2319         }
2320
2321         public IMemberContainer Parent {
2322                 get {
2323                         return BaseType;
2324                 }
2325         }
2326
2327         public bool IsInterface {
2328                 get {
2329                         return is_interface;
2330                 }
2331         }
2332
2333         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2334         {
2335                 if (mt == MemberTypes.Event)
2336                         return new MemberList (type.GetEvents (bf | BindingFlags.DeclaredOnly));
2337                 else
2338                         return new MemberList (type.FindMembers (mt, bf | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase,
2339                                                                  null, null));
2340         }
2341
2342         // IMemberFinder methods
2343
2344         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2345                                        MemberFilter filter, object criteria)
2346         {
2347                 return member_cache.FindMembers (mt, bf, name, filter, criteria);
2348         }
2349
2350         public MemberCache MemberCache {
2351                 get {
2352                         return member_cache;
2353                 }
2354         }
2355
2356         public override string ToString ()
2357         {
2358                 if (BaseType != null)
2359                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2360                 else
2361                         return "TypeHandle (" + id + "," + Name + ")";
2362         }
2363 }
2364
2365 }