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