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