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