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