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